code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python
import sys
from PySide6 import QtWidgets
from interface.interface import Interface
def main():
app = QtWidgets.QApplication(sys.argv)
application = Interface()
application.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
| [
"interface.interface.Interface",
"PySide6.QtWidgets.QApplication"
] | [((142, 174), 'PySide6.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (164, 174), False, 'from PySide6 import QtWidgets\n'), ((194, 205), 'interface.interface.Interface', 'Interface', ([], {}), '()\n', (203, 205), False, 'from interface.interface import Interface\n')] |
# Copyright (c) 2020 PaddlePaddle 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.
from pathlib import Path
import numpy as np
import pandas as pd
import librosa
import csv
from paddle import fluid
from parakeet import g2p
from parakeet import audio
from parakeet.data.sampler import *
from parakeet.data.datacargo import DataCargo
from parakeet.data.batch import TextIDBatcher, SpecBatcher
from parakeet.data.dataset import DatasetMixin, TransformDataset, CacheDataset, SliceDataset
from parakeet.models.transformer_tts.utils import *
class LJSpeechLoader:
def __init__(self,
config,
args,
nranks,
rank,
is_vocoder=False,
shuffle=True):
place = fluid.CUDAPlace(rank) if args.use_gpu else fluid.CPUPlace()
LJSPEECH_ROOT = Path(args.data_path)
metadata = LJSpeechMetaData(LJSPEECH_ROOT)
transformer = LJSpeech(config)
dataset = TransformDataset(metadata, transformer)
dataset = CacheDataset(dataset)
sampler = DistributedSampler(
len(dataset), nranks, rank, shuffle=shuffle)
assert args.batch_size % nranks == 0
each_bs = args.batch_size // nranks
if is_vocoder:
dataloader = DataCargo(
dataset,
sampler=sampler,
batch_size=each_bs,
shuffle=shuffle,
batch_fn=batch_examples_vocoder,
drop_last=True)
else:
dataloader = DataCargo(
dataset,
sampler=sampler,
batch_size=each_bs,
shuffle=shuffle,
batch_fn=batch_examples,
drop_last=True)
self.reader = fluid.io.DataLoader.from_generator(
capacity=32,
iterable=True,
use_double_buffer=True,
return_list=True)
self.reader.set_batch_generator(dataloader, place)
class LJSpeechMetaData(DatasetMixin):
def __init__(self, root):
self.root = Path(root)
self._wav_dir = self.root.joinpath("wavs")
csv_path = self.root.joinpath("metadata.csv")
self._table = pd.read_csv(
csv_path,
sep="|",
header=None,
quoting=csv.QUOTE_NONE,
names=["fname", "raw_text", "normalized_text"])
def get_example(self, i):
fname, raw_text, normalized_text = self._table.iloc[i]
fname = str(self._wav_dir.joinpath(fname + ".wav"))
return fname, raw_text, normalized_text
def __len__(self):
return len(self._table)
class LJSpeech(object):
def __init__(self, config):
super(LJSpeech, self).__init__()
self.config = config
self._ljspeech_processor = audio.AudioProcessor(
sample_rate=config['audio']['sr'],
num_mels=config['audio']['num_mels'],
min_level_db=config['audio']['min_level_db'],
ref_level_db=config['audio']['ref_level_db'],
n_fft=config['audio']['n_fft'],
win_length=config['audio']['win_length'],
hop_length=config['audio']['hop_length'],
power=config['audio']['power'],
preemphasis=config['audio']['preemphasis'],
signal_norm=True,
symmetric_norm=False,
max_norm=1.,
mel_fmin=0,
mel_fmax=None,
clip_norm=True,
griffin_lim_iters=60,
do_trim_silence=False,
sound_norm=False)
def __call__(self, metadatum):
"""All the code for generating an Example from a metadatum. If you want a
different preprocessing pipeline, you can override this method.
This method may require several processor, each of which has a lot of options.
In this case, you'd better pass a composed transform and pass it to the init
method.
"""
fname, raw_text, normalized_text = metadatum
# load -> trim -> preemphasis -> stft -> magnitude -> mel_scale -> logscale -> normalize
wav = self._ljspeech_processor.load_wav(str(fname))
mag = self._ljspeech_processor.spectrogram(wav).astype(np.float32)
mel = self._ljspeech_processor.melspectrogram(wav).astype(np.float32)
phonemes = np.array(
g2p.en.text_to_sequence(normalized_text), dtype=np.int64)
return (mag, mel, phonemes
) # maybe we need to implement it as a map in the future
def batch_examples(batch):
texts = []
mels = []
mel_inputs = []
mel_lens = []
text_lens = []
pos_texts = []
pos_mels = []
for data in batch:
_, mel, text = data
mel_inputs.append(
np.concatenate(
[np.zeros([mel.shape[0], 1], np.float32), mel[:, :-1]],
axis=-1))
mel_lens.append(mel.shape[1])
text_lens.append(len(text))
pos_texts.append(np.arange(1, len(text) + 1))
pos_mels.append(np.arange(1, mel.shape[1] + 1))
mels.append(mel)
texts.append(text)
# Sort by text_len in descending order
texts = [
i
for i, _ in sorted(
zip(texts, text_lens), key=lambda x: x[1], reverse=True)
]
mels = [
i
for i, _ in sorted(
zip(mels, text_lens), key=lambda x: x[1], reverse=True)
]
mel_inputs = [
i
for i, _ in sorted(
zip(mel_inputs, text_lens), key=lambda x: x[1], reverse=True)
]
mel_lens = [
i
for i, _ in sorted(
zip(mel_lens, text_lens), key=lambda x: x[1], reverse=True)
]
pos_texts = [
i
for i, _ in sorted(
zip(pos_texts, text_lens), key=lambda x: x[1], reverse=True)
]
pos_mels = [
i
for i, _ in sorted(
zip(pos_mels, text_lens), key=lambda x: x[1], reverse=True)
]
text_lens = sorted(text_lens, reverse=True)
# Pad sequence with largest len of the batch
texts = TextIDBatcher(pad_id=0)(texts) #(B, T)
pos_texts = TextIDBatcher(pad_id=0)(pos_texts) #(B,T)
pos_mels = TextIDBatcher(pad_id=0)(pos_mels) #(B,T)
mels = np.transpose(
SpecBatcher(pad_value=0.)(mels), axes=(0, 2, 1)) #(B,T,num_mels)
mel_inputs = np.transpose(
SpecBatcher(pad_value=0.)(mel_inputs), axes=(0, 2, 1)) #(B,T,num_mels)
enc_slf_mask = get_attn_key_pad_mask(pos_texts).astype(np.float32)
enc_query_mask = get_non_pad_mask(pos_texts).astype(np.float32)
dec_slf_mask = get_dec_attn_key_pad_mask(pos_mels,
mel_inputs).astype(np.float32)
enc_dec_mask = get_attn_key_pad_mask(enc_query_mask[:, :, 0]).astype(
np.float32)
dec_query_slf_mask = get_non_pad_mask(pos_mels).astype(np.float32)
dec_query_mask = get_non_pad_mask(pos_mels).astype(np.float32)
return (texts, mels, mel_inputs, pos_texts, pos_mels, np.array(text_lens),
np.array(mel_lens), enc_slf_mask, enc_query_mask, dec_slf_mask,
enc_dec_mask, dec_query_slf_mask, dec_query_mask)
def batch_examples_vocoder(batch):
mels = []
mags = []
for data in batch:
mag, mel, _ = data
mels.append(mel)
mags.append(mag)
mels = np.transpose(SpecBatcher(pad_value=0.)(mels), axes=(0, 2, 1))
mags = np.transpose(SpecBatcher(pad_value=0.)(mags), axes=(0, 2, 1))
return (mels, mags)
| [
"parakeet.data.datacargo.DataCargo",
"parakeet.data.dataset.TransformDataset",
"parakeet.audio.AudioProcessor",
"pandas.read_csv",
"pathlib.Path",
"paddle.fluid.io.DataLoader.from_generator",
"parakeet.g2p.en.text_to_sequence",
"paddle.fluid.CPUPlace",
"numpy.array",
"parakeet.data.batch.TextIDBat... | [((1375, 1395), 'pathlib.Path', 'Path', (['args.data_path'], {}), '(args.data_path)\n', (1379, 1395), False, 'from pathlib import Path\n'), ((1504, 1543), 'parakeet.data.dataset.TransformDataset', 'TransformDataset', (['metadata', 'transformer'], {}), '(metadata, transformer)\n', (1520, 1543), False, 'from parakeet.data.dataset import DatasetMixin, TransformDataset, CacheDataset, SliceDataset\n'), ((1562, 1583), 'parakeet.data.dataset.CacheDataset', 'CacheDataset', (['dataset'], {}), '(dataset)\n', (1574, 1583), False, 'from parakeet.data.dataset import DatasetMixin, TransformDataset, CacheDataset, SliceDataset\n'), ((2309, 2417), 'paddle.fluid.io.DataLoader.from_generator', 'fluid.io.DataLoader.from_generator', ([], {'capacity': '(32)', 'iterable': '(True)', 'use_double_buffer': '(True)', 'return_list': '(True)'}), '(capacity=32, iterable=True,\n use_double_buffer=True, return_list=True)\n', (2343, 2417), False, 'from paddle import fluid\n'), ((2612, 2622), 'pathlib.Path', 'Path', (['root'], {}), '(root)\n', (2616, 2622), False, 'from pathlib import Path\n'), ((2750, 2870), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {'sep': '"""|"""', 'header': 'None', 'quoting': 'csv.QUOTE_NONE', 'names': "['fname', 'raw_text', 'normalized_text']"}), "(csv_path, sep='|', header=None, quoting=csv.QUOTE_NONE, names=[\n 'fname', 'raw_text', 'normalized_text'])\n", (2761, 2870), True, 'import pandas as pd\n'), ((3348, 3917), 'parakeet.audio.AudioProcessor', 'audio.AudioProcessor', ([], {'sample_rate': "config['audio']['sr']", 'num_mels': "config['audio']['num_mels']", 'min_level_db': "config['audio']['min_level_db']", 'ref_level_db': "config['audio']['ref_level_db']", 'n_fft': "config['audio']['n_fft']", 'win_length': "config['audio']['win_length']", 'hop_length': "config['audio']['hop_length']", 'power': "config['audio']['power']", 'preemphasis': "config['audio']['preemphasis']", 'signal_norm': '(True)', 'symmetric_norm': '(False)', 'max_norm': '(1.0)', 'mel_fmin': '(0)', 'mel_fmax': 'None', 'clip_norm': '(True)', 'griffin_lim_iters': '(60)', 'do_trim_silence': '(False)', 'sound_norm': '(False)'}), "(sample_rate=config['audio']['sr'], num_mels=config[\n 'audio']['num_mels'], min_level_db=config['audio']['min_level_db'],\n ref_level_db=config['audio']['ref_level_db'], n_fft=config['audio'][\n 'n_fft'], win_length=config['audio']['win_length'], hop_length=config[\n 'audio']['hop_length'], power=config['audio']['power'], preemphasis=\n config['audio']['preemphasis'], signal_norm=True, symmetric_norm=False,\n max_norm=1.0, mel_fmin=0, mel_fmax=None, clip_norm=True,\n griffin_lim_iters=60, do_trim_silence=False, sound_norm=False)\n", (3368, 3917), False, 'from parakeet import audio\n'), ((6602, 6625), 'parakeet.data.batch.TextIDBatcher', 'TextIDBatcher', ([], {'pad_id': '(0)'}), '(pad_id=0)\n', (6615, 6625), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((6658, 6681), 'parakeet.data.batch.TextIDBatcher', 'TextIDBatcher', ([], {'pad_id': '(0)'}), '(pad_id=0)\n', (6671, 6681), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((6716, 6739), 'parakeet.data.batch.TextIDBatcher', 'TextIDBatcher', ([], {'pad_id': '(0)'}), '(pad_id=0)\n', (6729, 6739), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((7530, 7549), 'numpy.array', 'np.array', (['text_lens'], {}), '(text_lens)\n', (7538, 7549), True, 'import numpy as np\n'), ((7563, 7581), 'numpy.array', 'np.array', (['mel_lens'], {}), '(mel_lens)\n', (7571, 7581), True, 'import numpy as np\n'), ((1290, 1311), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['rank'], {}), '(rank)\n', (1305, 1311), False, 'from paddle import fluid\n'), ((1333, 1349), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (1347, 1349), False, 'from paddle import fluid\n'), ((1818, 1943), 'parakeet.data.datacargo.DataCargo', 'DataCargo', (['dataset'], {'sampler': 'sampler', 'batch_size': 'each_bs', 'shuffle': 'shuffle', 'batch_fn': 'batch_examples_vocoder', 'drop_last': '(True)'}), '(dataset, sampler=sampler, batch_size=each_bs, shuffle=shuffle,\n batch_fn=batch_examples_vocoder, drop_last=True)\n', (1827, 1943), False, 'from parakeet.data.datacargo import DataCargo\n'), ((2076, 2193), 'parakeet.data.datacargo.DataCargo', 'DataCargo', (['dataset'], {'sampler': 'sampler', 'batch_size': 'each_bs', 'shuffle': 'shuffle', 'batch_fn': 'batch_examples', 'drop_last': '(True)'}), '(dataset, sampler=sampler, batch_size=each_bs, shuffle=shuffle,\n batch_fn=batch_examples, drop_last=True)\n', (2085, 2193), False, 'from parakeet.data.datacargo import DataCargo\n'), ((4899, 4939), 'parakeet.g2p.en.text_to_sequence', 'g2p.en.text_to_sequence', (['normalized_text'], {}), '(normalized_text)\n', (4922, 4939), False, 'from parakeet import g2p\n'), ((5574, 5604), 'numpy.arange', 'np.arange', (['(1)', '(mel.shape[1] + 1)'], {}), '(1, mel.shape[1] + 1)\n', (5583, 5604), True, 'import numpy as np\n'), ((6791, 6817), 'parakeet.data.batch.SpecBatcher', 'SpecBatcher', ([], {'pad_value': '(0.0)'}), '(pad_value=0.0)\n', (6802, 6817), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((6896, 6922), 'parakeet.data.batch.SpecBatcher', 'SpecBatcher', ([], {'pad_value': '(0.0)'}), '(pad_value=0.0)\n', (6907, 6922), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((7879, 7905), 'parakeet.data.batch.SpecBatcher', 'SpecBatcher', ([], {'pad_value': '(0.0)'}), '(pad_value=0.0)\n', (7890, 7905), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((7952, 7978), 'parakeet.data.batch.SpecBatcher', 'SpecBatcher', ([], {'pad_value': '(0.0)'}), '(pad_value=0.0)\n', (7963, 7978), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((5341, 5380), 'numpy.zeros', 'np.zeros', (['[mel.shape[0], 1]', 'np.float32'], {}), '([mel.shape[0], 1], np.float32)\n', (5349, 5380), True, 'import numpy as np\n')] |
import os
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
def downloader(url):
"""
Downloads the specified URL and saves it to disk
"""
req = urllib.request.urlopen(url)
filename = os.path.basename(url)
ext = os.path.splitext(url)[1]
if not ext:
raise RuntimeError('URL does not contain an extension')
with open(filename, 'wb') as file_handle:
while True:
chunk = req.read(1024)
if not chunk:
break
file_handle.write(chunk)
msg = 'Finished downloading {filename}'.format(filename=filename)
return msg
def main(urls):
"""
Create a thread pool and download specified urls
"""
with ThreadPoolExecutor(max_workers=5) as executor:
return executor.map(downloader, urls, timeout=60)
if __name__ == '__main__':
urls = ["http://www.irs.gov/pub/irs-pdf/f1040.pdf",
"http://www.irs.gov/pub/irs-pdf/f1040a.pdf",
"http://www.irs.gov/pub/irs-pdf/f1040ez.pdf",
"http://www.irs.gov/pub/irs-pdf/f1040es.pdf",
"http://www.irs.gov/pub/irs-pdf/f1040sb.pdf"]
results = main(urls)
for result in results:
print(result) | [
"concurrent.futures.ThreadPoolExecutor",
"os.path.splitext",
"os.path.basename"
] | [((284, 305), 'os.path.basename', 'os.path.basename', (['url'], {}), '(url)\n', (300, 305), False, 'import os\n'), ((317, 338), 'os.path.splitext', 'os.path.splitext', (['url'], {}), '(url)\n', (333, 338), False, 'import os\n'), ((808, 841), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {'max_workers': '(5)'}), '(max_workers=5)\n', (826, 841), False, 'from concurrent.futures import ThreadPoolExecutor\n')] |
#!/usr/bin/python
# coding=utf-8
# 公众号:testerzhang
__author__ = 'testerzhang'
import os
import time
import traceback
from appium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException
from selenium.webdriver.support import expected_conditions as EC
from tqdm import tqdm
import parse
from loguru import logger
import jdconfig as config
logger.add(config.APPIUM_LOG)
def wait_time_bar(wait_sec):
logger.debug(f"等待{wait_sec}秒")
wait_value = 10 * wait_sec
for i in tqdm(range(wait_value)):
time.sleep(0.1)
# logger.debug("")
class JD(object):
def __init__(self):
device_port = config.DEVICE_PORT
desired_caps = config.DESIRED_CAPS
self.skip_list = config.SKIP_LIST
url = "http://localhost:{}/wd/hub".format(device_port)
try:
self.driver = webdriver.Remote(url, desired_caps)
except WebDriverException:
raise Exception("请手机连接到电脑哦!")
except:
logger.error(f"异常={traceback.format_exc()}")
raise Exception("连接手机出了问题,请检查下")
self.wait = WebDriverWait(self.driver, config.TIME_OUT)
self.game_over = False
self.windows_xpath = config.WINDOWS_XPATH
self.windows_xpath2 = config.WINDOWS_XPATH2
self.except_html = "./except"
if not os.path.exists(self.except_html):
os.makedirs(self.except_html)
self.finish_task_skip = []
logger.debug("1.打开京东")
wait_time_bar(4)
# 点击中间区域位置
def click_screen_middle(self):
screen_size = self.driver.get_window_size()
logger.debug(f"手机屏幕大小={screen_size}")
# 屏幕的宽度 width
x = screen_size['width']
# 屏幕的高度 height
y = screen_size['height']
start_x = x / 2
start_y = y / 2
positions = [(start_x, start_y), (start_x, start_y)]
logger.debug(f"点击屏幕位置={positions}")
self.driver.tap(positions, 100)
# 关闭
def close(self):
wait_time_bar(5)
logger.debug("6.关闭app")
self.driver.quit()
# 检测是否在当前自动化的app
def detect_app(self):
if self.driver.current_package != "com.jingdong.app.mall":
self.driver.back()
# 判断某些任务是不是直接跳过
def continue_task(self, content):
is_continue = True
for skip in self.skip_list:
if skip in content:
logger.warning(f"任务=[{content}]暂时不做")
is_continue = False
break
return is_continue
# 首页查找入口
def active_page(self):
search_result = False
logger.debug(f"2.查找活动入口")
try:
# 搜索框
search_div = '//android.widget.TextView[contains(@content-desc,"搜索")]'
search_elm = self.wait.until(EC.presence_of_element_located((By.XPATH, search_div)))
search_elm.click()
wait_time_bar(2)
# 换个思路,拿到动态的resource-id
my_regx = '''{temp}content-desc="搜索框,{temp2}resource-id="{search_id}"{temp3}'''
regx_result = parse.parse(my_regx, self.driver.page_source)
# logger.debug(f"regx_result={regx_result}")
if regx_result is None:
logger.warning("获取搜索框ID正则匹配失败,退出")
raise Exception("获取搜索框ID正则匹配失败,退出")
search_text_id = regx_result['search_id']
# 输入搜索文本,这里目前只能是用ID,xpath解析异常
# search_text_id = 'com.jd.lib.search.feature:id/a54'
box = self.wait.until(EC.presence_of_element_located((By.ID, search_text_id)))
box.set_text("炸年兽")
# 点击搜索按钮
logger.debug(f"点击搜索按钮")
search_btn_xpath = '//android.widget.TextView[@content-desc="搜索,按钮"]'
button = self.wait.until(EC.presence_of_element_located((By.XPATH, search_btn_xpath)))
button.click()
wait_time_bar(3)
# 废弃寻找元素
# door_xpath = '//androidx.recyclerview.widget.RecyclerView/android.widget.RelativeLayout[@index="2"]'
# door_button = self.wait.until(EC.presence_of_element_located((By.XPATH, door_xpath)))
# door_button.click()
# 屏幕点击位置进入活动
self.click_screen_middle()
# 加载新页面时间
wait_time_bar(5)
logger.debug("进入活动入口")
except NoSuchElementException:
raise Exception("找不到活动入口")
filename = f"{self.except_html}/search.html"
self.write_html(filename)
except:
raise Exception("元素定位了,但是找不到活动入口")
filename = f"{self.except_html}/search-except.html"
self.write_html(filename)
return True
def close_windows(self):
try:
count_div = f'//*[@text="累计任务奖励"]/../../android.view.View[1]'
count_elm = self.driver.find_element(By.XPATH, count_div)
logger.debug(f"点击关闭按钮")
count_elm.click()
except:
logger.warning(f"点击关闭异常")
# logger.debug(f"【{task}】点击异常={traceback.format_exc()}")
# task必须是副标题的内容
def print_task_detail(self, task):
continue_flag = True
task_title_xpath = ""
task_second_title_xpath = ""
task_title_text = ""
task_second_title_text = ""
try:
logger.debug(f"检查任务:【{task}】是否存在")
task_second_title_xpath = f'//*[contains(@text, "{task}")]'
task_second_title = self.driver.find_element(By.XPATH, task_second_title_xpath)
task_second_title_text = task_second_title.text
logger.debug(f"任务副标题={task_second_title_text}")
except:
logger.warning(f"该任务:【{task}】不执行")
continue_flag = False
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
try:
task_title_xpath = f'{task_second_title_xpath}//preceding-sibling::android.view.View[1]'
task_title_elm = self.driver.find_element(By.XPATH, task_title_xpath)
# 获取标题
task_title_text = task_title_elm.text
logger.debug(f"任务标题={task_title_text}")
except NoSuchElementException:
continue_flag = False
filename = f"{self.except_html}/获取任务主标题-不存在.html"
self.write_html(filename)
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
except:
logger.warning(f"该任务:【{task}】获取任务标题异常,不执行")
continue_flag = False
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
# 判断是否任务跳过
is_continue = self.continue_task(task_title_text)
if not is_continue:
logger.warning(f"满足跳过任务关键字,退出2")
continue_flag = False
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
# task必须是主标题的内容
def print_task_detail2(self, task):
continue_flag = True
task_title_xpath = ""
task_second_title_xpath = ""
task_title_text = ""
task_second_title_text = ""
try:
logger.debug(f"检查任务:【{task}】是否存在")
task_title_xpath = f'//*[contains(@text, "{task}")]'
task_title = self.driver.find_element(By.XPATH, task_title_xpath)
task_title_text = task_title.text
logger.debug(f"任务主标题={task_title_text}")
except NoSuchElementException:
pass
except:
logger.warning(f"该任务:【{task}】不执行")
continue_flag = False
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
try:
task_second_title_xpath = f'{task_title_xpath}//following-sibling::android.view.View[1]'
task_second_title_elm = self.driver.find_element(By.XPATH, task_second_title_xpath)
# 获取标题
task_second_title_text = task_second_title_elm.text
logger.debug(f"任务副标题={task_second_title_text}")
except NoSuchElementException:
continue_flag = False
filename = f"{self.except_html}/获取任务副标题-不存在.html"
self.write_html(filename)
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
except:
logger.warning(f"该任务:【{task}】获取任务副标题异常,不执行")
continue_flag = False
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
# 判断是否任务跳过
is_continue = self.continue_task(task_title_text)
if not is_continue:
logger.warning(f"满足跳过任务关键字,退出2")
continue_flag = False
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
return continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text
# 种草城
def grass_task(self, task):
init_loop = 0
max_loop = 1
jump_loop_flag = 0
while init_loop < max_loop:
init_loop = init_loop + 1
if jump_loop_flag == 1:
logger.debug(f"超过循环次数,退出该类任务。")
break
continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text = self.print_task_detail2(
task)
if not continue_flag:
break
# 开始点击
result = parse.parse("{temp}({now_times}/{total_times})", f"{task_title_text}")
now_times = int(result['now_times'])
total_times = 3
logger.debug(f"now_times={now_times},total_times={total_times}")
if now_times == total_times and total_times > 0:
continue
else:
while now_times < total_times:
logger.debug(f"开始【{task}】任务now_times={now_times}点击")
# todo:检测页面是否已经完成任务了
try:
task_button_do_xpath = f'{task_second_title_xpath}/following-sibling::android.view.View[1]'
task_button_do_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
task_button_do_elm.click()
except NoSuchElementException:
filename = f"{self.except_html}/互动种草城-点击-{now_times}-no-found.html"
self.write_html(filename)
break
except:
logger.warning(f"该任务:【{task}】获取任务按钮异常,不执行")
break
wait_time_bar(3)
# 检测页面是否含有"当前页点击浏览4个商品领爆竹"文字
logger.debug(f"检测页面是否有关键字")
source = self.driver.page_source
find_flag = source.find("互动种草城")
if find_flag == -1:
logger.warning(f"没找到【互动种草城】关键字,退出任务")
break
# 执行4次
shop_success = True
for i in range(1, 4):
try:
logger.debug(f"开始第{i}次访问店铺")
to_finish_xpath = f'//android.view.View[contains(@text, "去完成去完成")]'
to_finish_elm = self.driver.find_element(By.XPATH, to_finish_xpath)
to_finish_elm.click()
except NoSuchElementException:
shop_success = False
filename = f"{self.except_html}/互动种草城-店铺-{i}.html"
self.write_html(filename)
break
except:
shop_success = False
logger.warning(f"点击店铺异常={traceback.format_exc()}")
break
wait_time_bar(1)
logger.debug("从详情页返回")
self.driver.back()
wait_time_bar(2)
if shop_success:
logger.debug("返回任务列表")
self.driver.back()
now_times = now_times + 1
# gzh:testerzhang 做任务列表,还不能做全部,后续再看看。
def do_task(self, detect=False):
if detect:
enter_success = self.detect_enter_task_lists()
if not enter_success:
logger.warning(f"没有进入任务列表,退出")
return
# 配置文件配置需要执行的任务清单
task_list = config.TASK_LIST
for task in task_list:
if self.game_over:
break
while True:
# 开始做任务
logger.debug(f"开始真正做任务列表:【{task}】")
if task in ["去领取"]:
try:
progress_div = f'//*[@text="累计任务奖励"]/../android.view.View[3]/android.view.View/android.view.View'
progress_elm_lists = self.driver.find_elements(By.XPATH, progress_div)
logger.debug(f"找到[去领取]区域长度={len(progress_elm_lists)}")
for i, progress_elm in enumerate(progress_elm_lists, 0):
if i == 0:
continue
logger.debug(f"尝试点击第{i}个[去领取]")
progress_elm.click()
wait_time_bar(2)
close_tip_div = f'//android.view.View[contains(@text, "+")]'
close_tip_lists = self.driver.find_elements(By.XPATH, close_tip_div)
if len(close_tip_lists) > 0:
close_tip_elm = close_tip_lists[0]
tips = close_tip_elm.text
logger.debug(f"tips={tips}")
if '爆竹' in tips:
logger.debug(f"关闭弹窗")
self.close_windows()
wait_time_bar(2)
except NoSuchElementException:
filename = f"{self.except_html}/lingqu.html"
self.write_html(filename)
except:
logger.warning(f"[去领取]异常={traceback.format_exc()}")
else:
wait_time_bar(5)
break
elif task in ["关闭"]:
self.close_windows()
break
elif task in ["去组队可得", "玩AR游戏"]:
continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text = self.print_task_detail(
task)
if not continue_flag:
break
try:
logger.debug(f"开始【{task}】任务点击")
task_button_do_xpath = f'{task_title_xpath}/following-sibling::android.view.View[2]'
task_button_do_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
task_button_do_elm.click()
if task in ["玩AR游戏"]:
wait_time_bar(4)
self.driver.back()
else:
wait_time_bar(2)
except NoSuchElementException:
filename = f"{self.except_html}/join_group_or_ar_no.html"
self.write_html(filename)
except:
logger.warning(f"该任务:【{task}】获取任务按钮异常,不执行")
break
break
elif task in ["去种草城"]:
# todo: 只有一次种草城
self.grass_task(task)
break
elif '底部跳转app' == task:
try:
logger.debug(f"开始点击任务列表底部的横幅")
task_button_do_xpath = f'''//android.view.View[@resource-id="taskPanelBanner"]'''
task_button_do_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
task_button_do_elm.click()
self.do_other_app()
except NoSuchElementException:
filename = f"{self.except_html}/底部跳转app-no-found.html"
self.write_html(filename)
except:
logger.warning(f"该任务:【{task}】获取任务按钮异常,不执行")
logger.warning("做【其他任务】完成,直接退出吧")
self.game_over = True
## 不管做啥,都退出
break
elif '累计浏览' == task:
init_loop = 0
max_loop = 3
jump_loop_flag = 0
while init_loop < max_loop:
init_loop = init_loop + 1
if jump_loop_flag == 1:
logger.debug(f"超过循环次数,退出该类任务。")
break
continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text = self.print_task_detail(
task)
if not continue_flag:
break
# 开始点击
result = parse.parse("{temp}({now_times}/{total_times})", f"{task_title_text}")
now_times = int(result['now_times'])
total_times = int(result['total_times'])
logger.debug(f"now_times={now_times},total_times={total_times}")
if now_times == total_times and total_times > 0:
continue
else:
while now_times < total_times:
try:
logger.debug(f"开始【{task}】任务now_times={now_times}点击")
task_button_do_xpath = f'{task_second_title_xpath}/following-sibling::android.view.View[1]'
task_button_do_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
task_button_do_elm.click()
except NoSuchElementException:
filename = f"{self.except_html}/累计浏览-点击浏览-{now_times}-no-found.html"
self.write_html(filename)
break
except:
logger.warning(f"该任务:【{task}】获取任务按钮异常,不执行")
break
wait_time_bar(3)
# 检测页面是否含有"当前页点击浏览4个商品领爆竹"文字
logger.debug(f"检测页面是否有关键字")
source = self.driver.page_source
find_flag = source.find("当前页点击浏览4个商品领爆竹")
if find_flag == -1:
logger.warning(f"没找到【当前页点击浏览4个商品领爆竹】关键字,退出任务")
break
# 执行4次
browse_success = True
for i in range(1, 5):
try:
logger.debug(f"开始第{i}次浏览商品")
goods_views_xpath = f'//android.view.View[@resource-id="root"]/android.view.View[2]/android.view.View[{i}]'
# logger.debug(f"goods_views_xpath={goods_views_xpath}")
goods_views_elm = self.driver.find_element(By.XPATH, goods_views_xpath)
goods_views_elm.click()
except NoSuchElementException:
browse_success = False
filename = f"{self.except_html}/累计浏览-商品-{i}.html"
self.write_html(filename)
break
except:
browse_success = False
logger.warning(f"点击商品异常={traceback.format_exc()}")
break
wait_time_bar(1)
logger.debug("从商品详情页返回")
self.driver.back()
wait_time_bar(2)
if browse_success:
logger.debug("返回任务列表")
self.driver.back()
now_times = now_times + 1
break
elif '浏览3个品牌墙' == task:
init_loop = 0
max_loop = 3
jump_loop_flag = 0
while init_loop < max_loop:
init_loop = init_loop + 1
if jump_loop_flag == 1:
logger.debug(f"超过循环次数,退出该类任务。")
break
continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text = self.print_task_detail(
task)
if not continue_flag:
break
# 开始点击
result = parse.parse("{temp}({now_times}/{total_times})", f"{task_title_text}")
now_times = int(result['now_times'])
total_times = int(result['total_times'])
logger.debug(f"now_times={now_times},total_times={total_times}")
if now_times == total_times and total_times > 0:
continue
else:
while now_times < total_times:
try:
logger.debug(f"开始【{task}】任务now_times={now_times}点击")
task_button_do_xpath = f'{task_second_title_xpath}/following-sibling::android.view.View[1]'
task_button_do_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
task_button_do_elm.click()
except NoSuchElementException:
filename = f"{self.except_html}/浏览3个品牌墙-点击浏览-{now_times}-no-found.html"
self.write_html(filename)
break
except:
logger.warning(f"该任务:【{task}】获取任务按钮异常,不执行")
break
wait_time_bar(3)
# 检测页面是否含有"当前页点击浏览4个商品领爆竹"文字
logger.debug(f"检测页面是否有关键字")
source = self.driver.page_source
find_flag = source.find("feedBottom")
if find_flag == -1:
logger.warning(f"没找到【feedBottom】关键字,退出任务")
break
# 执行4次
browse_success = True
for i in range(1, 4):
try:
logger.debug(f"开始第{i}次浏览品牌墙")
goods_views_xpath = f'//android.view.View[@resource-id="feedBottom"]/android.view.View/android.view.View[2]/android.view.View[{i}]'
# logger.debug(f"goods_views_xpath={goods_views_xpath}")
goods_views_elm = self.driver.find_element(By.XPATH, goods_views_xpath)
goods_views_elm.click()
except NoSuchElementException:
browse_success = False
filename = f"{self.except_html}/浏览3个品牌墙-品牌浏览-{i}.html"
self.write_html(filename)
break
except:
browse_success = False
logger.warning(f"点击浏览品牌墙异常={traceback.format_exc()}")
break
wait_time_bar(1)
logger.debug("从品牌墙详情页返回")
self.driver.back()
wait_time_bar(2)
if browse_success:
logger.debug("返回任务列表")
self.driver.back()
# 屏幕点击位置进入活动
self.click_screen_middle()
# 加载新页面时间
wait_time_bar(5)
button_name = "重新进入:做任务,集爆竹"
enter_success = self.find_task_list_entrance(button_name)
if not enter_success:
logger.error(f"重新进入活动,依然没找到任务列表入口")
else:
wait_time_bar(5)
self.do_task(detect=True)
now_times = now_times + 1
break
elif '浏览' in task:
init_loop = 0
max_loop = 3
jump_loop_flag = 0
while init_loop < max_loop:
init_loop = init_loop + 1
if jump_loop_flag == 1:
logger.debug(f"超过循环次数,退出该类任务。")
break
continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text = self.print_task_detail(
task)
if not continue_flag:
break
if '浏览并加购' in task_second_title_text:
logger.warning(f"浏览并加购任务不做")
break
# elif '成功入会并浏览可得' in task_second_title_text:
# logger.warning(f"成功入会任务不做")
# break
elif '去财富岛' in task_second_title_text:
logger.debug(f"财富岛任务不做")
break
elif '去小程序' in task_second_title_text:
logger.debug(f"去小程序任务不做")
break
# 开始点击
result = parse.parse("{temp}({now_times}/{total_times})", f"{task_title_text}")
now_times = int(result['now_times'])
total_times = int(result['total_times'])
logger.debug(f"now_times={now_times},total_times={total_times}")
if now_times == total_times and total_times > 0:
continue
else:
while now_times < total_times:
# 当前节点是index=2,查找节点android.view.View index="3"
try:
task_button_do_xpath = f'{task_second_title_xpath}//following-sibling::android.view.View[1]'
task_button_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
except:
logger.warning(f"该任务:【{task}】获取任务按钮异常,不执行")
# logger.debug(f"【{task}】点击异常={traceback.format_exc()}")
jump_loop_flag = 1
break
# 开始任务点击
logger.debug(f"任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行")
task_button_elm.click()
if '直播间' in task_title_text:
# 直播时间更长
wait_time_bar(5 + 20)
logger.debug(f"关闭关注主播弹窗")
self.driver.back()
elif '去逛东东超市' in task_title_text:
wait_time_bar(5)
logger.debug(f"多返回一次")
self.driver.back()
elif '去京东金榜' in task_title_text:
wait_time_bar(5)
elif '去种草城' in task_title_text:
wait_time_bar(2)
self.driver.back()
self.grass_task('去种草城')
jump_loop_flag = 1
break
elif '浏览并关注可得' in task_second_title_text:
wait_time_bar(5)
elif '浏览可得10000爆竹' == task_second_title_text:
if '去成为' in task_title_text:
jump_loop_flag = 1
self.driver.back()
break
wait_time_bar(2)
elif '成功入会并浏览' in task_second_title_text:
wait_time_bar(10)
# 确认授权并加入店铺会员 关键字,就退出循环
page_source = self.driver.page_source
if '确认授权并加入店铺会员' in page_source:
logger.warning(f"发现【确认授权并加入店铺会员】,退出循环")
jump_loop_flag = 1
self.driver.back()
break
else:
logger.debug("没有触犯规则,继续")
else:
wait_time_bar(5 + 10)
if '去京东金榜' in task_title_text:
logger.warning(f"尝试点击左上角返回按钮,如果无效,需要手工执行")
div_xpath = '//*[@resource-id="com.jd.lib.RankingList.feature:id/q"]'
self.only_click("去京东金榜", div_xpath, times=0)
else:
logger.debug(f"返回一下,然后稍微休息")
self.driver.back()
wait_time_bar(3)
now_times = now_times + 1
# 更新任务正标题
try:
task_title_xpath = f'{task_second_title_xpath}//preceding-sibling::android.view.View[1]'
task_title_elm = self.driver.find_element(By.XPATH, task_title_xpath)
# 获取标题
task_title_text = task_title_elm.text
logger.debug(f"任务标题={task_title_text}")
except:
logger.warning(f"该任务:【{task}】获取任务标题异常,不执行")
continue
break
elif '城城' in task:
continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text = self.print_task_detail(
task)
if not continue_flag:
break
# 开始点击
result = parse.parse("{temp}({now_times}/{total_times})", f"{task_title_text}")
now_times = int(result['now_times'])
total_times = int(result['total_times'])
logger.debug(f"now_times={now_times},total_times={total_times}")
if now_times == total_times and total_times > 0:
break
else:
while now_times < total_times:
# 当前节点是index=2,查找节点android.view.View index="3"
try:
task_button_do_xpath = f'{task_second_title_xpath}//following-sibling::android.view.View[1]'
task_button_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
except:
logger.warning(f"该任务:【{task}】获取任务按钮异常,不执行")
break
# 开始任务点击
logger.debug(f"任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行")
task_button_elm.click()
wait_time_bar(6)
self.process_city()
logger.debug(f"返回一下,然后稍微休息")
self.driver.back()
wait_time_bar(3)
now_times = now_times + 1
# 更新任务正标题
try:
task_title_xpath = f'{task_second_title_xpath}//preceding-sibling::android.view.View[1]'
task_title_elm = self.driver.find_element(By.XPATH, task_title_xpath)
# 获取标题
task_title_elm_text = task_title_elm.text
logger.debug(f"任务标题={task_title_elm_text}")
except:
logger.warning(f"该任务:【{task}】获取任务标题异常,不执行")
break
break
elif '小程序' in task:
continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text = self.print_task_detail(
task)
if not continue_flag:
break
# 开始点击
result = parse.parse("{temp}({now_times}/{total_times})", f"{task_title_text}")
now_times = int(result['now_times'])
total_times = int(result['total_times'])
logger.debug(f"now_times={now_times},total_times={total_times}")
if now_times == total_times and total_times > 0:
break
else:
while now_times < total_times:
# 当前节点是index=2,查找节点android.view.View index="3"
program_flag = 0
try:
task_button_do_xpath = f'{task_second_title_xpath}/../android.view.View[@index="3"]'
task_button_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
if config.DEBUG_HTML:
logger.debug(f'第1次查找:{task_button_elm.get_attribute("bounds")}')
filename = f"{self.except_html}/program_to_do-1.html"
self.write_html(filename)
except NoSuchElementException:
logger.warning(f"没找到【去完成】按钮")
program_flag = 1
except:
logger.warning(f"该任务:【{task}】获取任务按钮异常,不执行。异常={traceback.format_exc()}")
break
# todo:修正了上一个定位,可能这个不需要了。
if program_flag == 1:
try:
task_button_do_xpath = f'{task_second_title_xpath}//following-sibling::android.view.View[2]'
task_button_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
if config.DEBUG_HTML:
logger.debug(f'第2次查找:{task_button_elm.get_attribute("bounds")}')
filename = f"{self.except_html}/program_to_do-2.html"
self.write_html(filename)
except NoSuchElementException:
logger.warning(f"再次没找到【去完成】按钮")
filename = f"{self.except_html}/program_to_do_not_found.html"
self.write_html(filename)
break
except:
logger.warning(f"该任务:【{task}】再次获取任务按钮异常,不执行。异常={traceback.format_exc()}")
break
# 开始任务点击
logger.debug(f"任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行")
task_button_elm.click()
# todo: 可能会有bug
wait_time_bar(3)
self.detect_app()
wait_time_bar(3)
self.detect_app()
logger.debug(f"返回一下,然后稍微休息")
self.detect_app()
wait_time_bar(6)
now_times = now_times + 1
# 更新任务正标题
try:
wait_time_bar(2)
task_title_xpath = f'{task_second_title_xpath}//preceding-sibling::android.view.View[1]'
task_title_elm = self.driver.find_element(By.XPATH, task_title_xpath)
# 获取标题
task_title_elm_text = task_title_elm.text
logger.debug(f"任务标题={task_title_elm_text}")
except NoSuchElementException:
try:
# 年货特卖
logger.debug(f"查找是否含有【好货特卖】文字")
nian_div_xpath = f'//android.widget.TextView[@text="好货特卖"]'
nian_sign_div_elm = self.driver.find_element(By.XPATH, nian_div_xpath)
if nian_sign_div_elm is not None:
logger.debug(f"从小程序跳转回来,还需要再返回一次")
self.driver.back()
except NoSuchElementException:
logger.warning(f"没找到任务标题信息")
filename = f"{self.except_html}/program_jump_back_title.html"
self.write_html(filename)
except:
logger.warning(f"该任务:【{task}】获取任务标题异常,不执行")
break
break
else:
logger.warning(f"其他任务不做:【{task}】")
break
return
# gzh:testerzhang 做任务列表,只做 浏览 任务。
def do_jr_task_details(self):
try:
logger.debug(f"检测是否进入金融app[任务列表]")
flag_div = f'//*[@text="累计任务奖励"]'
self.driver.find_elements(By.XPATH, flag_div)
if config.DEBUG_HTML:
filename = f"{self.except_html}/jr_task-temp.html"
self.write_html(filename)
except NoSuchElementException:
raise Exception("没成功进入金融app【任务列表】,退出")
return
except:
logger.warning(f"检测是否进入金融app[任务列表]异常={traceback.format_exc()}")
return
# 配置文件配置需要执行的任务清单
task_list = config.JR_TASK_LIST
for task in task_list:
while True:
# 开始做任务
logger.debug(f"开始真正做JR任务列表:【{task}】")
if task in ["去领取"]:
try:
progress_div = f'//*[@text="累计任务奖励"]/../android.view.View[3]/android.view.View/android.view.View'
progress_elm_lists = self.driver.find_elements(By.XPATH, progress_div)
logger.debug(f"找到[去领取]区域长度={len(progress_elm_lists)}")
for i, progress_elm in enumerate(progress_elm_lists, 0):
if i == 0:
continue
logger.debug(f"尝试点击第{i}个[去领取]")
progress_elm.click()
wait_time_bar(2)
close_tip_div = f'//android.view.View[contains(@text, "+")]'
close_tip_lists = self.driver.find_elements(By.XPATH, close_tip_div)
if len(close_tip_lists) > 0:
close_tip_elm = close_tip_lists[0]
tips = close_tip_elm.text
logger.debug(f"tips={tips}")
if '爆竹' in tips:
logger.debug(f"关闭弹窗")
self.close_windows()
wait_time_bar(2)
except NoSuchElementException:
filename = f"{self.except_html}/lingqu.html"
self.write_html(filename)
except:
logger.warning(f"[去领取]异常={traceback.format_exc()}")
else:
wait_time_bar(5)
break
elif task in ["关闭"]:
self.close_windows()
break
elif '浏览' in task:
init_loop = 0
max_loop = 3
jump_loop_flag = 0
while init_loop < max_loop:
init_loop = init_loop + 1
if jump_loop_flag == 1:
logger.debug(f"超过循环次数,退出该类任务。")
break
continue_flag, task_title_xpath, task_second_title_xpath, task_title_text, task_second_title_text = self.print_task_detail(
task)
if not continue_flag:
break
if '浏览并加购' in task_second_title_text:
logger.warning(f"浏览并加购任务不做")
break
# elif '成功入会并浏览可得' in task_second_title_text:
# logger.warning(f"成功入会任务不做")
# break
elif '去财富岛' in task_second_title_text:
logger.debug(f"财富岛任务不做")
break
elif '去小程序' in task_second_title_text:
logger.debug(f"去小程序任务不做")
break
# 开始点击
result = parse.parse("{temp}({now_times}/{total_times})", f"{task_title_text}")
now_times = int(result['now_times'])
total_times = int(result['total_times'])
logger.debug(f"now_times={now_times},total_times={total_times}")
if now_times == total_times and total_times > 0:
continue
else:
while now_times < total_times:
# 当前节点是index=2,查找节点android.view.View index="3"
try:
task_button_do_xpath = f'{task_second_title_xpath}//following-sibling::android.view.View[1]'
task_button_elm = self.driver.find_element(By.XPATH, task_button_do_xpath)
except:
logger.warning(f"该任务:【{task}】获取任务按钮异常,不执行")
# logger.debug(f"【{task}】点击异常={traceback.format_exc()}")
jump_loop_flag = 1
break
# 开始任务点击
logger.debug(f"任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行")
task_button_elm.click()
if '去合成压岁钱' in task_title_text:
logger.debug(f"去合成压岁钱要去财富岛,尝试直接返回")
elif '去瓜分3亿红包' in task_title_text:
wait_time_bar(5 + 10)
return_flag = self.detect_enter_task_lists()
if not return_flag:
logger.debug(f"不在任务列表页面,再次尝试返回一下")
self.driver.back()
elif '去京东金融app签到' in task_title_text:
wait_time_bar(15)
self.driver.back()
elif '浏览你的家庭保障缺口' in task_title_text:
wait_time_bar(15)
self.driver.back()
elif '浏览并关注可得' in task_second_title_text:
wait_time_bar(5)
else:
wait_time_bar(5 + 10)
logger.debug(f"返回一下,然后稍微休息")
self.driver.back()
wait_time_bar(5)
now_times = now_times + 1
# 更新任务正标题
try:
task_title_xpath = f'{task_second_title_xpath}//preceding-sibling::android.view.View[1]'
task_title_elm = self.driver.find_element(By.XPATH, task_title_xpath)
# 获取标题
task_title_text = task_title_elm.text
logger.debug(f"任务标题={task_title_text}")
except NoSuchElementException:
logger.warning(f"该任务:【{task}】获取金融任务标题异常,不执行")
filename = f"{self.except_html}/jr_task_title_no_found.html"
self.write_html(filename)
except:
logger.warning(f"该任务:【{task}】获取金融任务标题异常,不执行")
continue
break
else:
logger.warning(f"其他任务不做:【{task}】")
break
return
# 做jr app
def do_jr_app_task(self):
if config.DEBUG_HTML:
filename = f"{self.except_html}/金融app.html"
self.write_html(filename)
try:
logger.debug(f"开始点击金融app【任务列表】按钮")
button_div_xpath = config.JR_TASK_LISTS_BUTTON_XPATH
button_div_lists = self.driver.find_elements(By.XPATH, button_div_xpath)
len_button_div_lists = len(button_div_lists)
# logger.debug(f"button_div_lists={button_div_lists},len={len_button_div_lists}")
if len_button_div_lists == 0:
logger.warning("没有定位到金融app任务列表按钮元素,可能得手动杀掉进程,返回")
return
button_div_lists[-1].click()
if config.DEBUG_HTML:
filename = f"{self.except_html}/jr_home.html"
self.write_html(filename)
except NoSuchElementException:
logger.warning(f"找不到金融app【任务列表】按钮")
filename = f"{self.except_html}/jr_home_no_found.html"
self.write_html(filename)
except:
logger.warning(f"【金融app【任务列表】按钮点击异常={traceback.format_exc()}")
filename = f"{self.except_html}/jr_home_exception.html"
self.write_html(filename)
else:
wait_time_bar(3)
logger.debug(f"继续做金融的其他任务")
self.do_jr_task_details()
# 做wx app,涉及小程序,不做。
def do_wx_app_task(self):
pass
# 做其他任务
def do_other_app(self):
wait_time_bar(5)
now_app = self.driver.current_package
now_app_activity = self.driver.current_activity
logger.debug(f"now_app={now_app},now_app_activity={now_app_activity}")
if now_app == "com.jd.jrapp":
wait_time_bar(8 + 10)
logger.debug(f"做京东金融任务")
self.do_jr_app_task()
elif now_app == "com.tencent.mm":
wait_time_bar(1)
logger.debug(f"做微信任务")
self.do_wx_app_task()
else:
logger.warning("做【其他任务】异常,直接退出吧")
# 处理"城城"
def process_city(self):
if config.CITY_GAME_OVER_FLAG:
logger.debug(f"城城【活动已结束】,不会有弹窗")
try:
logger.debug(f"进入城城主页面,点击【查看我的现金】按钮")
invite_div = '''//android.view.View[@resource-id="app"]/android.view.View/android.view.View/android.view.View[5]/android.view.View'''
invite_button_elm = self.driver.find_element(By.XPATH, invite_div)
invite_button_elm.click()
wait_time_bar(5)
self.detect_app()
except:
logger.warning(f"点击【邀3人立领现金】按钮异常,不执行")
return
else:
# todo: 还有收下现金弹窗
invite_windows_flag = 0
try:
logger.debug(f"处理城城【邀请活动新朋友,金额更高噢】弹窗")
city_invite_text_div = f'//android.view.View[@text="邀请活动新朋友,金额更高噢"]'
self.driver.find_element(By.XPATH, city_invite_text_div)
close_city_invite_text_div = '''//android.view.View[@resource-id="dialogs"]/android.view.View[2]/android.view.View/android.view.View/android.view.View[1]'''
close_city_invite_button_elm = self.driver.find_element(By.XPATH, close_city_invite_text_div)
close_city_invite_button_elm.click()
invite_windows_flag = 1
except NoSuchElementException:
pass
except:
logger.warning(f"关闭城城【邀请活动新朋友,金额更高噢】弹窗异常,不执行。{traceback.format_exc()}")
return
if invite_windows_flag == 0:
try:
logger.debug(f"处理城城广告窗")
city_close_title_div = '''//android.view.View[@resource-id="dialogs"]/android.view.View[2]/android.view.View/android.view.View/android.view.View[3]'''
city_close_button_elm = self.driver.find_element(By.XPATH, city_close_title_div)
city_close_button_elm.click()
except NoSuchElementException:
logger.warning(f"没找到关闭城城弹窗")
except:
logger.warning(f"关闭城城弹窗异常,不执行。{traceback.format_exc()}")
return
wait_time_bar(3)
try:
logger.debug(f"进入城城主页面,点击【邀3人立领现金】按钮")
invite_div = '''//android.view.View[@resource-id="app"]/android.view.View/android.view.View/android.view.View[9]/android.view.View[2]'''
invite_button_elm = self.driver.find_element(By.XPATH, invite_div)
invite_button_elm.click()
wait_time_bar(5)
self.detect_app()
except:
logger.warning(f"点击【邀3人立领现金】按钮异常,不执行")
return
# todo:京口令复制弹窗
# gzh:testerzhang 点击生产出来的爆竹
def collect_bomb(self):
# source = self.driver.page_source
# logger.debug(f"领取币source:{source}")
try:
logger.debug("开始点击【年兽】图标,收集爆竹")
collect_bomb_div = '''//android.view.View[@resource-id="root"]/android.view.View[1]/android.view.View[3]'''
collect_bomb_button = self.driver.find_element(By.XPATH, collect_bomb_div)
# logger.debug(collect_bomb_button.get_attribute("bounds"))
collect_bomb_button.click()
except NoSuchElementException:
pass
except:
logger.warning(f"【年兽】点击异常={traceback.format_exc()}")
wait_time_bar(3)
return
def write_html(self, filename):
source = self.driver.page_source
# logger.debug(f"页面source:{source}")
# file_name = f"doc/{filename}"
with open(filename, 'w') as f:
f.write(source)
# gzh:testerzhang 点击每日签到
def do_sign(self):
try:
# 今日已签到
logger.debug(f"查找是否含有【今日已签到】文字")
query_sign_div_xpath = f'//android.view.View[@text="今日已签到"]'
query_sign_div_elm = self.driver.find_element(By.XPATH, query_sign_div_xpath)
# logger.debug(f"query_sign_div_elm={query_sign_div_elm}")
if query_sign_div_elm is not None:
logger.debug(f"【今日已签到】,不需要签到")
return
except NoSuchElementException:
filename = f"{self.except_html}/sign_detail.html"
self.write_html(filename)
except:
logger.warning(f"查找【今日已签到】文字点击异常={traceback.format_exc()}")
try:
# 签到领红包签到领红包
logger.debug(f"开始点击[签到领红包签到领红包]按钮")
sign_div_xpath = f'//android.view.View[@text="签到领红包签到领红包"]'
sign_div_lists = self.driver.find_element(By.XPATH, sign_div_xpath)
sign_div_lists.click()
except NoSuchElementException:
filename = f"{self.except_html}/sign_sign.html"
self.write_html(filename)
except:
logger.warning(f"点击[签到领红包签到领红包]按钮点击异常={traceback.format_exc()}")
else:
wait_time_bar(2)
# 开始点击页面的"点我签到"按钮
self.sign_page()
# 签到页面处理
def sign_page(self):
try:
# 明天再来明天再来
logger.debug(f"查找是否含有【明天再来明天再来】文字")
query_sign_div_xpath = f'//android.view.View[@text="明天再来明天再来"]'
query_sign_div_elm = self.driver.find_element(By.XPATH, query_sign_div_xpath)
# logger.debug(f"query_sign_div_elm={query_sign_div_elm}")
if query_sign_div_elm is not None:
logger.debug(f"【今日已签到】,准备退出弹窗")
try:
logger.debug(f"尝试点击[关闭]按钮")
# 可能这个位置后续会变
close_div_xpath = f'{self.windows_xpath}/android.view.View[2]'
close_div_elm = self.driver.find_element(By.XPATH, close_div_xpath)
close_div_elm.click()
except NoSuchElementException:
filename = f"{self.except_html}/sign_after_close.html"
self.write_html(filename)
except:
logger.warning(f"点击[关闭]动作异常={traceback.format_exc()}")
return
except NoSuchElementException:
pass
except:
logger.warning(f"查找【明天再来明天再来】文字处理异常={traceback.format_exc()}")
try:
logger.debug(f"查找是否含有【点我签到】按钮")
sign_div_xpath = f'//android.view.View[@text="点我签到点我签到"]'
sign_div_elm = self.driver.find_element(By.XPATH, sign_div_xpath)
logger.debug(f"sign_div_elm={sign_div_elm}")
if sign_div_elm is not None:
logger.debug(f"点击【点我签到】按钮")
sign_div_elm.click()
except NoSuchElementException:
filename = f"{self.except_html}/sign_home_text.html"
self.write_html(filename)
except:
logger.warning(f"点击[点我签到]按钮点击异常={traceback.format_exc()}")
else:
# todo: 处理弹窗,还没测试。
wait_time_bar(5)
# todo: 失效,换个写法看看找到关闭元素进行关闭
try:
logger.debug(f"开始点击[开心收下]按钮的关闭按钮")
# 开心收下 弹窗
sign_close_div_xpath = '//android.view.View[text="开心收下开心收下"]/../../../android.view.View[3]/android.view.View'
sign_close_div_elm = self.driver.find_element(By.XPATH, sign_close_div_xpath)
if sign_div_elm is not None:
sign_close_div_elm.click()
except NoSuchElementException:
logger.warning("找不到【开心收下】按钮,尝试跳出活动再进入")
filename = f"{self.except_html}/sign_finish_happy.html"
self.write_html(filename)
button_name = "做任务,集爆竹"
self.driver.back()
# 屏幕点击位置进入活动
self.click_screen_middle()
# 加载新页面时间
wait_time_bar(5)
enter_success = self.find_task_list_entrance(button_name)
if not enter_success:
logger.error(f"重新进入活动,依然没找到任务列表入口")
else:
wait_time_bar(5)
self.do_task(detect=True)
except:
logger.warning(f"点击[开心收下]按钮点击异常={traceback.format_exc()}")
else:
wait_time_bar(2)
# 检测是否进入任务列表
def detect_enter_task_lists(self):
enter_success = False
try:
logger.debug(f"检测是否进入[任务列表]")
flag_div = f'//*[@text="累计任务奖励"]'
self.driver.find_element(By.XPATH, flag_div)
enter_success = True
if config.DEBUG_HTML:
filename = f"{self.except_html}/detect_enter_task_lists.html"
self.write_html(filename)
except NoSuchElementException:
logger.warning("没成功进入【任务列表】,有可能是有两个手导致图层不对,退出")
filename = f"{self.except_html}/detect_enter_task_lists-nofound.html"
self.write_html(filename)
except:
logger.error(f"检测是否进入[任务列表]异常={traceback.format_exc()}")
return enter_success
# 查找任务列表入口
def find_task_list_entrance(self, button_name):
enter_success = False
try:
logger.debug(f"开始点击[{button_name}]按钮")
# 爆竹升级未够的时候在第二个view,够的时候在第三个view
button_div_xpath = '''//android.view.View[@resource-id="homeBtnTeam"]/following-sibling::android.view.View[2]'''
button_div_lists = self.driver.find_elements(By.XPATH, button_div_xpath)
len_button_div_lists = len(button_div_lists)
# logger.debug(f"button_div_lists={button_div_lists},len={len_button_div_lists}")
if len_button_div_lists == 0:
return
button_div_lists[-1].click()
enter_success = True
if config.DEBUG_HTML:
filename = f"{self.except_html}/tasks_list_debug.html"
self.write_html(filename)
except NoSuchElementException:
logger.warning(f"找不到【{button_name}】按钮")
filename = f"{self.except_html}/tasks_list_door.html"
self.write_html(filename)
except:
logger.warning(f"【{button_name}】点击异常={traceback.format_exc()}")
filename = f"{self.except_html}/tasks_list_door-other.html"
self.write_html(filename)
return enter_success
# gzh:testerzhang 点击任务列表按钮,然后进入具体的任务列表
def do_tasks(self, button_name):
enter_success = self.find_task_list_entrance(button_name)
if not enter_success:
logger.error(f"没找到任务列表入口")
else:
wait_time_bar(5)
enter_success = self.detect_enter_task_lists()
if enter_success:
# 最新任务列表签到
self.do_task()
else:
wait_time_bar(3)
# todo:先关闭弹窗
div_xpath = '//android.view.View[text="开心收下开心收下"]/../../../android.view.View[3]/android.view.View'
self.search_close("开心收下x按钮", div_xpath, times=0)
source = self.driver.page_source
if '开心收下开心收下' in source or '开启下一站开启下一站' in source:
logger.warning("还处于【开心收下】或者 【开启下一站】 弹窗,按住返回键,重新进入")
self.driver.back()
# 屏幕点击位置进入活动
self.click_screen_middle()
# 加载新页面时间
wait_time_bar(5)
enter_success = self.find_task_list_entrance(button_name)
if not enter_success:
logger.error(f"重新进入活动,依然没找到任务列表入口")
else:
wait_time_bar(5)
self.do_task(detect=True)
return
else:
logger.warning(f"没有检测到进入任务列表,再次尝试")
try:
logger.debug(f"再次开始点击[{button_name}]按钮")
button_div_xpath = '''//android.view.View[@resource-id="homeBtnTeam"]/following-sibling::android.view.View[3]'''
button_div_lists = self.driver.find_elements(By.XPATH, button_div_xpath)
len_button_div_lists = len(button_div_lists)
# logger.debug(f"button_div_lists={button_div_lists},len={len_button_div_lists}")
if len_button_div_lists == 0:
return
button_div_lists[-1].click()
if config.DEBUG_HTML:
filename = f"{self.except_html}/tasks_list_debug.html"
self.write_html(filename)
except NoSuchElementException:
logger.warning(f"找不到【{button_name}】按钮")
filename = f"{self.except_html}/tasks_list_door.html"
self.write_html(filename)
except:
logger.warning(f"【{button_name}】点击异常={traceback.format_exc()}")
filename = f"{self.except_html}/tasks_list_door-other.html"
self.write_html(filename)
else:
wait_time_bar(5)
self.do_task()
# 只负责点击,后续没其他动作
def only_click(self, text, div_xpath, times=0):
error_flag = True
try:
logger.debug(f"尝试点击[{text}]弹窗")
# 弹窗
# div_xpath = '//android.view.View[text="开心收下开心收下"]'
div_elm = self.driver.find_element(By.XPATH, div_xpath)
div_elm_click_enable = div_elm.get_attribute('clickable')
# logger.debug(f"元素是否可以点击={div_elm_click_enable}")
# logger.debug(f"元素的坐标={div_elm.get_attribute('bounds')}")
if text == "去京东金榜":
logger.debug(f"尝试返回")
self.driver.back()
logger.debug(f"再次尝试返回")
self.driver.back()
logger.debug(f"尝试点击之后...")
else:
if div_elm_click_enable:
logger.debug(f"元素状态是可以点击")
# logger.debug(f"元素的坐标={div_elm.get_attribute('bounds')}")
div_elm.click()
error_flag = False
if config.DEBUG_HTML and text == "去京东金榜":
filename = f"{self.except_html}/public_click-{text}.html"
self.write_html(filename)
except NoSuchElementException:
if times == 0:
filename = f"{self.except_html}/public_click-{text}.html"
else:
filename = f"{self.except_html}/public_click-{text}-{times}.html"
self.write_html(filename)
except:
logger.warning(f"点击[{text}]按钮点击异常={traceback.format_exc()}")
return error_flag
# 寻找弹窗关闭窗口
def search_close(self, text, div_xpath, times=0):
error_flag = True
try:
logger.debug(f"尝试点击[{text}]弹窗关闭按钮")
# 弹窗
div_elm = self.driver.find_element(By.XPATH, div_xpath)
logger.debug(f"元素是否可以点击={div_elm.get_attribute('clickable')}")
logger.debug(f"元素的坐标={div_elm.get_attribute('bounds')}")
div_elm.click()
error_flag = False
except NoSuchElementException:
if times == 0:
filename = f"{self.except_html}/public_click-{text}.html"
else:
filename = f"{self.except_html}/public_click-{text}-{times}.html"
self.write_html(filename)
if text == "开心收下x按钮" and config.DEBUG_HTML:
logger.debug(f"self.driver.page_source={self.driver.page_source}")
except:
logger.warning(f"点击[{text}]按钮点击异常={traceback.format_exc()}")
return error_flag
# gzh:testerzhang 首页处理点爆竹
def zha(self):
# 加多一层最大次数,防止循环。
max_times = config.DA_KA_LOOP
# 检测当前app
self.detect_app()
times = 1
logger.debug(f"开始执行,最大执行次数={max_times}次")
while True:
logger.debug(f"开始执行第{times}次")
if times > max_times:
break
wait_time_bar(2)
try:
# 集爆竹炸年兽,每次消耗89000个爆竹
logger.debug("开始点击【集爆竹炸年兽】图标")
# 每次消耗89000个爆竹
feed_div = '//*[contains(@text, "每次消耗")]'
self.driver.find_element(By.XPATH, feed_div).click()
except NoSuchElementException:
logger.warning(f"无法找到【集爆竹炸年兽】这个元素")
filename = f"{self.except_html}/home_bomb-{times}.html"
self.write_html(filename)
# 可能是因为弹窗了,暂时没修复。
# logger.debug(f"返回一下")
break
except:
logger.warning(f"【集爆竹炸年兽】点击异常={traceback.format_exc()}")
break
else:
wait_time_bar(8)
# todo: 只处理了两种弹窗,其他弹窗,后续再搞。
# 还有 立即完成,开启下一站 未测试
if config.DEBUG_HTML:
filename = f"{self.except_html}/zha-bug-{times}.html"
self.write_html(filename)
# todo: 开启下一站 弹窗,还要修正
div_xpath = '//android.view.View[text="开启下一站开启下一站"]/../android.view.View'
self.only_click("开启下一站", div_xpath, times=0)
# todo: 立即完成 弹窗,还要修正
div_xpath = '//android.view.View[text="立即完成"]'
self.only_click("立即完成", div_xpath, times=0)
# todo: 开心收下 弹窗,还要修正
div_xpath = '//android.view.View[text="开心收下开心收下"]/../../../android.view.View[3]/android.view.View'
self.search_close("开心收下x按钮", div_xpath, times=0)
close_flag = 0
if close_flag == 0:
# 爆竹不够的时候,弹出任务列表
try:
logger.debug("尝试关闭[任务列表]")
task_list_xpath = '//*[contains(@text, "累计任务奖励")]'
self.driver.find_element(By.XPATH, task_list_xpath)
# 点击右上角关闭按钮
self.close_windows()
# 退出
logger.warning("爆竹不够了,不再执行循环。")
break
except NoSuchElementException:
pass
except:
logger.warning(f"尝试关闭[任务列表]异常={traceback.format_exc()}")
else:
# todo: 这里还可能有弹窗。
pass
times = times + 1
return
# 第一次进入页面,弹窗处理
def process_windows(self):
# todo:判断弹框:继续抽奖
try:
windows_div = '//android.widget.ImageView[content-desc="返回"]'
windows_button = self.driver.find_element(By.XPATH, windows_div)
logger.debug(f"windows_button.text=[{windows_button.text}]")
windows_button.click()
except NoSuchElementException:
logger.warning(f"忽略")
except:
logger.warning(f"弹窗进行处理异常={traceback.format_exc()}")
# plus会员弹窗,未测试。
plus_flag = 0
try:
logger.debug(f"看是否有[Plus弹窗]")
# plus_div = '//android.view.View[text="送您"]'
plus_flag_div = '//android.view.View[text="Plus专享"]'
plus_flag_button = self.driver.find_element(By.XPATH, plus_flag_div)
logger.debug(f"plus_flag_button.text=[{plus_flag_button.text}]")
plus_div = '//android.view.View[text="Plus专享"]/../../following-sibling::android.view.View[1]/android.view.View'
plus_button = self.driver.find_element(By.XPATH, plus_div)
logger.debug(f"plus_button.text=[{plus_button.text}]")
plus_button.click()
plus_flag = 1
except NoSuchElementException:
# logger.warning(f"未找到plus弹窗,忽略")
pass
except:
logger.warning(f"弹窗进行处理异常={traceback.format_exc()}")
# 点击plus按钮之后,进入签到弹窗,未测试。
if plus_flag == 1:
try:
sign_flag_div = '//android.view.View[text="每天来签到,得最高111.1元红包"]'
sign_flag_button = self.driver.find_element(By.XPATH, sign_flag_div)
logger.debug(f"sign_flag_button.text=[{sign_flag_button.text}]")
sign_div_xpath = f'{self.windows_xpath2}/android.view.View[6]'
self.sign_page(sign_div_xpath)
except NoSuchElementException:
# logger.warning(f"未找到plus弹窗,忽略")
pass
except:
logger.warning(f"弹窗进行处理异常={traceback.format_exc()}")
else:
try:
logger.debug(f'尝试关掉[继续环游]弹窗')
draw_div_xpath = f'{self.windows_xpath2}/android.view.View[3]'
draw_close_div_elm = self.driver.find_element(By.XPATH, draw_div_xpath)
draw_close_div_elm.click()
except NoSuchElementException:
logger.warning(f"忽略")
except:
logger.warning(f"尝试关掉[继续环游]弹窗异常={traceback.format_exc()}")
try:
logger.debug(f'尝试关掉[立即抽奖]弹窗')
draw_div_xpath = f'{self.windows_xpath2}/android.view.View[2]/android.view.View[2]'
draw_close_div_elm = self.driver.find_element(By.XPATH, draw_div_xpath)
draw_close_div_elm.click()
except NoSuchElementException:
logger.warning(f"忽略")
except:
logger.warning(f"尝试关掉[立即抽奖]弹窗异常={traceback.format_exc()}")
return plus_flag
# gzh:testerzhang 进入H5页面
def do(self):
# 获取入口
search_result = self.active_page()
if not search_result:
logger.warning("找不到入口,退出")
return
logger.debug("3.准备切换H5页面")
wait_time_bar(4)
# todo: 尚未获取到相应弹窗信息,随缘修复。
if config.FIRST_WINDOWS_FLAG:
logger.debug("4.处理第一次进入页面的弹窗")
plus_flag = self.process_windows()
else:
plus_flag = 0
if config.DO_SIGN_FLAG and plus_flag == 0:
# 打开每日签到
self.do_sign()
if config.DO_TASKS_FLAG:
# 打开任务列表
self.do_tasks('做任务,集爆竹')
# # 点击收取爆竹
if config.RECEIVE_BOMB_FLAG and not self.game_over:
self.collect_bomb()
# 开始打卡
if config.DO_DA_KA_FLAG and not self.game_over:
self.zha()
def main():
jd = JD()
jd.do()
jd.close()
exit("退出")
if __name__ == '__main__':
main()
| [
"loguru.logger.add",
"os.path.exists",
"selenium.webdriver.support.ui.WebDriverWait",
"traceback.format_exc",
"parse.parse",
"loguru.logger.debug",
"os.makedirs",
"loguru.logger.warning",
"time.sleep",
"appium.webdriver.Remote",
"loguru.logger.error",
"selenium.webdriver.support.expected_condi... | [((502, 531), 'loguru.logger.add', 'logger.add', (['config.APPIUM_LOG'], {}), '(config.APPIUM_LOG)\n', (512, 531), False, 'from loguru import logger\n'), ((567, 597), 'loguru.logger.debug', 'logger.debug', (['f"""等待{wait_sec}秒"""'], {}), "(f'等待{wait_sec}秒')\n", (579, 597), False, 'from loguru import logger\n'), ((676, 691), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (686, 691), False, 'import time\n'), ((1244, 1287), 'selenium.webdriver.support.ui.WebDriverWait', 'WebDriverWait', (['self.driver', 'config.TIME_OUT'], {}), '(self.driver, config.TIME_OUT)\n', (1257, 1287), False, 'from selenium.webdriver.support.ui import WebDriverWait\n'), ((1598, 1620), 'loguru.logger.debug', 'logger.debug', (['"""1.打开京东"""'], {}), "('1.打开京东')\n", (1610, 1620), False, 'from loguru import logger\n'), ((1757, 1794), 'loguru.logger.debug', 'logger.debug', (['f"""手机屏幕大小={screen_size}"""'], {}), "(f'手机屏幕大小={screen_size}')\n", (1769, 1794), False, 'from loguru import logger\n'), ((2024, 2059), 'loguru.logger.debug', 'logger.debug', (['f"""点击屏幕位置={positions}"""'], {}), "(f'点击屏幕位置={positions}')\n", (2036, 2059), False, 'from loguru import logger\n'), ((2164, 2187), 'loguru.logger.debug', 'logger.debug', (['"""6.关闭app"""'], {}), "('6.关闭app')\n", (2176, 2187), False, 'from loguru import logger\n'), ((2735, 2760), 'loguru.logger.debug', 'logger.debug', (['f"""2.查找活动入口"""'], {}), "(f'2.查找活动入口')\n", (2747, 2760), False, 'from loguru import logger\n'), ((49750, 49820), 'loguru.logger.debug', 'logger.debug', (['f"""now_app={now_app},now_app_activity={now_app_activity}"""'], {}), "(f'now_app={now_app},now_app_activity={now_app_activity}')\n", (49762, 49820), False, 'from loguru import logger\n'), ((65986, 66027), 'loguru.logger.debug', 'logger.debug', (['f"""开始执行,最大执行次数={max_times}次"""'], {}), "(f'开始执行,最大执行次数={max_times}次')\n", (65998, 66027), False, 'from loguru import logger\n'), ((71780, 71806), 'loguru.logger.debug', 'logger.debug', (['"""3.准备切换H5页面"""'], {}), "('3.准备切换H5页面')\n", (71792, 71806), False, 'from loguru import logger\n'), ((992, 1027), 'appium.webdriver.Remote', 'webdriver.Remote', (['url', 'desired_caps'], {}), '(url, desired_caps)\n', (1008, 1027), False, 'from appium import webdriver\n'), ((1477, 1509), 'os.path.exists', 'os.path.exists', (['self.except_html'], {}), '(self.except_html)\n', (1491, 1509), False, 'import os\n'), ((1523, 1552), 'os.makedirs', 'os.makedirs', (['self.except_html'], {}), '(self.except_html)\n', (1534, 1552), False, 'import os\n'), ((3188, 3233), 'parse.parse', 'parse.parse', (['my_regx', 'self.driver.page_source'], {}), '(my_regx, self.driver.page_source)\n', (3199, 3233), False, 'import parse\n'), ((3751, 3774), 'loguru.logger.debug', 'logger.debug', (['f"""点击搜索按钮"""'], {}), "(f'点击搜索按钮')\n", (3763, 3774), False, 'from loguru import logger\n'), ((4411, 4433), 'loguru.logger.debug', 'logger.debug', (['"""进入活动入口"""'], {}), "('进入活动入口')\n", (4423, 4433), False, 'from loguru import logger\n'), ((4992, 5015), 'loguru.logger.debug', 'logger.debug', (['f"""点击关闭按钮"""'], {}), "(f'点击关闭按钮')\n", (5004, 5015), False, 'from loguru import logger\n'), ((5416, 5450), 'loguru.logger.debug', 'logger.debug', (['f"""检查任务:【{task}】是否存在"""'], {}), "(f'检查任务:【{task}】是否存在')\n", (5428, 5450), False, 'from loguru import logger\n'), ((5687, 5734), 'loguru.logger.debug', 'logger.debug', (['f"""任务副标题={task_second_title_text}"""'], {}), "(f'任务副标题={task_second_title_text}')\n", (5699, 5734), False, 'from loguru import logger\n'), ((6227, 6266), 'loguru.logger.debug', 'logger.debug', (['f"""任务标题={task_title_text}"""'], {}), "(f'任务标题={task_title_text}')\n", (6239, 6266), False, 'from loguru import logger\n'), ((6899, 6931), 'loguru.logger.warning', 'logger.warning', (['f"""满足跳过任务关键字,退出2"""'], {}), "(f'满足跳过任务关键字,退出2')\n", (6913, 6931), False, 'from loguru import logger\n'), ((7444, 7478), 'loguru.logger.debug', 'logger.debug', (['f"""检查任务:【{task}】是否存在"""'], {}), "(f'检查任务:【{task}】是否存在')\n", (7456, 7478), False, 'from loguru import logger\n'), ((7680, 7720), 'loguru.logger.debug', 'logger.debug', (['f"""任务主标题={task_title_text}"""'], {}), "(f'任务主标题={task_title_text}')\n", (7692, 7720), False, 'from loguru import logger\n'), ((8297, 8344), 'loguru.logger.debug', 'logger.debug', (['f"""任务副标题={task_second_title_text}"""'], {}), "(f'任务副标题={task_second_title_text}')\n", (8309, 8344), False, 'from loguru import logger\n'), ((8978, 9010), 'loguru.logger.warning', 'logger.warning', (['f"""满足跳过任务关键字,退出2"""'], {}), "(f'满足跳过任务关键字,退出2')\n", (8992, 9010), False, 'from loguru import logger\n'), ((9828, 9898), 'parse.parse', 'parse.parse', (['"""{temp}({now_times}/{total_times})"""', 'f"""{task_title_text}"""'], {}), "('{temp}({now_times}/{total_times})', f'{task_title_text}')\n", (9839, 9898), False, 'import parse\n'), ((9988, 10052), 'loguru.logger.debug', 'logger.debug', (['f"""now_times={now_times},total_times={total_times}"""'], {}), "(f'now_times={now_times},total_times={total_times}')\n", (10000, 10052), False, 'from loguru import logger\n'), ((40511, 40545), 'loguru.logger.debug', 'logger.debug', (['f"""检测是否进入金融app[任务列表]"""'], {}), "(f'检测是否进入金融app[任务列表]')\n", (40523, 40545), False, 'from loguru import logger\n'), ((48346, 48380), 'loguru.logger.debug', 'logger.debug', (['f"""开始点击金融app【任务列表】按钮"""'], {}), "(f'开始点击金融app【任务列表】按钮')\n", (48358, 48380), False, 'from loguru import logger\n'), ((49439, 49466), 'loguru.logger.debug', 'logger.debug', (['f"""继续做金融的其他任务"""'], {}), "(f'继续做金融的其他任务')\n", (49451, 49466), False, 'from loguru import logger\n'), ((49906, 49930), 'loguru.logger.debug', 'logger.debug', (['f"""做京东金融任务"""'], {}), "(f'做京东金融任务')\n", (49918, 49930), False, 'from loguru import logger\n'), ((50259, 50291), 'loguru.logger.debug', 'logger.debug', (['f"""城城【活动已结束】,不会有弹窗"""'], {}), "(f'城城【活动已结束】,不会有弹窗')\n", (50271, 50291), False, 'from loguru import logger\n'), ((53092, 53123), 'loguru.logger.debug', 'logger.debug', (['"""开始点击【年兽】图标,收集爆竹"""'], {}), "('开始点击【年兽】图标,收集爆竹')\n", (53104, 53123), False, 'from loguru import logger\n'), ((53952, 53984), 'loguru.logger.debug', 'logger.debug', (['f"""查找是否含有【今日已签到】文字"""'], {}), "(f'查找是否含有【今日已签到】文字')\n", (53964, 53984), False, 'from loguru import logger\n'), ((54614, 54649), 'loguru.logger.debug', 'logger.debug', (['f"""开始点击[签到领红包签到领红包]按钮"""'], {}), "(f'开始点击[签到领红包签到领红包]按钮')\n", (54626, 54649), False, 'from loguru import logger\n'), ((55256, 55291), 'loguru.logger.debug', 'logger.debug', (['f"""查找是否含有【明天再来明天再来】文字"""'], {}), "(f'查找是否含有【明天再来明天再来】文字')\n", (55268, 55291), False, 'from loguru import logger\n'), ((56405, 56436), 'loguru.logger.debug', 'logger.debug', (['f"""查找是否含有【点我签到】按钮"""'], {}), "(f'查找是否含有【点我签到】按钮')\n", (56417, 56436), False, 'from loguru import logger\n'), ((56597, 56641), 'loguru.logger.debug', 'logger.debug', (['f"""sign_div_elm={sign_div_elm}"""'], {}), "(f'sign_div_elm={sign_div_elm}')\n", (56609, 56641), False, 'from loguru import logger\n'), ((58467, 58496), 'loguru.logger.debug', 'logger.debug', (['f"""检测是否进入[任务列表]"""'], {}), "(f'检测是否进入[任务列表]')\n", (58479, 58496), False, 'from loguru import logger\n'), ((59244, 59282), 'loguru.logger.debug', 'logger.debug', (['f"""开始点击[{button_name}]按钮"""'], {}), "(f'开始点击[{button_name}]按钮')\n", (59256, 59282), False, 'from loguru import logger\n'), ((60595, 60621), 'loguru.logger.error', 'logger.error', (['f"""没找到任务列表入口"""'], {}), "(f'没找到任务列表入口')\n", (60607, 60621), False, 'from loguru import logger\n'), ((63402, 63433), 'loguru.logger.debug', 'logger.debug', (['f"""尝试点击[{text}]弹窗"""'], {}), "(f'尝试点击[{text}]弹窗')\n", (63414, 63433), False, 'from loguru import logger\n'), ((64942, 64977), 'loguru.logger.debug', 'logger.debug', (['f"""尝试点击[{text}]弹窗关闭按钮"""'], {}), "(f'尝试点击[{text}]弹窗关闭按钮')\n", (64954, 64977), False, 'from loguru import logger\n'), ((66061, 66091), 'loguru.logger.debug', 'logger.debug', (['f"""开始执行第{times}次"""'], {}), "(f'开始执行第{times}次')\n", (66073, 66091), False, 'from loguru import logger\n'), ((68820, 68880), 'loguru.logger.debug', 'logger.debug', (['f"""windows_button.text=[{windows_button.text}]"""'], {}), "(f'windows_button.text=[{windows_button.text}]')\n", (68832, 68880), False, 'from loguru import logger\n'), ((69142, 69171), 'loguru.logger.debug', 'logger.debug', (['f"""看是否有[Plus弹窗]"""'], {}), "(f'看是否有[Plus弹窗]')\n", (69154, 69171), False, 'from loguru import logger\n'), ((69388, 69452), 'loguru.logger.debug', 'logger.debug', (['f"""plus_flag_button.text=[{plus_flag_button.text}]"""'], {}), "(f'plus_flag_button.text=[{plus_flag_button.text}]')\n", (69400, 69452), False, 'from loguru import logger\n'), ((69661, 69715), 'loguru.logger.debug', 'logger.debug', (['f"""plus_button.text=[{plus_button.text}]"""'], {}), "(f'plus_button.text=[{plus_button.text}]')\n", (69673, 69715), False, 'from loguru import logger\n'), ((71725, 71751), 'loguru.logger.warning', 'logger.warning', (['"""找不到入口,退出"""'], {}), "('找不到入口,退出')\n", (71739, 71751), False, 'from loguru import logger\n'), ((71917, 71947), 'loguru.logger.debug', 'logger.debug', (['"""4.处理第一次进入页面的弹窗"""'], {}), "('4.处理第一次进入页面的弹窗')\n", (71929, 71947), False, 'from loguru import logger\n'), ((2531, 2568), 'loguru.logger.warning', 'logger.warning', (['f"""任务=[{content}]暂时不做"""'], {}), "(f'任务=[{content}]暂时不做')\n", (2545, 2568), False, 'from loguru import logger\n'), ((2917, 2971), 'selenium.webdriver.support.expected_conditions.presence_of_element_located', 'EC.presence_of_element_located', (['(By.XPATH, search_div)'], {}), '((By.XPATH, search_div))\n', (2947, 2971), True, 'from selenium.webdriver.support import expected_conditions as EC\n'), ((3343, 3377), 'loguru.logger.warning', 'logger.warning', (['"""获取搜索框ID正则匹配失败,退出"""'], {}), "('获取搜索框ID正则匹配失败,退出')\n", (3357, 3377), False, 'from loguru import logger\n'), ((3628, 3683), 'selenium.webdriver.support.expected_conditions.presence_of_element_located', 'EC.presence_of_element_located', (['(By.ID, search_text_id)'], {}), '((By.ID, search_text_id))\n', (3658, 3683), True, 'from selenium.webdriver.support import expected_conditions as EC\n'), ((3894, 3954), 'selenium.webdriver.support.expected_conditions.presence_of_element_located', 'EC.presence_of_element_located', (['(By.XPATH, search_btn_xpath)'], {}), '((By.XPATH, search_btn_xpath))\n', (3924, 3954), True, 'from selenium.webdriver.support import expected_conditions as EC\n'), ((5075, 5100), 'loguru.logger.warning', 'logger.warning', (['f"""点击关闭异常"""'], {}), "(f'点击关闭异常')\n", (5089, 5100), False, 'from loguru import logger\n'), ((5763, 5797), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】不执行"""'], {}), "(f'该任务:【{task}】不执行')\n", (5777, 5797), False, 'from loguru import logger\n'), ((6585, 6628), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务标题异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务标题异常,不执行')\n", (6599, 6628), False, 'from loguru import logger\n'), ((7805, 7839), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】不执行"""'], {}), "(f'该任务:【{task}】不执行')\n", (7819, 7839), False, 'from loguru import logger\n'), ((8663, 8707), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务副标题异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务副标题异常,不执行')\n", (8677, 8707), False, 'from loguru import logger\n'), ((9517, 9548), 'loguru.logger.debug', 'logger.debug', (['f"""超过循环次数,退出该类任务。"""'], {}), "(f'超过循环次数,退出该类任务。')\n", (9529, 9548), False, 'from loguru import logger\n'), ((12799, 12829), 'loguru.logger.warning', 'logger.warning', (['f"""没有进入任务列表,退出"""'], {}), "(f'没有进入任务列表,退出')\n", (12813, 12829), False, 'from loguru import logger\n'), ((13069, 13104), 'loguru.logger.debug', 'logger.debug', (['f"""开始真正做任务列表:【{task}】"""'], {}), "(f'开始真正做任务列表:【{task}】')\n", (13081, 13104), False, 'from loguru import logger\n'), ((41178, 41215), 'loguru.logger.debug', 'logger.debug', (['f"""开始真正做JR任务列表:【{task}】"""'], {}), "(f'开始真正做JR任务列表:【{task}】')\n", (41190, 41215), False, 'from loguru import logger\n'), ((48741, 48790), 'loguru.logger.warning', 'logger.warning', (['"""没有定位到金融app任务列表按钮元素,可能得手动杀掉进程,返回"""'], {}), "('没有定位到金融app任务列表按钮元素,可能得手动杀掉进程,返回')\n", (48755, 48790), False, 'from loguru import logger\n'), ((49046, 49081), 'loguru.logger.warning', 'logger.warning', (['f"""找不到金融app【任务列表】按钮"""'], {}), "(f'找不到金融app【任务列表】按钮')\n", (49060, 49081), False, 'from loguru import logger\n'), ((50048, 50070), 'loguru.logger.debug', 'logger.debug', (['f"""做微信任务"""'], {}), "(f'做微信任务')\n", (50060, 50070), False, 'from loguru import logger\n'), ((50131, 50164), 'loguru.logger.warning', 'logger.warning', (['"""做【其他任务】异常,直接退出吧"""'], {}), "('做【其他任务】异常,直接退出吧')\n", (50145, 50164), False, 'from loguru import logger\n'), ((50325, 50362), 'loguru.logger.debug', 'logger.debug', (['f"""进入城城主页面,点击【查看我的现金】按钮"""'], {}), "(f'进入城城主页面,点击【查看我的现金】按钮')\n", (50337, 50362), False, 'from loguru import logger\n'), ((50917, 50955), 'loguru.logger.debug', 'logger.debug', (['f"""处理城城【邀请活动新朋友,金额更高噢】弹窗"""'], {}), "(f'处理城城【邀请活动新朋友,金额更高噢】弹窗')\n", (50929, 50955), False, 'from loguru import logger\n'), ((52404, 52442), 'loguru.logger.debug', 'logger.debug', (['f"""进入城城主页面,点击【邀3人立领现金】按钮"""'], {}), "(f'进入城城主页面,点击【邀3人立领现金】按钮')\n", (52416, 52442), False, 'from loguru import logger\n'), ((54282, 54312), 'loguru.logger.debug', 'logger.debug', (['f"""【今日已签到】,不需要签到"""'], {}), "(f'【今日已签到】,不需要签到')\n", (54294, 54312), False, 'from loguru import logger\n'), ((55592, 55623), 'loguru.logger.debug', 'logger.debug', (['f"""【今日已签到】,准备退出弹窗"""'], {}), "(f'【今日已签到】,准备退出弹窗')\n", (55604, 55623), False, 'from loguru import logger\n'), ((56699, 56726), 'loguru.logger.debug', 'logger.debug', (['f"""点击【点我签到】按钮"""'], {}), "(f'点击【点我签到】按钮')\n", (56711, 56726), False, 'from loguru import logger\n'), ((57141, 57175), 'loguru.logger.debug', 'logger.debug', (['f"""开始点击[开心收下]按钮的关闭按钮"""'], {}), "(f'开始点击[开心收下]按钮的关闭按钮')\n", (57153, 57175), False, 'from loguru import logger\n'), ((58838, 58885), 'loguru.logger.warning', 'logger.warning', (['"""没成功进入【任务列表】,有可能是有两个手导致图层不对,退出"""'], {}), "('没成功进入【任务列表】,有可能是有两个手导致图层不对,退出')\n", (58852, 58885), False, 'from loguru import logger\n'), ((60029, 60068), 'loguru.logger.warning', 'logger.warning', (['f"""找不到【{button_name}】按钮"""'], {}), "(f'找不到【{button_name}】按钮')\n", (60043, 60068), False, 'from loguru import logger\n'), ((63836, 63857), 'loguru.logger.debug', 'logger.debug', (['f"""尝试返回"""'], {}), "(f'尝试返回')\n", (63848, 63857), False, 'from loguru import logger\n'), ((63909, 63932), 'loguru.logger.debug', 'logger.debug', (['f"""再次尝试返回"""'], {}), "(f'再次尝试返回')\n", (63921, 63932), False, 'from loguru import logger\n'), ((63984, 64010), 'loguru.logger.debug', 'logger.debug', (['f"""尝试点击之后..."""'], {}), "(f'尝试点击之后...')\n", (63996, 64010), False, 'from loguru import logger\n'), ((66249, 66279), 'loguru.logger.debug', 'logger.debug', (['"""开始点击【集爆竹炸年兽】图标"""'], {}), "('开始点击【集爆竹炸年兽】图标')\n", (66261, 66279), False, 'from loguru import logger\n'), ((68967, 68988), 'loguru.logger.warning', 'logger.warning', (['f"""忽略"""'], {}), "(f'忽略')\n", (68981, 68988), False, 'from loguru import logger\n'), ((70217, 70281), 'loguru.logger.debug', 'logger.debug', (['f"""sign_flag_button.text=[{sign_flag_button.text}]"""'], {}), "(f'sign_flag_button.text=[{sign_flag_button.text}]')\n", (70229, 70281), False, 'from loguru import logger\n'), ((70661, 70690), 'loguru.logger.debug', 'logger.debug', (['f"""尝试关掉[继续环游]弹窗"""'], {}), "(f'尝试关掉[继续环游]弹窗')\n", (70673, 70690), False, 'from loguru import logger\n'), ((71112, 71141), 'loguru.logger.debug', 'logger.debug', (['f"""尝试关掉[立即抽奖]弹窗"""'], {}), "(f'尝试关掉[立即抽奖]弹窗')\n", (71124, 71141), False, 'from loguru import logger\n'), ((10224, 10276), 'loguru.logger.debug', 'logger.debug', (['f"""开始【{task}】任务now_times={now_times}点击"""'], {}), "(f'开始【{task}】任务now_times={now_times}点击')\n", (10236, 10276), False, 'from loguru import logger\n'), ((11071, 11098), 'loguru.logger.debug', 'logger.debug', (['f"""检测页面是否有关键字"""'], {}), "(f'检测页面是否有关键字')\n", (11083, 11098), False, 'from loguru import logger\n'), ((50742, 50780), 'loguru.logger.warning', 'logger.warning', (['f"""点击【邀3人立领现金】按钮异常,不执行"""'], {}), "(f'点击【邀3人立领现金】按钮异常,不执行')\n", (50756, 50780), False, 'from loguru import logger\n'), ((51770, 51794), 'loguru.logger.debug', 'logger.debug', (['f"""处理城城广告窗"""'], {}), "(f'处理城城广告窗')\n", (51782, 51794), False, 'from loguru import logger\n'), ((52825, 52863), 'loguru.logger.warning', 'logger.warning', (['f"""点击【邀3人立领现金】按钮异常,不执行"""'], {}), "(f'点击【邀3人立领现金】按钮异常,不执行')\n", (52839, 52863), False, 'from loguru import logger\n'), ((55666, 55693), 'loguru.logger.debug', 'logger.debug', (['f"""尝试点击[关闭]按钮"""'], {}), "(f'尝试点击[关闭]按钮')\n", (55678, 55693), False, 'from loguru import logger\n'), ((57573, 57612), 'loguru.logger.warning', 'logger.warning', (['"""找不到【开心收下】按钮,尝试跳出活动再进入"""'], {}), "('找不到【开心收下】按钮,尝试跳出活动再进入')\n", (57587, 57612), False, 'from loguru import logger\n'), ((61211, 61262), 'loguru.logger.warning', 'logger.warning', (['"""还处于【开心收下】或者 【开启下一站】 弹窗,按住返回键,重新进入"""'], {}), "('还处于【开心收下】或者 【开启下一站】 弹窗,按住返回键,重新进入')\n", (61225, 61262), False, 'from loguru import logger\n'), ((61816, 61851), 'loguru.logger.warning', 'logger.warning', (['f"""没有检测到进入任务列表,再次尝试"""'], {}), "(f'没有检测到进入任务列表,再次尝试')\n", (61830, 61851), False, 'from loguru import logger\n'), ((64090, 64116), 'loguru.logger.debug', 'logger.debug', (['f"""元素状态是可以点击"""'], {}), "(f'元素状态是可以点击')\n", (64102, 64116), False, 'from loguru import logger\n'), ((65617, 65683), 'loguru.logger.debug', 'logger.debug', (['f"""self.driver.page_source={self.driver.page_source}"""'], {}), "(f'self.driver.page_source={self.driver.page_source}')\n", (65629, 65683), False, 'from loguru import logger\n'), ((66497, 66532), 'loguru.logger.warning', 'logger.warning', (['f"""无法找到【集爆竹炸年兽】这个元素"""'], {}), "(f'无法找到【集爆竹炸年兽】这个元素')\n", (66511, 66532), False, 'from loguru import logger\n'), ((70961, 70982), 'loguru.logger.warning', 'logger.warning', (['f"""忽略"""'], {}), "(f'忽略')\n", (70975, 70982), False, 'from loguru import logger\n'), ((71433, 71454), 'loguru.logger.warning', 'logger.warning', (['f"""忽略"""'], {}), "(f'忽略')\n", (71447, 71454), False, 'from loguru import logger\n'), ((11269, 11306), 'loguru.logger.warning', 'logger.warning', (['f"""没找到【互动种草城】关键字,退出任务"""'], {}), "(f'没找到【互动种草城】关键字,退出任务')\n", (11283, 11306), False, 'from loguru import logger\n'), ((12306, 12328), 'loguru.logger.debug', 'logger.debug', (['"""从详情页返回"""'], {}), "('从详情页返回')\n", (12318, 12328), False, 'from loguru import logger\n'), ((12475, 12497), 'loguru.logger.debug', 'logger.debug', (['"""返回任务列表"""'], {}), "('返回任务列表')\n", (12487, 12497), False, 'from loguru import logger\n'), ((52184, 52212), 'loguru.logger.warning', 'logger.warning', (['f"""没找到关闭城城弹窗"""'], {}), "(f'没找到关闭城城弹窗')\n", (52198, 52212), False, 'from loguru import logger\n'), ((58066, 58101), 'loguru.logger.error', 'logger.error', (['f"""重新进入活动,依然没找到任务列表入口"""'], {}), "(f'重新进入活动,依然没找到任务列表入口')\n", (58078, 58101), False, 'from loguru import logger\n'), ((61593, 61628), 'loguru.logger.error', 'logger.error', (['f"""重新进入活动,依然没找到任务列表入口"""'], {}), "(f'重新进入活动,依然没找到任务列表入口')\n", (61605, 61628), False, 'from loguru import logger\n'), ((61901, 61941), 'loguru.logger.debug', 'logger.debug', (['f"""再次开始点击[{button_name}]按钮"""'], {}), "(f'再次开始点击[{button_name}]按钮')\n", (61913, 61941), False, 'from loguru import logger\n'), ((67872, 67898), 'loguru.logger.debug', 'logger.debug', (['"""尝试关闭[任务列表]"""'], {}), "('尝试关闭[任务列表]')\n", (67884, 67898), False, 'from loguru import logger\n'), ((68184, 68215), 'loguru.logger.warning', 'logger.warning', (['"""爆竹不够了,不再执行循环。"""'], {}), "('爆竹不够了,不再执行循环。')\n", (68198, 68215), False, 'from loguru import logger\n'), ((1156, 1178), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (1176, 1178), False, 'import traceback\n'), ((10890, 10933), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务按钮异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务按钮异常,不执行')\n", (10904, 10933), False, 'from loguru import logger\n'), ((11504, 11532), 'loguru.logger.debug', 'logger.debug', (['f"""开始第{i}次访问店铺"""'], {}), "(f'开始第{i}次访问店铺')\n", (11516, 11532), False, 'from loguru import logger\n'), ((13652, 13683), 'loguru.logger.debug', 'logger.debug', (['f"""尝试点击第{i}个[去领取]"""'], {}), "(f'尝试点击第{i}个[去领取]')\n", (13664, 13683), False, 'from loguru import logger\n'), ((40994, 41016), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (41014, 41016), False, 'import traceback\n'), ((41763, 41794), 'loguru.logger.debug', 'logger.debug', (['f"""尝试点击第{i}个[去领取]"""'], {}), "(f'尝试点击第{i}个[去领取]')\n", (41775, 41794), False, 'from loguru import logger\n'), ((48074, 48108), 'loguru.logger.warning', 'logger.warning', (['f"""其他任务不做:【{task}】"""'], {}), "(f'其他任务不做:【{task}】')\n", (48088, 48108), False, 'from loguru import logger\n'), ((49277, 49299), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (49297, 49299), False, 'import traceback\n'), ((53571, 53593), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (53591, 53593), False, 'import traceback\n'), ((54562, 54584), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (54582, 54584), False, 'import traceback\n'), ((55066, 55088), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (55086, 55088), False, 'import traceback\n'), ((56378, 56400), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (56398, 56400), False, 'import traceback\n'), ((56991, 57013), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (57011, 57013), False, 'import traceback\n'), ((59089, 59111), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (59109, 59111), False, 'import traceback\n'), ((60251, 60273), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (60271, 60273), False, 'import traceback\n'), ((62754, 62793), 'loguru.logger.warning', 'logger.warning', (['f"""找不到【{button_name}】按钮"""'], {}), "(f'找不到【{button_name}】按钮')\n", (62768, 62793), False, 'from loguru import logger\n'), ((64784, 64806), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (64804, 64806), False, 'import traceback\n'), ((65763, 65785), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (65783, 65785), False, 'import traceback\n'), ((69060, 69082), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (69080, 69082), False, 'import traceback\n'), ((69948, 69970), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (69968, 69970), False, 'import traceback\n'), ((14179, 14207), 'loguru.logger.debug', 'logger.debug', (['f"""tips={tips}"""'], {}), "(f'tips={tips}')\n", (14191, 14207), False, 'from loguru import logger\n'), ((15241, 15272), 'loguru.logger.debug', 'logger.debug', (['f"""开始【{task}】任务点击"""'], {}), "(f'开始【{task}】任务点击')\n", (15253, 15272), False, 'from loguru import logger\n'), ((42290, 42318), 'loguru.logger.debug', 'logger.debug', (['f"""tips={tips}"""'], {}), "(f'tips={tips}')\n", (42302, 42318), False, 'from loguru import logger\n'), ((44336, 44406), 'parse.parse', 'parse.parse', (['"""{temp}({now_times}/{total_times})"""', 'f"""{task_title_text}"""'], {}), "('{temp}({now_times}/{total_times})', f'{task_title_text}')\n", (44347, 44406), False, 'import parse\n'), ((44557, 44621), 'loguru.logger.debug', 'logger.debug', (['f"""now_times={now_times},total_times={total_times}"""'], {}), "(f'now_times={now_times},total_times={total_times}')\n", (44569, 44621), False, 'from loguru import logger\n'), ((51663, 51685), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (51683, 51685), False, 'import traceback\n'), ((58302, 58324), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (58322, 58324), False, 'import traceback\n'), ((66834, 66856), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (66854, 66856), False, 'import traceback\n'), ((70603, 70625), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (70623, 70625), False, 'import traceback\n'), ((71076, 71098), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (71096, 71098), False, 'import traceback\n'), ((71548, 71570), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (71568, 71570), False, 'import traceback\n'), ((14293, 14314), 'loguru.logger.debug', 'logger.debug', (['f"""关闭弹窗"""'], {}), "(f'关闭弹窗')\n", (14305, 14314), False, 'from loguru import logger\n'), ((15985, 16028), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务按钮异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务按钮异常,不执行')\n", (15999, 16028), False, 'from loguru import logger\n'), ((16951, 16984), 'loguru.logger.warning', 'logger.warning', (['"""做【其他任务】完成,直接退出吧"""'], {}), "('做【其他任务】完成,直接退出吧')\n", (16965, 16984), False, 'from loguru import logger\n'), ((42404, 42425), 'loguru.logger.debug', 'logger.debug', (['f"""关闭弹窗"""'], {}), "(f'关闭弹窗')\n", (42416, 42425), False, 'from loguru import logger\n'), ((43323, 43354), 'loguru.logger.debug', 'logger.debug', (['f"""超过循环次数,退出该类任务。"""'], {}), "(f'超过循环次数,退出该类任务。')\n", (43335, 43354), False, 'from loguru import logger\n'), ((43743, 43771), 'loguru.logger.warning', 'logger.warning', (['f"""浏览并加购任务不做"""'], {}), "(f'浏览并加购任务不做')\n", (43757, 43771), False, 'from loguru import logger\n'), ((52312, 52334), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (52332, 52334), False, 'import traceback\n'), ((56198, 56220), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (56218, 56220), False, 'import traceback\n'), ((14681, 14703), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (14701, 14703), False, 'import traceback\n'), ((16320, 16350), 'loguru.logger.debug', 'logger.debug', (['f"""开始点击任务列表底部的横幅"""'], {}), "(f'开始点击任务列表底部的横幅')\n", (16332, 16350), False, 'from loguru import logger\n'), ((42792, 42814), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (42812, 42814), False, 'import traceback\n'), ((44061, 44085), 'loguru.logger.debug', 'logger.debug', (['f"""财富岛任务不做"""'], {}), "(f'财富岛任务不做')\n", (44073, 44085), False, 'from loguru import logger\n'), ((45561, 45636), 'loguru.logger.debug', 'logger.debug', (['f"""任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行"""'], {}), "(f'任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行')\n", (45573, 45636), False, 'from loguru import logger\n'), ((46840, 46868), 'loguru.logger.debug', 'logger.debug', (['f"""返回一下,然后稍微休息"""'], {}), "(f'返回一下,然后稍微休息')\n", (46852, 46868), False, 'from loguru import logger\n'), ((63024, 63046), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (63044, 63046), False, 'import traceback\n'), ((68429, 68451), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (68449, 68451), False, 'import traceback\n'), ((12192, 12214), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (12212, 12214), False, 'import traceback\n'), ((16886, 16929), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务按钮异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务按钮异常,不执行')\n", (16900, 16929), False, 'from loguru import logger\n'), ((17799, 17869), 'parse.parse', 'parse.parse', (['"""{temp}({now_times}/{total_times})"""', 'f"""{task_title_text}"""'], {}), "('{temp}({now_times}/{total_times})', f'{task_title_text}')\n", (17810, 17869), False, 'import parse\n'), ((18020, 18084), 'loguru.logger.debug', 'logger.debug', (['f"""now_times={now_times},total_times={total_times}"""'], {}), "(f'now_times={now_times},total_times={total_times}')\n", (18032, 18084), False, 'from loguru import logger\n'), ((44211, 44236), 'loguru.logger.debug', 'logger.debug', (['f"""去小程序任务不做"""'], {}), "(f'去小程序任务不做')\n", (44223, 44236), False, 'from loguru import logger\n'), ((45794, 45829), 'loguru.logger.debug', 'logger.debug', (['f"""去合成压岁钱要去财富岛,尝试直接返回"""'], {}), "(f'去合成压岁钱要去财富岛,尝试直接返回')\n", (45806, 45829), False, 'from loguru import logger\n'), ((47493, 47532), 'loguru.logger.debug', 'logger.debug', (['f"""任务标题={task_title_text}"""'], {}), "(f'任务标题={task_title_text}')\n", (47505, 47532), False, 'from loguru import logger\n'), ((17405, 17436), 'loguru.logger.debug', 'logger.debug', (['f"""超过循环次数,退出该类任务。"""'], {}), "(f'超过循环次数,退出该类任务。')\n", (17417, 17436), False, 'from loguru import logger\n'), ((22084, 22154), 'parse.parse', 'parse.parse', (['"""{temp}({now_times}/{total_times})"""', 'f"""{task_title_text}"""'], {}), "('{temp}({now_times}/{total_times})', f'{task_title_text}')\n", (22095, 22154), False, 'import parse\n'), ((22305, 22369), 'loguru.logger.debug', 'logger.debug', (['f"""now_times={now_times},total_times={total_times}"""'], {}), "(f'now_times={now_times},total_times={total_times}')\n", (22317, 22369), False, 'from loguru import logger\n'), ((45253, 45296), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务按钮异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务按钮异常,不执行')\n", (45267, 45296), False, 'from loguru import logger\n'), ((47632, 47677), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取金融任务标题异常,不执行"""'], {}), "(f'该任务:【{task}】获取金融任务标题异常,不执行')\n", (47646, 47677), False, 'from loguru import logger\n'), ((47913, 47958), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取金融任务标题异常,不执行"""'], {}), "(f'该任务:【{task}】获取金融任务标题异常,不执行')\n", (47927, 47958), False, 'from loguru import logger\n'), ((19293, 19320), 'loguru.logger.debug', 'logger.debug', (['f"""检测页面是否有关键字"""'], {}), "(f'检测页面是否有关键字')\n", (19305, 19320), False, 'from loguru import logger\n'), ((21690, 21721), 'loguru.logger.debug', 'logger.debug', (['f"""超过循环次数,退出该类任务。"""'], {}), "(f'超过循环次数,退出该类任务。')\n", (21702, 21721), False, 'from loguru import logger\n'), ((27680, 27750), 'parse.parse', 'parse.parse', (['"""{temp}({now_times}/{total_times})"""', 'f"""{task_title_text}"""'], {}), "('{temp}({now_times}/{total_times})', f'{task_title_text}')\n", (27691, 27750), False, 'import parse\n'), ((27901, 27965), 'loguru.logger.debug', 'logger.debug', (['f"""now_times={now_times},total_times={total_times}"""'], {}), "(f'now_times={now_times},total_times={total_times}')\n", (27913, 27965), False, 'from loguru import logger\n'), ((32900, 32970), 'parse.parse', 'parse.parse', (['"""{temp}({now_times}/{total_times})"""', 'f"""{task_title_text}"""'], {}), "('{temp}({now_times}/{total_times})', f'{task_title_text}')\n", (32911, 32970), False, 'import parse\n'), ((33109, 33173), 'loguru.logger.debug', 'logger.debug', (['f"""now_times={now_times},total_times={total_times}"""'], {}), "(f'now_times={now_times},total_times={total_times}')\n", (33121, 33173), False, 'from loguru import logger\n'), ((46132, 46166), 'loguru.logger.debug', 'logger.debug', (['f"""不在任务列表页面,再次尝试返回一下"""'], {}), "(f'不在任务列表页面,再次尝试返回一下')\n", (46144, 46166), False, 'from loguru import logger\n'), ((18357, 18409), 'loguru.logger.debug', 'logger.debug', (['f"""开始【{task}】任务now_times={now_times}点击"""'], {}), "(f'开始【{task}】任务now_times={now_times}点击')\n", (18369, 18409), False, 'from loguru import logger\n'), ((19548, 19594), 'loguru.logger.warning', 'logger.warning', (['f"""没找到【当前页点击浏览4个商品领爆竹】关键字,退出任务"""'], {}), "(f'没找到【当前页点击浏览4个商品领爆竹】关键字,退出任务')\n", (19562, 19594), False, 'from loguru import logger\n'), ((20982, 21006), 'loguru.logger.debug', 'logger.debug', (['"""从商品详情页返回"""'], {}), "('从商品详情页返回')\n", (20994, 21006), False, 'from loguru import logger\n'), ((21203, 21225), 'loguru.logger.debug', 'logger.debug', (['"""返回任务列表"""'], {}), "('返回任务列表')\n", (21215, 21225), False, 'from loguru import logger\n'), ((23581, 23608), 'loguru.logger.debug', 'logger.debug', (['f"""检测页面是否有关键字"""'], {}), "(f'检测页面是否有关键字')\n", (23593, 23608), False, 'from loguru import logger\n'), ((26667, 26698), 'loguru.logger.debug', 'logger.debug', (['f"""超过循环次数,退出该类任务。"""'], {}), "(f'超过循环次数,退出该类任务。')\n", (26679, 26698), False, 'from loguru import logger\n'), ((27087, 27115), 'loguru.logger.warning', 'logger.warning', (['f"""浏览并加购任务不做"""'], {}), "(f'浏览并加购任务不做')\n", (27101, 27115), False, 'from loguru import logger\n'), ((35337, 35407), 'parse.parse', 'parse.parse', (['"""{temp}({now_times}/{total_times})"""', 'f"""{task_title_text}"""'], {}), "('{temp}({now_times}/{total_times})', f'{task_title_text}')\n", (35348, 35407), False, 'import parse\n'), ((35546, 35610), 'loguru.logger.debug', 'logger.debug', (['f"""now_times={now_times},total_times={total_times}"""'], {}), "(f'now_times={now_times},total_times={total_times}')\n", (35558, 35610), False, 'from loguru import logger\n'), ((40335, 40369), 'loguru.logger.warning', 'logger.warning', (['f"""其他任务不做:【{task}】"""'], {}), "(f'其他任务不做:【{task}】')\n", (40349, 40369), False, 'from loguru import logger\n'), ((19064, 19107), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务按钮异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务按钮异常,不执行')\n", (19078, 19107), False, 'from loguru import logger\n'), ((19866, 19894), 'loguru.logger.debug', 'logger.debug', (['f"""开始第{i}次浏览商品"""'], {}), "(f'开始第{i}次浏览商品')\n", (19878, 19894), False, 'from loguru import logger\n'), ((22642, 22694), 'loguru.logger.debug', 'logger.debug', (['f"""开始【{task}】任务now_times={now_times}点击"""'], {}), "(f'开始【{task}】任务now_times={now_times}点击')\n", (22654, 22694), False, 'from loguru import logger\n'), ((23832, 23874), 'loguru.logger.warning', 'logger.warning', (['f"""没找到【feedBottom】关键字,退出任务"""'], {}), "(f'没找到【feedBottom】关键字,退出任务')\n", (23846, 23874), False, 'from loguru import logger\n'), ((25295, 25320), 'loguru.logger.debug', 'logger.debug', (['"""从品牌墙详情页返回"""'], {}), "('从品牌墙详情页返回')\n", (25307, 25320), False, 'from loguru import logger\n'), ((25517, 25539), 'loguru.logger.debug', 'logger.debug', (['"""返回任务列表"""'], {}), "('返回任务列表')\n", (25529, 25539), False, 'from loguru import logger\n'), ((27405, 27429), 'loguru.logger.debug', 'logger.debug', (['f"""财富岛任务不做"""'], {}), "(f'财富岛任务不做')\n", (27417, 27429), False, 'from loguru import logger\n'), ((28905, 28980), 'loguru.logger.debug', 'logger.debug', (['f"""任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行"""'], {}), "(f'任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行')\n", (28917, 28980), False, 'from loguru import logger\n'), ((33910, 33985), 'loguru.logger.debug', 'logger.debug', (['f"""任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行"""'], {}), "(f'任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行')\n", (33922, 33985), False, 'from loguru import logger\n'), ((34161, 34189), 'loguru.logger.debug', 'logger.debug', (['f"""返回一下,然后稍微休息"""'], {}), "(f'返回一下,然后稍微休息')\n", (34173, 34189), False, 'from loguru import logger\n'), ((23352, 23395), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务按钮异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务按钮异常,不执行')\n", (23366, 23395), False, 'from loguru import logger\n'), ((24146, 24175), 'loguru.logger.debug', 'logger.debug', (['f"""开始第{i}次浏览品牌墙"""'], {}), "(f'开始第{i}次浏览品牌墙')\n", (24158, 24175), False, 'from loguru import logger\n'), ((26063, 26098), 'loguru.logger.error', 'logger.error', (['f"""重新进入活动,依然没找到任务列表入口"""'], {}), "(f'重新进入活动,依然没找到任务列表入口')\n", (26075, 26098), False, 'from loguru import logger\n'), ((27555, 27580), 'loguru.logger.debug', 'logger.debug', (['f"""去小程序任务不做"""'], {}), "(f'去小程序任务不做')\n", (27567, 27580), False, 'from loguru import logger\n'), ((29238, 29263), 'loguru.logger.debug', 'logger.debug', (['f"""关闭关注主播弹窗"""'], {}), "(f'关闭关注主播弹窗')\n", (29250, 29263), False, 'from loguru import logger\n'), ((31367, 31409), 'loguru.logger.warning', 'logger.warning', (['f"""尝试点击左上角返回按钮,如果无效,需要手工执行"""'], {}), "(f'尝试点击左上角返回按钮,如果无效,需要手工执行')\n", (31381, 31409), False, 'from loguru import logger\n'), ((31672, 31700), 'loguru.logger.debug', 'logger.debug', (['f"""返回一下,然后稍微休息"""'], {}), "(f'返回一下,然后稍微休息')\n", (31684, 31700), False, 'from loguru import logger\n'), ((32329, 32368), 'loguru.logger.debug', 'logger.debug', (['f"""任务标题={task_title_text}"""'], {}), "(f'任务标题={task_title_text}')\n", (32341, 32368), False, 'from loguru import logger\n'), ((34777, 34820), 'loguru.logger.debug', 'logger.debug', (['f"""任务标题={task_title_elm_text}"""'], {}), "(f'任务标题={task_title_elm_text}')\n", (34789, 34820), False, 'from loguru import logger\n'), ((38120, 38195), 'loguru.logger.debug', 'logger.debug', (['f"""任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行"""'], {}), "(f'任务副标题={task_second_title_text},任务标题={task_title_text}:开始执行')\n", (38132, 38195), False, 'from loguru import logger\n'), ((38505, 38533), 'loguru.logger.debug', 'logger.debug', (['f"""返回一下,然后稍微休息"""'], {}), "(f'返回一下,然后稍微休息')\n", (38517, 38533), False, 'from loguru import logger\n'), ((28597, 28640), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务按钮异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务按钮异常,不执行')\n", (28611, 28640), False, 'from loguru import logger\n'), ((29474, 29496), 'loguru.logger.debug', 'logger.debug', (['f"""多返回一次"""'], {}), "(f'多返回一次')\n", (29486, 29496), False, 'from loguru import logger\n'), ((32446, 32489), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务标题异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务标题异常,不执行')\n", (32460, 32489), False, 'from loguru import logger\n'), ((33762, 33805), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务按钮异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务按钮异常,不执行')\n", (33776, 33805), False, 'from loguru import logger\n'), ((34889, 34932), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务标题异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务标题异常,不执行')\n", (34903, 34932), False, 'from loguru import logger\n'), ((39169, 39212), 'loguru.logger.debug', 'logger.debug', (['f"""任务标题={task_title_elm_text}"""'], {}), "(f'任务标题={task_title_elm_text}')\n", (39181, 39212), False, 'from loguru import logger\n'), ((36567, 36596), 'loguru.logger.warning', 'logger.warning', (['f"""没找到【去完成】按钮"""'], {}), "(f'没找到【去完成】按钮')\n", (36581, 36596), False, 'from loguru import logger\n'), ((40185, 40228), 'loguru.logger.warning', 'logger.warning', (['f"""该任务:【{task}】获取任务标题异常,不执行"""'], {}), "(f'该任务:【{task}】获取任务标题异常,不执行')\n", (40199, 40228), False, 'from loguru import logger\n'), ((20832, 20854), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (20852, 20854), False, 'import traceback\n'), ((37628, 37659), 'loguru.logger.warning', 'logger.warning', (['f"""再次没找到【去完成】按钮"""'], {}), "(f'再次没找到【去完成】按钮')\n", (37642, 37659), False, 'from loguru import logger\n'), ((39388, 39419), 'loguru.logger.debug', 'logger.debug', (['f"""查找是否含有【好货特卖】文字"""'], {}), "(f'查找是否含有【好货特卖】文字')\n", (39400, 39419), False, 'from loguru import logger\n'), ((25151, 25173), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (25171, 25173), False, 'import traceback\n'), ((39733, 39767), 'loguru.logger.debug', 'logger.debug', (['f"""从小程序跳转回来,还需要再返回一次"""'], {}), "(f'从小程序跳转回来,还需要再返回一次')\n", (39745, 39767), False, 'from loguru import logger\n'), ((39927, 39955), 'loguru.logger.warning', 'logger.warning', (['f"""没找到任务标题信息"""'], {}), "(f'没找到任务标题信息')\n", (39941, 39955), False, 'from loguru import logger\n'), ((36785, 36807), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (36805, 36807), False, 'import traceback\n'), ((38011, 38033), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (38031, 38033), False, 'import traceback\n'), ((30858, 30897), 'loguru.logger.warning', 'logger.warning', (['f"""发现【确认授权并加入店铺会员】,退出循环"""'], {}), "(f'发现【确认授权并加入店铺会员】,退出循环')\n", (30872, 30897), False, 'from loguru import logger\n'), ((31144, 31169), 'loguru.logger.debug', 'logger.debug', (['"""没有触犯规则,继续"""'], {}), "('没有触犯规则,继续')\n", (31156, 31169), False, 'from loguru import logger\n')] |
import salabim as sim
GAS_STATION_SIZE = 200. # liters
THRESHOLD = 25. # Threshold for calling the tank truck (in %)
FUEL_TANK_SIZE = 50. # liters
# Min/max levels of fuel tanks (in liters)
FUEL_TANK_LEVEL = sim.Uniform(5, 25)
REFUELING_SPEED = 2. # liters / second
TANK_TRUCK_TIME = 300. # Seconds it takes the tank truck to arrive
T_INTER = sim.Uniform(10, 100) # Create a car every [min, max] seconds
SIM_TIME = 200000 # Simulation time in seconds
class Car(sim.Component):
'''
A car arrives at the gas station for refueling.
It requests one of the gas station's fuel pumps and tries to get the
desired amount of gas from it. If the stations reservoir is
depleted, the car has to wait for the tank truck to arrive.
'''
def process(self):
fuel_tank_level = int(FUEL_TANK_LEVEL.sample())
yield self.request(gas_station)
liters_required = FUEL_TANK_SIZE - fuel_tank_level
if (fuel_pump.available_quantity() - liters_required) / fuel_pump.capacity() * 100 < THRESHOLD:
if tank_truck.ispassive():
tank_truck.activate()
yield self.request((fuel_pump, liters_required))
yield self.hold(liters_required / REFUELING_SPEED)
class TankTruck(sim.Component):
'''
Periodically check the level of the *fuel_pump* and call the tank
truck if the level falls below a threshold.
'''
def process(self):
while True:
yield self.passivate()
yield self.hold(TANK_TRUCK_TIME)
fuel_pump.release()
class CarGenerator(sim.Component):
'''
Generate new cars that arrive at the gas station.
'''
def process(self):
while True:
yield self.hold(T_INTER.sample())
Car()
# Setup and start the simulation
env = sim.Environment(trace=False)
print('Gas Station refuelling')
# Create environment and start processes
gas_station = sim.Resource('gas_station', 2)
fuel_pump = sim.Resource(
'fuel_pump', capacity=GAS_STATION_SIZE, anonymous=True)
tank_truck = TankTruck()
CarGenerator()
env.run(SIM_TIME)
fuel_pump.capacity.print_histogram()
fuel_pump.claimed_quantity.print_histogram()
fuel_pump.available_quantity.print_histogram()
gas_station.requesters().length.print_histogram()
gas_station.requesters().length_of_stay.print_histogram(30, 0, 10)
| [
"salabim.Resource",
"salabim.Environment",
"salabim.Uniform"
] | [((232, 250), 'salabim.Uniform', 'sim.Uniform', (['(5)', '(25)'], {}), '(5, 25)\n', (243, 250), True, 'import salabim as sim\n'), ((379, 399), 'salabim.Uniform', 'sim.Uniform', (['(10)', '(100)'], {}), '(10, 100)\n', (390, 399), True, 'import salabim as sim\n'), ((1853, 1881), 'salabim.Environment', 'sim.Environment', ([], {'trace': '(False)'}), '(trace=False)\n', (1868, 1881), True, 'import salabim as sim\n'), ((1970, 2000), 'salabim.Resource', 'sim.Resource', (['"""gas_station"""', '(2)'], {}), "('gas_station', 2)\n", (1982, 2000), True, 'import salabim as sim\n'), ((2013, 2081), 'salabim.Resource', 'sim.Resource', (['"""fuel_pump"""'], {'capacity': 'GAS_STATION_SIZE', 'anonymous': '(True)'}), "('fuel_pump', capacity=GAS_STATION_SIZE, anonymous=True)\n", (2025, 2081), True, 'import salabim as sim\n')] |
import os
import requests
import time
import pandas as pd
import config
from flask import request
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
import dash_table
from dash.dependencies import Input, Output, State
external_stylesheets = [
"https://use.fontawesome.com/releases/v5.0.7/css/all.css",
'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css',
'https://fonts.googleapis.com/css?family=Roboto&display=swap'
]
external_script = "https://raw.githubusercontent.com/MarwanDebbiche/post-tuto-deployment/master/src/dash/assets/gtag.js"
app = dash.Dash(
__name__,
external_stylesheets=external_stylesheets,
meta_tags=[
{"name": "viewport", "content": "width=device-width, initial-scale=1"}
],
suppress_callback_exceptions=True
)
app.scripts.append_script({
"external_url": external_script
})
app.title = 'Reviews powered by AI'
companies = pd.read_csv('./csv/companies_forbes.csv')
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='page-content')
])
home_layout = html.Div(
[
html.Div(
[
html.A(
html.Img(
id='company_logo',
style={
'height': '100px',
'padding': '5px'
}
),
id="company_link",
target="_blank"
)
],
style={
'height': '100px',
'backgroundColor': 'white',
'borderStyle': 'solid',
'borderRadius': '100px',
'borderWidth': 'thin'
}
),
html.H1(
[
"What do you think of ",
html.Span(
id='company_name'
),
" ?"
],
className="h3 mb-3 font-weight-normal",
style={
'marginTop': '5px'
}
),
html.Div(
[
dcc.Textarea(
className="form-control z-depth-1",
id="review",
rows="8",
placeholder="Write something here..."
)
],
className="form-group shadow-textarea"
),
html.H5(
'Sentiment analysis 🤖'
),
dbc.Progress(
children=html.Span(
id='proba',
style={
'color': 'black',
'fontWeight': 'bold'
}
),
id="progress",
striped=False,
animated=False,
style={
'marginBottom': '10px'
}
),
html.H5(
'Propose a rating 😁📢'
),
html.Div(
[
dcc.Slider(
id='rating',
max=5,
min=1,
step=1,
marks={i: f'{i}' for i in range(1, 6)}
),
],
style={'marginBottom': '30px'}
),
html.Button(
[
html.Span(
"Submit",
style={
"marginRight": "10px"
}
),
html.I(
className="fa fa-paper-plane m-l-7"
)
],
className="btn btn-lg btn-primary btn-block",
role="submit",
id="submit_button",
n_clicks_timestamp=0
),
html.Button(
[
html.Span(
"Review another brand",
style={
"marginRight": "10px"
}
),
html.I(
className="fas fa-sync-alt"
)
],
className="btn btn-lg btn-secondary btn-block",
id='switch_button',
n_clicks_timestamp=0
),
html.P(
dcc.Link("Go to Admin 🔑", id="admin-link", href="/admin"),
className="mt-2"
),
html.P(
[
html.A("<NAME>", href="https://www.linkedin.com/in/olaf-nowicki/", target="_blank"),
" - 2021"
],
className="mt-3 mb-2 text-muted"
),
],
className="form-review",
)
admin_layout = html.Div(
[
html.H1("Admin Page 🔑"),
html.Div(id="admin-page-content"),
html.P(
dcc.Link("Go to Home 🏡", href="/"),
style={"marginTop": "20px"}
)
]
)
@app.callback(
[
Output('company_logo', 'src'),
Output('company_name', 'children'),
Output('review', 'value'),
Output('company_link', 'href')
],
[
Input('submit_button', 'n_clicks_timestamp'),
Input('switch_button', 'n_clicks_timestamp')
],
[
State('review', 'value'),
State('progress', 'value'),
State('rating', 'value'),
State('company_name', 'children')
]
)
def change_brand(submit_click_ts, another_brand_click_ts, review_text, score, rating, brand_name):
if submit_click_ts > another_brand_click_ts:
sentiment_score = float(score) / 100
ip_address = request.remote_addr
user_agent = request.headers.get('User-Agent')
response = requests.post(
f"{config.API_URL}/review",
data={
'review': review_text,
'rating': rating,
'suggested_rating': min(int(sentiment_score * 5 + 1), 5),
'sentiment_score': sentiment_score,
'brand': brand_name,
'user_agent': user_agent,
'ip_address': ip_address
}
)
if response.ok:
print("Review Saved")
else:
print("Error Saving Review")
random_company = companies.sample(1).to_dict(orient="records")[0]
company_logo_url = random_company['company_logo']
if not company_logo_url.startswith('http'):
company_logo_url = 'https://' + company_logo_url
company_name = random_company['company_name']
company_website = random_company['company_website']
return company_logo_url, company_name, '', company_website
@app.callback(
[
Output('proba', 'children'),
Output('progress', 'value'),
Output('progress', 'color'),
Output('rating', 'value'),
Output('submit_button', 'disabled')
],
[Input('review', 'value')]
)
def update_proba(review):
if review is not None and review.strip() != '':
response = requests.post(
f"{config.API_URL}/predict", data={'review': review})
proba = response.json()
proba = round(proba * 100, 2)
suggested_rating = min(int((proba / 100) * 5 + 1), 5)
text_proba = f"{proba}%"
if proba >= 67:
return text_proba, proba, 'success', suggested_rating, False
elif 33 < proba < 67:
return text_proba, proba, 'warning', suggested_rating, False
elif proba <= 33:
return text_proba, proba, 'danger', suggested_rating, False
else:
return None, 0, None, 0, True
# Load review table
@app.callback(
Output('admin-page-content', 'children'),
[Input('url', 'pathname')]
)
def load_review_table(pathname):
if pathname != "/admin":
return None
response = requests.get(f"{config.API_URL}/reviews")
reviews = pd.DataFrame(response.json())
table = dbc.Table.from_dataframe(reviews,
striped=True,
bordered=True,
hover=True,
responsive=True,
header=["id", "brand", "created_date", "review",
"rating", "suggested_rating", "sentiment_score"],
columns=["id", "brand", "created_date", "review",
"rating", "suggested_rating", "sentiment_score"]
)
return table
# Update page layout
@app.callback(
Output('page-content', 'children'),
[Input('url', 'pathname')]
)
def display_page(pathname):
if pathname == '/':
return home_layout
if pathname == "/admin":
return admin_layout
else:
return [
html.Div(
[
html.Img(
src="./assets/404.png",
style={
"width": "50%"
}
),
],
className="form-review"
),
dcc.Link("Go to Home", href="/"),
]
if __name__ == '__main__':
app.run_server(debug=config.DEBUG, host=config.HOST)
| [
"requests.post",
"pandas.read_csv",
"dash_core_components.Location",
"dash_core_components.Textarea",
"dash.dependencies.Input",
"flask.request.headers.get",
"dash_html_components.Div",
"dash.Dash",
"dash_html_components.I",
"dash_core_components.Link",
"dash.dependencies.Output",
"dash_html_c... | [((656, 846), 'dash.Dash', 'dash.Dash', (['__name__'], {'external_stylesheets': 'external_stylesheets', 'meta_tags': "[{'name': 'viewport', 'content': 'width=device-width, initial-scale=1'}]", 'suppress_callback_exceptions': '(True)'}), "(__name__, external_stylesheets=external_stylesheets, meta_tags=[{\n 'name': 'viewport', 'content': 'width=device-width, initial-scale=1'}],\n suppress_callback_exceptions=True)\n", (665, 846), False, 'import dash\n'), ((989, 1030), 'pandas.read_csv', 'pd.read_csv', (['"""./csv/companies_forbes.csv"""'], {}), "('./csv/companies_forbes.csv')\n", (1000, 1030), True, 'import pandas as pd\n'), ((7746, 7787), 'requests.get', 'requests.get', (['f"""{config.API_URL}/reviews"""'], {}), "(f'{config.API_URL}/reviews')\n", (7758, 7787), False, 'import requests\n'), ((7846, 8152), 'dash_bootstrap_components.Table.from_dataframe', 'dbc.Table.from_dataframe', (['reviews'], {'striped': '(True)', 'bordered': '(True)', 'hover': '(True)', 'responsive': '(True)', 'header': "['id', 'brand', 'created_date', 'review', 'rating', 'suggested_rating',\n 'sentiment_score']", 'columns': "['id', 'brand', 'created_date', 'review', 'rating', 'suggested_rating',\n 'sentiment_score']"}), "(reviews, striped=True, bordered=True, hover=True,\n responsive=True, header=['id', 'brand', 'created_date', 'review',\n 'rating', 'suggested_rating', 'sentiment_score'], columns=['id',\n 'brand', 'created_date', 'review', 'rating', 'suggested_rating',\n 'sentiment_score'])\n", (7870, 8152), True, 'import dash_bootstrap_components as dbc\n'), ((7573, 7613), 'dash.dependencies.Output', 'Output', (['"""admin-page-content"""', '"""children"""'], {}), "('admin-page-content', 'children')\n", (7579, 7613), False, 'from dash.dependencies import Input, Output, State\n'), ((8549, 8583), 'dash.dependencies.Output', 'Output', (['"""page-content"""', '"""children"""'], {}), "('page-content', 'children')\n", (8555, 8583), False, 'from dash.dependencies import Input, Output, State\n'), ((1060, 1097), 'dash_core_components.Location', 'dcc.Location', ([], {'id': '"""url"""', 'refresh': '(False)'}), "(id='url', refresh=False)\n", (1072, 1097), True, 'import dash_core_components as dcc\n'), ((1103, 1130), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""page-content"""'}), "(id='page-content')\n", (1111, 1130), True, 'import dash_html_components as html\n'), ((2487, 2518), 'dash_html_components.H5', 'html.H5', (['"""Sentiment analysis 🤖"""'], {}), "('Sentiment analysis 🤖')\n", (2494, 2518), True, 'import dash_html_components as html\n'), ((2936, 2966), 'dash_html_components.H5', 'html.H5', (['"""Propose a rating 😁📢"""'], {}), "('Propose a rating 😁📢')\n", (2943, 2966), True, 'import dash_html_components as html\n'), ((4691, 4714), 'dash_html_components.H1', 'html.H1', (['"""Admin Page 🔑"""'], {}), "('Admin Page 🔑')\n", (4698, 4714), True, 'import dash_html_components as html\n'), ((4724, 4757), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""admin-page-content"""'}), "(id='admin-page-content')\n", (4732, 4757), True, 'import dash_html_components as html\n'), ((5603, 5636), 'flask.request.headers.get', 'request.headers.get', (['"""User-Agent"""'], {}), "('User-Agent')\n", (5622, 5636), False, 'from flask import request\n'), ((4912, 4941), 'dash.dependencies.Output', 'Output', (['"""company_logo"""', '"""src"""'], {}), "('company_logo', 'src')\n", (4918, 4941), False, 'from dash.dependencies import Input, Output, State\n'), ((4951, 4985), 'dash.dependencies.Output', 'Output', (['"""company_name"""', '"""children"""'], {}), "('company_name', 'children')\n", (4957, 4985), False, 'from dash.dependencies import Input, Output, State\n'), ((4995, 5020), 'dash.dependencies.Output', 'Output', (['"""review"""', '"""value"""'], {}), "('review', 'value')\n", (5001, 5020), False, 'from dash.dependencies import Input, Output, State\n'), ((5030, 5060), 'dash.dependencies.Output', 'Output', (['"""company_link"""', '"""href"""'], {}), "('company_link', 'href')\n", (5036, 5060), False, 'from dash.dependencies import Input, Output, State\n'), ((5082, 5126), 'dash.dependencies.Input', 'Input', (['"""submit_button"""', '"""n_clicks_timestamp"""'], {}), "('submit_button', 'n_clicks_timestamp')\n", (5087, 5126), False, 'from dash.dependencies import Input, Output, State\n'), ((5136, 5180), 'dash.dependencies.Input', 'Input', (['"""switch_button"""', '"""n_clicks_timestamp"""'], {}), "('switch_button', 'n_clicks_timestamp')\n", (5141, 5180), False, 'from dash.dependencies import Input, Output, State\n'), ((5202, 5226), 'dash.dependencies.State', 'State', (['"""review"""', '"""value"""'], {}), "('review', 'value')\n", (5207, 5226), False, 'from dash.dependencies import Input, Output, State\n'), ((5236, 5262), 'dash.dependencies.State', 'State', (['"""progress"""', '"""value"""'], {}), "('progress', 'value')\n", (5241, 5262), False, 'from dash.dependencies import Input, Output, State\n'), ((5272, 5296), 'dash.dependencies.State', 'State', (['"""rating"""', '"""value"""'], {}), "('rating', 'value')\n", (5277, 5296), False, 'from dash.dependencies import Input, Output, State\n'), ((5306, 5339), 'dash.dependencies.State', 'State', (['"""company_name"""', '"""children"""'], {}), "('company_name', 'children')\n", (5311, 5339), False, 'from dash.dependencies import Input, Output, State\n'), ((6939, 7006), 'requests.post', 'requests.post', (['f"""{config.API_URL}/predict"""'], {'data': "{'review': review}"}), "(f'{config.API_URL}/predict', data={'review': review})\n", (6952, 7006), False, 'import requests\n'), ((6620, 6647), 'dash.dependencies.Output', 'Output', (['"""proba"""', '"""children"""'], {}), "('proba', 'children')\n", (6626, 6647), False, 'from dash.dependencies import Input, Output, State\n'), ((6657, 6684), 'dash.dependencies.Output', 'Output', (['"""progress"""', '"""value"""'], {}), "('progress', 'value')\n", (6663, 6684), False, 'from dash.dependencies import Input, Output, State\n'), ((6694, 6721), 'dash.dependencies.Output', 'Output', (['"""progress"""', '"""color"""'], {}), "('progress', 'color')\n", (6700, 6721), False, 'from dash.dependencies import Input, Output, State\n'), ((6731, 6756), 'dash.dependencies.Output', 'Output', (['"""rating"""', '"""value"""'], {}), "('rating', 'value')\n", (6737, 6756), False, 'from dash.dependencies import Input, Output, State\n'), ((6766, 6801), 'dash.dependencies.Output', 'Output', (['"""submit_button"""', '"""disabled"""'], {}), "('submit_button', 'disabled')\n", (6772, 6801), False, 'from dash.dependencies import Input, Output, State\n'), ((6814, 6838), 'dash.dependencies.Input', 'Input', (['"""review"""', '"""value"""'], {}), "('review', 'value')\n", (6819, 6838), False, 'from dash.dependencies import Input, Output, State\n'), ((7620, 7644), 'dash.dependencies.Input', 'Input', (['"""url"""', '"""pathname"""'], {}), "('url', 'pathname')\n", (7625, 7644), False, 'from dash.dependencies import Input, Output, State\n'), ((8590, 8614), 'dash.dependencies.Input', 'Input', (['"""url"""', '"""pathname"""'], {}), "('url', 'pathname')\n", (8595, 8614), False, 'from dash.dependencies import Input, Output, State\n'), ((4285, 4342), 'dash_core_components.Link', 'dcc.Link', (['"""Go to Admin 🔑"""'], {'id': '"""admin-link"""', 'href': '"""/admin"""'}), "('Go to Admin 🔑', id='admin-link', href='/admin')\n", (4293, 4342), True, 'import dash_core_components as dcc\n'), ((4787, 4821), 'dash_core_components.Link', 'dcc.Link', (['"""Go to Home 🏡"""'], {'href': '"""/"""'}), "('Go to Home 🏡', href='/')\n", (4795, 4821), True, 'import dash_core_components as dcc\n'), ((9109, 9141), 'dash_core_components.Link', 'dcc.Link', (['"""Go to Home"""'], {'href': '"""/"""'}), "('Go to Home', href='/')\n", (9117, 9141), True, 'import dash_core_components as dcc\n'), ((1907, 1935), 'dash_html_components.Span', 'html.Span', ([], {'id': '"""company_name"""'}), "(id='company_name')\n", (1916, 1935), True, 'import dash_html_components as html\n'), ((2192, 2306), 'dash_core_components.Textarea', 'dcc.Textarea', ([], {'className': '"""form-control z-depth-1"""', 'id': '"""review"""', 'rows': '"""8"""', 'placeholder': '"""Write something here..."""'}), "(className='form-control z-depth-1', id='review', rows='8',\n placeholder='Write something here...')\n", (2204, 2306), True, 'import dash_core_components as dcc\n'), ((2586, 2655), 'dash_html_components.Span', 'html.Span', ([], {'id': '"""proba"""', 'style': "{'color': 'black', 'fontWeight': 'bold'}"}), "(id='proba', style={'color': 'black', 'fontWeight': 'bold'})\n", (2595, 2655), True, 'import dash_html_components as html\n'), ((3365, 3415), 'dash_html_components.Span', 'html.Span', (['"""Submit"""'], {'style': "{'marginRight': '10px'}"}), "('Submit', style={'marginRight': '10px'})\n", (3374, 3415), True, 'import dash_html_components as html\n'), ((3537, 3580), 'dash_html_components.I', 'html.I', ([], {'className': '"""fa fa-paper-plane m-l-7"""'}), "(className='fa fa-paper-plane m-l-7')\n", (3543, 3580), True, 'import dash_html_components as html\n'), ((3846, 3910), 'dash_html_components.Span', 'html.Span', (['"""Review another brand"""'], {'style': "{'marginRight': '10px'}"}), "('Review another brand', style={'marginRight': '10px'})\n", (3855, 3910), True, 'import dash_html_components as html\n'), ((4032, 4067), 'dash_html_components.I', 'html.I', ([], {'className': '"""fas fa-sync-alt"""'}), "(className='fas fa-sync-alt')\n", (4038, 4067), True, 'import dash_html_components as html\n'), ((4431, 4519), 'dash_html_components.A', 'html.A', (['"""<NAME>"""'], {'href': '"""https://www.linkedin.com/in/olaf-nowicki/"""', 'target': '"""_blank"""'}), "('<NAME>', href='https://www.linkedin.com/in/olaf-nowicki/', target=\n '_blank')\n", (4437, 4519), True, 'import dash_html_components as html\n'), ((1241, 1313), 'dash_html_components.Img', 'html.Img', ([], {'id': '"""company_logo"""', 'style': "{'height': '100px', 'padding': '5px'}"}), "(id='company_logo', style={'height': '100px', 'padding': '5px'})\n", (1249, 1313), True, 'import dash_html_components as html\n'), ((8841, 8897), 'dash_html_components.Img', 'html.Img', ([], {'src': '"""./assets/404.png"""', 'style': "{'width': '50%'}"}), "(src='./assets/404.png', style={'width': '50%'})\n", (8849, 8897), True, 'import dash_html_components as html\n')] |
#Import needed libraries
from litemapy import Schematic, Region, BlockState
from PIL import Image
import json
#Get the size of the image
img = Image.open(input("Path to image: "))
w,h = img.size
#Generate the shematic
schem = Schematic(w,1,h, name="WFCconvert litematic", main_region_name="main")
reg = schem.regions["main"]
#Set the block replacements
repl = json.loads(open("colorr.json").read())
#Fill the schematic
for x in range(1,w):
for y in range(1,h):
for obj in repl:
color = tuple(repl[obj]["color"]) #Get a tuple of the current color
if img.getpixel((x,y)) == (255, 255, 255, 255): #Detect white to replace with air
reg.setblock(x,0,y,BlockState("minecraft:air")) #Set the block to air
break
elif img.getpixel((x,y)) == color: #Check if the color is in this object
reg.setblock(x,0,y,BlockState(repl[obj]["replacement"])) #Set the block to the replacement
break
#Save the schematic
schem.save("output.litematic") | [
"litemapy.BlockState",
"litemapy.Schematic"
] | [((238, 310), 'litemapy.Schematic', 'Schematic', (['w', '(1)', 'h'], {'name': '"""WFCconvert litematic"""', 'main_region_name': '"""main"""'}), "(w, 1, h, name='WFCconvert litematic', main_region_name='main')\n", (247, 310), False, 'from litemapy import Schematic, Region, BlockState\n'), ((686, 713), 'litemapy.BlockState', 'BlockState', (['"""minecraft:air"""'], {}), "('minecraft:air')\n", (696, 713), False, 'from litemapy import Schematic, Region, BlockState\n'), ((849, 885), 'litemapy.BlockState', 'BlockState', (["repl[obj]['replacement']"], {}), "(repl[obj]['replacement'])\n", (859, 885), False, 'from litemapy import Schematic, Region, BlockState\n')] |
from django.conf.urls import include, url
from rest_framework import routers
from api import views
from django.urls import path
route = routers.DefaultRouter()
route.register(r'user', views.UserViewSet)
route.register(r'store', views.StoreViewSet)
route.register(r'itemCategory', views.ItemCategoryViewSet)
route.register(r'itemSubCategory', views.ItemSubCategoryViewSet)
route.register(r'item', views.ItemViewSet)
route.register(r'shoppingCart', views.ShppingCartViewSet)
route.register(r'trade', views.TradeViewSet)
route.register(r'group', views.GroupViewSet)
route.register(r'storeFollow', views.StoreFollowViewSet)
route.register(r'itemFollow', views.ItemFollowViewSet)
route.register(r'groupFollow', views.GroupFollowViewSet)
route.register(r'banner', views.BannerViewSet)
route.register(r'systemMessage', views.SystemMessageViewSet)
route.register(r'chatMessage', views.ChatMessageViewSet)
route.register(r'coupon', views.CouponViewSet)
route.register(r'dailyOffItem', views.DailyOffItemViewSet)
route.register(r'itemDetailImage', views.ItemDetailImageViewSet)
route.register(r'itemBannerImage', views.ItemBannerImageViewSet)
route.register(r'evaluateImage', views.EvaluateImageViewSet)
route.register(r'address', views.AddressViewSet)
route.register(r'brand', views.BrandViewSet)
route.register(r'collection', views.CollectionViewSet)
route.register(r'browseRecord', views.BrowseRecordViewSet)
route.register(r'searchRecord', views.SearchRecordViewSet)
route.register(r'evaluate', views.EvaluateViewSet)
urlpatterns = [
url('api/', include(route.urls)),
path('api/get_user_cart_item/<int:pk>', views.get_user_cart_item),
path('api/get_user_store_follow/<int:pk>', views.get_user_store_follow),
path('api/get_user_item_follow/<int:pk>', views.get_user_item_follow),
path('api/item_detail_image/<int:pk>', views.item_detail_image),
path('api/item_banner_image/<int:pk>', views.item_banner_image),
path('api/get_user_coupon/<int:pk>', views.get_user_coupon),
path('api/delete_user_collection/', views.delete_user_collection),
path('api/get_user_collection/<int:pk>', views.get_user_collection),
path('api/browse_item/', views.browse_item),
path('api/get_store_evaluate/<int:pk>', views.get_store_evaluate),
path('api/search_content/<int:pk>/', views.search_content),
path('api/whether_user_collect_item/', views.whether_user_collect_item),
path('api/evaluate_image/<int:pk>', views.evaluate_image),
path('api/get_item_evaluate_amount/<int:pk>', views.get_item_evaluate_amount),
path('api/get_item_evaluate_info/<int:pk>', views.get_item_evaluate_info),
path('api/whether_user_buy_item_in_store/', views.whether_user_buy_item_in_store),
path('api/get_item_collection_amount/<int:pk>', views.get_item_collection_amount),
path('api/get_recommend_item/<int:pk>', views.get_recommend_item),
path('api/get_evaluate_type/', views.get_evaluate_type),
path('api/get_wait_receive/', views.get_wait_receive),
path('api/get_wait_evaluate/', views.get_wait_evaluate),
path('api/get_complete_trade/', views.get_complete_trade),
path('api/buy_now/', views.buy_now),
path('api/add_into_cart/', views.add_into_cart),
path('api/buy_in_cart/', views.buy_in_cart),
path('api/confirm_receive/<int:pk>', views.confirm_receive),
path('api/get_history_item/<int:pk>', views.get_history_item),
path('api/get_user_store_info/<int:pk>', views.get_user_store_info),
path('api/update_user_address/', views.update_user_address),
path('api/upload_user_head_image/<int:pk>', views.upload_user_head_image),
path('api/upload_item_preview_image/<int:pk>', views.upload_item_preview_image),
] | [
"django.conf.urls.include",
"django.urls.path",
"rest_framework.routers.DefaultRouter"
] | [((137, 160), 'rest_framework.routers.DefaultRouter', 'routers.DefaultRouter', ([], {}), '()\n', (158, 160), False, 'from rest_framework import routers\n'), ((1573, 1638), 'django.urls.path', 'path', (['"""api/get_user_cart_item/<int:pk>"""', 'views.get_user_cart_item'], {}), "('api/get_user_cart_item/<int:pk>', views.get_user_cart_item)\n", (1577, 1638), False, 'from django.urls import path\n'), ((1644, 1715), 'django.urls.path', 'path', (['"""api/get_user_store_follow/<int:pk>"""', 'views.get_user_store_follow'], {}), "('api/get_user_store_follow/<int:pk>', views.get_user_store_follow)\n", (1648, 1715), False, 'from django.urls import path\n'), ((1721, 1790), 'django.urls.path', 'path', (['"""api/get_user_item_follow/<int:pk>"""', 'views.get_user_item_follow'], {}), "('api/get_user_item_follow/<int:pk>', views.get_user_item_follow)\n", (1725, 1790), False, 'from django.urls import path\n'), ((1796, 1859), 'django.urls.path', 'path', (['"""api/item_detail_image/<int:pk>"""', 'views.item_detail_image'], {}), "('api/item_detail_image/<int:pk>', views.item_detail_image)\n", (1800, 1859), False, 'from django.urls import path\n'), ((1865, 1928), 'django.urls.path', 'path', (['"""api/item_banner_image/<int:pk>"""', 'views.item_banner_image'], {}), "('api/item_banner_image/<int:pk>', views.item_banner_image)\n", (1869, 1928), False, 'from django.urls import path\n'), ((1934, 1993), 'django.urls.path', 'path', (['"""api/get_user_coupon/<int:pk>"""', 'views.get_user_coupon'], {}), "('api/get_user_coupon/<int:pk>', views.get_user_coupon)\n", (1938, 1993), False, 'from django.urls import path\n'), ((1999, 2064), 'django.urls.path', 'path', (['"""api/delete_user_collection/"""', 'views.delete_user_collection'], {}), "('api/delete_user_collection/', views.delete_user_collection)\n", (2003, 2064), False, 'from django.urls import path\n'), ((2070, 2137), 'django.urls.path', 'path', (['"""api/get_user_collection/<int:pk>"""', 'views.get_user_collection'], {}), "('api/get_user_collection/<int:pk>', views.get_user_collection)\n", (2074, 2137), False, 'from django.urls import path\n'), ((2143, 2186), 'django.urls.path', 'path', (['"""api/browse_item/"""', 'views.browse_item'], {}), "('api/browse_item/', views.browse_item)\n", (2147, 2186), False, 'from django.urls import path\n'), ((2192, 2257), 'django.urls.path', 'path', (['"""api/get_store_evaluate/<int:pk>"""', 'views.get_store_evaluate'], {}), "('api/get_store_evaluate/<int:pk>', views.get_store_evaluate)\n", (2196, 2257), False, 'from django.urls import path\n'), ((2263, 2321), 'django.urls.path', 'path', (['"""api/search_content/<int:pk>/"""', 'views.search_content'], {}), "('api/search_content/<int:pk>/', views.search_content)\n", (2267, 2321), False, 'from django.urls import path\n'), ((2327, 2398), 'django.urls.path', 'path', (['"""api/whether_user_collect_item/"""', 'views.whether_user_collect_item'], {}), "('api/whether_user_collect_item/', views.whether_user_collect_item)\n", (2331, 2398), False, 'from django.urls import path\n'), ((2404, 2461), 'django.urls.path', 'path', (['"""api/evaluate_image/<int:pk>"""', 'views.evaluate_image'], {}), "('api/evaluate_image/<int:pk>', views.evaluate_image)\n", (2408, 2461), False, 'from django.urls import path\n'), ((2467, 2544), 'django.urls.path', 'path', (['"""api/get_item_evaluate_amount/<int:pk>"""', 'views.get_item_evaluate_amount'], {}), "('api/get_item_evaluate_amount/<int:pk>', views.get_item_evaluate_amount)\n", (2471, 2544), False, 'from django.urls import path\n'), ((2550, 2623), 'django.urls.path', 'path', (['"""api/get_item_evaluate_info/<int:pk>"""', 'views.get_item_evaluate_info'], {}), "('api/get_item_evaluate_info/<int:pk>', views.get_item_evaluate_info)\n", (2554, 2623), False, 'from django.urls import path\n'), ((2629, 2715), 'django.urls.path', 'path', (['"""api/whether_user_buy_item_in_store/"""', 'views.whether_user_buy_item_in_store'], {}), "('api/whether_user_buy_item_in_store/', views.\n whether_user_buy_item_in_store)\n", (2633, 2715), False, 'from django.urls import path\n'), ((2716, 2802), 'django.urls.path', 'path', (['"""api/get_item_collection_amount/<int:pk>"""', 'views.get_item_collection_amount'], {}), "('api/get_item_collection_amount/<int:pk>', views.\n get_item_collection_amount)\n", (2720, 2802), False, 'from django.urls import path\n'), ((2803, 2868), 'django.urls.path', 'path', (['"""api/get_recommend_item/<int:pk>"""', 'views.get_recommend_item'], {}), "('api/get_recommend_item/<int:pk>', views.get_recommend_item)\n", (2807, 2868), False, 'from django.urls import path\n'), ((2874, 2929), 'django.urls.path', 'path', (['"""api/get_evaluate_type/"""', 'views.get_evaluate_type'], {}), "('api/get_evaluate_type/', views.get_evaluate_type)\n", (2878, 2929), False, 'from django.urls import path\n'), ((2935, 2988), 'django.urls.path', 'path', (['"""api/get_wait_receive/"""', 'views.get_wait_receive'], {}), "('api/get_wait_receive/', views.get_wait_receive)\n", (2939, 2988), False, 'from django.urls import path\n'), ((2994, 3049), 'django.urls.path', 'path', (['"""api/get_wait_evaluate/"""', 'views.get_wait_evaluate'], {}), "('api/get_wait_evaluate/', views.get_wait_evaluate)\n", (2998, 3049), False, 'from django.urls import path\n'), ((3055, 3112), 'django.urls.path', 'path', (['"""api/get_complete_trade/"""', 'views.get_complete_trade'], {}), "('api/get_complete_trade/', views.get_complete_trade)\n", (3059, 3112), False, 'from django.urls import path\n'), ((3118, 3153), 'django.urls.path', 'path', (['"""api/buy_now/"""', 'views.buy_now'], {}), "('api/buy_now/', views.buy_now)\n", (3122, 3153), False, 'from django.urls import path\n'), ((3159, 3206), 'django.urls.path', 'path', (['"""api/add_into_cart/"""', 'views.add_into_cart'], {}), "('api/add_into_cart/', views.add_into_cart)\n", (3163, 3206), False, 'from django.urls import path\n'), ((3212, 3255), 'django.urls.path', 'path', (['"""api/buy_in_cart/"""', 'views.buy_in_cart'], {}), "('api/buy_in_cart/', views.buy_in_cart)\n", (3216, 3255), False, 'from django.urls import path\n'), ((3261, 3320), 'django.urls.path', 'path', (['"""api/confirm_receive/<int:pk>"""', 'views.confirm_receive'], {}), "('api/confirm_receive/<int:pk>', views.confirm_receive)\n", (3265, 3320), False, 'from django.urls import path\n'), ((3326, 3387), 'django.urls.path', 'path', (['"""api/get_history_item/<int:pk>"""', 'views.get_history_item'], {}), "('api/get_history_item/<int:pk>', views.get_history_item)\n", (3330, 3387), False, 'from django.urls import path\n'), ((3393, 3460), 'django.urls.path', 'path', (['"""api/get_user_store_info/<int:pk>"""', 'views.get_user_store_info'], {}), "('api/get_user_store_info/<int:pk>', views.get_user_store_info)\n", (3397, 3460), False, 'from django.urls import path\n'), ((3466, 3525), 'django.urls.path', 'path', (['"""api/update_user_address/"""', 'views.update_user_address'], {}), "('api/update_user_address/', views.update_user_address)\n", (3470, 3525), False, 'from django.urls import path\n'), ((3531, 3604), 'django.urls.path', 'path', (['"""api/upload_user_head_image/<int:pk>"""', 'views.upload_user_head_image'], {}), "('api/upload_user_head_image/<int:pk>', views.upload_user_head_image)\n", (3535, 3604), False, 'from django.urls import path\n'), ((3610, 3689), 'django.urls.path', 'path', (['"""api/upload_item_preview_image/<int:pk>"""', 'views.upload_item_preview_image'], {}), "('api/upload_item_preview_image/<int:pk>', views.upload_item_preview_image)\n", (3614, 3689), False, 'from django.urls import path\n'), ((1547, 1566), 'django.conf.urls.include', 'include', (['route.urls'], {}), '(route.urls)\n', (1554, 1566), False, 'from django.conf.urls import include, url\n')] |
# Copyright 2016 Google Inc. 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.
"""The main command group for the gcloud debug command group."""
from googlecloudsdk.api_lib.debug import debug
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
from googlecloudsdk.core import resolvers
from googlecloudsdk.core import resources
from googlecloudsdk.core.credentials import store as c_store
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class Debug(base.Group):
"""Commands for interacting with the Cloud Debugger.
Commands that allow interacting with the Cloud Debugger to list and
manipulate debug targets, snapshots, and logpoints.
"""
detailed_help = {
'EXAMPLES': """\
To view all available debug targets, run:
$ {command} targets list
"""
}
def Filter(self, context, args):
"""Initialize context for Cloud Debugger commands.
Args:
context: The current context.
args: The argparse namespace that was specified on the CLI or API.
Returns:
The updated context.
"""
resources.SetParamDefault(
api='debug', collection=None, param='projectId',
resolver=resolvers.FromProperty(properties.VALUES.core.project))
debug.DebugObject.InitializeApiClients()
| [
"googlecloudsdk.core.resolvers.FromProperty",
"googlecloudsdk.api_lib.debug.debug.DebugObject.InitializeApiClients",
"googlecloudsdk.calliope.base.ReleaseTracks"
] | [((941, 983), 'googlecloudsdk.calliope.base.ReleaseTracks', 'base.ReleaseTracks', (['base.ReleaseTrack.BETA'], {}), '(base.ReleaseTrack.BETA)\n', (959, 983), False, 'from googlecloudsdk.calliope import base\n'), ((1772, 1812), 'googlecloudsdk.api_lib.debug.debug.DebugObject.InitializeApiClients', 'debug.DebugObject.InitializeApiClients', ([], {}), '()\n', (1810, 1812), False, 'from googlecloudsdk.api_lib.debug import debug\n'), ((1711, 1765), 'googlecloudsdk.core.resolvers.FromProperty', 'resolvers.FromProperty', (['properties.VALUES.core.project'], {}), '(properties.VALUES.core.project)\n', (1733, 1765), False, 'from googlecloudsdk.core import resolvers\n')] |
"""
Unit tests for JobQueue class
"""
import mock
import os
import pytest
from jade.exceptions import InvalidParameter
from jade.jobs.job_configuration_factory import (
create_config_from_file,
create_config_from_previous_run
)
from jade.result import Result, ResultsSummary, serialize_results
@pytest.fixture
def jade_data():
"""Fixture of serialized jade result"""
return {
"base_directory": "/jade/results/base/directory/",
"results": [
{
"name": "australia",
"return_code": 1,
"status": "unfinished",
"exec_time_s": 10,
"completion_time": 15555555555
},
{
"name": "brazil",
"return_code": 0,
"status": "finished",
"exec_time_s": 20,
"completion_time": 15555555555
},
{
"name": "united_states",
"return_code": 0,
"status": "finished",
"exec_time_s": 30,
"completion_time": 15555555555
},
],
"jade_version": 0.1,
"timestamp": "2019-09-02 15:00:00"
}
@pytest.fixture
def results_summary(jade_data):
"""Fixture of ResultsSummary instance"""
ResultsSummary._parse = mock.MagicMock(return_value=jade_data)
@pytest.fixture
def incomplete_results(jade_data):
"""Fixture of ResultsSummary instance"""
jade_data["results"] = jade_data["results"][:2]
ResultsSummary._parse = mock.MagicMock(return_value=jade_data)
@pytest.fixture
def test_data_dir(test_data_dir):
"""The path to the directory that contains the fixture data"""
return os.path.join(test_data_dir, "demo")
@pytest.fixture
def config_file(test_data_dir):
return os.path.join(test_data_dir, "test-config.json")
@pytest.fixture
def output_dir(test_data_dir):
return os.path.join(test_data_dir, "output")
def test_create_config_from_file(config_file):
"""Create should successfully return config"""
config = create_config_from_file(config_file)
assert len(config.list_jobs()) == 3
def test_create_config_from_file_missing_file(config_file):
"""Create should throw FileNotFoundError"""
with pytest.raises(FileNotFoundError):
create_config_from_file("a" + config_file)
def test_create_config_from_previous_run_successful_results(config_file, output_dir, results_summary):
"""Create should return config with 2 jobs"""
successful_config = create_config_from_previous_run(config_file, output_dir)
assert len(successful_config.list_jobs()) == 2
for job in successful_config.list_jobs():
assert job.name in [ "brazil", "united_states" ]
def test_create_config_from_previous_run_failed_results(config_file, output_dir, results_summary):
"""Create should return config with 1 job"""
failed_config = create_config_from_previous_run(config_file, output_dir, "failed")
assert len(failed_config.list_jobs()) == 1
for job in failed_config.list_jobs():
assert job.name in [ "australia" ]
def test_create_config_from_previous_run_missing_results(config_file, output_dir, incomplete_results):
"""Create should return config with 1 job"""
missing_config = create_config_from_previous_run(config_file, output_dir, "missing")
assert len(missing_config.list_jobs()) == 1
for job in missing_config.list_jobs():
assert job.name in [ "united_states" ]
@pytest.mark.noautofixt
def test_create_config_from_previous_run_invalid_type_results(config_file, output_dir, results_summary):
"""Create should throw InvalidParameter"""
with pytest.raises(InvalidParameter):
create_config_from_previous_run(config_file, output_dir, "invalid_type")
| [
"jade.jobs.job_configuration_factory.create_config_from_previous_run",
"os.path.join",
"jade.jobs.job_configuration_factory.create_config_from_file",
"pytest.raises",
"mock.MagicMock"
] | [((1348, 1386), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': 'jade_data'}), '(return_value=jade_data)\n', (1362, 1386), False, 'import mock\n'), ((1564, 1602), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': 'jade_data'}), '(return_value=jade_data)\n', (1578, 1602), False, 'import mock\n'), ((1732, 1767), 'os.path.join', 'os.path.join', (['test_data_dir', '"""demo"""'], {}), "(test_data_dir, 'demo')\n", (1744, 1767), False, 'import os\n'), ((1828, 1875), 'os.path.join', 'os.path.join', (['test_data_dir', '"""test-config.json"""'], {}), "(test_data_dir, 'test-config.json')\n", (1840, 1875), False, 'import os\n'), ((1935, 1972), 'os.path.join', 'os.path.join', (['test_data_dir', '"""output"""'], {}), "(test_data_dir, 'output')\n", (1947, 1972), False, 'import os\n'), ((2085, 2121), 'jade.jobs.job_configuration_factory.create_config_from_file', 'create_config_from_file', (['config_file'], {}), '(config_file)\n', (2108, 2121), False, 'from jade.jobs.job_configuration_factory import create_config_from_file, create_config_from_previous_run\n'), ((2543, 2599), 'jade.jobs.job_configuration_factory.create_config_from_previous_run', 'create_config_from_previous_run', (['config_file', 'output_dir'], {}), '(config_file, output_dir)\n', (2574, 2599), False, 'from jade.jobs.job_configuration_factory import create_config_from_file, create_config_from_previous_run\n'), ((2923, 2989), 'jade.jobs.job_configuration_factory.create_config_from_previous_run', 'create_config_from_previous_run', (['config_file', 'output_dir', '"""failed"""'], {}), "(config_file, output_dir, 'failed')\n", (2954, 2989), False, 'from jade.jobs.job_configuration_factory import create_config_from_file, create_config_from_previous_run\n'), ((3296, 3363), 'jade.jobs.job_configuration_factory.create_config_from_previous_run', 'create_config_from_previous_run', (['config_file', 'output_dir', '"""missing"""'], {}), "(config_file, output_dir, 'missing')\n", (3327, 3363), False, 'from jade.jobs.job_configuration_factory import create_config_from_file, create_config_from_previous_run\n'), ((2280, 2312), 'pytest.raises', 'pytest.raises', (['FileNotFoundError'], {}), '(FileNotFoundError)\n', (2293, 2312), False, 'import pytest\n'), ((2322, 2364), 'jade.jobs.job_configuration_factory.create_config_from_file', 'create_config_from_file', (["('a' + config_file)"], {}), "('a' + config_file)\n", (2345, 2364), False, 'from jade.jobs.job_configuration_factory import create_config_from_file, create_config_from_previous_run\n'), ((3688, 3719), 'pytest.raises', 'pytest.raises', (['InvalidParameter'], {}), '(InvalidParameter)\n', (3701, 3719), False, 'import pytest\n'), ((3729, 3801), 'jade.jobs.job_configuration_factory.create_config_from_previous_run', 'create_config_from_previous_run', (['config_file', 'output_dir', '"""invalid_type"""'], {}), "(config_file, output_dir, 'invalid_type')\n", (3760, 3801), False, 'from jade.jobs.job_configuration_factory import create_config_from_file, create_config_from_previous_run\n')] |
# -*- coding: utf-8 -*-
import base64
import functools
import hashlib
import hmac
import json
import logging
import time
from urllib.parse import quote
import requests
import werkzeug.urls
import werkzeug.utils
from werkzeug.exceptions import BadRequest
from odoo import SUPERUSER_ID, api, http
from odoo import registry as registry_get
from odoo.addons.auth_oauth.controllers.main import \
OAuthController as Controller
from odoo.addons.auth_oauth.controllers.main import OAuthLogin as Home
from odoo.addons.web.controllers.main import (login_and_redirect,
set_cookie_and_redirect)
from odoo.exceptions import AccessDenied, UserError
from odoo.http import request
from odoo.tools import pycompat
_logger = logging.getLogger(__name__)
def fragment_to_query_string(func):
@functools.wraps(func)
def wrapper(self, *a, **kw):
kw.pop('debug', False)
if not kw:
return """<html><head><script>
var l = window.location;
var q = l.hash.substring(1);
var r = l.pathname + l.search;
if(q.length !== 0) {
var s = l.search ? (l.search === '?' ? '' : '&') : '?';
r = l.pathname + l.search + s + q;
}
if (r == l.pathname) {
r = '/';
}
window.location = r;
</script></head><body></body></html>"""
return func(self, *a, **kw)
return wrapper
class OAuthLogin(Home):
def list_providers(self):
"""
oauth2登录入口
:param kw:
:return:
"""
result = super(OAuthLogin, self).list_providers()
for provider in result:
if 'dingtalk' in provider['auth_endpoint']:
return_url = request.httprequest.url_root + 'dingding/auto/login'
state = self.get_state(provider)
params = dict(
response_type='code',
appid=provider['client_id'], # appid 是钉钉移动应用的appId
redirect_uri=return_url,
scope=provider['scope'],
state=json.dumps(state),
)
provider['auth_link'] = "%s?%s" % (provider['auth_endpoint'], werkzeug.urls.url_encode(params))
return result
class OAuthController(Controller):
@http.route('/dingding/auto/login/in', type='http', auth='none')
def dingding_auto_login(self, **kw):
"""
免登入口
:param kw:
:return:
"""
logging.info(">>>用户正在使用免登...")
data = {'corp_id': request.env['ir.config_parameter'].sudo().get_param('ali_dindin.din_corpId')}
return request.render('dindin_login.dingding_auto_login', data)
@http.route('/dingding/auto/login', type='http', auth='none')
@fragment_to_query_string
def auto_signin(self, **kw):
"""
通过获得的【免登授权码或者临时授权码】获取用户信息
:param kw:
:return:
"""
if kw.get('authcode'): # 免登
auth_code = kw.get('authcode')
_logger.info("获得的auth_code: %s", auth_code)
userid = self.get_userid_by_auth_code(auth_code)
state = dict(
d=request.session.db,
p='dingtalk',
)
elif kw.get('code'): # 扫码或密码登录
tmp_auth_code = kw.get('code', "")
_logger.info("获得的tmp_auth_code: %s", tmp_auth_code)
unionid = self.get_unionid_by_tmp_auth_code(tmp_auth_code)
userid = self.get_userid_by_unionid(unionid)
state = json.loads(kw['state'])
mobile = self.get_user_mobile_by_userid(userid)
dbname = state['d']
if not http.db_filter([dbname]):
return BadRequest()
provider = 'dingtalk'
# provider = state['p']
context = state.get('c', {})
registry = registry_get(dbname)
with registry.cursor() as cr:
try:
env = api.Environment(cr, SUPERUSER_ID, context)
credentials = env['res.users'].sudo().auth_oauth_dingtalk(provider, mobile)
cr.commit()
action = state.get('a')
menu = state.get('m')
redirect = werkzeug.url_unquote_plus(state['r']) if state.get('r') else False
url = '/web'
if redirect:
url = redirect
elif action:
url = '/web#action=%s' % action
elif menu:
url = '/web#menu_id=%s' % menu
resp = login_and_redirect(*credentials, redirect_url=url)
# Since /web is hardcoded, verify user has right to land on it
if werkzeug.urls.url_parse(resp.location).path == '/web' and not request.env.user.has_group('base.group_user'):
resp.location = '/'
return resp
except AttributeError:
# auth_signup is not installed
_logger.error("auth_signup not installed on database %s: oauth sign up cancelled." % (dbname,))
url = "/web/login?oauth_error=1"
except AccessDenied:
# oauth credentials not valid, user could be on a temporary session
_logger.info(
'OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies')
url = "/web/login?oauth_error=3"
redirect = werkzeug.utils.redirect(url, 303)
redirect.autocorrect_location_header = False
return redirect
except Exception as e:
# signup error
_logger.exception("OAuth2: %s" % str(e))
url = "/web/login?oauth_error=2"
return set_cookie_and_redirect(url)
def get_unionid_by_tmp_auth_code(self, tmp_auth_code):
"""
根据返回的临时授权码获取用户信息
:param tmp_auth_code:用户授权的临时授权码code,只能使用一次
:return:
"""
url = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'getuserinfo_bycode')]).value
login_appid = request.env['ir.config_parameter'].sudo().get_param('ali_dindin.din_login_appid')
key = request.env['ir.config_parameter'].sudo().get_param('ali_dindin.din_login_appsecret')
msg = pycompat.to_text(int(time.time() * 1000))
# ------------------------
# 签名
# ------------------------
signature = hmac.new(key.encode('utf-8'), msg.encode('utf-8'),
hashlib.sha256).digest()
signature = quote(base64.b64encode(signature), 'utf-8')
data = {
'tmp_auth_code': tmp_auth_code
}
headers = {'Content-Type': 'application/json'}
new_url = "{}signature={}×tamp={}&accessKey={}".format(url, signature, msg, login_appid)
try:
result = requests.post(url=new_url, headers=headers, data=json.dumps(data), timeout=15)
result = json.loads(result.text)
logging.info(">>>钉钉登录获取用户信息返回结果{}".format(result))
if result.get('errcode') == 0:
user_info = result.get('user_info')
return user_info['unionid']
raise BadRequest(result)
except Exception as e:
return {'state': False, 'msg': "异常信息:{}".format(str(e))}
def get_userid_by_unionid(self, unionid):
"""
根据unionid获取userid
"""
url = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'getUseridByUnionid')]).value
token = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'token')]).value
data = {'unionid': unionid}
try:
result = requests.get(url="{}{}".format(url, token), params=data, timeout=20)
logging.info(">>>根据unionid获取userid获取结果:{}".format(result.text))
result = json.loads(result.text)
if result.get('errcode') == 0:
return result.get('userid')
raise BadRequest(result)
except Exception as e:
return {'state': False, 'msg': "异常信息:{}".format(str(e))}
def get_userid_by_auth_code(self, auth_code):
"""
根据返回的免登授权码获取用户userid
:param auth_code:
:return:
"""
url = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'get_userid')]).value
token = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'token')]).value
url = "{}?access_token={}&code={}".format(url, token, auth_code)
try:
result = requests.get(url=url, timeout=5)
result = json.loads(result.text)
if result.get('errcode') == 0:
return result.get('userid')
raise BadRequest(result)
except Exception as e:
return {'state': False, 'msg': "异常信息:{}".format(str(e))}
def get_user_mobile_by_userid(self, userid):
"""
根据钉钉userid获取用户手机号
:param userid:
:return:
"""
url = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'user_get')]).value
token = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'token')]).value
data = {'userid': userid}
try:
result = requests.get(url="{}{}".format(url, token), params=data, timeout=20)
result = json.loads(result.text)
if result.get('errcode') == 0:
return result.get('mobile')
raise BadRequest(result)
except Exception as e:
return {'state': False, 'msg': "异常信息:{}".format(str(e))}
| [
"logging.getLogger",
"odoo.http.request.render",
"json.loads",
"odoo.http.db_filter",
"odoo.api.Environment",
"base64.b64encode",
"time.time",
"json.dumps",
"functools.wraps",
"odoo.http.route",
"requests.get",
"odoo.addons.web.controllers.main.set_cookie_and_redirect",
"odoo.registry",
"o... | [((760, 787), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (777, 787), False, 'import logging\n'), ((831, 852), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (846, 852), False, 'import functools\n'), ((2415, 2478), 'odoo.http.route', 'http.route', (['"""/dingding/auto/login/in"""'], {'type': '"""http"""', 'auth': '"""none"""'}), "('/dingding/auto/login/in', type='http', auth='none')\n", (2425, 2478), False, 'from odoo import SUPERUSER_ID, api, http\n'), ((2815, 2875), 'odoo.http.route', 'http.route', (['"""/dingding/auto/login"""'], {'type': '"""http"""', 'auth': '"""none"""'}), "('/dingding/auto/login', type='http', auth='none')\n", (2825, 2875), False, 'from odoo import SUPERUSER_ID, api, http\n'), ((2601, 2631), 'logging.info', 'logging.info', (['""">>>用户正在使用免登..."""'], {}), "('>>>用户正在使用免登...')\n", (2613, 2631), False, 'import logging\n'), ((2752, 2808), 'odoo.http.request.render', 'request.render', (['"""dindin_login.dingding_auto_login"""', 'data'], {}), "('dindin_login.dingding_auto_login', data)\n", (2766, 2808), False, 'from odoo.http import request\n'), ((3938, 3958), 'odoo.registry', 'registry_get', (['dbname'], {}), '(dbname)\n', (3950, 3958), True, 'from odoo import registry as registry_get\n'), ((5877, 5905), 'odoo.addons.web.controllers.main.set_cookie_and_redirect', 'set_cookie_and_redirect', (['url'], {}), '(url)\n', (5900, 5905), False, 'from odoo.addons.web.controllers.main import login_and_redirect, set_cookie_and_redirect\n'), ((3762, 3786), 'odoo.http.db_filter', 'http.db_filter', (['[dbname]'], {}), '([dbname])\n', (3776, 3786), False, 'from odoo import SUPERUSER_ID, api, http\n'), ((3807, 3819), 'werkzeug.exceptions.BadRequest', 'BadRequest', ([], {}), '()\n', (3817, 3819), False, 'from werkzeug.exceptions import BadRequest\n'), ((6687, 6714), 'base64.b64encode', 'base64.b64encode', (['signature'], {}), '(signature)\n', (6703, 6714), False, 'import base64\n'), ((7086, 7109), 'json.loads', 'json.loads', (['result.text'], {}), '(result.text)\n', (7096, 7109), False, 'import json\n'), ((7330, 7348), 'werkzeug.exceptions.BadRequest', 'BadRequest', (['result'], {}), '(result)\n', (7340, 7348), False, 'from werkzeug.exceptions import BadRequest\n'), ((7991, 8014), 'json.loads', 'json.loads', (['result.text'], {}), '(result.text)\n', (8001, 8014), False, 'import json\n'), ((8120, 8138), 'werkzeug.exceptions.BadRequest', 'BadRequest', (['result'], {}), '(result)\n', (8130, 8138), False, 'from werkzeug.exceptions import BadRequest\n'), ((8694, 8726), 'requests.get', 'requests.get', ([], {'url': 'url', 'timeout': '(5)'}), '(url=url, timeout=5)\n', (8706, 8726), False, 'import requests\n'), ((8748, 8771), 'json.loads', 'json.loads', (['result.text'], {}), '(result.text)\n', (8758, 8771), False, 'import json\n'), ((8877, 8895), 'werkzeug.exceptions.BadRequest', 'BadRequest', (['result'], {}), '(result)\n', (8887, 8895), False, 'from werkzeug.exceptions import BadRequest\n'), ((9493, 9516), 'json.loads', 'json.loads', (['result.text'], {}), '(result.text)\n', (9503, 9516), False, 'import json\n'), ((9622, 9640), 'werkzeug.exceptions.BadRequest', 'BadRequest', (['result'], {}), '(result)\n', (9632, 9640), False, 'from werkzeug.exceptions import BadRequest\n'), ((3638, 3661), 'json.loads', 'json.loads', (["kw['state']"], {}), "(kw['state'])\n", (3648, 3661), False, 'import json\n'), ((4036, 4078), 'odoo.api.Environment', 'api.Environment', (['cr', 'SUPERUSER_ID', 'context'], {}), '(cr, SUPERUSER_ID, context)\n', (4051, 4078), False, 'from odoo import SUPERUSER_ID, api, http\n'), ((4646, 4696), 'odoo.addons.web.controllers.main.login_and_redirect', 'login_and_redirect', (['*credentials'], {'redirect_url': 'url'}), '(*credentials, redirect_url=url)\n', (4664, 4696), False, 'from odoo.addons.web.controllers.main import login_and_redirect, set_cookie_and_redirect\n'), ((6432, 6443), 'time.time', 'time.time', ([], {}), '()\n', (6441, 6443), False, 'import time\n'), ((7035, 7051), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (7045, 7051), False, 'import json\n'), ((2201, 2218), 'json.dumps', 'json.dumps', (['state'], {}), '(state)\n', (2211, 2218), False, 'import json\n'), ((4857, 4902), 'odoo.http.request.env.user.has_group', 'request.env.user.has_group', (['"""base.group_user"""'], {}), "('base.group_user')\n", (4883, 4902), False, 'from odoo.http import request\n')] |
import unittest
from Kenken import Kenken
kenken_size_3 = [
('/', 3, ['A1', 'A2']),
('-', 1, ['B1', 'C1']),
('/', 3, ['B2', 'B3']),
('/', 2, ['C2', 'C3']),
('', 2, ['A3'])
]
kenken_size_4 = [
('*', 24, ['A1', 'A2', 'B1']),
('', 3, ['A3']),
('-', 3, ['A4', 'B4']),
('/', 2, ['B2', 'B3']),
('+', 6, ['C1', 'C2', 'D1']),
('+', 11, ['C3', 'C4', 'D3', 'D4']),
('', 3, ['D2']),
]
kenken_size_6 = [
('-', 1, ['A1', 'A2']),
('', 2, ['A3']),
('+', 11, ['A4', 'A5']),
('+', 5, ['A6', 'B6']),
('*', 60, ['B1', 'C1', 'C2']),
('', 1, ['B2']),
('/', 2, ['B3', 'B4']),
('*', 24, ['B5', 'C5', 'C6']),
('-', 1, ['C3', 'D3']),
('+', 3, ['C4', 'D4']),
('+', 14, ['D1', 'D2', 'E2']),
('*', 10, ['D5', 'D6', 'E6']),
('-', 3, ['E1', 'F1']),
('+', 7, ['E3', 'E4']),
('', 6, ['E5']),
('/', 2, ['F2', 'F3']),
('', 5, ['F4']),
('/', 2, ['F5', 'F6']),
]
kenken_size_8 = [
('-', 2, ['A1', 'B1']),
('+', 17, ['A2', 'A3', 'B3']),
('-', 7, ['A4', 'A5']),
('*', 40, ['A6', 'A7', 'A8']),
('+', 16, ['B2', 'C2', 'C3']),
('', 6, ['B4']),
('*', 180, ['B5', 'C4', 'C5', 'C6']),
('+', 16, ['B6', 'B7', 'C7']),
('*', 10, ['B8', 'C8']),
('*', 24, ['C1', 'D1', 'D2']),
('+', 11, ['D3', 'D4', 'D5']),
('+', 13, ['D6', 'D7']),
('/', 3, ['D8', 'E8']),
('+', 14, ['E1', 'E2', 'F1']),
('+', 21, ['E3', 'E4', 'E5']),
('/', 4, ['E6', 'E7']),
('*', 40, ['F2', 'F3', 'G2']),
('+', 6, ['F4', 'F5', 'F6']),
('+', 13, ['F7', 'G6', 'G7']),
('-', 2, ['F8', 'G8']),
('-', 2, ['G1', 'H1']),
('+', 7, ['G3', 'H2', 'H3']),
('+', 11, ['G4', 'G5']),
('*', 30, ['H4', 'H5']),
('+', 17, ['H6', 'H7', 'H8'])
]
class Test_Kenken(unittest.TestCase):
def test_creation(self):
kenken = Kenken(kenken_size_3)
self.assertIsNotNone(kenken)
self.assertEqual(kenken.size, 3)
kenken.display()
def test_creation_and_display_of_all_sizes(self):
for puzzle_definition in [
kenken_size_3,
kenken_size_4,
kenken_size_6,
kenken_size_8
]:
kenken = Kenken(puzzle_definition)
self.assertIsNotNone(kenken)
kenken.display()
print()
def test_writing_puzzle_to_file(self):
kenken = Kenken(kenken_size_3)
kenken.write_puzzle_to_file('/tmp/kenken.puzzle')
def test_solve_simple(self):
kenken = Kenken(kenken_size_3)
kenken.display()
solved_puzzle = kenken.search()
solved_puzzle.display()
self.assertTrue(solved_puzzle.is_solved())
def test_solve_advanced(self):
kenken = Kenken(kenken_size_8)
kenken.display()
solved_puzzle = kenken.search()
solved_puzzle.display()
self.assertTrue(solved_puzzle.is_solved())
def test_all_puzzles(self):
for puzzle_definition in [
kenken_size_3,
kenken_size_4,
kenken_size_6,
kenken_size_8
]:
kenken = Kenken(puzzle_definition)
kenken.display()
solved_puzzle = kenken.search()
solved_puzzle.display()
print()
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"Kenken.Kenken"
] | [((3310, 3325), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3323, 3325), False, 'import unittest\n'), ((1858, 1879), 'Kenken.Kenken', 'Kenken', (['kenken_size_3'], {}), '(kenken_size_3)\n', (1864, 1879), False, 'from Kenken import Kenken\n'), ((2389, 2410), 'Kenken.Kenken', 'Kenken', (['kenken_size_3'], {}), '(kenken_size_3)\n', (2395, 2410), False, 'from Kenken import Kenken\n'), ((2520, 2541), 'Kenken.Kenken', 'Kenken', (['kenken_size_3'], {}), '(kenken_size_3)\n', (2526, 2541), False, 'from Kenken import Kenken\n'), ((2744, 2765), 'Kenken.Kenken', 'Kenken', (['kenken_size_8'], {}), '(kenken_size_8)\n', (2750, 2765), False, 'from Kenken import Kenken\n'), ((2212, 2237), 'Kenken.Kenken', 'Kenken', (['puzzle_definition'], {}), '(puzzle_definition)\n', (2218, 2237), False, 'from Kenken import Kenken\n'), ((3122, 3147), 'Kenken.Kenken', 'Kenken', (['puzzle_definition'], {}), '(puzzle_definition)\n', (3128, 3147), False, 'from Kenken import Kenken\n')] |
from challenge import solution
def test_challenge():
# Create empty array (dependent on test)
# Create single entry array
# Create an array with the answer at the start
# Create an array with the answer at the end
# Create an array with the answer in the middle
# Single entry slot
assert(solution([2, 3, 1, 5]) == 4)
| [
"challenge.solution"
] | [((319, 341), 'challenge.solution', 'solution', (['[2, 3, 1, 5]'], {}), '([2, 3, 1, 5])\n', (327, 341), False, 'from challenge import solution\n')] |
import sys
from app import app
from app import get_attempts_data as presenter
from app import topic_hlr_train as model_functions
from app import kafka_config
import json
from kafka import KafkaConsumer
from kafka.structs import OffsetAndMetadata, TopicPartition
from datetime import datetime, time, timedelta
from collections import defaultdict
def __run_inference(user_id, attempts_df, todays_attempts):
results = None
entity_types = ['subject', 'chapter']
if len(attempts_df) > 0:
last_practiced_map = presenter.get_last_practiced(user_id) if todays_attempts else defaultdict(list)
results = model_functions.run_inference(attempts_df, entity_types, last_practiced_map)
presenter.write_to_hlr_index(user_id, results, todays_attempts, entity_types)
def get_attempts_and_run_inference(user_id, t_start, today_start):
only_todays_attempts = t_start == today_start
attempts_df = presenter.get_attempts_of_user(user_id, t_start)
if len(attempts_df) == 0:
if not only_todays_attempts:
__run_inference(user_id, attempts_df, False)
return
if not only_todays_attempts:
prev_attempts = attempts_df[attempts_df['attempttime'] < today_start]
__run_inference(user_id, prev_attempts, False)
__run_inference(user_id, attempts_df[attempts_df['attempttime'] >= today_start], True)
else:
__run_inference(user_id, attempts_df, True)
def infer_on_attempts(user_id):
today_start_ms = int(datetime.combine(datetime.today(), time.min).timestamp() * 1000)
if not presenter.past_attempts_fetched(user_id):
t_minus_x = datetime.now() - timedelta(days=model_functions.MAX_HL)
start_time = int(t_minus_x.timestamp() * 1000)
else:
start_time = today_start_ms
get_attempts_and_run_inference(user_id, start_time, today_start_ms)
def start_consumer():
print ("Starting consumer...")
consumer = KafkaConsumer(bootstrap_servers=[kafka_config.HOST],
key_deserializer=lambda m: m.decode('utf8'),
value_deserializer=lambda m: json.loads(m.decode('utf8')),
auto_offset_reset="latest",
max_poll_records=50,
group_id=kafka_config.GROUP_ID)
consumer.subscribe([kafka_config.TOPIC])
for msg in consumer:
infer_on_attempts(msg.value['userid'])
print ("Consumer: {}".format(msg), file=sys.stdout)
tp = TopicPartition(msg.topic, msg.partition)
offsets = {tp: OffsetAndMetadata(msg.offset, None)}
try:
consumer.commit(offsets=offsets)
except Exception as e:
print (e)
| [
"kafka.structs.OffsetAndMetadata",
"app.get_attempts_data.get_attempts_of_user",
"kafka.structs.TopicPartition",
"datetime.datetime.now",
"collections.defaultdict",
"app.get_attempts_data.get_last_practiced",
"datetime.datetime.today",
"app.topic_hlr_train.run_inference",
"datetime.timedelta",
"ap... | [((683, 760), 'app.get_attempts_data.write_to_hlr_index', 'presenter.write_to_hlr_index', (['user_id', 'results', 'todays_attempts', 'entity_types'], {}), '(user_id, results, todays_attempts, entity_types)\n', (711, 760), True, 'from app import get_attempts_data as presenter\n'), ((893, 941), 'app.get_attempts_data.get_attempts_of_user', 'presenter.get_attempts_of_user', (['user_id', 't_start'], {}), '(user_id, t_start)\n', (923, 941), True, 'from app import get_attempts_data as presenter\n'), ((605, 681), 'app.topic_hlr_train.run_inference', 'model_functions.run_inference', (['attempts_df', 'entity_types', 'last_practiced_map'], {}), '(attempts_df, entity_types, last_practiced_map)\n', (634, 681), True, 'from app import topic_hlr_train as model_functions\n'), ((1482, 1522), 'app.get_attempts_data.past_attempts_fetched', 'presenter.past_attempts_fetched', (['user_id'], {}), '(user_id)\n', (1513, 1522), True, 'from app import get_attempts_data as presenter\n'), ((2248, 2288), 'kafka.structs.TopicPartition', 'TopicPartition', (['msg.topic', 'msg.partition'], {}), '(msg.topic, msg.partition)\n', (2262, 2288), False, 'from kafka.structs import OffsetAndMetadata, TopicPartition\n'), ((512, 549), 'app.get_attempts_data.get_last_practiced', 'presenter.get_last_practiced', (['user_id'], {}), '(user_id)\n', (540, 549), True, 'from app import get_attempts_data as presenter\n'), ((574, 591), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (585, 591), False, 'from collections import defaultdict\n'), ((1538, 1552), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1550, 1552), False, 'from datetime import datetime, time, timedelta\n'), ((1555, 1593), 'datetime.timedelta', 'timedelta', ([], {'days': 'model_functions.MAX_HL'}), '(days=model_functions.MAX_HL)\n', (1564, 1593), False, 'from datetime import datetime, time, timedelta\n'), ((2306, 2341), 'kafka.structs.OffsetAndMetadata', 'OffsetAndMetadata', (['msg.offset', 'None'], {}), '(msg.offset, None)\n', (2323, 2341), False, 'from kafka.structs import OffsetAndMetadata, TopicPartition\n'), ((1426, 1442), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (1440, 1442), False, 'from datetime import datetime, time, timedelta\n')] |
"""
Exam 1, problem 1.
Authors: <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, their colleagues,
and <NAME>.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
import rosegraphics as rg
# -----------------------------------------------------------------------------
# DONE: 2. Right-click on the src folder and
# Mark Directory as ... Sources Root,
# if you have not already done so.
# -----------------------------------------------------------------------------
def main():
""" Calls the TEST functions in this module. """
run_test_problem1()
def run_test_problem1():
""" Tests the problem1 function. """
print()
print('--------------------------------------------------')
print('Testing the problem1 function:')
print(' See the graphics windows that pop up.')
print('--------------------------------------------------')
# TWO tests on ONE window.
title = 'Tests 1 & 2 of problem1: '
title += 'red & blue, then cyan & magenta'
window = rg.RoseWindow(400, 250, title)
# Test 1:
square = rg.Square(rg.Point(125, 50), 60)
square.fill_color = 'red'
square.outline_color = 'blue'
square.outline_thickness = 3
problem1(square, 6, window)
window.continue_on_mouse_click()
# Test 2:
square = rg.Square(rg.Point(250, 100), 100)
square.fill_color = 'cyan'
square.outline_color = 'magenta'
square.outline_thickness = 6
problem1(square, 3, window)
window.close_on_mouse_click()
# A third test on ANOTHER window.
title = 'Test 3 of problem1: yellow & black'
window = rg.RoseWindow(300, 400, title)
# Test 3:
square = rg.Square(rg.Point(150, 125), 150)
square.fill_color = 'yellow'
problem1(square, 15, window)
window.close_on_mouse_click()
def problem1(square, thickness, window):
"""
See problem1_picture.pdf in this project for pictures
that may help you better understand the following specification:
What comes in:
-- An rg.Square.
-- A positive integer
-- An rg.RoseWindow.
What goes out: Nothing (i.e., None).
Side effects:
-- Draws, on the given rg.RoseWindow:
-- The given rg.Square.
-- An rg.Circle that:
-- is directly below and touching the given rg.Square,
-- has diameter the same as the length of each side
of the given rg.Square,
-- has fill color the same as the fill color
of the given rg.Square, and
-- has the given thickness as its outline thickness.
(SEE THE PICTURES.)
-- An rg.Line that:
-- has one endpoint is at the center of the above rg.Circle,
-- has another endpoint that is at the midpoint of the
left side of the given rg.Square,
-- has color the same as the outline color
of the given rg.Square, and
-- has the given thickness. (SEE THE PICTURES.)
Note: Attach the rg.Line AFTER attaching the rg.Square and rg.Circle.
Must render but ** NOT close ** the window.
Type hints:
:type square: rg.Square
:type thickness: int
:type window: rg.RoseWindow
"""
# -------------------------------------------------------------------------
# DONE: 3. Implement and test this function. SEE THE PICTURES in the PDF!
# Tests have been written for you (above).
# -------------------------------------------------------------------------
square.attach_to(window)
circle = rg.Circle(rg.Point(square.center.x, square.center.y + square.length_of_each_side), square.length_of_each_side / 2)
circle.outline_thickness = thickness
circle.fill_color = square.fill_color
circle.attach_to(window)
line = rg.Line(rg.Point(square.center.x - (square.length_of_each_side / 2), square.center.y), circle.center)
line.thickness = thickness
line.color = square.outline_color
line.attach_to(window)
window.render()
# -----------------------------------------------------------------------------
# Calls main to start the ball rolling.
# -----------------------------------------------------------------------------
main()
| [
"rosegraphics.RoseWindow",
"rosegraphics.Point"
] | [((1053, 1083), 'rosegraphics.RoseWindow', 'rg.RoseWindow', (['(400)', '(250)', 'title'], {}), '(400, 250, title)\n', (1066, 1083), True, 'import rosegraphics as rg\n'), ((1644, 1674), 'rosegraphics.RoseWindow', 'rg.RoseWindow', (['(300)', '(400)', 'title'], {}), '(300, 400, title)\n', (1657, 1674), True, 'import rosegraphics as rg\n'), ((1122, 1139), 'rosegraphics.Point', 'rg.Point', (['(125)', '(50)'], {}), '(125, 50)\n', (1130, 1139), True, 'import rosegraphics as rg\n'), ((1350, 1368), 'rosegraphics.Point', 'rg.Point', (['(250)', '(100)'], {}), '(250, 100)\n', (1358, 1368), True, 'import rosegraphics as rg\n'), ((1713, 1731), 'rosegraphics.Point', 'rg.Point', (['(150)', '(125)'], {}), '(150, 125)\n', (1721, 1731), True, 'import rosegraphics as rg\n'), ((3705, 3776), 'rosegraphics.Point', 'rg.Point', (['square.center.x', '(square.center.y + square.length_of_each_side)'], {}), '(square.center.x, square.center.y + square.length_of_each_side)\n', (3713, 3776), True, 'import rosegraphics as rg\n'), ((3941, 4016), 'rosegraphics.Point', 'rg.Point', (['(square.center.x - square.length_of_each_side / 2)', 'square.center.y'], {}), '(square.center.x - square.length_of_each_side / 2, square.center.y)\n', (3949, 4016), True, 'import rosegraphics as rg\n')] |
import numpy as np
import geocoder
def process_df(df):
"""
df: pd.DataFrame
"""
df.dropna(subset=['lat', 'lon'], axis=0, inplace=True)
df.reset_index(drop=True, inplace=True)
# Add new column to hold the years
df["year"] = [int(x.split("-")[0]) for x in df['date']]
# Convert coordinates to decimal degrees ISO 6709 format i.e:(14.76º,
# -23.2234º)
lat_flip = np.logical_and(df["lat-dir"] == "S", df["lat"] >= 0)
df.loc[lat_flip, "lat"] *= -1
lon_flip = np.logical_and(df["lon-dir"] == "W", df["lon"] >= 0)
df.loc[lon_flip, "lon"] *= -1
legend = []
print('Starting to pull data from Google Geolocation API')
for i in range(len(df['impact-e'])):
print(i+1, "of {}".format(len(df)+1))
g = geocoder.google([df['lat'][i], df['lon'][i]], method='reverse')
city = '{}'.format(g.city) if g.city else "N/A"
country = '{}'.format(g.country) if g.country else "N/A"
if city is not None and country is not None:
location = "Location: {},{}<br>".format(city, country)
if df['impact-e'][i] < 10:
legend.append('{}<10 kt<br>{}'.format(location, str(df['date'][i])))
else:
legend.append('{}{} kt<br>{}'.format(location, df['impact-e'][i], str(df['date'][i])))
df['legend'] = legend
return df
| [
"geocoder.google",
"numpy.logical_and"
] | [((409, 461), 'numpy.logical_and', 'np.logical_and', (["(df['lat-dir'] == 'S')", "(df['lat'] >= 0)"], {}), "(df['lat-dir'] == 'S', df['lat'] >= 0)\n", (423, 461), True, 'import numpy as np\n'), ((511, 563), 'numpy.logical_and', 'np.logical_and', (["(df['lon-dir'] == 'W')", "(df['lon'] >= 0)"], {}), "(df['lon-dir'] == 'W', df['lon'] >= 0)\n", (525, 563), True, 'import numpy as np\n'), ((777, 840), 'geocoder.google', 'geocoder.google', (["[df['lat'][i], df['lon'][i]]"], {'method': '"""reverse"""'}), "([df['lat'][i], df['lon'][i]], method='reverse')\n", (792, 840), False, 'import geocoder\n')] |
"""{{ cookiecutter.project_name }} URL Configuration
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls import include, url
# from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', TemplateView.as_view(template_name='index.html')),
path('api/', include('{{ cookiecutter.project_name }}.api.urls')),
path('', include('{{ cookiecutter.project_name }}.web.urls')),
]
# + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
| [
"django.views.generic.TemplateView.as_view",
"django.conf.urls.include",
"django.urls.path"
] | [((309, 340), 'django.urls.path', 'path', (['"""admin/"""', 'admin.site.urls'], {}), "('admin/', admin.site.urls)\n", (313, 340), False, 'from django.urls import path\n'), ((355, 403), 'django.views.generic.TemplateView.as_view', 'TemplateView.as_view', ([], {'template_name': '"""index.html"""'}), "(template_name='index.html')\n", (375, 403), False, 'from django.views.generic import TemplateView\n'), ((423, 474), 'django.conf.urls.include', 'include', (['"""{{ cookiecutter.project_name }}.api.urls"""'], {}), "('{{ cookiecutter.project_name }}.api.urls')\n", (430, 474), False, 'from django.conf.urls import include, url\n'), ((490, 541), 'django.conf.urls.include', 'include', (['"""{{ cookiecutter.project_name }}.web.urls"""'], {}), "('{{ cookiecutter.project_name }}.web.urls')\n", (497, 541), False, 'from django.conf.urls import include, url\n'), ((775, 802), 'django.conf.urls.include', 'include', (['debug_toolbar.urls'], {}), '(debug_toolbar.urls)\n', (782, 802), False, 'from django.conf.urls import include, url\n')] |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['IntegrationArgs', 'Integration']
@pulumi.input_type
class IntegrationArgs:
def __init__(__self__, *,
client_id: pulumi.Input[str],
client_secret: pulumi.Input[str],
tenant_name: pulumi.Input[str],
automute: Optional[pulumi.Input[bool]] = None,
host_filters: Optional[pulumi.Input[str]] = None):
"""
The set of arguments for constructing a Integration resource.
:param pulumi.Input[str] client_id: Your Azure web application ID.
:param pulumi.Input[str] client_secret: (Required for Initial Creation) Your Azure web application secret key.
:param pulumi.Input[str] tenant_name: Your Azure Active Directory ID.
:param pulumi.Input[bool] automute: Silence monitors for expected Azure VM shutdowns.
:param pulumi.Input[str] host_filters: String of host tag(s) (in the form `key:value,key:value`) defines a filter that Datadog will use when collecting metrics from Azure. Limit the Azure instances that are pulled into Datadog by using tags. Only hosts that match one of the defined tags are imported into Datadog. e.x. `env:production,deploymentgroup:red`
"""
pulumi.set(__self__, "client_id", client_id)
pulumi.set(__self__, "client_secret", client_secret)
pulumi.set(__self__, "tenant_name", tenant_name)
if automute is not None:
pulumi.set(__self__, "automute", automute)
if host_filters is not None:
pulumi.set(__self__, "host_filters", host_filters)
@property
@pulumi.getter(name="clientId")
def client_id(self) -> pulumi.Input[str]:
"""
Your Azure web application ID.
"""
return pulumi.get(self, "client_id")
@client_id.setter
def client_id(self, value: pulumi.Input[str]):
pulumi.set(self, "client_id", value)
@property
@pulumi.getter(name="clientSecret")
def client_secret(self) -> pulumi.Input[str]:
"""
(Required for Initial Creation) Your Azure web application secret key.
"""
return pulumi.get(self, "client_secret")
@client_secret.setter
def client_secret(self, value: pulumi.Input[str]):
pulumi.set(self, "client_secret", value)
@property
@pulumi.getter(name="tenantName")
def tenant_name(self) -> pulumi.Input[str]:
"""
Your Azure Active Directory ID.
"""
return pulumi.get(self, "tenant_name")
@tenant_name.setter
def tenant_name(self, value: pulumi.Input[str]):
pulumi.set(self, "tenant_name", value)
@property
@pulumi.getter
def automute(self) -> Optional[pulumi.Input[bool]]:
"""
Silence monitors for expected Azure VM shutdowns.
"""
return pulumi.get(self, "automute")
@automute.setter
def automute(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "automute", value)
@property
@pulumi.getter(name="hostFilters")
def host_filters(self) -> Optional[pulumi.Input[str]]:
"""
String of host tag(s) (in the form `key:value,key:value`) defines a filter that Datadog will use when collecting metrics from Azure. Limit the Azure instances that are pulled into Datadog by using tags. Only hosts that match one of the defined tags are imported into Datadog. e.x. `env:production,deploymentgroup:red`
"""
return pulumi.get(self, "host_filters")
@host_filters.setter
def host_filters(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "host_filters", value)
@pulumi.input_type
class _IntegrationState:
def __init__(__self__, *,
automute: Optional[pulumi.Input[bool]] = None,
client_id: Optional[pulumi.Input[str]] = None,
client_secret: Optional[pulumi.Input[str]] = None,
host_filters: Optional[pulumi.Input[str]] = None,
tenant_name: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering Integration resources.
:param pulumi.Input[bool] automute: Silence monitors for expected Azure VM shutdowns.
:param pulumi.Input[str] client_id: Your Azure web application ID.
:param pulumi.Input[str] client_secret: (Required for Initial Creation) Your Azure web application secret key.
:param pulumi.Input[str] host_filters: String of host tag(s) (in the form `key:value,key:value`) defines a filter that Datadog will use when collecting metrics from Azure. Limit the Azure instances that are pulled into Datadog by using tags. Only hosts that match one of the defined tags are imported into Datadog. e.x. `env:production,deploymentgroup:red`
:param pulumi.Input[str] tenant_name: Your Azure Active Directory ID.
"""
if automute is not None:
pulumi.set(__self__, "automute", automute)
if client_id is not None:
pulumi.set(__self__, "client_id", client_id)
if client_secret is not None:
pulumi.set(__self__, "client_secret", client_secret)
if host_filters is not None:
pulumi.set(__self__, "host_filters", host_filters)
if tenant_name is not None:
pulumi.set(__self__, "tenant_name", tenant_name)
@property
@pulumi.getter
def automute(self) -> Optional[pulumi.Input[bool]]:
"""
Silence monitors for expected Azure VM shutdowns.
"""
return pulumi.get(self, "automute")
@automute.setter
def automute(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "automute", value)
@property
@pulumi.getter(name="clientId")
def client_id(self) -> Optional[pulumi.Input[str]]:
"""
Your Azure web application ID.
"""
return pulumi.get(self, "client_id")
@client_id.setter
def client_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "client_id", value)
@property
@pulumi.getter(name="clientSecret")
def client_secret(self) -> Optional[pulumi.Input[str]]:
"""
(Required for Initial Creation) Your Azure web application secret key.
"""
return pulumi.get(self, "client_secret")
@client_secret.setter
def client_secret(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "client_secret", value)
@property
@pulumi.getter(name="hostFilters")
def host_filters(self) -> Optional[pulumi.Input[str]]:
"""
String of host tag(s) (in the form `key:value,key:value`) defines a filter that Datadog will use when collecting metrics from Azure. Limit the Azure instances that are pulled into Datadog by using tags. Only hosts that match one of the defined tags are imported into Datadog. e.x. `env:production,deploymentgroup:red`
"""
return pulumi.get(self, "host_filters")
@host_filters.setter
def host_filters(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "host_filters", value)
@property
@pulumi.getter(name="tenantName")
def tenant_name(self) -> Optional[pulumi.Input[str]]:
"""
Your Azure Active Directory ID.
"""
return pulumi.get(self, "tenant_name")
@tenant_name.setter
def tenant_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "tenant_name", value)
class Integration(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
automute: Optional[pulumi.Input[bool]] = None,
client_id: Optional[pulumi.Input[str]] = None,
client_secret: Optional[pulumi.Input[str]] = None,
host_filters: Optional[pulumi.Input[str]] = None,
tenant_name: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
Provides a Datadog - Microsoft Azure integration resource. This can be used to create and manage the integrations.
## Example Usage
```python
import pulumi
import pulumi_datadog as datadog
# Create a new Datadog - Microsoft Azure integration
sandbox = datadog.azure.Integration("sandbox",
client_id="<azure_client_id>",
client_secret="<azure_client_secret_key>",
host_filters="examplefilter:true,example:true",
tenant_name="<azure_tenant_name>")
```
## Import
# Microsoft Azure integrations can be imported using their `tenant name` and `client` id separated with a colon (`:`).
```sh
$ pulumi import datadog:azure/integration:Integration sandbox ${tenant_name}:${client_id}
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[bool] automute: Silence monitors for expected Azure VM shutdowns.
:param pulumi.Input[str] client_id: Your Azure web application ID.
:param pulumi.Input[str] client_secret: (Required for Initial Creation) Your Azure web application secret key.
:param pulumi.Input[str] host_filters: String of host tag(s) (in the form `key:value,key:value`) defines a filter that Datadog will use when collecting metrics from Azure. Limit the Azure instances that are pulled into Datadog by using tags. Only hosts that match one of the defined tags are imported into Datadog. e.x. `env:production,deploymentgroup:red`
:param pulumi.Input[str] tenant_name: Your Azure Active Directory ID.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: IntegrationArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Provides a Datadog - Microsoft Azure integration resource. This can be used to create and manage the integrations.
## Example Usage
```python
import pulumi
import pulumi_datadog as datadog
# Create a new Datadog - Microsoft Azure integration
sandbox = datadog.azure.Integration("sandbox",
client_id="<azure_client_id>",
client_secret="<azure_client_secret_key>",
host_filters="examplefilter:true,example:true",
tenant_name="<azure_tenant_name>")
```
## Import
# Microsoft Azure integrations can be imported using their `tenant name` and `client` id separated with a colon (`:`).
```sh
$ pulumi import datadog:azure/integration:Integration sandbox ${tenant_name}:${client_id}
```
:param str resource_name: The name of the resource.
:param IntegrationArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(IntegrationArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
automute: Optional[pulumi.Input[bool]] = None,
client_id: Optional[pulumi.Input[str]] = None,
client_secret: Optional[pulumi.Input[str]] = None,
host_filters: Optional[pulumi.Input[str]] = None,
tenant_name: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = IntegrationArgs.__new__(IntegrationArgs)
__props__.__dict__["automute"] = automute
if client_id is None and not opts.urn:
raise TypeError("Missing required property 'client_id'")
__props__.__dict__["client_id"] = client_id
if client_secret is None and not opts.urn:
raise TypeError("Missing required property 'client_secret'")
__props__.__dict__["client_secret"] = client_secret
__props__.__dict__["host_filters"] = host_filters
if tenant_name is None and not opts.urn:
raise TypeError("Missing required property 'tenant_name'")
__props__.__dict__["tenant_name"] = tenant_name
super(Integration, __self__).__init__(
'datadog:azure/integration:Integration',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
automute: Optional[pulumi.Input[bool]] = None,
client_id: Optional[pulumi.Input[str]] = None,
client_secret: Optional[pulumi.Input[str]] = None,
host_filters: Optional[pulumi.Input[str]] = None,
tenant_name: Optional[pulumi.Input[str]] = None) -> 'Integration':
"""
Get an existing Integration resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[bool] automute: Silence monitors for expected Azure VM shutdowns.
:param pulumi.Input[str] client_id: Your Azure web application ID.
:param pulumi.Input[str] client_secret: (Required for Initial Creation) Your Azure web application secret key.
:param pulumi.Input[str] host_filters: String of host tag(s) (in the form `key:value,key:value`) defines a filter that Datadog will use when collecting metrics from Azure. Limit the Azure instances that are pulled into Datadog by using tags. Only hosts that match one of the defined tags are imported into Datadog. e.x. `env:production,deploymentgroup:red`
:param pulumi.Input[str] tenant_name: Your Azure Active Directory ID.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _IntegrationState.__new__(_IntegrationState)
__props__.__dict__["automute"] = automute
__props__.__dict__["client_id"] = client_id
__props__.__dict__["client_secret"] = client_secret
__props__.__dict__["host_filters"] = host_filters
__props__.__dict__["tenant_name"] = tenant_name
return Integration(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def automute(self) -> pulumi.Output[Optional[bool]]:
"""
Silence monitors for expected Azure VM shutdowns.
"""
return pulumi.get(self, "automute")
@property
@pulumi.getter(name="clientId")
def client_id(self) -> pulumi.Output[str]:
"""
Your Azure web application ID.
"""
return pulumi.get(self, "client_id")
@property
@pulumi.getter(name="clientSecret")
def client_secret(self) -> pulumi.Output[str]:
"""
(Required for Initial Creation) Your Azure web application secret key.
"""
return pulumi.get(self, "client_secret")
@property
@pulumi.getter(name="hostFilters")
def host_filters(self) -> pulumi.Output[Optional[str]]:
"""
String of host tag(s) (in the form `key:value,key:value`) defines a filter that Datadog will use when collecting metrics from Azure. Limit the Azure instances that are pulled into Datadog by using tags. Only hosts that match one of the defined tags are imported into Datadog. e.x. `env:production,deploymentgroup:red`
"""
return pulumi.get(self, "host_filters")
@property
@pulumi.getter(name="tenantName")
def tenant_name(self) -> pulumi.Output[str]:
"""
Your Azure Active Directory ID.
"""
return pulumi.get(self, "tenant_name")
| [
"pulumi.getter",
"pulumi.set",
"pulumi.ResourceOptions",
"pulumi.get"
] | [((1934, 1964), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""clientId"""'}), "(name='clientId')\n", (1947, 1964), False, 'import pulumi\n'), ((2258, 2292), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""clientSecret"""'}), "(name='clientSecret')\n", (2271, 2292), False, 'import pulumi\n'), ((2646, 2678), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""tenantName"""'}), "(name='tenantName')\n", (2659, 2678), False, 'import pulumi\n'), ((3326, 3359), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""hostFilters"""'}), "(name='hostFilters')\n", (3339, 3359), False, 'import pulumi\n'), ((6040, 6070), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""clientId"""'}), "(name='clientId')\n", (6053, 6070), False, 'import pulumi\n'), ((6384, 6418), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""clientSecret"""'}), "(name='clientSecret')\n", (6397, 6418), False, 'import pulumi\n'), ((6792, 6825), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""hostFilters"""'}), "(name='hostFilters')\n", (6805, 6825), False, 'import pulumi\n'), ((7441, 7473), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""tenantName"""'}), "(name='tenantName')\n", (7454, 7473), False, 'import pulumi\n'), ((15989, 16019), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""clientId"""'}), "(name='clientId')\n", (16002, 16019), False, 'import pulumi\n'), ((16195, 16229), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""clientSecret"""'}), "(name='clientSecret')\n", (16208, 16229), False, 'import pulumi\n'), ((16453, 16486), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""hostFilters"""'}), "(name='hostFilters')\n", (16466, 16486), False, 'import pulumi\n'), ((16965, 16997), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""tenantName"""'}), "(name='tenantName')\n", (16978, 16997), False, 'import pulumi\n'), ((1563, 1607), 'pulumi.set', 'pulumi.set', (['__self__', '"""client_id"""', 'client_id'], {}), "(__self__, 'client_id', client_id)\n", (1573, 1607), False, 'import pulumi\n'), ((1616, 1668), 'pulumi.set', 'pulumi.set', (['__self__', '"""client_secret"""', 'client_secret'], {}), "(__self__, 'client_secret', client_secret)\n", (1626, 1668), False, 'import pulumi\n'), ((1677, 1725), 'pulumi.set', 'pulumi.set', (['__self__', '"""tenant_name"""', 'tenant_name'], {}), "(__self__, 'tenant_name', tenant_name)\n", (1687, 1725), False, 'import pulumi\n'), ((2089, 2118), 'pulumi.get', 'pulumi.get', (['self', '"""client_id"""'], {}), "(self, 'client_id')\n", (2099, 2118), False, 'import pulumi\n'), ((2201, 2237), 'pulumi.set', 'pulumi.set', (['self', '"""client_id"""', 'value'], {}), "(self, 'client_id', value)\n", (2211, 2237), False, 'import pulumi\n'), ((2461, 2494), 'pulumi.get', 'pulumi.get', (['self', '"""client_secret"""'], {}), "(self, 'client_secret')\n", (2471, 2494), False, 'import pulumi\n'), ((2585, 2625), 'pulumi.set', 'pulumi.set', (['self', '"""client_secret"""', 'value'], {}), "(self, 'client_secret', value)\n", (2595, 2625), False, 'import pulumi\n'), ((2806, 2837), 'pulumi.get', 'pulumi.get', (['self', '"""tenant_name"""'], {}), "(self, 'tenant_name')\n", (2816, 2837), False, 'import pulumi\n'), ((2924, 2962), 'pulumi.set', 'pulumi.set', (['self', '"""tenant_name"""', 'value'], {}), "(self, 'tenant_name', value)\n", (2934, 2962), False, 'import pulumi\n'), ((3150, 3178), 'pulumi.get', 'pulumi.get', (['self', '"""automute"""'], {}), "(self, 'automute')\n", (3160, 3178), False, 'import pulumi\n'), ((3270, 3305), 'pulumi.set', 'pulumi.set', (['self', '"""automute"""', 'value'], {}), "(self, 'automute', value)\n", (3280, 3305), False, 'import pulumi\n'), ((3784, 3816), 'pulumi.get', 'pulumi.get', (['self', '"""host_filters"""'], {}), "(self, 'host_filters')\n", (3794, 3816), False, 'import pulumi\n'), ((3915, 3954), 'pulumi.set', 'pulumi.set', (['self', '"""host_filters"""', 'value'], {}), "(self, 'host_filters', value)\n", (3925, 3954), False, 'import pulumi\n'), ((5864, 5892), 'pulumi.get', 'pulumi.get', (['self', '"""automute"""'], {}), "(self, 'automute')\n", (5874, 5892), False, 'import pulumi\n'), ((5984, 6019), 'pulumi.set', 'pulumi.set', (['self', '"""automute"""', 'value'], {}), "(self, 'automute', value)\n", (5994, 6019), False, 'import pulumi\n'), ((6205, 6234), 'pulumi.get', 'pulumi.get', (['self', '"""client_id"""'], {}), "(self, 'client_id')\n", (6215, 6234), False, 'import pulumi\n'), ((6327, 6363), 'pulumi.set', 'pulumi.set', (['self', '"""client_id"""', 'value'], {}), "(self, 'client_id', value)\n", (6337, 6363), False, 'import pulumi\n'), ((6597, 6630), 'pulumi.get', 'pulumi.get', (['self', '"""client_secret"""'], {}), "(self, 'client_secret')\n", (6607, 6630), False, 'import pulumi\n'), ((6731, 6771), 'pulumi.set', 'pulumi.set', (['self', '"""client_secret"""', 'value'], {}), "(self, 'client_secret', value)\n", (6741, 6771), False, 'import pulumi\n'), ((7250, 7282), 'pulumi.get', 'pulumi.get', (['self', '"""host_filters"""'], {}), "(self, 'host_filters')\n", (7260, 7282), False, 'import pulumi\n'), ((7381, 7420), 'pulumi.set', 'pulumi.set', (['self', '"""host_filters"""', 'value'], {}), "(self, 'host_filters', value)\n", (7391, 7420), False, 'import pulumi\n'), ((7611, 7642), 'pulumi.get', 'pulumi.get', (['self', '"""tenant_name"""'], {}), "(self, 'tenant_name')\n", (7621, 7642), False, 'import pulumi\n'), ((7739, 7777), 'pulumi.set', 'pulumi.set', (['self', '"""tenant_name"""', 'value'], {}), "(self, 'tenant_name', value)\n", (7749, 7777), False, 'import pulumi\n'), ((15940, 15968), 'pulumi.get', 'pulumi.get', (['self', '"""automute"""'], {}), "(self, 'automute')\n", (15950, 15968), False, 'import pulumi\n'), ((16145, 16174), 'pulumi.get', 'pulumi.get', (['self', '"""client_id"""'], {}), "(self, 'client_id')\n", (16155, 16174), False, 'import pulumi\n'), ((16399, 16432), 'pulumi.get', 'pulumi.get', (['self', '"""client_secret"""'], {}), "(self, 'client_secret')\n", (16409, 16432), False, 'import pulumi\n'), ((16912, 16944), 'pulumi.get', 'pulumi.get', (['self', '"""host_filters"""'], {}), "(self, 'host_filters')\n", (16922, 16944), False, 'import pulumi\n'), ((17126, 17157), 'pulumi.get', 'pulumi.get', (['self', '"""tenant_name"""'], {}), "(self, 'tenant_name')\n", (17136, 17157), False, 'import pulumi\n'), ((1771, 1813), 'pulumi.set', 'pulumi.set', (['__self__', '"""automute"""', 'automute'], {}), "(__self__, 'automute', automute)\n", (1781, 1813), False, 'import pulumi\n'), ((1863, 1913), 'pulumi.set', 'pulumi.set', (['__self__', '"""host_filters"""', 'host_filters'], {}), "(__self__, 'host_filters', host_filters)\n", (1873, 1913), False, 'import pulumi\n'), ((5243, 5285), 'pulumi.set', 'pulumi.set', (['__self__', '"""automute"""', 'automute'], {}), "(__self__, 'automute', automute)\n", (5253, 5285), False, 'import pulumi\n'), ((5332, 5376), 'pulumi.set', 'pulumi.set', (['__self__', '"""client_id"""', 'client_id'], {}), "(__self__, 'client_id', client_id)\n", (5342, 5376), False, 'import pulumi\n'), ((5427, 5479), 'pulumi.set', 'pulumi.set', (['__self__', '"""client_secret"""', 'client_secret'], {}), "(__self__, 'client_secret', client_secret)\n", (5437, 5479), False, 'import pulumi\n'), ((5529, 5579), 'pulumi.set', 'pulumi.set', (['__self__', '"""host_filters"""', 'host_filters'], {}), "(__self__, 'host_filters', host_filters)\n", (5539, 5579), False, 'import pulumi\n'), ((5628, 5676), 'pulumi.set', 'pulumi.set', (['__self__', '"""tenant_name"""', 'tenant_name'], {}), "(__self__, 'tenant_name', tenant_name)\n", (5638, 5676), False, 'import pulumi\n'), ((12281, 12305), 'pulumi.ResourceOptions', 'pulumi.ResourceOptions', ([], {}), '()\n', (12303, 12305), False, 'import pulumi\n'), ((15304, 15333), 'pulumi.ResourceOptions', 'pulumi.ResourceOptions', ([], {'id': 'id'}), '(id=id)\n', (15326, 15333), False, 'import pulumi\n')] |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import logging
import shutil
import time
import os
def create_test_directory():
test_dir_name = "tests/" + time.strftime("%Y_%m_%d_%H_%M_%S")
path = os.path.join(os.getcwd(), test_dir_name)
os.mkdir(path, mode=0o777)
print("Test directory: ", path)
return path
def configure_logging(log_filename, clear_log_file=True):
format_template = ("%(asctime)s %(threadName)s %(name)s %(levelname)s "
"%(filename)-25s %(lineno)-5s "
"%(funcName)-25s : %(message)s")
logging.basicConfig(format=format_template,
filename=log_filename,
filemode='a',
level=logging.DEBUG)
if clear_log_file:
with open(log_filename, "w") as f:
f.write("asctime\t\t\t\t\tthreadName name levelname filename\
\tlineno\tfuncName\t\t\t\tmessage\n")
logging.getLogger("asyncio").setLevel(logging.WARNING)
logging.getLogger("matplotlib").setLevel(logging.WARNING)
def copy_config_files_to_test_directory(files: list, test_directory: str):
for file in files:
shutil.copy(file, test_directory + "/" + file)
def copy_log_files_to_test_directory(dir: str):
log_files = ["log/log_rx.log", "log/log_tx.log", "log/check_addr.log"]
for file in log_files:
shutil.copy(file, dir + "/" + time.strftime("%Y_%m_%d_%H_%M_%S_") +
file.replace("log/", ""))
# Running tests as sudo implies root permissions on created directories/files.
# This function sets the default permission mode to dirs/files in given path
# recursively.
def set_default_chmod_recurs(path):
for root, dirs, files in os.walk(path):
for d in dirs:
os.chmod(os.path.join(root, d), 0o0777)
for f in files:
os.chmod(os.path.join(root, f), 0o0777)
| [
"logging.basicConfig",
"logging.getLogger",
"time.strftime",
"os.path.join",
"os.getcwd",
"os.mkdir",
"shutil.copy",
"os.walk"
] | [((992, 1016), 'os.mkdir', 'os.mkdir', (['path'], {'mode': '(511)'}), '(path, mode=511)\n', (1000, 1016), False, 'import os\n'), ((1324, 1430), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'format_template', 'filename': 'log_filename', 'filemode': '"""a"""', 'level': 'logging.DEBUG'}), "(format=format_template, filename=log_filename, filemode\n ='a', level=logging.DEBUG)\n", (1343, 1430), False, 'import logging\n'), ((2450, 2463), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (2457, 2463), False, 'import os\n'), ((901, 935), 'time.strftime', 'time.strftime', (['"""%Y_%m_%d_%H_%M_%S"""'], {}), "('%Y_%m_%d_%H_%M_%S')\n", (914, 935), False, 'import time\n'), ((960, 971), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (969, 971), False, 'import os\n'), ((1918, 1964), 'shutil.copy', 'shutil.copy', (['file', "(test_directory + '/' + file)"], {}), "(file, test_directory + '/' + file)\n", (1929, 1964), False, 'import shutil\n'), ((1693, 1721), 'logging.getLogger', 'logging.getLogger', (['"""asyncio"""'], {}), "('asyncio')\n", (1710, 1721), False, 'import logging\n'), ((1752, 1783), 'logging.getLogger', 'logging.getLogger', (['"""matplotlib"""'], {}), "('matplotlib')\n", (1769, 1783), False, 'import logging\n'), ((2509, 2530), 'os.path.join', 'os.path.join', (['root', 'd'], {}), '(root, d)\n', (2521, 2530), False, 'import os\n'), ((2585, 2606), 'os.path.join', 'os.path.join', (['root', 'f'], {}), '(root, f)\n', (2597, 2606), False, 'import os\n'), ((2143, 2178), 'time.strftime', 'time.strftime', (['"""%Y_%m_%d_%H_%M_%S_"""'], {}), "('%Y_%m_%d_%H_%M_%S_')\n", (2156, 2178), False, 'import time\n')] |
import copy
def F(a):
x = copy.deepcopy(a)
# Face Rotation
a[3][6] = x[5][6]
a[3][7] = x[4][6]
a[3][8] = x[3][6]
a[4][6] = x[5][7]
a[4][8] = x[3][7]
a[5][6] = x[5][8]
a[5][7] = x[4][8]
a[5][8] = x[3][8]
#Side Rotation
a[2][6] = x[5][5]
a[2][7] = x[4][5]
a[2][8] = x[3][5]
a[3][9] = x[2][6]
a[4][9] = x[2][7]
a[5][9] = x[2][8]
a[6][6] = x[5][9]
a[6][7] = x[4][9]
a[6][8] = x[3][9]
a[5][5] = x[6][8]
a[4][5] = x[6][7]
a[3][5] = x[6][6]
def Fi(a):
x = copy.deepcopy(a)
# Face Rotation
a[3][6] = x[3][8]
a[3][7] = x[4][8]
a[3][8] = x[5][8]
a[4][6] = x[3][7]
a[4][8] = x[5][7]
a[5][6] = x[3][6]
a[5][7] = x[4][6]
a[5][8] = x[5][6]
# Side Rotation
a[5][5] = x[2][6]
a[4][5] = x[2][7]
a[3][5] = x[2][8]
a[2][6] = x[3][9]
a[2][7] = x[4][9]
a[2][8] = x[5][9]
a[5][9] = x[6][6]
a[4][9] = x[6][7]
a[3][9] = x[6][8]
a[6][8] = x[5][5]
a[6][7] = x[4][5]
a[6][6] = x[3][5]
def R(a):
x = copy.deepcopy(a)
# Side Rotation
a[3][0] = x[2][8]
a[4][0] = x[1][8]
a[5][0] = x[0][8]
a[8][8] = x[3][0]
a[7][8] = x[4][0]
a[6][8] = x[5][0]
a[3][8] = x[6][8]
a[4][8] = x[7][8]
a[5][8] = x[8][8]
a[0][8] = x[3][8]
a[1][8] = x[4][8]
a[2][8] = x[5][8]
# Face Rotation
a[3][11] = x[3][9]
a[4][11] = x[3][10]
a[5][11] = x[3][11]
a[3][10] = x[4][9]
a[5][10] = x[4][11]
a[3][9] = x[5][9]
a[4][9] = x[5][10]
a[5][9] = x[5][11]
def Ri(a):
x = copy.deepcopy(a)
# Face Rotation
a[3][9] = x[3][11]
a[3][10] = x[4][11]
a[3][11] = x[5][11]
a[4][9] = x[3][10]
a[4][11] = x[5][10]
a[5][9] = x[3][9]
a[5][10] = x[4][9]
a[5][11] = x[5][9]
# Side Rotation
a[2][8] = x[3][0]
a[1][8] = x[4][0]
a[0][8] = x[5][0]
a[3][0] = x[8][8]
a[4][0] = x[7][8]
a[5][0] = x[6][8]
a[6][8] = x[3][8]
a[7][8] = x[4][8]
a[8][8] = x[5][8]
a[3][8] = x[0][8]
a[4][8] = x[1][8]
a[5][8] = x[2][8]
def L(a):
x = copy.deepcopy(a)
# Face Rotation
a[3][3] = x[5][3]
a[3][4] = x[4][3]
a[3][5] = x[3][3]
a[4][3] = x[5][4]
a[4][5] = x[3][4]
a[5][3] = x[5][5]
a[5][4] = x[4][5]
a[5][5] = x[3][5]
# Side Rotation
a[0][6] = x[5][2]
a[1][6] = x[4][2]
a[2][6] = x[3][2]
a[3][6] = x[0][6]
a[4][6] = x[1][6]
a[5][6] = x[2][6]
a[8][6] = x[5][6]
a[7][6] = x[4][6]
a[6][6] = x[3][6]
a[3][2] = x[8][6]
a[4][2] = x[7][6]
a[5][2] = x[6][6]
def Li(a):
x = copy.deepcopy(a)
# Face Rotation
a[5][3] = x[3][3]
a[4][3] = x[3][4]
a[3][3] = x[3][5]
a[5][4] = x[4][3]
a[3][4] = x[4][5]
a[5][5] = x[5][3]
a[4][5] = x[5][4]
a[3][5] = x[5][5]
# Side Rotation
a[5][2] = x[0][6]
a[4][2] = x[1][6]
a[3][2] = x[2][6]
a[0][6] = x[3][6]
a[1][6] = x[4][6]
a[2][6] = x[5][6]
a[5][6] = x[8][6]
a[4][6] = x[7][6]
a[3][6] = x[6][6]
a[8][6] = x[3][2]
a[7][6] = x[4][2]
a[6][6] = x[5][2]
def U(a):
x = copy.deepcopy(a)
# Face Rotation
a[0][6] = x[2][6]
a[0][7] = x[1][6]
a[0][8] = x[0][6]
a[1][6] = x[2][7]
a[1][8] = x[0][7]
a[2][6] = x[2][8]
a[2][7] = x[1][8]
a[2][8] = x[0][8]
# Side Rotation
a[3][2] = x[3][5]
a[3][1] = x[3][4]
a[3][0] = x[3][3]
a[3][11] = x[3][2]
a[3][10] = x[3][1]
a[3][9] = x[3][0]
a[3][6] = x[3][9]
a[3][7] = x[3][10]
a[3][8] = x[3][11]
a[3][3] = x[3][6]
a[3][4] = x[3][7]
a[3][5] = x[3][8]
def Ui(a):
x = copy.deepcopy(a)
# Face Rotation
a[2][6] = x[0][6]
a[1][6] = x[0][7]
a[0][6] = x[0][8]
a[2][7] = x[1][6]
a[0][7] = x[1][8]
a[2][8] = x[2][6]
a[1][8] = x[2][7]
a[0][8] = x[2][8]
# Side Rotation
a[3][5] = x[3][2]
a[3][4] = x[3][1]
a[3][3] = x[3][0]
a[3][2] = x[3][11]
a[3][1] = x[3][10]
a[3][0] = x[3][9]
a[3][9] = x[3][6]
a[3][10] = x[3][7]
a[3][11] = x[3][8]
a[3][6] = x[3][3]
a[3][7] = x[3][4]
a[3][8] = x[3][5]
def D(a):
x = copy.deepcopy(a)
# Face Rotation
a[6][6] = x[8][6]
a[6][7] = x[7][6]
a[6][8] = x[6][6]
a[7][6] = x[8][7]
a[7][8] = x[6][7]
a[8][6] = x[8][8]
a[8][7] = x[7][8]
a[8][8] = x[6][8]
# Side Rotation
a[5][6] = x[5][3]
a[5][7] = x[5][4]
a[5][8] = x[5][5]
a[5][9] = x[5][6]
a[5][10] = x[5][7]
a[5][11] = x[5][8]
a[5][0] = x[5][9]
a[5][1] = x[5][10]
a[5][2] = x[5][11]
a[5][3] = x[5][0]
a[5][4] = x[5][1]
a[5][5] = x[5][2]
def Di(a):
x = copy.deepcopy(a)
# Face Rotation
a[8][6] = x[6][6]
a[7][6] = x[6][7]
a[6][6] = x[6][8]
a[8][7] = x[7][6]
a[6][7] = x[7][8]
a[8][8] = x[8][6]
a[7][8] = x[8][7]
a[6][8] = x[8][8]
# Side Rotation
a[5][3] = x[5][6]
a[5][4] = x[5][7]
a[5][5] = x[5][8]
a[5][6] = x[5][9]
a[5][7] = x[5][10]
a[5][8] = x[5][11]
a[5][9] = x[5][0]
a[5][10] = x[5][1]
a[5][11] = x[5][2]
a[5][0] = x[5][3]
a[5][1] = x[5][4]
a[5][2] = x[5][5]
def B(a):
x = copy.deepcopy(a)
# Face Rotation
a[3][0] = x[5][0]
a[3][1] = x[4][0]
a[3][2] = x[3][0]
a[4][0] = x[5][1]
a[4][2] = x[3][1]
a[5][0] = x[5][2]
a[5][1] = x[4][2]
a[5][2] = x[3][2]
# Side Rotation
a[0][8] = x[5][11]
a[0][7] = x[4][11]
a[0][6] = x[3][11]
a[3][3] = x[0][8]
a[4][3] = x[0][7]
a[5][3] = x[0][6]
a[8][8] = x[5][3]
a[8][7] = x[4][3]
a[8][6] = x[3][3]
a[3][11] = x[8][8]
a[4][11] = x[8][7]
a[5][11] = x[8][6]
def Bi(a):
x = copy.deepcopy(a)
#Face Rotation
a[5][0] = x[3][0]
a[4][0] = x[3][1]
a[3][0] = x[3][2]
a[5][1] = x[4][0]
a[3][1] = x[4][2]
a[5][2] = x[5][0]
a[4][2] = x[5][1]
a[3][2] = x[5][2]
# Side Rotation
a[5][11] = x[0][8]
a[4][11] = x[0][7]
a[3][11] = x[0][6]
a[0][8] = x[3][3]
a[0][7] = x[4][3]
a[0][6] = x[5][3]
a[5][3] = x[8][8]
a[4][3] = x[8][7]
a[3][3] = x[8][6]
a[8][8] = x[3][11]
a[8][7] = x[4][11]
a[8][6] = x[5][11]
def HR(a): #Middle row horizontally to the right
x = copy.deepcopy(a)
a[4][0] = x[4][9]
a[4][1] = x[4][10]
a[4][2] = x[4][11]
a[4][3] = x[4][0]
a[4][4] = x[4][1]
a[4][5] = x[4][2]
a[4][6] = x[4][3]
a[4][7] = x[4][4]
a[4][8] = x[4][5]
a[4][9] = x[4][6]
a[4][10] = x[4][7]
a[4][11] = x[4][8]
def HL(a): #Middle row horizontally to the left
x = copy.deepcopy(a)
a[4][9] = x[4][0]
a[4][10] = x[4][1]
a[4][11] = x[4][2]
a[4][0] = x[4][3]
a[4][1] = x[4][4]
a[4][2] = x[4][5]
a[4][3] = x[4][6]
a[4][4] = x[4][7]
a[4][5] = x[4][8]
a[4][6] = x[4][9]
a[4][7] = x[4][10]
a[4][8] = x[4][11]
def VU(a): #Middle row vertically up
x = copy.deepcopy(a)
a[0][7] = x[3][7]
a[1][7] = x[4][7]
a[2][7] = x[5][7]
a[3][7] = x[6][7]
a[4][7] = x[7][7]
a[5][7] = x[8][7]
a[6][7] = x[5][1]
a[7][7] = x[4][1]
a[8][7] = x[3][1]
a[5][1] = x[0][7]
a[4][1] = x[1][7]
a[3][1] = x[2][7]
def VD(a): #Middle row vertically down
x = copy.deepcopy(a)
a[3][7] = x[0][7]
a[4][7] = x[1][7]
a[5][7] = x[2][7]
a[6][7] = x[3][7]
a[7][7] = x[4][7]
a[8][7] = x[5][7]
a[5][1] = x[6][7]
a[4][1] = x[7][7]
a[3][1] = x[8][7]
a[0][7] = x[5][1]
a[1][7] = x[4][1]
a[2][7] = x[3][1]
| [
"copy.deepcopy"
] | [((31, 47), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (44, 47), False, 'import copy\n'), ((547, 563), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (560, 563), False, 'import copy\n'), ((1063, 1079), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (1076, 1079), False, 'import copy\n'), ((1590, 1606), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (1603, 1606), False, 'import copy\n'), ((2116, 2132), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (2129, 2132), False, 'import copy\n'), ((2633, 2649), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (2646, 2649), False, 'import copy\n'), ((3149, 3165), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (3162, 3165), False, 'import copy\n'), ((3670, 3686), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (3683, 3686), False, 'import copy\n'), ((4190, 4206), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (4203, 4206), False, 'import copy\n'), ((4711, 4727), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (4724, 4727), False, 'import copy\n'), ((5231, 5247), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (5244, 5247), False, 'import copy\n'), ((5754, 5770), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (5767, 5770), False, 'import copy\n'), ((6314, 6330), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (6327, 6330), False, 'import copy\n'), ((6656, 6672), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (6669, 6672), False, 'import copy\n'), ((6987, 7003), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (7000, 7003), False, 'import copy\n'), ((7316, 7332), 'copy.deepcopy', 'copy.deepcopy', (['a'], {}), '(a)\n', (7329, 7332), False, 'import copy\n')] |
import asyncio
from couchbase.asynchronous import AsyncSearchResult
from couchbase.asynchronous import AsyncAnalyticsResult
from .fixtures import asynct, AioTestCase
from couchbase.exceptions import CouchbaseException, SearchException, NotSupportedException
from unittest import SkipTest
import couchbase.search as SEARCH
class CouchbaseBeerTest(AioTestCase):
def setUp(self, **kwargs):
try:
return super(CouchbaseBeerTest, self).setUp(
bucket='beer-sample', **kwargs)
except CouchbaseException:
raise SkipTest("Need 'beer-sample' bucket for this")
class CouchbaseBeerKVTest(CouchbaseBeerTest):
def setUp(self):
super(CouchbaseBeerKVTest, self).setUp()
@asynct
@asyncio.coroutine
def test_get_data(self):
connargs = self.make_connargs(bucket='beer-sample')
beer_default_collection = self.gen_collection(**connargs)
yield from (beer_default_collection.on_connect() or asyncio.sleep(0.01))
data = yield from beer_default_collection.get('21st_amendment_brewery_cafe')
self.assertEqual("21st Amendment Brewery Cafe", data.content["name"])
class CouchbaseBeerViewTest(CouchbaseBeerTest):
def setUp(self):
super(CouchbaseBeerViewTest, self).setUp(type='Bucket')
@asynct
@asyncio.coroutine
def test_query(self):
beer_bucket = self.gen_cluster(
**self.make_connargs()).bucket('beer-sample')
yield from (beer_bucket.on_connect() or asyncio.sleep(0.01))
viewiter = beer_bucket.view_query("beer", "brewery_beers", limit=10)
yield from viewiter.future
count = len(list(viewiter))
self.assertEqual(count, 10)
class CouchbaseDefaultTestKV(AioTestCase):
@asynct
@asyncio.coroutine
def test_upsert(self):
import uuid
expected = str(uuid.uuid4())
default_collection = self.gen_collection(**self.make_connargs())
yield from (default_collection.on_connect() or asyncio.sleep(0.01))
yield from default_collection.upsert('hello', {"key": expected})
obtained = yield from default_collection.get('hello')
self.assertEqual({"key": expected}, obtained.content)
class AIOClusterTest(AioTestCase):
def setUp(self, **kwargs):
super(AIOClusterTest, self).setUp(**kwargs)
@asynct
@asyncio.coroutine
def test_n1ql(self):
cluster = self.gen_cluster(**self.make_connargs())
yield from (cluster.on_connect() or asyncio.sleep(0.01))
it = cluster.query(self.query_props.statement)
yield from it.future
data = list(it)
self.assertEqual(self.query_props.rowcount, len(data))
@asynct
@asyncio.coroutine
def test_search(self # type: Base
):
cluster = self.gen_cluster(**self.make_connargs())
yield from (cluster.on_connect() or asyncio.sleep(0.01))
try:
it = cluster.search_query("beer-search", SEARCH.TermQuery("category"),
facets={'fred': SEARCH.TermFacet('category', 10)})
yield from it.future
data = list(it)
self.assertIsInstance(it, AsyncSearchResult)
self.assertEqual(10, len(data))
except SearchException as e:
if isinstance(e.inner_cause,
NotSupportedException) and self.is_mock:
raise SkipTest("Not supported")
class AnalyticsTest(AioTestCase):
def testBatchedAnalytics(self # type: Base
):
cluster = self.gen_cluster(**self.make_connargs())
yield from (cluster.on_connect() or asyncio.sleep(0.01))
it = cluster.analytics_query(
"SELECT * FROM `{}` LIMIT 1".format(self.dataset_name))
yield from it.future
self.assertIsInstance(it, AsyncAnalyticsResult)
self.assertEqual(1, len(it.rows()))
| [
"uuid.uuid4",
"couchbase.search.TermFacet",
"unittest.SkipTest",
"asyncio.sleep",
"couchbase.search.TermQuery"
] | [((1870, 1882), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1880, 1882), False, 'import uuid\n'), ((565, 611), 'unittest.SkipTest', 'SkipTest', (['"""Need \'beer-sample\' bucket for this"""'], {}), '("Need \'beer-sample\' bucket for this")\n', (573, 611), False, 'from unittest import SkipTest\n'), ((982, 1001), 'asyncio.sleep', 'asyncio.sleep', (['(0.01)'], {}), '(0.01)\n', (995, 1001), False, 'import asyncio\n'), ((1512, 1531), 'asyncio.sleep', 'asyncio.sleep', (['(0.01)'], {}), '(0.01)\n', (1525, 1531), False, 'import asyncio\n'), ((2013, 2032), 'asyncio.sleep', 'asyncio.sleep', (['(0.01)'], {}), '(0.01)\n', (2026, 2032), False, 'import asyncio\n'), ((2518, 2537), 'asyncio.sleep', 'asyncio.sleep', (['(0.01)'], {}), '(0.01)\n', (2531, 2537), False, 'import asyncio\n'), ((2913, 2932), 'asyncio.sleep', 'asyncio.sleep', (['(0.01)'], {}), '(0.01)\n', (2926, 2932), False, 'import asyncio\n'), ((3000, 3028), 'couchbase.search.TermQuery', 'SEARCH.TermQuery', (['"""category"""'], {}), "('category')\n", (3016, 3028), True, 'import couchbase.search as SEARCH\n'), ((3693, 3712), 'asyncio.sleep', 'asyncio.sleep', (['(0.01)'], {}), '(0.01)\n', (3706, 3712), False, 'import asyncio\n'), ((3448, 3473), 'unittest.SkipTest', 'SkipTest', (['"""Not supported"""'], {}), "('Not supported')\n", (3456, 3473), False, 'from unittest import SkipTest\n'), ((3084, 3116), 'couchbase.search.TermFacet', 'SEARCH.TermFacet', (['"""category"""', '(10)'], {}), "('category', 10)\n", (3100, 3116), True, 'import couchbase.search as SEARCH\n')] |
""" A generic IOS-XE connection implementation.
It covers many IOS-XE platforms, including ASR and ISR.
"""
__author__ = "<NAME> <<EMAIL>>"
from unicon.plugins.generic import ServiceList, HAServiceList
from unicon.bases.routers.connection import BaseSingleRpConnection
from unicon.plugins.iosxe.statemachine import IosXESingleRpStateMachine
from unicon.plugins.iosxe.statemachine import IosXEDualRpStateMachine
from unicon.plugins.generic import GenericSingleRpConnectionProvider,\
GenericDualRPConnection
from unicon.plugins.iosxe.settings import IosXESettings
from unicon.plugins.iosxe import service_implementation as svc
class IosXEServiceList(ServiceList):
def __init__(self):
super().__init__()
self.config = svc.Config
self.configure = svc.Configure
self.execute = svc.Execute
self.ping = svc.Ping
self.traceroute = svc.Traceroute
self.bash_console = svc.BashService
self.copy = svc.Copy
self.reload = svc.Reload
self.rommon = svc.Rommon
self.tclsh = svc.Tclsh
class HAIosXEServiceList(HAServiceList):
def __init__(self):
super().__init__()
self.config = svc.HAConfig
self.configure = svc.HAConfigure
self.execute = svc.HAExecute
self.reload = svc.HAReload
self.switchover = svc.HASwitchover
self.ping = svc.Ping
self.bash_console = svc.BashService
self.traceroute = svc.Traceroute
self.copy = svc.Copy
self.reset_standby_rp = svc.ResetStandbyRP
self.rommon = svc.HARommon
self.tclsh = svc.Tclsh
class IosXESingleRpConnection(BaseSingleRpConnection):
os = 'iosxe'
platform = None
chassis_type = 'single_rp'
state_machine_class = IosXESingleRpStateMachine
connection_provider_class = GenericSingleRpConnectionProvider
subcommand_list = IosXEServiceList
settings = IosXESettings()
class IosXEDualRPConnection(GenericDualRPConnection):
os = 'iosxe'
platform = None
chassis_type = 'dual_rp'
subcommand_list = HAIosXEServiceList
state_machine_class = IosXEDualRpStateMachine
settings = IosXESettings()
| [
"unicon.plugins.iosxe.settings.IosXESettings"
] | [((1914, 1929), 'unicon.plugins.iosxe.settings.IosXESettings', 'IosXESettings', ([], {}), '()\n', (1927, 1929), False, 'from unicon.plugins.iosxe.settings import IosXESettings\n'), ((2158, 2173), 'unicon.plugins.iosxe.settings.IosXESettings', 'IosXESettings', ([], {}), '()\n', (2171, 2173), False, 'from unicon.plugins.iosxe.settings import IosXESettings\n')] |
from __future__ import print_function
import re
import time
import curses
import bisect
try:
from queue import Queue
from queue import Empty as QueueEmpty
except ImportError:
from Queue import Queue
from Queue import Empty as QueueEmpty
import can
from .. import database
from .utils import format_message
class QuitError(Exception):
pass
class Monitor(can.Listener):
def __init__(self, stdscr, args):
self._stdscr = stdscr
self._dbase = database.load_file(args.database,
encoding=args.encoding,
frame_id_mask=args.frame_id_mask,
strict=not args.no_strict)
self._filtered_sorted_message_names = []
self._filter = ''
self._compiled_filter = None
self._formatted_messages = {}
self._playing = True
self._modified = True
self._show_filter = False
self._queue = Queue()
self._nrows, self._ncols = stdscr.getmaxyx()
self._received = 0
self._discarded = 0
self._basetime = None
stdscr.nodelay(True)
curses.use_default_colors()
curses.curs_set(False)
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)
bus = self.create_bus(args)
self._notifier = can.Notifier(bus, [self])
def create_bus(self, args):
kwargs = {}
if args.bit_rate is not None:
kwargs['bitrate'] = int(args.bit_rate)
try:
return can.Bus(bustype=args.bus_type,
channel=args.channel,
**kwargs)
except:
raise Exception(
"Failed to create CAN bus with bustype='{}' and "
"channel='{}'.".format(args.bus_type,
args.channel))
def run(self):
while True:
modified = self.update()
if modified:
self.redraw()
try:
self.process_user_input()
except QuitError:
break
time.sleep(0.05)
def redraw(self):
# Clear the screen.
self._stdscr.clear()
# Draw everything.
self.draw_stats(0)
self.draw_title(1)
row = 2
for name in self._filtered_sorted_message_names:
for line in self._formatted_messages[name]:
self.addstr(row, 0, line)
row += 1
if row > self._nrows - 2:
break
self.draw_menu(self._nrows - 1)
# Refresh the screen.
self._stdscr.refresh()
def draw_stats(self, row):
self.addstr(row, 0, 'Received: {}, Discarded: {}, Errors: 0'.format(
self._received,
self._discarded))
def draw_title(self, row):
self.addstr_color(row,
0,
self.stretch(' TIMESTAMP MESSAGE'),
curses.color_pair(1))
def draw_menu(self, row):
if self._show_filter:
text = 'Filter: ' + self._filter
else:
text = 'q: Quit, f: Filter, p: Play/Pause, r: Reset'
self.addstr_color(row,
0,
self.stretch(text),
curses.color_pair(2))
if self._show_filter:
self._stdscr.move(row, len(text))
def addstr(self, row, col, text):
try:
self._stdscr.addstr(row, col, text)
except curses.error:
pass
def addstr_color(self, row, col, text, color):
try:
self._stdscr.addstr(row, col, text, color)
except curses.error:
pass
def stretch(self, text):
return text + ' ' * (self._ncols - len(text))
def process_user_input(self):
try:
key = self._stdscr.getkey()
except curses.error:
return
if self._show_filter:
self.process_user_input_filter(key)
else:
self.process_user_input_menu(key)
def process_user_input_menu(self, key):
if key == 'q':
raise QuitError()
elif key == 'p':
self._playing = not self._playing
elif key == 'r':
self._playing = True
self._filtered_sorted_message_names = []
self._formatted_messages = {}
self._received = 0
self._discarded = 0
self._basetime = None
self._filter = ''
self._compiled_filter = None
self._modified = True
while not self._queue.empty():
self._queue.get()
elif key in ['f', '/']:
self._show_filter = True
self._modified = True
curses.curs_set(True)
def compile_filter(self):
try:
self._compiled_filter = re.compile(self._filter)
except:
self._compiled_filter = None
def process_user_input_filter(self, key):
if key == '\n':
self._show_filter = False
curses.curs_set(False)
elif key in ['KEY_BACKSPACE', '\b']:
self._filter = self._filter[:-1]
else:
self._filter += key
self.compile_filter()
self._filtered_sorted_message_names = []
for name in self._formatted_messages:
self.insort_filtered(name)
self._modified = True
def try_update_message(self):
message = self._queue.get_nowait()
frame_id = message.arbitration_id
data = message.data
timestamp = message.timestamp
if self._basetime is None:
self._basetime = timestamp
timestamp -= self._basetime
self._received += 1
try:
message = self._dbase.get_message_by_frame_id(frame_id)
except KeyError:
self._discarded += 1
return
if len(data) != message.length:
self._discarded += 1
return
formatted = format_message(message, data, True, False)
lines = formatted.splitlines()
formatted = ['{:12.3f} {}'.format(timestamp, lines[1])]
formatted += [14 * ' ' + line for line in lines[2:]]
self._formatted_messages[message.name] = formatted
if message.name not in self._filtered_sorted_message_names:
self.insort_filtered(message.name)
def update_messages(self):
modified = False
try:
while True:
self.try_update_message()
modified = True
except QueueEmpty:
pass
return modified
def update(self):
if self._playing:
modified = self.update_messages()
else:
modified = False
if self._modified:
self._modified = False
modified = True
if curses.is_term_resized(self._nrows, self._ncols):
self._nrows, self._ncols = self._stdscr.getmaxyx()
modified = True
return modified
def insort_filtered(self, name):
if self._compiled_filter is None or self._compiled_filter.search(name):
bisect.insort(self._filtered_sorted_message_names,
name)
def on_message_received(self, msg):
self._queue.put(msg)
def _do_monitor(args):
def monitor(stdscr):
Monitor(stdscr, args).run()
try:
curses.wrapper(monitor)
except KeyboardInterrupt:
pass
def add_subparser(subparsers):
monitor_parser = subparsers.add_parser(
'monitor',
description='Monitor CAN bus traffic in a text based user interface.')
monitor_parser.add_argument(
'-e', '--encoding',
default='utf-8',
help='File encoding (default: utf-8).')
monitor_parser.add_argument(
'--no-strict',
action='store_true',
help='Skip database consistency checks.')
monitor_parser.add_argument(
'-m', '--frame-id-mask',
type=lambda x: int(x, 0),
help=('Only compare selected frame id bits to find the message in the '
'database. By default the received and database frame ids must '
'be equal for a match.'))
monitor_parser.add_argument(
'-b', '--bus-type',
default='socketcan',
help='Python CAN bus type (default: socketcan).')
monitor_parser.add_argument(
'-c', '--channel',
default='vcan0',
help='Python CAN bus channel (default: vcan0).')
monitor_parser.add_argument(
'-B', '--bit-rate',
help='Python CAN bus bit rate.')
monitor_parser.add_argument(
'database',
help='Database file.')
monitor_parser.set_defaults(func=_do_monitor)
| [
"curses.color_pair",
"curses.wrapper",
"re.compile",
"curses.init_pair",
"curses.is_term_resized",
"time.sleep",
"curses.curs_set",
"curses.use_default_colors",
"can.Bus",
"bisect.insort",
"can.Notifier",
"Queue.Queue"
] | [((992, 999), 'Queue.Queue', 'Queue', ([], {}), '()\n', (997, 999), False, 'from Queue import Queue\n'), ((1176, 1203), 'curses.use_default_colors', 'curses.use_default_colors', ([], {}), '()\n', (1201, 1203), False, 'import curses\n'), ((1212, 1234), 'curses.curs_set', 'curses.curs_set', (['(False)'], {}), '(False)\n', (1227, 1234), False, 'import curses\n'), ((1243, 1302), 'curses.init_pair', 'curses.init_pair', (['(1)', 'curses.COLOR_BLACK', 'curses.COLOR_GREEN'], {}), '(1, curses.COLOR_BLACK, curses.COLOR_GREEN)\n', (1259, 1302), False, 'import curses\n'), ((1311, 1369), 'curses.init_pair', 'curses.init_pair', (['(2)', 'curses.COLOR_BLACK', 'curses.COLOR_CYAN'], {}), '(2, curses.COLOR_BLACK, curses.COLOR_CYAN)\n', (1327, 1369), False, 'import curses\n'), ((1432, 1457), 'can.Notifier', 'can.Notifier', (['bus', '[self]'], {}), '(bus, [self])\n', (1444, 1457), False, 'import can\n'), ((7076, 7124), 'curses.is_term_resized', 'curses.is_term_resized', (['self._nrows', 'self._ncols'], {}), '(self._nrows, self._ncols)\n', (7098, 7124), False, 'import curses\n'), ((7629, 7652), 'curses.wrapper', 'curses.wrapper', (['monitor'], {}), '(monitor)\n', (7643, 7652), False, 'import curses\n'), ((1634, 1696), 'can.Bus', 'can.Bus', ([], {'bustype': 'args.bus_type', 'channel': 'args.channel'}), '(bustype=args.bus_type, channel=args.channel, **kwargs)\n', (1641, 1696), False, 'import can\n'), ((2228, 2244), 'time.sleep', 'time.sleep', (['(0.05)'], {}), '(0.05)\n', (2238, 2244), False, 'import time\n'), ((3127, 3147), 'curses.color_pair', 'curses.color_pair', (['(1)'], {}), '(1)\n', (3144, 3147), False, 'import curses\n'), ((3467, 3487), 'curses.color_pair', 'curses.color_pair', (['(2)'], {}), '(2)\n', (3484, 3487), False, 'import curses\n'), ((5056, 5080), 're.compile', 're.compile', (['self._filter'], {}), '(self._filter)\n', (5066, 5080), False, 'import re\n'), ((5259, 5281), 'curses.curs_set', 'curses.curs_set', (['(False)'], {}), '(False)\n', (5274, 5281), False, 'import curses\n'), ((7372, 7428), 'bisect.insort', 'bisect.insort', (['self._filtered_sorted_message_names', 'name'], {}), '(self._filtered_sorted_message_names, name)\n', (7385, 7428), False, 'import bisect\n'), ((4954, 4975), 'curses.curs_set', 'curses.curs_set', (['(True)'], {}), '(True)\n', (4969, 4975), False, 'import curses\n')] |
from django.core.management import BaseCommand
from django.db import connection
class Command(BaseCommand):
"""
pipenv run ./manage.py cleardb
"""
help = "Clear the database"
def handle(self, *args, **options):
print("\nDropping all database tables..\n")
with connection.cursor() as cursor:
sql = """DO $$ DECLARE r RECORD;BEGIN FOR r IN (SELECT tablename FROM
pg_catalog.pg_tables WHERE schemaname = 'public\' AND tableowner != 'rdsadmin')
LOOP EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';END LOOP;END $$;"""
cursor.execute(sql)
| [
"django.db.connection.cursor"
] | [((300, 319), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (317, 319), False, 'from django.db import connection\n')] |
from typing import Dict
import torch
from torchtyping import TensorType
from typing import Dict, Optional
from tqdm import tqdm
from typeguard import typechecked
"""
# PCA rationale:
# check for the constraints , if small, do nothing
# if needed, project the result onto the constraints using the projection parameters
# pca_reproject(x_after_step, self.proj_params) to go back to plausible values (if epsilon = 0)
# if epsilon non-zero. project onto all evecs (discarded and kept). these are all orthogonal.
# you go one by one. if your in the kept eigenvecs, do nothing. if you're in discarded evecs, you're outside constraint space
# you have a sclar proj per dim. so in those held out dims, you manually set the projs to be epsilon instead of that high projection that you may encounter.
# you modify all the projections onto the discarded evecs. you have a vector which is num_obs x num_evecs. this is the representation of data in the PCA coordinate basis
# then, you modify that representation, and you send it back to the original space using the transpose of the evecs.
# Temporal rationale: want x_t - x_t-1 to be small. compute the difference per timepoint. choose one direction, say forward. you have two points in
# you have 2 points in 2d space. the difference vector is the direction. compute the norm. if norm > epsilon, rescale it so norm is equal to epsilon. diff/epsilon -- now you have a direction and a step size. you define x_t += x_t-1 + diff/epsilon.
# the next time point has to be inside a ball with radius epsilon. if it's outside, you project onto the exterior of that ball. if it's inside, keep it where it is.
# the result will be different if you start from the end or from the beggining.
"""
def MSE(preds: TensorType["num_samples", "num_keypoints",2],
gt: TensorType["num_samples", "num_keypoints",2]):
bp_error = torch.linalg.norm(preds - gt, dim=2) # error per keypoint-frame
average_error = torch.nanmean(bp_error, dim=1) # mean over keypoints
return average_error
@typechecked
class ProjectedGD(object):
""" projected gradient descent on an L2 ball subject to constraints"""
def __init__(
self,
data: TensorType["num_obs", "obs_dim"] = None,
ground_truth: Optional[TensorType["num_obs", "obs_dim"]] = None,
confidences: Optional[TensorType["num_obs", "num_keypoints"]] = None,
proj_params: dict = None,
lr: Optional[float] = None,
max_iter: int = 1000,
tol: float = 1e-5,
verbose: bool = False,
lr_decay_factor: float = 0.25,
):
"""assume you get only the bodyparts of interest for this, irrelevant cols get filtered externally"""
self.max_iter = max_iter
self.tol = tol
self.verbose = verbose
self.data: TensorType["num_samples", "num_keypoints", 2] = data.reshape(data.shape[0], -1, 2)
self.ground_truth: TensorType["num_samples", "num_keypoints", 2] = ground_truth.reshape(ground_truth.shape[0], -1, 2)
self.proj_params = proj_params
self.optimized_preds = self.data.detach().clone() # + torch.randn_like(data)*1e-4 # torch.nn.parameter.Parameter(data=data.detach().clone())
self.x_list = []
self.lr_list = []
self.error_list = []
self.confidences = 1.0
self.lr_decay_factor = lr_decay_factor
if confidences is not None:
self.confidences: TensorType["num_obs", "num_keypoints",1] = confidences.unsqueeze(2)
self.confidences = torch.clamp(confidences, min=0.0, max=1.0)
if lr is not None:
self.lr = lr
else:
self.lr = self.initialize_alpha()
# TODO: modify norm to bo over the last dimension. have num_keypoints norms per sample.
# TODO: everything else can remain in this shape?
# When conf comes in, reshape it similarly.
# currently this is not used.
@staticmethod
def l2_grad(
diffs: TensorType["num_samples", "num_keypoints", 2], scalar: float = 1.0
) -> TensorType["num_samples", "num_keypoints", 2]:
# TODO: test
if torch.allclose(diffs, torch.zeros_like(diffs)):
# don't divide by zero
return diffs
else:
norm: TensorType["num_samples", "num_keypoints",1] = torch.linalg.norm(diffs, dim=2, keepdim=True)
grad = diffs * scalar * (1.0 / norm)
return grad
def grad_step(
self, x_curr: TensorType["num_samples", "num_keypoints", 2]
) -> TensorType["num_samples", "num_keypoints", 2]:
norm: TensorType["num_samples", "num_keypoints", 1] = torch.linalg.norm(x_curr-self.data, dim=2, keepdim=True)
step: TensorType["num_samples", "num_keypoints", 1] = (self.lr * self.confidences) / (norm + 1e-8)
step = torch.clamp(step, min=0.0, max=1.0)
x_after_step = (1-step)*x_curr + step*self.data
return x_after_step
# standard way below
# return x_curr - self.lr * self.l2_grad(x_curr - self.data)
def project(
self, x_after_step: TensorType["num_samples", "num_keypoints", 2]
) -> TensorType["num_samples", "num_keypoints", 2]:
# reshape
x_after_step = x_after_step.reshape(x_after_step.shape[0],-1)
# reproject
reprojected = self.proj_params["pca_singleview"].reproject(x_after_step)
# reshape back
reprojected = reprojected.reshape(x_after_step.shape[0], -1, 2)
return reprojected
def step(
self, x_curr: TensorType["num_samples", "num_keypoints", 2]
) -> TensorType["num_samples", "num_keypoints", 2]:
x_after_step = self.grad_step(x_curr=x_curr) # gradient descent on the l2 norm objective
x_after_projection = self.project(x_after_step=x_after_step) # project the current x onto the constraints, get plausible x
return x_after_projection
def initialize_alpha(self) -> TensorType[(), float]:
# project
projected = self.project(x_after_step=self.data)
# compute the difference
diff = projected - self.data # X_0 - Y
# compute the norm and divide by confidences
alpha = torch.max(torch.norm(diff, dim=2, keepdim=True) / self.confidences)
return alpha
def fit(self) -> TensorType["num_samples", "num_keypoints", 2]:
# TODO: measure RMSE per iteration, run for longer, understand whar it's doing
x_curr = self.optimized_preds.clone()
# project and initialize step size.
for i in tqdm(range(self.max_iter)):
# projected gradient descent step
x_new = self.step(x_curr)
if self.verbose:
print(f"iteration {i}")
print(f"x_curr: {x_curr}")
print(f"x_new: {x_new}")
if torch.allclose(x_curr, x_new, atol=self.tol):
# if no change, you're clamped at step=1.0, too big, decrease and move away from data
self.lr = self.lr * self.lr_decay_factor
x_curr = x_new.clone()
self.error_list.append(MSE(x_curr, self.ground_truth))
self.x_list.append(x_new) # record the new x
self.lr_list.append(self.lr) # record the new step size
self.optimized_preds = x_new
return self.optimized_preds
| [
"torch.linalg.norm",
"torch.norm",
"torch.allclose",
"torch.zeros_like",
"torch.nanmean",
"torch.clamp"
] | [((1953, 1989), 'torch.linalg.norm', 'torch.linalg.norm', (['(preds - gt)'], {'dim': '(2)'}), '(preds - gt, dim=2)\n', (1970, 1989), False, 'import torch\n'), ((2037, 2067), 'torch.nanmean', 'torch.nanmean', (['bp_error'], {'dim': '(1)'}), '(bp_error, dim=1)\n', (2050, 2067), False, 'import torch\n'), ((4737, 4795), 'torch.linalg.norm', 'torch.linalg.norm', (['(x_curr - self.data)'], {'dim': '(2)', 'keepdim': '(True)'}), '(x_curr - self.data, dim=2, keepdim=True)\n', (4754, 4795), False, 'import torch\n'), ((4916, 4951), 'torch.clamp', 'torch.clamp', (['step'], {'min': '(0.0)', 'max': '(1.0)'}), '(step, min=0.0, max=1.0)\n', (4927, 4951), False, 'import torch\n'), ((3612, 3654), 'torch.clamp', 'torch.clamp', (['confidences'], {'min': '(0.0)', 'max': '(1.0)'}), '(confidences, min=0.0, max=1.0)\n', (3623, 3654), False, 'import torch\n'), ((4246, 4269), 'torch.zeros_like', 'torch.zeros_like', (['diffs'], {}), '(diffs)\n', (4262, 4269), False, 'import torch\n'), ((4411, 4456), 'torch.linalg.norm', 'torch.linalg.norm', (['diffs'], {'dim': '(2)', 'keepdim': '(True)'}), '(diffs, dim=2, keepdim=True)\n', (4428, 4456), False, 'import torch\n'), ((6926, 6970), 'torch.allclose', 'torch.allclose', (['x_curr', 'x_new'], {'atol': 'self.tol'}), '(x_curr, x_new, atol=self.tol)\n', (6940, 6970), False, 'import torch\n'), ((6299, 6336), 'torch.norm', 'torch.norm', (['diff'], {'dim': '(2)', 'keepdim': '(True)'}), '(diff, dim=2, keepdim=True)\n', (6309, 6336), False, 'import torch\n')] |
#!/usr/bin/python3 -u
from __future__ import print_function
import json
import optparse
import subprocess
import sys
parser = optparse.OptionParser()
parser.add_option("--buck-test-info")
parser.add_option("--jobs", type=int)
(options, args) = parser.parse_args()
with open(options.buck_test_info) as f:
test_infos = json.load(f)
print(test_infos[0]["additional_coverage_targets"][0])
| [
"json.load",
"optparse.OptionParser"
] | [((130, 153), 'optparse.OptionParser', 'optparse.OptionParser', ([], {}), '()\n', (151, 153), False, 'import optparse\n'), ((327, 339), 'json.load', 'json.load', (['f'], {}), '(f)\n', (336, 339), False, 'import json\n')] |
#
# The Python Imaging Library
# $Id$
#
# JPEG2000 file handling
#
# History:
# 2014-03-12 ajh Created
#
# Copyright (c) 2014 Coriolis Systems Limited
# Copyright (c) 2014 <NAME>
#
# See the README file for information on usage and redistribution.
#
__version__ = "0.1"
from PIL import Image, ImageFile
import struct
import os
import io
def _parse_codestream(fp):
"""Parse the JPEG 2000 codestream to extract the size and component
count from the SIZ marker segment, returning a PIL (size, mode) tuple."""
hdr = fp.read(2)
lsiz = struct.unpack('>H', hdr)[0]
siz = hdr + fp.read(lsiz - 2)
lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, xtsiz, ytsiz, \
xtosiz, ytosiz, csiz \
= struct.unpack('>HHIIIIIIIIH', siz[:38])
ssiz = [None]*csiz
xrsiz = [None]*csiz
yrsiz = [None]*csiz
for i in range(csiz):
ssiz[i], xrsiz[i], yrsiz[i] \
= struct.unpack('>BBB', siz[36 + 3 * i:39 + 3 * i])
size = (xsiz - xosiz, ysiz - yosiz)
if csiz == 1:
if (yrsiz[0] & 0x7f) > 8:
mode = 'I;16'
else:
mode = 'L'
elif csiz == 2:
mode = 'LA'
elif csiz == 3:
mode = 'RGB'
elif csiz == 4:
mode = 'RGBA'
else:
mode = None
return (size, mode)
def _parse_jp2_header(fp):
"""Parse the JP2 header box to extract size, component count and
color space information, returning a PIL (size, mode) tuple."""
# Find the JP2 header box
header = None
while True:
lbox, tbox = struct.unpack('>I4s', fp.read(8))
if lbox == 1:
lbox = struct.unpack('>Q', fp.read(8))[0]
hlen = 16
else:
hlen = 8
if tbox == b'jp2h':
header = fp.read(lbox - hlen)
break
else:
fp.seek(lbox - hlen, os.SEEK_CUR)
if header is None:
raise SyntaxError('could not find JP2 header')
size = None
mode = None
bpc = None
hio = io.BytesIO(header)
while True:
lbox, tbox = struct.unpack('>I4s', hio.read(8))
if lbox == 1:
lbox = struct.unpack('>Q', hio.read(8))[0]
hlen = 16
else:
hlen = 8
content = hio.read(lbox - hlen)
if tbox == b'ihdr':
height, width, nc, bpc, c, unkc, ipr \
= struct.unpack('>IIHBBBB', content)
size = (width, height)
if unkc:
if nc == 1 and (bpc & 0x7f) > 8:
mode = 'I;16'
elif nc == 1:
mode = 'L'
elif nc == 2:
mode = 'LA'
elif nc == 3:
mode = 'RGB'
elif nc == 4:
mode = 'RGBA'
break
elif tbox == b'colr':
meth, prec, approx = struct.unpack('>BBB', content[:3])
if meth == 1:
cs = struct.unpack('>I', content[3:7])[0]
if cs == 16: # sRGB
if nc == 1 and (bpc & 0x7f) > 8:
mode = 'I;16'
elif nc == 1:
mode = 'L'
elif nc == 3:
mode = 'RGB'
elif nc == 4:
mode = 'RGBA'
break
elif cs == 17: # grayscale
if nc == 1 and (bpc & 0x7f) > 8:
mode = 'I;16'
elif nc == 1:
mode = 'L'
elif nc == 2:
mode = 'LA'
break
elif cs == 18: # sYCC
if nc == 3:
mode = 'RGB'
elif nc == 4:
mode = 'RGBA'
break
return (size, mode)
##
# Image plugin for JPEG2000 images.
class Jpeg2KImageFile(ImageFile.ImageFile):
format = "JPEG2000"
format_description = "JPEG 2000 (ISO 15444)"
def _open(self):
sig = self.fp.read(4)
if sig == b'\xff\x4f\xff\x51':
self.codec = "j2k"
self.size, self.mode = _parse_codestream(self.fp)
else:
sig = sig + self.fp.read(8)
if sig == b'\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a':
self.codec = "jp2"
self.size, self.mode = _parse_jp2_header(self.fp)
else:
raise SyntaxError('not a JPEG 2000 file')
if self.size is None or self.mode is None:
raise SyntaxError('unable to determine size/mode')
self.reduce = 0
self.layers = 0
fd = -1
length = -1
try:
fd = self.fp.fileno()
length = os.fstat(fd).st_size
except:
fd = -1
try:
pos = self.fp.tell()
self.fp.seek(0, 2)
length = self.fp.tell()
self.fp.seek(pos, 0)
except:
length = -1
self.tile = [('jpeg2k', (0, 0) + self.size, 0,
(self.codec, self.reduce, self.layers, fd, length))]
def load(self):
if self.reduce:
power = 1 << self.reduce
adjust = power >> 1
self.size = (int((self.size[0] + adjust) / power),
int((self.size[1] + adjust) / power))
if self.tile:
# Update the reduce and layers settings
t = self.tile[0]
t3 = (t[3][0], self.reduce, self.layers, t[3][3], t[3][4])
self.tile = [(t[0], (0, 0) + self.size, t[2], t3)]
ImageFile.ImageFile.load(self)
def _accept(prefix):
return (prefix[:4] == b'\xff\x4f\xff\x51'
or prefix[:12] == b'\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a')
# ------------------------------------------------------------
# Save support
def _save(im, fp, filename):
if filename.endswith('.j2k'):
kind = 'j2k'
else:
kind = 'jp2'
# Get the keyword arguments
info = im.encoderinfo
offset = info.get('offset', None)
tile_offset = info.get('tile_offset', None)
tile_size = info.get('tile_size', None)
quality_mode = info.get('quality_mode', 'rates')
quality_layers = info.get('quality_layers', None)
num_resolutions = info.get('num_resolutions', 0)
cblk_size = info.get('codeblock_size', None)
precinct_size = info.get('precinct_size', None)
irreversible = info.get('irreversible', False)
progression = info.get('progression', 'LRCP')
cinema_mode = info.get('cinema_mode', 'no')
fd = -1
if hasattr(fp, "fileno"):
try:
fd = fp.fileno()
except:
fd = -1
im.encoderconfig = (
offset,
tile_offset,
tile_size,
quality_mode,
quality_layers,
num_resolutions,
cblk_size,
precinct_size,
irreversible,
progression,
cinema_mode,
fd
)
ImageFile._save(im, fp, [('jpeg2k', (0, 0)+im.size, 0, kind)])
# ------------------------------------------------------------
# Registry stuff
Image.register_open('JPEG2000', Jpeg2KImageFile, _accept)
Image.register_save('JPEG2000', _save)
Image.register_extension('JPEG2000', '.jp2')
Image.register_extension('JPEG2000', '.j2k')
Image.register_extension('JPEG2000', '.jpc')
Image.register_extension('JPEG2000', '.jpf')
Image.register_extension('JPEG2000', '.jpx')
Image.register_extension('JPEG2000', '.j2c')
Image.register_mime('JPEG2000', 'image/jp2')
Image.register_mime('JPEG2000', 'image/jpx')
| [
"PIL.ImageFile._save",
"PIL.Image.register_save",
"io.BytesIO",
"os.fstat",
"PIL.Image.register_extension",
"PIL.ImageFile.ImageFile.load",
"struct.unpack",
"PIL.Image.register_mime",
"PIL.Image.register_open"
] | [((7193, 7250), 'PIL.Image.register_open', 'Image.register_open', (['"""JPEG2000"""', 'Jpeg2KImageFile', '_accept'], {}), "('JPEG2000', Jpeg2KImageFile, _accept)\n", (7212, 7250), False, 'from PIL import Image, ImageFile\n'), ((7251, 7289), 'PIL.Image.register_save', 'Image.register_save', (['"""JPEG2000"""', '_save'], {}), "('JPEG2000', _save)\n", (7270, 7289), False, 'from PIL import Image, ImageFile\n'), ((7291, 7335), 'PIL.Image.register_extension', 'Image.register_extension', (['"""JPEG2000"""', '""".jp2"""'], {}), "('JPEG2000', '.jp2')\n", (7315, 7335), False, 'from PIL import Image, ImageFile\n'), ((7336, 7380), 'PIL.Image.register_extension', 'Image.register_extension', (['"""JPEG2000"""', '""".j2k"""'], {}), "('JPEG2000', '.j2k')\n", (7360, 7380), False, 'from PIL import Image, ImageFile\n'), ((7381, 7425), 'PIL.Image.register_extension', 'Image.register_extension', (['"""JPEG2000"""', '""".jpc"""'], {}), "('JPEG2000', '.jpc')\n", (7405, 7425), False, 'from PIL import Image, ImageFile\n'), ((7426, 7470), 'PIL.Image.register_extension', 'Image.register_extension', (['"""JPEG2000"""', '""".jpf"""'], {}), "('JPEG2000', '.jpf')\n", (7450, 7470), False, 'from PIL import Image, ImageFile\n'), ((7471, 7515), 'PIL.Image.register_extension', 'Image.register_extension', (['"""JPEG2000"""', '""".jpx"""'], {}), "('JPEG2000', '.jpx')\n", (7495, 7515), False, 'from PIL import Image, ImageFile\n'), ((7516, 7560), 'PIL.Image.register_extension', 'Image.register_extension', (['"""JPEG2000"""', '""".j2c"""'], {}), "('JPEG2000', '.j2c')\n", (7540, 7560), False, 'from PIL import Image, ImageFile\n'), ((7562, 7606), 'PIL.Image.register_mime', 'Image.register_mime', (['"""JPEG2000"""', '"""image/jp2"""'], {}), "('JPEG2000', 'image/jp2')\n", (7581, 7606), False, 'from PIL import Image, ImageFile\n'), ((7607, 7651), 'PIL.Image.register_mime', 'Image.register_mime', (['"""JPEG2000"""', '"""image/jpx"""'], {}), "('JPEG2000', 'image/jpx')\n", (7626, 7651), False, 'from PIL import Image, ImageFile\n'), ((713, 752), 'struct.unpack', 'struct.unpack', (['""">HHIIIIIIIIH"""', 'siz[:38]'], {}), "('>HHIIIIIIIIH', siz[:38])\n", (726, 752), False, 'import struct\n'), ((1992, 2010), 'io.BytesIO', 'io.BytesIO', (['header'], {}), '(header)\n', (2002, 2010), False, 'import io\n'), ((7048, 7112), 'PIL.ImageFile._save', 'ImageFile._save', (['im', 'fp', "[('jpeg2k', (0, 0) + im.size, 0, kind)]"], {}), "(im, fp, [('jpeg2k', (0, 0) + im.size, 0, kind)])\n", (7063, 7112), False, 'from PIL import Image, ImageFile\n'), ((552, 576), 'struct.unpack', 'struct.unpack', (['""">H"""', 'hdr'], {}), "('>H', hdr)\n", (565, 576), False, 'import struct\n'), ((902, 951), 'struct.unpack', 'struct.unpack', (['""">BBB"""', 'siz[36 + 3 * i:39 + 3 * i]'], {}), "('>BBB', siz[36 + 3 * i:39 + 3 * i])\n", (915, 951), False, 'import struct\n'), ((5679, 5709), 'PIL.ImageFile.ImageFile.load', 'ImageFile.ImageFile.load', (['self'], {}), '(self)\n', (5703, 5709), False, 'from PIL import Image, ImageFile\n'), ((2356, 2390), 'struct.unpack', 'struct.unpack', (['""">IIHBBBB"""', 'content'], {}), "('>IIHBBBB', content)\n", (2369, 2390), False, 'import struct\n'), ((2865, 2899), 'struct.unpack', 'struct.unpack', (['""">BBB"""', 'content[:3]'], {}), "('>BBB', content[:3])\n", (2878, 2899), False, 'import struct\n'), ((4790, 4802), 'os.fstat', 'os.fstat', (['fd'], {}), '(fd)\n', (4798, 4802), False, 'import os\n'), ((2947, 2980), 'struct.unpack', 'struct.unpack', (['""">I"""', 'content[3:7]'], {}), "('>I', content[3:7])\n", (2960, 2980), False, 'import struct\n')] |
# -*- coding: utf-8 -*-
from sqlalchemy.exc import SQLAlchemyError
from h.services.exceptions import ValidationError, ConflictError
class GroupUpdateService:
def __init__(self, session):
"""
Create a new GroupUpdateService
:param session: the SQLAlchemy session object
"""
self.session = session
def update(self, group, **kwargs):
"""
Update a group model with the args provided.
:arg group: the group to update
:type group: ~h.models.Group
:raise ValidationError: if setting an attribute on the model raises :exc:`ValueError`
:raise ConflictError: if the ``authority_provided_id`` is already in use
:rtype: ~h.models.Group
"""
for key, value in kwargs.items():
try:
setattr(group, key, value)
except ValueError as err:
raise ValidationError(err)
try:
self.session.flush()
except SQLAlchemyError as err:
# Handle DB integrity issues with duplicate ``authority_provided_id``
if (
'duplicate key value violates unique constraint "ix__group__groupid"'
in repr(err)
):
raise ConflictError(
"authority_provided_id '{id}' is already in use".format(
id=kwargs["authority_provided_id"]
)
)
else:
# Re-raise as this is an unexpected problem
raise
return group
def group_update_factory(context, request):
"""Return a GroupUpdateService instance for the passed context and request."""
return GroupUpdateService(session=request.db)
| [
"h.services.exceptions.ValidationError"
] | [((912, 932), 'h.services.exceptions.ValidationError', 'ValidationError', (['err'], {}), '(err)\n', (927, 932), False, 'from h.services.exceptions import ValidationError, ConflictError\n')] |
from app.encryption import CryptoSigner
signer = CryptoSigner()
def test_should_sign_content(notify_api):
signer.init_app(notify_api)
assert signer.sign("this") != "this"
def test_should_verify_content(notify_api):
signer.init_app(notify_api)
signed = signer.sign("this")
assert signer.verify(signed) == "this"
def test_should_sign_json(notify_api):
signer.init_app(notify_api)
signed = signer.sign({"this": "that"})
assert signer.verify(signed) == {"this": "that"}
| [
"app.encryption.CryptoSigner"
] | [((50, 64), 'app.encryption.CryptoSigner', 'CryptoSigner', ([], {}), '()\n', (62, 64), False, 'from app.encryption import CryptoSigner\n')] |
import requests
import json
class MetroSaoPaulo():
def get_metro_status(self):
response = requests.get('http://www.metro.sp.gov.br/Sistemas/direto-do-metro-via4/diretodoMetroHome.aspx')
body = response.text
begin = body.index('objArrLinhas')
end = body.index('var objArrL4') - 7
str = body[begin:end]
str_obj = str.replace('objArrLinhas = ', '')
obj = json.loads(str_obj)
begin = body.index('objArrL4')
end = body.index('"codigo" : "4"') + 15
str = body[begin:end]
str_obj = str.replace('objArrL4 = [', '')
obj_l4= json.loads(str_obj)
obj.append(obj_l4)
ret = {}
for l in obj:
ret[l.get('linha')] = l.get('status')
return ret
| [
"json.loads",
"requests.get"
] | [((114, 219), 'requests.get', 'requests.get', (['"""http://www.metro.sp.gov.br/Sistemas/direto-do-metro-via4/diretodoMetroHome.aspx"""'], {}), "(\n 'http://www.metro.sp.gov.br/Sistemas/direto-do-metro-via4/diretodoMetroHome.aspx'\n )\n", (126, 219), False, 'import requests\n'), ((424, 443), 'json.loads', 'json.loads', (['str_obj'], {}), '(str_obj)\n', (434, 443), False, 'import json\n'), ((627, 646), 'json.loads', 'json.loads', (['str_obj'], {}), '(str_obj)\n', (637, 646), False, 'import json\n')] |
import logging
from django import db
from dramatiq.middleware import Middleware
LOGGER = logging.getLogger("django_dramatiq.AdminMiddleware")
class AdminMiddleware(Middleware):
"""This middleware keeps track of task executions.
"""
def after_enqueue(self, broker, message, delay):
from .models import Task
LOGGER.debug("Creating Task from message %r.", message.message_id)
status = Task.STATUS_ENQUEUED
if delay:
status = Task.STATUS_DELAYED
Task.tasks.create_or_update_from_message(message, status=status)
def before_process_message(self, broker, message):
from .models import Task
LOGGER.debug("Updating Task from message %r.", message.message_id)
Task.tasks.create_or_update_from_message(message, status=Task.STATUS_RUNNING)
def after_process_message(self, broker, message, *, result=None, exception=None):
from .models import Task
status = Task.STATUS_DONE
if exception is not None:
status = Task.STATUS_FAILED
LOGGER.debug("Updating Task from message %r.", message.message_id)
Task.tasks.create_or_update_from_message(message, status=status)
class DbConnectionsMiddleware(Middleware):
"""This middleware cleans up db connections on worker shutdown.
"""
def _close_old_connections(self, *args, **kwargs):
db.close_old_connections()
before_process_message = _close_old_connections
after_process_message = _close_old_connections
def _close_connections(self, *args, **kwargs):
db.connections.close_all()
before_consumer_thread_shutdown = _close_connections
before_worker_thread_shutdown = _close_connections
before_worker_shutdown = _close_connections
| [
"logging.getLogger",
"django.db.connections.close_all",
"django.db.close_old_connections"
] | [((91, 143), 'logging.getLogger', 'logging.getLogger', (['"""django_dramatiq.AdminMiddleware"""'], {}), "('django_dramatiq.AdminMiddleware')\n", (108, 143), False, 'import logging\n'), ((1392, 1418), 'django.db.close_old_connections', 'db.close_old_connections', ([], {}), '()\n', (1416, 1418), False, 'from django import db\n'), ((1583, 1609), 'django.db.connections.close_all', 'db.connections.close_all', ([], {}), '()\n', (1607, 1609), False, 'from django import db\n')] |
from typing import Type
from fpipe.exceptions import FileDataException
from fpipe.file import File
from fpipe.meta.abstract import FileData, T
def meta_prioritized(t: Type[FileData[T]], *sources: File) -> T:
error = FileDataException(t)
for s in sources:
try:
return s[t]
except FileDataException:
pass
raise error
| [
"fpipe.exceptions.FileDataException"
] | [((223, 243), 'fpipe.exceptions.FileDataException', 'FileDataException', (['t'], {}), '(t)\n', (240, 243), False, 'from fpipe.exceptions import FileDataException\n')] |
"""Support for Xiaomi Mi Flora BLE plant sensor."""
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_FORCE_UPDATE, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_MAC,
CONF_SCAN_INTERVAL, EVENT_HOMEASSISTANT_START)
from homeassistant.core import callback
_LOGGER = logging.getLogger(__name__)
CONF_ADAPTER = 'adapter'
CONF_MEDIAN = 'median'
DEFAULT_ADAPTER = 'hci0'
DEFAULT_FORCE_UPDATE = False
DEFAULT_MEDIAN = 3
DEFAULT_NAME = 'Mi Flora'
SCAN_INTERVAL = timedelta(seconds=1200)
# Sensor types are defined like: Name, units, icon
SENSOR_TYPES = {
'temperature': ['Temperature', '°C', 'mdi:thermometer'],
'light': ['Light intensity', 'lx', 'mdi:white-balance-sunny'],
'moisture': ['Moisture', '%', 'mdi:water-percent'],
'conductivity': ['Conductivity', 'µS/cm', 'mdi:flash-circle'],
'battery': ['Battery', '%', 'mdi:battery-charging'],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_MAC): cv.string,
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_MEDIAN, default=DEFAULT_MEDIAN): cv.positive_int,
vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
vol.Optional(CONF_ADAPTER, default=DEFAULT_ADAPTER): cv.string,
})
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the MiFlora sensor."""
from miflora import miflora_poller
try:
import bluepy.btle # noqa: F401 pylint: disable=unused-import
from btlewrap import BluepyBackend
backend = BluepyBackend
except ImportError:
from btlewrap import GatttoolBackend
backend = GatttoolBackend
_LOGGER.debug('Miflora is using %s backend.', backend.__name__)
cache = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL).total_seconds()
poller = miflora_poller.MiFloraPoller(
config.get(CONF_MAC), cache_timeout=cache,
adapter=config.get(CONF_ADAPTER), backend=backend)
force_update = config.get(CONF_FORCE_UPDATE)
median = config.get(CONF_MEDIAN)
devs = []
for parameter in config[CONF_MONITORED_CONDITIONS]:
name = SENSOR_TYPES[parameter][0]
unit = SENSOR_TYPES[parameter][1]
icon = SENSOR_TYPES[parameter][2]
prefix = config.get(CONF_NAME)
if prefix:
name = "{} {}".format(prefix, name)
devs.append(MiFloraSensor(
poller, parameter, name, unit, icon, force_update, median))
async_add_entities(devs)
class MiFloraSensor(Entity):
"""Implementing the MiFlora sensor."""
def __init__(
self, poller, parameter, name, unit, icon, force_update, median):
"""Initialize the sensor."""
self.poller = poller
self.parameter = parameter
self._unit = unit
self._icon = icon
self._name = name
self._state = None
self.data = []
self._force_update = force_update
# Median is used to filter out outliers. median of 3 will filter
# single outliers, while median of 5 will filter double outliers
# Use median_count = 1 if no filtering is required.
self.median_count = median
async def async_added_to_hass(self):
"""Set initial state."""
@callback
def on_startup(_):
self.async_schedule_update_ha_state(True)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, on_startup)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the units of measurement."""
return self._unit
@property
def icon(self):
"""Return the icon of the sensor."""
return self._icon
@property
def force_update(self):
"""Force update."""
return self._force_update
def update(self):
"""
Update current conditions.
This uses a rolling median over 3 values to filter out outliers.
"""
from btlewrap import BluetoothBackendException
try:
_LOGGER.debug("Polling data for %s", self.name)
data = self.poller.parameter_value(self.parameter)
except IOError as ioerr:
_LOGGER.info("Polling error %s", ioerr)
return
except BluetoothBackendException as bterror:
_LOGGER.info("Polling error %s", bterror)
return
if data is not None:
_LOGGER.debug("%s = %s", self.name, data)
self.data.append(data)
else:
_LOGGER.info("Did not receive any data from Mi Flora sensor %s",
self.name)
# Remove old data from median list or set sensor value to None
# if no data is available anymore
if self.data:
self.data = self.data[1:]
else:
self._state = None
return
_LOGGER.debug("Data collected: %s", self.data)
if len(self.data) > self.median_count:
self.data = self.data[1:]
if len(self.data) == self.median_count:
median = sorted(self.data)[int((self.median_count - 1) / 2)]
_LOGGER.debug("Median is: %s", median)
self._state = median
elif self._state is None:
_LOGGER.debug("Set initial state")
self._state = self.data[0]
else:
_LOGGER.debug("Not yet enough data for median calculation")
| [
"logging.getLogger",
"voluptuous.Required",
"datetime.timedelta",
"voluptuous.Optional",
"voluptuous.In"
] | [((492, 519), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (509, 519), False, 'import logging\n'), ((686, 709), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(1200)'}), '(seconds=1200)\n', (695, 709), False, 'from datetime import timedelta\n'), ((1137, 1159), 'voluptuous.Required', 'vol.Required', (['CONF_MAC'], {}), '(CONF_MAC)\n', (1149, 1159), True, 'import voluptuous as vol\n'), ((1306, 1351), 'voluptuous.Optional', 'vol.Optional', (['CONF_NAME'], {'default': 'DEFAULT_NAME'}), '(CONF_NAME, default=DEFAULT_NAME)\n', (1318, 1351), True, 'import voluptuous as vol\n'), ((1368, 1417), 'voluptuous.Optional', 'vol.Optional', (['CONF_MEDIAN'], {'default': 'DEFAULT_MEDIAN'}), '(CONF_MEDIAN, default=DEFAULT_MEDIAN)\n', (1380, 1417), True, 'import voluptuous as vol\n'), ((1440, 1501), 'voluptuous.Optional', 'vol.Optional', (['CONF_FORCE_UPDATE'], {'default': 'DEFAULT_FORCE_UPDATE'}), '(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE)\n', (1452, 1501), True, 'import voluptuous as vol\n'), ((1519, 1570), 'voluptuous.Optional', 'vol.Optional', (['CONF_ADAPTER'], {'default': 'DEFAULT_ADAPTER'}), '(CONF_ADAPTER, default=DEFAULT_ADAPTER)\n', (1531, 1570), True, 'import voluptuous as vol\n'), ((1278, 1298), 'voluptuous.In', 'vol.In', (['SENSOR_TYPES'], {}), '(SENSOR_TYPES)\n', (1284, 1298), True, 'import voluptuous as vol\n')] |
import numpy as np
import matplotlib.pyplot as plt
augment_method = "Specaugment"
d = np.load("result_{}/curve.npz".format(augment_method))
loss = d['loss']
acc = d['acc']
best_acc = d['best_acc']
print(best_acc)
plt.plot(loss)
plt.show()
plt.clf()
plt.plot(acc)
plt.show()
plt.clf() | [
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.show"
] | [((217, 231), 'matplotlib.pyplot.plot', 'plt.plot', (['loss'], {}), '(loss)\n', (225, 231), True, 'import matplotlib.pyplot as plt\n'), ((232, 242), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (240, 242), True, 'import matplotlib.pyplot as plt\n'), ((243, 252), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (250, 252), True, 'import matplotlib.pyplot as plt\n'), ((254, 267), 'matplotlib.pyplot.plot', 'plt.plot', (['acc'], {}), '(acc)\n', (262, 267), True, 'import matplotlib.pyplot as plt\n'), ((268, 278), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (276, 278), True, 'import matplotlib.pyplot as plt\n'), ((279, 288), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (286, 288), True, 'import matplotlib.pyplot as plt\n')] |
'''
Defines the preferences dialog.
@author: <NAME>
@organization: Mozilla Foundation
@copyright: Copyright (c) 2006, 2007 Mozilla Foundation
@license: BSD
All rights reserved. This program and the accompanying materials are made
available under the terms of the BSD which accompanies this distribution, and
is available at U{http://www.opensource.org/licenses/bsd-license.php}
'''
import gi
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import Atk as atk
from gi.repository.Gio import Settings as GSettings
from .i18n import _
from . import node
from .tools import parseColorString
class AccerciserPreferencesDialog(gtk.Dialog):
'''
Class that creates a preferences dialog.
'''
def __init__(self, plugins_view=None, hotkeys_view=None):
'''
Initialize a preferences dialog.
@param plugins_view: Treeview of plugins.
@type plugins_view: L{PluginManager._View}
@param hotkeys_view: Treeview of global hotkeys.
@type hotkeys_view: L{HotkeyTreeView}
'''
gtk.Dialog.__init__(self, title=_('accerciser Preferences'))
self.add_buttons(gtk.STOCK_CLOSE, gtk.ResponseType.CLOSE)
self.connect('response', self._onResponse)
self.set_default_size(500, 250)
notebook = gtk.Notebook()
vbox = self.get_children()[0]
vbox.pack_start(notebook, True, True, 2)
for view, section in [(plugins_view, _('Plugins')),
(hotkeys_view, _('Global Hotkeys'))]:
if view is not None:
sw = gtk.ScrolledWindow()
sw.set_shadow_type(gtk.ShadowType.IN)
sw.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC)
sw.set_size_request(500, 150)
sw.add(view)
notebook.append_page(sw, gtk.Label.new(section))
notebook.append_page(_HighlighterView(), gtk.Label.new(_('Highlighting')))
def _onResponse(self, dialog, response_id):
'''
Callback for dialog responses, always destroy it.
@param dialog: This dialog.
@type dialog: L{AccerciserPreferencesDialog}
@param response_id: Response ID recieved.
@type response_id: integer
'''
dialog.destroy()
class _HighlighterView(gtk.Alignment):
'''
A container widget with the settings for the highlighter.
'''
def __init__(self):
gtk.Alignment.__init__(self)
self.set_padding(12, 12, 18, 12)
self.gsettings = GSettings.new('org.a11y.Accerciser')
self._buildUI()
def _buildUI(self):
'''
Programatically build the UI.
'''
table = gtk.Table.new(3, 2, True)
table.set_col_spacings(6)
self.add(table)
labels = [None, None, None]
controls = [None, None, None]
labels[0] = gtk.Label.new(_('Highlight duration:'))
controls[0] = gtk.SpinButton()
controls[0].set_range(0.01, 5)
controls[0].set_digits(2)
controls[0].set_value(self.gsettings.get_double('highlight-duration'))
controls[0].set_increments(0.01, 0.1)
controls[0].connect('value-changed', self._onDurationChanged)
labels[1] = gtk.Label.new(_('Border color:'))
controls[1] = self._ColorButton(node.BORDER_COLOR, node.BORDER_ALPHA)
controls[1].connect('color-set', self._onColorSet, 'highlight-border')
controls[1].set_tooltip_text(_('The border color of the highlight box'))
labels[2] = gtk.Label.new(_('Fill color:'))
controls[2] = self._ColorButton(node.FILL_COLOR, node.FILL_ALPHA)
controls[2].connect('color-set', self._onColorSet, 'highlight-fill')
controls[2].set_tooltip_text(_('The fill color of the highlight box'))
for label, control, row in zip(labels, controls, range(3)):
label.set_alignment(0, 0.5)
table.attach(label, 0, 1, row, row + 1, gtk.AttachOptions.FILL)
table.attach(control, 1, 2, row, row + 1, gtk.AttachOptions.FILL)
for label, control in zip([x.get_accessible() for x in labels],
[x.get_accessible() for x in controls]):
label.add_relationship(atk.RelationType.LABEL_FOR, control)
control.add_relationship(atk.RelationType.LABELLED_BY, label)
def _onDurationChanged(self, spin_button):
'''
Callback for the duration spin button. Update key and the global variable
in the L{node} module.
@param spin_button: The spin button that emitted the value-changed signal.
@type spin_button: gtk.SpinButton
'''
node.HL_DURATION = int(spin_button.get_value()*1000)
self.gsettings.set_double('highlight-duration',
spin_button.get_value())
def _onColorSet(self, color_button, key):
'''
Callback for a color button. Update gsettings and the global variables
in the L{node} module.
@param color_button: The color button that emitted the color-set signal.
@type color_button: l{_HighlighterView._ColorButton}
@param key: the key name suffix for this color setting.
@type key: string
'''
if 'fill' in key:
node.FILL_COLOR = color_button.get_rgb_string()
node.FILL_ALPHA = color_button.get_alpha_float()
else:
node.BORDER_COLOR = color_button.get_rgb_string()
node.BORDER_ALPHA = color_button.get_alpha_float()
self.gsettings.set_string(key, color_button.get_rgba_string())
class _ColorButton(gtk.ColorButton):
'''
ColorButton derivative with useful methods for us.
'''
def __init__(self, color, alpha):
color = gdk.color_parse(color)
gtk.ColorButton.__init__(self)
self.set_use_alpha(True)
self.set_alpha(int(alpha*0xffff))
self.set_color(color)
def get_rgba_string(self):
'''
Get the current color and alpha in string format.
@return: String in the format of #rrggbbaa.
@rtype: string.
'''
color = self.get_color()
color_val = 0
color_val |= color.red >> 8 << 24
color_val |= color.green >> 8 << 16
color_val |= color.blue >> 8 << 8
color_val |= self.get_alpha() >> 8
return \
'#' + hex(color_val).replace('0x', '').replace('L', '').rjust(8, '0')
def get_rgb_string(self):
'''
Get the current color in string format.
@return: String in the format of #rrggbb.
@rtype: string.
'''
color = self.get_color()
color_val = 0
color_val |= color.red >> 8 << 16
color_val |= color.green >> 8 << 8
color_val |= color.blue >> 8
return \
'#' + hex(color_val).replace('0x', '').replace('L', '').rjust(6, '0')
def get_alpha_float(self):
'''
Get the current alpha as a value from 0.0 to 1.0.
'''
return self.get_alpha()/float(0xffff)
| [
"gi.repository.Gtk.ColorButton.__init__",
"gi.repository.Gtk.SpinButton",
"gi.repository.Gio.Settings.new",
"gi.repository.Gtk.Table.new",
"gi.repository.Gdk.color_parse",
"gi.repository.Gtk.Alignment.__init__",
"gi.repository.Gtk.Label.new",
"gi.repository.Gtk.ScrolledWindow",
"gi.repository.Gtk.No... | [((1271, 1285), 'gi.repository.Gtk.Notebook', 'gtk.Notebook', ([], {}), '()\n', (1283, 1285), True, 'from gi.repository import Gtk as gtk\n'), ((2313, 2341), 'gi.repository.Gtk.Alignment.__init__', 'gtk.Alignment.__init__', (['self'], {}), '(self)\n', (2335, 2341), True, 'from gi.repository import Gtk as gtk\n'), ((2400, 2436), 'gi.repository.Gio.Settings.new', 'GSettings.new', (['"""org.a11y.Accerciser"""'], {}), "('org.a11y.Accerciser')\n", (2413, 2436), True, 'from gi.repository.Gio import Settings as GSettings\n'), ((2542, 2567), 'gi.repository.Gtk.Table.new', 'gtk.Table.new', (['(3)', '(2)', '(True)'], {}), '(3, 2, True)\n', (2555, 2567), True, 'from gi.repository import Gtk as gtk\n'), ((2758, 2774), 'gi.repository.Gtk.SpinButton', 'gtk.SpinButton', ([], {}), '()\n', (2772, 2774), True, 'from gi.repository import Gtk as gtk\n'), ((5427, 5449), 'gi.repository.Gdk.color_parse', 'gdk.color_parse', (['color'], {}), '(color)\n', (5442, 5449), True, 'from gi.repository import Gdk as gdk\n'), ((5456, 5486), 'gi.repository.Gtk.ColorButton.__init__', 'gtk.ColorButton.__init__', (['self'], {}), '(self)\n', (5480, 5486), True, 'from gi.repository import Gtk as gtk\n'), ((1525, 1545), 'gi.repository.Gtk.ScrolledWindow', 'gtk.ScrolledWindow', ([], {}), '()\n', (1543, 1545), True, 'from gi.repository import Gtk as gtk\n'), ((1758, 1780), 'gi.repository.Gtk.Label.new', 'gtk.Label.new', (['section'], {}), '(section)\n', (1771, 1780), True, 'from gi.repository import Gtk as gtk\n')] |
# 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 itertools
import random
import socket
import mock
from neutron_lib import constants
from neutron_lib.tests import _base as base
from neutron_lib.utils import net
class TestGetHostname(base.BaseTestCase):
@mock.patch.object(socket, 'gethostname',
return_value='fake-host-name')
def test_get_hostname(self, mock_gethostname):
self.assertEqual('fake-host-name',
net.get_hostname())
mock_gethostname.assert_called_once_with()
class TestGetRandomMac(base.BaseTestCase):
@mock.patch.object(random, 'getrandbits', return_value=0xa2)
def test_first_4_octets_unchanged(self, mock_rnd):
mac = net.get_random_mac(['aa', 'bb', '00', 'dd', 'ee', 'ff'])
self.assertEqual('aa:bb:00:dd:a2:a2', mac)
mock_rnd.assert_called_with(8)
@mock.patch.object(random, 'getrandbits', return_value=0xa2)
def test_first_4th_octet_generated(self, mock_rnd):
mac = net.get_random_mac(['aa', 'bb', 'cc', '00', 'ee', 'ff'])
self.assertEqual('aa:bb:cc:a2:a2:a2', mac)
mock_rnd.assert_called_with(8)
class TestRandomMacGenerator(base.BaseTestCase):
def test_all_macs_generated(self):
mac = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff']
generator = itertools.islice(net.random_mac_generator(mac), 70000)
self.assertEqual(2**16, len(list(generator)))
@mock.patch.object(random, 'getrandbits', return_value=0xa2)
def test_first_generated_mac(self, mock_rnd):
mac = ['aa', 'bb', 'cc', '00', 'ee', 'ff']
generator = itertools.islice(net.random_mac_generator(mac), 1)
self.assertEqual(['aa:bb:cc:a2:a2:a2'], list(generator))
mock_rnd.assert_called_with(8)
@mock.patch.object(random, 'getrandbits', return_value=0xa2)
def test_respected_early_zeroes_generated_mac(self, mock_rnd):
mac1 = ['00', 'bb', 'cc', '00', 'ee', 'ff']
generator = itertools.islice(net.random_mac_generator(mac1), 1)
self.assertEqual(['00:bb:cc:a2:a2:a2'], list(generator))
mac2 = ['aa', '00', 'cc', '00', 'ee', 'ff']
generator = itertools.islice(net.random_mac_generator(mac2), 1)
self.assertEqual(['aa:00:cc:a2:a2:a2'], list(generator))
mac3 = ['aa', 'bb', '00', '00', 'ee', 'ff']
generator = itertools.islice(net.random_mac_generator(mac3), 1)
self.assertEqual(['aa:bb:00:a2:a2:a2'], list(generator))
mock_rnd.assert_called_with(8)
@mock.patch.object(random, 'getrandbits', return_value=0xa2)
def test_short_supplied_mac(self, mock_rnd):
mac_base = '12:34:56:78'
mac = mac_base.split(':')
generator = itertools.islice(net.random_mac_generator(mac), 1)
self.assertEqual(['12:34:56:78:a2:a2'], list(generator))
mock_rnd.assert_called_with(8)
class TestPortDeviceOwner(base.BaseTestCase):
def test_is_port_trusted(self):
self.assertTrue(net.is_port_trusted(
{'device_owner':
constants.DEVICE_OWNER_NETWORK_PREFIX + 'dev'}))
def test_is_port_not_trusted(self):
self.assertFalse(net.is_port_trusted(
{'device_owner': constants.DEVICE_OWNER_COMPUTE_PREFIX + 'dev'}))
| [
"neutron_lib.utils.net.get_random_mac",
"neutron_lib.utils.net.is_port_trusted",
"neutron_lib.utils.net.random_mac_generator",
"mock.patch.object",
"neutron_lib.utils.net.get_hostname"
] | [((767, 838), 'mock.patch.object', 'mock.patch.object', (['socket', '"""gethostname"""'], {'return_value': '"""fake-host-name"""'}), "(socket, 'gethostname', return_value='fake-host-name')\n", (784, 838), False, 'import mock\n'), ((1103, 1161), 'mock.patch.object', 'mock.patch.object', (['random', '"""getrandbits"""'], {'return_value': '(162)'}), "(random, 'getrandbits', return_value=162)\n", (1120, 1161), False, 'import mock\n'), ((1385, 1443), 'mock.patch.object', 'mock.patch.object', (['random', '"""getrandbits"""'], {'return_value': '(162)'}), "(random, 'getrandbits', return_value=162)\n", (1402, 1443), False, 'import mock\n'), ((1939, 1997), 'mock.patch.object', 'mock.patch.object', (['random', '"""getrandbits"""'], {'return_value': '(162)'}), "(random, 'getrandbits', return_value=162)\n", (1956, 1997), False, 'import mock\n'), ((2281, 2339), 'mock.patch.object', 'mock.patch.object', (['random', '"""getrandbits"""'], {'return_value': '(162)'}), "(random, 'getrandbits', return_value=162)\n", (2298, 2339), False, 'import mock\n'), ((3023, 3081), 'mock.patch.object', 'mock.patch.object', (['random', '"""getrandbits"""'], {'return_value': '(162)'}), "(random, 'getrandbits', return_value=162)\n", (3040, 3081), False, 'import mock\n'), ((1232, 1288), 'neutron_lib.utils.net.get_random_mac', 'net.get_random_mac', (["['aa', 'bb', '00', 'dd', 'ee', 'ff']"], {}), "(['aa', 'bb', '00', 'dd', 'ee', 'ff'])\n", (1250, 1288), False, 'from neutron_lib.utils import net\n'), ((1515, 1571), 'neutron_lib.utils.net.get_random_mac', 'net.get_random_mac', (["['aa', 'bb', 'cc', '00', 'ee', 'ff']"], {}), "(['aa', 'bb', 'cc', '00', 'ee', 'ff'])\n", (1533, 1571), False, 'from neutron_lib.utils import net\n'), ((981, 999), 'neutron_lib.utils.net.get_hostname', 'net.get_hostname', ([], {}), '()\n', (997, 999), False, 'from neutron_lib.utils import net\n'), ((1841, 1870), 'neutron_lib.utils.net.random_mac_generator', 'net.random_mac_generator', (['mac'], {}), '(mac)\n', (1865, 1870), False, 'from neutron_lib.utils import net\n'), ((2137, 2166), 'neutron_lib.utils.net.random_mac_generator', 'net.random_mac_generator', (['mac'], {}), '(mac)\n', (2161, 2166), False, 'from neutron_lib.utils import net\n'), ((2498, 2528), 'neutron_lib.utils.net.random_mac_generator', 'net.random_mac_generator', (['mac1'], {}), '(mac1)\n', (2522, 2528), False, 'from neutron_lib.utils import net\n'), ((2688, 2718), 'neutron_lib.utils.net.random_mac_generator', 'net.random_mac_generator', (['mac2'], {}), '(mac2)\n', (2712, 2718), False, 'from neutron_lib.utils import net\n'), ((2878, 2908), 'neutron_lib.utils.net.random_mac_generator', 'net.random_mac_generator', (['mac3'], {}), '(mac3)\n', (2902, 2908), False, 'from neutron_lib.utils import net\n'), ((3236, 3265), 'neutron_lib.utils.net.random_mac_generator', 'net.random_mac_generator', (['mac'], {}), '(mac)\n', (3260, 3265), False, 'from neutron_lib.utils import net\n'), ((3483, 3571), 'neutron_lib.utils.net.is_port_trusted', 'net.is_port_trusted', (["{'device_owner': constants.DEVICE_OWNER_NETWORK_PREFIX + 'dev'}"], {}), "({'device_owner': constants.DEVICE_OWNER_NETWORK_PREFIX +\n 'dev'})\n", (3502, 3571), False, 'from neutron_lib.utils import net\n'), ((3661, 3749), 'neutron_lib.utils.net.is_port_trusted', 'net.is_port_trusted', (["{'device_owner': constants.DEVICE_OWNER_COMPUTE_PREFIX + 'dev'}"], {}), "({'device_owner': constants.DEVICE_OWNER_COMPUTE_PREFIX +\n 'dev'})\n", (3680, 3749), False, 'from neutron_lib.utils import net\n')] |
import pickle
import time
class Cache(object):
def __init__(self, j):
self._cache = {}
self._j = j
# def serialize(self, val):
# tt = self._j.data.types.type_detect(val)
def get(self, id="main", reset=False, expiration=3600):
"""
@param id is a unique id for the cache
db = when none then will be in memory
"""
if id not in self._cache:
self._cache[id] = CacheCategory(j=self._j, id=id, expiration=expiration, reset=reset)
if reset:
self._cache[id].reset()
return self._cache[id]
def resetAll(self):
for key, cache in self._cache.items():
cache.reset()
def reset(self, id=None):
if id is None:
self.resetAll()
else:
if id in self._cache:
self._cache[id].reset()
def _testAll(self, c):
c.set("something", "OK")
assert "something" in c.list()
assert c.exists("something")
c.reset()
assert c.exists("something") is False
c.set("something", "OK")
self.reset()
assert c.exists("something") is False
c.set("something", "OK")
assert "OK" == c.get("something")
def return1():
return 1
def return2():
return 2
def return3():
return 3
assert c.get("somethingElse", return1) == 1
assert c.get("somethingElse") == 1
c.reset()
try:
c.get("somethingElse")
except Exception as e:
if "Cannot get 'somethingElse' from cache" not in str(e):
raise j.exceptions.Base("error in test. non expected output")
time.sleep(2)
assert c.get("somethingElse", return2, expire=1) == 2
# still needs to be 2
assert c.get("somethingElse", return3, expire=1) == 2
time.sleep(2)
assert c.get("somethingElse", return3, expire=1) == 3 # now needs to be 3
assert c.get("somethingElse", return2, expire=100, refresh=True) == 2
assert c.exists("somethingElse")
time.sleep(2)
assert c.exists("somethingElse")
assert "somethingElse" in c.list()
self.reset()
assert c.exists("somethingElse") is False
assert "somethingElse" not in c.list()
def test(self):
"""
kosmos 'j.core.cache.test()'
"""
# make sure its redis
# self._j.clients.redis.core_get()
self._j.core.db_reset()
c = self.get("test", expiration=1)
self._testAll(c)
self._j.tools.tutorial.cache()
print("CACHE ALL TESTS DONE")
def test_without_redis(self):
""" kosmos 'j.core.cache.test_without_redis()'
NOTE: this test actually stops the redis server
(and restarts it afterwards). be careful!
"""
# now stop redis...
self._j.clients.redis.kill()
self._j.core.db_reset()
c = self.get("test", expiration=1)
self._testAll(c)
# ... and restart it again
self._j.clients.redis.start()
class CacheCategory(object):
def __init__(self, j, id, expiration=3600, reset=False):
self._j = j
self.id = id
self.db = self._j.core.db
self.hkey = "cache:%s" % self.id
self.expiration = expiration
if reset:
self.reset()
def _key_get(self, key):
return "cache:%s:%s" % (self.id, key)
def delete(self, key):
self.db.delete(self._key_get(key))
def set(self, key, value, expire=None):
if expire is None:
expire = self.expiration
data = pickle.dumps((self._j.data.time.epoch + expire, value))
self.db.set(self._key_get(key), data, ex=expire)
def exists(self, key):
return self.db.get(self._key_get(key)) is not None
def get(self, key, method=None, expire=None, refresh=False, retry=1, die=True, **kwargs):
"""
:param key: is a unique key for item to fetch out of the cache
:param method: the method to execute
:param expire: expiration in seconds (if 0 then will be same as refresh = True)
:param refresh: if True will execute again (will be set into local caching DB)
:param retry: std 1, means will only try 1 time, otherwise will try multiple times,
useful for e.g. fetching something from internet
:param kwargs: the arguments in kwargs form e.g. a="1" for the method to execute
:param die, normally True, means will raise error if doesnt work, if False will return the error object
:return: the output of the method
"""
if refresh:
self.delete(key)
res = None
else:
# check if key exists then return (only when no refresh)
res = self.db.get(self._key_get(key))
if res is not None:
expireEpoch, res = pickle.loads(res)
if self._j.data.time.epoch > expireEpoch:
self.delete(key)
res = None
else:
# print("cache hit:%s" % key)
return res
if expire is None:
expire = self.expiration
# print("key:%s res:%s" % (key, res))
if method is None:
raise self._j.exceptions.RuntimeError("Cannot get '%s' from cache,not found & method None" % key)
# print("cache miss:%s (%s)" % (key, method))
nr = 0
while nr < retry:
try:
val = method(**kwargs)
break
except Exception as e:
nr += 1
if nr == retry:
if die:
raise e
else:
return e
# print(val)
if val is None or val == "":
raise self._j.exceptions.RuntimeError("cache method cannot return None or empty string.")
self.set(key, val, expire=expire)
return val
def reset(self):
for item in self.list():
self.delete(item)
def list(self):
return [item.decode().split(":")[-1] for item in self.db.keys("cache:%s:*" % self.id)]
def __str__(self):
res = {}
for key in self.db.keys():
val = self.db.get(key)
res[key] = val
out = self._j.data.serializers.yaml.dumps(res)
return out
__repr__ = __str__
| [
"pickle.dumps",
"pickle.loads",
"time.sleep"
] | [((1741, 1754), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1751, 1754), False, 'import time\n'), ((1918, 1931), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1928, 1931), False, 'import time\n'), ((2143, 2156), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2153, 2156), False, 'import time\n'), ((3709, 3764), 'pickle.dumps', 'pickle.dumps', (['(self._j.data.time.epoch + expire, value)'], {}), '((self._j.data.time.epoch + expire, value))\n', (3721, 3764), False, 'import pickle\n'), ((4997, 5014), 'pickle.loads', 'pickle.loads', (['res'], {}), '(res)\n', (5009, 5014), False, 'import pickle\n')] |
"""
Offset Mirror Classes.
This module contains all the classes relating to the offset mirrors used in the
FEE and XRT. Each offset mirror contains a stepper motor and piezo motor to
control the pitch, and two pairs of motors to control the horizontal and
vertical gantries.
"""
import logging
import numpy as np
from ophyd import Component as Cpt
from ophyd import Device, EpicsSignal, EpicsSignalRO
from ophyd import FormattedComponent as FCpt
from ophyd import PVPositioner
from .device import GroupDevice
from .doc_stubs import basic_positioner_init
from .epics_motor import BeckhoffAxisNoOffset
from .inout import InOutRecordPositioner
from .interface import BaseInterface, FltMvInterface
from .pmps import TwinCATStatePMPS
from .signal import PytmcSignal
from .utils import get_status_value
logger = logging.getLogger(__name__)
class OMMotor(FltMvInterface, PVPositioner):
"""Base class for each motor in the LCLS offset mirror system."""
__doc__ += basic_positioner_init
# position
readback = Cpt(EpicsSignalRO, ':RBV', auto_monitor=True, kind='hinted')
setpoint = Cpt(EpicsSignal, ':VAL', auto_monitor=True, limits=True,
kind='normal')
done = Cpt(EpicsSignalRO, ':DMOV', auto_monitor=True, kind='omitted')
motor_egu = Cpt(EpicsSignal, ':RBV.EGU', kind='omitted')
# status
interlock = Cpt(EpicsSignalRO, ':INTERLOCK', kind='omitted')
enabled = Cpt(EpicsSignalRO, ':ENABLED', kind='omitted')
# limit switches
low_limit_switch = Cpt(EpicsSignalRO, ":LLS", kind='omitted')
high_limit_switch = Cpt(EpicsSignalRO, ":HLS", kind='omitted')
@property
def egu(self):
"""
Returns the Engineering Units of the readback PV, as reported by EPICS.
"""
return self.motor_egu.get()
def check_value(self, position):
"""
Checks that the value is both valid and within the motor's soft limits.
Parameters
----------
position : float
Position to check for validity.
Raises
------
ValueError
If position is `None`, `~numpy.NaN` or `~numpy.Inf`.
LimitError
If the position is outside the soft limits.
"""
# Check that we do not have a NaN or an Inf as those will
# will make the PLC very unhappy ...
if position is None or np.isnan(position) or np.isinf(position):
raise ValueError("Invalid value inputted: '{0}'".format(position))
# Use the built-in PVPositioner check_value
super().check_value(position)
class Pitch(OMMotor):
"""
HOMS Pitch Mechanism.
The axis is actually a piezo actuator and a stepper motor in series, and
this is reflected in the PV naming.
"""
__doc__ += basic_positioner_init
piezo_volts = FCpt(EpicsSignalRO, "{self._piezo}:VRBV", kind='normal')
stop_signal = FCpt(EpicsSignal, "{self._piezo}:STOP", kind='omitted')
# TODO: Limits will be added soon, but not present yet
def __init__(self, prefix, **kwargs):
# Predict the prefix of all piezo pvs
self._piezo = prefix.replace('MIRR', 'PIEZO')
super().__init__(prefix, **kwargs)
class Gantry(OMMotor):
"""
Gantry Axis.
The horizontal and vertical motion of the OffsetMirror are controlled by
two coupled stepper motors. Instructions are sent to both by simply
requesting a move on the primary so they are represented here as a single
motor with additional diagnostics and interlock.
Parameters
----------
prefix : str
Base prefix for both stepper motors e.g. 'XRT:M1H'. Do not include the
'P' or 'S' to indicate primary or secondary steppers.
gantry_prefix : str, optional
Prefix for the shared gantry diagnostics if it is different than the
stepper motor prefix.
"""
# Readbacks for gantry information
gantry_difference = FCpt(EpicsSignalRO, '{self.gantry_prefix}:GDIF',
kind='normal')
decoupled = FCpt(EpicsSignalRO, '{self.gantry_prefix}:DECOUPLE',
kind='config')
# Readbacks for the secondary motor
follower_readback = FCpt(EpicsSignalRO, '{self.follow_prefix}:RBV',
kind='normal')
follower_low_limit_switch = FCpt(EpicsSignalRO, '{self.follow_prefix}:LLS',
kind='omitted')
follower_high_limit_switch = FCpt(EpicsSignalRO,
'{self.follow_prefix}:HLS',
kind='omitted')
def __init__(self, prefix, *, gantry_prefix=None, **kwargs):
self.gantry_prefix = gantry_prefix or 'GANTRY:' + prefix
self.follow_prefix = prefix + ':S'
super().__init__(prefix + ':P', **kwargs)
def check_value(self, pos):
"""
Add additional check for the gantry coupling.
This is not a safety measure, but instead just here largely
for bookkeeping and to give the operator further feedback on why the
requested move is not completed.
"""
# Check that the gantry is not decoupled
if self.decoupled.get():
raise PermissionError("The gantry is not currently coupled")
# Allow OMMotor to check the value
super().check_value(pos)
class OffsetMirror(BaseInterface, GroupDevice):
"""
X-ray Offset Mirror class.
This is for each individual mirror system used in the FEE
and XRT. Controls for the pitch, and primary gantry x- and y-motors are
included.
When controlling the pitch motor, if the piezo is set to 'PID' mode, then
the pitch mechanism is setup to first move the stepper as close to the
desired position, then the piezo will kick in to constantly try and correct
any positional changes.
Parameters
----------
prefix : str
The EPICS base PV of the pitch motor.
prefix_xy : str
The EPICS base PV of the gantry x and y gantry motors.
xgantry_prefix : str
The name of the horizontal gantry if not identical to the prefix.
name : str
The name of the offset mirror.
"""
# Pitch Motor
pitch = FCpt(Pitch, "MIRR:{self.prefix}", kind='hinted')
# Gantry motors
xgantry = FCpt(Gantry, "{self._prefix_xy}:X",
gantry_prefix="{self._xgantry}",
add_prefix=['suffix', 'gantry_prefix'],
kind='normal')
ygantry = FCpt(Gantry, "{self._prefix_xy}:Y",
gantry_prefix='GANTRY:{self.prefix}:Y',
add_prefix=['suffix', 'gantry_prefix'],
kind='config')
# Transmission for Lightpath Interface
transmission = 1.0
# QIcon for UX
_icon = 'fa.minus-square'
# Subscription types
SUB_STATE = 'state'
tab_whitelist = ['pitch', 'xgantry', 'ygantry']
def __init__(self, prefix, *, prefix_xy=None,
xgantry_prefix=None, **kwargs):
# Handle prefix mangling
self._prefix_xy = prefix_xy or prefix
self._xgantry = xgantry_prefix or 'GANTRY:' + prefix + ':X'
super().__init__(prefix, **kwargs)
@property
def inserted(self):
"""Returns `True`. Treats OffsetMirror as always inserted."""
return True
@property
def removed(self):
"""Returns :keyword:`False`. Treats OffsetMirror as always inserted."""
return False
def format_status_info(self, status_info):
"""
Override status info handler to render the `OffsetMirror`.
Display `OffsetMirror` status info in the ipython terminal.
Parameters
----------
status_info: dict
Nested dictionary. Each level has keys name, kind, and is_device.
If is_device is True, subdevice dictionaries may follow. Otherwise,
the only other key in the dictionary will be value.
Returns
-------
status: str
Formatted string with all relevant status information.
"""
# happi metadata
try:
md = self.root.md
except AttributeError:
name = f'{self.prefix}'
else:
beamline = get_status_value(md, 'beamline')
functional_group = get_status_value(md, 'functional_group')
if functional_group is not None:
name = f'{self.prefix} ({beamline} {functional_group})'
else:
name = f'{self.prefix} ({beamline})'
p_position = get_status_value(status_info, 'pitch', 'position')
p_setpoint = get_status_value(status_info, 'pitch',
'setpoint', 'value')
p_units = get_status_value(status_info, 'pitch', 'setpoint',
'units')
return f"""\
{name}
------
pitch: ({self.pitch.prefix})
------
position: {p_position}
setpoint: {p_setpoint} [{p_units}]
"""
class PointingMirror(InOutRecordPositioner, OffsetMirror):
"""
Retractable `OffsetMirror`.
Both XRT M1H and XRT M2H can be completely removed from the beam depending
on the beam destination. In this case, the X gantry can be controlled via
the standard PCDS states record. This class has all the functionality of
`OffsetMirror` with the addition of the records that control the
overall state.
Parameters
----------
in_lines : list, optional
List of beamlines that are delivered beam when the mirror is in.
out_lines : list, optional
List of beamlines thate are delivered beam when the mirror is out.
"""
# Reverse state order as PointingMirror is non-standard
states_list = ['OUT', 'IN']
# Moving PointingMirror moves the x gantry
stage_group = [OffsetMirror.xgantry]
def __init__(self, prefix, *, out_lines=None, in_lines=None, **kwargs):
# Branching pattern
self.in_lines = in_lines or list()
self.out_lines = out_lines or list()
super().__init__(prefix, **kwargs)
@property
def destination(self):
"""Current list of destinations the mirror currently supports."""
# Inserted
if self.inserted and not self.removed:
return self.in_lines
# Removed
elif self.removed and not self.inserted:
return self.out_lines
# Unknown
else:
return []
@property
def branches(self):
"""Return all possible beamlines for mirror destinations."""
return self.in_lines + self.out_lines
def check_value(self, pos):
"""Check that our gantry is coupled before state moves."""
# Check the X gantry
if self.xgantry.decoupled.get():
raise PermissionError("Can not move the horizontal gantry is "
"uncoupled")
# Allow StatePositioner to check the state
return super().check_value(pos)
class XOffsetMirror(BaseInterface, GroupDevice):
"""
X-ray Offset Mirror.
1st and 2nd gen Axilon designs with LCLS-II Beckhoff motion architecture.
Parameters
----------
prefix : str
Base PV for the mirror.
name : str
Alias for the device.
"""
# UI representation
_icon = 'fa.minus-square'
# Motor components: can read/write positions
y_up = Cpt(BeckhoffAxisNoOffset, ':MMS:YUP', kind='hinted',
doc='Yupstream master axis [um]')
x_up = Cpt(BeckhoffAxisNoOffset, ':MMS:XUP', kind='hinted',
doc='Xupstream master [um]')
pitch = Cpt(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted',
doc='Pitch stepper and piezo axes [urad]')
bender = Cpt(BeckhoffAxisNoOffset, ':MMS:BENDER', kind='normal',
doc='Bender motor [um]')
y_dwn = Cpt(BeckhoffAxisNoOffset, ':MMS:YDWN', kind='config',
doc='Ydwnstream slave axis [um]')
x_dwn = Cpt(BeckhoffAxisNoOffset, ':MMS:XDWN', kind='config',
doc='Xdwnstream slave axis [um]')
# Gantry components
gantry_x = Cpt(PytmcSignal, ':GANTRY_X', io='i', kind='normal',
doc='X gantry difference [um]')
gantry_y = Cpt(PytmcSignal, ':GANTRY_Y', io='i', kind='normal',
doc='Y gantry difference [um]')
couple_y = Cpt(PytmcSignal, ':COUPLE_Y', io='o', kind='config',
doc='Couple Y motors [bool]')
couple_x = Cpt(PytmcSignal, ':COUPLE_X', io='o', kind='config',
doc='Couple X motors [bool]')
decouple_y = Cpt(PytmcSignal, ':DECOUPLE_Y', io='o', kind='config',
doc='Decouple Y motors [bool]')
decouple_x = Cpt(PytmcSignal, ':DECOUPLE_X', io='o', kind='config',
doc='Decouple X motors [bool]')
couple_status_y = Cpt(PytmcSignal, ':ALREADY_COUPLED_Y', io='i',
kind='normal')
couple_status_x = Cpt(PytmcSignal, ':ALREADY_COUPLED_X', io='i',
kind='normal')
# RMS Cpts:
y_enc_rms = Cpt(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal',
doc='Yup encoder RMS deviation [um]')
x_enc_rms = Cpt(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal',
doc='Xup encoder RMS deviation [um]')
pitch_enc_rms = Cpt(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal',
doc='Pitch encoder RMS deviation [urad]')
bender_enc_rms = Cpt(PytmcSignal, ':ENC:BENDER:RMS', io='i',
kind='normal',
doc='Bender encoder RMS deviation [um]')
# Lightpath config: implement inserted, removed, transmission, subscribe
# For now, keep it simple. Some mirrors need more than this, but it is
# sufficient for MR1L0 and MR2L0 for today.
inserted = True
removed = False
transmission = 1
SUB_STATE = 'state'
def format_status_info(self, status_info):
"""
Override status info handler to render the Hard X-ray Offset Mirror.
Display homs status info in the ipython terminal.
Parameters
----------
status_info: dict
Nested dictionary. Each level has keys name, kind, and is_device.
If is_device is True, subdevice dictionaries may follow. Otherwise,
the only other key in the dictionary will be value.
Returns
-------
status: str
Formatted string with all relevant status information.
"""
# happi metadata
try:
md = self.root.md
except AttributeError:
name = f'{self.prefix}'
else:
beamline = get_status_value(md, 'beamline')
functional_group = get_status_value(md, 'functional_group')
if functional_group is not None:
name = f'{self.prefix} ({beamline} {functional_group})'
else:
name = f'{self.prefix} ({beamline})'
x_position = get_status_value(status_info, 'x_up', 'position')
x_user_setpoint = get_status_value(status_info, 'x_up',
'user_setpoint', 'value')
x_units = get_status_value(status_info, 'x_up', 'user_setpoint',
'units')
x_description = get_status_value(status_info, 'x_up', 'description',
'value')
p_position = get_status_value(status_info, 'pitch', 'position')
p_user_setpoint = get_status_value(status_info, 'pitch',
'user_setpoint', 'value')
p_units = get_status_value(status_info, 'pitch', 'user_setpoint',
'units')
p_description = get_status_value(status_info, 'pitch', 'description',
'value')
p_enc_rms = get_status_value(status_info, 'pitch_enc_rms', 'value')
return f"""\
{name}
------
x_up: ({self.x_up.prefix})
------
position: {x_position}
user_setpoint: {x_user_setpoint} [{x_units}]
description: {x_description}
------
pitch: ({self.pitch.prefix})
------
position: {p_position}
user_setpoint: {p_user_setpoint} [{p_units}]
description: {p_description}
pitch_enc_rms: {p_enc_rms}
"""
class XOffsetMirrorBend(XOffsetMirror):
"""
X-ray Offset Mirror with 2 bender acutators.
1st and 2nd gen Axilon designs with LCLS-II Beckhoff motion architecture.
Parameters
----------
prefix : str
Base PV for the mirror.
name : str
Alias for the device.
"""
# UI representation
_icon = 'fa.minus-square'
# Do a dumb thing and kill inherited single bender
bender = None
bender_enc_rms = None
# Motor components: can read/write positions
bender_us = Cpt(BeckhoffAxisNoOffset, ':MMS:US', kind='hinted')
bender_ds = Cpt(BeckhoffAxisNoOffset, ':MMS:DS', kind='hinted')
# RMS Cpts:
bender_us_enc_rms = Cpt(PytmcSignal, ':ENC:US:RMS', io='i',
kind='normal')
bender_ds_enc_rms = Cpt(PytmcSignal, ':ENC:DS:RMS', io='i',
kind='normal')
# Bender RTD Cpts:
us_rtd = Cpt(EpicsSignalRO, ':RTD:US:1_RBV', kind='normal')
ds_rtd = Cpt(EpicsSignalRO, ':RTD:DS:1_RBV', kind='normal')
# Maintain backward compatibility
XOffsetMirror2 = XOffsetMirrorBend
class XOffsetMirrorSwitch(XOffsetMirror):
"""
X-ray Offset Mirror with Yleft/Yright
1st and 2nd gen Axilon designs with LCLS-II Beckhoff motion architecture.
Parameters
----------
prefix : str
Base PV for the mirror.
name : str
Alias for the device.
"""
# UI representation
_icon = 'fa.minus-square'
# Do a dumb thing and kill inherited/unused components
y_up = None
y_dwn = None
bender = None
bender_enc_rms = None
# Motor components: can read/write positions
y_left = Cpt(BeckhoffAxisNoOffset, ':MMS:YLEFT', kind='hinted',
doc='Yleft master axis [um]')
y_right = Cpt(BeckhoffAxisNoOffset, ':MMS:YRIGHT', kind='config',
doc='Yright slave axis [um]')
class KBOMirror(BaseInterface, GroupDevice):
"""
Kirkpatrick-Baez Mirror with Bender Axes.
1st gen Toyama designs with LCLS-II Beckhoff motion architecture.
Parameters
----------
prefix : str
Base PV for the mirror.
name : str
Alias for the device.
"""
# UI representation
_icon = 'fa.minus-square'
# Motor components: can read/write positions
x = Cpt(BeckhoffAxisNoOffset, ':MMS:X', kind='hinted')
y = Cpt(BeckhoffAxisNoOffset, ':MMS:Y', kind='hinted')
pitch = Cpt(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted')
bender_us = Cpt(BeckhoffAxisNoOffset, ':MMS:BEND:US', kind='hinted')
bender_ds = Cpt(BeckhoffAxisNoOffset, ':MMS:BEND:DS', kind='hinted')
# RMS Cpts:
x_enc_rms = Cpt(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal')
y_enc_rms = Cpt(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal')
pitch_enc_rms = Cpt(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal')
bender_us_enc_rms = Cpt(PytmcSignal, ':ENC:BEND:US:RMS', io='i',
kind='normal')
bender_ds_enc_rms = Cpt(PytmcSignal, ':ENC:BEND:DS:RMS', io='i',
kind='normal')
# Bender RTD Cpts:
us_rtd = Cpt(EpicsSignalRO, ':RTD:BEND:US:1_RBV', kind='normal')
ds_rtd = Cpt(EpicsSignalRO, ':RTD:BEND:DS:1_RBV', kind='normal')
# Lightpath config: implement inserted, removed, transmission, subscribe
inserted = True
removed = False
transmission = 1
SUB_STATE = 'state'
def format_status_info(self, status_info):
"""
Override status info handler to render the `KBOMirror`.
Display `KBOMirror` status info in the ipython terminal.
Parameters
----------
status_info: dict
Nested dictionary. Each level has keys name, kind, and is_device.
If is_device is True, subdevice dictionaries may follow. Otherwise,
the only other key in the dictionary will be value.
Returns
-------
status: str
Formatted string with all relevant status information.
"""
# happi metadata
try:
md = self.root.md
except AttributeError:
name = f'{self.prefix}'
else:
beamline = get_status_value(md, 'beamline')
functional_group = get_status_value(md, 'functional_group')
if functional_group is not None:
name = f'{self.prefix} ({beamline} {functional_group})'
else:
name = f'{self.prefix} ({beamline})'
x_position = get_status_value(status_info, 'x', 'position')
x_user_setpoint = get_status_value(status_info, 'x',
'user_setpoint', 'value')
x_units = get_status_value(status_info, 'x', 'user_setpoint',
'units')
x_description = get_status_value(status_info, 'x', 'description',
'value')
p_position = get_status_value(status_info, 'pitch', 'position')
p_user_setpoint = get_status_value(status_info, 'pitch',
'user_setpoint', 'value')
p_units = get_status_value(status_info, 'pitch', 'user_setpoint',
'units')
p_description = get_status_value(status_info, 'pitch', 'description',
'value')
p_enc_rms = get_status_value(status_info, 'pitch_enc_rms', 'value')
b_us_position = get_status_value(status_info, 'bender_us', 'position')
b_us_setpoint = get_status_value(status_info, 'bender_us',
'user_setpoint', 'value')
b_us_units = get_status_value(status_info, 'bender_us',
'user_setpoint', 'units')
b_us_description = get_status_value(status_info, 'bender_us',
'description', 'value')
b_us_enc_rms = get_status_value(status_info, 'bender_us_enc_rms',
'value')
b_ds_position = get_status_value(status_info, 'bender_ds', 'position')
b_ds_setpoint = get_status_value(status_info, 'bender_ds',
'user_setpoint', 'value')
b_ds_units = get_status_value(status_info, 'bender_ds',
'user_setpoint', 'units')
b_ds_description = get_status_value(status_info, 'bender_ds',
'description', 'value')
b_ds_enc_rms = get_status_value(status_info, 'bender_ds_enc_rms',
'value')
return f"""\
{name}
------
x_up: ({self.x.prefix})
------
position: {x_position}
user_setpoint: {x_user_setpoint} [{x_units}]
description: {x_description}
------
pitch: ({self.pitch.prefix})
------
position: {p_position}
user_setpoint: {p_user_setpoint} [{p_units}]
description: {p_description}
pitch_enc_rms: {p_enc_rms}
---------
bender_us ({self.bender_us.prefix})
---------
position {b_us_position}
user_setpoint: {b_us_setpoint} [{b_us_units}]
description: {b_us_description}
bender_us_enc_rms: {b_us_enc_rms}
---------
bender_ds ({self.bender_ds.prefix})
---------
position: {b_ds_position}
user_setpoint: {b_ds_setpoint} [{b_ds_units}]
description: {b_ds_description}
bender_ds_enc_rms: {b_ds_enc_rms}
"""
class FFMirror(BaseInterface, GroupDevice):
"""
Fixed Focus Kirkpatrick-Baez Mirror.
1st gen Toyama designs with LCLS-II Beckhoff motion architecture.
Parameters
----------
prefix : str
Base PV for the mirror.
name : str
Alias for the device.
"""
# UI representation
_icon = 'fa.minus-square'
# Motor components: can read/write positions
x = Cpt(BeckhoffAxisNoOffset, ':MMS:X', kind='hinted')
y = Cpt(BeckhoffAxisNoOffset, ':MMS:Y', kind='hinted')
pitch = Cpt(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted')
# RMS Cpts:
x_enc_rms = Cpt(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal')
y_enc_rms = Cpt(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal')
pitch_enc_rms = Cpt(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal')
# Lightpath config: implement inserted, removed, transmission, subscribe
inserted = True
removed = False
transmission = 1
SUB_STATE = 'state'
def format_status_info(self, status_info):
"""
Override status info handler to render the `FFMirror`.
Display `FFMirror` status info in the ipython terminal.
Parameters
----------
status_info: dict
Nested dictionary. Each level has keys name, kind, and is_device.
If is_device is True, subdevice dictionaries may follow. Otherwise,
the only other key in the dictionary will be value.
Returns
-------
status: str
Formatted string with all relevant status information.
"""
# happi metadata
try:
md = self.root.md
except AttributeError:
name = f'{self.prefix}'
else:
beamline = get_status_value(md, 'beamline')
functional_group = get_status_value(md, 'functional_group')
if functional_group is not None:
name = f'{self.prefix} ({beamline} {functional_group})'
else:
name = f'{self.prefix} ({beamline})'
x_position = get_status_value(status_info, 'x', 'position')
x_user_setpoint = get_status_value(status_info, 'x',
'user_setpoint', 'value')
x_units = get_status_value(status_info, 'x', 'user_setpoint',
'units')
x_description = get_status_value(status_info, 'x', 'description',
'value')
p_position = get_status_value(status_info, 'pitch', 'position')
p_user_setpoint = get_status_value(status_info, 'pitch',
'user_setpoint', 'value')
p_units = get_status_value(status_info, 'pitch', 'user_setpoint',
'units')
p_description = get_status_value(status_info, 'pitch', 'description',
'value')
p_enc_rms = get_status_value(status_info, 'pitch_enc_rms', 'value')
return f"""\
{name}
------
x_up: ({self.x.prefix})
------
position: {x_position}
user_setpoint: {x_user_setpoint} [{x_units}]
description: {x_description}
------
pitch: ({self.pitch.prefix})
------
position: {p_position}
user_setpoint: {p_user_setpoint} [{p_units}]
description: {p_description}
pitch_enc_rms: {p_enc_rms}
"""
class TwinCATMirrorStripe(TwinCATStatePMPS):
"""
Subclass of TwinCATStatePMPS for the mirror coatings.
Unless most TwinCATStatePMPS, we have:
- Only in_states
- No in_states block the beam
We also clear the states_list and set _in_if_not_out to True
to automatically pick up the coatings from each mirror enum.
"""
states_list = []
in_states = []
out_states = []
_in_if_not_out = True
@property
def transmission(self):
"""The mirror coating never blocks the beam."""
return 1
class CoatingState(Device):
"""
Extra parent class to put "coating" as the first device in order.
This makes it appear at the top of the screen in typhos.
"""
coating = Cpt(TwinCATMirrorStripe, ':COATING:STATE', kind='hinted',
doc='Control of the coating states via saved positions.')
class XOffsetMirrorState(XOffsetMirror, CoatingState):
"""
X-ray Offset Mirror with Yleft/Yright
1st and 2nd gen Axilon designs with LCLS-II Beckhoff motion architecture.
With Coating State selection implemented
Parameters
----------
prefix : str
Base PV for the mirror.
name : str
Alias for the device.
"""
# UI representation
_icon = 'fa.minus-square'
| [
"logging.getLogger",
"ophyd.Component",
"numpy.isnan",
"numpy.isinf",
"ophyd.FormattedComponent"
] | [((810, 837), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (827, 837), False, 'import logging\n'), ((1023, 1083), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RBV"""'], {'auto_monitor': '(True)', 'kind': '"""hinted"""'}), "(EpicsSignalRO, ':RBV', auto_monitor=True, kind='hinted')\n", (1026, 1083), True, 'from ophyd import Component as Cpt\n'), ((1099, 1170), 'ophyd.Component', 'Cpt', (['EpicsSignal', '""":VAL"""'], {'auto_monitor': '(True)', 'limits': '(True)', 'kind': '"""normal"""'}), "(EpicsSignal, ':VAL', auto_monitor=True, limits=True, kind='normal')\n", (1102, 1170), True, 'from ophyd import Component as Cpt\n'), ((1201, 1263), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":DMOV"""'], {'auto_monitor': '(True)', 'kind': '"""omitted"""'}), "(EpicsSignalRO, ':DMOV', auto_monitor=True, kind='omitted')\n", (1204, 1263), True, 'from ophyd import Component as Cpt\n'), ((1280, 1324), 'ophyd.Component', 'Cpt', (['EpicsSignal', '""":RBV.EGU"""'], {'kind': '"""omitted"""'}), "(EpicsSignal, ':RBV.EGU', kind='omitted')\n", (1283, 1324), True, 'from ophyd import Component as Cpt\n'), ((1355, 1403), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":INTERLOCK"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, ':INTERLOCK', kind='omitted')\n", (1358, 1403), True, 'from ophyd import Component as Cpt\n'), ((1418, 1464), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":ENABLED"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, ':ENABLED', kind='omitted')\n", (1421, 1464), True, 'from ophyd import Component as Cpt\n'), ((1509, 1551), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":LLS"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, ':LLS', kind='omitted')\n", (1512, 1551), True, 'from ophyd import Component as Cpt\n'), ((1576, 1618), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":HLS"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, ':HLS', kind='omitted')\n", (1579, 1618), True, 'from ophyd import Component as Cpt\n'), ((2829, 2885), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self._piezo}:VRBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, '{self._piezo}:VRBV', kind='normal')\n", (2833, 2885), True, 'from ophyd import FormattedComponent as FCpt\n'), ((2904, 2959), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignal', '"""{self._piezo}:STOP"""'], {'kind': '"""omitted"""'}), "(EpicsSignal, '{self._piezo}:STOP', kind='omitted')\n", (2908, 2959), True, 'from ophyd import FormattedComponent as FCpt\n'), ((3939, 4002), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.gantry_prefix}:GDIF"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, '{self.gantry_prefix}:GDIF', kind='normal')\n", (3943, 4002), True, 'from ophyd import FormattedComponent as FCpt\n'), ((4048, 4115), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.gantry_prefix}:DECOUPLE"""'], {'kind': '"""config"""'}), "(EpicsSignalRO, '{self.gantry_prefix}:DECOUPLE', kind='config')\n", (4052, 4115), True, 'from ophyd import FormattedComponent as FCpt\n'), ((4201, 4263), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.follow_prefix}:RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, '{self.follow_prefix}:RBV', kind='normal')\n", (4205, 4263), True, 'from ophyd import FormattedComponent as FCpt\n'), ((4325, 4388), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.follow_prefix}:LLS"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, '{self.follow_prefix}:LLS', kind='omitted')\n", (4329, 4388), True, 'from ophyd import FormattedComponent as FCpt\n'), ((4459, 4522), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.follow_prefix}:HLS"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, '{self.follow_prefix}:HLS', kind='omitted')\n", (4463, 4522), True, 'from ophyd import FormattedComponent as FCpt\n'), ((6229, 6277), 'ophyd.FormattedComponent', 'FCpt', (['Pitch', '"""MIRR:{self.prefix}"""'], {'kind': '"""hinted"""'}), "(Pitch, 'MIRR:{self.prefix}', kind='hinted')\n", (6233, 6277), True, 'from ophyd import FormattedComponent as FCpt\n'), ((6312, 6439), 'ophyd.FormattedComponent', 'FCpt', (['Gantry', '"""{self._prefix_xy}:X"""'], {'gantry_prefix': '"""{self._xgantry}"""', 'add_prefix': "['suffix', 'gantry_prefix']", 'kind': '"""normal"""'}), "(Gantry, '{self._prefix_xy}:X', gantry_prefix='{self._xgantry}',\n add_prefix=['suffix', 'gantry_prefix'], kind='normal')\n", (6316, 6439), True, 'from ophyd import FormattedComponent as FCpt\n'), ((6507, 6641), 'ophyd.FormattedComponent', 'FCpt', (['Gantry', '"""{self._prefix_xy}:Y"""'], {'gantry_prefix': '"""GANTRY:{self.prefix}:Y"""', 'add_prefix': "['suffix', 'gantry_prefix']", 'kind': '"""config"""'}), "(Gantry, '{self._prefix_xy}:Y', gantry_prefix='GANTRY:{self.prefix}:Y',\n add_prefix=['suffix', 'gantry_prefix'], kind='config')\n", (6511, 6641), True, 'from ophyd import FormattedComponent as FCpt\n'), ((11405, 11496), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:YUP"""'], {'kind': '"""hinted"""', 'doc': '"""Yupstream master axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:YUP', kind='hinted', doc=\n 'Yupstream master axis [um]')\n", (11408, 11496), True, 'from ophyd import Component as Cpt\n'), ((11518, 11604), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:XUP"""'], {'kind': '"""hinted"""', 'doc': '"""Xupstream master [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:XUP', kind='hinted', doc=\n 'Xupstream master [um]')\n", (11521, 11604), True, 'from ophyd import Component as Cpt\n'), ((11627, 11729), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:PITCH"""'], {'kind': '"""hinted"""', 'doc': '"""Pitch stepper and piezo axes [urad]"""'}), "(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted', doc=\n 'Pitch stepper and piezo axes [urad]')\n", (11630, 11729), True, 'from ophyd import Component as Cpt\n'), ((11754, 11839), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:BENDER"""'], {'kind': '"""normal"""', 'doc': '"""Bender motor [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:BENDER', kind='normal', doc='Bender motor [um]'\n )\n", (11757, 11839), True, 'from ophyd import Component as Cpt\n'), ((11864, 11956), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:YDWN"""'], {'kind': '"""config"""', 'doc': '"""Ydwnstream slave axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:YDWN', kind='config', doc=\n 'Ydwnstream slave axis [um]')\n", (11867, 11956), True, 'from ophyd import Component as Cpt\n'), ((11980, 12072), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:XDWN"""'], {'kind': '"""config"""', 'doc': '"""Xdwnstream slave axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:XDWN', kind='config', doc=\n 'Xdwnstream slave axis [um]')\n", (11983, 12072), True, 'from ophyd import Component as Cpt\n'), ((12124, 12213), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":GANTRY_X"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""X gantry difference [um]"""'}), "(PytmcSignal, ':GANTRY_X', io='i', kind='normal', doc=\n 'X gantry difference [um]')\n", (12127, 12213), True, 'from ophyd import Component as Cpt\n'), ((12243, 12332), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":GANTRY_Y"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Y gantry difference [um]"""'}), "(PytmcSignal, ':GANTRY_Y', io='i', kind='normal', doc=\n 'Y gantry difference [um]')\n", (12246, 12332), True, 'from ophyd import Component as Cpt\n'), ((12362, 12449), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":COUPLE_Y"""'], {'io': '"""o"""', 'kind': '"""config"""', 'doc': '"""Couple Y motors [bool]"""'}), "(PytmcSignal, ':COUPLE_Y', io='o', kind='config', doc=\n 'Couple Y motors [bool]')\n", (12365, 12449), True, 'from ophyd import Component as Cpt\n'), ((12479, 12566), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":COUPLE_X"""'], {'io': '"""o"""', 'kind': '"""config"""', 'doc': '"""Couple X motors [bool]"""'}), "(PytmcSignal, ':COUPLE_X', io='o', kind='config', doc=\n 'Couple X motors [bool]')\n", (12482, 12566), True, 'from ophyd import Component as Cpt\n'), ((12598, 12689), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":DECOUPLE_Y"""'], {'io': '"""o"""', 'kind': '"""config"""', 'doc': '"""Decouple Y motors [bool]"""'}), "(PytmcSignal, ':DECOUPLE_Y', io='o', kind='config', doc=\n 'Decouple Y motors [bool]')\n", (12601, 12689), True, 'from ophyd import Component as Cpt\n'), ((12723, 12814), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":DECOUPLE_X"""'], {'io': '"""o"""', 'kind': '"""config"""', 'doc': '"""Decouple X motors [bool]"""'}), "(PytmcSignal, ':DECOUPLE_X', io='o', kind='config', doc=\n 'Decouple X motors [bool]')\n", (12726, 12814), True, 'from ophyd import Component as Cpt\n'), ((12853, 12914), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ALREADY_COUPLED_Y"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ALREADY_COUPLED_Y', io='i', kind='normal')\n", (12856, 12914), True, 'from ophyd import Component as Cpt\n'), ((12963, 13024), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ALREADY_COUPLED_X"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ALREADY_COUPLED_X', io='i', kind='normal')\n", (12966, 13024), True, 'from ophyd import Component as Cpt\n'), ((13083, 13179), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:Y:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Yup encoder RMS deviation [um]"""'}), "(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal', doc=\n 'Yup encoder RMS deviation [um]')\n", (13086, 13179), True, 'from ophyd import Component as Cpt\n'), ((13211, 13307), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:X:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Xup encoder RMS deviation [um]"""'}), "(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal', doc=\n 'Xup encoder RMS deviation [um]')\n", (13214, 13307), True, 'from ophyd import Component as Cpt\n'), ((13343, 13447), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:PITCH:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Pitch encoder RMS deviation [urad]"""'}), "(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal', doc=\n 'Pitch encoder RMS deviation [urad]')\n", (13346, 13447), True, 'from ophyd import Component as Cpt\n'), ((13488, 13592), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:BENDER:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Bender encoder RMS deviation [um]"""'}), "(PytmcSignal, ':ENC:BENDER:RMS', io='i', kind='normal', doc=\n 'Bender encoder RMS deviation [um]')\n", (13491, 13592), True, 'from ophyd import Component as Cpt\n'), ((16880, 16931), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:US"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:US', kind='hinted')\n", (16883, 16931), True, 'from ophyd import Component as Cpt\n'), ((16948, 16999), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:DS"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:DS', kind='hinted')\n", (16951, 16999), True, 'from ophyd import Component as Cpt\n'), ((17041, 17095), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:US:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:US:RMS', io='i', kind='normal')\n", (17044, 17095), True, 'from ophyd import Component as Cpt\n'), ((17148, 17202), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:DS:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:DS:RMS', io='i', kind='normal')\n", (17151, 17202), True, 'from ophyd import Component as Cpt\n'), ((17268, 17318), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RTD:US:1_RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, ':RTD:US:1_RBV', kind='normal')\n", (17271, 17318), True, 'from ophyd import Component as Cpt\n'), ((17332, 17382), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RTD:DS:1_RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, ':RTD:DS:1_RBV', kind='normal')\n", (17335, 17382), True, 'from ophyd import Component as Cpt\n'), ((18015, 18104), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:YLEFT"""'], {'kind': '"""hinted"""', 'doc': '"""Yleft master axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:YLEFT', kind='hinted', doc=\n 'Yleft master axis [um]')\n", (18018, 18104), True, 'from ophyd import Component as Cpt\n'), ((18131, 18221), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:YRIGHT"""'], {'kind': '"""config"""', 'doc': '"""Yright slave axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:YRIGHT', kind='config', doc=\n 'Yright slave axis [um]')\n", (18134, 18221), True, 'from ophyd import Component as Cpt\n'), ((18653, 18703), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:X"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:X', kind='hinted')\n", (18656, 18703), True, 'from ophyd import Component as Cpt\n'), ((18712, 18762), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:Y"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:Y', kind='hinted')\n", (18715, 18762), True, 'from ophyd import Component as Cpt\n'), ((18775, 18829), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:PITCH"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted')\n", (18778, 18829), True, 'from ophyd import Component as Cpt\n'), ((18846, 18902), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:BEND:US"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:BEND:US', kind='hinted')\n", (18849, 18902), True, 'from ophyd import Component as Cpt\n'), ((18919, 18975), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:BEND:DS"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:BEND:DS', kind='hinted')\n", (18922, 18975), True, 'from ophyd import Component as Cpt\n'), ((19009, 19062), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:X:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal')\n", (19012, 19062), True, 'from ophyd import Component as Cpt\n'), ((19079, 19132), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:Y:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal')\n", (19082, 19132), True, 'from ophyd import Component as Cpt\n'), ((19153, 19210), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:PITCH:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal')\n", (19156, 19210), True, 'from ophyd import Component as Cpt\n'), ((19235, 19294), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:BEND:US:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:BEND:US:RMS', io='i', kind='normal')\n", (19238, 19294), True, 'from ophyd import Component as Cpt\n'), ((19347, 19406), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:BEND:DS:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:BEND:DS:RMS', io='i', kind='normal')\n", (19350, 19406), True, 'from ophyd import Component as Cpt\n'), ((19472, 19527), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RTD:BEND:US:1_RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, ':RTD:BEND:US:1_RBV', kind='normal')\n", (19475, 19527), True, 'from ophyd import Component as Cpt\n'), ((19541, 19596), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RTD:BEND:DS:1_RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, ':RTD:BEND:DS:1_RBV', kind='normal')\n", (19544, 19596), True, 'from ophyd import Component as Cpt\n'), ((24196, 24246), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:X"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:X', kind='hinted')\n", (24199, 24246), True, 'from ophyd import Component as Cpt\n'), ((24255, 24305), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:Y"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:Y', kind='hinted')\n", (24258, 24305), True, 'from ophyd import Component as Cpt\n'), ((24318, 24372), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:PITCH"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted')\n", (24321, 24372), True, 'from ophyd import Component as Cpt\n'), ((24406, 24459), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:X:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal')\n", (24409, 24459), True, 'from ophyd import Component as Cpt\n'), ((24476, 24529), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:Y:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal')\n", (24479, 24529), True, 'from ophyd import Component as Cpt\n'), ((24550, 24607), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:PITCH:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal')\n", (24553, 24607), True, 'from ophyd import Component as Cpt\n'), ((27917, 28037), 'ophyd.Component', 'Cpt', (['TwinCATMirrorStripe', '""":COATING:STATE"""'], {'kind': '"""hinted"""', 'doc': '"""Control of the coating states via saved positions."""'}), "(TwinCATMirrorStripe, ':COATING:STATE', kind='hinted', doc=\n 'Control of the coating states via saved positions.')\n", (27920, 28037), True, 'from ophyd import Component as Cpt\n'), ((2377, 2395), 'numpy.isnan', 'np.isnan', (['position'], {}), '(position)\n', (2385, 2395), True, 'import numpy as np\n'), ((2399, 2417), 'numpy.isinf', 'np.isinf', (['position'], {}), '(position)\n', (2407, 2417), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
from os import chmod
import pytest
TEMP_FOLDER = 'tmp'
MODE_EXECUTABLE = 0o755
MODE_NON_EXECUTABLE = 0o644
@pytest.fixture()
def make_file(tmp_path):
"""Fixture to make a temporary executable or non executable file."""
def factory(
filename: str,
file_content: str,
is_executable: bool,
) -> str:
temp_folder = tmp_path / TEMP_FOLDER
temp_folder.mkdir()
test_file = temp_folder / filename
file_mode = MODE_EXECUTABLE if is_executable else MODE_NON_EXECUTABLE
test_file.write_text(file_content)
chmod(test_file.as_posix(), file_mode)
return test_file.as_posix()
return factory
| [
"pytest.fixture"
] | [((137, 153), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (151, 153), False, 'import pytest\n')] |
# Copyright (c) 2020 <NAME>
from baselines.common import Dataset, explained_variance, fmt_row, zipsame
from baselines import logger
import baselines.common.tf_util as U
import tensorflow as tf, numpy as np
import time
from baselines.common.mpi_adam import MpiAdam
from baselines.common.mpi_moments import mpi_moments
from mpi4py import MPI
from collections import deque
import pdb
import os
import shutil
from scipy import spatial
import gym
def traj_segment_generator(pi, env, horizon, stochastic, num_options,saves,results,rewbuffer,dc):
# sample state action pairs, i.e. sample rollouts on the real system
max_action = env.action_space.high
t = 0
glob_count = 0
glob_count_thresh = -1
ac = env.action_space.sample() # not used, just so we have the datatype
new = True # marks if we're on first timestep of an episode
ob = env.reset()
ob_env_shape = np.shape(ob)
ac_env_shape = np.shape(ac)
ac = pi.reset_last_act().eval()
ob = np.concatenate((ob,ac))
cur_ep_ret = 0 # return in current episode
cur_ep_len = 0 # len of current episode
ep_rets = [] # returns of completed episodes in this segment
ep_lens = [] # lengths of ...
# Initialize history arrays
obs = np.array([ob for _ in range(horizon)])
rews = np.zeros(horizon, 'float32')
realrews = np.zeros(horizon, 'float32')
vpreds = np.zeros(horizon, 'float32')
news = np.zeros(horizon, 'int32')
opts = np.zeros(horizon, 'int32')
acs = np.array([ac for _ in range(horizon)])
prevacs = acs.copy()
option = pi.get_option(ob)
if (glob_count<glob_count_thresh):
option = 1
optpol_p=[]
term_p=[]
value_val=[]
opt_duration = [[] for _ in range(num_options)]
logstds = [[] for _ in range(num_options)]
curr_opt_duration = 0.
while True:
# in here collect the state action pairs:
prevac = ac
# remember u[k-1]
ob[ob_env_shape[0]:] = ac
# evaluate policy and recieve action
ac, vpred, feats,logstd = pi.act(stochastic, ob, option)
logstds[option].append(logstd)
# Slight weirdness here because we need value function at time T
# before returning segment [0, T-1] so we get the correct
# terminal value
if t > 0 and t % horizon == 0:
yield {"ob" : obs, "rew" : rews, "realrew": realrews, "vpred" : vpreds, "new" : news,
"ac" : acs, "opts" : opts, "prevac" : prevacs, "nextvpred": vpred * (1 - new),
"ep_rets" : ep_rets, "ep_lens" : ep_lens, 'term_p': term_p, 'value_val': value_val,
"opt_dur": opt_duration, "optpol_p":optpol_p, "logstds": logstds}
# Be careful!!! if you change the downstream algorithm to aggregate
# several of these batches, then be sure to do a deepcopy
ep_rets = []
ep_lens = []
term_p = []
value_val=[]
opt_duration = [[] for _ in range(num_options)]
logstds = [[] for _ in range(num_options)]
curr_opt_duration = 0.
glob_count += 1
i = t % horizon
obs[i] = ob
vpreds[i] = vpred
news[i] = new
opts[i] = option
acs[i] = ac
prevacs[i] = prevac
# Careful: Without this "copy" operation the variable ac is actually modified...
# Apply the action to the environment
ob[:ob_env_shape[0]], rew, new, _ = env.step(max_action*np.copy(ac))
# IMPORTANT: here there is no triggering decision
rew = rew*1.0
rew = rew/10 if num_options > 1 else rew # To stabilize learning.
rews[i] = rew
realrews[i] = rew
curr_opt_duration += 1
### Book-keeping
t_p = []
v_val = []
for oopt in range(num_options):
v_val.append(pi.get_vpred([ob],[oopt])[0][0])
t_p.append(pi.get_tpred([ob],[oopt])[0][0])
term_p.append(t_p)
optpol_p.append(pi._get_op([ob])[0][0])
value_val.append(v_val)
term = pi.get_term([ob],[option])[0][0]
# in case of termination, decide which option to execute next:
if term:
opt_duration[option].append(curr_opt_duration)
curr_opt_duration = 0.
option = pi.get_option(ob)
if (glob_count<glob_count_thresh):
option = 1
cur_ep_ret += rew*10 if num_options > 1 else rew
cur_ep_len += 1
if new:
# if new rollout starts -> reset last action and start anew
ep_rets.append(cur_ep_ret)
ep_lens.append(cur_ep_len)
cur_ep_ret = 0
cur_ep_len = 0
ob[:ob_env_shape[0]] = env.reset()
ob[ob_env_shape[0]:] = pi.reset_last_act().eval()
ac = pi.reset_last_act().eval()
option = pi.get_option(ob)
if (glob_count<glob_count_thresh):
option = 1
t += 1
def add_vtarg_and_adv(seg, gamma, lam):
"""
Compute target value using TD(lambda) estimator, and advantage with GAE(lambda)
"""
new = np.append(seg["new"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1
vpred = np.append(seg["vpred"], seg["nextvpred"])
T = len(seg["rew"])
seg["adv"] = gaelam = np.empty(T, 'float32')
rew = seg["rew"]
lastgaelam = 0
for t in reversed(range(T)):
nonterminal = 1-new[t+1]
delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t]
gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
seg["tdlamret"] = seg["adv"] + seg["vpred"]
def learn(env, policy_func, *,
timesteps_per_batch, # timesteps per actor per update
clip_param, entcoeff, # clipping parameter epsilon, entropy coeff
optim_epochs, optim_stepsize, optim_batchsize,# optimization hypers
gamma, lam, # advantage estimation
max_timesteps=0, max_episodes=0, max_iters=0, max_seconds=0, # time constraint
callback=None, # you can do anything in the callback, since it takes locals(), globals()
adam_epsilon=1e-5,
schedule='constant', # annealing for stepsize parameters (epsilon and adam)
num_options=1,
app='',
saves=False,
wsaves=False,
epoch=-1,
seed=1,
dc=0
):
optim_batchsize_ideal = optim_batchsize
np.random.seed(seed)
tf.set_random_seed(seed)
env.seed(seed)
### Book-keeping
gamename = env.spec.id[:-3].lower()
gamename += 'seed' + str(seed)
gamename += app
# This variable: "version name, defines the name of the training"
version_name = 'NORM-ACT-LOWER-LR-len-400-wNoise-update1-ppo-ESCH-1-own-impl-both-equal'
dirname = '{}_{}_{}opts_saves/'.format(version_name,gamename,num_options)
print (dirname)
# retrieve everything using relative paths. Create a train_results folder where the repo has been cloned
dirname_rel = os.path.dirname(__file__)
splitted = dirname_rel.split("/")
dirname_rel = ("/".join(dirname_rel.split("/")[:len(splitted)-3])+"/")
dirname = dirname_rel + "train_results/" + dirname
# if saving -> create the necessary directories
if wsaves:
first=True
if not os.path.exists(dirname):
os.makedirs(dirname)
first = False
# copy also the original files into the folder where the training results are stored
files = ['pposgd_simple.py','mlp_policy.py','run_mujoco.py']
first = True
for i in range(len(files)):
src = os.path.join(dirname_rel,'baselines/baselines/ppo1/') + files[i]
print (src)
#dest = os.path.join('/home/nfunk/results_NEW/ppo1/') + dirname
dest = dirname + "src_code/"
if (first):
os.makedirs(dest)
first = False
print (dest)
shutil.copy2(src,dest)
# brute force copy normal env file at end of copying process:
src = os.path.join(dirname_rel,'nfunk/envs_nf/pendulum_nf.py')
shutil.copy2(src,dest)
shutil.copy2(src,dest)
os.makedirs(dest+"assets/")
src = os.path.join(dirname_rel,'nfunk/envs_nf/assets/clockwise.png')
shutil.copy2(src,dest+"assets/")
###
# Setup losses and stuff
# ----------------------------------------
ob_space = env.observation_space
ac_space = env.action_space
max_action = env.action_space.high
# add the dimension in the observation space!
ob_space.shape =((ob_space.shape[0] + ac_space.shape[0]),)
print (ob_space.shape)
print (ac_space.shape)
pi = policy_func("pi", ob_space, ac_space) # Construct network for new policy
oldpi = policy_func("oldpi", ob_space, ac_space) # Network for old policy
atarg = tf.placeholder(dtype=tf.float32, shape=[None]) # Target advantage function
ret = tf.placeholder(dtype=tf.float32, shape=[None]) # Empirical return
pol_ov_op_ent = tf.placeholder(dtype=tf.float32, shape=None) # Entropy coefficient for policy over options
lrmult = tf.placeholder(name='lrmult', dtype=tf.float32, shape=[]) # learning rate multiplier, updated with schedule
clip_param = clip_param * lrmult # Annealed cliping parameter epislon for PPO
# setup observation, option and terminal advantace
ob = U.get_placeholder_cached(name="ob")
option = U.get_placeholder_cached(name="option")
term_adv = U.get_placeholder(name='term_adv', dtype=tf.float32, shape=[None])
# create variable for action
ac = pi.pdtype.sample_placeholder([None])
kloldnew = oldpi.pd.kl(pi.pd)
ent = pi.pd.entropy()
meankl = U.mean(kloldnew)
meanent = U.mean(ent)
pol_entpen = (-entcoeff) * meanent
# propability of choosing action under new policy vs old policy (PPO)
ratio = tf.exp(pi.pd.logp(ac) - oldpi.pd.logp(ac))
# advantage of choosing the action
atarg_clip = atarg
# surrogate 1:
surr1 = ratio * atarg_clip #atarg # surrogate from conservative policy iteration
# surrogate 2:
surr2 = U.clip(ratio, 1.0 - clip_param, 1.0 + clip_param) * atarg_clip
# PPO's pessimistic surrogate (L^CLIP)
pol_surr = - U.mean(tf.minimum(surr1, surr2))
# Loss on the Q-function
vf_loss = U.mean(tf.square(pi.vpred - ret))
# calculate the total loss
total_loss = pol_surr + vf_loss
losses = [pol_surr, pol_entpen, vf_loss, meankl, meanent]
loss_names = ["pol_surr", "pol_entpen", "vf_loss", "kl", "ent"]
# calculate logarithm of propability of policy over options
log_pi = tf.log(tf.clip_by_value(pi.op_pi, 1e-5, 1.0))
# calculate logarithm of propability of policy over options old parameter
old_log_pi = tf.log(tf.clip_by_value(oldpi.op_pi, 1e-5, 1.0))
# calculate entropy of policy over options
entropy = -tf.reduce_sum(pi.op_pi * log_pi, reduction_indices=1)
# calculate the ppo update for the policy over options:
ratio_pol_ov_op = tf.exp(tf.transpose(log_pi)[option[0]] - tf.transpose(old_log_pi)[option[0]]) # pnew / pold
term_adv_clip = term_adv
surr1_pol_ov_op = ratio_pol_ov_op * term_adv_clip # surrogate from conservative policy iteration
surr2_pol_ov_op = U.clip(ratio_pol_ov_op, 1.0 - clip_param, 1.0 + clip_param) * term_adv_clip #
pol_surr_pol_ov_op = - U.mean(tf.minimum(surr1_pol_ov_op, surr2_pol_ov_op)) # PPO's pessimistic surrogate (L^CLIP)
op_loss = pol_surr_pol_ov_op - pol_ov_op_ent*tf.reduce_sum(entropy)
# add loss of policy over options to total loss
total_loss += op_loss
var_list = pi.get_trainable_variables()
term_list = var_list[6:8]
# define function that we will later do gradien descent on
lossandgrad = U.function([ob, ac, atarg, ret, lrmult,option, term_adv,pol_ov_op_ent], losses + [U.flatgrad(total_loss, var_list)])
# define adam optimizer
adam = MpiAdam(var_list, epsilon=adam_epsilon)
# define function that will assign the current parameters to the old policy
assign_old_eq_new = U.function([],[], updates=[tf.assign(oldv, newv)
for (oldv, newv) in zipsame(oldpi.get_variables(), pi.get_variables())])
compute_losses = U.function([ob, ac, atarg, ret, lrmult, option], losses)
U.initialize()
adam.sync()
# NOW: all the stuff for training was defined, from here on we start with the execution:
# initialize "savers" which will store the results
saver = tf.train.Saver(max_to_keep=10000)
saver_best = tf.train.Saver(max_to_keep=1)
### Define the names of the .csv files that are going to be stored
results=[]
if saves:
results = open(dirname + version_name + '_' + gamename +'_'+str(num_options)+'opts_'+'_results.csv','w')
results_best_model = open(dirname + version_name + '_' + gamename +'_'+str(num_options)+'opts_'+'_bestmodel.csv','w')
out = 'epoch,avg_reward'
for opt in range(num_options): out += ',option {} dur'.format(opt)
for opt in range(num_options): out += ',option {} std'.format(opt)
for opt in range(num_options): out += ',option {} term'.format(opt)
for opt in range(num_options): out += ',option {} adv'.format(opt)
out+='\n'
results.write(out)
# results.write('epoch,avg_reward,option 1 dur, option 2 dur, option 1 term, option 2 term\n')
results.flush()
# speciality: if running the training with epoch argument -> a model is loaded
if epoch >= 0:
dirname = '{}_{}opts_saves/'.format(gamename,num_options)
print("Loading weights from iteration: " + str(epoch))
filename = dirname + '{}_epoch_{}.ckpt'.format(gamename,epoch)
saver.restore(U.get_session(),filename)
###
# start training
episodes_so_far = 0
timesteps_so_far = 0
global iters_so_far
iters_so_far = 0
des_pol_op_ent = 0.1 # define policy over options entropy scheduling
max_val = -100000 # define max_val, this will be updated to always store the best model
tstart = time.time()
lenbuffer = deque(maxlen=100) # rolling buffer for episode lengths
rewbuffer = deque(maxlen=100) # rolling buffer for episode rewards
assert sum([max_iters>0, max_timesteps>0, max_episodes>0, max_seconds>0])==1, "Only one time constraint permitted"
# Prepare for rollouts
# ----------------------------------------
seg_gen = traj_segment_generator(pi, env, timesteps_per_batch, stochastic=True, num_options=num_options,saves=saves,results=results,rewbuffer=rewbuffer,dc=dc)
datas = [0 for _ in range(num_options)]
while True:
if callback: callback(locals(), globals())
if max_timesteps and timesteps_so_far >= max_timesteps:
break
elif max_episodes and episodes_so_far >= max_episodes:
break
elif max_iters and iters_so_far >= max_iters:
break
elif max_seconds and time.time() - tstart >= max_seconds:
break
if schedule == 'constant':
cur_lrmult = 1.0
elif schedule == 'linear':
cur_lrmult = max(1.0 - float(timesteps_so_far) / max_timesteps, 0)
else:
raise NotImplementedError
logger.log("********** Iteration %i ************"%iters_so_far)
# Sample (s,a)-Transitions
seg = seg_gen.__next__()
# Calculate A(s,a,o) using GAE
add_vtarg_and_adv(seg, gamma, lam)
# calculate information for logging
opt_d = []
for i in range(num_options):
dur = np.mean(seg['opt_dur'][i]) if len(seg['opt_dur'][i]) > 0 else 0.
opt_d.append(dur)
std = []
for i in range(num_options):
logstd = np.mean(seg['logstds'][i]) if len(seg['logstds'][i]) > 0 else 0.
std.append(np.exp(logstd))
print("mean opt dur:", opt_d)
print("mean op pol:", np.mean(np.array(seg['optpol_p']),axis=0))
print("mean term p:", np.mean(np.array(seg['term_p']),axis=0))
print("mean value val:", np.mean(np.array(seg['value_val']),axis=0))
ob, ac, opts, atarg, tdlamret = seg["ob"], seg["ac"], seg["opts"], seg["adv"], seg["tdlamret"]
vpredbefore = seg["vpred"] # predicted value function before udpate
atarg = (atarg - atarg.mean()) / atarg.std() # standardized advantage function estimate
if hasattr(pi, "ob_rms"): pi.ob_rms.update(ob) # update running mean/std for policy
if hasattr(pi, "ob_rms_only"): pi.ob_rms_only.update(ob[:,:-ac_space.shape[0]]) # update running mean/std for policy
assign_old_eq_new() # set old parameter values to new parameter values
# if iterations modulo 1000 -> adapt entropy scheduling coefficient
if (iters_so_far+1)%1000 == 0:
des_pol_op_ent = des_pol_op_ent/10
# every 50 epochs save the best model
if iters_so_far % 50 == 0 and wsaves:
print("weights are saved...")
filename = dirname + '{}_epoch_{}.ckpt'.format(gamename,iters_so_far)
save_path = saver.save(U.get_session(),filename)
# adaptively save best model -> if current reward is highest, save the model
if (np.mean(rewbuffer)>max_val) and wsaves:
max_val = np.mean(rewbuffer)
results_best_model.write('epoch: '+str(iters_so_far) + 'rew: ' + str(np.mean(rewbuffer)) + '\n')
results_best_model.flush()
filename = dirname + 'best.ckpt'.format(gamename,iters_so_far)
save_path = saver_best.save(U.get_session(),filename)
# minimum batch size:
min_batch=160
t_advs = [[] for _ in range(num_options)]
# select all the samples concering one of the options
# Note: so far the update is that we first use all samples from option 0 to update, then we use all samples from option 1 to update
for opt in range(num_options):
indices = np.where(opts==opt)[0]
print("batch size:",indices.size)
opt_d[opt] = indices.size
if not indices.size:
t_advs[opt].append(0.)
continue
### This part is only necessasry when we use options. We proceed to these verifications in order not to discard any collected trajectories.
if datas[opt] != 0:
if (indices.size < min_batch and datas[opt].n > min_batch):
datas[opt] = Dataset(dict(ob=ob[indices], ac=ac[indices], atarg=atarg[indices], vtarg=tdlamret[indices]), shuffle=not pi.recurrent)
t_advs[opt].append(0.)
continue
elif indices.size + datas[opt].n < min_batch:
# pdb.set_trace()
oldmap = datas[opt].data_map
cat_ob = np.concatenate((oldmap['ob'],ob[indices]))
cat_ac = np.concatenate((oldmap['ac'],ac[indices]))
cat_atarg = np.concatenate((oldmap['atarg'],atarg[indices]))
cat_vtarg = np.concatenate((oldmap['vtarg'],tdlamret[indices]))
datas[opt] = Dataset(dict(ob=cat_ob, ac=cat_ac, atarg=cat_atarg, vtarg=cat_vtarg), shuffle=not pi.recurrent)
t_advs[opt].append(0.)
continue
elif (indices.size + datas[opt].n > min_batch and datas[opt].n < min_batch) or (indices.size > min_batch and datas[opt].n < min_batch):
oldmap = datas[opt].data_map
cat_ob = np.concatenate((oldmap['ob'],ob[indices]))
cat_ac = np.concatenate((oldmap['ac'],ac[indices]))
cat_atarg = np.concatenate((oldmap['atarg'],atarg[indices]))
cat_vtarg = np.concatenate((oldmap['vtarg'],tdlamret[indices]))
datas[opt] = d = Dataset(dict(ob=cat_ob, ac=cat_ac, atarg=cat_atarg, vtarg=cat_vtarg), shuffle=not pi.recurrent)
if (indices.size > min_batch and datas[opt].n > min_batch):
datas[opt] = d = Dataset(dict(ob=ob[indices], ac=ac[indices], atarg=atarg[indices], vtarg=tdlamret[indices]), shuffle=not pi.recurrent)
elif datas[opt] == 0:
datas[opt] = d = Dataset(dict(ob=ob[indices], ac=ac[indices], atarg=atarg[indices], vtarg=tdlamret[indices]), shuffle=not pi.recurrent)
###
# define the batchsize of the optimizer:
optim_batchsize = optim_batchsize or ob.shape[0]
print("optim epochs:", optim_epochs)
logger.log("Optimizing...")
# Here we do a bunch of optimization epochs over the data
for _ in range(optim_epochs):
losses = [] # list of tuples, each of which gives the loss for a minibatch
for batch in d.iterate_once(optim_batchsize):
# Calculate advantage for using specific option here
tadv,nodc_adv = pi.get_opt_adv(batch["ob"],[opt])
tadv = tadv if num_options > 1 else np.zeros_like(tadv)
t_advs[opt].append(nodc_adv)
# calculate the gradient
*newlosses, grads = lossandgrad(batch["ob"], batch["ac"], batch["atarg"], batch["vtarg"], cur_lrmult, [opt], tadv,des_pol_op_ent)
# perform gradient update
adam.update(grads, optim_stepsize * cur_lrmult)
losses.append(newlosses)
# do logging:
lrlocal = (seg["ep_lens"], seg["ep_rets"]) # local values
listoflrpairs = MPI.COMM_WORLD.allgather(lrlocal) # list of tuples
lens, rews = map(flatten_lists, zip(*listoflrpairs))
lenbuffer.extend(lens)
rewbuffer.extend(rews)
logger.record_tabular("EpLenMean", np.mean(lenbuffer))
logger.record_tabular("EpRewMean", np.mean(rewbuffer))
logger.record_tabular("EpThisIter", len(lens))
episodes_so_far += len(lens)
timesteps_so_far += sum(lens)
iters_so_far += 1
logger.record_tabular("EpisodesSoFar", episodes_so_far)
logger.record_tabular("TimestepsSoFar", timesteps_so_far)
logger.record_tabular("TimeElapsed", time.time() - tstart)
if MPI.COMM_WORLD.Get_rank()==0:
logger.dump_tabular()
### Book keeping
if saves:
out = "{},{}"
for _ in range(num_options): out+=",{},{},{},{}"
out+="\n"
info = [iters_so_far, np.mean(rewbuffer)]
for i in range(num_options): info.append(opt_d[i])
for i in range(num_options): info.append(std[i])
for i in range(num_options): info.append(np.mean(np.array(seg['term_p']),axis=0)[i])
for i in range(num_options):
info.append(np.mean(t_advs[i]))
results.write(out.format(*info))
results.flush()
###
def flatten_lists(listoflists):
return [el for list_ in listoflists for el in list_]
| [
"baselines.common.tf_util.get_session",
"baselines.common.mpi_adam.MpiAdam",
"tensorflow.transpose",
"tensorflow.reduce_sum",
"mpi4py.MPI.COMM_WORLD.allgather",
"numpy.array",
"baselines.logger.log",
"tensorflow.set_random_seed",
"baselines.common.tf_util.get_placeholder_cached",
"baselines.common... | [((895, 907), 'numpy.shape', 'np.shape', (['ob'], {}), '(ob)\n', (903, 907), True, 'import tensorflow as tf, numpy as np\n'), ((927, 939), 'numpy.shape', 'np.shape', (['ac'], {}), '(ac)\n', (935, 939), True, 'import tensorflow as tf, numpy as np\n'), ((987, 1011), 'numpy.concatenate', 'np.concatenate', (['(ob, ac)'], {}), '((ob, ac))\n', (1001, 1011), True, 'import tensorflow as tf, numpy as np\n'), ((1295, 1323), 'numpy.zeros', 'np.zeros', (['horizon', '"""float32"""'], {}), "(horizon, 'float32')\n", (1303, 1323), True, 'import tensorflow as tf, numpy as np\n'), ((1339, 1367), 'numpy.zeros', 'np.zeros', (['horizon', '"""float32"""'], {}), "(horizon, 'float32')\n", (1347, 1367), True, 'import tensorflow as tf, numpy as np\n'), ((1381, 1409), 'numpy.zeros', 'np.zeros', (['horizon', '"""float32"""'], {}), "(horizon, 'float32')\n", (1389, 1409), True, 'import tensorflow as tf, numpy as np\n'), ((1421, 1447), 'numpy.zeros', 'np.zeros', (['horizon', '"""int32"""'], {}), "(horizon, 'int32')\n", (1429, 1447), True, 'import tensorflow as tf, numpy as np\n'), ((1459, 1485), 'numpy.zeros', 'np.zeros', (['horizon', '"""int32"""'], {}), "(horizon, 'int32')\n", (1467, 1485), True, 'import tensorflow as tf, numpy as np\n'), ((5192, 5216), 'numpy.append', 'np.append', (["seg['new']", '(0)'], {}), "(seg['new'], 0)\n", (5201, 5216), True, 'import tensorflow as tf, numpy as np\n'), ((5314, 5355), 'numpy.append', 'np.append', (["seg['vpred']", "seg['nextvpred']"], {}), "(seg['vpred'], seg['nextvpred'])\n", (5323, 5355), True, 'import tensorflow as tf, numpy as np\n'), ((5406, 5428), 'numpy.empty', 'np.empty', (['T', '"""float32"""'], {}), "(T, 'float32')\n", (5414, 5428), True, 'import tensorflow as tf, numpy as np\n'), ((6507, 6527), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (6521, 6527), True, 'import tensorflow as tf, numpy as np\n'), ((6532, 6556), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (6550, 6556), True, 'import tensorflow as tf, numpy as np\n'), ((7084, 7109), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (7099, 7109), False, 'import os\n'), ((8949, 8995), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None]'}), '(dtype=tf.float32, shape=[None])\n', (8963, 8995), True, 'import tensorflow as tf, numpy as np\n'), ((9035, 9081), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None]'}), '(dtype=tf.float32, shape=[None])\n', (9049, 9081), True, 'import tensorflow as tf, numpy as np\n'), ((9121, 9165), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': 'None'}), '(dtype=tf.float32, shape=None)\n', (9135, 9165), True, 'import tensorflow as tf, numpy as np\n'), ((9227, 9284), 'tensorflow.placeholder', 'tf.placeholder', ([], {'name': '"""lrmult"""', 'dtype': 'tf.float32', 'shape': '[]'}), "(name='lrmult', dtype=tf.float32, shape=[])\n", (9241, 9284), True, 'import tensorflow as tf, numpy as np\n'), ((9483, 9518), 'baselines.common.tf_util.get_placeholder_cached', 'U.get_placeholder_cached', ([], {'name': '"""ob"""'}), "(name='ob')\n", (9507, 9518), True, 'import baselines.common.tf_util as U\n'), ((9532, 9571), 'baselines.common.tf_util.get_placeholder_cached', 'U.get_placeholder_cached', ([], {'name': '"""option"""'}), "(name='option')\n", (9556, 9571), True, 'import baselines.common.tf_util as U\n'), ((9587, 9653), 'baselines.common.tf_util.get_placeholder', 'U.get_placeholder', ([], {'name': '"""term_adv"""', 'dtype': 'tf.float32', 'shape': '[None]'}), "(name='term_adv', dtype=tf.float32, shape=[None])\n", (9604, 9653), True, 'import baselines.common.tf_util as U\n'), ((9808, 9824), 'baselines.common.tf_util.mean', 'U.mean', (['kloldnew'], {}), '(kloldnew)\n', (9814, 9824), True, 'import baselines.common.tf_util as U\n'), ((9839, 9850), 'baselines.common.tf_util.mean', 'U.mean', (['ent'], {}), '(ent)\n', (9845, 9850), True, 'import baselines.common.tf_util as U\n'), ((12038, 12077), 'baselines.common.mpi_adam.MpiAdam', 'MpiAdam', (['var_list'], {'epsilon': 'adam_epsilon'}), '(var_list, epsilon=adam_epsilon)\n', (12045, 12077), False, 'from baselines.common.mpi_adam import MpiAdam\n'), ((12334, 12390), 'baselines.common.tf_util.function', 'U.function', (['[ob, ac, atarg, ret, lrmult, option]', 'losses'], {}), '([ob, ac, atarg, ret, lrmult, option], losses)\n', (12344, 12390), True, 'import baselines.common.tf_util as U\n'), ((12397, 12411), 'baselines.common.tf_util.initialize', 'U.initialize', ([], {}), '()\n', (12409, 12411), True, 'import baselines.common.tf_util as U\n'), ((12591, 12624), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': '(10000)'}), '(max_to_keep=10000)\n', (12605, 12624), True, 'import tensorflow as tf, numpy as np\n'), ((12642, 12671), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': '(1)'}), '(max_to_keep=1)\n', (12656, 12671), True, 'import tensorflow as tf, numpy as np\n'), ((14199, 14210), 'time.time', 'time.time', ([], {}), '()\n', (14208, 14210), False, 'import time\n'), ((14227, 14244), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (14232, 14244), False, 'from collections import deque\n'), ((14298, 14315), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (14303, 14315), False, 'from collections import deque\n'), ((8141, 8198), 'os.path.join', 'os.path.join', (['dirname_rel', '"""nfunk/envs_nf/pendulum_nf.py"""'], {}), "(dirname_rel, 'nfunk/envs_nf/pendulum_nf.py')\n", (8153, 8198), False, 'import os\n'), ((8206, 8229), 'shutil.copy2', 'shutil.copy2', (['src', 'dest'], {}), '(src, dest)\n', (8218, 8229), False, 'import shutil\n'), ((8237, 8260), 'shutil.copy2', 'shutil.copy2', (['src', 'dest'], {}), '(src, dest)\n', (8249, 8260), False, 'import shutil\n'), ((8268, 8297), 'os.makedirs', 'os.makedirs', (["(dest + 'assets/')"], {}), "(dest + 'assets/')\n", (8279, 8297), False, 'import os\n'), ((8310, 8373), 'os.path.join', 'os.path.join', (['dirname_rel', '"""nfunk/envs_nf/assets/clockwise.png"""'], {}), "(dirname_rel, 'nfunk/envs_nf/assets/clockwise.png')\n", (8322, 8373), False, 'import os\n'), ((8381, 8416), 'shutil.copy2', 'shutil.copy2', (['src', "(dest + 'assets/')"], {}), "(src, dest + 'assets/')\n", (8393, 8416), False, 'import shutil\n'), ((10218, 10267), 'baselines.common.tf_util.clip', 'U.clip', (['ratio', '(1.0 - clip_param)', '(1.0 + clip_param)'], {}), '(ratio, 1.0 - clip_param, 1.0 + clip_param)\n', (10224, 10267), True, 'import baselines.common.tf_util as U\n'), ((10427, 10452), 'tensorflow.square', 'tf.square', (['(pi.vpred - ret)'], {}), '(pi.vpred - ret)\n', (10436, 10452), True, 'import tensorflow as tf, numpy as np\n'), ((10736, 10774), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['pi.op_pi', '(1e-05)', '(1.0)'], {}), '(pi.op_pi, 1e-05, 1.0)\n', (10752, 10774), True, 'import tensorflow as tf, numpy as np\n'), ((10877, 10918), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['oldpi.op_pi', '(1e-05)', '(1.0)'], {}), '(oldpi.op_pi, 1e-05, 1.0)\n', (10893, 10918), True, 'import tensorflow as tf, numpy as np\n'), ((10981, 11034), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(pi.op_pi * log_pi)'], {'reduction_indices': '(1)'}), '(pi.op_pi * log_pi, reduction_indices=1)\n', (10994, 11034), True, 'import tensorflow as tf, numpy as np\n'), ((11363, 11422), 'baselines.common.tf_util.clip', 'U.clip', (['ratio_pol_ov_op', '(1.0 - clip_param)', '(1.0 + clip_param)'], {}), '(ratio_pol_ov_op, 1.0 - clip_param, 1.0 + clip_param)\n', (11369, 11422), True, 'import baselines.common.tf_util as U\n'), ((15384, 15449), 'baselines.logger.log', 'logger.log', (["('********** Iteration %i ************' % iters_so_far)"], {}), "('********** Iteration %i ************' % iters_so_far)\n", (15394, 15449), False, 'from baselines import logger\n'), ((21787, 21820), 'mpi4py.MPI.COMM_WORLD.allgather', 'MPI.COMM_WORLD.allgather', (['lrlocal'], {}), '(lrlocal)\n', (21811, 21820), False, 'from mpi4py import MPI\n'), ((22251, 22306), 'baselines.logger.record_tabular', 'logger.record_tabular', (['"""EpisodesSoFar"""', 'episodes_so_far'], {}), "('EpisodesSoFar', episodes_so_far)\n", (22272, 22306), False, 'from baselines import logger\n'), ((22315, 22372), 'baselines.logger.record_tabular', 'logger.record_tabular', (['"""TimestepsSoFar"""', 'timesteps_so_far'], {}), "('TimestepsSoFar', timesteps_so_far)\n", (22336, 22372), False, 'from baselines import logger\n'), ((7380, 7403), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (7394, 7403), False, 'import os\n'), ((7417, 7437), 'os.makedirs', 'os.makedirs', (['dirname'], {}), '(dirname)\n', (7428, 7437), False, 'import os\n'), ((8034, 8057), 'shutil.copy2', 'shutil.copy2', (['src', 'dest'], {}), '(src, dest)\n', (8046, 8057), False, 'import shutil\n'), ((10349, 10373), 'tensorflow.minimum', 'tf.minimum', (['surr1', 'surr2'], {}), '(surr1, surr2)\n', (10359, 10373), True, 'import tensorflow as tf, numpy as np\n'), ((11475, 11519), 'tensorflow.minimum', 'tf.minimum', (['surr1_pol_ov_op', 'surr2_pol_ov_op'], {}), '(surr1_pol_ov_op, surr2_pol_ov_op)\n', (11485, 11519), True, 'import tensorflow as tf, numpy as np\n'), ((11614, 11636), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['entropy'], {}), '(entropy)\n', (11627, 11636), True, 'import tensorflow as tf, numpy as np\n'), ((13857, 13872), 'baselines.common.tf_util.get_session', 'U.get_session', ([], {}), '()\n', (13870, 13872), True, 'import baselines.common.tf_util as U\n'), ((17457, 17475), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (17464, 17475), True, 'import tensorflow as tf, numpy as np\n'), ((20752, 20779), 'baselines.logger.log', 'logger.log', (['"""Optimizing..."""'], {}), "('Optimizing...')\n", (20762, 20779), False, 'from baselines import logger\n'), ((22004, 22022), 'numpy.mean', 'np.mean', (['lenbuffer'], {}), '(lenbuffer)\n', (22011, 22022), True, 'import tensorflow as tf, numpy as np\n'), ((22067, 22085), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (22074, 22085), True, 'import tensorflow as tf, numpy as np\n'), ((22451, 22476), 'mpi4py.MPI.COMM_WORLD.Get_rank', 'MPI.COMM_WORLD.Get_rank', ([], {}), '()\n', (22474, 22476), False, 'from mpi4py import MPI\n'), ((22493, 22514), 'baselines.logger.dump_tabular', 'logger.dump_tabular', ([], {}), '()\n', (22512, 22514), False, 'from baselines import logger\n'), ((3522, 3533), 'numpy.copy', 'np.copy', (['ac'], {}), '(ac)\n', (3529, 3533), True, 'import tensorflow as tf, numpy as np\n'), ((7703, 7757), 'os.path.join', 'os.path.join', (['dirname_rel', '"""baselines/baselines/ppo1/"""'], {}), "(dirname_rel, 'baselines/baselines/ppo1/')\n", (7715, 7757), False, 'import os\n'), ((7949, 7966), 'os.makedirs', 'os.makedirs', (['dest'], {}), '(dest)\n', (7960, 7966), False, 'import os\n'), ((11125, 11145), 'tensorflow.transpose', 'tf.transpose', (['log_pi'], {}), '(log_pi)\n', (11137, 11145), True, 'import tensorflow as tf, numpy as np\n'), ((11159, 11183), 'tensorflow.transpose', 'tf.transpose', (['old_log_pi'], {}), '(old_log_pi)\n', (11171, 11183), True, 'import tensorflow as tf, numpy as np\n'), ((11959, 11991), 'baselines.common.tf_util.flatgrad', 'U.flatgrad', (['total_loss', 'var_list'], {}), '(total_loss, var_list)\n', (11969, 11991), True, 'import baselines.common.tf_util as U\n'), ((12210, 12231), 'tensorflow.assign', 'tf.assign', (['oldv', 'newv'], {}), '(oldv, newv)\n', (12219, 12231), True, 'import tensorflow as tf, numpy as np\n'), ((15719, 15745), 'numpy.mean', 'np.mean', (["seg['opt_dur'][i]"], {}), "(seg['opt_dur'][i])\n", (15726, 15745), True, 'import tensorflow as tf, numpy as np\n'), ((15890, 15916), 'numpy.mean', 'np.mean', (["seg['logstds'][i]"], {}), "(seg['logstds'][i])\n", (15897, 15916), True, 'import tensorflow as tf, numpy as np\n'), ((15978, 15992), 'numpy.exp', 'np.exp', (['logstd'], {}), '(logstd)\n', (15984, 15992), True, 'import tensorflow as tf, numpy as np\n'), ((16083, 16108), 'numpy.array', 'np.array', (["seg['optpol_p']"], {}), "(seg['optpol_p'])\n", (16091, 16108), True, 'import tensorflow as tf, numpy as np\n'), ((16165, 16188), 'numpy.array', 'np.array', (["seg['term_p']"], {}), "(seg['term_p'])\n", (16173, 16188), True, 'import tensorflow as tf, numpy as np\n'), ((16239, 16265), 'numpy.array', 'np.array', (["seg['value_val']"], {}), "(seg['value_val'])\n", (16247, 16265), True, 'import tensorflow as tf, numpy as np\n'), ((17271, 17286), 'baselines.common.tf_util.get_session', 'U.get_session', ([], {}), '()\n', (17284, 17286), True, 'import baselines.common.tf_util as U\n'), ((17395, 17413), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (17402, 17413), True, 'import tensorflow as tf, numpy as np\n'), ((17739, 17754), 'baselines.common.tf_util.get_session', 'U.get_session', ([], {}), '()\n', (17752, 17754), True, 'import baselines.common.tf_util as U\n'), ((18143, 18164), 'numpy.where', 'np.where', (['(opts == opt)'], {}), '(opts == opt)\n', (18151, 18164), True, 'import tensorflow as tf, numpy as np\n'), ((22418, 22429), 'time.time', 'time.time', ([], {}), '()\n', (22427, 22429), False, 'import time\n'), ((22716, 22734), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (22723, 22734), True, 'import tensorflow as tf, numpy as np\n'), ((23027, 23045), 'numpy.mean', 'np.mean', (['t_advs[i]'], {}), '(t_advs[i])\n', (23034, 23045), True, 'import tensorflow as tf, numpy as np\n'), ((19013, 19056), 'numpy.concatenate', 'np.concatenate', (["(oldmap['ob'], ob[indices])"], {}), "((oldmap['ob'], ob[indices]))\n", (19027, 19056), True, 'import tensorflow as tf, numpy as np\n'), ((19085, 19128), 'numpy.concatenate', 'np.concatenate', (["(oldmap['ac'], ac[indices])"], {}), "((oldmap['ac'], ac[indices]))\n", (19099, 19128), True, 'import tensorflow as tf, numpy as np\n'), ((19160, 19209), 'numpy.concatenate', 'np.concatenate', (["(oldmap['atarg'], atarg[indices])"], {}), "((oldmap['atarg'], atarg[indices]))\n", (19174, 19209), True, 'import tensorflow as tf, numpy as np\n'), ((19241, 19293), 'numpy.concatenate', 'np.concatenate', (["(oldmap['vtarg'], tdlamret[indices])"], {}), "((oldmap['vtarg'], tdlamret[indices]))\n", (19255, 19293), True, 'import tensorflow as tf, numpy as np\n'), ((21247, 21266), 'numpy.zeros_like', 'np.zeros_like', (['tadv'], {}), '(tadv)\n', (21260, 21266), True, 'import tensorflow as tf, numpy as np\n'), ((17557, 17575), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (17564, 17575), True, 'import tensorflow as tf, numpy as np\n'), ((19726, 19769), 'numpy.concatenate', 'np.concatenate', (["(oldmap['ob'], ob[indices])"], {}), "((oldmap['ob'], ob[indices]))\n", (19740, 19769), True, 'import tensorflow as tf, numpy as np\n'), ((19798, 19841), 'numpy.concatenate', 'np.concatenate', (["(oldmap['ac'], ac[indices])"], {}), "((oldmap['ac'], ac[indices]))\n", (19812, 19841), True, 'import tensorflow as tf, numpy as np\n'), ((19873, 19922), 'numpy.concatenate', 'np.concatenate', (["(oldmap['atarg'], atarg[indices])"], {}), "((oldmap['atarg'], atarg[indices]))\n", (19887, 19922), True, 'import tensorflow as tf, numpy as np\n'), ((19954, 20006), 'numpy.concatenate', 'np.concatenate', (["(oldmap['vtarg'], tdlamret[indices])"], {}), "((oldmap['vtarg'], tdlamret[indices]))\n", (19968, 20006), True, 'import tensorflow as tf, numpy as np\n'), ((22921, 22944), 'numpy.array', 'np.array', (["seg['term_p']"], {}), "(seg['term_p'])\n", (22929, 22944), True, 'import tensorflow as tf, numpy as np\n'), ((15088, 15099), 'time.time', 'time.time', ([], {}), '()\n', (15097, 15099), False, 'import time\n')] |
"""
Copyright 2021 MPI-SWS
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 queryfuzz.datalog.base_fact import BaseFact
from queryfuzz.engines.z3.z3_subgoal import Z3Subgoal
from queryfuzz.datalog.variable import Variable
import string
from copy import deepcopy
class Z3Fact(BaseFact):
def generate_fact(self):
allowed_variable_types = self.params["z3_types"]
self.name = self.randomness.get_lower_case_alpha_string(4)
self.variables_types = [self.randomness.random_choice(allowed_variable_types) for i in range(self.arity)]
# Generate rows
for i in range(self.number_of_rows):
table_entry = self.name + "("
raw_data_row = ""
for j in range(self.arity):
data_type = self.variables_types[j]
data_item = self.generate_data_item(data_type)
table_entry += str(data_item) + ", "
raw_data_row += str(data_item) + "\t"
table_entry = table_entry[:-2] + ")."
self.raw_data_entries.append(raw_data_row)
self.fact_data.append(table_entry)
def get_fact_as_a_relation(self):
fact_subgoal = Z3Subgoal(randomness=self.randomness, arity=self.arity, params=self.params)
fact_subgoal.generate_subgoal(name=self.name,
variables=[Variable(name=string.ascii_uppercase[i], vtype=self.variables_types[i]) for i in range(self.arity)],
variables_types=self.variables_types)
return fact_subgoal
def generate_decleration(self):
self.declaration = self.name + "("
for i in range(self.arity):
self.declaration += string.ascii_uppercase[i] + ":" + self.variables_types[i] + ", "
self.declaration = self.declaration[:-2] + ") input"
def generate_data_item(self, type):
if type == "Z":
return self.randomness.get_random_integer(0,50)
| [
"queryfuzz.engines.z3.z3_subgoal.Z3Subgoal",
"queryfuzz.datalog.variable.Variable"
] | [((1655, 1730), 'queryfuzz.engines.z3.z3_subgoal.Z3Subgoal', 'Z3Subgoal', ([], {'randomness': 'self.randomness', 'arity': 'self.arity', 'params': 'self.params'}), '(randomness=self.randomness, arity=self.arity, params=self.params)\n', (1664, 1730), False, 'from queryfuzz.engines.z3.z3_subgoal import Z3Subgoal\n'), ((1837, 1908), 'queryfuzz.datalog.variable.Variable', 'Variable', ([], {'name': 'string.ascii_uppercase[i]', 'vtype': 'self.variables_types[i]'}), '(name=string.ascii_uppercase[i], vtype=self.variables_types[i])\n', (1845, 1908), False, 'from queryfuzz.datalog.variable import Variable\n')] |
#!/usr/bin/python3.6
from datetime import timedelta, datetime
import logging
import os
import requests
import sys
import time
import json
log_file = 'audit.log'
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
#
# This will archive inactive channels. The inactive period is in days as 'self.days_inactive'
# You can put this in a cron job to run daily to do slack cleanup.
#
class ChannelReaper(object):
def __init__(self):
self.admin_channel = os.getenv('ADMIN_CHANNEL')
self.days_inactive = int(os.getenv('DAYS_INACTIVE', 60))
# set MIN_MEMBERS and any channels larger than this in people
# are exempt from archiving. 0 is no limit.
self.min_members = int(os.getenv('MIN_MEMBERS', 0))
self.dry_run = (os.getenv('DRY_RUN', 'true') == 'true')
self.slack_token = os.getenv('SLACK_TOKEN')
self.too_old_datetime = datetime.now() - timedelta(days=self.days_inactive)
self.whitelist_keywords = os.getenv('WHITELIST_KEYWORDS')
self.skip_subtypes = {'channel_leave', 'channel_join'} # 'bot_message'
# note, if the channel purpose has this string in it, we'll skip archiving this channel.
self.skip_channel_str = os.getenv('SLACK_SKIP_PURPOSE', '%noarchive')
def get_whitelist_keywords(self):
keywords = []
if os.path.isfile('whitelist.txt'):
with open('whitelist.txt') as f:
keywords = f.readlines()
# remove whitespace characters like `\n` at the end of each line
keywords = map(lambda x: x.strip(), keywords)
if self.whitelist_keywords:
keywords = keywords + self.whitelist_keywords.split(',')
return list(keywords)
def get_channel_alerts(self):
alerts = {
'channel_template': 'This channel has had no activity for %s days. It is being auto-archived. If you feel this is a mistake you can <https://get.slack.help/hc/en-us/articles/201563847-Archive-a-channel#unarchive-a-channel|unarchive this channel> to bring it back at any point. In the future, you can add "%noarchive" to your channel topic or purpose to avoid being archived. This script was run from this repo: https://github.com/Symantec/slack-autoarchive'
}
if os.path.isfile('templates.json'):
with open('templates.json') as f:
alerts = json.load(f)
return alerts
# api_endpoint is a string, and payload is a dict
def slack_api_http(self, api_endpoint=None, payload=None, method='GET', retry=True, retry_delay=0):
uri = 'https://slack.com/api/' + api_endpoint
payload['token'] = self.slack_token
try:
# Force request to take at least 1 second. Slack docs state:
# > In general we allow applications that integrate with Slack to send
# > no more than one message per second. We allow bursts over that
# > limit for short periods.
if retry_delay > 0:
time.sleep(retry_delay)
if method == 'POST':
response = requests.post(uri, data=payload)
else:
response = requests.get(uri, params=payload)
if response.status_code == requests.codes.ok and 'error' in response.json() and response.json()['error'] == 'not_authed':
print('Need to setup auth. eg, SLACK_TOKEN=<secret token> python slack-autoarchive.py')
sys.exit(1)
elif response.status_code == requests.codes.ok and response.json()['ok']:
return response.json()
elif response.status_code == requests.codes.too_many_requests:
retry_timeout = float(response.headers['Retry-After'])
return self.slack_api_http(api_endpoint, payload, method, False, retry_timeout)
else:
raise
except Exception as error_msg:
raise Exception(error_msg)
# too_old_datetime is a datetime object
def get_all_channels(self):
payload = {'exclude_archived': 1}
api_endpoint = 'channels.list'
channels = self.slack_api_http(api_endpoint=api_endpoint, payload=payload)['channels']
all_channels = []
for channel in channels:
all_channels.append({'id': channel['id'], 'name': channel['name'], 'created': channel['created'], 'num_members': channel['num_members']})
return all_channels
def get_last_message_timestamp(self, channel_history, too_old_datetime):
last_message_datetime = too_old_datetime
last_bot_message_datetime = too_old_datetime
if 'messages' not in channel_history:
return (last_message_datetime, False) # no messages
for message in channel_history['messages']:
if 'subtype' in message and message['subtype'] in self.skip_subtypes:
continue
last_message_datetime = datetime.fromtimestamp(float(message['ts']))
break
# for folks with the free plan, sometimes there is no last message,
# then just set last_message_datetime to epoch
if not last_message_datetime:
last_bot_message_datetime = datetime.utcfromtimestamp(0)
# return bot message time if there was no user message
if last_bot_message_datetime > too_old_datetime and last_message_datetime <= too_old_datetime:
return (last_bot_message_datetime, False)
else:
return (last_message_datetime, True)
def is_channel_disused(self, channel, too_old_datetime):
num_members = channel['num_members']
payload = {'inclusive': 0, 'oldest': 0, 'count': 50}
api_endpoint = 'channels.history'
payload['channel'] = channel['id']
channel_history = self.slack_api_http(api_endpoint=api_endpoint, payload=payload)
(last_message_datetime, is_user) = self.get_last_message_timestamp(channel_history, datetime.fromtimestamp(float(channel['created'])))
# mark inactive if last message is too old, but don't
# if there have been bot messages and the channel has
# at least the minimum number of members
has_min_users = (self.min_members == 0 or self.min_members > num_members)
return last_message_datetime <= too_old_datetime and (not is_user or has_min_users)
# If you add channels to the WHITELIST_KEYWORDS constant they will be exempt from archiving.
def is_channel_whitelisted(self, channel, white_listed_channels):
# self.skip_channel_str
# if the channel purpose contains the string self.skip_channel_str, we'll skip it.
info_payload = {'channel': channel['id']}
channel_info = self.slack_api_http(api_endpoint='channels.info', payload=info_payload, method='GET')
channel_purpose = channel_info['channel']['purpose']['value']
channel_topic = channel_info['channel']['topic']['value']
if self.skip_channel_str in channel_purpose or self.skip_channel_str in channel_topic:
return True
# check the white listed channels (file / env)
for white_listed_channel in white_listed_channels:
wl_channel_name = white_listed_channel.strip('#')
if wl_channel_name in channel['name']:
return True
return False
def send_channel_message(self, channel_id, message):
payload = {'channel': channel_id, 'username': 'channel_reaper', 'icon_emoji': ':ghost:', 'text': message}
api_endpoint = 'chat.postMessage'
self.slack_api_http(api_endpoint=api_endpoint, payload=payload, method='POST')
def archive_channel(self, channel, alert):
api_endpoint = 'channels.archive'
stdout_message = 'Archiving channel... %s' % channel['name']
print(stdout_message)
if not self.dry_run:
# channel_message = alert % self.days_inactive
# self.send_channel_message(channel['id'], channel_message)
payload = {'channel': channel['id']}
self.slack_api_http(api_endpoint=api_endpoint, payload=payload)
logging.info(stdout_message)
def send_admin_report(self, channels):
if self.admin_channel:
channel_names = ', '.join('#' + channel['name'] for channel in channels)
admin_msg = 'Archiving %d channels: %s' % (len(channels), channel_names)
if self.dry_run:
admin_msg = '[DRY RUN] %s' % admin_msg
self.send_channel_message(self.admin_channel, admin_msg)
def main(self):
if self.dry_run:
print('THIS IS A DRY RUN. NO CHANNELS ARE ACTUALLY ARCHIVED.')
whitelist_keywords = self.get_whitelist_keywords()
alert_templates = self.get_channel_alerts()
archived_channels = []
for channel in self.get_all_channels():
sys.stdout.write('.')
sys.stdout.flush()
if (not self.is_channel_whitelisted(channel, whitelist_keywords) and self.is_channel_disused(channel, self.too_old_datetime)):
archived_channels.append(channel)
self.archive_channel(channel, alert_templates['channel_template'])
self.send_admin_report(archived_channels)
if __name__ == '__main__':
channel_reaper = ChannelReaper()
channel_reaper.main()
| [
"logging.basicConfig",
"datetime.datetime.utcfromtimestamp",
"sys.stdout.flush",
"requests.post",
"os.getenv",
"time.sleep",
"requests.get",
"os.path.isfile",
"datetime.datetime.now",
"sys.exit",
"json.load",
"datetime.timedelta",
"logging.info",
"sys.stdout.write"
] | [((163, 278), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': 'log_file', 'level': 'logging.INFO', 'format': '"""%(asctime)s - %(levelname)s - %(message)s"""'}), "(filename=log_file, level=logging.INFO, format=\n '%(asctime)s - %(levelname)s - %(message)s')\n", (182, 278), False, 'import logging\n'), ((523, 549), 'os.getenv', 'os.getenv', (['"""ADMIN_CHANNEL"""'], {}), "('ADMIN_CHANNEL')\n", (532, 549), False, 'import os\n'), ((894, 918), 'os.getenv', 'os.getenv', (['"""SLACK_TOKEN"""'], {}), "('SLACK_TOKEN')\n", (903, 918), False, 'import os\n'), ((1031, 1062), 'os.getenv', 'os.getenv', (['"""WHITELIST_KEYWORDS"""'], {}), "('WHITELIST_KEYWORDS')\n", (1040, 1062), False, 'import os\n'), ((1267, 1312), 'os.getenv', 'os.getenv', (['"""SLACK_SKIP_PURPOSE"""', '"""%noarchive"""'], {}), "('SLACK_SKIP_PURPOSE', '%noarchive')\n", (1276, 1312), False, 'import os\n'), ((1375, 1406), 'os.path.isfile', 'os.path.isfile', (['"""whitelist.txt"""'], {}), "('whitelist.txt')\n", (1389, 1406), False, 'import os\n'), ((2246, 2278), 'os.path.isfile', 'os.path.isfile', (['"""templates.json"""'], {}), "('templates.json')\n", (2260, 2278), False, 'import os\n'), ((584, 614), 'os.getenv', 'os.getenv', (['"""DAYS_INACTIVE"""', '(60)'], {}), "('DAYS_INACTIVE', 60)\n", (593, 614), False, 'import os\n'), ((764, 791), 'os.getenv', 'os.getenv', (['"""MIN_MEMBERS"""', '(0)'], {}), "('MIN_MEMBERS', 0)\n", (773, 791), False, 'import os\n'), ((824, 852), 'os.getenv', 'os.getenv', (['"""DRY_RUN"""', '"""true"""'], {}), "('DRY_RUN', 'true')\n", (833, 852), False, 'import os\n'), ((949, 963), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (961, 963), False, 'from datetime import timedelta, datetime\n'), ((966, 1000), 'datetime.timedelta', 'timedelta', ([], {'days': 'self.days_inactive'}), '(days=self.days_inactive)\n', (975, 1000), False, 'from datetime import timedelta, datetime\n'), ((4897, 4925), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['(0)'], {}), '(0)\n', (4922, 4925), False, 'from datetime import timedelta, datetime\n'), ((7622, 7650), 'logging.info', 'logging.info', (['stdout_message'], {}), '(stdout_message)\n', (7634, 7650), False, 'import logging\n'), ((8303, 8324), 'sys.stdout.write', 'sys.stdout.write', (['"""."""'], {}), "('.')\n", (8319, 8324), False, 'import sys\n'), ((8331, 8349), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (8347, 8349), False, 'import sys\n'), ((2337, 2349), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2346, 2349), False, 'import json\n'), ((2909, 2932), 'time.sleep', 'time.sleep', (['retry_delay'], {}), '(retry_delay)\n', (2919, 2932), False, 'import time\n'), ((2980, 3012), 'requests.post', 'requests.post', (['uri'], {'data': 'payload'}), '(uri, data=payload)\n', (2993, 3012), False, 'import requests\n'), ((3044, 3077), 'requests.get', 'requests.get', (['uri'], {'params': 'payload'}), '(uri, params=payload)\n', (3056, 3077), False, 'import requests\n'), ((3311, 3322), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3319, 3322), False, 'import sys\n')] |
import os
from .base import GnuRecipe
from ..util import patch
class EudevRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(EudevRecipe, self).__init__(*args, **kwargs)
self.sha256 = '49c2d04105cad2526302627e040fa24b' \
'1916a9a3e059539bc8bb919b973890af'
self.name = 'eudev'
self.version = '3.2.5'
self.url = 'http://dev.gentoo.org/~blueness/eudev/' \
'eudev-$version.tar.gz'
self.depends = ['gperf']
self.configure_args += ['--enable-manpages']
def _patch(self, filename, text):
with open(filename, 'rt') as f:
file_text = text + f.read()
with open(filename, 'wt') as f:
f.write(file_text)
def patch(self):
self.log_dir('patch', self.directory,
'adding BTN_TRIGGER_HAPPY and INPUT_PROP_MAX')
text = """
#ifndef BTN_TRIGGER_HAPPY
#define BTN_TRIGGER_HAPPY (0x2c0)
#endif
#ifndef INPUT_PROP_MAX
#define INPUT_PROP_MAX (0x1f)
#endif
"""
filename = os.path.join(self.directory,
'src/udev/udev-builtin-input_id.c')
self._patch(filename, text)
self.log_dir('patch', self.directory,
'removing duplicate declaration')
def install(self):
super(EudevRecipe, self).install()
self.install_args = ['udevadm',
'hwdb',
'--update']
super(EudevRecipe, self).install()
# def patch(self):
# cache = os.path.join(self.directory, 'config.cache')
# text = '''
#HAVE_BLKID=1
#BLKID_LIBS="-lblkid"
#BLKID_CFLAGS=""
#'''
# with open(cache, 'wt') as f:
# f.write(text)
| [
"os.path.join"
] | [((1058, 1122), 'os.path.join', 'os.path.join', (['self.directory', '"""src/udev/udev-builtin-input_id.c"""'], {}), "(self.directory, 'src/udev/udev-builtin-input_id.c')\n", (1070, 1122), False, 'import os\n')] |
import os
import sys
# `scandir()` collects info in one system call
# https://pymotw.com/3/os/
# Run from interpreter as follows to check current directory:
# >>> python3 os_scandir.py .
def main():
for entry in os.scandir(sys.argv[1]):
if entry.is_dir():
typ = 'dir'
elif entry.is_file():
typ = 'file'
elif entry.is_symlink():
typ = 'link'
else:
typ = 'unknown'
print('{name}\t{typ}'.format(name=entry.name, typ=typ,))
if __name__ == '__main__':
main() | [
"os.scandir"
] | [((219, 242), 'os.scandir', 'os.scandir', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (229, 242), False, 'import os\n')] |
import time
from unittest.case import SkipTest
from ddtrace.context import Context
from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY
from ddtrace.span import Span
from ddtrace.ext import errors
def test_ids():
s = Span(tracer=None, name='span.test')
assert s.trace_id
assert s.span_id
assert not s.parent_id
s2 = Span(tracer=None, name='t', trace_id=1, span_id=2, parent_id=1)
assert s2.trace_id == 1
assert s2.span_id == 2
assert s2.parent_id == 1
def test_tags():
s = Span(tracer=None, name='test.span')
s.set_tag('a', 'a')
s.set_tag('b', 1)
s.set_tag('c', '1')
d = s.to_dict()
expected = {
'a': 'a',
'b': '1',
'c': '1',
}
assert d['meta'] == expected
def test_set_valid_metrics():
s = Span(tracer=None, name='test.span')
s.set_metric('a', 0)
s.set_metric('b', -12)
s.set_metric('c', 12.134)
s.set_metric('d', 1231543543265475686787869123)
s.set_metric('e', '12.34')
d = s.to_dict()
expected = {
'a': 0,
'b': -12,
'c': 12.134,
'd': 1231543543265475686787869123,
'e': 12.34,
}
assert d['metrics'] == expected
def test_set_invalid_metric():
s = Span(tracer=None, name='test.span')
invalid_metrics = [
None,
{},
[],
s,
'quarante-douze',
float('nan'),
float('inf'),
1j
]
for i, m in enumerate(invalid_metrics):
k = str(i)
s.set_metric(k, m)
assert s.get_metric(k) is None
def test_set_numpy_metric():
try:
import numpy as np
except ImportError:
raise SkipTest('numpy not installed')
s = Span(tracer=None, name='test.span')
s.set_metric('a', np.int64(1))
assert s.get_metric('a') == 1
assert type(s.get_metric('a')) == float
def test_tags_not_string():
# ensure we can cast as strings
class Foo(object):
def __repr__(self):
1 / 0
s = Span(tracer=None, name='test.span')
s.set_tag('a', Foo())
def test_finish():
# ensure finish will record a span
dt = DummyTracer()
ctx = Context()
s = Span(dt, 'test.span', context=ctx)
ctx.add_span(s)
assert s.duration is None
sleep = 0.05
with s as s1:
assert s is s1
time.sleep(sleep)
assert s.duration >= sleep, '%s < %s' % (s.duration, sleep)
assert 1 == dt.spans_recorded
def test_finish_no_tracer():
# ensure finish works with no tracer without raising exceptions
s = Span(tracer=None, name='test.span')
s.finish()
def test_finish_called_multiple_times():
# we should only record a span the first time finish is called on it
dt = DummyTracer()
ctx = Context()
s = Span(dt, 'bar', context=ctx)
ctx.add_span(s)
s.finish()
s.finish()
assert dt.spans_recorded == 1
def test_finish_set_span_duration():
# If set the duration on a span, the span should be recorded with this
# duration
s = Span(tracer=None, name='test.span')
s.duration = 1337.0
s.finish()
assert s.duration == 1337.0
def test_traceback_with_error():
s = Span(None, 'test.span')
try:
1 / 0
except ZeroDivisionError:
s.set_traceback()
else:
assert 0, 'should have failed'
assert s.error
assert 'by zero' in s.get_tag(errors.ERROR_MSG)
assert 'ZeroDivisionError' in s.get_tag(errors.ERROR_TYPE)
def test_traceback_without_error():
s = Span(None, 'test.span')
s.set_traceback()
assert not s.error
assert not s.get_tag(errors.ERROR_MSG)
assert not s.get_tag(errors.ERROR_TYPE)
assert 'in test_traceback_without_error' in s.get_tag(errors.ERROR_STACK)
def test_ctx_mgr():
dt = DummyTracer()
s = Span(dt, 'bar')
assert not s.duration
assert not s.error
e = Exception('boo')
try:
with s:
time.sleep(0.01)
raise e
except Exception as out:
assert out == e
assert s.duration > 0, s.duration
assert s.error
assert s.get_tag(errors.ERROR_MSG) == 'boo'
assert 'Exception' in s.get_tag(errors.ERROR_TYPE)
assert s.get_tag(errors.ERROR_STACK)
else:
assert 0, 'should have failed'
def test_span_to_dict():
s = Span(tracer=None, name='test.span', service='s', resource='r')
s.span_type = 'foo'
s.set_tag('a', '1')
s.set_meta('b', '2')
s.finish()
d = s.to_dict()
assert d
assert d['span_id'] == s.span_id
assert d['trace_id'] == s.trace_id
assert d['parent_id'] == s.parent_id
assert d['meta'] == {'a': '1', 'b': '2'}
assert d['type'] == 'foo'
assert d['error'] == 0
assert type(d['error']) == int
def test_span_to_dict_sub():
parent = Span(tracer=None, name='test.span', service='s', resource='r')
s = Span(tracer=None, name='test.span', service='s', resource='r')
s._parent = parent
s.span_type = 'foo'
s.set_tag('a', '1')
s.set_meta('b', '2')
s.finish()
d = s.to_dict()
assert d
assert d['span_id'] == s.span_id
assert d['trace_id'] == s.trace_id
assert d['parent_id'] == s.parent_id
assert d['meta'] == {'a': '1', 'b': '2'}
assert d['type'] == 'foo'
assert d['error'] == 0
assert type(d['error']) == int
def test_span_boolean_err():
s = Span(tracer=None, name='foo.bar', service='s', resource='r')
s.error = True
s.finish()
d = s.to_dict()
assert d
assert d['error'] == 1
assert type(d['error']) == int
def test_numeric_tags_none():
s = Span(tracer=None, name='test.span')
s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, None)
d = s.to_dict()
assert d
assert 'metrics' not in d
def test_numeric_tags_true():
s = Span(tracer=None, name='test.span')
s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, True)
d = s.to_dict()
assert d
expected = {
ANALYTICS_SAMPLE_RATE_KEY: 1.0
}
assert d['metrics'] == expected
def test_numeric_tags_value():
s = Span(tracer=None, name='test.span')
s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, 0.5)
d = s.to_dict()
assert d
expected = {
ANALYTICS_SAMPLE_RATE_KEY: 0.5
}
assert d['metrics'] == expected
def test_numeric_tags_bad_value():
s = Span(tracer=None, name='test.span')
s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, 'Hello')
d = s.to_dict()
assert d
assert 'metrics' not in d
class DummyTracer(object):
def __init__(self):
self.debug_logging = False
self.last_span = None
self.spans_recorded = 0
def record(self, span):
self.last_span = span
self.spans_recorded += 1
| [
"ddtrace.span.Span",
"numpy.int64",
"unittest.case.SkipTest",
"time.sleep",
"ddtrace.context.Context"
] | [((228, 263), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""span.test"""'}), "(tracer=None, name='span.test')\n", (232, 263), False, 'from ddtrace.span import Span\n'), ((344, 407), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""t"""', 'trace_id': '(1)', 'span_id': '(2)', 'parent_id': '(1)'}), "(tracer=None, name='t', trace_id=1, span_id=2, parent_id=1)\n", (348, 407), False, 'from ddtrace.span import Span\n'), ((519, 554), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (523, 554), False, 'from ddtrace.span import Span\n'), ((795, 830), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (799, 830), False, 'from ddtrace.span import Span\n'), ((1234, 1269), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (1238, 1269), False, 'from ddtrace.span import Span\n'), ((1706, 1741), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (1710, 1741), False, 'from ddtrace.span import Span\n'), ((1999, 2034), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (2003, 2034), False, 'from ddtrace.span import Span\n'), ((2154, 2163), 'ddtrace.context.Context', 'Context', ([], {}), '()\n', (2161, 2163), False, 'from ddtrace.context import Context\n'), ((2172, 2206), 'ddtrace.span.Span', 'Span', (['dt', '"""test.span"""'], {'context': 'ctx'}), "(dt, 'test.span', context=ctx)\n", (2176, 2206), False, 'from ddtrace.span import Span\n'), ((2547, 2582), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (2551, 2582), False, 'from ddtrace.span import Span\n'), ((2747, 2756), 'ddtrace.context.Context', 'Context', ([], {}), '()\n', (2754, 2756), False, 'from ddtrace.context import Context\n'), ((2765, 2793), 'ddtrace.span.Span', 'Span', (['dt', '"""bar"""'], {'context': 'ctx'}), "(dt, 'bar', context=ctx)\n", (2769, 2793), False, 'from ddtrace.span import Span\n'), ((3015, 3050), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (3019, 3050), False, 'from ddtrace.span import Span\n'), ((3165, 3188), 'ddtrace.span.Span', 'Span', (['None', '"""test.span"""'], {}), "(None, 'test.span')\n", (3169, 3188), False, 'from ddtrace.span import Span\n'), ((3498, 3521), 'ddtrace.span.Span', 'Span', (['None', '"""test.span"""'], {}), "(None, 'test.span')\n", (3502, 3521), False, 'from ddtrace.span import Span\n'), ((3785, 3800), 'ddtrace.span.Span', 'Span', (['dt', '"""bar"""'], {}), "(dt, 'bar')\n", (3789, 3800), False, 'from ddtrace.span import Span\n'), ((4309, 4371), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""', 'service': '"""s"""', 'resource': '"""r"""'}), "(tracer=None, name='test.span', service='s', resource='r')\n", (4313, 4371), False, 'from ddtrace.span import Span\n'), ((4792, 4854), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""', 'service': '"""s"""', 'resource': '"""r"""'}), "(tracer=None, name='test.span', service='s', resource='r')\n", (4796, 4854), False, 'from ddtrace.span import Span\n'), ((4863, 4925), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""', 'service': '"""s"""', 'resource': '"""r"""'}), "(tracer=None, name='test.span', service='s', resource='r')\n", (4867, 4925), False, 'from ddtrace.span import Span\n'), ((5364, 5424), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""foo.bar"""', 'service': '"""s"""', 'resource': '"""r"""'}), "(tracer=None, name='foo.bar', service='s', resource='r')\n", (5368, 5424), False, 'from ddtrace.span import Span\n'), ((5595, 5630), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (5599, 5630), False, 'from ddtrace.span import Span\n'), ((5781, 5816), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (5785, 5816), False, 'from ddtrace.span import Span\n'), ((6036, 6071), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (6040, 6071), False, 'from ddtrace.span import Span\n'), ((6294, 6329), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (6298, 6329), False, 'from ddtrace.span import Span\n'), ((1764, 1775), 'numpy.int64', 'np.int64', (['(1)'], {}), '(1)\n', (1772, 1775), True, 'import numpy as np\n'), ((2324, 2341), 'time.sleep', 'time.sleep', (['sleep'], {}), '(sleep)\n', (2334, 2341), False, 'import time\n'), ((1666, 1697), 'unittest.case.SkipTest', 'SkipTest', (['"""numpy not installed"""'], {}), "('numpy not installed')\n", (1674, 1697), False, 'from unittest.case import SkipTest\n'), ((3913, 3929), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (3923, 3929), False, 'import time\n')] |
import logging, matplotlib, os, sys, glob
import scanpy as sc
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib import colors
import pandas as pd
from glbase3 import genelist
plt.rcParams['figure.figsize']=(8,8)
sc.settings.verbosity = 3
sc.set_figure_params(dpi=200, dpi_save=200)
matplotlib.rcParams['pdf.fonttype']=42
matplotlib.rcParams['font.size']=10
from glbase3 import genelist, glload
sc.settings.figdir = 'diffexp'
[os.remove(f) for f in glob.glob('{}/*.pdf'.format(sc.settings.figdir))]
[os.remove(f) for f in glob.glob('gls/*.glb'.format(sc.settings.figdir))]
[os.remove(f) for f in glob.glob('gls/*.tsv'.format(sc.settings.figdir))]
transcript_id = glload('../../transcript_assembly/packed/all_genes.glb')
transcript_id = {i['transcript_id']: i for i in transcript_id}
de_leiden = 'de_clusters' # If you merge clusters;
#de_leiden = 'leiden_r1.00'
adata = sc.read('./de.h5ad')
sc.pl.rank_genes_groups(adata, n_genes=25, sharey=True, show=False, save='genes-top25.pdf')
sc.pl.rank_genes_groups(adata, key='rank_genes_groups', show=False, save='genes.pdf')
sc.pl.rank_genes_groups_dotplot(adata, key='rank_genes_groups', show=False, save='genes-top25.pdf')
topall = pd.DataFrame(adata.uns['rank_genes_groups']['names']) # get all;
fcs = pd.DataFrame(adata.uns['rank_genes_groups']['logfoldchanges'])
padj = pd.DataFrame(adata.uns['rank_genes_groups']['pvals_adj'])
# Matrix of DE genes:
groups = list(topall.columns.values)
newcols = {}
for group in groups:
newcols[group] = []
t = zip([i[group] for i in adata.uns['rank_genes_groups']['names']], [i[group] for i in adata.uns['rank_genes_groups']['logfoldchanges']], [i[group] for i in adata.uns['rank_genes_groups']['pvals_adj']])
print('Group: {0}'.format(group))
for item in t:
if item[1] < 2: # fold change
continue
if item[2] > 0.01: # just in case
continue
newcols[group].append({'transcript_id': item[0], 'log2FC': item[1], 'q': item[2],
'ensg': transcript_id[item[0]]['ensg'], 'enst': transcript_id[item[0]]['enst'], 'name': transcript_id[item[0]]['name']})
# join all and draw a dotplot:
for group in newcols:
print('Top 10:\n', newcols[group][0:10])
if newcols[group]:
gl = genelist()
gl.load_list(newcols[group])
gl.saveTSV('gls/de_genes-grp{0}.tsv'.format(group))
gl.save('gls/de_genes-grp{0}.glb'.format(group))
genes = [i['transcript_id'] for i in newcols[group]]
#sc.pl.dotplot(adata, genes, groupby=de_leiden, dot_max=0.7, dendrogram=True, standard_scale='var', show=False, save='de-grp{0}.pdf'.format(group))
#sc.pl.matrixplot(adata, genes, groupby=de_leiden, dendrogram=True, standard_scale='var', show=False, save='de-grp{0}.pdf'.format(group))
for grp in newcols:
if not newcols[grp]:
continue
for k in newcols[grp]:
title = k['name']
sc.pl.umap(adata, color=k['transcript_id'], size=10, legend_loc='on data',
title=title,
vmin=0, vmax=3,
show=False, save='-markers-grp{0}-{1}-{2}.pdf'.format(grp, k['transcript_id'], k['name']))
#sc.pl.violin(adata, [k], groupby='disease', size=0, log=False, cut=0, show=False, save='markers-{0}-disease.pdf'.format(k))
#sc.pl.violin(adata, [k], groupby='cell_type', size=0, log=False, cut=0, show=False, save='markers-{0}-cell_type.pdf'.format(k))
| [
"scanpy.read",
"pandas.DataFrame",
"glbase3.glload",
"scanpy.pl.rank_genes_groups",
"glbase3.genelist",
"scanpy.pl.rank_genes_groups_dotplot",
"scanpy.set_figure_params",
"os.remove"
] | [((268, 311), 'scanpy.set_figure_params', 'sc.set_figure_params', ([], {'dpi': '(200)', 'dpi_save': '(200)'}), '(dpi=200, dpi_save=200)\n', (288, 311), True, 'import scanpy as sc\n'), ((696, 752), 'glbase3.glload', 'glload', (['"""../../transcript_assembly/packed/all_genes.glb"""'], {}), "('../../transcript_assembly/packed/all_genes.glb')\n", (702, 752), False, 'from glbase3 import genelist, glload\n'), ((905, 925), 'scanpy.read', 'sc.read', (['"""./de.h5ad"""'], {}), "('./de.h5ad')\n", (912, 925), True, 'import scanpy as sc\n'), ((927, 1023), 'scanpy.pl.rank_genes_groups', 'sc.pl.rank_genes_groups', (['adata'], {'n_genes': '(25)', 'sharey': '(True)', 'show': '(False)', 'save': '"""genes-top25.pdf"""'}), "(adata, n_genes=25, sharey=True, show=False, save=\n 'genes-top25.pdf')\n", (950, 1023), True, 'import scanpy as sc\n'), ((1019, 1109), 'scanpy.pl.rank_genes_groups', 'sc.pl.rank_genes_groups', (['adata'], {'key': '"""rank_genes_groups"""', 'show': '(False)', 'save': '"""genes.pdf"""'}), "(adata, key='rank_genes_groups', show=False, save=\n 'genes.pdf')\n", (1042, 1109), True, 'import scanpy as sc\n'), ((1105, 1208), 'scanpy.pl.rank_genes_groups_dotplot', 'sc.pl.rank_genes_groups_dotplot', (['adata'], {'key': '"""rank_genes_groups"""', 'show': '(False)', 'save': '"""genes-top25.pdf"""'}), "(adata, key='rank_genes_groups', show=False,\n save='genes-top25.pdf')\n", (1136, 1208), True, 'import scanpy as sc\n'), ((1215, 1268), 'pandas.DataFrame', 'pd.DataFrame', (["adata.uns['rank_genes_groups']['names']"], {}), "(adata.uns['rank_genes_groups']['names'])\n", (1227, 1268), True, 'import pandas as pd\n'), ((1286, 1348), 'pandas.DataFrame', 'pd.DataFrame', (["adata.uns['rank_genes_groups']['logfoldchanges']"], {}), "(adata.uns['rank_genes_groups']['logfoldchanges'])\n", (1298, 1348), True, 'import pandas as pd\n'), ((1356, 1413), 'pandas.DataFrame', 'pd.DataFrame', (["adata.uns['rank_genes_groups']['pvals_adj']"], {}), "(adata.uns['rank_genes_groups']['pvals_adj'])\n", (1368, 1413), True, 'import pandas as pd\n'), ((459, 471), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (468, 471), False, 'import logging, matplotlib, os, sys, glob\n'), ((532, 544), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (541, 544), False, 'import logging, matplotlib, os, sys, glob\n'), ((606, 618), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (615, 618), False, 'import logging, matplotlib, os, sys, glob\n'), ((2284, 2294), 'glbase3.genelist', 'genelist', ([], {}), '()\n', (2292, 2294), False, 'from glbase3 import genelist, glload\n')] |
#!/usr/bin/env python
import os.path
from datetime import datetime
import tempfile
import json
import vcr
from libcomcat.classes import DetailEvent, Product, VersionOption
from libcomcat.search import search, get_event_by_id
def get_datadir():
# where is this script?
homedir = os.path.dirname(os.path.abspath(__file__))
datadir = os.path.join(homedir, '..', 'data')
return datadir
def test_summary():
datadir = get_datadir()
tape_file = os.path.join(datadir, 'vcr_summary.yaml')
with vcr.use_cassette(tape_file):
eventlist = search(starttime=datetime(1994, 1, 17, 12, 30),
endtime=datetime(1994, 1, 18, 12, 35),
minmagnitude=6.6)
event = eventlist[0]
cmp = 'ci3144585 1994-01-17 12:30:55.390000 (34.213,-118.537) 18.2 km M6.7'
assert str(event) == cmp
assert event.id == 'ci3144585'
assert event.time == datetime(1994, 1, 17, 12, 30, 55, 390000)
assert event.latitude == 34.213
assert event.longitude == -118.537
assert event.depth == 18.202
assert event.magnitude == 6.7
assert 'cdi' in event.properties
assert event['cdi'] == 8.6
assert event.hasProduct('shakemap')
assert not event.hasProduct('foo')
try:
event['foo']
assert 1 == 2
except AttributeError:
pass
assert event.hasProperty('cdi')
assert not event.hasProperty('foo')
assert isinstance(event.getDetailEvent(), DetailEvent)
durl = 'https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=ci3144585&format=geojson'
assert event.getDetailURL() == durl
try:
detail = event.getDetailEvent(includedeleted=True,
includesuperseded=True)
assert 1 == 2
except RuntimeError:
pass
# find an event that has multiple versions of shakemap to test
# include superseded
# official20110311054624120_30
eventlist = search(starttime=datetime(2011, 3, 11, 0, 0),
endtime=datetime(2011, 3, 12, 0, 0),
minmagnitude=8.8)
honshu = eventlist[0]
detail = honshu.getDetailEvent(includesuperseded=True)
shakemaps = detail.getProducts('shakemap', version=VersionOption.ALL)
assert shakemaps[1].source == 'atlas'
assert event.toDict()['depth'] == 18.202
def test_detail_product_versions():
datadir = get_datadir()
tape_file = os.path.join(datadir, 'vcr_detail_product.yaml')
with vcr.use_cassette(tape_file):
eventid = 'nn00570710'
detail = get_event_by_id(eventid, includesuperseded=True)
pref_origin_pref_source = detail.getProducts(
'origin', source='preferred', version=VersionOption.LAST)[0]
pref_origin_pref_source2 = detail.getProducts('origin')[0]
first_origin_pref_source = detail.getProducts(
'origin', source='preferred', version=VersionOption.FIRST)[0]
first_origin_us_source = detail.getProducts(
'origin', source='us', version=VersionOption.FIRST)[0]
last_origin_us_source = detail.getProducts(
'origin', source='us', version=VersionOption.LAST)[0]
pref_origins_all_sources = detail.getProducts(
'origin', source='all', version=VersionOption.LAST)
first_origins_all_sources = detail.getProducts(
'origin', source='all', version=VersionOption.FIRST)
all_origins_all_sources = detail.getProducts(
'origin', source='all', version=VersionOption.ALL)
assert pref_origin_pref_source.source == 'nn'
assert pref_origin_pref_source2.source == 'nn'
assert pref_origin_pref_source.version >= 7
assert pref_origin_pref_source2.version >= 7
assert first_origin_pref_source.source == 'nn'
assert first_origin_pref_source.version == 1
assert first_origin_us_source.source == 'us'
assert first_origin_us_source.version == 1
assert last_origin_us_source.source == 'us'
assert last_origin_us_source.version >= 5
sources = []
for origin in pref_origins_all_sources:
source = origin.source
version = origin.version
assert source not in sources
sources.append(source)
sources = []
for origin in first_origins_all_sources:
source = origin.source
version = origin.version
assert source not in sources
assert version == 1
sources.append(source)
def test_moment_supplement():
datadir = get_datadir()
tape_file = os.path.join(datadir, 'vcr_moment.yaml')
with vcr.use_cassette(tape_file):
eventid = 'us2000ar20' # 2017 M7.1 Mexico City
detail = get_event_by_id(eventid)
edict = detail.toDict(get_moment_supplement=True,
get_tensors='preferred')
assert edict['us_Mww_percent_double_couple'] == 0.9992
def test_detail():
datadir = get_datadir()
tape_file = os.path.join(datadir, 'vcr_detail.yaml')
with vcr.use_cassette(tape_file):
eventid = 'ci3144585' # northridge
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/%s.geojson' % eventid
event = DetailEvent(url)
assert str(
event) == 'ci3144585 1994-01-17 12:30:55.390000 (34.213,-118.537) 18.2 km M6.7'
assert event.hasProduct('shakemap')
assert event.hasProduct('foo') == False
assert event.hasProperty('foo') == False
assert event.hasProperty('time')
try:
event['foo']
assert 1 == 2
except AttributeError as ae:
pass
try:
event.getNumVersions('foo')
assert 1 == 2
except AttributeError as ae:
pass
try:
event.getProducts('foo')
assert 1 == 2
except AttributeError as ae:
pass
try:
event.getProducts('shakemap', source='foo')
assert 1 == 2
except AttributeError as ae:
pass
assert event.toDict()['magnitude'] == 6.7
eventid = 'nc72282711' # Napa 2014 eq, multiple origins and MTs.
# cievent = get_event_by_id(eventid,catalog='ci')
# usevent = get_event_by_id(eventid,catalog='us')
# atevent = get_event_by_id(eventid,catalog='at')
event = get_event_by_id(eventid)
phases = event.getProducts('phase-data', source='all')
ncdict = event.toDict(catalog='nc')
usdict = event.toDict(catalog='us')
atdict = event.toDict(catalog='at')
try:
event.toDict(catalog='foo')
assert 1 == 2
except AttributeError as ae:
pass
assert ncdict['depth'] == 11.12
assert usdict['depth'] == 11.25
assert atdict['depth'] == 9.0
ncdict_allmags = event.toDict(get_all_magnitudes=True)
assert ncdict_allmags['magtype3'] == 'Ml'
ncdict_alltensors = event.toDict(get_tensors='all')
assert ncdict_alltensors['us_Mwb_mrr'] == 7.63e+16
ncdict_allfocals = event.toDict(get_focals='all')
assert ncdict_allfocals['nc_np1_strike'] == '345.0'
assert event.getNumVersions('shakemap') > 0
assert isinstance(event.getProducts('shakemap')[0], Product)
assert event.latitude == 38.2151667
assert event.longitude == -122.3123333
assert event.depth == 11.12
assert event.id == eventid
assert event.time == datetime(2014, 8, 24, 10, 20, 44, 70000)
assert 'sources' in event.properties
assert event['mag'] == 6.02
# test all of the different functionality of the getProducts() method
# first, test default behavior (get the most preferred product):
# 2003 Central California
event = get_event_by_id('nc21323712', includesuperseded=True)
pref_shakemap = event.getProducts('shakemap')[0]
assert pref_shakemap.source == 'atlas'
assert pref_shakemap.update_time >= datetime(
2017, 4, 12, 10, 50, 9, 368000)
assert pref_shakemap.preferred_weight >= 100000000
# get the first Atlas shakemap
first_shakemap = event.getProducts(
'shakemap', version=VersionOption.FIRST, source='atlas')[0]
assert first_shakemap.source == 'atlas'
assert first_shakemap.update_time >= datetime(
2015, 2, 4, 6, 1, 33, 400000)
assert first_shakemap.preferred_weight >= 81
# get the first nc shakemap
first_shakemap = event.getProducts(
'shakemap', version=VersionOption.FIRST, source='nc')[0]
assert first_shakemap.source == 'nc'
assert first_shakemap.update_time >= datetime(
2017, 3, 8, 20, 12, 59, 380000)
assert first_shakemap.preferred_weight >= 231
# get the last version of the nc shakemaps
last_shakemap = event.getProducts(
'shakemap', version=VersionOption.LAST, source='nc')[0]
assert last_shakemap.source == 'nc'
assert last_shakemap.update_time >= datetime(
2017, 3, 17, 17, 40, 26, 576000)
assert last_shakemap.preferred_weight >= 231
# get all the nc versions of the shakemap
shakemaps = event.getProducts(
'shakemap', version=VersionOption.ALL, source='nc')
for shakemap4 in shakemaps:
assert shakemap4.source == 'nc'
# get all versions of all shakemaps
shakemaps = event.getProducts(
'shakemap', version=VersionOption.ALL, source='all')
assert event.getNumVersions('shakemap') == len(shakemaps)
def test_product():
datadir = get_datadir()
tape_file = os.path.join(datadir, 'vcr_product.yaml')
with vcr.use_cassette(tape_file):
eventid = 'ci3144585' # northridge
event = get_event_by_id(eventid)
product = event.getProducts('shakemap')[0]
assert product.preferred_weight == 100000000
assert product.source == 'atlas'
assert product.update_time >= datetime(2017, 4, 12, 6, 25, 42, 120000)
pnames = product.getContentsMatching('grid.xml')
url = product.getContentURL('grid.xml')
assert url == 'https://earthquake.usgs.gov/archive/product/shakemap/atlas19940117123055/atlas/1491978342120/download/grid.xml'
assert len(product.getContentsMatching('foo')) == 0
assert len(pnames) > 1
assert str(
product) == 'Product shakemap from atlas updated 2017-04-12 06:25:42.120000 containing 63 content files.'
assert product.hasProperty('maxmmi')
assert 'maxmmi' in product.properties
assert product['maxmmi'] == '8.6'
assert 'download/cont_mi.kmz' in product.contents
assert product.getContentName('grid.xml') == 'grid.xml'
assert product.getContentName('foo') is None
assert product.getContentURL('foo') is None
try:
product.getContent('foo', filename=None)
assert 1 == 2
except AttributeError as ae:
pass
try:
product['foo']
assert 1 == 2
except AttributeError as ae:
pass
try:
handle, tfilename = tempfile.mkstemp()
os.close(handle)
product.getContent('info.json', tfilename)
f = open(tfilename, 'rt')
jdict = json.load(f)
f.close()
assert jdict['input']['event_information']['depth'] == 19
except:
raise Exception('Failure to download Product content file')
finally:
os.remove(tfilename)
# test getting content as a string.
infobytes, url = product.getContentBytes('info.json')
infostring = infobytes.decode('utf-8')
jdict = json.loads(infostring)
eid = jdict['input']['event_information']['event_id']
assert eid == '19940117123055'
if __name__ == '__main__':
test_moment_supplement()
test_detail_product_versions()
test_summary()
test_detail()
test_product()
| [
"datetime.datetime",
"json.loads",
"libcomcat.search.get_event_by_id",
"vcr.use_cassette",
"libcomcat.classes.DetailEvent",
"json.load",
"tempfile.mkstemp"
] | [((520, 547), 'vcr.use_cassette', 'vcr.use_cassette', (['tape_file'], {}), '(tape_file)\n', (536, 547), False, 'import vcr\n'), ((2642, 2669), 'vcr.use_cassette', 'vcr.use_cassette', (['tape_file'], {}), '(tape_file)\n', (2658, 2669), False, 'import vcr\n'), ((2719, 2767), 'libcomcat.search.get_event_by_id', 'get_event_by_id', (['eventid'], {'includesuperseded': '(True)'}), '(eventid, includesuperseded=True)\n', (2734, 2767), False, 'from libcomcat.search import search, get_event_by_id\n'), ((4812, 4839), 'vcr.use_cassette', 'vcr.use_cassette', (['tape_file'], {}), '(tape_file)\n', (4828, 4839), False, 'import vcr\n'), ((4914, 4938), 'libcomcat.search.get_event_by_id', 'get_event_by_id', (['eventid'], {}), '(eventid)\n', (4929, 4938), False, 'from libcomcat.search import search, get_event_by_id\n'), ((5230, 5257), 'vcr.use_cassette', 'vcr.use_cassette', (['tape_file'], {}), '(tape_file)\n', (5246, 5257), False, 'import vcr\n'), ((5413, 5429), 'libcomcat.classes.DetailEvent', 'DetailEvent', (['url'], {}), '(url)\n', (5424, 5429), False, 'from libcomcat.classes import DetailEvent, Product, VersionOption\n'), ((6573, 6597), 'libcomcat.search.get_event_by_id', 'get_event_by_id', (['eventid'], {}), '(eventid)\n', (6588, 6597), False, 'from libcomcat.search import search, get_event_by_id\n'), ((8037, 8090), 'libcomcat.search.get_event_by_id', 'get_event_by_id', (['"""nc21323712"""'], {'includesuperseded': '(True)'}), "('nc21323712', includesuperseded=True)\n", (8052, 8090), False, 'from libcomcat.search import search, get_event_by_id\n'), ((9979, 10006), 'vcr.use_cassette', 'vcr.use_cassette', (['tape_file'], {}), '(tape_file)\n', (9995, 10006), False, 'import vcr\n'), ((10068, 10092), 'libcomcat.search.get_event_by_id', 'get_event_by_id', (['eventid'], {}), '(eventid)\n', (10083, 10092), False, 'from libcomcat.search import search, get_event_by_id\n'), ((12034, 12056), 'json.loads', 'json.loads', (['infostring'], {}), '(infostring)\n', (12044, 12056), False, 'import json\n'), ((942, 983), 'datetime.datetime', 'datetime', (['(1994)', '(1)', '(17)', '(12)', '(30)', '(55)', '(390000)'], {}), '(1994, 1, 17, 12, 30, 55, 390000)\n', (950, 983), False, 'from datetime import datetime\n'), ((7713, 7753), 'datetime.datetime', 'datetime', (['(2014)', '(8)', '(24)', '(10)', '(20)', '(44)', '(70000)'], {}), '(2014, 8, 24, 10, 20, 44, 70000)\n', (7721, 7753), False, 'from datetime import datetime\n'), ((8239, 8279), 'datetime.datetime', 'datetime', (['(2017)', '(4)', '(12)', '(10)', '(50)', '(9)', '(368000)'], {}), '(2017, 4, 12, 10, 50, 9, 368000)\n', (8247, 8279), False, 'from datetime import datetime\n'), ((8601, 8639), 'datetime.datetime', 'datetime', (['(2015)', '(2)', '(4)', '(6)', '(1)', '(33)', '(400000)'], {}), '(2015, 2, 4, 6, 1, 33, 400000)\n', (8609, 8639), False, 'from datetime import datetime\n'), ((8946, 8986), 'datetime.datetime', 'datetime', (['(2017)', '(3)', '(8)', '(20)', '(12)', '(59)', '(380000)'], {}), '(2017, 3, 8, 20, 12, 59, 380000)\n', (8954, 8986), False, 'from datetime import datetime\n'), ((9305, 9346), 'datetime.datetime', 'datetime', (['(2017)', '(3)', '(17)', '(17)', '(40)', '(26)', '(576000)'], {}), '(2017, 3, 17, 17, 40, 26, 576000)\n', (9313, 9346), False, 'from datetime import datetime\n'), ((10276, 10316), 'datetime.datetime', 'datetime', (['(2017)', '(4)', '(12)', '(6)', '(25)', '(42)', '(120000)'], {}), '(2017, 4, 12, 6, 25, 42, 120000)\n', (10284, 10316), False, 'from datetime import datetime\n'), ((11460, 11478), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (11476, 11478), False, 'import tempfile\n'), ((11621, 11633), 'json.load', 'json.load', (['f'], {}), '(f)\n', (11630, 11633), False, 'import json\n'), ((586, 615), 'datetime.datetime', 'datetime', (['(1994)', '(1)', '(17)', '(12)', '(30)'], {}), '(1994, 1, 17, 12, 30)\n', (594, 615), False, 'from datetime import datetime\n'), ((652, 681), 'datetime.datetime', 'datetime', (['(1994)', '(1)', '(18)', '(12)', '(35)'], {}), '(1994, 1, 18, 12, 35)\n', (660, 681), False, 'from datetime import datetime\n'), ((2098, 2125), 'datetime.datetime', 'datetime', (['(2011)', '(3)', '(11)', '(0)', '(0)'], {}), '(2011, 3, 11, 0, 0)\n', (2106, 2125), False, 'from datetime import datetime\n'), ((2162, 2189), 'datetime.datetime', 'datetime', (['(2011)', '(3)', '(12)', '(0)', '(0)'], {}), '(2011, 3, 12, 0, 0)\n', (2170, 2189), False, 'from datetime import datetime\n')] |
import functools
import json
from contextlib import contextmanager
import pytest
import launch
import launch.cli
import launch.config
import pkgpanda
import ssh
import test_util
from launch.util import get_temp_config_path, stub
from test_util.helpers import Host
@contextmanager
def mocked_context(*args, **kwargs):
""" To be directly patched into an ssh.tunnel invocation to prevent
any real SSH attempt
"""
yield type('Tunnelled', (object,), {})
@pytest.fixture
def mocked_test_runner(monkeypatch):
monkeypatch.setattr(ssh.tunnel, 'tunnel', mocked_context)
monkeypatch.setattr(test_util.runner, 'integration_test', stub(0))
@pytest.fixture
def ssh_key_path(tmpdir):
ssh_key_path = tmpdir.join('ssh_key')
ssh_key_path.write(launch.util.MOCK_SSH_KEY_DATA)
return str(ssh_key_path)
class MockStack:
def __init__(self):
self.stack_id = launch.util.MOCK_STACK_ID
mock_pub_priv_host = Host('127.0.0.1', '12.34.56')
mock_priv_host = Host('127.0.0.1', None)
@pytest.fixture
def mocked_aws_cf(monkeypatch, mocked_test_runner):
"""Does not include SSH key mocking
"""
monkeypatch.setattr(test_util.aws.DcosCfStack, '__init__', stub(None))
monkeypatch.setattr(
test_util.aws, 'fetch_stack', lambda stack_name, bw: test_util.aws.DcosCfStack(stack_name, bw))
# mock create
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_stack', stub(MockStack()))
# mock wait
monkeypatch.setattr(test_util.aws.CfStack, 'wait_for_complete', stub(None))
# mock describe
monkeypatch.setattr(test_util.aws.DcosCfStack, 'get_master_ips',
stub([mock_pub_priv_host]))
monkeypatch.setattr(test_util.aws.DcosCfStack, 'get_private_agent_ips',
stub([mock_priv_host]))
monkeypatch.setattr(test_util.aws.DcosCfStack, 'get_public_agent_ips',
stub([mock_pub_priv_host]))
# mock delete
monkeypatch.setattr(test_util.aws.DcosCfStack, 'delete', stub(None))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'delete_key_pair', stub(None))
# mock config
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_key_pair', stub(launch.util.MOCK_SSH_KEY_DATA))
@pytest.fixture
def mocked_aws_zen_cf(monkeypatch, mocked_aws_cf):
monkeypatch.setattr(test_util.aws.DcosZenCfStack, '__init__', stub(None))
monkeypatch.setattr(
test_util.aws, 'fetch_stack', lambda stack_name, bw: test_util.aws.DcosZenCfStack(stack_name, bw))
# mock create
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_vpc_tagged', stub(launch.util.MOCK_VPC_ID))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_internet_gateway_tagged', stub(launch.util.MOCK_GATEWAY_ID))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_subnet_tagged', stub(launch.util.MOCK_SUBNET_ID))
# mock delete
monkeypatch.setattr(test_util.aws.BotoWrapper, 'delete_subnet', stub(None))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'delete_vpc', stub(None))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'delete_internet_gateway', stub(None))
# mock describe
monkeypatch.setattr(test_util.aws.DcosZenCfStack, 'get_master_ips',
stub([mock_pub_priv_host]))
monkeypatch.setattr(test_util.aws.DcosZenCfStack, 'get_private_agent_ips',
stub([mock_priv_host]))
monkeypatch.setattr(test_util.aws.DcosZenCfStack, 'get_public_agent_ips',
stub([mock_pub_priv_host]))
# mock delete
monkeypatch.setattr(test_util.aws.DcosZenCfStack, 'delete', stub(None))
@pytest.fixture
def mocked_azure(monkeypatch, mocked_test_runner):
monkeypatch.setattr(test_util.azure.ServicePrincipalCredentials, '__init__', stub(None))
monkeypatch.setattr(test_util.azure.ResourceManagementClient, '__init__', stub(None))
monkeypatch.setattr(test_util.azure.NetworkManagementClient, '__init__', stub(None))
monkeypatch.setattr(test_util.azure.AzureWrapper, 'deploy_template_to_new_resource_group', stub(None))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'wait_for_deployment', stub(None))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'delete', stub(None))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'get_master_ips',
stub([mock_pub_priv_host]))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'get_private_agent_ips',
stub([mock_priv_host]))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'get_public_agent_ips',
stub([mock_pub_priv_host]))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'public_agent_lb_fqdn', 'abc-foo-bar')
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'public_master_lb_fqdn', 'dead-beef')
@pytest.fixture
def aws_cf_config_path(tmpdir, ssh_key_path, mocked_aws_cf):
return get_temp_config_path(tmpdir, 'aws-cf.yaml', update={'ssh_private_key_filename': ssh_key_path})
@pytest.fixture
def aws_cf_with_helper_config_path(tmpdir, mocked_aws_cf):
return get_temp_config_path(tmpdir, 'aws-cf-with-helper.yaml')
@pytest.fixture
def aws_zen_cf_config_path(tmpdir, ssh_key_path, mocked_aws_zen_cf):
return get_temp_config_path(tmpdir, 'aws-zen-cf.yaml')
@pytest.fixture
def aws_cf_no_pytest_config_path(tmpdir, mocked_aws_cf):
return get_temp_config_path(tmpdir, 'aws-cf-no-pytest.yaml')
@pytest.fixture
def azure_config_path(tmpdir, mocked_azure, ssh_key_path):
return get_temp_config_path(tmpdir, 'azure.yaml', update={'ssh_private_key_filename': ssh_key_path})
@pytest.fixture
def azure_with_helper_config_path(tmpdir, mocked_azure):
return get_temp_config_path(tmpdir, 'azure-with-helper.yaml')
@pytest.fixture
def aws_onprem_config_path(tmpdir, ssh_key_path):
return get_temp_config_path(tmpdir, 'aws-onprem.yaml', update={'ssh_private_key_filename': ssh_key_path})
@pytest.fixture
def aws_onprem_with_helper_config_path(tmpdir):
return get_temp_config_path(tmpdir, 'aws-onprem-with-helper.yaml')
@pytest.fixture
def aws_bare_cluster_config_path(tmpdir, ssh_key_path):
return get_temp_config_path(tmpdir, 'aws-bare-cluster.yaml', update={'ssh_private_key_filename': ssh_key_path})
@pytest.fixture
def bare_cluster_onprem_config_path(tmpdir, ssh_key_path):
platform_info_path = tmpdir.join('bare_cluster_info.json')
platform_info_path.write("""
{
"ssh_user": "core"
}
""")
return get_temp_config_path(tmpdir, 'bare-cluster-onprem.yaml', update={
'ssh_private_key_filename': ssh_key_path,
'platform_info_filename': str(platform_info_path)})
def check_cli(cmd):
assert launch.cli.main(cmd) == 0, 'Command failed! {}'.format(' '.join(cmd))
def check_success(capsys, tmpdir, config_path):
"""
Runs through the required functions of a launcher and then
runs through the default usage of the script for a
given config path and info path, ensuring each step passes
if all steps finished successfully, this parses and returns the generated
info JSON and stdout description JSON for more specific checks
"""
# Test launcher directly first
config = launch.config.get_validated_config(config_path)
launcher = launch.get_launcher(config)
info = launcher.create(config)
launcher.wait(info)
launcher.describe(info)
launcher.test(info, 'py.test')
launcher.delete(info)
info_path = str(tmpdir.join('my_specific_info.json')) # test non-default name
# Now check launcher via CLI
check_cli(['create', '--config-path={}'.format(config_path), '--info-path={}'.format(info_path)])
# use the info written to disk to ensure JSON parsable
info = pkgpanda.util.load_json(info_path)
check_cli(['wait', '--info-path={}'.format(info_path)])
# clear stdout capture
capsys.readouterr()
check_cli(['describe', '--info-path={}'.format(info_path)])
# capture stdout from describe and ensure JSON parse-able
description = json.loads(capsys.readouterr()[0])
# general assertions about description
assert 'masters' in description
assert 'private_agents' in description
assert 'public_agents' in description
check_cli(['pytest', '--info-path={}'.format(info_path)])
check_cli(['delete', '--info-path={}'.format(info_path)])
return info, description
@pytest.fixture
def check_cli_success(capsys, tmpdir):
return functools.partial(check_success, capsys, tmpdir)
| [
"pkgpanda.util.load_json",
"launch.config.get_validated_config",
"test_util.helpers.Host",
"test_util.aws.DcosCfStack",
"test_util.aws.DcosZenCfStack",
"functools.partial",
"launch.cli.main",
"launch.util.stub",
"launch.util.get_temp_config_path",
"launch.get_launcher"
] | [((942, 971), 'test_util.helpers.Host', 'Host', (['"""127.0.0.1"""', '"""12.34.56"""'], {}), "('127.0.0.1', '12.34.56')\n", (946, 971), False, 'from test_util.helpers import Host\n'), ((989, 1012), 'test_util.helpers.Host', 'Host', (['"""127.0.0.1"""', 'None'], {}), "('127.0.0.1', None)\n", (993, 1012), False, 'from test_util.helpers import Host\n'), ((4954, 5053), 'launch.util.get_temp_config_path', 'get_temp_config_path', (['tmpdir', '"""aws-cf.yaml"""'], {'update': "{'ssh_private_key_filename': ssh_key_path}"}), "(tmpdir, 'aws-cf.yaml', update={\n 'ssh_private_key_filename': ssh_key_path})\n", (4974, 5053), False, 'from launch.util import get_temp_config_path, stub\n'), ((5137, 5192), 'launch.util.get_temp_config_path', 'get_temp_config_path', (['tmpdir', '"""aws-cf-with-helper.yaml"""'], {}), "(tmpdir, 'aws-cf-with-helper.yaml')\n", (5157, 5192), False, 'from launch.util import get_temp_config_path, stub\n'), ((5291, 5338), 'launch.util.get_temp_config_path', 'get_temp_config_path', (['tmpdir', '"""aws-zen-cf.yaml"""'], {}), "(tmpdir, 'aws-zen-cf.yaml')\n", (5311, 5338), False, 'from launch.util import get_temp_config_path, stub\n'), ((5425, 5478), 'launch.util.get_temp_config_path', 'get_temp_config_path', (['tmpdir', '"""aws-cf-no-pytest.yaml"""'], {}), "(tmpdir, 'aws-cf-no-pytest.yaml')\n", (5445, 5478), False, 'from launch.util import get_temp_config_path, stub\n'), ((5567, 5665), 'launch.util.get_temp_config_path', 'get_temp_config_path', (['tmpdir', '"""azure.yaml"""'], {'update': "{'ssh_private_key_filename': ssh_key_path}"}), "(tmpdir, 'azure.yaml', update={\n 'ssh_private_key_filename': ssh_key_path})\n", (5587, 5665), False, 'from launch.util import get_temp_config_path, stub\n'), ((5747, 5801), 'launch.util.get_temp_config_path', 'get_temp_config_path', (['tmpdir', '"""azure-with-helper.yaml"""'], {}), "(tmpdir, 'azure-with-helper.yaml')\n", (5767, 5801), False, 'from launch.util import get_temp_config_path, stub\n'), ((5881, 5984), 'launch.util.get_temp_config_path', 'get_temp_config_path', (['tmpdir', '"""aws-onprem.yaml"""'], {'update': "{'ssh_private_key_filename': ssh_key_path}"}), "(tmpdir, 'aws-onprem.yaml', update={\n 'ssh_private_key_filename': ssh_key_path})\n", (5901, 5984), False, 'from launch.util import get_temp_config_path, stub\n'), ((6057, 6116), 'launch.util.get_temp_config_path', 'get_temp_config_path', (['tmpdir', '"""aws-onprem-with-helper.yaml"""'], {}), "(tmpdir, 'aws-onprem-with-helper.yaml')\n", (6077, 6116), False, 'from launch.util import get_temp_config_path, stub\n'), ((6202, 6311), 'launch.util.get_temp_config_path', 'get_temp_config_path', (['tmpdir', '"""aws-bare-cluster.yaml"""'], {'update': "{'ssh_private_key_filename': ssh_key_path}"}), "(tmpdir, 'aws-bare-cluster.yaml', update={\n 'ssh_private_key_filename': ssh_key_path})\n", (6222, 6311), False, 'from launch.util import get_temp_config_path, stub\n'), ((7242, 7289), 'launch.config.get_validated_config', 'launch.config.get_validated_config', (['config_path'], {}), '(config_path)\n', (7276, 7289), False, 'import launch\n'), ((7305, 7332), 'launch.get_launcher', 'launch.get_launcher', (['config'], {}), '(config)\n', (7324, 7332), False, 'import launch\n'), ((7771, 7805), 'pkgpanda.util.load_json', 'pkgpanda.util.load_json', (['info_path'], {}), '(info_path)\n', (7794, 7805), False, 'import pkgpanda\n'), ((8487, 8535), 'functools.partial', 'functools.partial', (['check_success', 'capsys', 'tmpdir'], {}), '(check_success, capsys, tmpdir)\n', (8504, 8535), False, 'import functools\n'), ((648, 655), 'launch.util.stub', 'stub', (['(0)'], {}), '(0)\n', (652, 655), False, 'from launch.util import get_temp_config_path, stub\n'), ((1194, 1204), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (1198, 1204), False, 'from launch.util import get_temp_config_path, stub\n'), ((1523, 1533), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (1527, 1533), False, 'from launch.util import get_temp_config_path, stub\n'), ((1648, 1674), 'launch.util.stub', 'stub', (['[mock_pub_priv_host]'], {}), '([mock_pub_priv_host])\n', (1652, 1674), False, 'from launch.util import get_temp_config_path, stub\n'), ((1776, 1798), 'launch.util.stub', 'stub', (['[mock_priv_host]'], {}), '([mock_priv_host])\n', (1780, 1798), False, 'from launch.util import get_temp_config_path, stub\n'), ((1899, 1925), 'launch.util.stub', 'stub', (['[mock_pub_priv_host]'], {}), '([mock_pub_priv_host])\n', (1903, 1925), False, 'from launch.util import get_temp_config_path, stub\n'), ((2006, 2016), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (2010, 2016), False, 'from launch.util import get_temp_config_path, stub\n'), ((2088, 2098), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (2092, 2098), False, 'from launch.util import get_temp_config_path, stub\n'), ((2188, 2223), 'launch.util.stub', 'stub', (['launch.util.MOCK_SSH_KEY_DATA'], {}), '(launch.util.MOCK_SSH_KEY_DATA)\n', (2192, 2223), False, 'from launch.util import get_temp_config_path, stub\n'), ((2360, 2370), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (2364, 2370), False, 'from launch.util import get_temp_config_path, stub\n'), ((2594, 2623), 'launch.util.stub', 'stub', (['launch.util.MOCK_VPC_ID'], {}), '(launch.util.MOCK_VPC_ID)\n', (2598, 2623), False, 'from launch.util import get_temp_config_path, stub\n'), ((2710, 2743), 'launch.util.stub', 'stub', (['launch.util.MOCK_GATEWAY_ID'], {}), '(launch.util.MOCK_GATEWAY_ID)\n', (2714, 2743), False, 'from launch.util import get_temp_config_path, stub\n'), ((2820, 2852), 'launch.util.stub', 'stub', (['launch.util.MOCK_SUBNET_ID'], {}), '(launch.util.MOCK_SUBNET_ID)\n', (2824, 2852), False, 'from launch.util import get_temp_config_path, stub\n'), ((2940, 2950), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (2944, 2950), False, 'from launch.util import get_temp_config_path, stub\n'), ((3017, 3027), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (3021, 3027), False, 'from launch.util import get_temp_config_path, stub\n'), ((3107, 3117), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (3111, 3117), False, 'from launch.util import get_temp_config_path, stub\n'), ((3235, 3261), 'launch.util.stub', 'stub', (['[mock_pub_priv_host]'], {}), '([mock_pub_priv_host])\n', (3239, 3261), False, 'from launch.util import get_temp_config_path, stub\n'), ((3366, 3388), 'launch.util.stub', 'stub', (['[mock_priv_host]'], {}), '([mock_priv_host])\n', (3370, 3388), False, 'from launch.util import get_temp_config_path, stub\n'), ((3492, 3518), 'launch.util.stub', 'stub', (['[mock_pub_priv_host]'], {}), '([mock_pub_priv_host])\n', (3496, 3518), False, 'from launch.util import get_temp_config_path, stub\n'), ((3602, 3612), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (3606, 3612), False, 'from launch.util import get_temp_config_path, stub\n'), ((3764, 3774), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (3768, 3774), False, 'from launch.util import get_temp_config_path, stub\n'), ((3854, 3864), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (3858, 3864), False, 'from launch.util import get_temp_config_path, stub\n'), ((3943, 3953), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (3947, 3953), False, 'from launch.util import get_temp_config_path, stub\n'), ((4051, 4061), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (4055, 4061), False, 'from launch.util import get_temp_config_path, stub\n'), ((4150, 4160), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (4154, 4160), False, 'from launch.util import get_temp_config_path, stub\n'), ((4236, 4246), 'launch.util.stub', 'stub', (['None'], {}), '(None)\n', (4240, 4246), False, 'from launch.util import get_temp_config_path, stub\n'), ((4354, 4380), 'launch.util.stub', 'stub', (['[mock_pub_priv_host]'], {}), '([mock_pub_priv_host])\n', (4358, 4380), False, 'from launch.util import get_temp_config_path, stub\n'), ((4495, 4517), 'launch.util.stub', 'stub', (['[mock_priv_host]'], {}), '([mock_priv_host])\n', (4499, 4517), False, 'from launch.util import get_temp_config_path, stub\n'), ((4631, 4657), 'launch.util.stub', 'stub', (['[mock_pub_priv_host]'], {}), '([mock_pub_priv_host])\n', (4635, 4657), False, 'from launch.util import get_temp_config_path, stub\n'), ((6732, 6752), 'launch.cli.main', 'launch.cli.main', (['cmd'], {}), '(cmd)\n', (6747, 6752), False, 'import launch\n'), ((1292, 1333), 'test_util.aws.DcosCfStack', 'test_util.aws.DcosCfStack', (['stack_name', 'bw'], {}), '(stack_name, bw)\n', (1317, 1333), False, 'import test_util\n'), ((2458, 2502), 'test_util.aws.DcosZenCfStack', 'test_util.aws.DcosZenCfStack', (['stack_name', 'bw'], {}), '(stack_name, bw)\n', (2486, 2502), False, 'import test_util\n')] |
from gzip import (
compress,
GzipFile
)
import numpy as np
from .record import Record
UNK = '<unk>'
PAD = '<pad>'
class Vocab(Record):
__attributes__ = ['words', 'counts']
def __init__(self, words, counts):
self.words = words
self.counts = counts
self.word_ids = {
word: id
for id, word in enumerate(self.words)
}
self.unk_id = self.word_ids.get(UNK)
self.pad_id = self.word_ids.get(PAD)
def __getitem__(self, word):
return self.word_ids[word]
def __contains__(self, word):
return word in self.word_ids
def get(self, word, default=None):
if word in self:
return self[word]
return default
def count(self, word):
return self.counts[self.word_ids[word]]
def top(self, count=None):
return sorted(
self.words,
key=self.count,
reverse=True
)[:count]
def sampled(self, words):
words = list(words)
counts = [
self.counts[self.word_ids[_]]
for _ in words
]
return Vocab(words, counts)
def __repr__(self):
return '{name}(words=[...], counts=[...])'.format(
name=self.__class__.__name__
)
def _repr_pretty_(self, printer, cycle):
printer.text(repr(self))
@classmethod
def from_glove(cls, words, counts):
# for some reason glove vocab may have words with broken
# unicode
words = [_.decode('utf8', errors='ignore') for _ in words]
# emb has unk in the end
for word in (UNK, PAD):
words.append(word)
counts.append(0)
return cls(words, counts)
@property
def as_glove(self):
for word, count in zip(self.words, self.counts):
if word in (UNK, PAD):
continue
word = word.encode('utf8')
yield word, count
@property
def as_bytes(self):
meta = [len(self.counts)]
meta = np.array(meta).astype(np.uint32).tobytes()
words = '\n'.join(self.words)
words = words.encode('utf8')
counts = np.array(self.counts, dtype=np.uint32).tobytes()
return compress(meta + counts + words)
@classmethod
def from_file(cls, file):
file = GzipFile(mode='rb', fileobj=file)
buffer = file.read(4)
size, = np.frombuffer(buffer, np.uint32)
buffer = file.read(4 * size)
counts = np.frombuffer(buffer, np.uint32).tolist()
text = file.read().decode('utf8')
words = text.splitlines()
return cls(words, counts)
| [
"gzip.GzipFile",
"numpy.array",
"numpy.frombuffer",
"gzip.compress"
] | [((2259, 2290), 'gzip.compress', 'compress', (['(meta + counts + words)'], {}), '(meta + counts + words)\n', (2267, 2290), False, 'from gzip import compress, GzipFile\n'), ((2354, 2387), 'gzip.GzipFile', 'GzipFile', ([], {'mode': '"""rb"""', 'fileobj': 'file'}), "(mode='rb', fileobj=file)\n", (2362, 2387), False, 'from gzip import compress, GzipFile\n'), ((2435, 2467), 'numpy.frombuffer', 'np.frombuffer', (['buffer', 'np.uint32'], {}), '(buffer, np.uint32)\n', (2448, 2467), True, 'import numpy as np\n'), ((2195, 2233), 'numpy.array', 'np.array', (['self.counts'], {'dtype': 'np.uint32'}), '(self.counts, dtype=np.uint32)\n', (2203, 2233), True, 'import numpy as np\n'), ((2523, 2555), 'numpy.frombuffer', 'np.frombuffer', (['buffer', 'np.uint32'], {}), '(buffer, np.uint32)\n', (2536, 2555), True, 'import numpy as np\n'), ((2058, 2072), 'numpy.array', 'np.array', (['meta'], {}), '(meta)\n', (2066, 2072), True, 'import numpy as np\n')] |
from setuptools import setup, find_packages
setup(
name='aioteleclient',
version='0.0.1',
url='https://github.com/elmcrest/aioteleclient',
license='MIT',
description='An fast and heavily tested async telegram messenger client.',
long_description="An fast and heavily tested async telegram messenger client",
author='<NAME>',
author_email='<EMAIL>',
keywords='python telegram-client telegram-client-api asyncio async-telegram-client'
'bot bot-framework telegram aioteleclient',
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Topic :: Communications :: Chat'
],
packages=find_packages(),
install_requires=[
'aiohttp'
],
)
| [
"setuptools.find_packages"
] | [((747, 762), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (760, 762), False, 'from setuptools import setup, find_packages\n')] |
# This is only an example of a battle that I used to test.
from core.Automata import Automata
# init
shiki = Automata("assets/Qp4.png", "assets/eg-sp1.png", (248, 0))
# start
shiki.quick_start()
# battle 1
shiki.select_servant_skill(5)
shiki.select_servant_skill(6)
shiki.select_servant_skill(7)
shiki.select_cards([7])
# battle 2
shiki.select_servant_skill(8)
shiki.select_cards([8])
# battle 3
# shiki.toggle_master_skill()
shiki.select_master_skill(2, 1)
shiki.select_servant_skill(1)
shiki.select_servant_skill(2)
shiki.select_cards([6])
# finish
shiki.finish_battle()
| [
"core.Automata.Automata"
] | [((109, 166), 'core.Automata.Automata', 'Automata', (['"""assets/Qp4.png"""', '"""assets/eg-sp1.png"""', '(248, 0)'], {}), "('assets/Qp4.png', 'assets/eg-sp1.png', (248, 0))\n", (117, 166), False, 'from core.Automata import Automata\n')] |
#!/usr/bin/env python3
# still in development
#
import asyncio
import websockets
import json
import requests
eventsAPIPath = '/api/v1/events'
localServerIP = '0.0.0.0'
localServerAPIPort = '8000'
localServerWSPort = '8000'
localServerPath = '/sealog-server'
#devel
localToken = "<KEY>"
#prod
#localToken = "<KEY>"
localClientWSID = 'localSealogReceive'
remoteServerIP = '162.243.201.175'
remoteServerAPIPort = '80'
remoteServerWSPort = '80'
remoteServerPath = '/sealog-server'
remoteToken = "<KEY>"
remoteClientWSID = 'remoteSealogReceive'
hello = {
'type': 'hello',
'id': localClientWSID,
'auth': {
'headers': {
'authorization': localToken
}
},
'version': '2',
'subs': ['/ws/status/newEvents']
}
ping = {
'type':'ping',
'id':localClientWSID
}
localHeaders = {'authorization': localToken}
remoteHeaders = {'authorization': remoteToken}
async def eventlog():
try:
async with websockets.connect('ws://' + localServerIP + ':' + localServerWSPort) as websocket:
await websocket.send(json.dumps(hello))
while(True):
event = await websocket.recv()
eventObj = json.loads(event)
print("eventObj:", eventObj)
if eventObj['type'] and eventObj['type'] == 'ping':
await websocket.send(json.dumps(ping))
elif eventObj['type'] and eventObj['type'] == 'pub':
r = requests.post('http://' + remoteServerIP + ':' + remoteServerAPIPort + remoteServerPath + eventsAPIPath, headers=remoteHeaders, data = json.dumps(eventObj['message']))
print(r.text)
### end of repeat
except Exception as error:
print(error)
asyncio.get_event_loop().run_until_complete(eventlog())
| [
"websockets.connect",
"json.dumps",
"json.loads",
"asyncio.get_event_loop"
] | [((1773, 1797), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1795, 1797), False, 'import asyncio\n'), ((955, 1024), 'websockets.connect', 'websockets.connect', (["('ws://' + localServerIP + ':' + localServerWSPort)"], {}), "('ws://' + localServerIP + ':' + localServerWSPort)\n", (973, 1024), False, 'import websockets\n'), ((1193, 1210), 'json.loads', 'json.loads', (['event'], {}), '(event)\n', (1203, 1210), False, 'import json\n'), ((1073, 1090), 'json.dumps', 'json.dumps', (['hello'], {}), '(hello)\n', (1083, 1090), False, 'import json\n'), ((1366, 1382), 'json.dumps', 'json.dumps', (['ping'], {}), '(ping)\n', (1376, 1382), False, 'import json\n'), ((1613, 1644), 'json.dumps', 'json.dumps', (["eventObj['message']"], {}), "(eventObj['message'])\n", (1623, 1644), False, 'import json\n')] |
#!/usr/bin/env python
from athstmt import *
from athinterpreter import TildeAthInterp
stmts = AthStatementList([
AthTokenStatement('PROCREATE', [IdentifierToken('TEST'), None]),
TildeAthLoop(False, AthStatementList([
CondiJump([IdentifierToken('TEST'), 3]),
AthTokenStatement('print', [LiteralToken('Test!\\n', str)]),
AthTokenStatement('REPLICATE', [IdentifierToken('TEST'), UnaryExpr(['!', IdentifierToken('TEST')])]),
CondiJump([None, 5]),
CondiJump([UnaryExpr(['!', IdentifierToken('TEST')]), 3]),
AthTokenStatement('print', [LiteralToken('Test died\\n', str)]),
AthTokenStatement('DIE', [IdentifierToken('THIS')]),
CondiJump([None, 1]),
AthTokenStatement('print', [LiteralToken('should not print\\n', str)]),
], pendant='THIS'),
AthTokenStatement('EXECUTE', [IdentifierToken('NULL')]))
], pendant='THIS')
if __name__ == '__main__':
TildeAthInterp().exec_stmts('IfJump.~ATH', stmts)
| [
"athinterpreter.TildeAthInterp"
] | [((943, 959), 'athinterpreter.TildeAthInterp', 'TildeAthInterp', ([], {}), '()\n', (957, 959), False, 'from athinterpreter import TildeAthInterp\n')] |
import torch
from torch.utils.data import dataset
from tqdm import tqdm
from pathlib import Path
class DatasetBase(dataset.Dataset):
def __init__(self,
dataset_name, split,
cache_dir = None,
load_cache_if_exists=True,
**kwargs):
super().__init__(**kwargs)
self.dataset_name = dataset_name
self.split = split
self.cache_dir = cache_dir
self.is_cached = False
if load_cache_if_exists:
self.cache(verbose=0, must_exist=True)
@property
def record_tokens(self):
raise NotImplementedError
def read_record(self, token):
raise NotImplementedError
def __len__(self):
return len(self.record_tokens)
def __getitem__(self, index):
token = self.record_tokens[index]
try:
return self._records[token]
except AttributeError:
record = self.read_record(token)
self._records = {token:record}
return record
except KeyError:
record = self.read_record(token)
self._records[token] = record
return record
def read_all_records(self, verbose=1):
self._records = {}
if verbose:
print(f'Reading all {self.split} records...', flush=True)
for token in tqdm(self.record_tokens):
self._records[token] = self.read_record(token)
else:
for token in self.record_tokens:
self._records[token] = self.read_record(token)
def get_cache_path(self, path=None):
if path is None: path = self.cache_dir
base_path = (Path(path)/self.dataset_name)/self.split
base_path.mkdir(parents=True, exist_ok=True)
return base_path
def cache_load_and_save(self, base_path, op, verbose):
tokens_path = base_path/'tokens.pt'
records_path = base_path/'records.pt'
if op == 'load':
self._record_tokens = torch.load(str(tokens_path))
self._records = torch.load(str(records_path))
elif op == 'save':
if tokens_path.exists() and records_path.exists() \
and hasattr(self, '_record_tokens') and hasattr(self, '_records'):
return
self.read_all_records(verbose=verbose)
torch.save(self.record_tokens, str(tokens_path))
torch.save(self._records, str(records_path))
else:
raise ValueError(f'Unknown operation: {op}')
def cache(self, path=None, verbose=1, must_exist=False):
if self.is_cached: return
base_path = self.get_cache_path(path)
try:
if verbose: print(f'Trying to load {self.split} cache from disk...', flush=True)
self.cache_load_and_save(base_path, 'load', verbose)
if verbose: print(f'Loaded {self.split} cache from disk.', flush=True)
except FileNotFoundError:
if must_exist: return
if verbose: print(f'{self.split} cache does not exist! Cacheing...', flush=True)
self.cache_load_and_save(base_path, 'save', verbose)
if verbose: print(f'Saved {self.split} cache to disk.', flush=True)
self.is_cached = True
| [
"tqdm.tqdm",
"pathlib.Path"
] | [((1403, 1427), 'tqdm.tqdm', 'tqdm', (['self.record_tokens'], {}), '(self.record_tokens)\n', (1407, 1427), False, 'from tqdm import tqdm\n'), ((1728, 1738), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (1732, 1738), False, 'from pathlib import Path\n')] |
# (c) Copyright 2013 IBM Company
#
# 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 mock
from os_brick.initiator.connectors import fibre_channel_ppc64
from os_brick.initiator import linuxscsi
from os_brick.tests.initiator import test_connector
class FibreChannelConnectorPPC64TestCase(test_connector.ConnectorTestCase):
def setUp(self):
super(FibreChannelConnectorPPC64TestCase, self).setUp()
self.connector = fibre_channel_ppc64.FibreChannelConnectorPPC64(
None, execute=self.fake_execute, use_multipath=False)
self.assertIsNotNone(self.connector)
self.assertIsNotNone(self.connector._linuxfc)
self.assertEqual(self.connector._linuxfc.__class__.__name__,
"LinuxFibreChannel")
self.assertIsNotNone(self.connector._linuxscsi)
@mock.patch.object(linuxscsi.LinuxSCSI, 'process_lun_id', return_value='2')
def test_get_host_devices(self, mock_process_lun_id):
lun = 2
possible_devs = [(3, "0x5005076802232ade"),
(3, "0x5005076802332ade"), ]
devices = self.connector._get_host_devices(possible_devs, lun)
self.assertEqual(2, len(devices))
device_path = "/dev/disk/by-path/fc-0x5005076802332ade-lun-2"
self.assertIn(device_path, devices)
device_path = "/dev/disk/by-path/fc-0x5005076802232ade-lun-2"
self.assertIn(device_path, devices)
# test duplicates
possible_devs = [(3, "0x5005076802232ade"),
(3, "0x5005076802232ade"), ]
devices = self.connector._get_host_devices(possible_devs, lun)
self.assertEqual(1, len(devices))
device_path = "/dev/disk/by-path/fc-0x5005076802232ade-lun-2"
self.assertIn(device_path, devices)
| [
"mock.patch.object",
"os_brick.initiator.connectors.fibre_channel_ppc64.FibreChannelConnectorPPC64"
] | [((1354, 1428), 'mock.patch.object', 'mock.patch.object', (['linuxscsi.LinuxSCSI', '"""process_lun_id"""'], {'return_value': '"""2"""'}), "(linuxscsi.LinuxSCSI, 'process_lun_id', return_value='2')\n", (1371, 1428), False, 'import mock\n'), ((964, 1069), 'os_brick.initiator.connectors.fibre_channel_ppc64.FibreChannelConnectorPPC64', 'fibre_channel_ppc64.FibreChannelConnectorPPC64', (['None'], {'execute': 'self.fake_execute', 'use_multipath': '(False)'}), '(None, execute=self.\n fake_execute, use_multipath=False)\n', (1010, 1069), False, 'from os_brick.initiator.connectors import fibre_channel_ppc64\n')] |
# Execute below code with command,
# spark-submit --master local[*] network_wordcount.py localhost 9999
from __future__ import print_function
import sys
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: network_wordcount.py <hostname> <port>", file=sys.stderr)
exit(-1)
sc = SparkContext(appName="PythonStreamingNetworkWordCount")
ssc = StreamingContext(sc, 1)
lines = ssc.socketTextStream(sys.argv[1], int(sys.argv[2]))
counts = lines.flatMap(lambda line: line.split(" "))\
.map(lambda word: (word, 1))\
.reduceByKey(lambda a, b: a+b)
counts.pprint()
ssc.start()
ssc.awaitTermination()
| [
"pyspark.streaming.StreamingContext",
"pyspark.SparkContext"
] | [((408, 463), 'pyspark.SparkContext', 'SparkContext', ([], {'appName': '"""PythonStreamingNetworkWordCount"""'}), "(appName='PythonStreamingNetworkWordCount')\n", (420, 463), False, 'from pyspark import SparkContext\n'), ((475, 498), 'pyspark.streaming.StreamingContext', 'StreamingContext', (['sc', '(1)'], {}), '(sc, 1)\n', (491, 498), False, 'from pyspark.streaming import StreamingContext\n')] |
from pathlib import Path
from easy_sdm.data.data_loader import ShapefileLoader
from easy_sdm.featuarizer.build_features import OccurrancesDatasetBuilder
from easy_sdm.utils.utils import PathUtils
def extract_occurances(species_shapefile_path: Path):
processed_rasters_dirpath = PathUtils.dir_path(Path.cwd() / "data/processed_rasters/standarized_rasters")
species_shapefile_path = PathUtils.file_path(species_shapefile_path)
raster_paths_list = PathUtils.get_rasters_filepaths_in_dir(
processed_rasters_dirpath
)
occ_dst_builder = OccurrancesDatasetBuilder(raster_paths_list)
df = occ_dst_builder.build(
ShapefileLoader().read_geodataframe(species_shapefile_path)
)
assert(df.shape[0]>0)
assert(df.index.names == ['lat', 'lon']) | [
"easy_sdm.utils.utils.PathUtils.get_rasters_filepaths_in_dir",
"pathlib.Path.cwd",
"easy_sdm.utils.utils.PathUtils.file_path",
"easy_sdm.featuarizer.build_features.OccurrancesDatasetBuilder",
"easy_sdm.data.data_loader.ShapefileLoader"
] | [((392, 435), 'easy_sdm.utils.utils.PathUtils.file_path', 'PathUtils.file_path', (['species_shapefile_path'], {}), '(species_shapefile_path)\n', (411, 435), False, 'from easy_sdm.utils.utils import PathUtils\n'), ((460, 525), 'easy_sdm.utils.utils.PathUtils.get_rasters_filepaths_in_dir', 'PathUtils.get_rasters_filepaths_in_dir', (['processed_rasters_dirpath'], {}), '(processed_rasters_dirpath)\n', (498, 525), False, 'from easy_sdm.utils.utils import PathUtils\n'), ((562, 606), 'easy_sdm.featuarizer.build_features.OccurrancesDatasetBuilder', 'OccurrancesDatasetBuilder', (['raster_paths_list'], {}), '(raster_paths_list)\n', (587, 606), False, 'from easy_sdm.featuarizer.build_features import OccurrancesDatasetBuilder\n'), ((304, 314), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (312, 314), False, 'from pathlib import Path\n'), ((647, 664), 'easy_sdm.data.data_loader.ShapefileLoader', 'ShapefileLoader', ([], {}), '()\n', (662, 664), False, 'from easy_sdm.data.data_loader import ShapefileLoader\n')] |
# Generated by Django 2.1.7 on 2019-05-21 14:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0008_auto_20190521_1937'),
]
operations = [
migrations.AddField(
model_name='account',
name='name',
field=models.CharField(default='', max_length=64, verbose_name='Name'),
preserve_default=False,
),
]
| [
"django.db.models.CharField"
] | [((334, 398), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(64)', 'verbose_name': '"""Name"""'}), "(default='', max_length=64, verbose_name='Name')\n", (350, 398), False, 'from django.db import migrations, models\n')] |
# -*- coding: utf-8 -*-
from EXOSIMS.Prototypes.OpticalSystem import OpticalSystem
import astropy.units as u
import numpy as np
import scipy.stats as st
import scipy.optimize as opt
class Nemati(OpticalSystem):
"""Nemati Optical System class
This class contains all variables and methods necessary to perform
Optical System Module calculations in exoplanet mission simulation using
the model from Nemati 2014.
Args:
\*\*specs:
user specified values
"""
def __init__(self, **specs):
OpticalSystem.__init__(self, **specs)
def calc_intTime(self, TL, sInds, fZ, fEZ, dMag, WA, mode):
"""Finds integration times of target systems for a specific observing
mode (imaging or characterization), based on Nemati 2014 (SPIE).
Args:
TL (TargetList module):
TargetList class object
sInds (integer ndarray):
Integer indices of the stars of interest
fZ (astropy Quantity array):
Surface brightness of local zodiacal light in units of 1/arcsec2
fEZ (astropy Quantity array):
Surface brightness of exo-zodiacal light in units of 1/arcsec2
dMag (float ndarray):
Differences in magnitude between planets and their host star
WA (astropy Quantity array):
Working angles of the planets of interest in units of arcsec
mode (dict):
Selected observing mode
Returns:
intTime (astropy Quantity array):
Integration times in units of day
"""
# electron counts
C_p, C_b, C_sp = self.Cp_Cb_Csp(TL, sInds, fZ, fEZ, dMag, WA, mode)
# get SNR threshold
SNR = mode['SNR']
# calculate integration time based on Nemati 2014
with np.errstate(divide='ignore', invalid='ignore'):
intTime = np.true_divide(SNR**2*C_b, (C_p**2 - (SNR*C_sp)**2))
# infinite and NAN are set to zero
intTime[np.isinf(intTime) | np.isnan(intTime)] = 0.*u.d
# negative values are set to zero
intTime[intTime < 0] = 0.*u.d
return intTime.to('day')
def calc_dMag_per_intTime(self, intTimes, TL, sInds, fZ, fEZ, WA, mode, C_b=None, C_sp=None):
"""Finds achievable dMag for one integration time per star in the input
list at one working angle.
Args:
intTimes (astropy Quantity array):
Integration times
TL (TargetList module):
TargetList class object
sInds (integer ndarray):
Integer indices of the stars of interest
fZ (astropy Quantity array):
Surface brightness of local zodiacal light for each star in sInds
in units of 1/arcsec2
fEZ (astropy Quantity array):
Surface brightness of exo-zodiacal light for each star in sInds
in units of 1/arcsec2
WA (astropy Quantity array):
Working angle for each star in sInds in units of arcsec
mode (dict):
Selected observing mode
C_b (astropy Quantity array):
Background noise electron count rate in units of 1/s (optional)
C_sp (astropy Quantity array):
Residual speckle spatial structure (systematic error) in units of 1/s
(optional)
Returns:
dMag (ndarray):
Achievable dMag for given integration time and working angle
"""
# cast sInds, WA, fZ, fEZ, and intTimes to arrays
sInds = np.array(sInds, ndmin=1, copy=False)
WA = np.array(WA.value, ndmin=1)*WA.unit
fZ = np.array(fZ.value, ndmin=1)*fZ.unit
fEZ = np.array(fEZ.value, ndmin=1)*fEZ.unit
intTimes = np.array(intTimes.value, ndmin=1)*intTimes.unit
assert len(intTimes) == len(sInds), "intTimes and sInds must be same length"
assert len(fEZ) == len(sInds), "fEZ must be an array of length len(sInds)"
assert len(fZ) == len(sInds), "fZ must be an array of length len(sInds)"
assert len(WA) == len(sInds), "WA must be an array of length len(sInds)"
# get scienceInstrument and starlightSuppressionSystem
inst = mode['inst']
syst = mode['syst']
# get mode wavelength
lam = mode['lam']
# get mode bandwidth (including any IFS spectral resolving power)
deltaLam = lam/inst['Rs'] if 'spec' in inst['name'].lower() else mode['deltaLam']
# get star magnitude
mV = TL.starMag(sInds, lam)
# get signal to noise ratio
SNR = mode['SNR']
# spectral flux density = F0 * A * Dlam * QE * T (attenuation due to optics)
attenuation = inst['optics']*syst['optics']
C_F0 = self.F0(lam)*self.pupilArea*deltaLam*inst['QE'](lam)*attenuation
# get core_thruput
core_thruput = syst['core_thruput'](lam, WA)
# calculate planet delta magnitude
dMagLim = np.zeros(len(sInds)) + 25
if (C_b is None) or (C_sp is None):
_, C_b, C_sp = self.Cp_Cb_Csp(TL, sInds, fZ, fEZ, dMagLim, WA, mode)
dMag = -2.5*np.log10((SNR*np.sqrt(C_b/intTimes + C_sp**2)/(C_F0*10.0**(-0.4*mV)*core_thruput*inst['PCeff'])).decompose().value)
return dMag
def ddMag_dt(self, intTimes, TL, sInds, fZ, fEZ, WA, mode, C_b=None, C_sp=None):
"""Finds derivative of achievable dMag with respect to integration time
Args:
intTimes (astropy Quantity array):
Integration times
TL (TargetList module):
TargetList class object
sInds (integer ndarray):
Integer indices of the stars of interest
fZ (astropy Quantity array):
Surface brightness of local zodiacal light for each star in sInds
in units of 1/arcsec2
fEZ (astropy Quantity array):
Surface brightness of exo-zodiacal light for each star in sInds
in units of 1/arcsec2
WA (astropy Quantity array):
Working angle for each star in sInds in units of arcsec
mode (dict):
Selected observing mode
C_b (astropy Quantity array):
Background noise electron count rate in units of 1/s (optional)
C_sp (astropy Quantity array):
Residual speckle spatial structure (systematic error) in units of 1/s
(optional)
Returns:
ddMagdt (ndarray):
Derivative of achievable dMag with respect to integration time
"""
# cast sInds, WA, fZ, fEZ, and intTimes to arrays
sInds = np.array(sInds, ndmin=1, copy=False)
WA = np.array(WA.value, ndmin=1)*WA.unit
fZ = np.array(fZ.value, ndmin=1)*fZ.unit
fEZ = np.array(fEZ.value, ndmin=1)*fEZ.unit
intTimes = np.array(intTimes.value, ndmin=1)*intTimes.unit
assert len(intTimes) == len(sInds), "intTimes and sInds must be same length"
assert len(fEZ) == len(sInds), "fEZ must be an array of length len(sInds)"
assert len(fZ) == len(sInds), "fZ must be an array of length len(sInds)"
assert len(WA) == len(sInds), "WA must be an array of length len(sInds)"
dMagLim = np.zeros(len(sInds)) + 25
if (C_b is None) or (C_sp is None):
_, C_b, C_sp = self.Cp_Cb_Csp(TL, sInds, fZ, fEZ, dMagLim, WA, mode)
ddMagdt = 2.5/(2.0*np.log(10.0))*(C_b/(C_b*intTimes + (C_sp*intTimes)**2)).to('1/s').value
return ddMagdt/u.s
| [
"numpy.sqrt",
"numpy.log",
"EXOSIMS.Prototypes.OpticalSystem.OpticalSystem.__init__",
"numpy.array",
"numpy.errstate",
"numpy.isnan",
"numpy.true_divide",
"numpy.isinf"
] | [((590, 627), 'EXOSIMS.Prototypes.OpticalSystem.OpticalSystem.__init__', 'OpticalSystem.__init__', (['self'], {}), '(self, **specs)\n', (612, 627), False, 'from EXOSIMS.Prototypes.OpticalSystem import OpticalSystem\n'), ((3905, 3941), 'numpy.array', 'np.array', (['sInds'], {'ndmin': '(1)', 'copy': '(False)'}), '(sInds, ndmin=1, copy=False)\n', (3913, 3941), True, 'import numpy as np\n'), ((7218, 7254), 'numpy.array', 'np.array', (['sInds'], {'ndmin': '(1)', 'copy': '(False)'}), '(sInds, ndmin=1, copy=False)\n', (7226, 7254), True, 'import numpy as np\n'), ((1997, 2043), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (2008, 2043), True, 'import numpy as np\n'), ((2068, 2128), 'numpy.true_divide', 'np.true_divide', (['(SNR ** 2 * C_b)', '(C_p ** 2 - (SNR * C_sp) ** 2)'], {}), '(SNR ** 2 * C_b, C_p ** 2 - (SNR * C_sp) ** 2)\n', (2082, 2128), True, 'import numpy as np\n'), ((3956, 3983), 'numpy.array', 'np.array', (['WA.value'], {'ndmin': '(1)'}), '(WA.value, ndmin=1)\n', (3964, 3983), True, 'import numpy as np\n'), ((4006, 4033), 'numpy.array', 'np.array', (['fZ.value'], {'ndmin': '(1)'}), '(fZ.value, ndmin=1)\n', (4014, 4033), True, 'import numpy as np\n'), ((4057, 4085), 'numpy.array', 'np.array', (['fEZ.value'], {'ndmin': '(1)'}), '(fEZ.value, ndmin=1)\n', (4065, 4085), True, 'import numpy as np\n'), ((4115, 4148), 'numpy.array', 'np.array', (['intTimes.value'], {'ndmin': '(1)'}), '(intTimes.value, ndmin=1)\n', (4123, 4148), True, 'import numpy as np\n'), ((7269, 7296), 'numpy.array', 'np.array', (['WA.value'], {'ndmin': '(1)'}), '(WA.value, ndmin=1)\n', (7277, 7296), True, 'import numpy as np\n'), ((7319, 7346), 'numpy.array', 'np.array', (['fZ.value'], {'ndmin': '(1)'}), '(fZ.value, ndmin=1)\n', (7327, 7346), True, 'import numpy as np\n'), ((7370, 7398), 'numpy.array', 'np.array', (['fEZ.value'], {'ndmin': '(1)'}), '(fEZ.value, ndmin=1)\n', (7378, 7398), True, 'import numpy as np\n'), ((7428, 7461), 'numpy.array', 'np.array', (['intTimes.value'], {'ndmin': '(1)'}), '(intTimes.value, ndmin=1)\n', (7436, 7461), True, 'import numpy as np\n'), ((2182, 2199), 'numpy.isinf', 'np.isinf', (['intTime'], {}), '(intTime)\n', (2190, 2199), True, 'import numpy as np\n'), ((2202, 2219), 'numpy.isnan', 'np.isnan', (['intTime'], {}), '(intTime)\n', (2210, 2219), True, 'import numpy as np\n'), ((8020, 8032), 'numpy.log', 'np.log', (['(10.0)'], {}), '(10.0)\n', (8026, 8032), True, 'import numpy as np\n'), ((5589, 5624), 'numpy.sqrt', 'np.sqrt', (['(C_b / intTimes + C_sp ** 2)'], {}), '(C_b / intTimes + C_sp ** 2)\n', (5596, 5624), True, 'import numpy as np\n')] |
# Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch.nn as nn
class AdjustLayer(nn.Module):
def __init__(self, inplane, outplane):
super(AdjustLayer, self).__init__()
self.downsample = nn.Sequential(
nn.Conv2d(inplane, outplane, kernel_size=1, bias=False),
nn.BatchNorm2d(outplane),
)
def forward(self, x):
x = self.downsample(x)
if x.size(3) < 20:
l = 4
r = l + 7
x = x[:, :, l:r, l:r]
return x
class AdjustAllLayer(nn.Module):
def __init__(self, in_channels, out_channels):
super(AdjustAllLayer, self).__init__()
self.num = len(out_channels)
if self.num == 1:
self.downsample = AdjustLayer(in_channels[0], out_channels[0])
else:
for i in range(self.num):
self.add_module('downsample'+str(i+2),
AdjustLayer(in_channels[i], out_channels[i]))
def forward(self, features):
if self.num == 1:
return self.downsample(features)
else:
out = []
for i in range(self.num):
adj_layer = getattr(self, 'downsample'+str(i+2))
out.append(adj_layer(features[i]))
return out
| [
"torch.nn.BatchNorm2d",
"torch.nn.Conv2d"
] | [((412, 467), 'torch.nn.Conv2d', 'nn.Conv2d', (['inplane', 'outplane'], {'kernel_size': '(1)', 'bias': '(False)'}), '(inplane, outplane, kernel_size=1, bias=False)\n', (421, 467), True, 'import torch.nn as nn\n'), ((486, 510), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['outplane'], {}), '(outplane)\n', (500, 510), True, 'import torch.nn as nn\n')] |
import logging
from django.conf.urls import include, url
from django.db import transaction
from django.db.models import F
from django.http import Http404
from django.shortcuts import redirect, render
from django.template.defaultfilters import pluralize
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from wagtail.admin import messages
from wagtail.admin.site_summary import PagesSummaryItem, SummaryItem
from wagtail.admin.views.pages.utils import get_valid_next_url_from_request
from wagtail.admin.widgets import Button, ButtonWithDropdownFromHook
from wagtail.core import hooks
from wagtail.core.models import Page
from wagtail_personalisation import admin_urls, models, utils
from wagtail_personalisation.adapters import get_segment_adapter
from wagtail_personalisation.models import PersonalisablePageMetadata
logger = logging.getLogger(__name__)
@hooks.register('register_admin_urls')
def register_admin_urls():
"""Adds the administration urls for the personalisation apps."""
return [
url(r'^personalisation/', include(
admin_urls, namespace='wagtail_personalisation')),
]
@hooks.register('before_serve_page')
def set_visit_count(page, request, serve_args, serve_kwargs):
"""Tests the provided rules to see if the request still belongs
to a segment.
:param page: The page being served
:type page: wagtail.core.models.Page
:param request: The http request
:type request: django.http.HttpRequest
"""
adapter = get_segment_adapter(request)
adapter.add_page_visit(page)
@hooks.register('before_serve_page')
def segment_user(page, request, serve_args, serve_kwargs):
"""Apply a segment to a visitor before serving the page.
:param page: The page being served
:type page: wagtail.core.models.Page
:param request: The http request
:type request: django.http.HttpRequest
"""
adapter = get_segment_adapter(request)
adapter.refresh()
forced_segment = request.GET.get('segment', None)
if request.user.is_superuser and forced_segment is not None:
segment = models.Segment.objects.filter(pk=forced_segment).first()
if segment:
adapter.set_segments([segment])
class UserbarSegmentedLinkItem:
def __init__(self, segment):
self.segment = segment
def render(self, request):
return f"""<div class="wagtail-userbar__item">
<a href="{request.path}?segment={self.segment.pk}"
class="wagtail-action">
Show as segment: {self.segment.name}</a></div>"""
@hooks.register('construct_wagtail_userbar')
def add_segment_link_items(request, items):
for item in models.Segment.objects.enabled():
items.append(UserbarSegmentedLinkItem(item))
return items
@hooks.register('before_serve_page')
def serve_variant(page, request, serve_args, serve_kwargs):
"""Apply a segment to a visitor before serving the page.
:param page: The page being served
:type page: wagtail.core.models.Page
:param request: The http request
:type request: django.http.HttpRequest
:returns: A variant if one is available for the visitor's segment,
otherwise the original page
:rtype: wagtail.core.models.Page
"""
user_segments = []
if not isinstance(page, models.PersonalisablePageMixin):
return
adapter = get_segment_adapter(request)
user_segments = adapter.get_segments()
metadata = page.personalisation_metadata
# If page is not canonical, don't serve it.
if not metadata.is_canonical:
raise Http404
if user_segments:
# TODO: This is never more then one page? (fix query count)
metadata = metadata.metadata_for_segments(user_segments)
if metadata:
variant = metadata.first().variant.specific
return variant.serve(request, *serve_args, **serve_kwargs)
@hooks.register('construct_explorer_page_queryset')
def dont_show_variant(parent_page, pages, request):
return utils.exclude_variants(pages)
@hooks.register('register_page_listing_buttons')
def page_listing_variant_buttons(page, page_perms, is_parent=False, next_url=None):
"""Adds page listing buttons to personalisable pages. Shows variants for
the page (if any) and a 'Create a new variant' button.
"""
if not isinstance(page, models.PersonalisablePageMixin):
return
metadata = page.personalisation_metadata
if metadata.is_canonical:
yield ButtonWithDropdownFromHook(
_('Variants'),
hook_name='register_page_listing_variant_buttons',
page=page,
page_perms=page_perms,
is_parent=is_parent,
attrs={'target': '_blank', 'title': _('Create or edit a variant')},
priority=100)
@hooks.register('register_page_listing_variant_buttons')
def page_listing_more_buttons(page, page_perms, is_parent=False, next_url=None):
"""Adds a 'more' button to personalisable pages allowing users to quickly
create a new variant for the selected segment.
"""
if not isinstance(page, models.PersonalisablePageMixin):
return
metadata = page.personalisation_metadata
for vm in metadata.variants_metadata:
yield Button('%s variant' % (vm.segment.name),
reverse('wagtailadmin_pages:edit', args=[vm.variant_id]),
attrs={"title": _('Edit this variant')},
classes=("icon", "icon-fa-pencil"),
priority=0)
for segment in metadata.get_unused_segments():
yield Button('%s variant' % (segment.name),
reverse('segment:copy_page', args=[page.pk, segment.pk]),
attrs={"title": _('Create this variant')},
classes=("icon", "icon-fa-plus"),
priority=100)
yield Button(_('Create a new segment'),
reverse('wagtail_personalisation_segment_modeladmin_create'),
attrs={"title": _('Create a new segment')},
classes=("icon", "icon-fa-snowflake-o"),
priority=200)
class CorrectedPagesSummaryItem(PagesSummaryItem):
def get_context(self):
# Perform the same check as Wagtail to get the correct count.
# Only correct the count when a root page is available to the user.
# The `PagesSummaryItem` will return a page count of 0 otherwise.
# https://github.com/wagtail/wagtail/blob/5c9ff23e229acabad406c42c4e13cbaea32e6c15/wagtail/admin/site_summary.py#L38
context = super().get_context()
root_page = context.get('root_page', None)
if root_page:
pages = utils.exclude_variants(
Page.objects.descendant_of(root_page, inclusive=True))
page_count = pages.count()
if root_page.is_root():
page_count -= 1
context['total_pages'] = page_count
return context
@hooks.register('construct_homepage_summary_items')
def add_corrected_pages_summary_panel(request, items):
"""Replaces the Pages summary panel to hide variants."""
for index, item in enumerate(items):
if item.__class__ is PagesSummaryItem:
items[index] = CorrectedPagesSummaryItem(request)
class SegmentSummaryPanel(SummaryItem):
"""The segment summary panel showing the total amount of segments on the
site and allowing quick access to the Segment dashboard.
"""
order = 2000
def render(self):
segment_count = models.Segment.objects.count()
target_url = reverse('wagtail_personalisation_segment_modeladmin_index')
title = _("Segments")
return mark_safe("""
<li class="icon icon-fa-snowflake-o">
<a href="{}"><span>{}</span>{}</a>
</li>""".format(target_url, segment_count, title))
class PersonalisedPagesSummaryPanel(PagesSummaryItem):
order = 2100
def render(self):
page_count = models.PersonalisablePageMetadata.objects.filter(segment__isnull=True).count()
title = _("Personalised Page")
return mark_safe("""
<li class="icon icon-fa-file-o">
<span>{}</span>{}{}
</li>""".format(page_count, title, pluralize(page_count)))
class VariantPagesSummaryPanel(PagesSummaryItem):
order = 2200
def render(self):
page_count = models.PersonalisablePageMetadata.objects.filter(
segment__isnull=False).count()
title = _("Variant")
return mark_safe("""
<li class="icon icon-fa-files-o">
<span>{}</span>{}{}
</li>""".format(page_count, title, pluralize(page_count)))
@hooks.register('construct_homepage_summary_items')
def add_personalisation_summary_panels(request, items):
"""Adds a summary panel to the Wagtail dashboard showing the total amount
of segments on the site and allowing quick access to the Segment
dashboard.
"""
items.append(SegmentSummaryPanel(request))
items.append(PersonalisedPagesSummaryPanel(request))
items.append(VariantPagesSummaryPanel(request))
@hooks.register('before_delete_page')
def delete_related_variants(request, page):
if not isinstance(page, models.PersonalisablePageMixin) \
or not page.personalisation_metadata.is_canonical:
return
# Get a list of related personalisation metadata for all the related
# variants.
variants_metadata = (
page.personalisation_metadata.variants_metadata
.select_related('variant')
)
next_url = get_valid_next_url_from_request(request)
if request.method == 'POST':
parent_id = page.get_parent().id
with transaction.atomic():
# To ensure variants are deleted for all descendants, start with
# the deepest ones, and explicitly delete variants and metadata
# for all of them, including the page itself. Otherwise protected
# foreign key constraints are violated. Only consider canonical
# pages.
for metadata in PersonalisablePageMetadata.objects.filter(
canonical_page__in=page.get_descendants(inclusive=True),
variant=F("canonical_page"),
).order_by('-canonical_page__depth'):
for variant_metadata in metadata.variants_metadata.select_related('variant'):
# Call delete() on objects to trigger any signals or hooks.
variant_metadata.variant.delete()
metadata.delete()
metadata.canonical_page.delete()
msg = _("Page '{0}' and its variants deleted.")
messages.success(
request,
msg.format(page.get_admin_display_title())
)
for fn in hooks.get_hooks('after_delete_page'):
result = fn(request, page)
if hasattr(result, 'status_code'):
return result
if next_url:
return redirect(next_url)
return redirect('wagtailadmin_explore', parent_id)
return render(
request,
'wagtailadmin/pages/wagtail_personalisation/confirm_delete.html', {
'page': page,
'descendant_count': page.get_descendant_count(),
'next': next_url,
'variants': Page.objects.filter(
pk__in=variants_metadata.values_list('variant_id')
)
}
)
| [
"logging.getLogger",
"wagtail_personalisation.models.Segment.objects.count",
"django.utils.translation.ugettext_lazy",
"wagtail_personalisation.models.PersonalisablePageMetadata.objects.filter",
"django.db.transaction.atomic",
"wagtail_personalisation.models.Segment.objects.enabled",
"wagtail.core.model... | [((913, 940), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (930, 940), False, 'import logging\n'), ((944, 981), 'wagtail.core.hooks.register', 'hooks.register', (['"""register_admin_urls"""'], {}), "('register_admin_urls')\n", (958, 981), False, 'from wagtail.core import hooks\n'), ((1206, 1241), 'wagtail.core.hooks.register', 'hooks.register', (['"""before_serve_page"""'], {}), "('before_serve_page')\n", (1220, 1241), False, 'from wagtail.core import hooks\n'), ((1639, 1674), 'wagtail.core.hooks.register', 'hooks.register', (['"""before_serve_page"""'], {}), "('before_serve_page')\n", (1653, 1674), False, 'from wagtail.core import hooks\n'), ((2650, 2693), 'wagtail.core.hooks.register', 'hooks.register', (['"""construct_wagtail_userbar"""'], {}), "('construct_wagtail_userbar')\n", (2664, 2693), False, 'from wagtail.core import hooks\n'), ((2861, 2896), 'wagtail.core.hooks.register', 'hooks.register', (['"""before_serve_page"""'], {}), "('before_serve_page')\n", (2875, 2896), False, 'from wagtail.core import hooks\n'), ((3982, 4032), 'wagtail.core.hooks.register', 'hooks.register', (['"""construct_explorer_page_queryset"""'], {}), "('construct_explorer_page_queryset')\n", (3996, 4032), False, 'from wagtail.core import hooks\n'), ((4129, 4176), 'wagtail.core.hooks.register', 'hooks.register', (['"""register_page_listing_buttons"""'], {}), "('register_page_listing_buttons')\n", (4143, 4176), False, 'from wagtail.core import hooks\n'), ((4890, 4945), 'wagtail.core.hooks.register', 'hooks.register', (['"""register_page_listing_variant_buttons"""'], {}), "('register_page_listing_variant_buttons')\n", (4904, 4945), False, 'from wagtail.core import hooks\n'), ((7064, 7114), 'wagtail.core.hooks.register', 'hooks.register', (['"""construct_homepage_summary_items"""'], {}), "('construct_homepage_summary_items')\n", (7078, 7114), False, 'from wagtail.core import hooks\n'), ((8818, 8868), 'wagtail.core.hooks.register', 'hooks.register', (['"""construct_homepage_summary_items"""'], {}), "('construct_homepage_summary_items')\n", (8832, 8868), False, 'from wagtail.core import hooks\n'), ((9255, 9291), 'wagtail.core.hooks.register', 'hooks.register', (['"""before_delete_page"""'], {}), "('before_delete_page')\n", (9269, 9291), False, 'from wagtail.core import hooks\n'), ((1574, 1602), 'wagtail_personalisation.adapters.get_segment_adapter', 'get_segment_adapter', (['request'], {}), '(request)\n', (1593, 1602), False, 'from wagtail_personalisation.adapters import get_segment_adapter\n'), ((1979, 2007), 'wagtail_personalisation.adapters.get_segment_adapter', 'get_segment_adapter', (['request'], {}), '(request)\n', (1998, 2007), False, 'from wagtail_personalisation.adapters import get_segment_adapter\n'), ((2754, 2786), 'wagtail_personalisation.models.Segment.objects.enabled', 'models.Segment.objects.enabled', ([], {}), '()\n', (2784, 2786), False, 'from wagtail_personalisation import admin_urls, models, utils\n'), ((3452, 3480), 'wagtail_personalisation.adapters.get_segment_adapter', 'get_segment_adapter', (['request'], {}), '(request)\n', (3471, 3480), False, 'from wagtail_personalisation.adapters import get_segment_adapter\n'), ((4096, 4125), 'wagtail_personalisation.utils.exclude_variants', 'utils.exclude_variants', (['pages'], {}), '(pages)\n', (4118, 4125), False, 'from wagtail_personalisation import admin_urls, models, utils\n'), ((9732, 9772), 'wagtail.admin.views.pages.utils.get_valid_next_url_from_request', 'get_valid_next_url_from_request', (['request'], {}), '(request)\n', (9763, 9772), False, 'from wagtail.admin.views.pages.utils import get_valid_next_url_from_request\n'), ((7634, 7664), 'wagtail_personalisation.models.Segment.objects.count', 'models.Segment.objects.count', ([], {}), '()\n', (7662, 7664), False, 'from wagtail_personalisation import admin_urls, models, utils\n'), ((7686, 7745), 'django.urls.reverse', 'reverse', (['"""wagtail_personalisation_segment_modeladmin_index"""'], {}), "('wagtail_personalisation_segment_modeladmin_index')\n", (7693, 7745), False, 'from django.urls import reverse\n'), ((7762, 7775), 'django.utils.translation.ugettext_lazy', '_', (['"""Segments"""'], {}), "('Segments')\n", (7763, 7775), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((8182, 8204), 'django.utils.translation.ugettext_lazy', '_', (['"""Personalised Page"""'], {}), "('Personalised Page')\n", (8183, 8204), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((8608, 8620), 'django.utils.translation.ugettext_lazy', '_', (['"""Variant"""'], {}), "('Variant')\n", (8609, 8620), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((10776, 10817), 'django.utils.translation.ugettext_lazy', '_', (['"""Page \'{0}\' and its variants deleted."""'], {}), '("Page \'{0}\' and its variants deleted.")\n', (10777, 10817), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((10949, 10985), 'wagtail.core.hooks.get_hooks', 'hooks.get_hooks', (['"""after_delete_page"""'], {}), "('after_delete_page')\n", (10964, 10985), False, 'from wagtail.core import hooks\n'), ((11178, 11221), 'django.shortcuts.redirect', 'redirect', (['"""wagtailadmin_explore"""', 'parent_id'], {}), "('wagtailadmin_explore', parent_id)\n", (11186, 11221), False, 'from django.shortcuts import redirect, render\n'), ((1125, 1181), 'django.conf.urls.include', 'include', (['admin_urls'], {'namespace': '"""wagtail_personalisation"""'}), "(admin_urls, namespace='wagtail_personalisation')\n", (1132, 1181), False, 'from django.conf.urls import include, url\n'), ((5971, 5996), 'django.utils.translation.ugettext_lazy', '_', (['"""Create a new segment"""'], {}), "('Create a new segment')\n", (5972, 5996), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((6015, 6075), 'django.urls.reverse', 'reverse', (['"""wagtail_personalisation_segment_modeladmin_create"""'], {}), "('wagtail_personalisation_segment_modeladmin_create')\n", (6022, 6075), False, 'from django.urls import reverse\n'), ((9861, 9881), 'django.db.transaction.atomic', 'transaction.atomic', ([], {}), '()\n', (9879, 9881), False, 'from django.db import transaction\n'), ((11144, 11162), 'django.shortcuts.redirect', 'redirect', (['next_url'], {}), '(next_url)\n', (11152, 11162), False, 'from django.shortcuts import redirect, render\n'), ((2168, 2216), 'wagtail_personalisation.models.Segment.objects.filter', 'models.Segment.objects.filter', ([], {'pk': 'forced_segment'}), '(pk=forced_segment)\n', (2197, 2216), False, 'from wagtail_personalisation import admin_urls, models, utils\n'), ((4612, 4625), 'django.utils.translation.ugettext_lazy', '_', (['"""Variants"""'], {}), "('Variants')\n", (4613, 4625), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((5406, 5462), 'django.urls.reverse', 'reverse', (['"""wagtailadmin_pages:edit"""'], {'args': '[vm.variant_id]'}), "('wagtailadmin_pages:edit', args=[vm.variant_id])\n", (5413, 5462), False, 'from django.urls import reverse\n'), ((5741, 5797), 'django.urls.reverse', 'reverse', (['"""segment:copy_page"""'], {'args': '[page.pk, segment.pk]'}), "('segment:copy_page', args=[page.pk, segment.pk])\n", (5748, 5797), False, 'from django.urls import reverse\n'), ((6825, 6878), 'wagtail.core.models.Page.objects.descendant_of', 'Page.objects.descendant_of', (['root_page'], {'inclusive': '(True)'}), '(root_page, inclusive=True)\n', (6851, 6878), False, 'from wagtail.core.models import Page\n'), ((8087, 8157), 'wagtail_personalisation.models.PersonalisablePageMetadata.objects.filter', 'models.PersonalisablePageMetadata.objects.filter', ([], {'segment__isnull': '(True)'}), '(segment__isnull=True)\n', (8135, 8157), False, 'from wagtail_personalisation import admin_urls, models, utils\n'), ((8362, 8383), 'django.template.defaultfilters.pluralize', 'pluralize', (['page_count'], {}), '(page_count)\n', (8371, 8383), False, 'from django.template.defaultfilters import pluralize\n'), ((8499, 8570), 'wagtail_personalisation.models.PersonalisablePageMetadata.objects.filter', 'models.PersonalisablePageMetadata.objects.filter', ([], {'segment__isnull': '(False)'}), '(segment__isnull=False)\n', (8547, 8570), False, 'from wagtail_personalisation import admin_urls, models, utils\n'), ((8791, 8812), 'django.template.defaultfilters.pluralize', 'pluralize', (['page_count'], {}), '(page_count)\n', (8800, 8812), False, 'from django.template.defaultfilters import pluralize\n'), ((6110, 6135), 'django.utils.translation.ugettext_lazy', '_', (['"""Create a new segment"""'], {}), "('Create a new segment')\n", (6111, 6135), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4829, 4858), 'django.utils.translation.ugettext_lazy', '_', (['"""Create or edit a variant"""'], {}), "('Create or edit a variant')\n", (4830, 4858), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((5501, 5523), 'django.utils.translation.ugettext_lazy', '_', (['"""Edit this variant"""'], {}), "('Edit this variant')\n", (5502, 5523), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((5836, 5860), 'django.utils.translation.ugettext_lazy', '_', (['"""Create this variant"""'], {}), "('Create this variant')\n", (5837, 5860), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((10379, 10398), 'django.db.models.F', 'F', (['"""canonical_page"""'], {}), "('canonical_page')\n", (10380, 10398), False, 'from django.db.models import F\n')] |
import datetime
import os
import textwrap
from unittest import mock
import pytest
from stograde.common import chdir
from stograde.toolkit.config import Config
_dir = os.path.dirname(os.path.realpath(__file__))
def test_setup(tmpdir):
with tmpdir.as_cwd():
assert not os.path.exists('stograde.ini')
with mock.patch('stograde.toolkit.config.Config._filename', 'stograde.ini'):
Config()
assert os.path.exists('stograde.ini')
@pytest.mark.datafiles(os.path.join(_dir, 'fixtures', 'config'))
def test_get_last_update_check(datafiles):
with chdir(str(datafiles)):
with mock.patch('stograde.toolkit.config.Config._filename', 'stograde.ini'):
c = Config()
assert c.get_last_update_check() == datetime.datetime(2020, 8, 30, 11, 59, 39, 378987)
@pytest.mark.datafiles(os.path.join(_dir, 'fixtures', 'config'))
def test_set_last_update_check(datafiles):
with chdir(str(datafiles)):
with open('stograde.ini') as file:
old_contents = file.read()
file.close()
with mock.patch('stograde.toolkit.config.Config._filename', 'stograde.ini'):
Config().set_last_update_check()
with open('stograde.ini') as file:
new_contents = file.read()
file.close()
assert old_contents != new_contents
@pytest.mark.datafiles(os.path.join(_dir, 'fixtures', 'config'))
def test_needs_update_check(datafiles):
with chdir(str(datafiles)):
with mock.patch('stograde.toolkit.config.Config._filename', 'stograde.ini'):
c = Config()
assert c.needs_update_check()
c.set_last_update_check()
assert not c.needs_update_check()
| [
"datetime.datetime",
"os.path.exists",
"stograde.toolkit.config.Config",
"os.path.join",
"os.path.realpath",
"unittest.mock.patch"
] | [((185, 211), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (201, 211), False, 'import os\n'), ((492, 532), 'os.path.join', 'os.path.join', (['_dir', '"""fixtures"""', '"""config"""'], {}), "(_dir, 'fixtures', 'config')\n", (504, 532), False, 'import os\n'), ((843, 883), 'os.path.join', 'os.path.join', (['_dir', '"""fixtures"""', '"""config"""'], {}), "(_dir, 'fixtures', 'config')\n", (855, 883), False, 'import os\n'), ((1374, 1414), 'os.path.join', 'os.path.join', (['_dir', '"""fixtures"""', '"""config"""'], {}), "(_dir, 'fixtures', 'config')\n", (1386, 1414), False, 'import os\n'), ((436, 466), 'os.path.exists', 'os.path.exists', (['"""stograde.ini"""'], {}), "('stograde.ini')\n", (450, 466), False, 'import os\n'), ((284, 314), 'os.path.exists', 'os.path.exists', (['"""stograde.ini"""'], {}), "('stograde.ini')\n", (298, 314), False, 'import os\n'), ((328, 398), 'unittest.mock.patch', 'mock.patch', (['"""stograde.toolkit.config.Config._filename"""', '"""stograde.ini"""'], {}), "('stograde.toolkit.config.Config._filename', 'stograde.ini')\n", (338, 398), False, 'from unittest import mock\n'), ((412, 420), 'stograde.toolkit.config.Config', 'Config', ([], {}), '()\n', (418, 420), False, 'from stograde.toolkit.config import Config\n'), ((622, 692), 'unittest.mock.patch', 'mock.patch', (['"""stograde.toolkit.config.Config._filename"""', '"""stograde.ini"""'], {}), "('stograde.toolkit.config.Config._filename', 'stograde.ini')\n", (632, 692), False, 'from unittest import mock\n'), ((710, 718), 'stograde.toolkit.config.Config', 'Config', ([], {}), '()\n', (716, 718), False, 'from stograde.toolkit.config import Config\n'), ((1080, 1150), 'unittest.mock.patch', 'mock.patch', (['"""stograde.toolkit.config.Config._filename"""', '"""stograde.ini"""'], {}), "('stograde.toolkit.config.Config._filename', 'stograde.ini')\n", (1090, 1150), False, 'from unittest import mock\n'), ((1501, 1571), 'unittest.mock.patch', 'mock.patch', (['"""stograde.toolkit.config.Config._filename"""', '"""stograde.ini"""'], {}), "('stograde.toolkit.config.Config._filename', 'stograde.ini')\n", (1511, 1571), False, 'from unittest import mock\n'), ((1589, 1597), 'stograde.toolkit.config.Config', 'Config', ([], {}), '()\n', (1595, 1597), False, 'from stograde.toolkit.config import Config\n'), ((767, 817), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(8)', '(30)', '(11)', '(59)', '(39)', '(378987)'], {}), '(2020, 8, 30, 11, 59, 39, 378987)\n', (784, 817), False, 'import datetime\n'), ((1164, 1172), 'stograde.toolkit.config.Config', 'Config', ([], {}), '()\n', (1170, 1172), False, 'from stograde.toolkit.config import Config\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 22 11:21:01 2017
@author: Zlatko
"""
from pyEPR import *
if 0:
# Specify the HFSS project to be analyzed
project_info = ProjectInfo(r"X:\Simulation\\hfss\\KC\\")
project_info.project_name = '2013-12-03_9GHzCavity' # Name of the project file (string). "None" will get the current active one.
project_info.design_name = '9GHz_EM_center_SNAIL' # Name of the desgin file (string). "None" will get the current active one.
project_info.setup_name = None # Name of the setup(string). "None" will get the current active one.
## Describe the junctions in the HFSS desgin
project_info.junctions['snail'] = {'rect':'qubit', 'line': 'JunctionLine', 'Lj_variable':'LJ', 'length':0.0001}
# project_info.junctions['jBob'] = {'rect':'qubitBob', 'line': 'bob_line', 'Lj_variable':'LJBob', 'length':0.0001}
# Dissipative elments EPR
project_info.dissipative['dielectric_surfaces'] = None # supply names here, there are more options in project_info.dissipative.
# Run analysis
epr_hfss = DistributedAnalysis(project_info)
epr_hfss.do_EPR_analysis() #variations = ['1', '70']
if 1: # Hamiltonian analysis
# filename = epr_hfss.data_filename
filename = r'X:\Simulation\hfss\KC\pyEPR_results_2018\2013-12-03_9GHzCavity\9GHz_EM_center_SNAIL\9GHz_EM_center_SNAIL_20180726_170049.hdf5'
#filename = r'C:\\Users\\rslqulab\\Desktop\\zkm\\2017_pyEPR_data\\\\/2017_08_Zlatko_Shyam_AutStab/2 pyEPR/2 pyEPR_20170825_170550.hdf5'
epr = QuantumAnalysis(filename)
#result = epr.analyze_variation('1', cos_trunc = 8, fock_trunc = 7)
epr.analyze_all_variations(cos_trunc = None, fock_trunc = 4) # only quadratic part
epr.plot_hamiltonian_results()
if 1:
from pyEPR.toolbox_plotting import cmap_discrete
f0 = epr.results.get_frequencies_HFSS()
f1 = epr.results.get_frequencies_O1()
chi = epr.results.get_chi_O1()
mode_idx = list(f0.index)
nmodes = len(mode_idx)
cmap = cmap_discrete(nmodes)
| [
"pyEPR.toolbox_plotting.cmap_discrete"
] | [((2072, 2093), 'pyEPR.toolbox_plotting.cmap_discrete', 'cmap_discrete', (['nmodes'], {}), '(nmodes)\n', (2085, 2093), False, 'from pyEPR.toolbox_plotting import cmap_discrete\n')] |
# -*- coding: utf-8 -*-
# File: dorefa.py
# Author: <NAME>
import tensorflow as tf
from tensorpack.utils.argtools import graph_memoized
@graph_memoized
def get_dorefa(bitW, bitA, bitG):
"""
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively
It's unsafe to call this function multiple times with different parameters
"""
def quantize(x, k):
n = float(2 ** k - 1)
@tf.custom_gradient
def _quantize(x):
return tf.round(x * n) / n, lambda dy: dy
return _quantize(x)
def fw(x):
if bitW == 32:
return x
if bitW == 1: # BWN
E = tf.stop_gradient(tf.reduce_mean(tf.abs(x)))
@tf.custom_gradient
def _sign(x):
return tf.where(tf.equal(x, 0), tf.ones_like(x), tf.sign(x / E)) * E, lambda dy: dy
return _sign(x)
x = tf.tanh(x)
x = x / tf.reduce_max(tf.abs(x)) * 0.5 + 0.5
return 2 * quantize(x, bitW) - 1
def fa(x):
if bitA == 32:
return x
return quantize(x, bitA)
def fg(x):
if bitG == 32:
return x
@tf.custom_gradient
def _identity(input):
def grad_fg(x):
rank = x.get_shape().ndims
assert rank is not None
maxx = tf.reduce_max(tf.abs(x), list(range(1, rank)), keep_dims=True)
x = x / maxx
n = float(2**bitG - 1)
x = x * 0.5 + 0.5 + tf.random_uniform(
tf.shape(x), minval=-0.5 / n, maxval=0.5 / n)
x = tf.clip_by_value(x, 0.0, 1.0)
x = quantize(x, bitG) - 0.5
return x * maxx * 2
return input, grad_fg
return _identity(x)
return fw, fa, fg
def ternarize(x, thresh=0.05):
"""
Implemented Trained Ternary Quantization:
https://arxiv.org/abs/1612.01064
Code modified from the authors' at:
https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py
"""
shape = x.get_shape()
thre_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)) * thresh)
w_p = tf.get_variable('Wp', initializer=1.0, dtype=tf.float32)
w_n = tf.get_variable('Wn', initializer=1.0, dtype=tf.float32)
tf.summary.scalar(w_p.op.name + '-summary', w_p)
tf.summary.scalar(w_n.op.name + '-summary', w_n)
mask = tf.ones(shape)
mask_p = tf.where(x > thre_x, tf.ones(shape) * w_p, mask)
mask_np = tf.where(x < -thre_x, tf.ones(shape) * w_n, mask_p)
mask_z = tf.where((x < thre_x) & (x > - thre_x), tf.zeros(shape), mask)
@tf.custom_gradient
def _sign_mask(x):
return tf.sign(x) * mask_z, lambda dy: dy
w = _sign_mask(x)
w = w * mask_np
tf.summary.histogram(w.name, w)
return w
| [
"tensorflow.round",
"tensorflow.equal",
"tensorflow.shape",
"tensorflow.get_variable",
"tensorflow.ones",
"tensorflow.tanh",
"tensorflow.sign",
"tensorflow.summary.histogram",
"tensorflow.clip_by_value",
"tensorflow.ones_like",
"tensorflow.summary.scalar",
"tensorflow.zeros",
"tensorflow.abs... | [((2217, 2273), 'tensorflow.get_variable', 'tf.get_variable', (['"""Wp"""'], {'initializer': '(1.0)', 'dtype': 'tf.float32'}), "('Wp', initializer=1.0, dtype=tf.float32)\n", (2232, 2273), True, 'import tensorflow as tf\n'), ((2284, 2340), 'tensorflow.get_variable', 'tf.get_variable', (['"""Wn"""'], {'initializer': '(1.0)', 'dtype': 'tf.float32'}), "('Wn', initializer=1.0, dtype=tf.float32)\n", (2299, 2340), True, 'import tensorflow as tf\n'), ((2346, 2394), 'tensorflow.summary.scalar', 'tf.summary.scalar', (["(w_p.op.name + '-summary')", 'w_p'], {}), "(w_p.op.name + '-summary', w_p)\n", (2363, 2394), True, 'import tensorflow as tf\n'), ((2399, 2447), 'tensorflow.summary.scalar', 'tf.summary.scalar', (["(w_n.op.name + '-summary')", 'w_n'], {}), "(w_n.op.name + '-summary', w_n)\n", (2416, 2447), True, 'import tensorflow as tf\n'), ((2460, 2474), 'tensorflow.ones', 'tf.ones', (['shape'], {}), '(shape)\n', (2467, 2474), True, 'import tensorflow as tf\n'), ((2826, 2857), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['w.name', 'w'], {}), '(w.name, w)\n', (2846, 2857), True, 'import tensorflow as tf\n'), ((937, 947), 'tensorflow.tanh', 'tf.tanh', (['x'], {}), '(x)\n', (944, 947), True, 'import tensorflow as tf\n'), ((2656, 2671), 'tensorflow.zeros', 'tf.zeros', (['shape'], {}), '(shape)\n', (2664, 2671), True, 'import tensorflow as tf\n'), ((2509, 2523), 'tensorflow.ones', 'tf.ones', (['shape'], {}), '(shape)\n', (2516, 2523), True, 'import tensorflow as tf\n'), ((2573, 2587), 'tensorflow.ones', 'tf.ones', (['shape'], {}), '(shape)\n', (2580, 2587), True, 'import tensorflow as tf\n'), ((1660, 1689), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['x', '(0.0)', '(1.0)'], {}), '(x, 0.0, 1.0)\n', (1676, 1689), True, 'import tensorflow as tf\n'), ((2185, 2194), 'tensorflow.abs', 'tf.abs', (['x'], {}), '(x)\n', (2191, 2194), True, 'import tensorflow as tf\n'), ((2742, 2752), 'tensorflow.sign', 'tf.sign', (['x'], {}), '(x)\n', (2749, 2752), True, 'import tensorflow as tf\n'), ((521, 536), 'tensorflow.round', 'tf.round', (['(x * n)'], {}), '(x * n)\n', (529, 536), True, 'import tensorflow as tf\n'), ((724, 733), 'tensorflow.abs', 'tf.abs', (['x'], {}), '(x)\n', (730, 733), True, 'import tensorflow as tf\n'), ((1402, 1411), 'tensorflow.abs', 'tf.abs', (['x'], {}), '(x)\n', (1408, 1411), True, 'import tensorflow as tf\n'), ((978, 987), 'tensorflow.abs', 'tf.abs', (['x'], {}), '(x)\n', (984, 987), True, 'import tensorflow as tf\n'), ((1594, 1605), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (1602, 1605), True, 'import tensorflow as tf\n'), ((827, 841), 'tensorflow.equal', 'tf.equal', (['x', '(0)'], {}), '(x, 0)\n', (835, 841), True, 'import tensorflow as tf\n'), ((843, 858), 'tensorflow.ones_like', 'tf.ones_like', (['x'], {}), '(x)\n', (855, 858), True, 'import tensorflow as tf\n'), ((860, 874), 'tensorflow.sign', 'tf.sign', (['(x / E)'], {}), '(x / E)\n', (867, 874), True, 'import tensorflow as tf\n')] |
from unittest import TestCase
from icon_storage.util.cache_help import CacheHelp
from icon_storage.actions.store import Store
from icon_storage.actions.check_for_variable import CheckForVariable
class TestStoreAction(TestCase):
def test_store(self):
store = Store()
var_check = CheckForVariable()
params = {
"variable_name": "foobar",
"variable_value": "barfoo"
}
store.run(params)
actual = var_check.run(params)
expected = {'variable_found': True}
self.assertEqual(expected, actual)
cache_help = CacheHelp()
cache_help.delete_variable("foobar")
expected = {'variable_found': False}
actual = var_check.run(params)
self.assertEqual(expected, actual)
| [
"icon_storage.util.cache_help.CacheHelp",
"icon_storage.actions.check_for_variable.CheckForVariable",
"icon_storage.actions.store.Store"
] | [((272, 279), 'icon_storage.actions.store.Store', 'Store', ([], {}), '()\n', (277, 279), False, 'from icon_storage.actions.store import Store\n'), ((300, 318), 'icon_storage.actions.check_for_variable.CheckForVariable', 'CheckForVariable', ([], {}), '()\n', (316, 318), False, 'from icon_storage.actions.check_for_variable import CheckForVariable\n'), ((601, 612), 'icon_storage.util.cache_help.CacheHelp', 'CacheHelp', ([], {}), '()\n', (610, 612), False, 'from icon_storage.util.cache_help import CacheHelp\n')] |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of multiheaded FAVOR-attention & FAVOR-self-attention layers.
Prefix Sum Tensorflow implementation by <NAME>.
"""
import math
import tensorflow as tf
from performer.fast_attention.tensorflow import util
BIG_CONSTANT = 1e8
def create_projection_matrix(m, d, seed=0, scaling=0):
r"""Constructs the matrix of random projections.
Constructs a matrix of random orthogonal projections. Each projection vector
has direction chosen uniformly at random and either deterministic length
\sqrt{d} or length taken from the \chi(d) distribution (in the latter case
marginal distributions of the projections are d-dimensional Gaussian vectors
with associated identity covariance matrix).
Args:
m: number of random projections.
d: dimensionality of each random projection.
seed: random seed used to construct projections.
scaling: 1 if all the random projections need to be renormalized to have
length \sqrt{d}, 0 if the lengths of random projections should follow
\chi(d) distribution.
Returns:
The matrix of random projections of the shape [m, d].
"""
nb_full_blocks = int(m / d)
block_list = []
current_seed = seed
for _ in range(nb_full_blocks):
unstructured_block = tf.random.normal((d, d), seed=current_seed)
q, _ = tf.linalg.qr(unstructured_block)
q = tf.transpose(q)
block_list.append(q)
current_seed += 1
remaining_rows = m - nb_full_blocks * d
if remaining_rows > 0:
unstructured_block = tf.random.normal((d, d), seed=current_seed)
q, _ = tf.linalg.qr(unstructured_block)
q = tf.transpose(q)
block_list.append(q[0:remaining_rows])
final_matrix = tf.experimental.numpy.vstack(block_list)
current_seed += 1
if scaling == 0:
multiplier = tf.norm(tf.random.normal((m, d), seed=current_seed), axis=1)
elif scaling == 1:
multiplier = tf.math.sqrt(float(d)) * tf.ones((m))
else:
raise ValueError("Scaling must be one of {0, 1}. Was %s" % scaling)
return tf.linalg.matmul(tf.linalg.diag(multiplier), final_matrix)
def relu_kernel_transformation(data,
is_query,
projection_matrix=None,
numerical_stabilizer=0.001):
"""Computes features for the ReLU-kernel.
Computes random features for the ReLU kernel from
https://arxiv.org/pdf/2009.14794.pdf.
Args:
data: input data tensor of the shape [B, L, H, D], where: B - batch
dimension, L - attention dimensions, H - heads, D - features.
is_query: indicates whether input data is a query oor key tensor.
projection_matrix: random Gaussian matrix of shape [M, D], where M stands
for the number of random features and each D x D sub-block has pairwise
orthogonal rows.
numerical_stabilizer: small positive constant for numerical stability.
Returns:
Corresponding kernel feature map.
"""
del is_query
if projection_matrix is None:
return tf.nn.relu(data) + numerical_stabilizer
else:
ratio = 1.0 / tf.math.sqrt(
tf.dtypes.cast(projection_matrix.shape[0], tf.float32))
data_dash = ratio * tf.einsum("blhd,md->blhm", data, projection_matrix)
return tf.nn.relu(data_dash) + numerical_stabilizer
def softmax_kernel_transformation(data,
is_query,
projection_matrix=None,
numerical_stabilizer=0.000001):
"""Computes random features for the softmax kernel using FAVOR+ mechanism.
Computes random features for the softmax kernel using FAVOR+ mechanism from
https://arxiv.org/pdf/2009.14794.pdf.
Args:
data: input data tensor of the shape [B, L, H, D], where: B - batch
dimension, L - attention dimensions, H - heads, D - features.
is_query: indicates whether input data is a query oor key tensor.
projection_matrix: random Gaussian matrix of shape [M, D], where M stands
for the number of random features and each D x D sub-block has pairwise
orthogonal rows.
numerical_stabilizer: small positive constant for numerical stability.
Returns:
Corresponding kernel feature map.
"""
data_normalizer = 1.0 / (
tf.math.sqrt(tf.math.sqrt(tf.dtypes.cast(data.shape[-1], tf.float32))))
ratio = 1.0 / tf.math.sqrt(
tf.dtypes.cast(projection_matrix.shape[0], tf.float32))
data_dash = tf.einsum("blhd,md->blhm", data, projection_matrix)
diag_data = tf.math.square(data)
diag_data = tf.math.reduce_sum(
diag_data, axis=tf.keras.backend.ndim(data) - 1)
diag_data = (diag_data / 2.0) * data_normalizer * data_normalizer
diag_data = tf.expand_dims(diag_data, axis=tf.keras.backend.ndim(data) - 1)
if is_query:
last_dims_t = (len(data_dash.shape) - 1,)
data_dash = ratio * (
tf.math.exp(data_dash - diag_data - tf.math.reduce_max(
data_dash, axis=last_dims_t, keepdims=True)) + numerical_stabilizer)
else:
data_dash = ratio * (
tf.math.exp(data_dash - diag_data - tf.math.reduce_max(data_dash)) +
numerical_stabilizer)
return data_dash
def noncausal_numerator(qs, ks, vs):
"""Computes not-normalized FAVOR noncausal attention AV.
Args:
qs: query_prime tensor of the shape [L,B,H,M].
ks: key_prime tensor of the shape [L,B,H,M].
vs: value tensor of the shape [L,B,H,D].
Returns:
Not-normalized FAVOR noncausal attention AV.
"""
kvs = tf.einsum("lbhm,lbhd->bhmd", ks, vs)
return tf.einsum("lbhm,bhmd->lbhd", qs, kvs)
def noncausal_denominator(qs, ks):
"""Computes FAVOR normalizer in noncausal attention.
Args:
qs: query_prime tensor of the shape [L,B,H,M].
ks: key_prime tensor of the shape [L,B,H,M].
Returns:
FAVOR normalizer in noncausal attention.
"""
all_ones = tf.ones([ks.shape[0]])
ks_sum = tf.einsum("lbhm,l->bhm", ks, all_ones)
return tf.einsum("lbhm,bhm->lbh", qs, ks_sum)
@tf.custom_gradient
def causal_numerator(qs, ks, vs):
"""Computes not-normalized FAVOR causal attention A_{masked}V.
Args:
qs: query_prime tensor of the shape [L,B,H,M].
ks: key_prime tensor of the shape [L,B,H,M].
vs: value tensor of the shape [L,B,H,D].
Returns:
Not-normalized FAVOR causal attention A_{masked}V.
"""
result = []
sums = tf.zeros_like(tf.einsum("ijk,ijl->ijkl", ks[0], vs[0]))
for index in range(qs.shape[0]):
sums = sums + tf.einsum("ijk,ijl->ijkl", ks[index], vs[index])
result.append(tf.einsum("ijkl,ijk->ijl", sums, qs[index])[None, Ellipsis])
result = tf.concat(result, axis=0)
def grad(res_grad):
grads = tf.zeros_like(tf.einsum("ijk,ijl->ijkl", ks[0], vs[0]))
gr_sums = sums
q_grads = []
k_grads = []
v_grads = []
for index in range(qs.shape[0] - 1, -1, -1):
q_grads.append(
tf.einsum("ijkl,ijl->ijk", gr_sums, res_grad[index])[None, Ellipsis])
grads = grads + tf.einsum("ijk,ijl->ijkl", qs[index], res_grad[index])
k_grads.append(tf.einsum("ijkl,ijl->ijk", grads, vs[index])[None, Ellipsis])
v_grads.append(tf.einsum("ijkl,ijk->ijl", grads, ks[index])[None, Ellipsis])
gr_sums = gr_sums - tf.einsum("ijk,ijl->ijkl", ks[index], vs[index])
q_grads = tf.concat(q_grads[::-1], axis=0)
k_grads = tf.concat(k_grads[::-1], axis=0)
v_grads = tf.concat(v_grads[::-1], axis=0)
return q_grads, k_grads, v_grads
return result, grad
@tf.custom_gradient
def causal_denominator(qs, ks):
"""Computes FAVOR normalizer in causal attention.
Args:
qs: query_prime tensor of the shape [L,B,H,M].
ks: key_prime tensor of the shape [L,B,H,M].
Returns:
FAVOR normalizer in causal attention.
"""
result = []
sums = tf.zeros_like(ks[0])
for index in range(qs.shape[0]):
sums = sums + ks[index]
result.append(tf.reduce_sum(qs[index] * sums, axis=2)[None, Ellipsis])
result = tf.concat(result, axis=0)
def grad(res_grad):
k_grad = tf.zeros_like(ks[0])
gr_sums = sums
q_grads = []
k_grads = []
for index in range(qs.shape[0] - 1, -1, -1):
q_grads.append(
tf.einsum("ijk,ij->ijk", gr_sums, res_grad[index])[None, Ellipsis])
k_grad = k_grad + tf.einsum("ijk,ij->ijk", qs[index], res_grad[index])
k_grads.append(k_grad[None, Ellipsis])
gr_sums = gr_sums - ks[index]
q_grads = tf.concat(q_grads[::-1], axis=0)
k_grads = tf.concat(k_grads[::-1], axis=0)
return q_grads, k_grads
return result, grad
def favor_attention(query,
key,
value,
kernel_transformation,
causal,
projection_matrix=None):
"""Computes FAVOR normalized attention.
Args:
query: query tensor.
key: key tensor.
value: value tensor.
kernel_transformation: transformation used to get finite kernel features.
causal: whether attention is causal or not.
projection_matrix: projection matrix to be used.
Returns:
FAVOR normalized attention.
"""
query_prime = kernel_transformation(query, True,
projection_matrix) # [B,L,H,M]
key_prime = kernel_transformation(key, False, projection_matrix) # [B,L,H,M]
query_prime = tf.transpose(query_prime, [1, 0, 2, 3]) # [L,B,H,M]
key_prime = tf.transpose(key_prime, [1, 0, 2, 3]) # [L,B,H,M]
value = tf.transpose(value, [1, 0, 2, 3]) # [L,B,H,D]
if causal:
av_attention = causal_numerator(query_prime, key_prime, value)
attention_normalizer = causal_denominator(query_prime, key_prime)
else:
av_attention = noncausal_numerator(query_prime, key_prime, value)
attention_normalizer = noncausal_denominator(query_prime, key_prime)
# TODO(kchoro): Add more comments.
av_attention = tf.transpose(av_attention, [1, 0, 2, 3])
attention_normalizer = tf.transpose(attention_normalizer, [1, 0, 2])
attention_normalizer = tf.expand_dims(attention_normalizer,
len(attention_normalizer.shape))
return av_attention / attention_normalizer
class Attention(tf.keras.layers.Layer):
"""Multi-headed attention layer."""
def __init__(self,
hidden_size,
num_heads,
attention_dropout,
kernel_transformation=relu_kernel_transformation,
numerical_stabilizer=0.001,
causal=False,
projection_matrix_type=None,
nb_random_features=0):
"""Initialize Attention.
Args:
hidden_size: int, output dim of hidden layer.
num_heads: int, number of heads to repeat the same attention structure.
attention_dropout: float, dropout rate inside attention for training.
kernel_transformation: transformation used to produce kernel features for
attention.
numerical_stabilizer: used to bound away from zero kernel values.
causal: whether attention is causal or not.
projection_matrix_type: None if Identity should be used, otherwise random
projection matrix will be applied.
nb_random_features: number of random features to be used (relevant only if
projection_matrix is not None).
"""
if hidden_size % num_heads:
raise ValueError(
"Hidden size ({}) must be divisible by the number of heads ({})."
.format(hidden_size, num_heads))
super(Attention, self).__init__()
self.hidden_size = hidden_size
self.num_heads = num_heads
self.attention_dropout = attention_dropout
self.kernel_transformation = kernel_transformation
self.numerical_stabilizer = numerical_stabilizer
self.causal = causal
self.projection_matrix_type = projection_matrix_type
self.nb_random_features = nb_random_features
def build(self, input_shape):
"""Builds the layer."""
# Layers for linearly projecting the queries, keys, and values.
size_per_head = self.hidden_size // self.num_heads
def _glorot_initializer(fan_in, fan_out):
limit = math.sqrt(6.0 / (fan_in + fan_out))
return tf.keras.initializers.RandomUniform(minval=-limit, maxval=limit)
attention_initializer = _glorot_initializer(input_shape.as_list()[-1],
self.hidden_size)
self.query_dense_layer = util.DenseEinsum(
output_shape=(self.num_heads, size_per_head),
kernel_initializer=attention_initializer,
use_bias=False,
name="query")
self.key_dense_layer = util.DenseEinsum(
output_shape=(self.num_heads, size_per_head),
kernel_initializer=attention_initializer,
use_bias=False,
name="key")
self.value_dense_layer = util.DenseEinsum(
output_shape=(self.num_heads, size_per_head),
kernel_initializer=attention_initializer,
use_bias=False,
name="value")
output_initializer = _glorot_initializer(self.hidden_size, self.hidden_size)
self.output_dense_layer = util.DenseEinsum(
output_shape=self.hidden_size,
num_summed_dimensions=2,
kernel_initializer=output_initializer,
use_bias=False,
name="output_transform")
super(Attention, self).build(input_shape)
def get_config(self):
return {
"hidden_size": self.hidden_size,
"num_heads": self.num_heads,
"attention_dropout": self.attention_dropout,
}
def call(self,
query_input,
source_input,
bias,
training,
cache=None,
decode_loop_step=None):
"""Apply attention mechanism to query_input and source_input.
Args:
query_input: A tensor with shape [batch_size, length_query, hidden_size].
source_input: A tensor with shape [batch_size, length_source,
hidden_size].
bias: A tensor with shape [batch_size, 1, length_query, length_source],
the attention bias that will be added to the result of the dot product.
training: A bool, whether in training mode or not.
cache: (Used during prediction) A dictionary with tensors containing
results of previous attentions. The dictionary must have the items:
{"k": tensor with shape [batch_size, i, heads, dim_per_head],
"v": tensor with shape [batch_size, i, heads, dim_per_head]} where
i is the current decoded length for non-padded decode, or max
sequence length for padded decode.
decode_loop_step: An integer, step number of the decoding loop. Used only
for autoregressive inference on TPU.
Returns:
Attention layer output with shape [batch_size, length_query, hidden_size]
"""
# Linearly project the query, key and value using different learned
# projections. Splitting heads is automatically done during the linear
# projections --> [batch_size, length, num_heads, dim_per_head].
query = self.query_dense_layer(query_input)
key = self.key_dense_layer(source_input)
value = self.value_dense_layer(source_input)
if self.projection_matrix_type is None:
projection_matrix = None
else:
dim = query.shape[-1]
seed = tf.math.ceil(tf.math.abs(tf.math.reduce_sum(query) * BIG_CONSTANT))
seed = tf.dtypes.cast(seed, tf.int32)
projection_matrix = create_projection_matrix(
self.nb_random_features, dim, seed=seed)
if cache is not None:
# Combine cached keys and values with new keys and values.
if decode_loop_step is not None:
cache_k_shape = cache["k"].shape.as_list()
indices = tf.reshape(
tf.one_hot(decode_loop_step, cache_k_shape[1], dtype=key.dtype),
[1, cache_k_shape[1], 1, 1])
key = cache["k"] + key * indices
cache_v_shape = cache["v"].shape.as_list()
indices = tf.reshape(
tf.one_hot(decode_loop_step, cache_v_shape[1], dtype=value.dtype),
[1, cache_v_shape[1], 1, 1])
value = cache["v"] + value * indices
else:
key = tf.concat([tf.cast(cache["k"], key.dtype), key], axis=1)
value = tf.concat([tf.cast(cache["v"], value.dtype), value], axis=1)
# Update cache
cache["k"] = key
cache["v"] = value
attention_output = favor_attention(query, key, value,
self.kernel_transformation, self.causal,
projection_matrix)
attention_output = self.output_dense_layer(attention_output)
return attention_output
class SelfAttention(Attention):
"""Multiheaded self-attention layer."""
def call(self,
query_input,
bias,
training,
cache=None,
decode_loop_step=None):
return super(SelfAttention, self).call(query_input, query_input, bias,
training, cache, decode_loop_step)
| [
"performer.fast_attention.tensorflow.util.DenseEinsum",
"tensorflow.keras.initializers.RandomUniform",
"tensorflow.transpose",
"tensorflow.reduce_sum",
"math.sqrt",
"tensorflow.keras.backend.ndim",
"tensorflow.einsum",
"tensorflow.linalg.qr",
"tensorflow.cast",
"tensorflow.random.normal",
"tenso... | [((2273, 2313), 'tensorflow.experimental.numpy.vstack', 'tf.experimental.numpy.vstack', (['block_list'], {}), '(block_list)\n', (2301, 2313), True, 'import tensorflow as tf\n'), ((4999, 5050), 'tensorflow.einsum', 'tf.einsum', (['"""blhd,md->blhm"""', 'data', 'projection_matrix'], {}), "('blhd,md->blhm', data, projection_matrix)\n", (5008, 5050), True, 'import tensorflow as tf\n'), ((5065, 5085), 'tensorflow.math.square', 'tf.math.square', (['data'], {}), '(data)\n', (5079, 5085), True, 'import tensorflow as tf\n'), ((6041, 6077), 'tensorflow.einsum', 'tf.einsum', (['"""lbhm,lbhd->bhmd"""', 'ks', 'vs'], {}), "('lbhm,lbhd->bhmd', ks, vs)\n", (6050, 6077), True, 'import tensorflow as tf\n'), ((6087, 6124), 'tensorflow.einsum', 'tf.einsum', (['"""lbhm,bhmd->lbhd"""', 'qs', 'kvs'], {}), "('lbhm,bhmd->lbhd', qs, kvs)\n", (6096, 6124), True, 'import tensorflow as tf\n'), ((6402, 6424), 'tensorflow.ones', 'tf.ones', (['[ks.shape[0]]'], {}), '([ks.shape[0]])\n', (6409, 6424), True, 'import tensorflow as tf\n'), ((6436, 6474), 'tensorflow.einsum', 'tf.einsum', (['"""lbhm,l->bhm"""', 'ks', 'all_ones'], {}), "('lbhm,l->bhm', ks, all_ones)\n", (6445, 6474), True, 'import tensorflow as tf\n'), ((6484, 6522), 'tensorflow.einsum', 'tf.einsum', (['"""lbhm,bhm->lbh"""', 'qs', 'ks_sum'], {}), "('lbhm,bhm->lbh', qs, ks_sum)\n", (6493, 6522), True, 'import tensorflow as tf\n'), ((7145, 7170), 'tensorflow.concat', 'tf.concat', (['result'], {'axis': '(0)'}), '(result, axis=0)\n', (7154, 7170), True, 'import tensorflow as tf\n'), ((8308, 8328), 'tensorflow.zeros_like', 'tf.zeros_like', (['ks[0]'], {}), '(ks[0])\n', (8321, 8328), True, 'import tensorflow as tf\n'), ((8480, 8505), 'tensorflow.concat', 'tf.concat', (['result'], {'axis': '(0)'}), '(result, axis=0)\n', (8489, 8505), True, 'import tensorflow as tf\n'), ((9840, 9879), 'tensorflow.transpose', 'tf.transpose', (['query_prime', '[1, 0, 2, 3]'], {}), '(query_prime, [1, 0, 2, 3])\n', (9852, 9879), True, 'import tensorflow as tf\n'), ((9907, 9944), 'tensorflow.transpose', 'tf.transpose', (['key_prime', '[1, 0, 2, 3]'], {}), '(key_prime, [1, 0, 2, 3])\n', (9919, 9944), True, 'import tensorflow as tf\n'), ((9968, 10001), 'tensorflow.transpose', 'tf.transpose', (['value', '[1, 0, 2, 3]'], {}), '(value, [1, 0, 2, 3])\n', (9980, 10001), True, 'import tensorflow as tf\n'), ((10371, 10411), 'tensorflow.transpose', 'tf.transpose', (['av_attention', '[1, 0, 2, 3]'], {}), '(av_attention, [1, 0, 2, 3])\n', (10383, 10411), True, 'import tensorflow as tf\n'), ((10437, 10482), 'tensorflow.transpose', 'tf.transpose', (['attention_normalizer', '[1, 0, 2]'], {}), '(attention_normalizer, [1, 0, 2])\n', (10449, 10482), True, 'import tensorflow as tf\n'), ((1850, 1893), 'tensorflow.random.normal', 'tf.random.normal', (['(d, d)'], {'seed': 'current_seed'}), '((d, d), seed=current_seed)\n', (1866, 1893), True, 'import tensorflow as tf\n'), ((1905, 1937), 'tensorflow.linalg.qr', 'tf.linalg.qr', (['unstructured_block'], {}), '(unstructured_block)\n', (1917, 1937), True, 'import tensorflow as tf\n'), ((1946, 1961), 'tensorflow.transpose', 'tf.transpose', (['q'], {}), '(q)\n', (1958, 1961), True, 'import tensorflow as tf\n'), ((2101, 2144), 'tensorflow.random.normal', 'tf.random.normal', (['(d, d)'], {'seed': 'current_seed'}), '((d, d), seed=current_seed)\n', (2117, 2144), True, 'import tensorflow as tf\n'), ((2156, 2188), 'tensorflow.linalg.qr', 'tf.linalg.qr', (['unstructured_block'], {}), '(unstructured_block)\n', (2168, 2188), True, 'import tensorflow as tf\n'), ((2197, 2212), 'tensorflow.transpose', 'tf.transpose', (['q'], {}), '(q)\n', (2209, 2212), True, 'import tensorflow as tf\n'), ((2615, 2641), 'tensorflow.linalg.diag', 'tf.linalg.diag', (['multiplier'], {}), '(multiplier)\n', (2629, 2641), True, 'import tensorflow as tf\n'), ((6909, 6949), 'tensorflow.einsum', 'tf.einsum', (['"""ijk,ijl->ijkl"""', 'ks[0]', 'vs[0]'], {}), "('ijk,ijl->ijkl', ks[0], vs[0])\n", (6918, 6949), True, 'import tensorflow as tf\n'), ((7821, 7853), 'tensorflow.concat', 'tf.concat', (['q_grads[::-1]'], {'axis': '(0)'}), '(q_grads[::-1], axis=0)\n', (7830, 7853), True, 'import tensorflow as tf\n'), ((7868, 7900), 'tensorflow.concat', 'tf.concat', (['k_grads[::-1]'], {'axis': '(0)'}), '(k_grads[::-1], axis=0)\n', (7877, 7900), True, 'import tensorflow as tf\n'), ((7915, 7947), 'tensorflow.concat', 'tf.concat', (['v_grads[::-1]'], {'axis': '(0)'}), '(v_grads[::-1], axis=0)\n', (7924, 7947), True, 'import tensorflow as tf\n'), ((8543, 8563), 'tensorflow.zeros_like', 'tf.zeros_like', (['ks[0]'], {}), '(ks[0])\n', (8556, 8563), True, 'import tensorflow as tf\n'), ((8943, 8975), 'tensorflow.concat', 'tf.concat', (['q_grads[::-1]'], {'axis': '(0)'}), '(q_grads[::-1], axis=0)\n', (8952, 8975), True, 'import tensorflow as tf\n'), ((8990, 9022), 'tensorflow.concat', 'tf.concat', (['k_grads[::-1]'], {'axis': '(0)'}), '(k_grads[::-1], axis=0)\n', (8999, 9022), True, 'import tensorflow as tf\n'), ((12887, 13025), 'performer.fast_attention.tensorflow.util.DenseEinsum', 'util.DenseEinsum', ([], {'output_shape': '(self.num_heads, size_per_head)', 'kernel_initializer': 'attention_initializer', 'use_bias': '(False)', 'name': '"""query"""'}), "(output_shape=(self.num_heads, size_per_head),\n kernel_initializer=attention_initializer, use_bias=False, name='query')\n", (12903, 13025), False, 'from performer.fast_attention.tensorflow import util\n'), ((13082, 13218), 'performer.fast_attention.tensorflow.util.DenseEinsum', 'util.DenseEinsum', ([], {'output_shape': '(self.num_heads, size_per_head)', 'kernel_initializer': 'attention_initializer', 'use_bias': '(False)', 'name': '"""key"""'}), "(output_shape=(self.num_heads, size_per_head),\n kernel_initializer=attention_initializer, use_bias=False, name='key')\n", (13098, 13218), False, 'from performer.fast_attention.tensorflow import util\n'), ((13277, 13415), 'performer.fast_attention.tensorflow.util.DenseEinsum', 'util.DenseEinsum', ([], {'output_shape': '(self.num_heads, size_per_head)', 'kernel_initializer': 'attention_initializer', 'use_bias': '(False)', 'name': '"""value"""'}), "(output_shape=(self.num_heads, size_per_head),\n kernel_initializer=attention_initializer, use_bias=False, name='value')\n", (13293, 13415), False, 'from performer.fast_attention.tensorflow import util\n'), ((13557, 13718), 'performer.fast_attention.tensorflow.util.DenseEinsum', 'util.DenseEinsum', ([], {'output_shape': 'self.hidden_size', 'num_summed_dimensions': '(2)', 'kernel_initializer': 'output_initializer', 'use_bias': '(False)', 'name': '"""output_transform"""'}), "(output_shape=self.hidden_size, num_summed_dimensions=2,\n kernel_initializer=output_initializer, use_bias=False, name=\n 'output_transform')\n", (13573, 13718), False, 'from performer.fast_attention.tensorflow import util\n'), ((2379, 2422), 'tensorflow.random.normal', 'tf.random.normal', (['(m, d)'], {'seed': 'current_seed'}), '((m, d), seed=current_seed)\n', (2395, 2422), True, 'import tensorflow as tf\n'), ((3576, 3592), 'tensorflow.nn.relu', 'tf.nn.relu', (['data'], {}), '(data)\n', (3586, 3592), True, 'import tensorflow as tf\n'), ((3744, 3795), 'tensorflow.einsum', 'tf.einsum', (['"""blhd,md->blhm"""', 'data', 'projection_matrix'], {}), "('blhd,md->blhm', data, projection_matrix)\n", (3753, 3795), True, 'import tensorflow as tf\n'), ((3807, 3828), 'tensorflow.nn.relu', 'tf.nn.relu', (['data_dash'], {}), '(data_dash)\n', (3817, 3828), True, 'import tensorflow as tf\n'), ((4929, 4983), 'tensorflow.dtypes.cast', 'tf.dtypes.cast', (['projection_matrix.shape[0]', 'tf.float32'], {}), '(projection_matrix.shape[0], tf.float32)\n', (4943, 4983), True, 'import tensorflow as tf\n'), ((7005, 7053), 'tensorflow.einsum', 'tf.einsum', (['"""ijk,ijl->ijkl"""', 'ks[index]', 'vs[index]'], {}), "('ijk,ijl->ijkl', ks[index], vs[index])\n", (7014, 7053), True, 'import tensorflow as tf\n'), ((7221, 7261), 'tensorflow.einsum', 'tf.einsum', (['"""ijk,ijl->ijkl"""', 'ks[0]', 'vs[0]'], {}), "('ijk,ijl->ijkl', ks[0], vs[0])\n", (7230, 7261), True, 'import tensorflow as tf\n'), ((12602, 12637), 'math.sqrt', 'math.sqrt', (['(6.0 / (fan_in + fan_out))'], {}), '(6.0 / (fan_in + fan_out))\n', (12611, 12637), False, 'import math\n'), ((12651, 12715), 'tensorflow.keras.initializers.RandomUniform', 'tf.keras.initializers.RandomUniform', ([], {'minval': '(-limit)', 'maxval': 'limit'}), '(minval=-limit, maxval=limit)\n', (12686, 12715), True, 'import tensorflow as tf\n'), ((15822, 15852), 'tensorflow.dtypes.cast', 'tf.dtypes.cast', (['seed', 'tf.int32'], {}), '(seed, tf.int32)\n', (15836, 15852), True, 'import tensorflow as tf\n'), ((2495, 2505), 'tensorflow.ones', 'tf.ones', (['m'], {}), '(m)\n', (2502, 2505), True, 'import tensorflow as tf\n'), ((3664, 3718), 'tensorflow.dtypes.cast', 'tf.dtypes.cast', (['projection_matrix.shape[0]', 'tf.float32'], {}), '(projection_matrix.shape[0], tf.float32)\n', (3678, 3718), True, 'import tensorflow as tf\n'), ((4847, 4889), 'tensorflow.dtypes.cast', 'tf.dtypes.cast', (['data.shape[-1]', 'tf.float32'], {}), '(data.shape[-1], tf.float32)\n', (4861, 4889), True, 'import tensorflow as tf\n'), ((5142, 5169), 'tensorflow.keras.backend.ndim', 'tf.keras.backend.ndim', (['data'], {}), '(data)\n', (5163, 5169), True, 'import tensorflow as tf\n'), ((5288, 5315), 'tensorflow.keras.backend.ndim', 'tf.keras.backend.ndim', (['data'], {}), '(data)\n', (5309, 5315), True, 'import tensorflow as tf\n'), ((7072, 7115), 'tensorflow.einsum', 'tf.einsum', (['"""ijkl,ijk->ijl"""', 'sums', 'qs[index]'], {}), "('ijkl,ijk->ijl', sums, qs[index])\n", (7081, 7115), True, 'import tensorflow as tf\n'), ((7510, 7564), 'tensorflow.einsum', 'tf.einsum', (['"""ijk,ijl->ijkl"""', 'qs[index]', 'res_grad[index]'], {}), "('ijk,ijl->ijkl', qs[index], res_grad[index])\n", (7519, 7564), True, 'import tensorflow as tf\n'), ((7757, 7805), 'tensorflow.einsum', 'tf.einsum', (['"""ijk,ijl->ijkl"""', 'ks[index]', 'vs[index]'], {}), "('ijk,ijl->ijkl', ks[index], vs[index])\n", (7766, 7805), True, 'import tensorflow as tf\n'), ((8411, 8450), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(qs[index] * sums)'], {'axis': '(2)'}), '(qs[index] * sums, axis=2)\n', (8424, 8450), True, 'import tensorflow as tf\n'), ((8794, 8846), 'tensorflow.einsum', 'tf.einsum', (['"""ijk,ij->ijk"""', 'qs[index]', 'res_grad[index]'], {}), "('ijk,ij->ijk', qs[index], res_grad[index])\n", (8803, 8846), True, 'import tensorflow as tf\n'), ((7418, 7470), 'tensorflow.einsum', 'tf.einsum', (['"""ijkl,ijl->ijk"""', 'gr_sums', 'res_grad[index]'], {}), "('ijkl,ijl->ijk', gr_sums, res_grad[index])\n", (7427, 7470), True, 'import tensorflow as tf\n'), ((7586, 7630), 'tensorflow.einsum', 'tf.einsum', (['"""ijkl,ijl->ijk"""', 'grads', 'vs[index]'], {}), "('ijkl,ijl->ijk', grads, vs[index])\n", (7595, 7630), True, 'import tensorflow as tf\n'), ((7669, 7713), 'tensorflow.einsum', 'tf.einsum', (['"""ijkl,ijk->ijl"""', 'grads', 'ks[index]'], {}), "('ijkl,ijk->ijl', grads, ks[index])\n", (7678, 7713), True, 'import tensorflow as tf\n'), ((8702, 8752), 'tensorflow.einsum', 'tf.einsum', (['"""ijk,ij->ijk"""', 'gr_sums', 'res_grad[index]'], {}), "('ijk,ij->ijk', gr_sums, res_grad[index])\n", (8711, 8752), True, 'import tensorflow as tf\n'), ((16180, 16243), 'tensorflow.one_hot', 'tf.one_hot', (['decode_loop_step', 'cache_k_shape[1]'], {'dtype': 'key.dtype'}), '(decode_loop_step, cache_k_shape[1], dtype=key.dtype)\n', (16190, 16243), True, 'import tensorflow as tf\n'), ((16420, 16485), 'tensorflow.one_hot', 'tf.one_hot', (['decode_loop_step', 'cache_v_shape[1]'], {'dtype': 'value.dtype'}), '(decode_loop_step, cache_v_shape[1], dtype=value.dtype)\n', (16430, 16485), True, 'import tensorflow as tf\n'), ((5452, 5514), 'tensorflow.math.reduce_max', 'tf.math.reduce_max', (['data_dash'], {'axis': 'last_dims_t', 'keepdims': '(True)'}), '(data_dash, axis=last_dims_t, keepdims=True)\n', (5470, 5514), True, 'import tensorflow as tf\n'), ((5631, 5660), 'tensorflow.math.reduce_max', 'tf.math.reduce_max', (['data_dash'], {}), '(data_dash)\n', (5649, 5660), True, 'import tensorflow as tf\n'), ((15766, 15791), 'tensorflow.math.reduce_sum', 'tf.math.reduce_sum', (['query'], {}), '(query)\n', (15784, 15791), True, 'import tensorflow as tf\n'), ((16610, 16640), 'tensorflow.cast', 'tf.cast', (["cache['k']", 'key.dtype'], {}), "(cache['k'], key.dtype)\n", (16617, 16640), True, 'import tensorflow as tf\n'), ((16683, 16715), 'tensorflow.cast', 'tf.cast', (["cache['v']", 'value.dtype'], {}), "(cache['v'], value.dtype)\n", (16690, 16715), True, 'import tensorflow as tf\n')] |
import argparse
import requests
from bs4 import BeautifulSoup
import pandas as pd
def getAllCryptos():
elementList = []
response = requests.get('https://coinmarketcap.com/coins/')
soup = BeautifulSoup(response.text, "html.parser")
table = soup.findAll('table')[2]
index = 0
for row in table.findAll("tr"):
if (index > 0):
columns = row.findAll("td")
cryptoUrl = columns[1].find('a')['href'].split('/')[2]
elementList.append(cryptoUrl)
index += 1
return elementList
def getExchangePrices(crypto) :
elementList = []
url = "https://coinmarketcap.com/currencies/{crypto}/markets/".format(crypto=crypto)
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
table = soup.findAll('table')[2]
index = 0
for row in table.findAll("tr"):
if (index > 0):
columns = row.findAll("td")
if (columns[2].find(text=True).endswith("/USD".format(crypto=crypto))):
exchange = columns[1].find('a')['title']
price=float(columns[4].find(text=True).split("$")[1].replace(',',''))
element=[exchange,price]
elementList.append(element)
index += 1
return elementList
def main():
availableCryptos = getAllCryptos()
parser = argparse.ArgumentParser()
parser.add_argument('--filter', type=str, nargs='*', help="USAGE: --filter " + " ".join(availableCryptos))
args=parser.parse_args()
cryptoList = []
if args.filter:
if (len(args.filter) <= 8):
for crypto in args.filter:
if (crypto in availableCryptos):
cryptoList.append(crypto)
else:
print("Not found: " + crypto)
else:
raise argparse.ArgumentTypeError("Too many arguments, max 8")
else:
cryptoList = ['bitcoin', 'ethereum', 'dash', 'litecoin', 'bitcoin-cash']
print('Scrapping...')
df = pd.DataFrame()
for crypto in cryptoList:
elements = getExchangePrices(crypto)
auxDf = pd.DataFrame(elements, columns=["exchange", crypto+"-USD"])
if (df.empty):
df = auxDf
else:
df = pd.merge(left=df, right=auxDf, on="exchange", how="outer")
df.to_csv(r'csv/dataframe.csv', index=False, header=True)
print('Done!')
if __name__ == "__main__":
main()
| [
"argparse.ArgumentParser",
"pandas.merge",
"argparse.ArgumentTypeError",
"requests.get",
"bs4.BeautifulSoup",
"pandas.DataFrame"
] | [((141, 189), 'requests.get', 'requests.get', (['"""https://coinmarketcap.com/coins/"""'], {}), "('https://coinmarketcap.com/coins/')\n", (153, 189), False, 'import requests\n'), ((201, 244), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.text', '"""html.parser"""'], {}), "(response.text, 'html.parser')\n", (214, 244), False, 'from bs4 import BeautifulSoup\n'), ((712, 729), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (724, 729), False, 'import requests\n'), ((741, 784), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.text', '"""html.parser"""'], {}), "(response.text, 'html.parser')\n", (754, 784), False, 'from bs4 import BeautifulSoup\n'), ((1358, 1383), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1381, 1383), False, 'import argparse\n'), ((2023, 2037), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2035, 2037), True, 'import pandas as pd\n'), ((2129, 2190), 'pandas.DataFrame', 'pd.DataFrame', (['elements'], {'columns': "['exchange', crypto + '-USD']"}), "(elements, columns=['exchange', crypto + '-USD'])\n", (2141, 2190), True, 'import pandas as pd\n'), ((1839, 1894), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['"""Too many arguments, max 8"""'], {}), "('Too many arguments, max 8')\n", (1865, 1894), False, 'import argparse\n'), ((2266, 2324), 'pandas.merge', 'pd.merge', ([], {'left': 'df', 'right': 'auxDf', 'on': '"""exchange"""', 'how': '"""outer"""'}), "(left=df, right=auxDf, on='exchange', how='outer')\n", (2274, 2324), True, 'import pandas as pd\n')] |
'''
Example Pose Estimation Network with SE3 loss function (Inference Script)
Dataset: KingsCollege
Network: Inception v1
Loss Function: Geomstats SE(3) Loss
'''
import argparse
import sys
import os
os.environ['GEOMSTATS_BACKEND'] = 'tensorflow' # NOQA
import geomstats.lie_group as lie_group
import tensorflow as tf
from geomstats.special_euclidean_group import SpecialEuclideanGroup
from tensorflow.contrib.slim.python.slim.nets import inception
# command line argument parser
ARGPARSER = argparse.ArgumentParser(
description='Test SE3 PoseNet Inception v1 Model.')
ARGPARSER.add_argument(
'--model_dir', type=str, default='./model',
help='The path to the model directory.')
ARGPARSER.add_argument(
'--dataset', type=str, default='dataset_test.tfrecords',
help='The path to the TFRecords dataset.')
ARGPARSER.add_argument(
'--cuda', type=str, default='0',
help='Specify default GPU to use.')
ARGPARSER.add_argument(
'--debug', default=False, action='store_true',
help="Enables debugging mode.")
class PoseNetReader:
def __init__(self, tfrecord_list):
self.file_q = tf.train.string_input_producer(
tfrecord_list, num_epochs=1)
def read_and_decode(self):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(self.file_q)
features = tf.parse_single_example(
serialized_example,
features={
'image': tf.FixedLenFeature([], tf.string),
'pose': tf.FixedLenFeature([], tf.string)
})
image = tf.decode_raw(features['image'], tf.uint8)
pose = tf.decode_raw(features['pose'], tf.float32)
image = tf.reshape(image, (1, 480, 270, 3))
pose.set_shape((6))
# Random transformations can be put here: right before you crop images
# to predefined size. To get more information look at the stackoverflow
# question linked above.
# image = tf.image.resize_images(image, size=[224, 224])
image = tf.image.resize_image_with_crop_or_pad(image=image,
target_height=224,
target_width=224)
return image, pose
def main(args):
SE3_GROUP = SpecialEuclideanGroup(3)
metric = SE3_GROUP.left_canonical_metric
reader_train = PoseNetReader([FLAGS.dataset])
# Get Input Tensors
image, y_true = reader_train.read_and_decode()
# Construct model and encapsulating all ops into scopes, making
# Tensorboard's Graph visualization more convenient
print('Making Model')
with tf.name_scope('Model'):
py_x, _ = inception.inception_v1(tf.cast(image, tf.float32),
num_classes=6,
is_training=False)
# tanh(pred_angle) required to prevent infinite spins on rotation axis
y_pred = tf.concat((tf.nn.tanh(py_x[:, :3]), py_x[:, 3:]), axis=1)
loss = tf.reduce_mean(
lie_group.loss(y_pred, y_true, SE3_GROUP, metric))
print('Initializing Variables...')
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
# Main Testing Routine
with tf.Session() as sess:
# Run the initializer
sess.run(init_op)
# Start Queue Threads
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
# Load saved weights
print('Loading Trained Weights')
saver = tf.train.Saver()
latest_checkpoint = tf.train.latest_checkpoint(FLAGS.model_dir)
saver.restore(sess, latest_checkpoint)
i = 0
# Inference cycle
try:
while True:
_y_pred, _y_true, _loss = sess.run([y_pred, y_true, loss])
print('Iteration:', i, 'loss:', _loss)
print('_y_pred:', _y_pred)
print('_y_true:', _y_true)
print('\n')
i = i + 1
except tf.errors.OutOfRangeError:
print('End of Testing Data')
except KeyboardInterrupt:
print('KeyboardInterrupt!')
finally:
print('Stopping Threads')
coord.request_stop()
coord.join(threads)
if __name__ == '__main__':
print('Testing SE3 PoseNet Inception v1 Model.')
FLAGS, UNPARSED_ARGV = ARGPARSER.parse_known_args()
print('FLAGS:', FLAGS)
# Set verbosity
if FLAGS.debug:
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
tf.logging.set_verbosity(tf.logging.INFO)
else:
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
tf.logging.set_verbosity(tf.logging.ERROR)
# GPU allocation options
os.environ["CUDA_VISIBLE_DEVICES"] = FLAGS.cuda
tf.app.run(main=main, argv=[sys.argv[0]] + UNPARSED_ARGV)
| [
"tensorflow.local_variables_initializer",
"tensorflow.logging.set_verbosity",
"tensorflow.TFRecordReader",
"geomstats.special_euclidean_group.SpecialEuclideanGroup",
"tensorflow.cast",
"tensorflow.app.run",
"argparse.ArgumentParser",
"tensorflow.train.Coordinator",
"tensorflow.Session",
"tensorflo... | [((497, 572), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test SE3 PoseNet Inception v1 Model."""'}), "(description='Test SE3 PoseNet Inception v1 Model.')\n", (520, 572), False, 'import argparse\n'), ((2310, 2334), 'geomstats.special_euclidean_group.SpecialEuclideanGroup', 'SpecialEuclideanGroup', (['(3)'], {}), '(3)\n', (2331, 2334), False, 'from geomstats.special_euclidean_group import SpecialEuclideanGroup\n'), ((4879, 4936), 'tensorflow.app.run', 'tf.app.run', ([], {'main': 'main', 'argv': '([sys.argv[0]] + UNPARSED_ARGV)'}), '(main=main, argv=[sys.argv[0]] + UNPARSED_ARGV)\n', (4889, 4936), True, 'import tensorflow as tf\n'), ((1125, 1184), 'tensorflow.train.string_input_producer', 'tf.train.string_input_producer', (['tfrecord_list'], {'num_epochs': '(1)'}), '(tfrecord_list, num_epochs=1)\n', (1155, 1184), True, 'import tensorflow as tf\n'), ((1247, 1266), 'tensorflow.TFRecordReader', 'tf.TFRecordReader', ([], {}), '()\n', (1264, 1266), True, 'import tensorflow as tf\n'), ((1590, 1632), 'tensorflow.decode_raw', 'tf.decode_raw', (["features['image']", 'tf.uint8'], {}), "(features['image'], tf.uint8)\n", (1603, 1632), True, 'import tensorflow as tf\n'), ((1648, 1691), 'tensorflow.decode_raw', 'tf.decode_raw', (["features['pose']", 'tf.float32'], {}), "(features['pose'], tf.float32)\n", (1661, 1691), True, 'import tensorflow as tf\n'), ((1709, 1744), 'tensorflow.reshape', 'tf.reshape', (['image', '(1, 480, 270, 3)'], {}), '(image, (1, 480, 270, 3))\n', (1719, 1744), True, 'import tensorflow as tf\n'), ((2048, 2140), 'tensorflow.image.resize_image_with_crop_or_pad', 'tf.image.resize_image_with_crop_or_pad', ([], {'image': 'image', 'target_height': '(224)', 'target_width': '(224)'}), '(image=image, target_height=224,\n target_width=224)\n', (2086, 2140), True, 'import tensorflow as tf\n'), ((2667, 2689), 'tensorflow.name_scope', 'tf.name_scope', (['"""Model"""'], {}), "('Model')\n", (2680, 2689), True, 'import tensorflow as tf\n'), ((3187, 3220), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (3218, 3220), True, 'import tensorflow as tf\n'), ((3245, 3277), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (3275, 3277), True, 'import tensorflow as tf\n'), ((3316, 3328), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3326, 3328), True, 'import tensorflow as tf\n'), ((3441, 3463), 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), '()\n', (3461, 3463), True, 'import tensorflow as tf\n'), ((3482, 3523), 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'coord': 'coord'}), '(coord=coord)\n', (3510, 3523), True, 'import tensorflow as tf\n'), ((3611, 3627), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (3625, 3627), True, 'import tensorflow as tf\n'), ((3656, 3699), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['FLAGS.model_dir'], {}), '(FLAGS.model_dir)\n', (3682, 3699), True, 'import tensorflow as tf\n'), ((4640, 4681), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), '(tf.logging.INFO)\n', (4664, 4681), True, 'import tensorflow as tf\n'), ((4749, 4791), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.ERROR'], {}), '(tf.logging.ERROR)\n', (4773, 4791), True, 'import tensorflow as tf\n'), ((2732, 2758), 'tensorflow.cast', 'tf.cast', (['image', 'tf.float32'], {}), '(image, tf.float32)\n', (2739, 2758), True, 'import tensorflow as tf\n'), ((3073, 3122), 'geomstats.lie_group.loss', 'lie_group.loss', (['y_pred', 'y_true', 'SE3_GROUP', 'metric'], {}), '(y_pred, y_true, SE3_GROUP, metric)\n', (3087, 3122), True, 'import geomstats.lie_group as lie_group\n'), ((2983, 3006), 'tensorflow.nn.tanh', 'tf.nn.tanh', (['py_x[:, :3]'], {}), '(py_x[:, :3])\n', (2993, 3006), True, 'import tensorflow as tf\n'), ((1457, 1490), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.string'], {}), '([], tf.string)\n', (1475, 1490), True, 'import tensorflow as tf\n'), ((1524, 1557), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.string'], {}), '([], tf.string)\n', (1542, 1557), True, 'import tensorflow as tf\n')] |
#!/usr/bin/env python
import numpy as np
from olympus.surfaces import AbstractSurface
class AckleyPath(AbstractSurface):
def __init__(self, param_dim=2, noise=None):
"""Ackley path function.
Args:
param_dim (int): Number of input dimensions. Default is 2.
noise (Noise): Noise object that injects noise into the evaluations of the surface. Default is None.
"""
AbstractSurface.__init__(**locals())
@property
def minima(self):
# minimum at the centre
params = [0.5] * self.param_dim
value = self._run(params)
return [{'params': params, 'value': value}]
@property
def maxima(self):
return None
def _run(self, params):
params = np.array(params)
params = 64 * np.array(params) - 32 # rescale onto [-32, 32]
a = 20.
b = 0.2
c = 2 * np.pi
n = float(len(params))
params = np.array(params)
result = - a * np.exp(- b * np.sqrt(np.sum(params ** 2) / n)) - np.exp(np.sum(np.cos(c * params)) / n) + a + np.exp(1.)
if self.noise is None:
return result
else:
return self.noise(result)
| [
"numpy.exp",
"numpy.array",
"numpy.sum",
"numpy.cos"
] | [((761, 777), 'numpy.array', 'np.array', (['params'], {}), '(params)\n', (769, 777), True, 'import numpy as np\n'), ((950, 966), 'numpy.array', 'np.array', (['params'], {}), '(params)\n', (958, 966), True, 'import numpy as np\n'), ((1084, 1095), 'numpy.exp', 'np.exp', (['(1.0)'], {}), '(1.0)\n', (1090, 1095), True, 'import numpy as np\n'), ((800, 816), 'numpy.array', 'np.array', (['params'], {}), '(params)\n', (808, 816), True, 'import numpy as np\n'), ((1053, 1071), 'numpy.cos', 'np.cos', (['(c * params)'], {}), '(c * params)\n', (1059, 1071), True, 'import numpy as np\n'), ((1011, 1030), 'numpy.sum', 'np.sum', (['(params ** 2)'], {}), '(params ** 2)\n', (1017, 1030), True, 'import numpy as np\n')] |
import json
import lzma
from glob import glob
from pprint import pprint
import pandas as pd
import smart_open
import typer
from tqdm import tqdm
ORDERED_VAR = ["table", "name", "description", "type"]
TEXTTT_VAR = ["table", "name"]
app = typer.Typer()
@app.command()
def sniff(path: str, tar: bool = True, examples: bool = False, break_after: int = None):
"""Print the schema of a JSON file to stdout
Notes:
--tar: for .xz files
--examples/--no-examples: report example for each var
--break-after: number of iterations after which sniffing stops
"""
key_val = {}
i = 0
for file in tqdm(glob(path)):
if tar:
_open = lzma.open
else:
_open = smart_open.open
with _open(file) as f:
for l in tqdm(f):
i += 1
for k, v in json.loads(l).items():
if k in key_val.keys():
if examples:
key_val.update(
{k: (key_val[k][0] + 1, key_val[k][1], key_val[k][2])}
)
else:
key_val.update({k: (key_val[k][0] + 1, key_val[k][1])})
else:
if examples:
key_val.update({k: (1, type(v), v)})
else:
key_val.update({k: (1, type(v))})
if break_after:
if i > break_after:
break
pprint(key_val)
@app.command()
def json2md(file: str):
"""Transform a Json schema to Markdown - Copy to clip-board"""
to_texttt = lambda x: "`" + x + "`"
df = pd.read_json(file)
table = True if "fields" in df.columns else False
if table:
df["table"] = "bibl"
for name, field in df[["name", "fields"]].query("fields==fields").values:
tmp = pd.DataFrame.from_dict(field)
tmp["table"] = name
df = df.append(tmp, sort=False)
df = df[df["fields"].isna()]
# df = df.drop(["mode", "fields"], axis=1)
if not table:
ORDERED_VAR.remove("table")
TEXTTT_VAR.remove("table")
df = df[ORDERED_VAR]
for var in TEXTTT_VAR:
df[var] = df[var].apply(to_texttt)
typer.echo(f"{df.set_index(ORDERED_VAR[0])}")
# typer.secho(message="Table (.md) copied to clip-board", fg=typer.colors.BLUE)
if __name__ == "__main__":
app()
| [
"json.loads",
"tqdm.tqdm",
"typer.Typer",
"pandas.DataFrame.from_dict",
"pandas.read_json",
"pprint.pprint",
"glob.glob"
] | [((240, 253), 'typer.Typer', 'typer.Typer', ([], {}), '()\n', (251, 253), False, 'import typer\n'), ((1566, 1581), 'pprint.pprint', 'pprint', (['key_val'], {}), '(key_val)\n', (1572, 1581), False, 'from pprint import pprint\n'), ((1739, 1757), 'pandas.read_json', 'pd.read_json', (['file'], {}), '(file)\n', (1751, 1757), True, 'import pandas as pd\n'), ((639, 649), 'glob.glob', 'glob', (['path'], {}), '(path)\n', (643, 649), False, 'from glob import glob\n'), ((800, 807), 'tqdm.tqdm', 'tqdm', (['f'], {}), '(f)\n', (804, 807), False, 'from tqdm import tqdm\n'), ((1957, 1986), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['field'], {}), '(field)\n', (1979, 1986), True, 'import pandas as pd\n'), ((860, 873), 'json.loads', 'json.loads', (['l'], {}), '(l)\n', (870, 873), False, 'import json\n')] |
import random
import numpy as np
import cv2
from utils.transforms.transforms import CustomTransform
class RandomFlip(CustomTransform):
def __init__(self, prob_x=0, prob_y=0):
"""
Arguments:
----------
prob_x: range [0, 1], probability to use horizontal flip, setting to 0 means disabling flip
prob_y: range [0, 1], probability to use vertical flip
"""
self.prob_x = prob_x
self.prob_y = prob_y
def __call__(self, sample):
img = sample.get('img').copy()
segLabel = sample.get('segLabel', None)
if segLabel is not None:
segLabel = segLabel.copy()
flip_x = np.random.choice([False, True], p=(1 - self.prob_x, self.prob_x))
flip_y = np.random.choice([False, True], p=(1 - self.prob_y, self.prob_y))
if flip_x:
img = np.ascontiguousarray(np.flip(img, axis=1))
if segLabel is not None:
segLabel = np.ascontiguousarray(np.flip(segLabel, axis=1))
if flip_y:
img = np.ascontiguousarray(np.flip(img, axis=0))
if segLabel is not None:
segLabel = np.ascontiguousarray(np.flip(segLabel, axis=0))
_sample = sample.copy()
_sample['img'] = img
_sample['segLabel'] = segLabel
return _sample
class Darkness(CustomTransform):
def __init__(self, coeff):
assert coeff >= 1., "Darkness coefficient must be greater than 1"
self.coeff = coeff
def __call__(self, sample):
img = sample.get('img')
coeff = np.random.uniform(1., self.coeff)
img = (img.astype('float32') / coeff).astype('uint8')
_sample = sample.copy()
_sample['img'] = img
return _sample | [
"numpy.random.choice",
"numpy.flip",
"numpy.random.uniform"
] | [((675, 740), 'numpy.random.choice', 'np.random.choice', (['[False, True]'], {'p': '(1 - self.prob_x, self.prob_x)'}), '([False, True], p=(1 - self.prob_x, self.prob_x))\n', (691, 740), True, 'import numpy as np\n'), ((758, 823), 'numpy.random.choice', 'np.random.choice', (['[False, True]'], {'p': '(1 - self.prob_y, self.prob_y)'}), '([False, True], p=(1 - self.prob_y, self.prob_y))\n', (774, 823), True, 'import numpy as np\n'), ((1581, 1615), 'numpy.random.uniform', 'np.random.uniform', (['(1.0)', 'self.coeff'], {}), '(1.0, self.coeff)\n', (1598, 1615), True, 'import numpy as np\n'), ((882, 902), 'numpy.flip', 'np.flip', (['img'], {'axis': '(1)'}), '(img, axis=1)\n', (889, 902), True, 'import numpy as np\n'), ((1075, 1095), 'numpy.flip', 'np.flip', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (1082, 1095), True, 'import numpy as np\n'), ((989, 1014), 'numpy.flip', 'np.flip', (['segLabel'], {'axis': '(1)'}), '(segLabel, axis=1)\n', (996, 1014), True, 'import numpy as np\n'), ((1182, 1207), 'numpy.flip', 'np.flip', (['segLabel'], {'axis': '(0)'}), '(segLabel, axis=0)\n', (1189, 1207), True, 'import numpy as np\n')] |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
from __future__ import division
from __future__ import print_function
import numpy as np
from ..ops.functions import CloneMethod, Function, load_model
from ..ops.variables import Variable, Parameter, Constant
from ..utils import get_data_type
from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap
from ..axis import Axis
@typemap
def lambda_rank(output, gain, group, name=''):
r'''
Groups samples according to ``group``, sorts
them within each group based on ``output`` and
computes the Normalized Discounted Cumulative Gain
(NDCG) at infinity for each group. Concretely,
the Discounted Cumulative Gain (DCG) at infinity is:
:math:`\mathrm{DCG_{\infty}}()=\sum_{i=0}^{\infty} \frac{gain_{(i)}}{\log(i+2)}`
where :math:`gain_{(i)}` means the gain of the :math:`i`-th ranked sample.
The NDCG is just the DCG divided by the maximum achievable DCG (obtained
by placing the samples with the largest gain at the top of the ranking).
Samples in the same group must appear in order of decreasing gain.
It returns 1 minus the average NDCG across all the groups in the minibatch
multiplied by 100 times the number of samples in the minibatch.
In the backward direction it back-propagates LambdaRank gradients.
Example:
>>> group = C.input_variable((1,))
>>> score = C.input_variable((1,), needs_gradient=True)
>>> gain = C.input_variable((1,))
>>> g = np.array([1, 1, 2, 2], dtype=np.float32).reshape(4,1,1)
>>> s = np.array([1, 2, 3, 4], dtype=np.float32).reshape(4,1,1)
>>> n = np.array([7, 1, 3, 1], dtype=np.float32).reshape(4,1,1)
>>> f = C.lambda_rank(score, gain, group)
>>> np.round(f.grad({score:s, gain:n, group: g}, wrt=[score]),4)
array([[[-0.2121]],
<BLANKLINE>
[[ 0.2121]],
<BLANKLINE>
[[-0.1486]],
<BLANKLINE>
[[ 0.1486]]], dtype=float32)
Args:
output: score of each sample
gain: gain of each sample
group: group of each sample
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function`
'''
from cntk.cntk_py import lambda_rank
dtype = get_data_type(output, gain, group)
output = sanitize_input(output, dtype)
gain = sanitize_input(gain, dtype)
group = sanitize_input(group, dtype)
return lambda_rank(output, gain, group, name)
@typemap
def ndcg_at_1(output, gain, group, name=''):
r'''
Groups samples according to ``group``, sorts
them within each group based on ``output`` and
computes the Normalized Discounted Cumulative Gain
(NDCG) at 1 for each group. Concretely,
the NDCG at 1 is:
:math:`\mathrm{NDCG_1} = \frac{gain_{(1)}}{\max_i gain_i}`
where :math:`gain_{(1)}` means the gain of the first ranked sample.
Samples in the same group must appear in order of decreasing gain.
It returns the average NDCG at 1 across all the groups in the minibatch
multiplied by 100 times the number of samples in the minibatch.
This is a forward-only operation, there is no gradient for it.
Example:
>>> group = C.input_variable((1,))
>>> score = C.input_variable((1,))
>>> gain = C.input_variable((1,))
>>> g = np.array([1, 1, 2, 2], dtype=np.float32).reshape(4,1,1)
>>> s = np.array([2, 1, 3, 1], dtype=np.float32).reshape(4,1,1)
>>> n = np.array([7, 1, 3, 1], dtype=np.float32).reshape(4,1,1)
>>> C.ndcg_at_1(score, gain, group).eval({score:s, gain:n, group: g})
array(400.0, dtype=float32)
Args:
output: score of each sample
gain: gain of each sample
group: group of each sample
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function`
'''
from cntk.cntk_py import ndcg_at_1
dtype = get_data_type(output, gain, group)
output = sanitize_input(output, dtype)
gain = sanitize_input(gain, dtype)
group = sanitize_input(group, dtype)
return ndcg_at_1(output, gain, group, name)
@typemap
def classification_error(output_vector, target_vector, axis=-1, topN=1, name=''):
'''
This operation computes the classification error. It finds the index of the highest
value in the output_vector and compares it to the actual ground truth label
(the index of the hot bit in the target vector). The result is a scalar
(i.e., one by one matrix). This is often used as an evaluation criterion.
It cannot be used as a training criterion though since the gradient is not
defined for it.
Example:
>>> C.classification_error([[1., 2., 3., 4.]], [[0., 0., 0., 1.]]).eval()
array([[ 0.]], dtype=float32)
>>> C.classification_error([[1., 2., 3., 4.]], [[0., 0., 1., 0.]]).eval()
array([[ 1.]], dtype=float32)
>>> # Note that non-1 values are treated as 0
>>> C.classification_error([[1., 2., 3., 4.]], [[5., 0., 1., 0.]]).eval()
array([[ 1.]], dtype=float32)
Args:
output_vector: the output values from the network
target_vector: it is one-hot vector where the hot bit corresponds to
the label index.
axis (int or :class:`~cntk.axis.Axis`): axis along which the
classification error will be computed.
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function`
'''
from cntk.cntk_py import classification_error
dtype = get_data_type(output_vector, target_vector)
output_vector = sanitize_input(output_vector, dtype)
target_vector = sanitize_input(target_vector, dtype)
axis = sanitize_axis(axis)
return classification_error(output_vector, target_vector, topN, axis, name)
@typemap
def edit_distance_error(input_a, input_b, subPen=0, delPen=0, insPen=0, squashInputs=False, tokensToIgnore=[], name=''):
'''
Edit distance error evaluation node with the option of specifying penalty of substitution, deletion and insertion, as well as squashing the input sequences and ignoring certain samples.
Using the classic DP algorithm as described in https://en.wikipedia.org/wiki/Edit_distance, adjusted to take into account the penalties.
Each sequence in the inputs is expected to be a matrix. Prior to computation of the edit distance, the operation extracts the indices of maximum element in each column.
For example, a sequence matrix
1 2 9 1
3 0 3 2
will be represented as the vector of labels (indices) as [1, 0, 0, 1], on which edit distance will be actually evaluated.
The node allows to squash sequences of repeating labels and ignore certain labels. For example, if squashInputs is true and tokensToIgnore contains label '-' then
given first input sequence as s1="1-12-" and second as s2="-11--122" the edit distance will be computed against s1' = "112" and s2' = "112".
The returned error is computed as: EditDistance(s1,s2) * length(s1') / length(s1)
Just like ClassificationError and other evaluation nodes, when used as an evaluation criterion, the SGD process will aggregate all values over an epoch and report the average, i.e. the error rate.
Primary objective of this node is for error evaluation of CTC training, see formula (1) in "Connectionist Temporal Classification: Labelling Unsegmented
Sequence Data with Recurrent Neural Networks", http://machinelearning.wustl.edu/mlpapers/paper_files/icml2006_GravesFGS06.pdf
Example:
i1 = cntk.input_variable(shape=(2,))
i2 = cntk.input_variable(shape=(2,))
arguments = {i1 : [[1, 3], [2, 0]], i2 : [[2, 0], [2, 0]]}
a = edit_distance_error(i1, i2, 0, 1, 1, True, [1])
print(a.eval(arguments))
Args:
input_a: first input sequence
input_b: second input sequence
subPen, delPen, insPen: substitution, deletion and insertion penalties
squashInputs: whether to merge sequences of identical samples (in both input sequences). If true and tokensToIgnore contains label '-' then
given first input sequence as s1="a-ab-" and second as s2="-aa--abb" the edit distance will be computed against s1' = "aab" and s2' = "aab".
tokensToIgnore: list of samples to ignore during edit distance evaluation (in both sequences)
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function`
'''
from cntk.cntk_py import edit_distance_error
dtype = get_data_type(input_a, input_b)
input_a = sanitize_input(input_a, dtype)
input_b = sanitize_input(input_b, dtype)
return edit_distance_error(input_a, input_b, subPen, delPen, insPen, squashInputs, tokensToIgnore, name)
| [
"cntk.internal.sanitize_axis",
"cntk.cntk_py.ndcg_at_1",
"cntk.cntk_py.edit_distance_error",
"cntk.cntk_py.classification_error",
"cntk.internal.sanitize_input",
"cntk.cntk_py.lambda_rank"
] | [((2607, 2636), 'cntk.internal.sanitize_input', 'sanitize_input', (['output', 'dtype'], {}), '(output, dtype)\n', (2621, 2636), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((2648, 2675), 'cntk.internal.sanitize_input', 'sanitize_input', (['gain', 'dtype'], {}), '(gain, dtype)\n', (2662, 2675), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((2688, 2716), 'cntk.internal.sanitize_input', 'sanitize_input', (['group', 'dtype'], {}), '(group, dtype)\n', (2702, 2716), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((2728, 2766), 'cntk.cntk_py.lambda_rank', 'lambda_rank', (['output', 'gain', 'group', 'name'], {}), '(output, gain, group, name)\n', (2739, 2766), False, 'from cntk.cntk_py import lambda_rank\n'), ((4311, 4340), 'cntk.internal.sanitize_input', 'sanitize_input', (['output', 'dtype'], {}), '(output, dtype)\n', (4325, 4340), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((4352, 4379), 'cntk.internal.sanitize_input', 'sanitize_input', (['gain', 'dtype'], {}), '(gain, dtype)\n', (4366, 4379), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((4392, 4420), 'cntk.internal.sanitize_input', 'sanitize_input', (['group', 'dtype'], {}), '(group, dtype)\n', (4406, 4420), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((4432, 4468), 'cntk.cntk_py.ndcg_at_1', 'ndcg_at_1', (['output', 'gain', 'group', 'name'], {}), '(output, gain, group, name)\n', (4441, 4468), False, 'from cntk.cntk_py import ndcg_at_1\n'), ((5982, 6018), 'cntk.internal.sanitize_input', 'sanitize_input', (['output_vector', 'dtype'], {}), '(output_vector, dtype)\n', (5996, 6018), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((6039, 6075), 'cntk.internal.sanitize_input', 'sanitize_input', (['target_vector', 'dtype'], {}), '(target_vector, dtype)\n', (6053, 6075), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((6087, 6106), 'cntk.internal.sanitize_axis', 'sanitize_axis', (['axis'], {}), '(axis)\n', (6100, 6106), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((6118, 6186), 'cntk.cntk_py.classification_error', 'classification_error', (['output_vector', 'target_vector', 'topN', 'axis', 'name'], {}), '(output_vector, target_vector, topN, axis, name)\n', (6138, 6186), False, 'from cntk.cntk_py import classification_error\n'), ((8996, 9026), 'cntk.internal.sanitize_input', 'sanitize_input', (['input_a', 'dtype'], {}), '(input_a, dtype)\n', (9010, 9026), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((9041, 9071), 'cntk.internal.sanitize_input', 'sanitize_input', (['input_b', 'dtype'], {}), '(input_b, dtype)\n', (9055, 9071), False, 'from cntk.internal import sanitize_input, sanitize_shape, sanitize_axis, sanitize_dynamic_axes, typemap\n'), ((9083, 9184), 'cntk.cntk_py.edit_distance_error', 'edit_distance_error', (['input_a', 'input_b', 'subPen', 'delPen', 'insPen', 'squashInputs', 'tokensToIgnore', 'name'], {}), '(input_a, input_b, subPen, delPen, insPen, squashInputs,\n tokensToIgnore, name)\n', (9102, 9184), False, 'from cntk.cntk_py import edit_distance_error\n')] |
#
# 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 contextlib
import mock
from heat.common import exception as exc
from heat.engine import stack
from heat.engine import template
from heat.tests import common
from heat.tests import utils
class SoftwareConfigTest(common.HeatTestCase):
def setUp(self):
super(SoftwareConfigTest, self).setUp()
self.ctx = utils.dummy_context()
self.properties = {
'group': 'Heat::Shell',
'inputs': [],
'outputs': [],
'options': {},
'config': '#!/bin/bash'
}
self.stack = stack.Stack(
self.ctx, 'software_config_test_stack',
template.Template({
'HeatTemplateFormatVersion': '2012-12-12',
'Resources': {
'config_mysql': {
'Type': 'OS::Heat::SoftwareConfig',
'Properties': self.properties
}}}))
self.config = self.stack['config_mysql']
self.rpc_client = mock.MagicMock()
self.config._rpc_client = self.rpc_client
@contextlib.contextmanager
def exc_filter(*args):
try:
yield
except exc.NotFound:
pass
self.rpc_client.ignore_error_by_name.side_effect = exc_filter
def test_handle_create(self):
config_id = 'c8a19429-7fde-47ea-a42f-40045488226c'
value = {'id': config_id}
self.rpc_client.create_software_config.return_value = value
self.config.handle_create()
self.assertEqual(config_id, self.config.resource_id)
def test_handle_delete(self):
self.resource_id = None
self.assertIsNone(self.config.handle_delete())
config_id = 'c8a19429-7fde-47ea-a42f-40045488226c'
self.config.resource_id = config_id
self.rpc_client.delete_software_config.return_value = None
self.assertIsNone(self.config.handle_delete())
self.rpc_client.delete_software_config.side_effect = exc.NotFound
self.assertIsNone(self.config.handle_delete())
def test_resolve_attribute(self):
self.assertIsNone(self.config._resolve_attribute('others'))
self.config.resource_id = None
self.assertIsNone(self.config._resolve_attribute('config'))
self.config.resource_id = 'c8a19429-7fde-47ea-a42f-40045488226c'
value = {'config': '#!/bin/bash'}
self.rpc_client.show_software_config.return_value = value
self.assertEqual(
'#!/bin/bash', self.config._resolve_attribute('config'))
self.rpc_client.show_software_config.side_effect = exc.NotFound
self.assertIsNone(self.config._resolve_attribute('config'))
| [
"heat.engine.template.Template",
"mock.MagicMock",
"heat.tests.utils.dummy_context"
] | [((907, 928), 'heat.tests.utils.dummy_context', 'utils.dummy_context', ([], {}), '()\n', (926, 928), False, 'from heat.tests import utils\n'), ((1580, 1596), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (1594, 1596), False, 'import mock\n'), ((1217, 1387), 'heat.engine.template.Template', 'template.Template', (["{'HeatTemplateFormatVersion': '2012-12-12', 'Resources': {'config_mysql': {\n 'Type': 'OS::Heat::SoftwareConfig', 'Properties': self.properties}}}"], {}), "({'HeatTemplateFormatVersion': '2012-12-12', 'Resources':\n {'config_mysql': {'Type': 'OS::Heat::SoftwareConfig', 'Properties':\n self.properties}}})\n", (1234, 1387), False, 'from heat.engine import template\n')] |
"""Implementation of AppGroup API.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import fnmatch
from treadmill import context
from treadmill import schema
from treadmill import admin
class API(object):
"""Treadmill AppGroup REST api."""
def __init__(self):
"""init"""
def _admin_app_group():
"""Lazily return admin object."""
return admin.AppGroup(context.GLOBAL.ldap.conn)
@schema.schema({'$ref': 'app_group.json#/resource_id'})
def get(rsrc_id):
"""Get application configuration."""
result = _admin_app_group().get(rsrc_id)
result['_id'] = rsrc_id
return result
@schema.schema(
{'$ref': 'app_group.json#/resource_id'},
{'allOf': [{'$ref': 'app_group.json#/resource'},
{'$ref': 'app_group.json#/verbs/create'}]}
)
def create(rsrc_id, rsrc):
"""Create (configure) application."""
_admin_app_group().create(rsrc_id, rsrc)
return _admin_app_group().get(rsrc_id)
@schema.schema(
{'$ref': 'app_group.json#/resource_id'},
{'allOf': [{'$ref': 'app_group.json#/resource'},
{'$ref': 'app_group.json#/verbs/update'}]}
)
def update(rsrc_id, rsrc):
"""Update application configuration."""
_admin_app_group().replace(rsrc_id, rsrc)
return _admin_app_group().get(rsrc_id)
@schema.schema({'$ref': 'app_group.json#/resource_id'})
def delete(rsrc_id):
"""Delete configured application."""
_admin_app_group().delete(rsrc_id)
return None
def _list(match=None):
"""List configured applications."""
if match is None:
match = '*'
app_groups = _admin_app_group().list({})
filtered = [
app_group for app_group in app_groups
if fnmatch.fnmatch(app_group['_id'], match)
]
return sorted(filtered, key=lambda item: item['_id'])
self.get = get
self.create = create
self.update = update
self.delete = delete
self.list = _list
| [
"fnmatch.fnmatch",
"treadmill.admin.AppGroup",
"treadmill.schema.schema"
] | [((546, 600), 'treadmill.schema.schema', 'schema.schema', (["{'$ref': 'app_group.json#/resource_id'}"], {}), "({'$ref': 'app_group.json#/resource_id'})\n", (559, 600), False, 'from treadmill import schema\n'), ((801, 952), 'treadmill.schema.schema', 'schema.schema', (["{'$ref': 'app_group.json#/resource_id'}", "{'allOf': [{'$ref': 'app_group.json#/resource'}, {'$ref':\n 'app_group.json#/verbs/create'}]}"], {}), "({'$ref': 'app_group.json#/resource_id'}, {'allOf': [{'$ref':\n 'app_group.json#/resource'}, {'$ref': 'app_group.json#/verbs/create'}]})\n", (814, 952), False, 'from treadmill import schema\n'), ((1205, 1356), 'treadmill.schema.schema', 'schema.schema', (["{'$ref': 'app_group.json#/resource_id'}", "{'allOf': [{'$ref': 'app_group.json#/resource'}, {'$ref':\n 'app_group.json#/verbs/update'}]}"], {}), "({'$ref': 'app_group.json#/resource_id'}, {'allOf': [{'$ref':\n 'app_group.json#/resource'}, {'$ref': 'app_group.json#/verbs/update'}]})\n", (1218, 1356), False, 'from treadmill import schema\n'), ((1612, 1666), 'treadmill.schema.schema', 'schema.schema', (["{'$ref': 'app_group.json#/resource_id'}"], {}), "({'$ref': 'app_group.json#/resource_id'})\n", (1625, 1666), False, 'from treadmill import schema\n'), ((495, 535), 'treadmill.admin.AppGroup', 'admin.AppGroup', (['context.GLOBAL.ldap.conn'], {}), '(context.GLOBAL.ldap.conn)\n', (509, 535), False, 'from treadmill import admin\n'), ((2106, 2146), 'fnmatch.fnmatch', 'fnmatch.fnmatch', (["app_group['_id']", 'match'], {}), "(app_group['_id'], match)\n", (2121, 2146), False, 'import fnmatch\n')] |
# Copyright 2017 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.
from recipe_engine import post_process
from recipe_engine import recipe_api
DEPS = [
'gclient',
'recipe_engine/properties',
]
PROPERTIES = {
'patch_project': recipe_api.Property(),
}
def RunSteps(api, patch_project):
api.gclient.set_config('chromium')
patch_root = api.gclient.calculate_patch_root(patch_project)
api.gclient.set_patch_project_revision(patch_project)
def GenTests(api):
yield (
api.test('chromium') +
api.properties(patch_project='chromium') +
api.post_process(post_process.DropExpectation)
)
yield (
api.test('v8') +
api.properties(patch_project='v8') +
api.post_process(post_process.DropExpectation)
)
| [
"recipe_engine.recipe_api.Property"
] | [((331, 352), 'recipe_engine.recipe_api.Property', 'recipe_api.Property', ([], {}), '()\n', (350, 352), False, 'from recipe_engine import recipe_api\n')] |
from text import symbols
class Hparams:
def __init__(self):
################################
# Experiment Parameters #
################################
self.epochs = 500
self.iters_per_checkpoint = 1000
self.iters_per_validation = 1000
self.seed = 1234
self.dynamic_loss_scaling = True
self.fp16_run = False
self.distributed_run = False
self.cudnn_enabled = True
self.cudnn_benchmark = False
self.ignore_layers = ["embedding.weight"]
################################
# Data Parameters #
################################
self.training_files = "DATASET/train.csv.txt"
self.validation_files = "DATASET/val.csv.txt"
self.text_cleaners = ["basic_cleaners"]
self.symbols_lang = "en" # en: English characters; py: Chinese Pinyin symbols
################################
# Model Parameters #
################################
self.tacotron_version = "2" # 1: Tacotron; 2: Tacotron-2
self.tacotron_config = "tacotron2.json"
self.num_symbols = len(symbols(self.symbols_lang))
self.symbols_embed_dim = 512
self.mel_dim = 80
self.r = 3
self.max_decoder_steps = 1000
self.stop_threshold = 0.5
################################
# Optimization Hyperparameters #
################################
self.use_saved_learning_rate = False
self.learning_rate = 1e-3
self.weight_decay = 1e-6
self.grad_clip_thresh = 1.0
self.batch_size = 32
self.mask_padding = True # set model's padded outputs to padded values
def __str__(self):
return "\n".join(
["Hyper Parameters:"]
+ ["{}:{}".format(key, getattr(self, key, None)) for key in self.__dict__]
)
def create_hparams():
"""Create model hyperparameters. Parse nondefault from object args."""
return Hparams() | [
"text.symbols"
] | [((1188, 1214), 'text.symbols', 'symbols', (['self.symbols_lang'], {}), '(self.symbols_lang)\n', (1195, 1214), False, 'from text import symbols\n')] |
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Ascending bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.bijectors import bijector
from tensorflow_probability.python.internal import assert_util
from tensorflow_probability.python.internal import auto_composite_tensor
__all__ = [
'Ascending',
]
@auto_composite_tensor.auto_composite_tensor(omit_kwargs=('name',))
class Ascending(bijector.AutoCompositeTensorBijector):
"""Maps unconstrained R^n to R^n in ascending order.
Both the domain and the codomain of the mapping is `[-inf, inf]^n`, however,
the input of the inverse mapping must be strictly increasing.
On the last dimension of the tensor, the Ascending bijector performs:
`y = tf.cumsum([x[0], tf.exp(x[1]), tf.exp(x[2]), ..., tf.exp(x[-1])])`
#### Example Use:
```python
bijectors.Ascending().inverse([2, 3, 4])
# Result: [2., 0., 0.]
bijectors.Ascending().forward([0.06428002, -1.07774478, -0.71530371])
# Result: [0.06428002, 0.40464228, 0.8936858]
```
"""
_type_spec_id = 366918634
def __init__(self, validate_args=False, name='ascending'):
parameters = dict(locals())
with tf.name_scope(name) as name:
super(Ascending, self).__init__(
forward_min_event_ndims=1,
validate_args=validate_args,
parameters=parameters,
name=name)
@classmethod
def _parameter_properties(cls, dtype):
return dict()
def _forward(self, x):
y0 = x[..., :1]
yk = tf.exp(x[..., 1:])
y = tf.concat([y0, yk], axis=-1)
return tf.cumsum(y, axis=-1)
def _inverse(self, y):
with tf.control_dependencies(self._assertions(y)):
x0 = y[..., :1]
xk = tf.math.log(y[..., 1:] - y[..., :-1])
x = tf.concat([x0, xk], axis=-1)
return x
def _forward_log_det_jacobian(self, x):
# The Jacobian of the forward mapping is lower
# triangular, with the diagonal elements being:
# J[i,i] = 1 if i=1, and
# exp(x_i) if 1<i<=K
# which gives the absolute Jacobian determinant:
# |det(Jac)| = prod_{i=1}^{K} exp(x[i]).
# (1) - Stan Modeling Language User's Guide and Reference Manual
# Version 2.17.0 session 35.2
return tf.reduce_sum(x[..., 1:], axis=-1)
def _inverse_log_det_jacobian(self, y):
with tf.control_dependencies(self._assertions(y)):
return -tf.reduce_sum(tf.math.log(y[..., 1:] - y[..., :-1]), axis=-1)
def _assertions(self, t):
if not self.validate_args:
return []
return [assert_util.assert_greater(
t[..., 1:], t[..., :-1],
message='Inverse transformation input must be strictly increasing.')]
| [
"tensorflow_probability.python.internal.assert_util.assert_greater",
"tensorflow.compat.v2.cumsum",
"tensorflow.compat.v2.math.log",
"tensorflow.compat.v2.concat",
"tensorflow.compat.v2.exp",
"tensorflow_probability.python.internal.auto_composite_tensor.auto_composite_tensor",
"tensorflow.compat.v2.name... | [((1083, 1149), 'tensorflow_probability.python.internal.auto_composite_tensor.auto_composite_tensor', 'auto_composite_tensor.auto_composite_tensor', ([], {'omit_kwargs': "('name',)"}), "(omit_kwargs=('name',))\n", (1126, 1149), False, 'from tensorflow_probability.python.internal import auto_composite_tensor\n'), ((2246, 2264), 'tensorflow.compat.v2.exp', 'tf.exp', (['x[..., 1:]'], {}), '(x[..., 1:])\n', (2252, 2264), True, 'import tensorflow.compat.v2 as tf\n'), ((2273, 2301), 'tensorflow.compat.v2.concat', 'tf.concat', (['[y0, yk]'], {'axis': '(-1)'}), '([y0, yk], axis=-1)\n', (2282, 2301), True, 'import tensorflow.compat.v2 as tf\n'), ((2313, 2334), 'tensorflow.compat.v2.cumsum', 'tf.cumsum', (['y'], {'axis': '(-1)'}), '(y, axis=-1)\n', (2322, 2334), True, 'import tensorflow.compat.v2 as tf\n'), ((2968, 3002), 'tensorflow.compat.v2.reduce_sum', 'tf.reduce_sum', (['x[..., 1:]'], {'axis': '(-1)'}), '(x[..., 1:], axis=-1)\n', (2981, 3002), True, 'import tensorflow.compat.v2 as tf\n'), ((1918, 1937), 'tensorflow.compat.v2.name_scope', 'tf.name_scope', (['name'], {}), '(name)\n', (1931, 1937), True, 'import tensorflow.compat.v2 as tf\n'), ((2449, 2486), 'tensorflow.compat.v2.math.log', 'tf.math.log', (['(y[..., 1:] - y[..., :-1])'], {}), '(y[..., 1:] - y[..., :-1])\n', (2460, 2486), True, 'import tensorflow.compat.v2 as tf\n'), ((2497, 2525), 'tensorflow.compat.v2.concat', 'tf.concat', (['[x0, xk]'], {'axis': '(-1)'}), '([x0, xk], axis=-1)\n', (2506, 2525), True, 'import tensorflow.compat.v2 as tf\n'), ((3265, 3390), 'tensorflow_probability.python.internal.assert_util.assert_greater', 'assert_util.assert_greater', (['t[..., 1:]', 't[..., :-1]'], {'message': '"""Inverse transformation input must be strictly increasing."""'}), "(t[..., 1:], t[..., :-1], message=\n 'Inverse transformation input must be strictly increasing.')\n", (3291, 3390), False, 'from tensorflow_probability.python.internal import assert_util\n'), ((3129, 3166), 'tensorflow.compat.v2.math.log', 'tf.math.log', (['(y[..., 1:] - y[..., :-1])'], {}), '(y[..., 1:] - y[..., :-1])\n', (3140, 3166), True, 'import tensorflow.compat.v2 as tf\n')] |
# Calculate cloud storage cash requirements
from math import ceil
price = {
'server': 2, # usd/hour
'data': 0.5, # usd/hour
'host': 10 # usd/month
}
capacity = {
'server': 50, # users
'data': 500 # megabytes
}
budget = float(input())
users = int(input())
data = int(input()) # gigabytes
hosts = int(input())
uptime = float(input())
cost_user = ceil(users / capacity['server']) * price['server'] * 24 * 30
cost_data = ceil(data * 1000 / capacity['data']) * price['data'] * 24 * 30
cost_hosts = hosts * price['host']
cost_all = (cost_user + cost_data + cost_hosts) * uptime / 100
if budget >= cost_all:
leftover = budget - cost_all
result = f'Clouds Ahoy! Monthly cost: ${cost_all:.2f} (${leftover:.2f} leftover)'
else:
more = cost_all - budget
result = f'Stay Grounded! Monthly cost: ${cost_all:.2f} (Need ${more:.2f} more)'
print(result)
| [
"math.ceil"
] | [((369, 401), 'math.ceil', 'ceil', (["(users / capacity['server'])"], {}), "(users / capacity['server'])\n", (373, 401), False, 'from math import ceil\n'), ((442, 478), 'math.ceil', 'ceil', (["(data * 1000 / capacity['data'])"], {}), "(data * 1000 / capacity['data'])\n", (446, 478), False, 'from math import ceil\n')] |
#!/usr/bin/env python3
import sys
from muse_tool import multi_muse
if __name__ == "__main__":
# CLI Entrypoint.
retcode = 0
try:
retcode = multi_muse.main()
except Exception as e:
retcode = 1
sys.exit(retcode)
# __END__
| [
"muse_tool.multi_muse.main",
"sys.exit"
] | [((232, 249), 'sys.exit', 'sys.exit', (['retcode'], {}), '(retcode)\n', (240, 249), False, 'import sys\n'), ((162, 179), 'muse_tool.multi_muse.main', 'multi_muse.main', ([], {}), '()\n', (177, 179), False, 'from muse_tool import multi_muse\n')] |
from django.db import models
from django.core.validators import MinValueValidator
from user_management.models import Librarian, DeliveryMan, Reader
class Library(models.Model):
ID = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
address = models.TextField(max_length=1000)
librarian = models.OneToOneField(Librarian, on_delete=models.PROTECT)
subscription_fee = models.IntegerField(validators=[MinValueValidator(0.0)])
class Meta:
indexes = [
models.Index(fields=['name'], name='library_name_index')
]
unique_together = ['name', 'address']
@property
def librarian_name(self):
return self.librarian.reader.user_name
def __str__(self)->str:
return f'{self.name} is managed by {self.librarian.username} in {self.address}. To join pay {self.subscription_fee}'
def deliveryman_paid(self,deliveryman:DeliveryMan, amount:int)->None:
payment = Payment.objects.get(deliveryman = deliveryman, library = self)
payment.decrese_amount(amount)
payment.save()
def ban_reader(self, reader:Reader)->None:
member = MemberShip.objects.get(lib=self, reader=reader)
member.ban()
def fine_user(self, reader:Reader, amount:int)->None:
pass
class MemberShip(models.Model):
ID = models.AutoField(primary_key=True)
lib = models.ForeignKey(Library, on_delete = models.CASCADE)
reader = models.ForeignKey(Reader, on_delete = models.CASCADE)
banned = models.BooleanField(default=0)
fine = models.IntegerField(default=0,validators=[MinValueValidator(0.0)])
class Meta:
indexes = [
models.Index(fields=['reader'],name='member_index')
]
unique_together = ['lib','reader']
@property
def user_name():
return self.reader.username
@property
def library_name():
return self.lib.name
def library_id():
return self.library_id
def __str__(self)->str:
ban_status = "banned" if self.banned else ""
return f'{self.reader} is {ban_status} member of {self.library}'
def ban(self)->None:
self.banned = True
self.save()
def unban(self)->None:
self.banned = False
self.save()
def add_fine(self, amount:int)->int:
self.fine += amount
self.save()
return self.fine
def pay_fine(self, amount:int, deliveryman: DeliveryMan)->int:
self.fine -= amount
self.save()
payment = Payment.objects.get(deliveryman=deliverymanm, library=self.lib)
payment.increase_amount(amount)
return self.fine
def pay_membership_fee(self, deliveryman: DeliveryMan)->None:
payment = Payment.objects.get(deliveryman=deliveryman, library=self.lib)
payment.increase_amount(self.lib.subscription_fee)
class Payment(models.Model):
ID = models.AutoField(primary_key=True)
library = models.ForeignKey(Library, on_delete=models.CASCADE)
deliveryman = models.ForeignKey(DeliveryMan, on_delete=models.CASCADE)
amount = models.IntegerField(validators=[MinValueValidator(0.0)])
class Meta:
indexes = [
models.Index(fields=['library'],name='library_payment_index'),
models.Index(fields=['deliveryman'],name='deliveryman_payment_index')
]
unique_together=['library','deliveryman']
def __str__(self)->None:
return f'{self.deliveryman} owe {self.library} Rs {self.amount}'
def increase_amount(self, amount:int):
if type(amount) != int:
raise TypeError
self.amount += amount
self.save()
def decrese_amount(self, amount:int):
if type(amount) != int:
raise TypeError
if self.amount - amount < 0:
raise ValueError
self.amount -= amount
self.save() | [
"django.db.models.Index",
"django.db.models.OneToOneField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.core.validators.MinValueValidator",
"django.db.models.CharField"
] | [((187, 221), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (203, 221), False, 'from django.db import models\n'), ((233, 265), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (249, 265), False, 'from django.db import models\n'), ((280, 313), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(1000)'}), '(max_length=1000)\n', (296, 313), False, 'from django.db import models\n'), ((330, 387), 'django.db.models.OneToOneField', 'models.OneToOneField', (['Librarian'], {'on_delete': 'models.PROTECT'}), '(Librarian, on_delete=models.PROTECT)\n', (350, 387), False, 'from django.db import models\n'), ((1346, 1380), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (1362, 1380), False, 'from django.db import models\n'), ((1391, 1443), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Library'], {'on_delete': 'models.CASCADE'}), '(Library, on_delete=models.CASCADE)\n', (1408, 1443), False, 'from django.db import models\n'), ((1459, 1510), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Reader'], {'on_delete': 'models.CASCADE'}), '(Reader, on_delete=models.CASCADE)\n', (1476, 1510), False, 'from django.db import models\n'), ((1526, 1556), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(0)'}), '(default=0)\n', (1545, 1556), False, 'from django.db import models\n'), ((2911, 2945), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (2927, 2945), False, 'from django.db import models\n'), ((2960, 3012), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Library'], {'on_delete': 'models.CASCADE'}), '(Library, on_delete=models.CASCADE)\n', (2977, 3012), False, 'from django.db import models\n'), ((3031, 3087), 'django.db.models.ForeignKey', 'models.ForeignKey', (['DeliveryMan'], {'on_delete': 'models.CASCADE'}), '(DeliveryMan, on_delete=models.CASCADE)\n', (3048, 3087), False, 'from django.db import models\n'), ((517, 573), 'django.db.models.Index', 'models.Index', ([], {'fields': "['name']", 'name': '"""library_name_index"""'}), "(fields=['name'], name='library_name_index')\n", (529, 573), False, 'from django.db import models\n'), ((1684, 1736), 'django.db.models.Index', 'models.Index', ([], {'fields': "['reader']", 'name': '"""member_index"""'}), "(fields=['reader'], name='member_index')\n", (1696, 1736), False, 'from django.db import models\n'), ((3207, 3269), 'django.db.models.Index', 'models.Index', ([], {'fields': "['library']", 'name': '"""library_payment_index"""'}), "(fields=['library'], name='library_payment_index')\n", (3219, 3269), False, 'from django.db import models\n'), ((3282, 3352), 'django.db.models.Index', 'models.Index', ([], {'fields': "['deliveryman']", 'name': '"""deliveryman_payment_index"""'}), "(fields=['deliveryman'], name='deliveryman_payment_index')\n", (3294, 3352), False, 'from django.db import models\n'), ((443, 465), 'django.core.validators.MinValueValidator', 'MinValueValidator', (['(0.0)'], {}), '(0.0)\n', (460, 465), False, 'from django.core.validators import MinValueValidator\n'), ((1610, 1632), 'django.core.validators.MinValueValidator', 'MinValueValidator', (['(0.0)'], {}), '(0.0)\n', (1627, 1632), False, 'from django.core.validators import MinValueValidator\n'), ((3133, 3155), 'django.core.validators.MinValueValidator', 'MinValueValidator', (['(0.0)'], {}), '(0.0)\n', (3150, 3155), False, 'from django.core.validators import MinValueValidator\n')] |
import os
from batman.run import run
from tests.integration.utils import batman_dir, update_batman_yml, touch_file
def test_that_batmanyml_changes_are_noticed():
"""
Sometimes we need to change the .batman.yml file, so make sure that changes are noticed
and get run.
"""
with batman_dir({
"ensure_symlinks": {
"cotts.txt": "ravine.txt"
}
}) as tmp_batman_dir:
os.system('batman {0}'.format(tmp_batman_dir))
assert os.path.realpath(os.path.join(tmp_batman_dir, 'ravine.txt')) == os.path.join(tmp_batman_dir, 'cotts.txt')
with open(os.path.join(tmp_batman_dir,'.batman.yml'),'a') as yml_file:
update_batman_yml(tmp_batman_dir, {'ensure_symlinks': { 'cotts2.txt':'ravine2.txt'}})
os.system('batman {0}'.format(tmp_batman_dir))
assert os.path.realpath(os.path.join(tmp_batman_dir, 'ravine2.txt')) == os.path.join(tmp_batman_dir, 'cotts2.txt')
def test_that_on_update_commands_dont_get_rerun(tmpdir):
"""
Should keep track of yaml stuff on a key-by-key basis and only rerun commands if
that specific piece has changed.
"""
test_yml = {
"hash_dir": str(tmpdir),
"update_on_change": {
"monkey.txt": "echo -ne '.' >> onedot.txt"
}
}
with batman_dir(test_yml) as tmp_batman_dir:
touch_file(os.path.join(tmp_batman_dir, 'monkey.txt'))
os.system('batman {0}'.format(tmp_batman_dir))
test_yml['update_on_change']['walrus.txt'] = 'touch bucket.txt'
update_batman_yml(tmp_batman_dir, test_yml)
os.system('batman {0}'.format(tmp_batman_dir))
assert run('cat onedot.txt', in_dir=tmp_batman_dir).output == '.'
def test_that_on_update_commands_still_get_rerun_if_file_is_updated(tmpdir):
test_yml = {
"hash_dir": str(tmpdir),
"update_on_change": {
"monkey.txt": "echo -ne '.' >> onedot.txt"
}
}
with batman_dir(test_yml) as tmp_batman_dir:
touch_file(os.path.join(tmp_batman_dir, 'monkey.txt'))
os.system('batman {0}'.format(tmp_batman_dir))
run('echo -ne "updated" > monkey.txt', in_dir=tmp_batman_dir)
os.system('batman {0}'.format(tmp_batman_dir))
assert run('cat onedot.txt', in_dir=tmp_batman_dir).output == '..'
def test_wildcard_expansion(tmpdir):
with batman_dir({
"hash_dir": str(tmpdir),
"update_on_change": {
"*/migrations/*": "echo -ne '.' >> onedot.txt"
}
}) as tmp_batman_dir:
testpath = os.path.join(tmp_batman_dir, 'testapp', 'migrations')
os.makedirs(testpath)
os.system('batman {0}'.format(tmp_batman_dir))
touch_file(os.path.join(testpath, 'imhere.txt'))
os.system('batman {0}'.format(tmp_batman_dir))
run('echo "bleh" > {0}'.format(os.path.join(tmp_batman_dir, 'imhere.txt')))
assert run('cat onedot.txt', in_dir=tmp_batman_dir).output == '..'
def test_create_old_dict_if_not_exists(tmpdir):
"""
If the hashdir doesnt exist, create it.
"""
test_hashdir = os.path.join(str(tmpdir), 'hashdir/')
with batman_dir({
"hash_dir": test_hashdir,
"update_on_change": {
"monkey.txt": "echo -ne '.' >> onedot.txt"
}
}) as tmp_batman_dir:
os.system('batman {0}'.format(tmp_batman_dir))
assert(os.path.isfile(os.path.join(test_hashdir, 'old_dict.yml')))
def test_that_order_is_preserved(tmpdir):
"""
If the hashdir doesnt exist, create it.
"""
with batman_dir({
"hash_dir": str(tmpdir),
"update_on_change": {
"a": "echo -ne 'a' >> alpha.txt",
"b": "echo -ne 'b' >> alpha.txt",
"c": "echo -ne 'c' >> alpha.txt",
"d": "echo -ne 'd' >> alpha.txt",
"e": "echo -ne 'e' >> alpha.txt",
"f": "echo -ne 'f' >> alpha.txt",
"g": "echo -ne 'g' >> alpha.txt",
"h": "echo -ne 'h' >> alpha.txt",
}
}) as tmp_batman_dir:
os.system('batman {0}'.format(tmp_batman_dir))
assert run('cat alpha.txt', in_dir=tmp_batman_dir).output == 'abcdefgh'
| [
"batman.run.run",
"os.makedirs",
"tests.integration.utils.update_batman_yml",
"os.path.join",
"tests.integration.utils.batman_dir"
] | [((297, 357), 'tests.integration.utils.batman_dir', 'batman_dir', (["{'ensure_symlinks': {'cotts.txt': 'ravine.txt'}}"], {}), "({'ensure_symlinks': {'cotts.txt': 'ravine.txt'}})\n", (307, 357), False, 'from tests.integration.utils import batman_dir, update_batman_yml, touch_file\n'), ((1300, 1320), 'tests.integration.utils.batman_dir', 'batman_dir', (['test_yml'], {}), '(test_yml)\n', (1310, 1320), False, 'from tests.integration.utils import batman_dir, update_batman_yml, touch_file\n'), ((1538, 1581), 'tests.integration.utils.update_batman_yml', 'update_batman_yml', (['tmp_batman_dir', 'test_yml'], {}), '(tmp_batman_dir, test_yml)\n', (1555, 1581), False, 'from tests.integration.utils import batman_dir, update_batman_yml, touch_file\n'), ((1949, 1969), 'tests.integration.utils.batman_dir', 'batman_dir', (['test_yml'], {}), '(test_yml)\n', (1959, 1969), False, 'from tests.integration.utils import batman_dir, update_batman_yml, touch_file\n'), ((2115, 2176), 'batman.run.run', 'run', (['"""echo -ne "updated" > monkey.txt"""'], {'in_dir': 'tmp_batman_dir'}), '(\'echo -ne "updated" > monkey.txt\', in_dir=tmp_batman_dir)\n', (2118, 2176), False, 'from batman.run import run\n'), ((2544, 2597), 'os.path.join', 'os.path.join', (['tmp_batman_dir', '"""testapp"""', '"""migrations"""'], {}), "(tmp_batman_dir, 'testapp', 'migrations')\n", (2556, 2597), False, 'import os\n'), ((2606, 2627), 'os.makedirs', 'os.makedirs', (['testpath'], {}), '(testpath)\n', (2617, 2627), False, 'import os\n'), ((3130, 3238), 'tests.integration.utils.batman_dir', 'batman_dir', (['{\'hash_dir\': test_hashdir, \'update_on_change\': {\'monkey.txt\':\n "echo -ne \'.\' >> onedot.txt"}}'], {}), '({\'hash_dir\': test_hashdir, \'update_on_change\': {\'monkey.txt\':\n "echo -ne \'.\' >> onedot.txt"}})\n', (3140, 3238), False, 'from tests.integration.utils import batman_dir, update_batman_yml, touch_file\n'), ((547, 588), 'os.path.join', 'os.path.join', (['tmp_batman_dir', '"""cotts.txt"""'], {}), "(tmp_batman_dir, 'cotts.txt')\n", (559, 588), False, 'import os\n'), ((680, 769), 'tests.integration.utils.update_batman_yml', 'update_batman_yml', (['tmp_batman_dir', "{'ensure_symlinks': {'cotts2.txt': 'ravine2.txt'}}"], {}), "(tmp_batman_dir, {'ensure_symlinks': {'cotts2.txt':\n 'ravine2.txt'}})\n", (697, 769), False, 'from tests.integration.utils import batman_dir, update_batman_yml, touch_file\n'), ((901, 943), 'os.path.join', 'os.path.join', (['tmp_batman_dir', '"""cotts2.txt"""'], {}), "(tmp_batman_dir, 'cotts2.txt')\n", (913, 943), False, 'import os\n'), ((1359, 1401), 'os.path.join', 'os.path.join', (['tmp_batman_dir', '"""monkey.txt"""'], {}), "(tmp_batman_dir, 'monkey.txt')\n", (1371, 1401), False, 'import os\n'), ((2008, 2050), 'os.path.join', 'os.path.join', (['tmp_batman_dir', '"""monkey.txt"""'], {}), "(tmp_batman_dir, 'monkey.txt')\n", (2020, 2050), False, 'import os\n'), ((2702, 2738), 'os.path.join', 'os.path.join', (['testpath', '"""imhere.txt"""'], {}), "(testpath, 'imhere.txt')\n", (2714, 2738), False, 'import os\n'), ((3383, 3425), 'os.path.join', 'os.path.join', (['test_hashdir', '"""old_dict.yml"""'], {}), "(test_hashdir, 'old_dict.yml')\n", (3395, 3425), False, 'import os\n'), ((500, 542), 'os.path.join', 'os.path.join', (['tmp_batman_dir', '"""ravine.txt"""'], {}), "(tmp_batman_dir, 'ravine.txt')\n", (512, 542), False, 'import os\n'), ((607, 650), 'os.path.join', 'os.path.join', (['tmp_batman_dir', '""".batman.yml"""'], {}), "(tmp_batman_dir, '.batman.yml')\n", (619, 650), False, 'import os\n'), ((853, 896), 'os.path.join', 'os.path.join', (['tmp_batman_dir', '"""ravine2.txt"""'], {}), "(tmp_batman_dir, 'ravine2.txt')\n", (865, 896), False, 'import os\n'), ((1652, 1696), 'batman.run.run', 'run', (['"""cat onedot.txt"""'], {'in_dir': 'tmp_batman_dir'}), "('cat onedot.txt', in_dir=tmp_batman_dir)\n", (1655, 1696), False, 'from batman.run import run\n'), ((2247, 2291), 'batman.run.run', 'run', (['"""cat onedot.txt"""'], {'in_dir': 'tmp_batman_dir'}), "('cat onedot.txt', in_dir=tmp_batman_dir)\n", (2250, 2291), False, 'from batman.run import run\n'), ((2834, 2876), 'os.path.join', 'os.path.join', (['tmp_batman_dir', '"""imhere.txt"""'], {}), "(tmp_batman_dir, 'imhere.txt')\n", (2846, 2876), False, 'import os\n'), ((2894, 2938), 'batman.run.run', 'run', (['"""cat onedot.txt"""'], {'in_dir': 'tmp_batman_dir'}), "('cat onedot.txt', in_dir=tmp_batman_dir)\n", (2897, 2938), False, 'from batman.run import run\n'), ((4091, 4134), 'batman.run.run', 'run', (['"""cat alpha.txt"""'], {'in_dir': 'tmp_batman_dir'}), "('cat alpha.txt', in_dir=tmp_batman_dir)\n", (4094, 4134), False, 'from batman.run import run\n')] |
""" Provide the ``LoadTest`` class.
"""
# -- Imports -----------------------------------------------------------------
from edafos.viz import LoadTestPlot
import pandas as pd
from edafos import set_units
# -- LoadTest Class ----------------------------------------------------------
class LoadTest(object):
""" Class to represent a new pile load test.
.. warning::
Pay attention to the input units for each unit system that you
choose to use. Refer to the parameter definition below or the
:ref:`input_units` page.
"""
# -- Constructor ---------------------------------------------------------
def __init__(self, unit_system, **kwargs):
"""
Args:
unit_system (str): The unit system for the load test. Can only be
'English', or 'SI'. Properties inherited from the ``Project``
class.
Keyword Args:
name (str): Name of load test. If not specified it will be assigned
a generic "Pile Load Test".
loadtest_type (str): Type of load test. Available options are:
- ``static``: TODO: a lot more to add here
qs_data (list): A list of points where each point is represented by
a ``(Q, S)`` tuple.
- For **SI**: Enter load, :math:`Q`, in **kN** and
displacement, :math:`S`, in **millimeters**.
- For **English**: Enter load, :math:`Q`, in **kip** and
displacement, :math:`S`, in **inches**.
pile (class): Define the pile object that this load test is
associated with.
"""
# -- Check for Unit System -------------------------------------------
if unit_system in ['English', 'SI']:
self.unit_system = unit_system
else:
raise ValueError("Unit system can only be 'English' or 'SI'.")
# -- Check for valid kwargs ------------------------------------------
allowed_keys = ['name', 'loadtest_type', 'qs_data', 'pile']
for key in kwargs:
if key not in allowed_keys:
raise AttributeError("'{}' is not a valid attribute.\nThe "
"allowed attributes are: {}"
"".format(key, allowed_keys))
# -- Assign values ---------------------------------------------------
self.name = kwargs.get('name', 'Pile Load Test')
self.loadtest_type = kwargs.get('loadtest_type', None)
self.qs_data = kwargs.get('qs_data', None)
self.pile = kwargs.get('pile', None)
# -- Check for valid loadtest type -----------------------------------
allowed_loadtest_type = ['static']
if self.loadtest_type in allowed_loadtest_type:
pass
elif self.loadtest_type is None:
raise ValueError("Must specify `loadtest_type`.")
else:
raise ValueError("'{}' not recognized. Pile load test type can "
"only be {}.".format(self.loadtest_type,
allowed_loadtest_type))
# -- Convert Q/S data to DataFrame -----------------------------------
if self.qs_data:
self.qs_data = pd.DataFrame(data=self.qs_data, columns=['Q', 'S'])
# -- Method that returns a plot ------------------------------------------
def plot(self, library='matplotlib', web_embed=False, image_name=None):
""" Method that draws the load test plot.
Args:
library (str): Define the library that sill be used to draw the
plot. Options are 'matplotlib' or 'bokeh'. Default is
'matplotlib'.
web_embed (bool): If True, the plot is returned but not shown or
saved. Used to embed the plot in websites, tested with Flask.
Default is False. Currently only works with the Bokeh library.
image_name (str): Define the filename of the saved image (png
format) of the load test plot. Default is ``None`` and no image
is exported. Note: when 'image_name' is defined, the image is
exported but not shown. Also, plots are exported for the
'matplotlib' library only, the 'bokeh' library (v.0.13.0)
required far to many dependencies to export.
Returns:
A load test plot.
"""
p = LoadTestPlot(unit_system=self.unit_system,
library=library,
web_embed=web_embed,
title=self.name,
q=self.qs_data.Q.values,
s=self.qs_data.S.values,
filename=image_name,
elastic_deflection=self.elastic_deflection(
with_units=False))
return p.draw()
# -- Method that returns the pile elastic deflection ---------------------
def elastic_deflection(self, with_units=True):
""" Method that returns the pile elastic deflection as per Davisson,
1972:
.. math::
\delta = \dfrac{PL}{AE}
Args:
with_units (bool): If true, returns elastic deflection with
units attached (aka as a 'Quantity'). If false, only numerical
results are returned as per the units below.
Returns:
dict: The points defining the elastic deflection line.
- For **SI**: Settlement is in **millimeters** and load
in **kilonewtons**.
- For **English**: Settlement is in **inches** and load
in **kip**.
"""
min_q = 0 * set_units('capacity', self.unit_system)
max_q = self.qs_data.Q.max() * set_units('capacity', self.unit_system)
min_s = 0 * set_units('pile_settlement', self.unit_system)
max_s = max_q / self.pile.aeol()
if with_units:
return {'S': [min_s, max_s], 'Q': [min_q, max_q]}
else:
return {'S': [min_s.magnitude, max_s.magnitude],
'Q': [min_q.magnitude, max_q.magnitude]}
# -- Method that returns the Davisson criterion --------------------------
def davisson_criterion(self, with_units=True):
""" Method that returns the criterion line as per Davisson, 1972:
.. math::
\delta = \dfrac{PL}{AE} + [0.15 \\text{ in } \\textit{ or }
4 \\textrm{ mm }] + \dfrac{b}{120}
Args:
with_units (bool): If true, returns the criterion with
units attached (aka as a 'Quantity'). If false, only numerical
results are returned as per the units below.
Returns:
dict: The points defining the criterion line.
- For **SI**: Settlement is in **millimeters** and load
in **kilonewtons**.
- For **English**: Settlement is in **inches** and load
in **kip**.
"""
min_s_elastic = self.elastic_deflection()['S'][0]
max_s_elastic = self.elastic_deflection()['S'][1]
if self.unit_system == 'SI':
crit = 3.81 * set_units('pile_settlement', self.unit_system)
else:
crit = 0.15 * set_units('pile_settlement', self.unit_system)
min_s = min_s_elastic + crit + self.pile.diameter/120
return min_s
| [
"pandas.DataFrame",
"edafos.set_units"
] | [((3317, 3368), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'self.qs_data', 'columns': "['Q', 'S']"}), "(data=self.qs_data, columns=['Q', 'S'])\n", (3329, 3368), True, 'import pandas as pd\n'), ((5810, 5849), 'edafos.set_units', 'set_units', (['"""capacity"""', 'self.unit_system'], {}), "('capacity', self.unit_system)\n", (5819, 5849), False, 'from edafos import set_units\n'), ((5889, 5928), 'edafos.set_units', 'set_units', (['"""capacity"""', 'self.unit_system'], {}), "('capacity', self.unit_system)\n", (5898, 5928), False, 'from edafos import set_units\n'), ((5950, 5996), 'edafos.set_units', 'set_units', (['"""pile_settlement"""', 'self.unit_system'], {}), "('pile_settlement', self.unit_system)\n", (5959, 5996), False, 'from edafos import set_units\n'), ((7306, 7352), 'edafos.set_units', 'set_units', (['"""pile_settlement"""', 'self.unit_system'], {}), "('pile_settlement', self.unit_system)\n", (7315, 7352), False, 'from edafos import set_units\n'), ((7393, 7439), 'edafos.set_units', 'set_units', (['"""pile_settlement"""', 'self.unit_system'], {}), "('pile_settlement', self.unit_system)\n", (7402, 7439), False, 'from edafos import set_units\n')] |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#------------------------------------------------------------------------------
from atom.api import Event, Typed, Unicode
from atom.datastructures.api import sortedmap
from .declarative_meta import DeclarativeMeta
from .expression_engine import ExpressionEngine
from .object import Object, flag_generator, flag_property
from enaml.compat import with_metaclass
def d_(member, readable=True, writable=True, final=True):
""" Mark an Atom member as bindable from Enaml syntax.
Parameters
----------
member : Member
The atom member to mark as bindable from Enaml syntax.
readable : bool, optional
Whether the member is readable from Enaml syntax. The member
must be readable to use the '>>', ':=', and '::' operators.
The default is True.
writable : bool, optional
Whether the member is writable from Enaml syntax. The member
must be writable to use the '=', '<<', and ':=' operators.
The default is True.
final : bool, optional
Whether or not the member can be redefined from Enaml syntax
using the 'attr' keyword. The default is True and indicates
that the member cannot be overridden.
"""
metadata = member.metadata
if metadata is None:
metadata = member.metadata = {}
metadata['d_member'] = True
metadata['d_readable'] = readable
metadata['d_writable'] = writable
metadata['d_final'] = final
return member
def d_func(func):
""" Mark a method as overridable from Enaml syntax.
Parameters
----------
func : FunctionType
The function to tag as declarative.
Returns
-------
result : func
The original function tagged with the compiler metadata.
"""
func._d_func = True
return func
#: The flag indicating that the Declarative object has been initialized.
INITIALIZED_FLAG = next(flag_generator)
class Declarative(with_metaclass(DeclarativeMeta, Object)):
""" The most base class of the Enaml declarative objects.
This class provides the core functionality required of declarative
Enaml types. It can be used directly in a declarative Enaml object
tree to store and react to state changes. It has no concept of a
visual representation; that functionality is added by subclasses.
"""
#: Export the 'name' attribute as a declarative member.
name = d_(Unicode())
#: An event fired when an object is initialized. It is triggered
#: once during the object lifetime, at the end of the initialize
#: method.
initialized = d_(Event(), writable=False)
#: A property which gets and sets the initialized flag. This should
#: not be manipulated directly by user code.
is_initialized = flag_property(INITIALIZED_FLAG)
#: Storage space for the declarative runtime. This value should not
#: be manipulated by user code.
_d_storage = Typed(sortedmap, ())
#: Storage space for the declarative engine. This value should not
#: be manipulated by user code.
_d_engine = Typed(ExpressionEngine)
def initialize(self):
""" Initialize this object all of its children recursively.
This is called to give the objects in the tree the opportunity
to initialize additional state which depends upon the object
tree being fully built. It is the responsibility of external
code to call this method at the appropriate time. This will
emit the `initialized` signal after all of the children have
been initialized.
"""
# Iterate over a copy since the children add and remove
# other children during initialization.
for child in self.children[:]:
if isinstance(child, Declarative):
child.initialize()
self.is_initialized = True
self.initialized()
def destroy(self):
""" An overridden destructor method for declarative cleanup.
"""
self.is_initialized = False
del self._d_storage
del self._d_engine
super(Declarative, self).destroy()
def child_added(self, child):
""" An overridden child added event handler.
This handler will automatically initialize a declarative child
if this object itself has already been initialized.
"""
super(Declarative, self).child_added(child)
if isinstance(child, Declarative):
if self.is_initialized and not child.is_initialized:
child.initialize()
| [
"enaml.compat.with_metaclass",
"atom.api.Unicode",
"atom.api.Event",
"atom.api.Typed"
] | [((2199, 2238), 'enaml.compat.with_metaclass', 'with_metaclass', (['DeclarativeMeta', 'Object'], {}), '(DeclarativeMeta, Object)\n', (2213, 2238), False, 'from enaml.compat import with_metaclass\n'), ((3181, 3201), 'atom.api.Typed', 'Typed', (['sortedmap', '()'], {}), '(sortedmap, ())\n', (3186, 3201), False, 'from atom.api import Event, Typed, Unicode\n'), ((3326, 3349), 'atom.api.Typed', 'Typed', (['ExpressionEngine'], {}), '(ExpressionEngine)\n', (3331, 3349), False, 'from atom.api import Event, Typed, Unicode\n'), ((2669, 2678), 'atom.api.Unicode', 'Unicode', ([], {}), '()\n', (2676, 2678), False, 'from atom.api import Event, Typed, Unicode\n'), ((2855, 2862), 'atom.api.Event', 'Event', ([], {}), '()\n', (2860, 2862), False, 'from atom.api import Event, Typed, Unicode\n')] |
'''Utility functions and classes for handling image datasets.'''
import cPickle
import cv2
import os.path as osp
import numpy as np
import tensorflow as tf
from config_tfvgg import cfg
FLAGS = tf.app.flags.FLAGS
def get_facebox_dims(img_shape,face_bbox,target_size,crop_size,spec,crop_ind):
face_bbox = np.zeros_like(face_bbox)
center = np.floor(np.array([face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]]) / 2)
dims = np.array([face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]]) * scale
face_bbox[0] = max(0, (center[0] - dims[0] / 2).astype(np.int32))
face_bbox[2] = min(img_shape[1], (center[0] + dims[0] / 2).astype(np.int32))
face_bbox[1] = max(0, (center[1] - dims[1] / 2).astype(np.int32))
face_bbox[3] = min(img_shape[0], (center[1] + dims[1] / 2).astype(np.int32))
(scale, isotropic, crop, mean) = (spec.scale_size, spec.isotropic, spec.crop_size)
img_shape = np.array((face_bbox[3]-face_bbox[1]+1,face_bbox[2]-face_bbox[0]+1))
min_length = np.min(img_shape)
new_shape = np.ceil((target_size * 1.0 / min_length) * img_shape)
offset = ((new_shape - crop) / 2).astype(np.int32)
return new_shape,offset
def process_image_reg(img_path,spec, flip=False, crop_ind=0, face_bbox=None,face_box_scale=1):
'''Crops, scales, and normalizes the given image.
scale : The image wil be first scaled to this size.
If isotropic is true, the smaller side is rescaled to this,
preserving the aspect ratio.
crop : After scaling, depending on crop_ind a crop of the image is given.
crope_ind: 0 center, 1 SW, 2 SE, 3 NE, 4 NW crop
flip: Whether to flip the image
mean : Subtracted from the image
'''
(scale, isotropic, crop, mean) = (spec.scale_size, spec.isotropic, spec.crop_size, spec.mean)
img = cv2.imread(img_path)
if face_bbox is not None:
face_bbox = np.array(face_bbox)
center =np.floor(np.array([face_bbox[2]+face_bbox[0],face_bbox[3]+face_bbox[1]])/2)
dims =np.array([face_bbox[2]-face_bbox[0],face_bbox[3]-face_bbox[1]]) * face_box_scale
face_bbox[0] = max(0,(center[0] - dims[0] / 2).astype(np.int32))
face_bbox[2] = min(img.shape[1],(center[0] + dims[0] / 2).astype(np.int32))
face_bbox[1] = max(0,(center[1] - dims[1] / 2).astype(np.int32))
face_bbox[3] = min(img.shape[0],(center[1] + dims[1] / 2).astype(np.int32))
img = img[face_bbox[1]:face_bbox[3],face_bbox[0]:face_bbox[2],:]
# Rescale
if flip:
img = img[:,::-1,:]
if isotropic:
img_shape = np.array(img.shape[:2])
min_length = np.min(img_shape)
new_shape = np.ceil((scale *1.0/ min_length) * img_shape)
else:
new_shape = np.array([scale, scale])
img = cv2.resize(img, tuple(new_shape.astype(np.int32).tolist()[::-1]))
offset = [0,0]
if crop_ind == 1:
offset[0] = new_shape[0]-crop
offset = new_shape-crop
elif crop_ind == 2:
offset = new_shape-crop
elif crop_ind == 3:
offset[1] = new_shape[1]-crop
elif crop_ind == 4:
offset = [0,0]
else:
offset = ((new_shape - crop) / 2).astype(np.int32)
img = img[offset[0]:offset[0]+crop,offset[1]:offset[1]+crop,:]
# Mean subtraction
return img.astype(np.float) - mean
def process_image(img, scale, isotropic, crop, mean, flip=False, crop_ind=0, face_bbox=None):
'''Crops, scales, and normalizes the given image.
scale : The image wil be first scaled to this size.
If isotropic is true, the smaller side is rescaled to this,
preserving the aspect ratio.
crop : After scaling, depending on crop_ind a crop of the image is given.
crope_ind: 0 center, 1 SW, 2 SE, 3 NE, 4 NW crop
flip: Whether to flip the image
mean : Subtracted from the image
'''
if face_bbox is not None:
img = tf.slice(img, begin=tf.pack([face_bbox[0], face_bbox[1], 0]), size=tf.pack([face_bbox[2]-face_bbox[0], face_bbox[3]-face_bbox[1], -1]))
# Rescale
if flip:
img = tf.reverse(img,[False,True,False])
if isotropic:
img_shape = tf.to_float(tf.shape(img)[:2])
min_length = tf.minimum(img_shape[0], img_shape[1])
new_shape = tf.to_int32((scale / min_length) * img_shape)
else:
new_shape = tf.pack([scale, scale])
img = tf.image.resize_images(img, new_shape)
offset = [0,0]
if crop_ind == 1:
offset[0] = new_shape[0]-crop
offset = new_shape-crop
elif crop_ind == 2:
offset = new_shape-crop
elif crop_ind == 3:
offset[1] = new_shape[1]-crop
elif crop_ind == 4:
offset = [0,0]
else:
offset = (new_shape - crop) / 2
img = tf.slice(img, begin=tf.pack([offset[0], offset[1], 0]), size=tf.pack([crop, crop, -1]))
# Mean subtraction
return tf.to_float(img) - mean
class ImageProducer(object):
'''
Loads and processes batches of images in parallel.
'''
def __init__(self, image_paths, data_spec, num_concurrent=4, batch_size=None, labels=None):
# The data specifications describe how to process the image
self.data_spec = data_spec
# A list of full image paths
self.image_paths = image_paths
# An optional list of labels corresponding to each image path
self.labels = labels
# A boolean flag per image indicating whether its a JPEG or PNG
self.extension_mask = self.create_extension_mask(self.image_paths)
# Create the loading and processing operations
self.setup(batch_size=batch_size, num_concurrent=num_concurrent)
def start(self, session, coordinator, num_concurrent=4):
'''Start the processing worker threads.'''
# Queue all paths
session.run(self.enqueue_paths_op)
# Close the path queue
session.run(self.close_path_queue_op)
# Start the queue runner and return the created threads
return self.queue_runner.create_threads(session, coord=coordinator, start=True)
def get(self, session):
'''
Get a single batch of images along with their indices. If a set of labels were provided,
the corresponding labels are returned instead of the indices.
'''
(indices, images) = session.run(self.dequeue_op)
if self.labels is not None:
labels = [self.labels[idx] for idx in indices]
return (labels, images)
return (indices, images)
def batches(self, session):
'''Yield a batch until no more images are left.'''
for _ in xrange(self.num_batches):
yield self.get(session=session)
def load_image(self, image_path, is_jpeg):
# Read the file
file_data = tf.read_file(image_path)
# Decode the image data
img = tf.cond(
is_jpeg,
lambda: tf.image.decode_jpeg(file_data, channels=self.data_spec.channels),
lambda: tf.image.decode_png(file_data, channels=self.data_spec.channels))
if self.data_spec.expects_bgr:
# Convert from RGB channel ordering to BGR
# This matches, for instance, how OpenCV orders the channels.
img = tf.reverse(img, [False, False, True])
return img
def process(self,crop_flip):
# Dequeue a single image path
idx, is_jpeg, image_path = self.path_bbox_queue.dequeue()
# Load the image
# Process the image
img_list = []
idx_list = []
for (c,f) in crop_flip:
img = self.load_image(image_path, is_jpeg)
processed_img = process_image(img=img,
scale=self.data_spec.scale_size,
isotropic=self.data_spec.isotropic,
crop=self.data_spec.crop_size,
mean=self.data_spec.mean,
flip=f,
crop_ind=c)
img_list.append(processed_img)
idx_list.append(idx)
# Return the processed image, along with its index
processed_idx_list = tf.pack(idx_list)
processed_img_list = tf.pack(img_list)
return (processed_idx_list, processed_img_list)
@staticmethod
def create_extension_mask(paths):
def is_jpeg(path):
extension = osp.splitext(path)[-1].lower()
if extension in ('.jpg', '.jpeg'):
return True
if extension != '.png':
raise ValueError('Unsupported image format: {}'.format(extension))
return False
return [is_jpeg(p) for p in paths]
def __len__(self):
return len(self.image_paths)
def setup(self, batch_size, num_concurrent):
pass
class VGGFaceProducer(ImageProducer):
def __init__(self, image_paths, data_spec ,num_concurrent=4,bbox_fp=None,labels=None):
round_rect = lambda x: [int(p) for p in x]
try:
v = self.face_bboxes
except AttributeError:
self.face_bboxes = None
if bbox_fp is not None:
face_bboxes=cPickle.load(open(bbox_fp,'r'))
self.face_bboxes = [round_rect(face_bboxes[p][0]) for p in image_paths]
# Initialize base
super(VGGFaceProducer, self).__init__(image_paths=image_paths,
data_spec=data_spec,num_concurrent=num_concurrent,labels=labels)
def setup(self, batch_size, num_concurrent):
# Validate the batch size
num_images = len(self.image_paths)
batch_size = min(num_images, batch_size or self.data_spec.batch_size)
if num_images % batch_size != 0:
raise ValueError(
'The total number of images ({}) must be divisible by the batch size ({}).'.format(
num_images, batch_size))
self.num_batches = num_images / batch_size
# Create a queue that will contain image paths (and their indices and extension indicator)
if self.face_bboxes is None:
self.path_bbox_queue = tf.FIFOQueue(capacity=num_images,
dtypes=[tf.int32, tf.bool, tf.string],
name='path_queue')
indices = tf.range(num_images)
self.enqueue_paths_op = self.path_bbox_queue.enqueue_many([indices, self.extension_mask,
self.image_paths])
else:
self.path_bbox_queue = tf.FIFOQueue(capacity=num_images,
dtypes=[tf.int32, tf.bool, tf.string, tf.int32],
name='path_queue')
indices = tf.range(num_images)
self.enqueue_paths_op = self.path_bbox_queue.enqueue_many([indices, self.extension_mask,
self.image_paths,self.face_bboxes])
# Close the path queue (no more additions)
self.close_path_queue_op = self.path_bbox_queue.close()
# Create an operation that dequeues a single path and returns a processed image
crop_flip = [[0,False]]
if cfg.CROP:
for i in range(1,5):
crop_flip.append([i,False])
if cfg.FLIP:
for i in range(len(crop_flip)):
crop_flip.append((crop_flip[i][0],True))
(processed_idx_list,processed_img_list) = self.process(crop_flip)
# Create a queue that will contain the processed images (and their indices)
image_shape = (self.data_spec.crop_size, self.data_spec.crop_size, self.data_spec.channels)
processed_queue = tf.FIFOQueue(capacity=int(np.ceil(len(crop_flip)*num_images / float(num_concurrent))),
dtypes=[tf.int32, tf.float32],
shapes=[(), image_shape],
name='processed_queue')
# Enqueue the processed image and path
enqueue_processed_op = processed_queue.enqueue_many([processed_idx_list,processed_img_list])
# Create a dequeue op that fetches a batch of processed images off the queue
[self.ind_deq,self.img_deq] = processed_queue.dequeue_many(batch_size)
self.dequeue_op = [self.ind_deq,self.img_deq]
# Create a queue runner to perform the processing operations in parallel
num_concurrent = min(num_concurrent, num_images)
self.queue_runner = tf.train.QueueRunner(processed_queue,
[enqueue_processed_op] * num_concurrent)
self.num_imgs = len(crop_flip)*num_images
self.num_feats_per_image = len(crop_flip)
def process(self,crop_flip):
# Dequeue a single image path
if self.face_bboxes is None:
idx, is_jpeg, image_path = self.path_bbox_queue.dequeue()
face_bbox = None
else:
idx, is_jpeg, image_path, face_bbox = self.path_bbox_queue.dequeue()
# Load the image
# Process the image
img_list = []
idx_list = []
for (c,f) in crop_flip:
img = self.load_image(image_path, is_jpeg)
processed_img = process_image(img=img,
scale=self.data_spec.scale_size,
isotropic=self.data_spec.isotropic,
crop=self.data_spec.crop_size,
mean=self.data_spec.mean,
flip=f,
crop_ind=c,
face_bbox=face_bbox)
img_list.append(processed_img)
idx_list.append(idx)
# Return the processed image, along with its index
processed_idx_list = tf.pack(idx_list)
processed_img_list = tf.pack(img_list)
return (processed_idx_list, processed_img_list)
class LFWProducer(VGGFaceProducer):
def __init__(self, val_path, data_path, data_spec,bbox_fp=None,num_concurrent=4,labels=None):
round_rect = lambda x: [int(p) for p in x]
image_paths = [osp.join(data_path, p) for p in val_path]
self.face_bboxes=None
if bbox_fp is not None:
face_bboxes=cPickle.load(open(bbox_fp,'r'))
self.face_bboxes = [round_rect(face_bboxes[p][0]) for p in val_path]
super(LFWProducer, self).__init__(image_paths=image_paths,
data_spec=data_spec,num_concurrent=num_concurrent,labels=labels)
| [
"tensorflow.image.resize_images",
"tensorflow.shape",
"tensorflow.read_file",
"numpy.array",
"tensorflow.FIFOQueue",
"numpy.min",
"numpy.ceil",
"tensorflow.reverse",
"os.path.splitext",
"tensorflow.to_int32",
"tensorflow.range",
"cv2.imread",
"tensorflow.minimum",
"tensorflow.image.decode_... | [((309, 333), 'numpy.zeros_like', 'np.zeros_like', (['face_bbox'], {}), '(face_bbox)\n', (322, 333), True, 'import numpy as np\n'), ((925, 1001), 'numpy.array', 'np.array', (['(face_bbox[3] - face_bbox[1] + 1, face_bbox[2] - face_bbox[0] + 1)'], {}), '((face_bbox[3] - face_bbox[1] + 1, face_bbox[2] - face_bbox[0] + 1))\n', (933, 1001), True, 'import numpy as np\n'), ((1010, 1027), 'numpy.min', 'np.min', (['img_shape'], {}), '(img_shape)\n', (1016, 1027), True, 'import numpy as np\n'), ((1044, 1095), 'numpy.ceil', 'np.ceil', (['(target_size * 1.0 / min_length * img_shape)'], {}), '(target_size * 1.0 / min_length * img_shape)\n', (1051, 1095), True, 'import numpy as np\n'), ((1826, 1846), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (1836, 1846), False, 'import cv2\n'), ((4373, 4411), 'tensorflow.image.resize_images', 'tf.image.resize_images', (['img', 'new_shape'], {}), '(img, new_shape)\n', (4395, 4411), True, 'import tensorflow as tf\n'), ((441, 509), 'numpy.array', 'np.array', (['[face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]]'], {}), '([face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]])\n', (449, 509), True, 'import numpy as np\n'), ((1898, 1917), 'numpy.array', 'np.array', (['face_bbox'], {}), '(face_bbox)\n', (1906, 1917), True, 'import numpy as np\n'), ((2588, 2611), 'numpy.array', 'np.array', (['img.shape[:2]'], {}), '(img.shape[:2])\n', (2596, 2611), True, 'import numpy as np\n'), ((2633, 2650), 'numpy.min', 'np.min', (['img_shape'], {}), '(img_shape)\n', (2639, 2650), True, 'import numpy as np\n'), ((2671, 2716), 'numpy.ceil', 'np.ceil', (['(scale * 1.0 / min_length * img_shape)'], {}), '(scale * 1.0 / min_length * img_shape)\n', (2678, 2716), True, 'import numpy as np\n'), ((2747, 2771), 'numpy.array', 'np.array', (['[scale, scale]'], {}), '([scale, scale])\n', (2755, 2771), True, 'import numpy as np\n'), ((4078, 4115), 'tensorflow.reverse', 'tf.reverse', (['img', '[False, True, False]'], {}), '(img, [False, True, False])\n', (4088, 4115), True, 'import tensorflow as tf\n'), ((4204, 4242), 'tensorflow.minimum', 'tf.minimum', (['img_shape[0]', 'img_shape[1]'], {}), '(img_shape[0], img_shape[1])\n', (4214, 4242), True, 'import tensorflow as tf\n'), ((4263, 4306), 'tensorflow.to_int32', 'tf.to_int32', (['(scale / min_length * img_shape)'], {}), '(scale / min_length * img_shape)\n', (4274, 4306), True, 'import tensorflow as tf\n'), ((4339, 4362), 'tensorflow.pack', 'tf.pack', (['[scale, scale]'], {}), '([scale, scale])\n', (4346, 4362), True, 'import tensorflow as tf\n'), ((4871, 4887), 'tensorflow.to_float', 'tf.to_float', (['img'], {}), '(img)\n', (4882, 4887), True, 'import tensorflow as tf\n'), ((6770, 6794), 'tensorflow.read_file', 'tf.read_file', (['image_path'], {}), '(image_path)\n', (6782, 6794), True, 'import tensorflow as tf\n'), ((8224, 8241), 'tensorflow.pack', 'tf.pack', (['idx_list'], {}), '(idx_list)\n', (8231, 8241), True, 'import tensorflow as tf\n'), ((8271, 8288), 'tensorflow.pack', 'tf.pack', (['img_list'], {}), '(img_list)\n', (8278, 8288), True, 'import tensorflow as tf\n'), ((12703, 12781), 'tensorflow.train.QueueRunner', 'tf.train.QueueRunner', (['processed_queue', '([enqueue_processed_op] * num_concurrent)'], {}), '(processed_queue, [enqueue_processed_op] * num_concurrent)\n', (12723, 12781), True, 'import tensorflow as tf\n'), ((14098, 14115), 'tensorflow.pack', 'tf.pack', (['idx_list'], {}), '(idx_list)\n', (14105, 14115), True, 'import tensorflow as tf\n'), ((14145, 14162), 'tensorflow.pack', 'tf.pack', (['img_list'], {}), '(img_list)\n', (14152, 14162), True, 'import tensorflow as tf\n'), ((356, 424), 'numpy.array', 'np.array', (['[face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]]'], {}), '([face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]])\n', (364, 424), True, 'import numpy as np\n'), ((2024, 2092), 'numpy.array', 'np.array', (['[face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]]'], {}), '([face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]])\n', (2032, 2092), True, 'import numpy as np\n'), ((4769, 4803), 'tensorflow.pack', 'tf.pack', (['[offset[0], offset[1], 0]'], {}), '([offset[0], offset[1], 0])\n', (4776, 4803), True, 'import tensorflow as tf\n'), ((4810, 4835), 'tensorflow.pack', 'tf.pack', (['[crop, crop, -1]'], {}), '([crop, crop, -1])\n', (4817, 4835), True, 'import tensorflow as tf\n'), ((7230, 7267), 'tensorflow.reverse', 'tf.reverse', (['img', '[False, False, True]'], {}), '(img, [False, False, True])\n', (7240, 7267), True, 'import tensorflow as tf\n'), ((10206, 10301), 'tensorflow.FIFOQueue', 'tf.FIFOQueue', ([], {'capacity': 'num_images', 'dtypes': '[tf.int32, tf.bool, tf.string]', 'name': '"""path_queue"""'}), "(capacity=num_images, dtypes=[tf.int32, tf.bool, tf.string],\n name='path_queue')\n", (10218, 10301), True, 'import tensorflow as tf\n'), ((10408, 10428), 'tensorflow.range', 'tf.range', (['num_images'], {}), '(num_images)\n', (10416, 10428), True, 'import tensorflow as tf\n'), ((10665, 10771), 'tensorflow.FIFOQueue', 'tf.FIFOQueue', ([], {'capacity': 'num_images', 'dtypes': '[tf.int32, tf.bool, tf.string, tf.int32]', 'name': '"""path_queue"""'}), "(capacity=num_images, dtypes=[tf.int32, tf.bool, tf.string, tf.\n int32], name='path_queue')\n", (10677, 10771), True, 'import tensorflow as tf\n'), ((10885, 10905), 'tensorflow.range', 'tf.range', (['num_images'], {}), '(num_images)\n', (10893, 10905), True, 'import tensorflow as tf\n'), ((14428, 14450), 'os.path.join', 'osp.join', (['data_path', 'p'], {}), '(data_path, p)\n', (14436, 14450), True, 'import os.path as osp\n'), ((1943, 2011), 'numpy.array', 'np.array', (['[face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]]'], {}), '([face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]])\n', (1951, 2011), True, 'import numpy as np\n'), ((3920, 3960), 'tensorflow.pack', 'tf.pack', (['[face_bbox[0], face_bbox[1], 0]'], {}), '([face_bbox[0], face_bbox[1], 0])\n', (3927, 3960), True, 'import tensorflow as tf\n'), ((3967, 4038), 'tensorflow.pack', 'tf.pack', (['[face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1], -1]'], {}), '([face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1], -1])\n', (3974, 4038), True, 'import tensorflow as tf\n'), ((4164, 4177), 'tensorflow.shape', 'tf.shape', (['img'], {}), '(img)\n', (4172, 4177), True, 'import tensorflow as tf\n'), ((6891, 6956), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (['file_data'], {'channels': 'self.data_spec.channels'}), '(file_data, channels=self.data_spec.channels)\n', (6911, 6956), True, 'import tensorflow as tf\n'), ((6978, 7042), 'tensorflow.image.decode_png', 'tf.image.decode_png', (['file_data'], {'channels': 'self.data_spec.channels'}), '(file_data, channels=self.data_spec.channels)\n', (6997, 7042), True, 'import tensorflow as tf\n'), ((8454, 8472), 'os.path.splitext', 'osp.splitext', (['path'], {}), '(path)\n', (8466, 8472), True, 'import os.path as osp\n')] |
#!/usr/bin/env python3
#######################################################################################################################
# Licensed Materials –Property of HCL Technologies Ltd.
# © Copyright HCL Technologies Ltd. 2020.
# All rights reserved. See product license for details. US Government Users Restricted Rights. Use, duplication,
# or disclosure restricted by GSA ADP Schedule Contract with HCL Technologies Ltd. Java and all Java-based trademarks
# and logos are trademarks or registered trademarks of Oracle and/or its affiliates. HCL, the HCL logo,
# and Tivoli are registered trademarks of HCL Technologies in the United States, other countries, or both.
#######################################################################################################################
import inspect
import json
import logging
import time
import requests
from .IastUtils import IastException
from .RequestApi import post_request, get_request, delete_request, download_request, put_request
ASOC_IAST_API = "https://cloud.appscan.com/IAST/"
ASOC_API = "https://cloud.appscan.com/api/v2"
zip_filename = 'IASTAgent.zip'
####################################################################
# ASOC - IAST API https://stage.cloud.appscan.com/IAST/swagger/ui/
####################################################################
def url_join(*arguments):
return '/'.join([argument.strip('/') for argument in arguments])
# start new execution directly from ASoC IAST interface
# Swagger: https://cloud.appscan.com/IAST/swagger/ui/index#!/IAST/IAST_StartNewExecution
# request URL : POST https://cloud.appscan.com/IAST/api/StartNewExecution
# headers: "Authorization=Bearer <accessToken>"
def start_new_execution(agent_key: str, host=ASOC_IAST_API, retries=0) -> str:
url = url_join(host, "api/StartNewExecution")
headers = {"Authorization": "Bearer " + agent_key}
json_response = None
try:
response = post_request(url, headers=headers, timeout=30, retries=retries)
json_response = json.loads(response.text)
logging.info("Started new execution with id: " + json_response["ExecutionId"])
return json_response["ExecutionId"]
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + "failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# stop current execution directly from ASoC IAST interface
# Swagger: https://cloud.appscan.com/IAST/swagger/ui/index#!/IAST/IAST_StopExecution
# request URL : POST https://cloud.appscan.com/IAST/api/StopExecution
# headers: "Authorization=Bearer <accessToken>"
def stop_execution(agent_key: str, host=ASOC_IAST_API, retries=0) -> None:
url = url_join(host, "/api/StopExecution")
headers = {"Authorization": "Bearer " + agent_key}
try:
post_request(url, headers=headers, timeout=30, retries=retries)
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
# Downloads zip file with IAST agent war inside - no asoc-config.json - need to set manually token
# Swagger: https://cloud.appscan.com/IAST/swagger/ui/index#!/IAST/IAST_DownloadVersion
# request URL : GET https://cloud.appscan.com/IAST/api/DownloadVersion
# headers: "Authorization=Bearer <accessToken>"
def download_agent(agent_key: str, host=ASOC_IAST_API, retries=0) -> None:
url = url_join(host, "/api/DownloadVersion")
headers = {"Authorization": "Bearer " + agent_key}
try:
download_request(url, headers=headers, timeout=30, retries=retries)
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
# Downloads zip file with IAST agent war inside - with asoc-config.json - ready to work
# note it will disable previous token for this scan
# Swagger: https://cloud.appscan.com/api/V2/Tools/IAST/DownloadWithKey
# request URL : GET https://cloud.appscan.com/IAST/api/DownloadVersion
# headers: "Authorization=Bearer <accessToken>"
def download_agent_with_key(token: str, scan_id: str, host=ASOC_API) -> None:
url = url_join(host, "/Tools/IAST/DownloadWithKey")
headers = {"Accept": "text/plain", "Authorization": "Bearer " + token}
params = {'scanId': scan_id}
try:
download_request(url, headers=headers, timeout=30, params=params)
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
#####################################################
# ASOC - API https://cloud.appscan.com/swagger/ui/
#####################################################
# Authenticate using the API Key ID / Secret.Return a Bearer Token used for all other REST APIs
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Account/Account_ApiKeyLogin
# request URL : POST https://cloud.appscan.com/api/V2/Account/ApiKeyLogin
# json: { "KeyId" : "aaa" , "KeySecret" : "bbb" }
def get_api_key_login(key_id, key_secret, host=ASOC_API, retries=0):
api_key = {
"KeyId": key_id,
"KeySecret": key_secret
}
url = url_join(host, "/Account/ApiKeyLogin")
headers = {"Accept": "application/json"}
json_response = None
try:
response = post_request(url, headers=headers, json_body=api_key, retries=retries, timeout=30)
json_response = json.loads(response.text)
token = json_response["Token"]
logging.info("token: " + token)
return token
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + "failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/AssetGroups/AssetGroups_GetAssetGroups
# request URL : GET https://cloud.appscan.com/api/V2/AssetGroups
# params: "$filter=IsDefault eq true, $select=Id"
# headers: "Authorization=Bearer <token>"
def get_default_asset_group(token, host=ASOC_API):
url = url_join(host, "/AssetGroups")
params = {"$filter": "IsDefault eq true", "$select": "Id"}
headers = {"Accept": "application/json", "Authorization": "Bearer " + token}
try:
response = get_request(url, params=params, headers=headers, timeout=30)
json_response = json.loads(response.text)
if len(json_response) == 0:
raise IastException("Error - No default asset group found.")
asset_group_id = json_response[0]["Id"]
return asset_group_id
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + "failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
#####################################################
# ASOC - Apps API
#####################################################
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Apps/Apps_CreateApp
# request URL : POST https://cloud.appscan.com/api/V2/Apps
# headers: "Authorization=Bearer <token>"
def create_app(token, app_name, asset_group, host=ASOC_API, retries=0):
app_model = {
"Name": app_name,
"AssetGroupId": asset_group
}
url = url_join(host, "/Apps")
headers = {"Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer " + token}
json_response = None
try:
response = post_request(url, headers=headers, json_body=app_model, retries=retries, timeout=30)
json_response = json.loads(response.text)
app_id = json_response["Id"]
return app_id
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Apps/Apps_GetApp
# request URL : GET https://cloud.appscan.com/api/V2/Apps
# headers: "Authorization=Bearer <token>"
# params: "id=<appId>"
def get_app_name_by_id(app_id, token, host=ASOC_API):
url = url_join(host, "/Apps")
headers = {"Accept": "application/json", "Authorization": "Bearer " + token}
params = {"id": app_id}
try:
response = get_request(url, params=params, headers=headers, timeout=30)
json_response = json.loads(response.text)
app_name = json_response["Name"]
return app_name
except IastException as e:
if 'Client Error: 400' in str(e):
return None
else:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Apps/Apps_GetApps
# request URL : GET https://cloud.appscan.com/api/V2/Apps
# headers: "Authorization=Bearer <token>"
# params: "$filter=Name eq <appName>, $select=Id"
def get_app_id_by_name(app_name, token, host=ASOC_API):
url = url_join(host, "/Apps")
headers = {"Accept": "application/json", "Authorization": "Bearer " + token}
params = {"$filter": f"Name eq '{app_name}'", "$select": "Id"}
try:
response = get_request(url, params=params, headers=headers, timeout=30)
json_response = json.loads(response.text)
if len(json_response) == 0:
return None
app_id = json_response[0]["Id"]
return app_id
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Apps/Apps_DeleteApp
# request URL : DELETE https://cloud.appscan.com/api/V2/Apps/<app_id>
# headers: "Authorization=Bearer <token>"
# params: "id=<appId>"
def delete_app(app_id, token, host=ASOC_API, retries=0):
url = url_join(host, "Apps", app_id)
headers = {"Accept": "text/plain", "Authorization": "Bearer " + token}
try:
delete_request(url, headers=headers, retries=retries, timeout=60)
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
#####################################################
# ASOC - scan API
#####################################################
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Scans/Scans_CreateIastAnalyzerScan
# request URL : POST https://cloud.appscan.com/api/V2/Scans/IASTAnalyzer
# headers: "Authorization=Bearer <token>, Accept: application/json, Content-Type: application/json"
# json: {
# "ConnLostStopTimer": "",
# "ScanName": <scanName>,
# "EnableMailNotification": True,
# "Locale": "en-US",
# "AppId": <appId>,
# "Personal": False,
# "AgentType": "Java" - one of: Java, DotNet, NodeJS
# }
def create_scan(app_id, token, scan_name, host=ASOC_API, retries=0, is_personal=False, agent_type='Java', config_file_id=None):
scan_model = {
"ConnLostStopTimer": "", # Timeout in minutes to stop scan after agent connection lost
"ScanName": scan_name,
"EnableMailNotification": True,
"Locale": "en-US",
"AppId": app_id,
"Personal": is_personal,
"AgentType": agent_type,
}
if config_file_id != None:
scan_model.update({"ConfigFileId": config_file_id})
url = url_join(host, "/Scans/IASTAnalyzer")
headers = {"Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer " + token}
json_response = None
try:
response = post_request(url, headers=headers, json_body=scan_model, retries=retries, timeout=60)
json_response = json.loads(response.text)
agent_key = json_response["Agentkey"]
scan_id = json_response["Id"]
logging.info("agent_key: " + agent_key)
logging.info("scan_id: " + scan_id)
return agent_key, scan_id
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Scans/Scans_GetScan
# request URL : GET https://cloud.appscan.com/api/V2/Scans
# headers: "Authorization=Bearer <token>"
# params: "scanId=<scanId>"
def get_scan_info_by_id(scan_id, token, host=ASOC_API):
url = url_join(host, "/Scans")
headers = {"Accept": "application/json", "Authorization": "Bearer " + token}
params = {"scanId": scan_id}
try:
response = get_request(url, params=params, headers=headers, timeout=30)
json_response = json.loads(response.text)
scan_name = json_response["Name"]
app_name = json_response["AppName"]
app_id = json_response["AppId"]
return scan_name, app_name, app_id
except IastException as e:
if 'Client Error: 400' in str(e):
return None
else:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException("KeyError:" + str(e) + " not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Scans/Scans_GetScans
# request URL : GET https://cloud.appscan.com/api/V2/Scans
# headers: "Authorization=Bearer <token>"
# params: "$filter=Name eq <scanName>"
def get_scan_info_by_name(scan_name, token, host=ASOC_API):
url = url_join(host, "Scans")
headers = {"Accept": "application/json", "Authorization": "Bearer " + token}
params = {"$filter": f"Name eq '{scan_name}'"}
try:
response = get_request(url, params=params, headers=headers, timeout=30)
json_response = json.loads(response.text)
if len(json_response) == 0:
return None, None, None
scan_id = json_response[0]["Id"]
app_name = json_response[0]["AppName"]
app_id = json_response[0]["AppId"]
return scan_id, app_name, app_id
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Scans/Scans_GetScan
# request URL : GET https://cloud.appscan.com/api/V2/Scans
# headers: "Authorization=Bearer <token>"
# params: "$select=<Id>"
def get_scans(token, host=ASOC_API):
url = url_join(host, "/Scans")
headers = {"Accept": "application/json", "Authorization": "Bearer " + token}
params = {"$select": "Id"}
try:
response = get_request(url, params=params, headers=headers, timeout=30)
json_response = json.loads(response.text)
return json_response
except IastException as e:
if 'Client Error: 400' in str(e):
return None
else:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException("KeyError:" + str(e) + " not in response: " + str(json_response))
# Swagger: https://https://cloud.appscan.com/swagger/ui/index#!/Apps/Apps_ScansById
# request URL : GET https://https://cloud.appscan.com/api/v2/Apps/<app_id>/Scans
# headers: "Authorization=Bearer <token>"
# params: "$select=<Id>"
def get_scans_for_app(token, app_id, host=ASOC_API):
url = url_join(host, "Apps", app_id, "Scans")
headers = {"Accept": "application/json", "Authorization": "Bearer " + token}
params = {"$select": "Id"}
try:
response = get_request(url, params=params, headers=headers, timeout=30)
json_response = json.loads(response.text)
return json_response
except IastException as e:
if 'Client Error: 400' in str(e):
return None
else:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException("KeyError:" + str(e) + " not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Scans/Scans_DeleteScan
# request URL : DELETE https://cloud.appscan.com/api/V2/Scans/<scan_id>
# headers: "Authorization=Bearer <token>"
# params: "scanId=<scanId>, deleteIssues=True"
def delete_scan(scan_id, token, host=ASOC_API, retries=0):
if scan_id is not None:
url = url_join(host, "Scans", scan_id)
headers = {"Accept": "text/plain", "Authorization": "Bearer " + token}
params = {"deleteIssues": True}
try:
delete_request(url, headers=headers, params=params, retries=retries, timeout=60)
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Scans/Scans_GenerateNewIastKey
# request URL : POST https://cloud.appscan.com/api/V2/Scans/NewIASTKey/<scan_id>
# headers: "Authorization=Bearer <token>"
# params: "scanId=<scanId>"
def get_new_iast_key_for_scan(scan_id, token, host=ASOC_API):
url = url_join(host, "/Scans/NewIASTKey/", scan_id)
headers = {"Accept": "application/json", "Authorization": "Bearer " + token}
try:
response = post_request(url, headers=headers, timeout=30)
json_response = json.loads(response.text)
key = json_response["Key"]
return key
except IastException as e:
if 'Client Error: 400' in str(e):
return None
else:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException("KeyError:" + str(e) + " not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/FileUpload/FileUpload_Upload
# request URL : POST https://cloud.appscan.com/api/v2/FileUpload
# headers: "Authorization=Bearer <token>"
# params: "fileToUpload=<filePath>"
def upload_file(token, file_to_upload, host=ASOC_API, timeout=60, retries=2):
url = url_join(host, "/FileUpload")
headers = {"Authorization": "Bearer " + token, "Accept": "text/plain"}
json_response = ""
try:
with open(file_to_upload, "rb") as file:
response = post_request(url, headers=headers, files={"fileToUpload": file}, timeout=timeout, retries=retries)
json_response = json.loads(response.text)
file_id = json_response["FileId"]
return file_id
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Scans/Scans_UpdateIastScanByScanid
# request URL : PUT https://cloud.appscan.com/api/v2/Scans/{scanId}/UpdateIastScan
# headers: "Authorization=Bearer <token>"
# params: "scanId=<scanId>, scanData=<scanData>"
def update_iast_scan(scan_id, token, file_id, host=ASOC_API, retries=0):
scan_model = {
"ConfigFileId": file_id
}
url = url_join(host, "Scans", scan_id, "UpdateIastScan")
headers = {"Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer " + token}
try:
put_request(url, headers=headers, params={"scanId": scan_id}, json_body=scan_model, retries=retries, timeout=30)
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
#####################################################
# ASOC - report API https://cloud.appscan.com/swagger/ui/
#####################################################
# starts a report creation
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Reports/Reports_CreateSecurityReport
# request URL : POST https://cloud.appscan.com/api/V2/Reports/Security/<scope>/<id>
# headers: "Authorization=Bearer <token>"
# params: "scope=Scan, id=<scanId>"
# json: {
# "Summary": True,
# "Details": True,
# "Discussion": False,
# "Overview": False,
# "TableOfContent": True,
# "Advisories": False,
# "FixRecommendation": False,
# "History": True,
# "IsTrialReport": True,
# "ReportFileType": Xml
# }
def create_report(scan_id, token, host=ASOC_API):
# url
scope = "Scan" # one of: Application/Scan/ScanExecution (ScanExecution not supported)
url = url_join(host, "/Reports/Security/", scope, scan_id)
# headers
headers = {"Authorization": "Bearer " + token, "Content-Type": "application/json", "Accept": "text/plain"}
# body
report_type = "Xml" # one of: Xml/Html/Pdf - xml is quick, html slower, pdf VERY slow
configuration = {
"Summary": True,
"Details": True,
"Discussion": False,
"Overview": False,
"TableOfContent": True,
"Advisories": False,
"FixRecommendation": False,
"History": True,
"IsTrialReport": True,
"ReportFileType": report_type
}
body = {"Configuration": configuration}
json_response = None
try:
response = post_request(url, json_body=body, headers=headers, timeout=30)
json_response = json.loads(response.text)
print(json_response)
logging.info("report id: " + json_response["Id"])
return json_response["Id"]
except IastException as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# returns the status of report preparation
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Reports/Reports_GetReportJobs
# request URL : GET https://cloud.appscan.com/api/V2/Reports/<report_id>
# headers: "Authorization=Bearer <token>"
# params: "id=<reportId>"
def get_report_status(report_id, token, host=ASOC_API):
url = url_join(host, "/Reports/", report_id)
headers = {"Authorization": "Bearer " + token, "Accept": "application/json"}
json_response = None
try:
response = get_request(url, headers=headers, timeout=60)
json_response = json.loads(response.text)
print(json_response)
report_status = json_response["Status"]
logging.info("report status: " + report_status)
if report_status == 'failed':
raise IastException("Report creation failed!")
return report_status
except requests.exceptions.HTTPError as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
except KeyError as e:
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "KeyError:" + str(e) +
" not in response: " + str(json_response))
# polls asoc until report is ready
def wait_for_report_ready(report_id, token, max_retries=100, host=ASOC_API):
counter = max_retries
while counter > 0:
report_status = get_report_status(report_id=report_id, token=token, host=host)
if report_status == 'Ready':
return
if report_status == 'Failed':
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "asoc report generation failed")
time.sleep(2)
counter -= 1
raise IastException(inspect.currentframe().f_code.co_name + " failed:" + "Timed out waiting for report ready")
# returns the status of report preparation
# Swagger: https://cloud.appscan.com/swagger/ui/index#!/Reports/Reports_DownloadReport
# request URL : GET https://cloud.appscan.com/api/V2/Reports/Download/<report_id>
# headers: "Authorization=Bearer <token>"
# params: "id=<reportId>"
def download_report(report_id, token, host=ASOC_API):
url = url_join(host, "/Reports/Download/", report_id)
headers = {"Authorization": "Bearer " + token, "Accept": "text/plain"}
try:
response = get_request(url, headers=headers, stream=False, timeout=30)
report = ""
for chunk in response.iter_content(chunk_size=1024 * 1024):
if chunk:
# report.append(chunk)
report += chunk.decode("utf-8")
return report
except requests.exceptions.HTTPError as e:
raise IastException(f"{inspect.currentframe().f_code.co_name} failed: {str(e)}")
| [
"inspect.currentframe",
"json.loads",
"logging.info",
"time.sleep"
] | [((2082, 2107), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (2092, 2107), False, 'import json\n'), ((2117, 2195), 'logging.info', 'logging.info', (["('Started new execution with id: ' + json_response['ExecutionId'])"], {}), "('Started new execution with id: ' + json_response['ExecutionId'])\n", (2129, 2195), False, 'import logging\n'), ((5621, 5646), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (5631, 5646), False, 'import json\n'), ((5696, 5727), 'logging.info', 'logging.info', (["('token: ' + token)"], {}), "('token: ' + token)\n", (5708, 5727), False, 'import logging\n'), ((6699, 6724), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (6709, 6724), False, 'import json\n'), ((8040, 8065), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (8050, 8065), False, 'import json\n'), ((8982, 9007), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (8992, 9007), False, 'import json\n'), ((10086, 10111), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (10096, 10111), False, 'import json\n'), ((12742, 12767), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (12752, 12767), False, 'import json\n'), ((12863, 12902), 'logging.info', 'logging.info', (["('agent_key: ' + agent_key)"], {}), "('agent_key: ' + agent_key)\n", (12875, 12902), False, 'import logging\n'), ((12912, 12947), 'logging.info', 'logging.info', (["('scan_id: ' + scan_id)"], {}), "('scan_id: ' + scan_id)\n", (12924, 12947), False, 'import logging\n'), ((13858, 13883), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (13868, 13883), False, 'import json\n'), ((14967, 14992), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (14977, 14992), False, 'import json\n'), ((16091, 16116), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (16101, 16116), False, 'import json\n'), ((17061, 17086), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (17071, 17086), False, 'import json\n'), ((18758, 18783), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (18768, 18783), False, 'import json\n'), ((19843, 19868), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (19853, 19868), False, 'import json\n'), ((22901, 22926), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (22911, 22926), False, 'import json\n'), ((22966, 23015), 'logging.info', 'logging.info', (["('report id: ' + json_response['Id'])"], {}), "('report id: ' + json_response['Id'])\n", (22978, 23015), False, 'import logging\n'), ((23981, 24006), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (23991, 24006), False, 'import json\n'), ((24095, 24142), 'logging.info', 'logging.info', (["('report status: ' + report_status)"], {}), "('report status: ' + report_status)\n", (24107, 24142), False, 'import logging\n'), ((25096, 25109), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (25106, 25109), False, 'import time\n'), ((25157, 25179), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (25177, 25179), False, 'import inspect\n'), ((2305, 2327), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (2325, 2327), False, 'import inspect\n'), ((3167, 3189), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (3187, 3189), False, 'import inspect\n'), ((3875, 3897), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (3895, 3897), False, 'import inspect\n'), ((4671, 4693), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (4691, 4693), False, 'import inspect\n'), ((5814, 5836), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (5834, 5836), False, 'import inspect\n'), ((6980, 7002), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (7000, 7002), False, 'import inspect\n'), ((8191, 8213), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (8211, 8213), False, 'import inspect\n'), ((10302, 10324), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (10322, 10324), False, 'import inspect\n'), ((11116, 11138), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (11136, 11138), False, 'import inspect\n'), ((13049, 13071), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (13069, 13071), False, 'import inspect\n'), ((15307, 15329), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (15327, 15329), False, 'import inspect\n'), ((20000, 20022), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (20020, 20022), False, 'import inspect\n'), ((21051, 21073), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (21071, 21073), False, 'import inspect\n'), ((23116, 23138), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (23136, 23138), False, 'import inspect\n'), ((24352, 24374), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (24372, 24374), False, 'import inspect\n'), ((25001, 25023), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (25021, 25023), False, 'import inspect\n'), ((26131, 26153), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (26151, 26153), False, 'import inspect\n'), ((9226, 9248), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (9246, 9248), False, 'import inspect\n'), ((14208, 14230), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (14228, 14230), False, 'import inspect\n'), ((16298, 16320), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (16318, 16320), False, 'import inspect\n'), ((17268, 17290), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (17288, 17290), False, 'import inspect\n'), ((18142, 18164), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (18162, 18164), False, 'import inspect\n'), ((18991, 19013), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (19011, 19013), False, 'import inspect\n'), ((2419, 2441), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (2439, 2441), False, 'import inspect\n'), ((5928, 5950), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (5948, 5950), False, 'import inspect\n'), ((7094, 7116), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (7114, 7116), False, 'import inspect\n'), ((8305, 8327), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (8325, 8327), False, 'import inspect\n'), ((9340, 9362), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (9360, 9362), False, 'import inspect\n'), ((10416, 10438), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (10436, 10438), False, 'import inspect\n'), ((13163, 13185), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (13183, 13185), False, 'import inspect\n'), ((15421, 15443), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (15441, 15443), False, 'import inspect\n'), ((20114, 20136), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (20134, 20136), False, 'import inspect\n'), ((23230, 23252), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (23250, 23252), False, 'import inspect\n'), ((24466, 24488), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (24486, 24488), False, 'import inspect\n')] |
#!/usr/bin/env python
# * coding: utf8 *
'''
cloudb
Usage:
cloudb enable extensions [--verbosity=<level>]
cloudb create schema [--schemas=<name> --verbosity=<level>]
cloudb create admin-user [--verbosity=<level>]
cloudb create read-only-user [--verbosity=<level>]
cloudb create indexes [--verbosity=<level>]
cloudb drop schema [--schemas=<name> --verbosity=<level>]
cloudb import [--missing --dry-run --verbosity=<level> --skip-if-exists]
cloudb trim [--dry-run --verbosity=<level>]
cloudb update [--table=<tables>... --dry-run --verbosity=<level> --from-change-detection]
cloudb update-schema [--table=<tables>... --dry-run --verbosity=<level>]
'''
import sys
from datetime import datetime
from pathlib import Path
from time import perf_counter
import psycopg2
from colorama import Back, Fore, init
from docopt import docopt
from osgeo import gdal, ogr
import pyodbc
from . import CONNECTION_TABLE_CACHE, LOG, execute_sql, config, roles, schema, utils
from .index import INDEXES
gdal.SetConfigOption('MSSQLSPATIAL_LIST_ALL_TABLES', 'YES')
gdal.SetConfigOption('PG_LIST_ALL_TABLES', 'YES')
gdal.SetConfigOption('PG_USE_POSTGIS', 'YES')
gdal.SetConfigOption('PG_USE_COPY', 'YES')
def enable_extensions():
'''enable the database extension
owner: string db owner
'''
LOG.info('enabling extensions')
execute_sql('CREATE EXTENSION postgis;CREATE EXTENSION pg_stat_statements;', config.DBO_CONNECTION)
def _get_tables_with_fields(connection_string, specific_tables):
'''creates a list of tables with fields from the connection string
connection_string: string to connect to db
specific_tables: array of tables to get in schema.table format
returns: array of tuples with 0: schema, 1: table name: 2: array of field names
'''
layer_schema_map = []
filter_tables = False
if specific_tables and len(specific_tables) > 0:
LOG.debug(f'{Fore.CYAN}filtering for specific tables{Fore.RESET}')
filter_tables = True
LOG.verbose('connecting to database')
connection = gdal.OpenEx(connection_string)
LOG.verbose('getting layer count')
table_count = connection.GetLayerCount()
LOG.info(f'discovered {Fore.YELLOW}{table_count}{Fore.RESET} tables')
for table_index in range(table_count):
qualified_layer = connection.GetLayerByIndex(table_index)
schema_name, layer = qualified_layer.GetName().split('.')
schema_name = schema_name.lower()
layer = layer.lower()
LOG.debug(f'- {Fore.CYAN}{schema_name}.{layer}{Fore.RESET}')
if schema_name in config.EXCLUDE_SCHEMAS or filter_tables and f'{schema_name}.{layer}' not in specific_tables:
LOG.verbose(f' {Fore.RED}- skipping:{Fore.RESET} {schema_name}')
continue
definition = qualified_layer.GetLayerDefn()
fields = []
for field_index in range(definition.GetFieldCount()):
field = definition.GetFieldDefn(field_index)
field_name = field.GetName().lower()
if field_name in config.EXCLUDE_FIELDS:
LOG.verbose(f' {Fore.YELLOW}- skipping:{Fore.RESET} {field_name}')
continue
fields.append(field_name)
layer_schema_map.append((schema_name, layer, fields))
del qualified_layer
schema_map_count = len(layer_schema_map)
noun = 'tables'
if schema_map_count == 1:
noun = 'table'
LOG.info(f'planning to import {Fore.GREEN}{schema_map_count}{Fore.RESET} {noun}')
layer_schema_map.sort(key=lambda items: items[0])
connection = None
return layer_schema_map
def _get_schema_table_name_map(table_name):
'''a method to split a qualified table into it's parts
'''
parts = table_name.split('.')
schema_index = 1
table_index = 2
if len(parts) == 2:
schema_index = 0
table_index = 1
return {'schema': parts[schema_index].lower(), 'table_name': parts[table_index].lower()}
def _format_title_for_pg(title):
if title is None:
return title
new_title = title.lower()
new_title = new_title.replace('utah ', '', 1).replace(' ', '_')
LOG.verbose(f'updating {Fore.MAGENTA}{title}{Fore.RESET} to {Fore.CYAN}{new_title}{Fore.RESET}')
return new_title
def _get_table_meta():
'''gets the meta data about fields from meta.agolitems
'''
mapping = {}
with pyodbc.connect(config.get_source_connection()[6:]) as connection:
cursor = connection.cursor()
cursor.execute("SELECT [TABLENAME],[AGOL_PUBLISHED_NAME],[GEOMETRY_TYPE] FROM [SGID].[META].[AGOLITEMS]")
rows = cursor.fetchall()
#: table: SGID.ENVIRONMENT.DAQPermitCompApproval
#: title: Utah Retail Culinary Water Service Areas
#: geometry_type: POINT POLYGON POLYLINE
for table, title, geometry_type in rows:
table_parts = _get_schema_table_name_map(table)
pg_title = _format_title_for_pg(title)
schema_name = mapping.setdefault(table_parts['schema'], {})
schema_name[table_parts['table_name']] = {'title': pg_title, 'geometry_type': geometry_type}
return mapping
def _populate_table_cache(connection_string, pgify=False, name_map=None):
'''adds all the table from a connection string to a dictionary for caching purposes
pgify: lowercases and adds underscores
name_map: is a dictionary to replace names from the meta table
'''
skip_schema = ['meta', 'sde']
LOG.verbose('connecting to database')
#: gdal.open gave a 0 table count
connection = ogr.Open(connection_string)
LOG.verbose('getting layer count')
table_count = connection.GetLayerCount()
LOG.debug(f'found {Fore.YELLOW}{table_count}{Fore.RESET} total tables for cache')
CONNECTION_TABLE_CACHE.setdefault(connection_string, [])
for table_index in range(table_count):
qualified_layer = connection.GetLayerByIndex(table_index)
table = None
if qualified_layer:
name = qualified_layer.GetName()
LOG.verbose(f'qualified layer name: {name}')
if '.' not in name:
continue
table_parts = _get_schema_table_name_map(name)
name = f"{table_parts['schema']}.{table_parts['table_name']}"
if table_parts['schema'] in skip_schema:
continue
if pgify:
pg_title = _format_title_for_pg(table_parts['table_name'])
schema_name = table_parts['schema']
if schema_name in name_map and pg_title in name_map[schema_name]:
table, _ = name_map[schema_name][pg_title].values()
else:
continue
name = f"{schema_name}.{table}"
LOG.verbose(f'found layer: {name}')
CONNECTION_TABLE_CACHE[connection_string].append(name)
del qualified_layer
connection = None
def _check_if_exists(connection_string, schema_name, table, agol_meta_map):
'''returns true or false if a table exists in the connections_string db
connection_string: string of db to check
schema_name: string schema name
table: string table name
returns: bool
'''
LOG.debug('checking cache')
if schema_name in agol_meta_map and table in agol_meta_map[schema_name]:
table, _ = agol_meta_map[schema_name][table].values()
if connection_string in CONNECTION_TABLE_CACHE and len(CONNECTION_TABLE_CACHE[connection_string]) > 0:
LOG.verbose('cache hit')
return f'{schema_name}.{table}' in CONNECTION_TABLE_CACHE[connection_string]
LOG.verbose('cache miss')
_populate_table_cache(connection_string)
found = False
if f'{schema}.{table}' in CONNECTION_TABLE_CACHE[connection_string]:
found = True
return found
def _replace_data(schema_name, layer, fields, agol_meta_map, dry_run):
'''the insert logic for writing to the destination
'''
cloud_db = config.format_ogr_connection(config.DBO_CONNECTION)
internal_sgid = config.get_source_connection()
internal_name = f'{schema_name}.{layer}'
sql = f'SELECT objectid FROM "{schema_name}.{layer}"'
if len(fields) > 0:
#: escape reserved words?
fields = [f'"{field}"' for field in fields]
sql = f"SELECT {','.join(fields)} FROM \"{schema_name}.{layer}\""
options = [
'-f',
'PostgreSQL',
'-dialect',
'OGRSQL',
'-sql',
sql,
'-lco',
'FID=xid',
'-lco',
f'SCHEMA={schema_name}',
'-lco',
'OVERWRITE=YES',
'-lco',
'GEOMETRY_NAME=shape',
'-lco',
'PRECISION=YES',
'-a_srs',
config.UTM,
]
if schema_name in agol_meta_map and layer in agol_meta_map[schema_name]:
new_name, geometry_type = agol_meta_map[schema_name][layer].values()
if new_name:
layer = new_name
if geometry_type == 'POLYGON':
options.append('-nlt')
options.append('MULTIPOLYGON')
elif geometry_type == 'POLYLINE':
options.append('-nlt')
options.append('MULTILINESTRING')
elif geometry_type == 'STAND ALONE':
options.append('-nlt')
options.append('NONE')
else:
options.append('-nlt')
options.append(geometry_type)
else:
LOG.info(f'- skipping {Fore.MAGENTA}{layer}{Fore.RESET} since it is no longer in the meta table{Fore.RESET}')
return
options.append('-nln')
options.append(f'{layer}')
pg_options = None
try:
pg_options = gdal.VectorTranslateOptions(options=options)
except Exception:
LOG.fatal(f'- {Fore.RED}invalid options{Fore.RESET} for {Fore.BLUE}{layer}{Fore.RESET}')
return
LOG.info(f'- inserting {Fore.MAGENTA}{layer}{Fore.RESET} into {Fore.BLUE}{schema_name}{Fore.RESET} as {Fore.CYAN}{geometry_type}{Fore.RESET}')
LOG.debug(f'with {Fore.CYAN}{sql}{Fore.RESET}')
if not dry_run:
start_seconds = perf_counter()
result = gdal.VectorTranslate(cloud_db, internal_sgid, options=pg_options)
LOG.debug(f'- {Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
del result
LOG.debug(f'- {Fore.CYAN}make valid{Fore.RESET}')
qualified_layer = f'{schema_name}.{layer}'
make_valid(qualified_layer)
schema.update_schema_for(internal_name, qualified_layer)
create_index(qualified_layer)
def import_data(if_not_exists, missing_only, dry_run):
'''imports data from sql to postgis
if_not_exists: create new tables if the destination does not have it
dry_run: do not modify the destination
missing_only: only import missing tables
'''
cloud_db = config.format_ogr_connection(config.DBO_CONNECTION)
internal_sgid = config.get_source_connection()
tables = []
if missing_only:
source, destination = _get_table_sets()
tables = destination - source
table_count = len(tables)
verb = 'are'
noun = 'tables'
if table_count == 1:
verb = 'is'
noun = 'table'
LOG.info(f'there {verb} {Fore.CYAN}{table_count}{Fore.RESET} {noun} in the source not in the destination')
LOG.verbose(','.join(tables))
if table_count == 0:
return
agol_meta_map = _get_table_meta()
if missing_only:
origin_table_name = []
#: reverse lookup the table names
for table in tables:
schema_name, table_name = table.split('.')
schema_name = schema_name.lower()
table_name = table_name.lower()
schema_items = agol_meta_map[schema_name]
for origin_name in schema_items:
if schema_items[origin_name]['title'] == table_name:
origin_table_name.append(f'{schema_name}.{origin_name}')
break
if len(origin_table_name) > 0:
tables = origin_table_name
layer_schema_map = _get_tables_with_fields(internal_sgid, tables)
for schema_name, layer, fields in layer_schema_map:
if if_not_exists and _check_if_exists(cloud_db, schema_name, layer, agol_meta_map):
LOG.info(f'- skipping {Fore.MAGENTA}{schema_name}.{layer} {Fore.CYAN}already exists{Fore.RESET}')
continue
_replace_data(schema_name, layer, fields, agol_meta_map, dry_run)
def _get_table_sets():
'''gets a set of each schema.tablename from the source and destination database to help figure out what is different between them
'''
cloud_db = config.format_ogr_connection(config.DBO_CONNECTION)
internal_sgid = config.get_source_connection()
if cloud_db not in CONNECTION_TABLE_CACHE:
_populate_table_cache(cloud_db)
if internal_sgid not in CONNECTION_TABLE_CACHE:
_populate_table_cache(internal_sgid, pgify=True, name_map=_get_table_meta())
source = set(CONNECTION_TABLE_CACHE[cloud_db])
destination = set(CONNECTION_TABLE_CACHE[internal_sgid])
return source, destination
def trim(dry_run):
'''get source tables with updated names
get destination tables with original names
drop the tables in the destination found in the difference between the two sets
'''
source, destination = _get_table_sets()
items_to_trim = source - destination
items_to_trim_count = len(items_to_trim)
verb = 'are'
noun = 'tables'
if items_to_trim_count == 1:
verb = 'is'
noun = 'table'
LOG.info(f'there {verb} {Fore.CYAN}{items_to_trim_count}{Fore.RESET} {noun} in the destination not in the source')
LOG.verbose(','.join(items_to_trim))
if items_to_trim_count == 0:
return
clean_items = []
for item in items_to_trim:
schema, table = item.split('.')
clean_items.append(f'{schema}."{table}"')
sql = f'DROP TABLE {",".join(clean_items)}'
LOG.info(f'dropping {clean_items}')
if not dry_run:
execute_sql(sql, config.DBO_CONNECTION)
LOG.info(f'{Fore.GREEN}finished{Fore.RESET}')
def update(specific_tables, dry_run):
'''update specific tables in the destination
specific_tables: a list of tables from the source without the schema
dry_run: bool if insertion should actually happen
'''
internal_sgid = config.get_source_connection()
if not specific_tables or len(specific_tables) == 0:
LOG.info(f'{Fore.YELLOW} no tables to import!{Fore.RESET}')
return
layer_schema_map = _get_tables_with_fields(internal_sgid, specific_tables)
if len(layer_schema_map) == 0:
LOG.info(f'{Fore.YELLOW} no matching table found!{Fore.RESET}')
return
agol_meta_map = _get_table_meta()
if len(specific_tables) != len(layer_schema_map):
LOG.warn((
f'{Back.YELLOW}{Fore.BLACK}input {len(specific_tables)} tables but only {len(layer_schema_map)} found.{Fore.RESET}{Back.RESET} '
'check your spelling'
))
for schema_name, layer, fields in layer_schema_map:
_replace_data(schema_name, layer, fields, agol_meta_map, dry_run)
def read_last_check_date():
last_checked = Path('./.last_checked')
if not last_checked.exists():
last_checked.touch()
last_date_string = ''
with open(last_checked, 'r') as log_file:
last_date_string = log_file.readline().strip()
if last_date_string is None or len(last_date_string) < 1:
return None
return last_date_string
def update_last_check_date():
last_checked = Path('./.last_checked')
if not last_checked.exists():
last_checked.touch()
with open(last_checked, 'w') as log_file:
log_file.write(datetime.today().strftime('%Y-%m-%d'))
def get_tables_from_change_detection():
last_checked = read_last_check_date()
if last_checked is None:
last_checked = datetime.today()
else:
last_checked = datetime.strptime(last_checked, '%Y-%m-%d')
LOG.info(f'Checking for changes since {Fore.MAGENTA}{last_checked}{Fore.RESET}')
updated_tables = []
with pyodbc.connect(config.get_source_connection()[6:]) as connection:
cursor = connection.cursor()
cursor.execute("SELECT [TABLE_NAME] FROM [SGID].[META].[CHANGEDETECTION] WHERE [LAST_MODIFIED] >= ?", last_checked)
rows = cursor.fetchall()
#: table: SGID.ENVIRONMENT.DAQPermitCompApproval
for table, in rows:
table_parts = _get_schema_table_name_map(table)
table_schema = table_parts['schema']
table_name = table_parts['table_name']
updated_tables.append(f'{table_schema}.{table_name}')
update_last_check_date()
return updated_tables
def make_valid(layer):
'''update invalid shapes in postgres
'''
sql = f'UPDATE {layer} SET shape = ST_MakeValid(shape) WHERE ST_IsValid(shape) = false;'
unfixable_layers = ['utilities.broadband_service']
if layer in unfixable_layers:
return
try:
execute_sql(sql, config.DBO_CONNECTION)
except psycopg2.errors.UndefinedColumn:
#: table doesn't have shape field
pass
def create_index(layer):
"""
creates an index if availabe in the index map
"""
if layer.lower() not in INDEXES:
return
LOG.debug(f'- {Fore.CYAN}adding index{Fore.RESET}')
for sql in INDEXES[layer]:
try:
execute_sql(sql, config.DBO_CONNECTION)
except Exception as ex:
LOG.warn(f'- {Fore.RED}failed running: {Fore.YELLOW}{sql}{Fore.CYAN}{ex}{Fore.RESET}')
def main():
'''Main entry point for program. Parse arguments and pass to sweeper modules.
'''
init()
args = docopt(__doc__, version='1.1.0')
start_seconds = perf_counter()
LOG.init(args['--verbosity'])
LOG.debug(f'{Back.WHITE}{Fore.BLACK}{args}{Back.RESET}{Fore.RESET}')
if args['enable']:
enable_extensions()
LOG.info(f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
sys.exit()
if args['create']:
if args['schema']:
name = args['--schemas']
if name is None or name == 'all':
schema.create_schemas(config.SCHEMAS)
sys.exit()
name = name.lower()
if name in config.SCHEMAS:
schema.create_schemas([name])
sys.exit()
if args['admin-user']:
roles.create_admin_user(config.ADMIN)
LOG.info(f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
sys.exit()
if args['read-only-user']:
roles.create_read_only_user(config.SCHEMAS)
LOG.info(f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
sys.exit()
if args['indexes']:
for key, _ in INDEXES.items():
create_index(key)
if args['drop']:
if args['schema']:
name = args['--schemas']
if name is None or name == 'all':
schema.drop_schemas(config.SCHEMAS)
LOG.info(f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
sys.exit()
name = name.lower()
if name in config.SCHEMAS:
schema.drop_schemas([name])
LOG.info(f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
sys.exit()
if args['import']:
import_data(args['--skip-if-exists'], args['--missing'], args['--dry-run'])
LOG.info(f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
sys.exit()
if args['trim']:
trim(args['--dry-run'])
LOG.info(f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
sys.exit()
if args['update']:
tables = args['--table']
if args['--from-change-detection']:
tables = get_tables_from_change_detection()
update(tables, args['--dry-run'])
LOG.info(f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
sys.exit()
if args['update-schema']:
tables = args['--table']
if len(tables) == 0:
schema.update_schemas(_get_table_meta(), args['--dry-run'])
else:
agol_meta_map = _get_table_meta()
for sgid_table in tables:
schema_name, table_name = sgid_table.lower().split('.')
pg_table = f'{schema_name}.{agol_meta_map[schema_name][table_name]["title"]}'
schema.update_schema_for(sgid_table, pg_table, args['--dry-run'])
LOG.info(
f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}'
)
sys.exit()
LOG.info(f'{Fore.GREEN}completed{Fore.RESET} in {Fore.CYAN}{utils.format_time(perf_counter() - start_seconds)}{Fore.RESET}')
sys.exit()
if __name__ == '__main__':
main()
| [
"osgeo.gdal.VectorTranslate",
"pathlib.Path",
"datetime.datetime.strptime",
"time.perf_counter",
"osgeo.gdal.SetConfigOption",
"osgeo.gdal.VectorTranslateOptions",
"osgeo.ogr.Open",
"sys.exit",
"datetime.datetime.today",
"osgeo.gdal.OpenEx",
"docopt.docopt",
"colorama.init"
] | [((1006, 1065), 'osgeo.gdal.SetConfigOption', 'gdal.SetConfigOption', (['"""MSSQLSPATIAL_LIST_ALL_TABLES"""', '"""YES"""'], {}), "('MSSQLSPATIAL_LIST_ALL_TABLES', 'YES')\n", (1026, 1065), False, 'from osgeo import gdal, ogr\n'), ((1066, 1115), 'osgeo.gdal.SetConfigOption', 'gdal.SetConfigOption', (['"""PG_LIST_ALL_TABLES"""', '"""YES"""'], {}), "('PG_LIST_ALL_TABLES', 'YES')\n", (1086, 1115), False, 'from osgeo import gdal, ogr\n'), ((1116, 1161), 'osgeo.gdal.SetConfigOption', 'gdal.SetConfigOption', (['"""PG_USE_POSTGIS"""', '"""YES"""'], {}), "('PG_USE_POSTGIS', 'YES')\n", (1136, 1161), False, 'from osgeo import gdal, ogr\n'), ((1162, 1204), 'osgeo.gdal.SetConfigOption', 'gdal.SetConfigOption', (['"""PG_USE_COPY"""', '"""YES"""'], {}), "('PG_USE_COPY', 'YES')\n", (1182, 1204), False, 'from osgeo import gdal, ogr\n'), ((2060, 2090), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['connection_string'], {}), '(connection_string)\n', (2071, 2090), False, 'from osgeo import gdal, ogr\n'), ((5606, 5633), 'osgeo.ogr.Open', 'ogr.Open', (['connection_string'], {}), '(connection_string)\n', (5614, 5633), False, 'from osgeo import gdal, ogr\n'), ((15350, 15373), 'pathlib.Path', 'Path', (['"""./.last_checked"""'], {}), "('./.last_checked')\n", (15354, 15373), False, 'from pathlib import Path\n'), ((15729, 15752), 'pathlib.Path', 'Path', (['"""./.last_checked"""'], {}), "('./.last_checked')\n", (15733, 15752), False, 'from pathlib import Path\n'), ((17874, 17880), 'colorama.init', 'init', ([], {}), '()\n', (17878, 17880), False, 'from colorama import Back, Fore, init\n'), ((17892, 17924), 'docopt.docopt', 'docopt', (['__doc__'], {'version': '"""1.1.0"""'}), "(__doc__, version='1.1.0')\n", (17898, 17924), False, 'from docopt import docopt\n'), ((17946, 17960), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (17958, 17960), False, 'from time import perf_counter\n'), ((21533, 21543), 'sys.exit', 'sys.exit', ([], {}), '()\n', (21541, 21543), False, 'import sys\n'), ((9695, 9739), 'osgeo.gdal.VectorTranslateOptions', 'gdal.VectorTranslateOptions', ([], {'options': 'options'}), '(options=options)\n', (9722, 9739), False, 'from osgeo import gdal, ogr\n'), ((10119, 10133), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (10131, 10133), False, 'from time import perf_counter\n'), ((10151, 10216), 'osgeo.gdal.VectorTranslate', 'gdal.VectorTranslate', (['cloud_db', 'internal_sgid'], {'options': 'pg_options'}), '(cloud_db, internal_sgid, options=pg_options)\n', (10171, 10216), False, 'from osgeo import gdal, ogr\n'), ((16063, 16079), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (16077, 16079), False, 'from datetime import datetime\n'), ((16113, 16156), 'datetime.datetime.strptime', 'datetime.strptime', (['last_checked', '"""%Y-%m-%d"""'], {}), "(last_checked, '%Y-%m-%d')\n", (16130, 16156), False, 'from datetime import datetime\n'), ((18264, 18274), 'sys.exit', 'sys.exit', ([], {}), '()\n', (18272, 18274), False, 'import sys\n'), ((20134, 20144), 'sys.exit', 'sys.exit', ([], {}), '()\n', (20142, 20144), False, 'import sys\n'), ((20342, 20352), 'sys.exit', 'sys.exit', ([], {}), '()\n', (20350, 20352), False, 'import sys\n'), ((20697, 20707), 'sys.exit', 'sys.exit', ([], {}), '()\n', (20705, 20707), False, 'import sys\n'), ((21387, 21397), 'sys.exit', 'sys.exit', ([], {}), '()\n', (21395, 21397), False, 'import sys\n'), ((18870, 18880), 'sys.exit', 'sys.exit', ([], {}), '()\n', (18878, 18880), False, 'import sys\n'), ((19124, 19134), 'sys.exit', 'sys.exit', ([], {}), '()\n', (19132, 19134), False, 'import sys\n'), ((18480, 18490), 'sys.exit', 'sys.exit', ([], {}), '()\n', (18488, 18490), False, 'import sys\n'), ((18626, 18636), 'sys.exit', 'sys.exit', ([], {}), '()\n', (18634, 18636), False, 'import sys\n'), ((19585, 19595), 'sys.exit', 'sys.exit', ([], {}), '()\n', (19593, 19595), False, 'import sys\n'), ((19872, 19882), 'sys.exit', 'sys.exit', ([], {}), '()\n', (19880, 19882), False, 'import sys\n'), ((15887, 15903), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (15901, 15903), False, 'from datetime import datetime\n'), ((21481, 21495), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (21493, 21495), False, 'from time import perf_counter\n'), ((10306, 10320), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (10318, 10320), False, 'from time import perf_counter\n'), ((18208, 18222), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (18220, 18222), False, 'from time import perf_counter\n'), ((20078, 20092), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (20090, 20092), False, 'from time import perf_counter\n'), ((20286, 20300), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (20298, 20300), False, 'from time import perf_counter\n'), ((20641, 20655), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (20653, 20655), False, 'from time import perf_counter\n'), ((21322, 21336), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (21334, 21336), False, 'from time import perf_counter\n'), ((18810, 18824), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (18822, 18824), False, 'from time import perf_counter\n'), ((19064, 19078), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (19076, 19078), False, 'from time import perf_counter\n'), ((19521, 19535), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (19533, 19535), False, 'from time import perf_counter\n'), ((19808, 19822), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (19820, 19822), False, 'from time import perf_counter\n')] |
#(C) Copyright <NAME> 2017-2021
#(C) Copyright Thousand Smiles Foundation 2017-2021
#
#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 rest_framework.views import APIView
from rest_framework.exceptions import APIException, NotFound
from rest_framework.response import Response
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from medicalhistory.models import *
from clinic.models import *
from patient.models import *
from datetime import *
from django.core import serializers
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound
from common.decorators import *
import sys
import numbers
import json
class MedicalHistoryView(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def serialize(self, entry):
m = {}
m["id"] = entry.id
m["clinic"] = entry.clinic_id
m["patient"] = entry.patient_id
m["time"] = entry.time
m["cold_cough_fever"] = entry.cold_cough_fever
m["hivaids"] = entry.hivaids
m["anemia"] = entry.anemia
m["athsma"] = entry.athsma
m["cancer"] = entry.cancer
m["congenitalheartdefect"] = entry.congenitalheartdefect
m["congenitalheartdefect_workup"] = entry.congenitalheartdefect_workup
m["congenitalheartdefect_planforcare"] = entry.congenitalheartdefect_planforcare
m["diabetes"] = entry.diabetes
m["epilepsy"] = entry.epilepsy
m["bleeding_problems"] = entry.bleeding_problems
m["hepititis"] = entry.hepititis
m["tuberculosis"] = entry.tuberculosis
m["troublespeaking"] = entry.troublespeaking
m["troublehearing"] = entry.troublehearing
m["troubleeating"] = entry.troubleeating
m["pregnancy_duration"] = entry.pregnancy_duration
m["pregnancy_smoke"] = entry.pregnancy_smoke
m["birth_complications"] = entry.birth_complications
m["pregnancy_complications"] = entry.pregnancy_complications
m["mother_alcohol"] = entry.mother_alcohol
m["relative_cleft"] = entry.relative_cleft
m["parents_cleft"] = entry.parents_cleft
m["siblings_cleft"] = entry.siblings_cleft
m["meds"] = entry.meds
m["allergymeds"] = entry.allergymeds
m["first_crawl"] = entry.first_crawl
m["first_sit"] = entry.first_sit
m["first_walk"] = entry.first_walk
m["first_words"] = entry.first_words
m["birth_weight"] = entry.birth_weight
m["birth_weight_metric"] = entry.birth_weight_metric
m["height"] = entry.height
m["height_metric"] = entry.height_metric
m["weight"] = entry.weight
m["weight_metric"] = entry.weight_metric
m["born_with_cleft_lip"] = entry.born_with_cleft_lip
m["born_with_cleft_palate"] = entry.born_with_cleft_palate
return m
@log_request
def get(self, request, medical_history_id=None, format=None):
medical_history = None
badRequest = False
aPatient = None
aClinic = None
aStation = None
aClinicStation = None
kwargs = {}
if medical_history_id:
try:
medical_history = MedicalHistory.objects.get(id = medical_history_id)
except:
medical_history = None
else:
# look for optional arguments
try:
patientid = request.GET.get('patient', '')
if patientid != '':
try:
aPatient = Patient.objects.get(id=patientid)
if not aPatient:
badRequest = True
else:
kwargs["patient"] = aPatient
except:
badRequest = True
except:
pass # no patient ID
try:
clinicid = request.GET.get('clinic', '')
if clinicid != '':
try:
aClinic = Clinic.objects.get(id=clinicid)
if not aClinic:
badRequest = True
else:
kwargs["clinic"] = aClinic
except:
badRequest = True
except:
pass # no clinic ID
if not badRequest and len(kwargs):
# look for invalid arg combinations
# there are 2 legal combinations of args
case1 = False
case2 = False
case3 = False
if aPatient and aClinic:
case1 = True
elif aPatient and not aClinic:
case2 = True
elif aClinic and not aPatient:
case3 = True
else:
badRequest = True
if not badRequest:
kwargs = {}
if case1:
kwargs["patient"] = aPatient
kwargs["clinic"] = aClinic
elif case2:
kwargs["patient"] = aPatient
elif case3:
kwargs["clinic"] = aClinic
try:
medical_history = MedicalHistory.objects.filter(**kwargs)
except:
medical_history = None
if not medical_history and not badRequest:
raise NotFound
elif not badRequest:
if medical_history_id:
ret = self.serialize(medical_history)
elif case1 and len(medical_history) == 1:
ret = self.serialize(medical_history[0])
else:
ret = []
for x in medical_history:
m = self.serialize(x)
ret.append(m)
if badRequest:
return HttpResponseBadRequest()
else:
return Response(ret)
def validatePostArgs(self, data):
valid = True
kwargs = data
try:
val = data["cold_cough_fever"]
if not (val == True or val == False):
valid = False
val = data["hivaids"]
if not (val == True or val == False):
valid = False
val = data["anemia"]
if not (val == True or val == False):
valid = False
val = data["athsma"]
if not (val == True or val == False):
valid = False
val = data["cancer"]
if not (val == True or val == False):
valid = False
val = data["congenitalheartdefect"]
if not (val == True or val == False):
valid = False
val = data["congenitalheartdefect_workup"]
if not (val == True or val == False):
valid = False
val = data["congenitalheartdefect_planforcare"]
if not (val == True or val == False):
valid = False
val = data["diabetes"]
if not (val == True or val == False):
valid = False
val = data["epilepsy"]
if not (val == True or val == False):
valid = False
val = data["bleeding_problems"]
if not (val == True or val == False):
valid = False
val = data["hepititis"]
if not (val == True or val == False):
valid = False
val = data["tuberculosis"]
if not (val == True or val == False):
valid = False
val = data["troublespeaking"]
if not (val == True or val == False):
valid = False
val = data["troublehearing"]
if not (val == True or val == False):
valid = False
val = data["troubleeating"]
if not (val == True or val == False):
valid = False
val = int(data["pregnancy_duration"])
if val < 5 or val > 10:
valid = False
else:
kwargs["pregnancy_duration"] = val
val = int(data["first_crawl"])
if val < 0:
valid = False
else:
kwargs["first_crawl"] = val
val = int(data["first_sit"])
if val < 0:
valid = False
else:
kwargs["first_sit"] = val
val = int(data["first_walk"])
if val < 0:
valid = False
else:
kwargs["first_walk"] = val
val = int(data["first_words"])
if val < 0:
valid = False
else:
kwargs["first_words"] = val
val = data["pregnancy_smoke"]
if not (val == True or val == False):
valid = False
val = data["birth_complications"]
if not (val == True or val == False):
valid = False
val = data["pregnancy_complications"]
if not (val == True or val == False):
valid = False
val = data["mother_alcohol"]
if not (val == True or val == False):
valid = False
val = data["relative_cleft"]
if not (val == True or val == False):
valid = False
val = data["parents_cleft"]
if not (val == True or val == False):
valid = False
val = data["siblings_cleft"]
if not (val == True or val == False):
valid = False
val = int(data["birth_weight"])
if val < 0:
valid = False
else:
kwargs["birth_weight"] = val
val = data["birth_weight_metric"]
if not (val == True or val == False):
valid = False
val = int(data["height"])
if val < 0:
valid = False
else:
kwargs["height"] = val
val = data["height_metric"]
if not (val == True or val == False):
valid = False
val = int(data["weight"])
if val < 0:
valid = False
else:
kwargs["weight"] = val
val = data["weight_metric"]
if not (val == True or val == False):
valid = False
val = data["born_with_cleft_lip"]
if not (val == True or val == False):
valid = False
val = data["born_with_cleft_palate"]
if not (val == True or val == False):
valid = False
except:
valid = False
return valid, kwargs
def validatePutArgs(self, data, medical_history):
valid = True
try:
if "cold_cough_fever" in data:
val = data["cold_cough_fever"]
if not (val == True or val == False):
valid = False
else:
medical_history.cold_cough_fever = val
if "hivaids" in data:
val = data["hivaids"]
if not (val == True or val == False):
valid = False
else:
medical_history.hivaids = val
if "anemia" in data:
val = data["anemia"]
if not (val == True or val == False):
valid = False
else:
medical_history.anemia = val
if "athsma" in data:
val = data["athsma"]
if not (val == True or val == False):
valid = False
else:
medical_history.athsma = val
if "cancer" in data:
val = data["cancer"]
if not (val == True or val == False):
valid = False
else:
medical_history.cancer = val
if "congenitalheartdefect" in data:
val = data["congenitalheartdefect"]
if not (val == True or val == False):
valid = False
else:
medical_history.congenitalheartdefect = val
if "congenitalheartdefect_workup" in data:
val = data["congenitalheartdefect_workup"]
if not (val == True or val == False):
valid = False
else:
medical_history.congenitalheartdefect_workup = val
if "congenitalheartdefect_planforcare" in data:
val = data["congenitalheartdefect_planforcare"]
if not (val == True or val == False):
valid = False
else:
medical_history.congenitalheartdefect_planforcare = val
if "diabetes" in data:
val = data["diabetes"]
if not (val == True or val == False):
valid = False
else:
medical_history.diabetes = val
if "epilepsy" in data:
val = data["epilepsy"]
if not (val == True or val == False):
valid = False
else:
medical_history.epilepsy = val
if "bleeding_problems" in data:
val = data["bleeding_problems"]
if not (val == True or val == False):
valid = False
else:
medical_history.bleeding_problems = val
if "hepititis" in data:
val = data["hepititis"]
if not (val == True or val == False):
valid = False
else:
medical_history.hepititis = val
if "tuberculosis" in data:
val = data["tuberculosis"]
if not (val == True or val == False):
valid = False
else:
medical_history.tuberculosis = val
if "troublespeaking" in data:
val = data["troublespeaking"]
if not (val == True or val == False):
valid = False
else:
medical_history.troublespeaking = val
if "troublehearing" in data:
val = data["troublehearing"]
if not (val == True or val == False):
valid = False
else:
medical_history.troublehearing = val
if "troubleeating" in data:
val = data["troubleeating"]
if not (val == True or val == False):
valid = False
else:
medical_history.troubleeating = val
if "pregnancy_duration" in data:
val = int(data["pregnancy_duration"])
if (val < 5 or val > 10):
valid = False
else:
medical_history.pregnancy_duration = val
if "pregnancy_smoke" in data:
val = data["pregnancy_smoke"]
if not (val == True or val == False):
valid = False
else:
medical_history.pregnancy_smoke = val
if "birth_complications" in data:
val = data["birth_complications"]
if not (val == True or val == False):
valid = False
else:
medical_history.birth_complications = val
if "pregnancy_complications" in data:
val = data["pregnancy_complications"]
if not (val == True or val == False):
valid = False
else:
medical_history.pregnancy_complications = val
if "mother_alcohol" in data:
val = data["mother_alcohol"]
if not (val == True or val == False):
valid = False
else:
medical_history.mother_alcohol = val
if "relative_cleft" in data:
val = data["relative_cleft"]
if not (val == True or val == False):
valid = False
else:
medical_history.relative_cleft = val
if "parents_cleft" in data:
val = data["parents_cleft"]
if not (val == True or val == False):
valid = False
else:
medical_history.parents_cleft = val
if "siblings_cleft" in data:
val = data["siblings_cleft"]
if not (val == True or val == False):
valid = False
else:
medical_history.siblings_cleft = val
if "meds" in data:
val = data["meds"]
if not isinstance(val, basestring):
valid = False
else:
medical_history.meds = val
if "allergymeds" in data:
val = data["allergymeds"]
if not isinstance(val, basestring):
valid = False
else:
medical_history.allergymeds = val
if "first_crawl" in data:
val = int(data["first_crawl"])
if (val < 0):
valid = False
else:
medical_history.first_crawl = val
if "first_sit" in data:
val = int(data["first_sit"])
if (val < 0):
valid = False
else:
medical_history.first_sit = val
if "first_walk" in data:
val = int(data["first_walk"])
if (val < 0):
valid = False
else:
medical_history.first_walk = val
if "first_words" in data:
val = int(data["first_words"])
if (val < 0):
valid = False
else:
medical_history.first_words = val
if "birth_weight" in data:
val = int(data["birth_weight"])
if (val < 0):
valid = False
else:
medical_history.birth_weight = val
if "birth_weight_metric" in data:
val = data["birth_weight_metric"]
if not (val == True or val == False):
valid = False
else:
medical_history.birth_weight_metric = val
if "height" in data:
val = int(data["height"])
if (val < 0):
valid = False
else:
medical_history.height = val
if "height_metric" in data:
val = data["height_metric"]
if not (val == True or val == False):
valid = False
else:
medical_history.height_metric = val
if "weight" in data:
val = int(data["weight"])
if (val < 0):
valid = False
else:
medical_history.weight = val
if "weight_metric" in data:
val = data["weight_metric"]
if not (val == True or val == False):
valid = False
else:
medical_history.weight_metric = val
if "born_with_cleft_lip" in data:
val = data["born_with_cleft_lip"]
if not (val == True or val == False):
valid = False
else:
medical_history.born_with_cleft_lip = val
if "born_with_cleft_palate" in data:
val = data["born_with_cleft_palate"]
if not (val == True or val == False):
valid = False
else:
medical_history.born_with_cleft_palate = val
except:
valid = False
return valid, medical_history
@log_request
def post(self, request, format=None):
badRequest = False
implError = False
data = json.loads(request.body)
try:
patientid = int(data["patient"])
except:
badRequest = True
try:
clinicid = int(data["clinic"])
except:
badRequest = True
# validate the post data, and get a kwargs dict for
# creating the object
valid, kwargs = self.validatePostArgs(data)
if not valid:
badRequest = True
if not badRequest:
# get the instances
try:
aPatient = Patient.objects.get(id=patientid)
except:
aPatient = None
try:
aClinic = Clinic.objects.get(id=clinicid)
except:
aClinic = None
if not aPatient or not aClinic:
raise NotFound
if not badRequest:
try:
kwargs["patient"] = aPatient
kwargs["clinic"] = aClinic
medical_history = MedicalHistory(**kwargs)
if medical_history:
medical_history.save()
else:
implError = True
except Exception as e:
implError = True
implMsg = sys.exc_info()[0]
if badRequest:
return HttpResponseBadRequest()
if implError:
return HttpResponseServerError(implMsg)
else:
return Response({'id': medical_history.id})
@log_request
def put(self, request, medical_history_id=None, format=None):
badRequest = False
implError = False
notFound = False
if not medical_history_id:
badRequest = True
if not badRequest:
medical_history = None
try:
medical_history = MedicalHistory.objects.get(id=medical_history_id)
except:
pass
if not medical_history:
notFound = True
else:
try:
data = json.loads(request.body)
valid, medical_history = self.validatePutArgs(data, medical_history)
if valid:
medical_history.save()
else:
badRequest = True
except:
implError = True
implMsg = sys.exc_info()[0]
if badRequest:
return HttpResponseBadRequest()
if notFound:
return HttpResponseNotFound()
if implError:
return HttpResponseServerError(implMsg)
else:
return Response({})
@log_request
def delete(self, request, medical_history_id=None, format=None):
medical_history = None
# see if the state change object exists
if not medical_history_id:
return HttpResponseBadRequest()
try:
medical_history = MedicalHistory.objects.get(id=medical_history_id)
except:
medical_history = None
if not medical_history:
raise NotFound
else:
medical_history.delete()
return Response({})
| [
"json.loads",
"django.http.HttpResponseBadRequest",
"sys.exc_info",
"rest_framework.response.Response",
"django.http.HttpResponseServerError",
"django.http.HttpResponseNotFound"
] | [((21314, 21338), 'json.loads', 'json.loads', (['request.body'], {}), '(request.body)\n', (21324, 21338), False, 'import json\n'), ((24530, 24542), 'rest_framework.response.Response', 'Response', (['{}'], {}), '({})\n', (24538, 24542), False, 'from rest_framework.response import Response\n'), ((6617, 6641), 'django.http.HttpResponseBadRequest', 'HttpResponseBadRequest', ([], {}), '()\n', (6639, 6641), False, 'from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound\n'), ((6675, 6688), 'rest_framework.response.Response', 'Response', (['ret'], {}), '(ret)\n', (6683, 6688), False, 'from rest_framework.response import Response\n'), ((22643, 22667), 'django.http.HttpResponseBadRequest', 'HttpResponseBadRequest', ([], {}), '()\n', (22665, 22667), False, 'from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound\n'), ((22709, 22741), 'django.http.HttpResponseServerError', 'HttpResponseServerError', (['implMsg'], {}), '(implMsg)\n', (22732, 22741), False, 'from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound\n'), ((22776, 22812), 'rest_framework.response.Response', 'Response', (["{'id': medical_history.id}"], {}), "({'id': medical_history.id})\n", (22784, 22812), False, 'from rest_framework.response import Response\n'), ((23795, 23819), 'django.http.HttpResponseBadRequest', 'HttpResponseBadRequest', ([], {}), '()\n', (23817, 23819), False, 'from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound\n'), ((23860, 23882), 'django.http.HttpResponseNotFound', 'HttpResponseNotFound', ([], {}), '()\n', (23880, 23882), False, 'from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound\n'), ((23924, 23956), 'django.http.HttpResponseServerError', 'HttpResponseServerError', (['implMsg'], {}), '(implMsg)\n', (23947, 23956), False, 'from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound\n'), ((23991, 24003), 'rest_framework.response.Response', 'Response', (['{}'], {}), '({})\n', (23999, 24003), False, 'from rest_framework.response import Response\n'), ((24234, 24258), 'django.http.HttpResponseBadRequest', 'HttpResponseBadRequest', ([], {}), '()\n', (24256, 24258), False, 'from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound\n'), ((23383, 23407), 'json.loads', 'json.loads', (['request.body'], {}), '(request.body)\n', (23393, 23407), False, 'import json\n'), ((22581, 22595), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (22593, 22595), False, 'import sys\n'), ((23734, 23748), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (23746, 23748), False, 'import sys\n')] |
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name='amieclient',
version='0.4.0',
packages=find_packages(),
install_requires=[
'requests>=2.20.0,<3',
'python-dateutil>=2.6.1,<2.7'
],
author='<NAME>',
author_email='<EMAIL>',
python_requires='>=3.5',
description='Library for the XSEDE AMIE REST API.',
long_description=long_description,
long_description_content_type="text/markdown",
license='Apache Software License v2.0',
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
project_urls={
'Documentation & Examples': 'https://xsede.github.io/amieclient/',
'Source': 'https://github.com/xsede/amieclient/',
'Tracker': 'https://github.com/xsede/amieclient/issues',
},
)
| [
"setuptools.find_packages"
] | [((196, 211), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (209, 211), False, 'from setuptools import setup, find_packages\n')] |
import spartan
from spartan import core, expr, util, blob_ctx
import numpy as np
from .qr import qr
def svd(A, k=None):
"""
Stochastic SVD.
Parameters
----------
A : spartan matrix
Array to compute the SVD on, of shape (M, N)
k : int, optional
Number of singular values and vectors to compute.
The operations include matrix multiplication and QR decomposition.
We parallelize both of them.
Returns
--------
U : Spartan array of shape (M, k)
S : numpy array of shape (k,)
V : numpy array of shape (k, k)
"""
if k is None: k = A.shape[1]
Omega = expr.randn(A.shape[1], k)
Y = expr.dot(A, Omega)
Q, R = qr(Y)
B = expr.dot(expr.transpose(Q), A)
BTB = expr.dot(B, expr.transpose(B)).optimized().glom()
S, U_ = np.linalg.eig(BTB)
S = np.sqrt(S)
# Sort by eigen values from large to small
si = np.argsort(S)[::-1]
S = S[si]
U_ = U_[:, si]
U = expr.dot(Q, U_).optimized().evaluate()
V = np.dot(np.dot(expr.transpose(B).optimized().glom(), U_), np.diag(np.ones(S.shape[0]) / S))
return U, S, V.T
| [
"spartan.expr.randn",
"spartan.expr.dot",
"numpy.sqrt",
"numpy.linalg.eig",
"numpy.ones",
"spartan.expr.transpose",
"numpy.argsort"
] | [((594, 619), 'spartan.expr.randn', 'expr.randn', (['A.shape[1]', 'k'], {}), '(A.shape[1], k)\n', (604, 619), False, 'from spartan import core, expr, util, blob_ctx\n'), ((627, 645), 'spartan.expr.dot', 'expr.dot', (['A', 'Omega'], {}), '(A, Omega)\n', (635, 645), False, 'from spartan import core, expr, util, blob_ctx\n'), ((769, 787), 'numpy.linalg.eig', 'np.linalg.eig', (['BTB'], {}), '(BTB)\n', (782, 787), True, 'import numpy as np\n'), ((794, 804), 'numpy.sqrt', 'np.sqrt', (['S'], {}), '(S)\n', (801, 804), True, 'import numpy as np\n'), ((678, 695), 'spartan.expr.transpose', 'expr.transpose', (['Q'], {}), '(Q)\n', (692, 695), False, 'from spartan import core, expr, util, blob_ctx\n'), ((858, 871), 'numpy.argsort', 'np.argsort', (['S'], {}), '(S)\n', (868, 871), True, 'import numpy as np\n'), ((1024, 1043), 'numpy.ones', 'np.ones', (['S.shape[0]'], {}), '(S.shape[0])\n', (1031, 1043), True, 'import numpy as np\n'), ((914, 929), 'spartan.expr.dot', 'expr.dot', (['Q', 'U_'], {}), '(Q, U_)\n', (922, 929), False, 'from spartan import core, expr, util, blob_ctx\n'), ((720, 737), 'spartan.expr.transpose', 'expr.transpose', (['B'], {}), '(B)\n', (734, 737), False, 'from spartan import core, expr, util, blob_ctx\n'), ((973, 990), 'spartan.expr.transpose', 'expr.transpose', (['B'], {}), '(B)\n', (987, 990), False, 'from spartan import core, expr, util, blob_ctx\n')] |
# @file
#
# Copyright (c) Microsoft Corporation.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.<BR>
# Copyright (c) 2020 - 2021, ARM Limited. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
import os
import logging
from edk2toolext.environment import shell_environment
from edk2toolext.invocables.edk2_ci_build import CiBuildSettingsManager
from edk2toolext.invocables.edk2_ci_setup import CiSetupSettingsManager # MU_CHANGE
from edk2toolext.invocables.edk2_setup import SetupSettingsManager, RequiredSubmodule
from edk2toolext.invocables.edk2_update import UpdateSettingsManager
from edk2toolext.invocables.edk2_pr_eval import PrEvalSettingsManager
from edk2toollib.utility_functions import GetHostInfo
# MU_CHANGE - Add CiSetupSettingsManager superclass.
class Settings(CiSetupSettingsManager, CiBuildSettingsManager, UpdateSettingsManager, SetupSettingsManager, PrEvalSettingsManager):
def __init__(self):
self.ActualPackages = []
self.ActualTargets = []
self.ActualArchitectures = []
self.ActualToolChainTag = ""
self.UseBuiltInBaseTools = None
self.ActualScopes = None
# ####################################################################################### #
# Extra CmdLine configuration #
# ####################################################################################### #
def AddCommandLineOptions(self, parserObj):
group = parserObj.add_mutually_exclusive_group()
group.add_argument("-force_piptools", "--fpt", dest="force_piptools", action="store_true", default=False, help="Force the system to use pip tools")
group.add_argument("-no_piptools", "--npt", dest="no_piptools", action="store_true", default=False, help="Force the system to not use pip tools")
def RetrieveCommandLineOptions(self, args):
super().RetrieveCommandLineOptions(args)
if args.force_piptools:
self.UseBuiltInBaseTools = True
if args.no_piptools:
self.UseBuiltInBaseTools = False
# ####################################################################################### #
# Default Support for this Ci Build #
# ####################################################################################### #
def GetPackagesSupported(self):
''' return iterable of edk2 packages supported by this build.
These should be edk2 workspace relative paths '''
return ("IntelFsp2Pkg", # MU_CHANGE
"IntelFsp2WrapperPkg", # MU_CHANGE
"IntelSiliconPkg" # MU_CHANGE
)
def GetArchitecturesSupported(self):
''' return iterable of edk2 architectures supported by this build '''
return (
"IA32",
"X64",
"ARM",
"AARCH64")
def GetTargetsSupported(self):
''' return iterable of edk2 target tags supported by this build '''
return ("DEBUG", "RELEASE", "NO-TARGET", "NOOPT")
# ####################################################################################### #
# Verify and Save requested Ci Build Config #
# ####################################################################################### #
def SetPackages(self, list_of_requested_packages):
''' Confirm the requested package list is valid and configure SettingsManager
to build the requested packages.
Raise UnsupportedException if a requested_package is not supported
'''
unsupported = set(list_of_requested_packages) - \
set(self.GetPackagesSupported())
if(len(unsupported) > 0):
logging.critical(
"Unsupported Package Requested: " + " ".join(unsupported))
raise Exception("Unsupported Package Requested: " +
" ".join(unsupported))
self.ActualPackages = list_of_requested_packages
def SetArchitectures(self, list_of_requested_architectures):
''' Confirm the requests architecture list is valid and configure SettingsManager
to run only the requested architectures.
Raise Exception if a list_of_requested_architectures is not supported
'''
unsupported = set(list_of_requested_architectures) - \
set(self.GetArchitecturesSupported())
if(len(unsupported) > 0):
logging.critical(
"Unsupported Architecture Requested: " + " ".join(unsupported))
raise Exception(
"Unsupported Architecture Requested: " + " ".join(unsupported))
self.ActualArchitectures = list_of_requested_architectures
def SetTargets(self, list_of_requested_target):
''' Confirm the request target list is valid and configure SettingsManager
to run only the requested targets.
Raise UnsupportedException if a requested_target is not supported
'''
unsupported = set(list_of_requested_target) - \
set(self.GetTargetsSupported())
if(len(unsupported) > 0):
logging.critical(
"Unsupported Targets Requested: " + " ".join(unsupported))
raise Exception("Unsupported Targets Requested: " +
" ".join(unsupported))
self.ActualTargets = list_of_requested_target
# ####################################################################################### #
# Actual Configuration for Ci Build #
# ####################################################################################### #
def GetActiveScopes(self):
''' return tuple containing scopes that should be active for this process '''
if self.ActualScopes is None:
scopes = ("cibuild", "edk2-build", "host-based-test")
self.ActualToolChainTag = shell_environment.GetBuildVars().GetValue("TOOL_CHAIN_TAG", "")
is_linux = GetHostInfo().os.upper() == "LINUX"
if self.UseBuiltInBaseTools is None:
# MU_CHANGE - redundant is_linux = GetHostInfo().os.upper() == "LINUX"
# try and import the pip module for basetools
try:
import edk2basetools
self.UseBuiltInBaseTools = True
except ImportError:
self.UseBuiltInBaseTools = False
pass
if self.UseBuiltInBaseTools == True:
scopes += ('pipbuild-unix',) if is_linux else ('pipbuild-win',)
logging.warning("Using Pip Tools based BaseTools")
else:
logging.warning("Falling back to using in-tree BaseTools")
if is_linux and self.ActualToolChainTag.upper().startswith("GCC"):
if "AARCH64" in self.ActualArchitectures:
scopes += ("gcc_aarch64_linux",)
if "ARM" in self.ActualArchitectures:
scopes += ("gcc_arm_linux",)
if "RISCV64" in self.ActualArchitectures:
scopes += ("gcc_riscv64_unknown",)
self.ActualScopes = scopes
return self.ActualScopes
def GetRequiredSubmodules(self):
''' return iterable containing RequiredSubmodule objects.
If no RequiredSubmodules return an empty iterable
'''
rs = []
return rs
def GetName(self):
# MU_CHANGE
return "SiliconIntelTiano"
def GetDependencies(self):
# MU_CHANGE BEGIN
''' Return Git Repository Dependencies
Return an iterable of dictionary objects with the following fields
{
Path: <required> Workspace relative path
Url: <required> Url of git repo
Commit: <optional> Commit to checkout of repo
Branch: <optional> Branch to checkout (will checkout most recent commit in branch)
Full: <optional> Boolean to do shallow or Full checkout. (default is False)
ReferencePath: <optional> Workspace relative path to git repo to use as "reference"
}
'''
return [
{
"Path": "Common/MU_TIANO",
"Url": "https://github.com/microsoft/mu_tiano_plus.git",
"Branch": "release/202202"
},
{
"Path": "MU_BASECORE",
"Url": "https://github.com/microsoft/mu_basecore.git",
"Branch": "release/202202"
}
]
# MU_CHANGE END
def GetPackagesPath(self):
# MU_CHANGE BEGIN
''' Return a list of workspace relative paths that should be mapped as edk2 PackagesPath '''
result = []
for a in self.GetDependencies():
result.append(a["Path"])
return result
# MU_CHANGE END
def GetWorkspaceRoot(self):
''' get WorkspacePath '''
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def FilterPackagesToTest(self, changedFilesList: list, potentialPackagesList: list) -> list:
''' Filter potential packages to test based on changed files. '''
return []
| [
"os.path.abspath",
"edk2toolext.environment.shell_environment.GetBuildVars",
"logging.warning",
"edk2toollib.utility_functions.GetHostInfo"
] | [((6980, 7030), 'logging.warning', 'logging.warning', (['"""Using Pip Tools based BaseTools"""'], {}), "('Using Pip Tools based BaseTools')\n", (6995, 7030), False, 'import logging\n'), ((7067, 7125), 'logging.warning', 'logging.warning', (['"""Falling back to using in-tree BaseTools"""'], {}), "('Falling back to using in-tree BaseTools')\n", (7082, 7125), False, 'import logging\n'), ((9441, 9466), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (9456, 9466), False, 'import os\n'), ((6267, 6299), 'edk2toolext.environment.shell_environment.GetBuildVars', 'shell_environment.GetBuildVars', ([], {}), '()\n', (6297, 6299), False, 'from edk2toolext.environment import shell_environment\n'), ((6357, 6370), 'edk2toollib.utility_functions.GetHostInfo', 'GetHostInfo', ([], {}), '()\n', (6368, 6370), False, 'from edk2toollib.utility_functions import GetHostInfo\n')] |
from os import path
from pprint import pformat
from git_sh_sync.proc import CHAR_NEWLINE
def test_cmd_init_empty(helpcmd):
res = helpcmd.init('test-command')
assert res.cmd == ['test-command']
assert res.cwd is None
assert res.cin is None
assert res.exc is None
assert res.code is None
assert res.stdout == ''
assert res.stderr == ''
assert res.command == 'test-command'
assert res.launched is False
assert res.success is False
assert res.out == []
assert res.err == []
def test_cmd_init_more(helpcmd):
res = helpcmd.init('test-command', cwd='test-dir', cin='test-input')
assert res.cmd == ['test-command']
assert res.cwd == path.realpath('test-dir')
assert res.cin == 'test-input'
assert res.exc is None
assert res.code is None
assert res.stdout == ''
assert res.stderr == ''
assert res.command == 'test-command'
assert res.launched is False
assert res.success is False
assert res.out == []
assert res.err == []
def test_cmd_out_err(helpcmd):
res = helpcmd.init('test-command')
assert res.cmd == ['test-command']
assert res.stdout == ''
assert res.out == []
assert res.stderr == ''
assert res.err == []
helpcmd.edit(res, stdout='test\nout', stderr='test\nerr')
assert res.stdout == 'test\nout'
assert res.out == ['test', 'out']
assert res.stderr == 'test\nerr'
assert res.err == ['test', 'err']
def test_cmd_launched_c(helpcmd):
res = helpcmd.init('test-command')
assert res.cmd == ['test-command']
assert res.code is None
assert res.launched is False
helpcmd.edit(res, code=0)
assert res.code == 0
assert res.launched is True
def test_cmd_launched_e(helpcmd):
res = helpcmd.init('test-command')
assert res.cmd == ['test-command']
assert res.exc is None
assert res.launched is False
helpcmd.edit(res, exc='exception')
assert res.exc == 'exception'
assert res.launched is True
def test_cmd_fields_pre(helpcmd):
res = helpcmd.init('test-command', cwd='test-dir', cin='test-input')
assert res.fields == dict(
command='test-command',
cwd=path.realpath('test-dir'),
cin='test-input',
)
def test_cmd_repr_pre(helpcmd):
res = helpcmd.init('test-command', cwd='test-dir', cin='test-input')
assert str(res) == pformat(dict(
command='test-command',
cwd=path.realpath('test-dir'),
cin='test-input',
))
def test_cmd_fields_post(helpcmd):
res = helpcmd.init('test-command', cwd='test-dir', cin='test-input')
assert res.fields == dict(
command='test-command',
cwd=path.realpath('test-dir'),
cin='test-input',
)
helpcmd.edit(res, code=0)
assert res.fields == dict(
command='test-command',
cwd=path.realpath('test-dir'),
cin='test-input',
stdout='',
stderr='',
code=0,
exc=None,
)
def test_cmd_repr_post(helpcmd):
res = helpcmd.init('test-command', cwd='test-dir', cin='test-input')
assert str(res) == pformat(dict(
command='test-command',
cwd=path.realpath('test-dir'),
cin='test-input',
))
helpcmd.edit(res, code=0)
assert str(res) == pformat(dict(
command='test-command',
cwd=path.realpath('test-dir'),
cin='test-input',
stdout='',
stderr='',
code=0,
exc=None,
))
def test_cmd_repr_repr(helpcmd):
res = helpcmd.init('test-command', cwd='test-dir', cin='test-input')
assert res.repr == '"""{}{}{}"""'.format(
CHAR_NEWLINE, str(res), CHAR_NEWLINE
)
| [
"os.path.realpath"
] | [((694, 719), 'os.path.realpath', 'path.realpath', (['"""test-dir"""'], {}), "('test-dir')\n", (707, 719), False, 'from os import path\n'), ((2176, 2201), 'os.path.realpath', 'path.realpath', (['"""test-dir"""'], {}), "('test-dir')\n", (2189, 2201), False, 'from os import path\n'), ((2668, 2693), 'os.path.realpath', 'path.realpath', (['"""test-dir"""'], {}), "('test-dir')\n", (2681, 2693), False, 'from os import path\n'), ((2832, 2857), 'os.path.realpath', 'path.realpath', (['"""test-dir"""'], {}), "('test-dir')\n", (2845, 2857), False, 'from os import path\n'), ((2423, 2448), 'os.path.realpath', 'path.realpath', (['"""test-dir"""'], {}), "('test-dir')\n", (2436, 2448), False, 'from os import path\n'), ((3152, 3177), 'os.path.realpath', 'path.realpath', (['"""test-dir"""'], {}), "('test-dir')\n", (3165, 3177), False, 'from os import path\n'), ((3323, 3348), 'os.path.realpath', 'path.realpath', (['"""test-dir"""'], {}), "('test-dir')\n", (3336, 3348), False, 'from os import path\n')] |
import os
import pymel.core as pm
import crab
# ------------------------------------------------------------------------------
def get_icon(name):
return os.path.join(
os.path.dirname(__file__),
'icons',
'%s.png' % name,
)
# ------------------------------------------------------------------------------
def get_namespace(node):
if ':' in node:
return node.rsplit(':', 1)[0]
return None
# ------------------------------------------------------------------------------
class SelectAllTool(crab.tools.AnimTool):
"""
Selects all the controls from within the active scene
"""
identifier = 'Select : All'
icon = get_icon('select_all')
def run(self):
pm.select(crab.utils.access.get_controls())
# ------------------------------------------------------------------------------
class SelectOppositeTool(crab.tools.AnimTool):
"""
Selects all the controls from within the active scene
"""
identifier = 'Select : Opposite'
icon = get_icon('select_opposite')
def run(self, nodes=None):
current_selection = nodes or pm.selected()
nodes_to_select = list()
for node in current_selection:
side = crab.config.get_side(node.name())
opp = crab.config.MIDDLE
if side == crab.config.RIGHT:
opp = crab.config.LEFT
elif side == crab.config.LEFT:
opp = crab.config.RIGHT
opp_name = node.name().replace(side, opp)
if pm.objExists(opp_name):
nodes_to_select.append(opp_name)
pm.select(nodes_to_select)
# ------------------------------------------------------------------------------
class SelectAllOnCharacter(crab.tools.AnimTool):
"""
Selects all the controls on the currently active character
"""
identifier = 'Select : All : Character'
icon = get_icon('select_all_character')
def run(self):
pm.select(crab.utils.access.get_controls(current_only=True))
# ------------------------------------------------------------------------------
class KeyAllTool(crab.tools.AnimTool):
"""
Keys alls the controls in the scene
"""
identifier = 'Key : All'
icon = get_icon('key_all')
def run(self):
pm.setKeyframe(crab.utils.access.get_controls())
# ------------------------------------------------------------------------------
class KeyAllOnCharacterTool(crab.tools.AnimTool):
"""
Keys all the controls on the currently active character
"""
identifier = 'Key : All : Character'
icon = get_icon('key_character')
def run(self):
pm.setKeyframe(crab.utils.access.get_controls(current_only=True))
# ------------------------------------------------------------------------------
class CopyPoseTool(crab.tools.AnimTool):
"""
Copies the pose of the currently selected objects
"""
identifier = 'Pose : Copy'
icon = get_icon('pose_store')
Pose = dict()
def run(self, nodes=None):
nodes = nodes or pm.selected()
for ctl in nodes:
CopyPoseTool.Pose[ctl.name().rsplit(':', 1)[-1]] = ctl.getMatrix()
# ------------------------------------------------------------------------------
class PastePoseTool(crab.tools.AnimTool):
"""
Applies the pose of the currently selected object
"""
identifier = 'Pose : Paste'
icon = get_icon('pose_apply')
def __init__(self):
super(PastePoseTool, self).__init__()
self.options.selection_only = False
def run(self, nodes=None):
nodes = nodes or pm.selected()
if not nodes:
return
selected_names = [
node.name()
for node in nodes
]
ns = get_namespace(selected_names[0])
for ctl, pose in CopyPoseTool.Pose.items():
# -- Add the namespace onto the ctl
resolved_name = ctl
if ns:
resolved_name = ns + ':' + ctl
if not pm.objExists(resolved_name):
continue
if self.options.selection_only and ctl not in selected_names:
continue
pm.PyNode(resolved_name).setMatrix(pose)
# ------------------------------------------------------------------------------
class CopyWorldSpaceTool(crab.tools.AnimTool):
identifier = 'Pose : Copy : World Space'
icon = get_icon('pose_store')
TRANSFORM_DATA = dict()
def run(self):
# -- Clear out any dictionary data
CopyWorldSpaceTool.TRANSFORM_DATA = dict()
for node in pm.selected():
CopyWorldSpaceTool.TRANSFORM_DATA[node.name()] = node.getMatrix(worldSpace=True)
# ------------------------------------------------------------------------------
class PasteWorldSpaceTool(crab.tools.AnimTool):
identifier = 'Pose : Paste : World Space'
icon = get_icon('pose_apply')
def run(self):
for name, matrix in CopyWorldSpaceTool.TRANSFORM_DATA.items():
if pm.objExists(name):
pm.PyNode(name).setMatrix(
CopyWorldSpaceTool.TRANSFORM_DATA[name],
worldSpace=True,
)
# ------------------------------------------------------------------------------
class ResetSelection(crab.tools.AnimTool):
"""
Reselects the current objects.
"""
identifier = 'Reset : Selected'
icon = get_icon('reset_selection')
def __init__(self):
super(ResetSelection, self).__init__()
self.options.KeyOnReset = False
def run(self, nodes=None):
nodes = nodes or pm.selected()
for node in nodes:
self.reset_node(node)
if self.options.KeyOnReset:
pm.setKeyframe(nodes)
# --------------------------------------------------------------------------
@classmethod
def reset_node(cls, node):
for attr in node.listAttr(k=True):
attr_name = attr.name(includeNode=False)
if 'scale' in attr_name:
value = 1.0
elif 'translate' in attr_name or 'rotate' in attr_name:
value = 0.0
else:
continue
try:
attr.set(value)
except Exception:
pass
for attr in node.listAttr(k=True, ud=True):
value = pm.attributeQuery(
attr.name(includeNode=False),
node=node,
listDefault=True,
)
try:
attr.set(value)
except Exception:
continue
# ------------------------------------------------------------------------------
class ResetCharacter(crab.tools.AnimTool):
"""
Resets all the controls on the currently active character
"""
identifier = 'Reset : Character'
icon = get_icon('reset_character')
def __init__(self):
super(ResetCharacter, self).__init__()
self.options.KeyOnReset = False
def run(self, nodes=None):
if nodes:
pm.select(nodes)
if not pm.selected():
return
nodes = crab.utils.access.get_controls(current_only=True)
for node in nodes:
ResetSelection.reset_node(node)
if self.options.KeyOnReset:
pm.setKeyframe(nodes)
# ------------------------------------------------------------------------------
class SnapTool(crab.tools.AnimTool):
"""
Snaps whichever limb is currently selected
"""
identifier = 'Snap : IKFK'
icon = None
def __init__(self):
super(SnapTool, self).__init__()
self.options.KeyOnSnap = False
self.options.SelectionOnly = False
self.options.AcrossTimeSpan = False
def run(self):
# -- Get a list of all the results
results = [
n
for n in crab.utils.access.component_nodes(pm.selected()[0], 'transform')
if crab.config.CONTROL in n.name()
]
# -- Create a unique list of labels
labels = set()
for node in results:
labels.update(crab.utils.snap.labels(node))
labels = list(labels)
if not labels:
return
# -- Apply the snap.
crab.utils.snap.snap_label(
label=labels[0],
restrict_to=pm.selected() if self.options.SelectionOnly else None,
start_time=int(pm.playbackOptions(q=True, min=True)) if self.options.AcrossTimeSpan else None,
end_time=int(pm.playbackOptions(q=True, max=True)) if self.options.AcrossTimeSpan else None,
key=self.options.KeyOnSnap,
)
| [
"pymel.core.selected",
"crab.utils.access.get_controls",
"pymel.core.select",
"os.path.dirname",
"pymel.core.objExists",
"pymel.core.PyNode",
"pymel.core.playbackOptions",
"pymel.core.setKeyframe",
"crab.utils.snap.labels"
] | [((184, 209), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (199, 209), False, 'import os\n'), ((1626, 1652), 'pymel.core.select', 'pm.select', (['nodes_to_select'], {}), '(nodes_to_select)\n', (1635, 1652), True, 'import pymel.core as pm\n'), ((4626, 4639), 'pymel.core.selected', 'pm.selected', ([], {}), '()\n', (4637, 4639), True, 'import pymel.core as pm\n'), ((7199, 7248), 'crab.utils.access.get_controls', 'crab.utils.access.get_controls', ([], {'current_only': '(True)'}), '(current_only=True)\n', (7229, 7248), False, 'import crab\n'), ((746, 778), 'crab.utils.access.get_controls', 'crab.utils.access.get_controls', ([], {}), '()\n', (776, 778), False, 'import crab\n'), ((1130, 1143), 'pymel.core.selected', 'pm.selected', ([], {}), '()\n', (1141, 1143), True, 'import pymel.core as pm\n'), ((1544, 1566), 'pymel.core.objExists', 'pm.objExists', (['opp_name'], {}), '(opp_name)\n', (1556, 1566), True, 'import pymel.core as pm\n'), ((1991, 2040), 'crab.utils.access.get_controls', 'crab.utils.access.get_controls', ([], {'current_only': '(True)'}), '(current_only=True)\n', (2021, 2040), False, 'import crab\n'), ((2323, 2355), 'crab.utils.access.get_controls', 'crab.utils.access.get_controls', ([], {}), '()\n', (2353, 2355), False, 'import crab\n'), ((2688, 2737), 'crab.utils.access.get_controls', 'crab.utils.access.get_controls', ([], {'current_only': '(True)'}), '(current_only=True)\n', (2718, 2737), False, 'import crab\n'), ((3075, 3088), 'pymel.core.selected', 'pm.selected', ([], {}), '()\n', (3086, 3088), True, 'import pymel.core as pm\n'), ((3630, 3643), 'pymel.core.selected', 'pm.selected', ([], {}), '()\n', (3641, 3643), True, 'import pymel.core as pm\n'), ((5053, 5071), 'pymel.core.objExists', 'pm.objExists', (['name'], {}), '(name)\n', (5065, 5071), True, 'import pymel.core as pm\n'), ((5656, 5669), 'pymel.core.selected', 'pm.selected', ([], {}), '()\n', (5667, 5669), True, 'import pymel.core as pm\n'), ((5781, 5802), 'pymel.core.setKeyframe', 'pm.setKeyframe', (['nodes'], {}), '(nodes)\n', (5795, 5802), True, 'import pymel.core as pm\n'), ((7115, 7131), 'pymel.core.select', 'pm.select', (['nodes'], {}), '(nodes)\n', (7124, 7131), True, 'import pymel.core as pm\n'), ((7148, 7161), 'pymel.core.selected', 'pm.selected', ([], {}), '()\n', (7159, 7161), True, 'import pymel.core as pm\n'), ((7370, 7391), 'pymel.core.setKeyframe', 'pm.setKeyframe', (['nodes'], {}), '(nodes)\n', (7384, 7391), True, 'import pymel.core as pm\n'), ((4043, 4070), 'pymel.core.objExists', 'pm.objExists', (['resolved_name'], {}), '(resolved_name)\n', (4055, 4070), True, 'import pymel.core as pm\n'), ((8179, 8207), 'crab.utils.snap.labels', 'crab.utils.snap.labels', (['node'], {}), '(node)\n', (8201, 8207), False, 'import crab\n'), ((4210, 4234), 'pymel.core.PyNode', 'pm.PyNode', (['resolved_name'], {}), '(resolved_name)\n', (4219, 4234), True, 'import pymel.core as pm\n'), ((8401, 8414), 'pymel.core.selected', 'pm.selected', ([], {}), '()\n', (8412, 8414), True, 'import pymel.core as pm\n'), ((5089, 5104), 'pymel.core.PyNode', 'pm.PyNode', (['name'], {}), '(name)\n', (5098, 5104), True, 'import pymel.core as pm\n'), ((7968, 7981), 'pymel.core.selected', 'pm.selected', ([], {}), '()\n', (7979, 7981), True, 'import pymel.core as pm\n'), ((8483, 8519), 'pymel.core.playbackOptions', 'pm.playbackOptions', ([], {'q': '(True)', 'min': '(True)'}), '(q=True, min=True)\n', (8501, 8519), True, 'import pymel.core as pm\n'), ((8588, 8624), 'pymel.core.playbackOptions', 'pm.playbackOptions', ([], {'q': '(True)', 'max': '(True)'}), '(q=True, max=True)\n', (8606, 8624), True, 'import pymel.core as pm\n')] |
# TinyTuya Module
# -*- coding: utf-8 -*-
"""
Python module to interface with Tuya WiFi smart devices
Author: <NAME>
For more information see https://github.com/jasonacox/tinytuya
Classes
OutletDevice(dev_id, address, local_key=None, dev_type='default')
CoverDevice(dev_id, address, local_key=None, dev_type='default')
BulbDevice(dev_id, address, local_key=None, dev_type='default')
dev_id (str): Device ID e.g. 01234567891234567890
address (str): Device Network IP Address e.g. 10.0.1.99
local_key (str, optional): The encryption key. Defaults to None.
dev_type (str): Device type for payload options (see below)
Functions
json = status() # returns json payload
set_version(version) # 3.1 [default] or 3.3
set_dpsUsed(dpsUsed) # set data points (DPs)
set_retry(retry=True) # retry if response payload is truncated
set_status(on, switch=1) # Set status of the device to 'on' or 'off' (bool)
set_value(index, value) # Set int value of any index.
turn_on(switch=1):
turn_off(switch=1):
set_timer(num_secs):
CoverDevice:
open_cover(switch=1):
close_cover(switch=1):
stop_cover(switch=1):
BulbDevice
set_colour(r, g, b):
set_white(brightness, colourtemp):
set_brightness(brightness):
set_colourtemp(colourtemp):
result = brightness():
result = colourtemp():
(r, g, b) = colour_rgb():
(h,s,v) = colour_hsv()
result = state():
Credits
* TuyaAPI https://github.com/codetheweb/tuyapi by codetheweb and blackrozes
For protocol reverse engineering
* PyTuya https://github.com/clach04/python-tuya by clach04
The origin of this python module (now abandoned)
* LocalTuya https://github.com/rospogrigio/localtuya-homeassistant by rospogrigio
Updated pytuya to support devices with Device IDs of 22 characters
"""
from __future__ import print_function # python 2.7 support
import base64
from hashlib import md5
import json
import logging
import socket
import sys
import time
import colorsys
import binascii
# Required module: pycryptodome
try:
import Crypto
from Crypto.Cipher import AES # PyCrypto
except ImportError:
Crypto = AES = None
import pyaes # https://github.com/ricmoo/pyaes
version_tuple = (1, 0, 4)
version = __version__ = '%d.%d.%d' % version_tuple
__author__ = 'jasonacox'
log = logging.getLogger(__name__)
#logging.basicConfig(level=logging.DEBUG) # Uncomment to Debug
log.debug('%s version %s', __name__, __version__)
log.debug('Python %s on %s', sys.version, sys.platform)
if Crypto is None:
log.debug('Using pyaes version %r', pyaes.VERSION)
log.debug('Using pyaes from %r', pyaes.__file__)
else:
log.debug('Using PyCrypto %r', Crypto.version_info)
log.debug('Using PyCrypto from %r', Crypto.__file__)
## Tuya Command Types
UDP = 0
AP_CONFIG = 1
ACTIVE = 2
BIND = 3
RENAME_GW = 4
RENAME_DEVICE = 5
UNBIND = 6
CONTROL = 7 # set values
STATUS = 8
HEART_BEAT = 9
DP_QUERY = 10 # get data points
QUERY_WIFI = 11
TOKEN_BIND = 12
CONTROL_NEW = 13
ENABLE_WIFI = 14
DP_QUERY_NEW = 16
SCENE_EXECUTE = 17
UDP_NEW = 19
AP_CONFIG_NEW = 20
LAN_GW_ACTIVE = 240
LAN_SUB_DEV_REQUEST = 241
LAN_DELETE_SUB_DEV = 242
LAN_REPORT_SUB_DEV = 243
LAN_SCENE = 244
LAN_PUBLISH_CLOUD_CONFIG = 245
LAN_PUBLISH_APP_CONFIG = 246
LAN_EXPORT_APP_CONFIG = 247
LAN_PUBLISH_SCENE_PANEL = 248
LAN_REMOVE_GW = 249
LAN_CHECK_GW_UPDATE = 250
LAN_GW_UPDATE = 251
LAN_SET_GW_CHANNEL = 252
## Protocol Versions
PROTOCOL_VERSION_BYTES_31 = b'3.1'
PROTOCOL_VERSION_BYTES_33 = b'3.3'
## Python 2 Support
IS_PY2 = sys.version_info[0] == 2
## Cryptography Helpers
class AESCipher(object):
def __init__(self, key):
self.bs = 16
self.key = key
def encrypt(self, raw, use_base64 = True):
if Crypto:
raw = self._pad(raw)
cipher = AES.new(self.key, mode=AES.MODE_ECB)
crypted_text = cipher.encrypt(raw)
else:
_ = self._pad(raw)
cipher = pyaes.blockfeeder.Encrypter(pyaes.AESModeOfOperationECB(self.key)) # no IV, auto pads to 16
crypted_text = cipher.feed(raw)
crypted_text += cipher.feed() # flush final block
if use_base64:
return base64.b64encode(crypted_text)
else:
return crypted_text
def decrypt(self, enc, use_base64=True):
if use_base64:
enc = base64.b64decode(enc)
if Crypto:
cipher = AES.new(self.key, AES.MODE_ECB)
raw = cipher.decrypt(enc)
return self._unpad(raw).decode('utf-8')
else:
cipher = pyaes.blockfeeder.Decrypter(pyaes.AESModeOfOperationECB(self.key)) # no IV, auto pads to 16
plain_text = cipher.feed(enc)
plain_text += cipher.feed() # flush final block
return plain_text
def _pad(self, s):
padnum = self.bs - len(s) % self.bs
return s + padnum * chr(padnum).encode()
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
def bin2hex(x, pretty=False):
if pretty:
space = ' '
else:
space = ''
if IS_PY2:
result = ''.join('%02X%s' % (ord(y), space) for y in x)
else:
result = ''.join('%02X%s' % (y, space) for y in x)
return result
def hex2bin(x):
if IS_PY2:
return x.decode('hex')
else:
return bytes.fromhex(x)
# Tuya Device Dictionary - Commands and Payload Template
# See requests.json payload at https://github.com/codetheweb/tuyapi
payload_dict = {
# Default Device
"default": {
CONTROL: { # Set Control Values on Device
"hexByte": "07",
"command": {"devId": "", "uid": "", "t": ""}
},
STATUS: { # Get Status from Device
"hexByte": "08",
"command": {"gwId": "", "devId": ""}
},
HEART_BEAT: {
"hexByte": "09",
"command": {}
},
DP_QUERY: { # Get Data Points from Device
"hexByte": "0a",
"command": {"gwId": "", "devId": "", "uid": "", "t": ""},
},
CONTROL_NEW: {
"hexByte": "0d",
"command": {"devId": "", "uid": "", "t": ""}
},
DP_QUERY_NEW: {
"hexByte": "0f",
"command": {"devId": "", "uid": "", "t": ""}
},
"prefix": "000055aa00000000000000",
# Next byte is command "hexByte" + length of remaining payload + command + suffix
# (unclear if multiple bytes used for length, zero padding implies could be more
# than one byte)
"suffix": "000000000000aa55"
},
# Special Case Device
"device22": {
DP_QUERY: { # Get Data Points from Device
"hexByte": "0d", # Uses CONTROL_NEW command for some reason
"command": {"devId": "", "uid": "", "t": ""}
},
CONTROL: { # Set Control Values on Device
"hexByte": "07",
"command": {"devId": "", "uid": "", "t": ""}
},
"prefix": "000055aa00000000000000",
"suffix": "000000000000aa55"
}
}
class XenonDevice(object):
def __init__(self, dev_id, address, local_key="", dev_type="default", connection_timeout=10):
"""
Represents a Tuya device.
Args:
dev_id (str): The device id.
address (str): The network address.
local_key (str, optional): The encryption key. Defaults to None.
Attributes:
port (int): The port to connect to.
"""
self.id = dev_id
self.address = address
self.local_key = local_key
self.local_key = local_key.encode('latin1')
self.connection_timeout = connection_timeout
self.version = 3.1
self.retry = True
self.dev_type = dev_type
self.port = 6668 # default - do not expect caller to pass in
def __repr__(self):
return '%r' % ((self.id, self.address),) # FIXME can do better than this
def _send_receive(self, payload):
"""
Send single buffer `payload` and receive a single buffer.
Args:
payload(bytes): Data to send.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s.settimeout(self.connection_timeout)
s.connect((self.address, self.port))
s.send(payload)
data = s.recv(1024)
# Some devices fail to send full payload in first response
if self.retry and len(data) < 40:
time.sleep(0.1)
data = s.recv(1024) # try again
s.close()
return data
def set_version(self, version):
self.version = version
def set_dpsUsed(self, dpsUsed):
self.dpsUsed = dpsUsed
def set_retry(self, retry):
self.retry = retry
def generate_payload(self, command, data=None):
"""
Generate the payload to send.
Args:
command(str): The type of command.
This is one of the entries from payload_dict
data(dict, optional): The data to send.
This is what will be passed via the 'dps' entry
"""
json_data = payload_dict[self.dev_type][command]['command']
command_hb = payload_dict[self.dev_type][command]['hexByte']
if 'gwId' in json_data:
json_data['gwId'] = self.id
if 'devId' in json_data:
json_data['devId'] = self.id
if 'uid' in json_data:
json_data['uid'] = self.id # use device ID
if 't' in json_data:
json_data['t'] = str(int(time.time()))
if data is not None:
json_data['dps'] = data
if command_hb == '0d': # CONTROL_NEW
json_data['dps'] = self.dpsUsed
# Create byte buffer from hex data
json_payload = json.dumps(json_data)
json_payload = json_payload.replace(' ', '') # if spaces are not removed device does not respond!
json_payload = json_payload.encode('utf-8')
log.debug('json_payload=%r', json_payload)
if self.version == 3.3:
self.cipher = AESCipher(self.local_key) # expect to connect and then disconnect to set new
json_payload = self.cipher.encrypt(json_payload, False)
self.cipher = None
if command_hb != '0a':
# add the 3.3 header
json_payload = PROTOCOL_VERSION_BYTES_33 + b"\0\0\0\0\0\0\0\0\0\0\0\0" + json_payload
elif command == CONTROL:
# need to encrypt
self.cipher = AESCipher(self.local_key) # expect to connect and then disconnect to set new
json_payload = self.cipher.encrypt(json_payload)
preMd5String = b'data=' + json_payload + b'||lpv=' + PROTOCOL_VERSION_BYTES_31 + b'||' + self.local_key
m = md5()
m.update(preMd5String)
hexdigest = m.hexdigest()
json_payload = PROTOCOL_VERSION_BYTES_31 + hexdigest[8:][:16].encode('latin1') + json_payload
self.cipher = None # expect to connect and then disconnect to set new
postfix_payload = hex2bin(bin2hex(json_payload) + payload_dict[self.dev_type]['suffix'])
assert len(postfix_payload) <= 0xff
postfix_payload_hex_len = '%x' % len(postfix_payload) # single byte 0-255 (0x00-0xff)
buffer = hex2bin( payload_dict[self.dev_type]['prefix'] +
payload_dict[self.dev_type][command]['hexByte'] +
'000000' +
postfix_payload_hex_len ) + postfix_payload
# calc the CRC of everything except where the CRC goes and the suffix
hex_crc = format(binascii.crc32(buffer[:-8]) & 0xffffffff, '08X')
buffer = buffer[:-8] + hex2bin(hex_crc) + buffer[-4:]
return buffer
class Device(XenonDevice):
def __init__(self, dev_id, address, local_key="", dev_type="default"):
super(Device, self).__init__(dev_id, address, local_key, dev_type)
def status(self):
log.debug('status() entry (dev_type is %s)', self.dev_type)
# open device, send request, then close connection
payload = self.generate_payload(DP_QUERY)
data = self._send_receive(payload)
log.debug('status received data=%r', data)
result = data[20:-8] # hard coded offsets
if self.dev_type != 'default':
result = result[15:]
log.debug('result=%r', result)
if result.startswith(b'{'):
# this is the regular expected code path
if not isinstance(result, str):
result = result.decode()
result = json.loads(result)
elif result.startswith(PROTOCOL_VERSION_BYTES_31):
# got an encrypted payload, happens occasionally
# expect resulting json to look similar to:: {"devId":"ID","dps":{"1":true,"2":0},"t":EPOCH_SECS,"s":3_DIGIT_NUM}
# NOTE dps.2 may or may not be present
result = result[len(PROTOCOL_VERSION_BYTES_31):] # remove version header
result = result[16:] # Remove 16-bytes appears to be MD5 hexdigest of payload
cipher = AESCipher(self.local_key)
result = cipher.decrypt(result)
log.debug('decrypted result=%r', result)
if not isinstance(result, str):
result = result.decode()
result = json.loads(result)
elif self.version == 3.3:
cipher = AESCipher(self.local_key)
result = cipher.decrypt(result, False)
log.debug('decrypted result=%r', result)
if not isinstance(result, str):
result = result.decode()
result = json.loads(result)
else:
log.error('Unexpected status() payload=%r', result)
return result
def set_status(self, on, switch=1):
"""
Set status of the device to 'on' or 'off'.
Args:
on(bool): True for 'on', False for 'off'.
switch(int): The switch to set
"""
# open device, send request, then close connection
if isinstance(switch, int):
switch = str(switch) # index and payload is a string
payload = self.generate_payload(CONTROL, {switch:on})
data = self._send_receive(payload)
log.debug('set_status received data=%r', data)
return data
def set_value(self, index, value):
"""
Set int value of any index.
Args:
index(int): index to set
value(int): new value for the index
"""
# open device, send request, then close connection
if isinstance(index, int):
index = str(index) # index and payload is a string
payload = self.generate_payload(CONTROL, {
index: value})
data = self._send_receive(payload)
return data
def turn_on(self, switch=1):
"""Turn the device on"""
self.set_status(True, switch)
def turn_off(self, switch=1):
"""Turn the device off"""
self.set_status(False, switch)
def set_timer(self, num_secs):
"""
Set a timer.
Args:
num_secs(int): Number of seconds
"""
# Query status, pick last device id as that is probably the timer
status = self.status()
devices = status['dps']
devices_numbers = list(devices.keys())
devices_numbers.sort()
dps_id = devices_numbers[-1]
payload = self.generate_payload(CONTROL, {dps_id:num_secs})
data = self._send_receive(payload)
log.debug('set_timer received data=%r', data)
return data
class OutletDevice(Device):
"""
Represents a Tuya based Smart Plug or Switch.
Args:
dev_id (str): The device id.
address (str): The network address.
local_key (str, optional): The encryption key. Defaults to None.
"""
def __init__(self, dev_id, address, local_key="", dev_type="default"):
super(OutletDevice, self).__init__(dev_id, address, local_key, dev_type)
class CoverDevice(Device):
"""
Represents a Tuya based Smart Window Cover.
Args:
dev_id (str): The device id.
address (str): The network address.
local_key (str, optional): The encryption key. Defaults to None.
"""
DPS_INDEX_MOVE = '1'
DPS_INDEX_BL = '101'
DPS_2_STATE = {
'1':'movement',
'101':'backlight',
}
def __init__(self, dev_id, address, local_key="", dev_type="default"):
super(CoverDevice, self).__init__(dev_id, address, local_key, dev_type)
def open_cover(self, switch=1):
"""Open the cover"""
self.set_status('on', switch)
def close_cover(self, switch=1):
"""Close the cover"""
self.set_status('off', switch)
def stop_cover(self, switch=1):
"""Stop the motion of the cover"""
self.set_status('stop', switch)
class BulbDevice(Device):
"""
Represents a Tuya based Smart Light/Bulb.
Args:
dev_id (str): The device id.
address (str): The network address.
local_key (str, optional): The encryption key. Defaults to None.
"""
DPS_INDEX_ON = '1'
DPS_INDEX_MODE = '2'
DPS_INDEX_BRIGHTNESS = '3'
DPS_INDEX_COLOURTEMP = '4'
DPS_INDEX_COLOUR = '5'
DPS = 'dps'
DPS_MODE_COLOUR = 'colour'
DPS_MODE_WHITE = 'white'
DPS_2_STATE = {
'1':'is_on',
'2':'mode',
'3':'brightness',
'4':'colourtemp',
'5':'colour',
}
def __init__(self, dev_id, address, local_key="", dev_type="default"):
super(BulbDevice, self).__init__(dev_id, address, local_key, dev_type)
@staticmethod
def _rgb_to_hexvalue(r, g, b):
"""
Convert an RGB value to the hex representation expected by tuya.
Index '5' (DPS_INDEX_COLOUR) is assumed to be in the format:
rrggbb0hhhssvv
While r, g and b are just hexadecimal values of the corresponding
Red, Green and Blue values, the h, s and v values (which are values
between 0 and 1) are scaled to 360 (h) and 255 (s and v) respectively.
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255.
"""
rgb = [r,g,b]
hsv = colorsys.rgb_to_hsv(rgb[0]/255, rgb[1]/255, rgb[2]/255)
hexvalue = ""
for value in rgb:
temp = str(hex(int(value))).replace("0x","")
if len(temp) == 1:
temp = "0" + temp
hexvalue = hexvalue + temp
hsvarray = [int(hsv[0] * 360), int(hsv[1] * 255), int(hsv[2] * 255)]
hexvalue_hsv = ""
for value in hsvarray:
temp = str(hex(int(value))).replace("0x","")
if len(temp) == 1:
temp = "0" + temp
hexvalue_hsv = hexvalue_hsv + temp
if len(hexvalue_hsv) == 7:
hexvalue = hexvalue + "0" + hexvalue_hsv
else:
hexvalue = hexvalue + "00" + hexvalue_hsv
return hexvalue
@staticmethod
def _hexvalue_to_rgb(hexvalue):
"""
Converts the hexvalue used by Tuya for colour representation into
an RGB value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
"""
r = int(hexvalue[0:2], 16)
g = int(hexvalue[2:4], 16)
b = int(hexvalue[4:6], 16)
return (r, g, b)
@staticmethod
def _hexvalue_to_hsv(hexvalue):
"""
Converts the hexvalue used by Tuya for colour representation into
an HSV value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
"""
h = int(hexvalue[7:10], 16) / 360
s = int(hexvalue[10:12], 16) / 255
v = int(hexvalue[12:14], 16) / 255
return (h, s, v)
def set_colour(self, r, g, b):
"""
Set colour of an rgb bulb.
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255.
"""
if not 0 <= r <= 255:
raise ValueError("The value for red needs to be between 0 and 255.")
if not 0 <= g <= 255:
raise ValueError("The value for green needs to be between 0 and 255.")
if not 0 <= b <= 255:
raise ValueError("The value for blue needs to be between 0 and 255.")
#print(BulbDevice)
hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b)
payload = self.generate_payload(CONTROL, {
self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR,
self.DPS_INDEX_COLOUR: hexvalue})
data = self._send_receive(payload)
return data
def set_white(self, brightness, colourtemp):
"""
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
colourtemp(int): Value for the colour temperature (0-255).
"""
if not 25 <= brightness <= 255:
raise ValueError("The brightness needs to be between 25 and 255.")
if not 0 <= colourtemp <= 255:
raise ValueError("The colour temperature needs to be between 0 and 255.")
payload = self.generate_payload(CONTROL, {
self.DPS_INDEX_MODE: self.DPS_MODE_WHITE,
self.DPS_INDEX_BRIGHTNESS: brightness,
self.DPS_INDEX_COLOURTEMP: colourtemp})
data = self._send_receive(payload)
return data
def set_brightness(self, brightness):
"""
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
"""
if not 25 <= brightness <= 255:
raise ValueError("The brightness needs to be between 25 and 255.")
payload = self.generate_payload(CONTROL, {self.DPS_INDEX_BRIGHTNESS: brightness})
data = self._send_receive(payload)
return data
def set_colourtemp(self, colourtemp):
"""
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature (0-255).
"""
if not 0 <= colourtemp <= 255:
raise ValueError("The colour temperature needs to be between 0 and 255.")
payload = self.generate_payload(CONTROL, {self.DPS_INDEX_COLOURTEMP: colourtemp})
data = self._send_receive(payload)
return data
def brightness(self):
"""Return brightness value"""
return self.status()[self.DPS][self.DPS_INDEX_BRIGHTNESS]
def colourtemp(self):
"""Return colour temperature"""
return self.status()[self.DPS][self.DPS_INDEX_COLOURTEMP]
def colour_rgb(self):
"""Return colour as RGB value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
return BulbDevice._hexvalue_to_rgb(hexvalue)
def colour_hsv(self):
"""Return colour as HSV value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
return BulbDevice._hexvalue_to_hsv(hexvalue)
def state(self):
"""Return state of Bulb"""
status = self.status()
state = {}
for key in status[self.DPS].keys():
if(int(key)<=5):
state[self.DPS_2_STATE[key]]=status[self.DPS][key]
return state
# Utility Functions
# SCAN network for Tuya devices
MAXCOUNT = 15 # How many tries before stopping
UDPPORT = 6666 # Tuya 3.1 UDP Port
UDPPORTS = 6667 # Tuya 3.3 encrypted UDP Port
TIMEOUT = 3.0 # Seconds to wait for a broadcast
# UDP packet payload decryption - credit to tuya-convert
pad = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
encrypt = lambda msg, key: AES.new(key, AES.MODE_ECB).encrypt(pad(msg).encode())
decrypt = lambda msg, key: unpad(AES.new(key, AES.MODE_ECB).decrypt(msg)).decode()
udpkey = md5(b"yGAdlopoPVldABfn").digest()
decrypt_udp = lambda msg: decrypt(msg, udpkey)
# Return positive number or zero
def floor(x):
if x > 0:
return x
else:
return 0
def appenddevice(newdevice, devices):
if(newdevice['ip'] in devices):
return True
"""
for i in devices:
if i['ip'] == newdevice['ip']:
return True
"""
devices[newdevice['ip']] = newdevice
return False
# Scan function shortcut
def scan(maxretry = MAXCOUNT):
"""Scans your network for Tuya devices with output to stdout
"""
d = deviceScan(True,maxretry)
# Scan function
def deviceScan(verbose = False,maxretry = MAXCOUNT):
"""Scans your network for Tuya devices and returns dictionary of devices discovered
devices = tinytuya.deviceScan(verbose)
Parameters:
verbose = True or False, print formatted output to stdout
Response:
devices = Dictionary of all devices found
To unpack data, you can do something like this:
devices = tinytuya.deviceScan()
for ip in devices:
id = devices[ip]['gwId']
key = devices[ip]['productKey']
vers = devices[ip]['version']
dps = devices[ip]['dps']
"""
# Enable UDP listening broadcasting mode on UDP port 6666 - 3.1 Devices
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
client.bind(("", UDPPORT))
client.settimeout(TIMEOUT)
# Enable UDP listening broadcasting mode on encrypted UDP port 6667 - 3.3 Devices
clients = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
clients.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
clients.bind(("", UDPPORTS))
clients.settimeout(TIMEOUT)
if(verbose):
print("Scanning on UDP ports %s and %s for devices (%s retries)...\n"%(UDPPORT,UDPPORTS,maxretry))
# globals
devices={}
count = 0
counts = 0
spinnerx = 0
spinner = "|/-\\|"
while (count + counts) <= maxretry:
note = 'invalid'
if(verbose):
print("Scanning... %s\r" % (spinner[spinnerx]), end = '')
spinnerx = (spinnerx + 1) % 4
if (count <= counts): # alternate between 6666 and 6667 ports
try:
data, addr = client.recvfrom(4048)
except:
# Timeout
count = count + 1
continue
else:
try:
data, addr = clients.recvfrom(4048)
except:
# Timeout
counts = counts + 1
continue
ip = addr[0]
gwId = productKey = version = ""
result = data
try:
result = data[20:-8]
try:
result = decrypt_udp(result)
except:
result = result.decode()
result = json.loads(result)
note = 'Valid'
ip = result['ip']
gwId = result['gwId']
productKey = result['productKey']
version = result['version']
except:
print("* Unexpected payload=%r\n", result)
result = {"ip": ip}
note = "Unknown"
# check to see if we have seen this device before and add to devices array
if appenddevice(result, devices) == False:
# new device found - back off count if we keep getting new devices
if(version=='3.1'):
count = floor(count - 1)
else:
counts = floor(counts - 1)
if(verbose):
print("FOUND Device [%s payload]: %s\n ID = %s, product = %s, Version = %s" % (note,ip,gwId,productKey,version))
try:
if(version == '3.1'):
# Version 3.1 - no device key requires - poll for status data points
d = OutletDevice(gwId, ip)
d.set_version(3.1)
dpsdata = d.status()
devices[ip]['dps'] = dpsdata
if(verbose):
print(" Status = %s" % dpsdata)
else:
# Version 3.3+ requires device key
if(verbose):
print(" No Stats - Device Key required to poll for status")
except:
if(verbose):
print(" No Stats for %s: Unable to poll"%ip)
devices[ip]['err'] = 'Unable to poll'
else:
if(version=='3.1'):
count = count + 1
else:
counts = counts + 1
if(verbose):
print(" \nScan Complete! Found %s devices.\n"%len(devices))
return(devices)
| [
"logging.getLogger",
"json.loads",
"hashlib.md5",
"socket.socket",
"base64.b64encode",
"json.dumps",
"base64.b64decode",
"time.sleep",
"Crypto.Cipher.AES.new",
"time.time",
"binascii.crc32",
"colorsys.rgb_to_hsv",
"pyaes.AESModeOfOperationECB"
] | [((2535, 2562), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2552, 2562), False, 'import logging\n'), ((26706, 26774), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM', 'socket.IPPROTO_UDP'], {}), '(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n', (26719, 26774), False, 'import socket\n'), ((27009, 27077), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM', 'socket.IPPROTO_UDP'], {}), '(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n', (27022, 27077), False, 'import socket\n'), ((8469, 8518), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (8482, 8518), False, 'import socket\n'), ((10231, 10252), 'json.dumps', 'json.dumps', (['json_data'], {}), '(json_data)\n', (10241, 10252), False, 'import json\n'), ((19333, 19394), 'colorsys.rgb_to_hsv', 'colorsys.rgb_to_hsv', (['(rgb[0] / 255)', '(rgb[1] / 255)', '(rgb[2] / 255)'], {}), '(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255)\n', (19352, 19394), False, 'import colorsys\n'), ((25307, 25331), 'hashlib.md5', 'md5', (["b'yGAdlopoPVldABfn'"], {}), "(b'yGAdlopoPVldABfn')\n", (25310, 25331), False, 'from hashlib import md5\n'), ((4092, 4128), 'Crypto.Cipher.AES.new', 'AES.new', (['self.key'], {'mode': 'AES.MODE_ECB'}), '(self.key, mode=AES.MODE_ECB)\n', (4099, 4128), False, 'from Crypto.Cipher import AES\n'), ((4494, 4524), 'base64.b64encode', 'base64.b64encode', (['crypted_text'], {}), '(crypted_text)\n', (4510, 4524), False, 'import base64\n'), ((4676, 4697), 'base64.b64decode', 'base64.b64decode', (['enc'], {}), '(enc)\n', (4692, 4697), False, 'import base64\n'), ((4742, 4773), 'Crypto.Cipher.AES.new', 'AES.new', (['self.key', 'AES.MODE_ECB'], {}), '(self.key, AES.MODE_ECB)\n', (4749, 4773), False, 'from Crypto.Cipher import AES\n'), ((8857, 8872), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (8867, 8872), False, 'import time\n'), ((13127, 13145), 'json.loads', 'json.loads', (['result'], {}), '(result)\n', (13137, 13145), False, 'import json\n'), ((25159, 25185), 'Crypto.Cipher.AES.new', 'AES.new', (['key', 'AES.MODE_ECB'], {}), '(key, AES.MODE_ECB)\n', (25166, 25185), False, 'from Crypto.Cipher import AES\n'), ((28389, 28407), 'json.loads', 'json.loads', (['result'], {}), '(result)\n', (28399, 28407), False, 'import json\n'), ((4274, 4311), 'pyaes.AESModeOfOperationECB', 'pyaes.AESModeOfOperationECB', (['self.key'], {}), '(self.key)\n', (4301, 4311), False, 'import pyaes\n'), ((4933, 4970), 'pyaes.AESModeOfOperationECB', 'pyaes.AESModeOfOperationECB', (['self.key'], {}), '(self.key)\n', (4960, 4970), False, 'import pyaes\n'), ((11252, 11257), 'hashlib.md5', 'md5', ([], {}), '()\n', (11255, 11257), False, 'from hashlib import md5\n'), ((12127, 12154), 'binascii.crc32', 'binascii.crc32', (['buffer[:-8]'], {}), '(buffer[:-8])\n', (12141, 12154), False, 'import binascii\n'), ((13882, 13900), 'json.loads', 'json.loads', (['result'], {}), '(result)\n', (13892, 13900), False, 'import json\n'), ((9985, 9996), 'time.time', 'time.time', ([], {}), '()\n', (9994, 9996), False, 'import time\n'), ((14199, 14217), 'json.loads', 'json.loads', (['result'], {}), '(result)\n', (14209, 14217), False, 'import json\n'), ((25247, 25273), 'Crypto.Cipher.AES.new', 'AES.new', (['key', 'AES.MODE_ECB'], {}), '(key, AES.MODE_ECB)\n', (25254, 25273), False, 'from Crypto.Cipher import AES\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-11-21 06:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0006_user_terminal_password'),
]
operations = [
migrations.AddField(
model_name='user',
name='rank',
field=models.IntegerField(default=1),
),
]
| [
"django.db.models.IntegerField"
] | [((396, 426), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(1)'}), '(default=1)\n', (415, 426), False, 'from django.db import migrations, models\n')] |
""" Contains base tf losses """
import tensorflow.compat.v1 as tf
def softmax_cross_entropy(labels, logits, *args, **kwargs):
""" Multi-class CE which takes plain or one-hot labels
Parameters
----------
labels : tf.Tensor
logits : tf.Tensor
args
other positional parameters from `tf.losses.softmax_cross_entropy`
kwargs
other named parameters from `tf.losses.softmax_cross_entropy`
Returns
-------
tf.Tensor
"""
labels_shape = tf.shape(labels)
logits_shape = tf.shape(logits)
c = tf.cast(tf.equal(labels_shape, logits_shape), tf.int32)
e = tf.equal(tf.reduce_sum(c, axis=-1), logits_shape.shape[-1])
labels = tf.cond(e, lambda: tf.cast(labels, dtype=logits.dtype),
lambda: tf.one_hot(tf.cast(labels, tf.int32), logits_shape[-1], dtype=logits.dtype))
return tf.losses.softmax_cross_entropy(labels, logits, *args, **kwargs)
| [
"tensorflow.compat.v1.equal",
"tensorflow.compat.v1.shape",
"tensorflow.compat.v1.reduce_sum",
"tensorflow.compat.v1.cast",
"tensorflow.compat.v1.losses.softmax_cross_entropy"
] | [((497, 513), 'tensorflow.compat.v1.shape', 'tf.shape', (['labels'], {}), '(labels)\n', (505, 513), True, 'import tensorflow.compat.v1 as tf\n'), ((533, 549), 'tensorflow.compat.v1.shape', 'tf.shape', (['logits'], {}), '(logits)\n', (541, 549), True, 'import tensorflow.compat.v1 as tf\n'), ((868, 932), 'tensorflow.compat.v1.losses.softmax_cross_entropy', 'tf.losses.softmax_cross_entropy', (['labels', 'logits', '*args'], {}), '(labels, logits, *args, **kwargs)\n', (899, 932), True, 'import tensorflow.compat.v1 as tf\n'), ((566, 602), 'tensorflow.compat.v1.equal', 'tf.equal', (['labels_shape', 'logits_shape'], {}), '(labels_shape, logits_shape)\n', (574, 602), True, 'import tensorflow.compat.v1 as tf\n'), ((631, 656), 'tensorflow.compat.v1.reduce_sum', 'tf.reduce_sum', (['c'], {'axis': '(-1)'}), '(c, axis=-1)\n', (644, 656), True, 'import tensorflow.compat.v1 as tf\n'), ((714, 749), 'tensorflow.compat.v1.cast', 'tf.cast', (['labels'], {'dtype': 'logits.dtype'}), '(labels, dtype=logits.dtype)\n', (721, 749), True, 'import tensorflow.compat.v1 as tf\n'), ((791, 816), 'tensorflow.compat.v1.cast', 'tf.cast', (['labels', 'tf.int32'], {}), '(labels, tf.int32)\n', (798, 816), True, 'import tensorflow.compat.v1 as tf\n')] |
from datetime import datetime, timedelta
from urllib import parse
from ably.http.paginatedresult import PaginatedResult
from ably.types.mixins import EncodeDataMixin
def _ms_since_epoch(dt):
epoch = datetime.utcfromtimestamp(0)
delta = dt - epoch
return int(delta.total_seconds() * 1000)
def _dt_from_ms_epoch(ms):
epoch = datetime.utcfromtimestamp(0)
return epoch + timedelta(milliseconds=ms)
class PresenceAction:
ABSENT = 0
PRESENT = 1
ENTER = 2
LEAVE = 3
UPDATE = 4
class PresenceMessage(EncodeDataMixin):
def __init__(self,
id=None, # TP3a
action=None, # TP3b
client_id=None, # TP3c
connection_id=None, # TP3d
data=None, # TP3e
encoding=None, # TP3f
timestamp=None, # TP3g
member_key=None, # TP3h (for RT only)
extras=None, # TP3i (functionality not specified)
):
self.__id = id
self.__action = action
self.__client_id = client_id
self.__connection_id = connection_id
self.__data = data
self.__encoding = encoding
self.__timestamp = timestamp
self.__member_key = member_key
self.__extras = extras
@property
def id(self):
return self.__id
@property
def action(self):
return self.__action
@property
def client_id(self):
return self.__client_id
@property
def connection_id(self):
return self.__connection_id
@property
def data(self):
return self.__data
@property
def encoding(self):
return self.__encoding
@property
def timestamp(self):
return self.__timestamp
@property
def member_key(self):
if self.connection_id and self.client_id:
return "%s:%s" % (self.connection_id, self.client_id)
@property
def extras(self):
return self.__extras
@staticmethod
def from_encoded(obj, cipher=None):
id = obj.get('id')
action = obj.get('action', PresenceAction.ENTER)
client_id = obj.get('clientId')
connection_id = obj.get('connectionId')
data = obj.get('data')
encoding = obj.get('encoding', '')
timestamp = obj.get('timestamp')
# member_key = obj.get('memberKey', None)
extras = obj.get('extras', None)
if timestamp is not None:
timestamp = _dt_from_ms_epoch(timestamp)
decoded_data = PresenceMessage.decode(data, encoding, cipher)
return PresenceMessage(
id=id,
action=action,
client_id=client_id,
connection_id=connection_id,
timestamp=timestamp,
extras=extras,
**decoded_data
)
class Presence:
def __init__(self, channel):
self.__base_path = '/channels/%s/' % parse.quote_plus(channel.name)
self.__binary = channel.ably.options.use_binary_protocol
self.__http = channel.ably.http
self.__cipher = channel.cipher
def _path_with_qs(self, rel_path, qs=None):
path = rel_path
if qs:
path += ('?' + parse.urlencode(qs))
return path
async def get(self, limit=None):
qs = {}
if limit:
if limit > 1000:
raise ValueError("The maximum allowed limit is 1000")
qs['limit'] = limit
path = self._path_with_qs(self.__base_path + 'presence', qs)
presence_handler = make_presence_response_handler(self.__cipher)
return await PaginatedResult.paginated_query(
self.__http, url=path, response_processor=presence_handler)
async def history(self, limit=None, direction=None, start=None, end=None):
qs = {}
if limit:
if limit > 1000:
raise ValueError("The maximum allowed limit is 1000")
qs['limit'] = limit
if direction:
qs['direction'] = direction
if start:
if isinstance(start, int):
qs['start'] = start
else:
qs['start'] = _ms_since_epoch(start)
if end:
if isinstance(end, int):
qs['end'] = end
else:
qs['end'] = _ms_since_epoch(end)
if 'start' in qs and 'end' in qs and qs['start'] > qs['end']:
raise ValueError("'end' parameter has to be greater than or equal to 'start'")
path = self._path_with_qs(self.__base_path + 'presence/history', qs)
presence_handler = make_presence_response_handler(self.__cipher)
return await PaginatedResult.paginated_query(
self.__http, url=path, response_processor=presence_handler)
def make_presence_response_handler(cipher):
def encrypted_presence_response_handler(response):
messages = response.to_native()
return PresenceMessage.from_encoded_array(messages, cipher=cipher)
return encrypted_presence_response_handler
| [
"datetime.datetime.utcfromtimestamp",
"ably.http.paginatedresult.PaginatedResult.paginated_query",
"urllib.parse.urlencode",
"datetime.timedelta",
"urllib.parse.quote_plus"
] | [((206, 234), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['(0)'], {}), '(0)\n', (231, 234), False, 'from datetime import datetime, timedelta\n'), ((344, 372), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['(0)'], {}), '(0)\n', (369, 372), False, 'from datetime import datetime, timedelta\n'), ((392, 418), 'datetime.timedelta', 'timedelta', ([], {'milliseconds': 'ms'}), '(milliseconds=ms)\n', (401, 418), False, 'from datetime import datetime, timedelta\n'), ((2953, 2983), 'urllib.parse.quote_plus', 'parse.quote_plus', (['channel.name'], {}), '(channel.name)\n', (2969, 2983), False, 'from urllib import parse\n'), ((3651, 3747), 'ably.http.paginatedresult.PaginatedResult.paginated_query', 'PaginatedResult.paginated_query', (['self.__http'], {'url': 'path', 'response_processor': 'presence_handler'}), '(self.__http, url=path, response_processor=\n presence_handler)\n', (3682, 3747), False, 'from ably.http.paginatedresult import PaginatedResult\n'), ((4714, 4810), 'ably.http.paginatedresult.PaginatedResult.paginated_query', 'PaginatedResult.paginated_query', (['self.__http'], {'url': 'path', 'response_processor': 'presence_handler'}), '(self.__http, url=path, response_processor=\n presence_handler)\n', (4745, 4810), False, 'from ably.http.paginatedresult import PaginatedResult\n'), ((3243, 3262), 'urllib.parse.urlencode', 'parse.urlencode', (['qs'], {}), '(qs)\n', (3258, 3262), False, 'from urllib import parse\n')] |
# Copyright 2019 IBM Corporation
#
# 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 typing import Any, Dict, Iterable, List, Optional, Tuple
import itertools
import warnings
import random
import math
from collections import ChainMap
from lale.util.Visitor import Visitor
from lale.search.search_space import SearchSpace, SearchSpaceObject, SearchSpaceEnum
from lale.search.schema2search_space import schemaToSearchSpace
from lale.search.PGO import PGO
# To avoid import cycle, since we only realy on lale.operators for types
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from lale.operators import PlannedOperator, OperatorChoice, PlannedIndividualOp, PlannedPipeline
SearchSpaceGrid = Dict[str,SearchSpace]
def get_search_space_grids( op:'PlannedOperator',
num_grids:Optional[float]=None,
pgo:Optional[PGO]=None)->List[SearchSpaceGrid]:
""" Top level function: given a lale operator, returns a list of hp grids.
Parameters
----------
op : The lale PlannedOperator
num_grids: integer or float, optional
if set to an integer => 1, it will determine how many parameter grids will be returned (at most)
if set to an float between 0 and 1, it will determine what fraction should be returned
note that setting it to 1 is treated as in integer. To return all results, use None
"""
all_parameters = SearchSpaceGridVisitor.run(op, pgo=pgo)
if num_grids is None:
return all_parameters
else:
if num_grids <= 0:
warnings.warn(f"get_search_space_grids(num_grids={num_grids}) called with a non-positive value for lale_num_grids")
return []
if num_grids >= 1:
samples = math.ceil(num_grids)
if samples >= len(all_parameters):
return all_parameters
else:
warnings.warn(f"get_search_space_grids(num_grids={num_grids}) sampling {math.ceil(num_grids)}/{len(all_parameters)}")
return random.sample(all_parameters, math.ceil(num_grids))
else:
samples = round(len(all_parameters)*num_grids)
warnings.warn(f"get_search_space_grids(num_grids={num_grids}) sampling {samples}/{len(all_parameters)}")
return random.sample(all_parameters, samples)
def SearchSpaceObjectChoiceToGrid(keys:List[str], values:Tuple)->SearchSpaceGrid:
assert len(keys) == len(values)
return dict(zip(keys, values))
def SearchSpaceObjectectToGrid(hp:SearchSpaceObject)->List[SearchSpaceGrid]:
return [SearchSpaceObjectChoiceToGrid(hp.keys, c) for c in hp.choices]
def searchSpaceToGrids(hp:SearchSpace)->List[SearchSpaceGrid]:
if isinstance(hp, SearchSpaceObject):
return SearchSpaceObjectectToGrid(hp)
else:
raise ValueError("Can only convert SearchSpaceObject into a GridSearchCV schema")
def schemaToSearchSpaceGrids(longName:str,
name:str,
schema,
pgo:Optional[PGO]=None)->List[SearchSpaceGrid]:
h = schemaToSearchSpace(longName, name, schema, pgo=pgo)
if h is None:
return []
grids = searchSpaceToGrids(h)
return grids
class SearchSpaceGridVisitor(Visitor):
pgo:Optional[PGO]
@classmethod
def run(cls, op:'PlannedOperator', pgo:Optional[PGO]=None):
visitor = cls(pgo=pgo)
accepting_op:Any = op
return accepting_op.accept(visitor)
def __init__(self, pgo:Optional[PGO]=None):
super(SearchSpaceGridVisitor, self).__init__()
self.pgo = pgo
def augment_grid(self, grid:SearchSpaceGrid, hyperparams)->SearchSpaceGrid:
if not hyperparams:
return grid
ret = dict(grid)
for (k,v) in hyperparams.items():
if k not in ret:
ret[k] = SearchSpaceEnum([v])
return ret
def visitPlannedIndividualOp(self, op:'PlannedIndividualOp')->List[SearchSpaceGrid]:
schema = op.hyperparam_schema_with_hyperparams()
module = op._impl.__module__
if module is None or module == str.__class__.__module__:
long_name = op.name()
else:
long_name = module + '.' + op.name()
name = op.name()
grids = schemaToSearchSpaceGrids(long_name, name, schema, pgo=self.pgo)
if hasattr(op, '_hyperparams'):
hyperparams = op._hyperparams
if hyperparams and not grids:
grids = [{}]
augmented_grids = [self.augment_grid(g, hyperparams) for g in grids]
return augmented_grids
else:
return grids
visitTrainableIndividualOp = visitPlannedIndividualOp
visitTrainedIndividualOp = visitPlannedIndividualOp
def visitPlannedPipeline(self, op:'PlannedPipeline')->List[SearchSpaceGrid]:
param_grids:List[List[SearchSpaceGrid]] = [
nest_all_HPparams(s.name(), s.accept(self)) for s in op.steps()]
param_grids_product:Iterable[Iterable[SearchSpaceGrid]] = itertools.product(*param_grids)
chained_grids:List[SearchSpaceGrid] = [
dict(ChainMap(*gridline)) for gridline in param_grids_product]
return chained_grids
visitTrainablePipeline = visitPlannedPipeline
visitTrainedPipeline = visitPlannedPipeline
def visitOperatorChoice(self, op:'OperatorChoice')->List[SearchSpaceGrid]:
choice_name:str = "_lale_discriminant"
ret:List[SearchSpaceGrid] = []
for s in op.steps():
# if not isinstance(s, PlannedOperator):
# raise ValueError("This method should really be defined on PlannedOperatorChoice")
# else:
grids:List[SearchSpaceGrid] = s.accept(self)
# If there are no parameters, we still need to add a choice for the discriminant
if not grids:
grids = [{}]
op_name:str = s.name()
discriminated_grids:List[SearchSpaceGrid]=[{**d, choice_name:SearchSpaceEnum([op_name])} for d in grids]
ret.extend(discriminated_grids)
return ret
# Auxiliary functions
def nest_HPparam(name:str, key:str):
return name + "__" + key
def nest_HPparams(name:str, grid:SearchSpaceGrid)->SearchSpaceGrid:
return {(nest_HPparam(name, k)):v for k, v in grid.items()}
def nest_all_HPparams(name:str, grids:List[SearchSpaceGrid])->List[SearchSpaceGrid]:
""" Given the name of an operator in a pipeline, this transforms every key(parameter name) in the grids
to use the operator name as a prefix (separated by __). This is the convention in scikit-learn pipelines.
"""
return [nest_HPparams(name, grid) for grid in grids]
def unnest_HPparams(k:str)->List[str]:
return k.split("__") | [
"random.sample",
"math.ceil",
"lale.search.schema2search_space.schemaToSearchSpace",
"lale.search.search_space.SearchSpaceEnum",
"itertools.product",
"collections.ChainMap",
"warnings.warn"
] | [((3595, 3647), 'lale.search.schema2search_space.schemaToSearchSpace', 'schemaToSearchSpace', (['longName', 'name', 'schema'], {'pgo': 'pgo'}), '(longName, name, schema, pgo=pgo)\n', (3614, 3647), False, 'from lale.search.schema2search_space import schemaToSearchSpace\n'), ((5566, 5597), 'itertools.product', 'itertools.product', (['*param_grids'], {}), '(*param_grids)\n', (5583, 5597), False, 'import itertools\n'), ((2059, 2184), 'warnings.warn', 'warnings.warn', (['f"""get_search_space_grids(num_grids={num_grids}) called with a non-positive value for lale_num_grids"""'], {}), "(\n f'get_search_space_grids(num_grids={num_grids}) called with a non-positive value for lale_num_grids'\n )\n", (2072, 2184), False, 'import warnings\n'), ((2246, 2266), 'math.ceil', 'math.ceil', (['num_grids'], {}), '(num_grids)\n', (2255, 2266), False, 'import math\n'), ((2788, 2826), 'random.sample', 'random.sample', (['all_parameters', 'samples'], {}), '(all_parameters, samples)\n', (2801, 2826), False, 'import random\n'), ((4369, 4389), 'lale.search.search_space.SearchSpaceEnum', 'SearchSpaceEnum', (['[v]'], {}), '([v])\n', (4384, 4389), False, 'from lale.search.search_space import SearchSpace, SearchSpaceObject, SearchSpaceEnum\n'), ((5663, 5682), 'collections.ChainMap', 'ChainMap', (['*gridline'], {}), '(*gridline)\n', (5671, 5682), False, 'from collections import ChainMap\n'), ((2557, 2577), 'math.ceil', 'math.ceil', (['num_grids'], {}), '(num_grids)\n', (2566, 2577), False, 'import math\n'), ((6536, 6562), 'lale.search.search_space.SearchSpaceEnum', 'SearchSpaceEnum', (['[op_name]'], {}), '([op_name])\n', (6551, 6562), False, 'from lale.search.search_space import SearchSpace, SearchSpaceObject, SearchSpaceEnum\n'), ((2458, 2478), 'math.ceil', 'math.ceil', (['num_grids'], {}), '(num_grids)\n', (2467, 2478), False, 'import math\n')] |
"""."""
class Node(object):
"""."""
def __init__(self, val, next=None):
"""."""
self.val = val
self.next = next
def test_2_2():
"""."""
from CTCI_2_2 import kth_to_last
head = Node('a', Node('b', Node('c', Node('d'))))
assert kth_to_last(2, head) == ['c', 'd']
| [
"CTCI_2_2.kth_to_last"
] | [((279, 299), 'CTCI_2_2.kth_to_last', 'kth_to_last', (['(2)', 'head'], {}), '(2, head)\n', (290, 299), False, 'from CTCI_2_2 import kth_to_last\n')] |
# -*- coding: utf-8 -*-
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
# PCBA from MoleculeNet for the prediction of biological activities
import pandas as pd
from dgl.data.utils import get_download_dir, download, _get_dgl_url, extract_archive
from .csv_dataset import MoleculeCSVDataset
from ..utils.mol_to_graph import smiles_to_bigraph
__all__ = ['PCBA']
class PCBA(MoleculeCSVDataset):
r"""PCBA from MoleculeNet for the prediction of biological activities
PubChem BioAssay (PCBA) is a database consisting of biological activities of small molecules
generated by high-throughput screening. This dataset is a subset of PCBA, containing 128
bioassays measured over 400 thousand compounds.
References:
* [1] MoleculeNet: A Benchmark for Molecular Machine Learning.
* [2] Massively Multitask Networks for Drug Discovery.
Parameters
----------
smiles_to_graph: callable, str -> DGLGraph
A function turning a SMILES string into a DGLGraph.
Default to :func:`dgllife.utils.smiles_to_bigraph`.
node_featurizer : callable, rdkit.Chem.rdchem.Mol -> dict
Featurization for nodes like atoms in a molecule, which can be used to update
ndata for a DGLGraph. Default to None.
edge_featurizer : callable, rdkit.Chem.rdchem.Mol -> dict
Featurization for edges like bonds in a molecule, which can be used to update
edata for a DGLGraph. Default to None.
load : bool
Whether to load the previously pre-processed dataset or pre-process from scratch.
``load`` should be False when we want to try different graph construction and
featurization methods and need to preprocess from scratch. Default to False.
log_every : bool
Print a message every time ``log_every`` molecules are processed. Default to 1000.
cache_file_path : str
Path to the cached DGLGraphs, default to 'pcba_dglgraph.bin'.
n_jobs : int
The maximum number of concurrently running jobs for graph construction and featurization,
using joblib backend. Default to 1.
Examples
--------
>>> import torch
>>> from dgllife.data import PCBA
>>> from dgllife.utils import smiles_to_bigraph, CanonicalAtomFeaturizer
>>> dataset = PCBA(smiles_to_bigraph, CanonicalAtomFeaturizer())
>>> # Get size of the dataset
>>> len(dataset)
437929
>>> # Get the 0th datapoint, consisting of SMILES, DGLGraph, labels, and masks
>>> dataset[0]
('CC(=O)N1CCC2(CC1)NC(=O)N(c1ccccc1)N2',
DGLGraph(num_nodes=20, num_edges=44,
ndata_schemes={'h': Scheme(shape=(74,), dtype=torch.float32)}
edata_schemes={}),
tensor([0., ..., 0.]),
tensor([1., ..., 0.]))
The dataset instance also contains information about molecule ids.
>>> dataset.ids[i]
We can also get the id along with SMILES, DGLGraph, labels, and masks at once.
>>> dataset.load_full = True
>>> dataset[0]
('CC(=O)N1CCC2(CC1)NC(=O)N(c1ccccc1)N2',
DGLGraph(num_nodes=20, num_edges=44,
ndata_schemes={'h': Scheme(shape=(74,), dtype=torch.float32)}
edata_schemes={}),
tensor([0., ..., 0.]),
tensor([1., ..., 0.]),
'CID1511280')
To address the imbalance between positive and negative samples, we can re-weight
positive samples for each task based on the training datapoints.
>>> train_ids = torch.arange(1000)
>>> dataset.task_pos_weights(train_ids)
tensor([7.3400, 489.0000, ..., 1.0000])
"""
def __init__(self,
smiles_to_graph=smiles_to_bigraph,
node_featurizer=None,
edge_featurizer=None,
load=False,
log_every=1000,
cache_file_path='./pcba_dglgraph.bin',
n_jobs=1):
self._url = 'dataset/pcba.zip'
data_path = get_download_dir() + '/pcba.zip'
dir_path = get_download_dir() + '/pcba'
download(_get_dgl_url(self._url), path=data_path, overwrite=False)
extract_archive(data_path, dir_path)
df = pd.read_csv(dir_path + '/pcba.csv')
self.ids = df['mol_id'].tolist()
self.load_full = False
df = df.drop(columns=['mol_id'])
super(PCBA, self).__init__(df=df,
smiles_to_graph=smiles_to_graph,
node_featurizer=node_featurizer,
edge_featurizer=edge_featurizer,
smiles_column='smiles',
cache_file_path=cache_file_path,
load=load,
log_every=log_every,
init_mask=True,
n_jobs=n_jobs)
self.ids = [self.ids[i] for i in self.valid_ids]
def __getitem__(self, item):
"""Get datapoint with index
Parameters
----------
item : int
Datapoint index
Returns
-------
str
SMILES for the ith datapoint
DGLGraph
DGLGraph for the ith datapoint
Tensor of dtype float32 and shape (T)
Labels of the ith datapoint for all tasks. T for the number of tasks.
Tensor of dtype float32 and shape (T)
Binary masks of the ith datapoint indicating the existence of labels for all tasks.
str, optional
Id for the ith datapoint, returned only when ``self.load_full`` is True.
"""
if self.load_full:
return self.smiles[item], self.graphs[item], self.labels[item], \
self.mask[item], self.ids[item]
else:
return self.smiles[item], self.graphs[item], self.labels[item], self.mask[item]
| [
"dgl.data.utils.extract_archive",
"dgl.data.utils.get_download_dir",
"dgl.data.utils._get_dgl_url",
"pandas.read_csv"
] | [((4132, 4168), 'dgl.data.utils.extract_archive', 'extract_archive', (['data_path', 'dir_path'], {}), '(data_path, dir_path)\n', (4147, 4168), False, 'from dgl.data.utils import get_download_dir, download, _get_dgl_url, extract_archive\n'), ((4182, 4217), 'pandas.read_csv', 'pd.read_csv', (["(dir_path + '/pcba.csv')"], {}), "(dir_path + '/pcba.csv')\n", (4193, 4217), True, 'import pandas as pd\n'), ((3968, 3986), 'dgl.data.utils.get_download_dir', 'get_download_dir', ([], {}), '()\n', (3984, 3986), False, 'from dgl.data.utils import get_download_dir, download, _get_dgl_url, extract_archive\n'), ((4020, 4038), 'dgl.data.utils.get_download_dir', 'get_download_dir', ([], {}), '()\n', (4036, 4038), False, 'from dgl.data.utils import get_download_dir, download, _get_dgl_url, extract_archive\n'), ((4066, 4089), 'dgl.data.utils._get_dgl_url', '_get_dgl_url', (['self._url'], {}), '(self._url)\n', (4078, 4089), False, 'from dgl.data.utils import get_download_dir, download, _get_dgl_url, extract_archive\n')] |
from collections import namedtuple
import tensorflow as tf
import numpy as np
from rl.agents.a2c.agent import A2CAgent
TestArgType = namedtuple('ArgType', ['name'])
arg_type = TestArgType('arg')
A = np.array
class A2CAgentTest(tf.test.TestCase):
def test_compute_policy_log_probs(self):
from rl.agents.a2c.agent import compute_policy_log_probs
available_actions = A([[1, 0, 1],
[1, 0, 0],
[1, 1, 1]], dtype=np.float32)
fn_pi = A([[0.2, 0.0, 0.8],
[1.0, 0.0, 0.0],
[0.2, 0.7, 0.1]], dtype=np.float32)
fn_ids = A([2, 0, 1], dtype=np.int32)
arg_pi = {arg_type: A([[0.8, 0.2],
[0.0, 1.0],
[0.5, 0.5]], dtype=np.float32)}
arg_ids = {arg_type: A([0, 1, -1], dtype=np.int32)}
log_probs = compute_policy_log_probs(
available_actions, (fn_pi, arg_pi), (fn_ids, arg_ids)
)
expected_log_probs = np.log([0.8, 1.0, 0.7]) + A([np.log(0.8), np.log(1.0), 0])
with self.test_session() as sess:
log_probs_out = sess.run(log_probs)
self.assertAllClose(log_probs_out, expected_log_probs)
def test_compute_policy_entropy(self):
from rl.agents.a2c.agent import compute_policy_entropy
available_actions = A([[1, 0, 1],
[1, 0, 0],
[1, 1, 1]], dtype=np.float32)
fn_pi = A([[0.2, 0.0, 0.8],
[1.0, 0.0, 0.0],
[0.2, 0.7, 0.1]], dtype=np.float32)
fn_ids = A([2, 0, 1], dtype=np.int32)
arg_pi = {arg_type: A([[0.8, 0.2],
[0.0, 1.0],
[0.5, 0.5]], dtype=np.float32)}
arg_ids = {arg_type: A([0, 1, -1], dtype=np.int32)}
entropy = compute_policy_entropy(
available_actions, (fn_pi, arg_pi), (fn_ids, arg_ids)
)
expected_entropy = (0.50040245 + 0.80181855) / 3.0 + (0.50040245) / 2
with self.test_session() as sess:
entropy_out = sess.run(entropy)
self.assertAllClose(entropy_out, expected_entropy)
if __name__ == '__main__':
tf.test.main()
| [
"collections.namedtuple",
"rl.agents.a2c.agent.compute_policy_entropy",
"numpy.log",
"tensorflow.test.main",
"rl.agents.a2c.agent.compute_policy_log_probs"
] | [((137, 168), 'collections.namedtuple', 'namedtuple', (['"""ArgType"""', "['name']"], {}), "('ArgType', ['name'])\n", (147, 168), False, 'from collections import namedtuple\n'), ((2115, 2129), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (2127, 2129), True, 'import tensorflow as tf\n'), ((862, 941), 'rl.agents.a2c.agent.compute_policy_log_probs', 'compute_policy_log_probs', (['available_actions', '(fn_pi, arg_pi)', '(fn_ids, arg_ids)'], {}), '(available_actions, (fn_pi, arg_pi), (fn_ids, arg_ids))\n', (886, 941), False, 'from rl.agents.a2c.agent import compute_policy_log_probs\n'), ((1785, 1862), 'rl.agents.a2c.agent.compute_policy_entropy', 'compute_policy_entropy', (['available_actions', '(fn_pi, arg_pi)', '(fn_ids, arg_ids)'], {}), '(available_actions, (fn_pi, arg_pi), (fn_ids, arg_ids))\n', (1807, 1862), False, 'from rl.agents.a2c.agent import compute_policy_entropy\n'), ((980, 1003), 'numpy.log', 'np.log', (['[0.8, 1.0, 0.7]'], {}), '([0.8, 1.0, 0.7])\n', (986, 1003), True, 'import numpy as np\n'), ((1009, 1020), 'numpy.log', 'np.log', (['(0.8)'], {}), '(0.8)\n', (1015, 1020), True, 'import numpy as np\n'), ((1022, 1033), 'numpy.log', 'np.log', (['(1.0)'], {}), '(1.0)\n', (1028, 1033), True, 'import numpy as np\n')] |