content
stringlengths
7
928k
avg_line_length
float64
3.5
33.8k
max_line_length
int64
6
139k
alphanum_fraction
float64
0.08
0.96
licenses
sequence
repository_name
stringlengths
7
104
path
stringlengths
4
230
size
int64
7
928k
lang
stringclasses
1 value
cipher = [75, 203, 190, 126, 184, 169, 27, 74, 35, 83, 113, 65, 207, 193, 27, 137, 37, 98, 0, 68, 219, 113, 21, 180, 223, 135, 5, 129, 189, 200, 245, 100, 117, 62, 192, 101, 239, 92, 182, 136, 159, 235, 166, 90, 74, 133, 83, 78, 6, 225, 101, 103, 82, 78, 144, 205, 130, 238, 175, 245, 172, 62, 157, 176] key = b"SECCON2021" Sbox = [0xff - i for i in range(0x100)] j = 0 for i in range(0x100): j = (j + Sbox[i] + key[i % 10]) % 0x100 Sbox[i], Sbox[j] = Sbox[j], Sbox[i] def FYinv(bits): for i in range(63, -1, -1): j = (i**3 % 67) % 64 bits[i], bits[j] = bits[j], bits[i] def Pinv(data, length): for i in range(length // 8): bits = [] for j in range(8): bits += [(data[i*8+j] >> k) & 1 for k in range(8)] FYinv(bits) for j in range(8): c = 0 for k in range(8): c |= bits[j*8+k] << k data[i*8+j] = c def Sinv(Sbox, data, length): for i in range(length): data[i] = Sbox.index(data[i]) for rnd in range(10): for i in range(0x40): cipher[i] ^= key[9 - rnd] Pinv(cipher, 0x40) Sinv(Sbox, cipher, 0x40) print(cipher) print(''.join(map(chr, cipher)))
31
303
0.507858
[ "Apache-2.0" ]
SECCON/SECCON2021_online_CTF
reversing/pyast64++.rev/solver/solve.py
1,209
Python
import asyncio import logging import pytest from clvm.casts import int_to_bytes from flax.consensus.blockchain import Blockchain from flax.full_node.hint_store import HintStore from flax.types.blockchain_format.coin import Coin from flax.types.condition_opcodes import ConditionOpcode from flax.types.condition_with_args import ConditionWithArgs from flax.types.spend_bundle import SpendBundle from tests.util.db_connection import DBConnection from tests.wallet_tools import WalletTool from tests.setup_nodes import bt @pytest.fixture(scope="module") def event_loop(): loop = asyncio.get_event_loop() yield loop log = logging.getLogger(__name__) class TestHintStore: @pytest.mark.asyncio async def test_basic_store(self): async with DBConnection() as db_wrapper: hint_store = await HintStore.create(db_wrapper) hint_0 = 32 * b"\0" hint_1 = 32 * b"\1" not_existing_hint = 32 * b"\3" coin_id_0 = 32 * b"\4" coin_id_1 = 32 * b"\5" coin_id_2 = 32 * b"\6" hints = [(coin_id_0, hint_0), (coin_id_1, hint_0), (coin_id_2, hint_1)] await hint_store.add_hints(hints) await db_wrapper.commit_transaction() coins_for_hint_0 = await hint_store.get_coin_ids(hint_0) assert coin_id_0 in coins_for_hint_0 assert coin_id_1 in coins_for_hint_0 coins_for_hint_1 = await hint_store.get_coin_ids(hint_1) assert coin_id_2 in coins_for_hint_1 coins_for_non_hint = await hint_store.get_coin_ids(not_existing_hint) assert coins_for_non_hint == [] @pytest.mark.asyncio async def test_hints_in_blockchain(self, empty_blockchain): # noqa: F811 blockchain: Blockchain = empty_blockchain blocks = bt.get_consecutive_blocks( 5, block_list_input=[], guarantee_transaction_block=True, farmer_reward_puzzle_hash=bt.pool_ph, pool_reward_puzzle_hash=bt.pool_ph, ) for block in blocks: await blockchain.receive_block(block) wt: WalletTool = bt.get_pool_wallet_tool() puzzle_hash = 32 * b"\0" amount = int_to_bytes(1) hint = 32 * b"\5" coin_spent = list(blocks[-1].get_included_reward_coins())[0] condition_dict = { ConditionOpcode.CREATE_COIN: [ConditionWithArgs(ConditionOpcode.CREATE_COIN, [puzzle_hash, amount, hint])] } tx: SpendBundle = wt.generate_signed_transaction( 10, wt.get_new_puzzlehash(), coin_spent, condition_dic=condition_dict, ) blocks = bt.get_consecutive_blocks( 10, block_list_input=blocks, guarantee_transaction_block=True, transaction_data=tx ) for block in blocks: await blockchain.receive_block(block) get_hint = await blockchain.hint_store.get_coin_ids(hint) assert get_hint[0] == Coin(coin_spent.name(), puzzle_hash, 1).name()
33.402174
118
0.66645
[ "Apache-2.0" ]
Flax-Network/flax-blockchain
tests/core/full_node/test_hint_store.py
3,073
Python
from __future__ import absolute_import, division, unicode_literals import socket from .base import StatsClientBase, PipelineBase class Pipeline(PipelineBase): def __init__(self, client): super(Pipeline, self).__init__(client) self._maxudpsize = client._maxudpsize def _send(self): data = self._stats.popleft() while self._stats: # Use popleft to preserve the order of the stats. stat = self._stats.popleft() if len(stat) + len(data) + 1 >= self._maxudpsize: self._client._after(data) data = stat else: data += '\n' + stat self._client._after(data) class StatsClient(StatsClientBase): """A client for statsd.""" def __init__(self, host='localhost', port=8125, prefix=None, maxudpsize=512, ipv6=False): """Create a new client.""" fam = socket.AF_INET6 if ipv6 else socket.AF_INET family, _, _, _, addr = socket.getaddrinfo( host, port, fam, socket.SOCK_DGRAM)[0] self._addr = addr self._sock = socket.socket(family, socket.SOCK_DGRAM) self._prefix = prefix self._maxudpsize = maxudpsize def _send(self, data): """Send data to statsd.""" try: self._sock.sendto(data.encode('ascii'), self._addr) except (socket.error, RuntimeError): # No time for love, Dr. Jones! pass def pipeline(self): return Pipeline(self)
30.019608
66
0.594383
[ "MIT" ]
alanhamlett/pystatsd
statsd/client/udp.py
1,531
Python
"""grpc service. Reliably launch and connect to grpc process. """ import datetime import enum import logging import os import subprocess import sys import tempfile import time from typing import Any, Dict, Optional from typing import TYPE_CHECKING import grpc from wandb.proto import wandb_server_pb2 as spb from wandb.proto import wandb_server_pb2_grpc as pbgrpc from wandb.sdk.wandb_settings import Settings if TYPE_CHECKING: from google.protobuf.internal.containers import MessageMap def _pbmap_apply_dict( m: "MessageMap[str, spb.SettingsValue]", d: Dict[str, Any] ) -> None: for k, v in d.items(): if isinstance(v, datetime.datetime): continue if isinstance(v, enum.Enum): continue sv = spb.SettingsValue() if v is None: sv.null_value = True elif isinstance(v, int): sv.int_value = v elif isinstance(v, float): sv.float_value = v elif isinstance(v, str): sv.string_value = v elif isinstance(v, bool): sv.bool_value = v elif isinstance(v, tuple): sv.tuple_value.string_values.extend(v) m[k].CopyFrom(sv) class _Service: _stub: Optional[pbgrpc.InternalServiceStub] def __init__(self) -> None: self._stub = None def _grpc_wait_for_port( self, fname: str, proc: subprocess.Popen = None ) -> Optional[int]: time_max = time.time() + 30 port = None while time.time() < time_max: if proc and proc.poll(): # process finished print("proc exited with", proc.returncode) return None if not os.path.isfile(fname): time.sleep(0.2) continue try: f = open(fname) port = int(f.read()) except Exception as e: print("Error:", e) return port return None def _grpc_launch_server(self) -> Optional[int]: """Launch grpc server and return port.""" # References for starting processes # - https://github.com/wandb/client/blob/archive/old-cli/wandb/__init__.py # - https://stackoverflow.com/questions/1196074/how-to-start-a-background-process-in-python kwargs: Dict[str, Any] = dict(close_fds=True) pid = os.getpid() with tempfile.TemporaryDirectory() as tmpdir: fname = os.path.join(tmpdir, f"port-{pid}.txt") pid_str = str(os.getpid()) exec_cmd_list = [sys.executable, "-m"] # Add coverage collection if needed if os.environ.get("COVERAGE_RCFILE"): exec_cmd_list += ["coverage", "run", "-m"] internal_proc = subprocess.Popen( exec_cmd_list + [ "wandb", "service", "--port-filename", fname, "--pid", pid_str, "--debug", "true", ], env=os.environ, **kwargs, ) port = self._grpc_wait_for_port(fname, proc=internal_proc) return port def start(self) -> Optional[int]: port = self._grpc_launch_server() return port def connect(self, port: int) -> None: channel = grpc.insecure_channel("localhost:{}".format(port)) stub = pbgrpc.InternalServiceStub(channel) self._stub = stub # TODO: make sure service is up def _get_stub(self) -> Optional[pbgrpc.InternalServiceStub]: return self._stub def _svc_inform_init(self, settings: Settings, run_id: str) -> None: assert self._stub inform_init = spb.ServerInformInitRequest() settings_dict = dict(settings) settings_dict["_log_level"] = logging.DEBUG _pbmap_apply_dict(inform_init._settings_map, settings_dict) inform_init._info.stream_id = run_id _ = self._stub.ServerInformInit(inform_init) def _svc_inform_finish(self, run_id: str = None) -> None: assert self._stub assert run_id inform_fin = spb.ServerInformFinishRequest() inform_fin._info.stream_id = run_id _ = self._stub.ServerInformFinish(inform_fin) def _svc_inform_attach(self, attach_id: str) -> None: assert self._stub inform_attach = spb.ServerInformAttachRequest() inform_attach._info.stream_id = attach_id _ = self._stub.ServerInformAttach(inform_attach) def _svc_inform_teardown(self, exit_code: int) -> None: assert self._stub inform_fin = spb.ServerInformTeardownRequest(exit_code=exit_code) _ = self._stub.ServerInformTeardown(inform_fin)
31.070513
99
0.592119
[ "MIT" ]
KnightZhang625/client
wandb/sdk/service/service.py
4,847
Python
import numpy as np from sklearn.metrics import r2_score np.random.seed(42) import matplotlib.pyplot as plt import seaborn as sns import pandas as pd figsize = (8, 4) def show_r2(results): data_size = results["data_size"] test_scores = results["test_scores"] test_scores_exp = results["test_scores_exp"] fig, ax = plt.subplots(figsize=(8, 4)) ax.plot(list(map(lambda x: x["r2"], test_scores)), marker="o", label="Log(Exec. time)", color="#777777") ax.plot(list(map(lambda x: x["r2"], test_scores_exp)), marker="o", label="Exec. time", color="#111111") ax.set_xticks(list(range(data_size.__len__()))) ax.set_xticklabels(data_size, rotation=60) ax.set_ylim((0, 1)) ax.set_yticks(np.arange(0, 1, 0.1)) ax.set_xlabel("# Executed Jobs") ax.set_ylabel("$R^2$ Score") ax.legend() return ax def compare_r2(results, results_real_card, results_random_sampling=None, exp=True): data_size = results["data_size"] if exp: test_scores_real = results_real_card["test_scores_exp"] test_scores = results["test_scores_exp"] else: test_scores_real = results_real_card["test_scores"] test_scores = results["test_scores"] fig, ax = plt.subplots(figsize=(8, 2)) if results_random_sampling: if exp: test_scores_random = results_random_sampling["test_scores_exp"] else: test_scores_random = results_random_sampling["test_scores"] ax.plot(list(map(lambda x: x["r2"], test_scores_random)), marker="^", linestyle="dotted", label="Rand. samples - Estimated out card. (Baseline)", color=sns.color_palette()[-4]) ax.plot(list(map(lambda x: x["r2"], test_scores)), marker="o", label="Active labeling - Estimated out card.", color="#111111") ax.plot(list(map(lambda x: x["r2"], test_scores_real)), linestyle="--", marker="s", label="Active labeling - Real out card. (Top-line)", color=sns.color_palette()[-3], alpha=0.85) ax.set_xticks(list(range(data_size.__len__()))) ax.set_xticklabels(data_size, rotation=60) ax.set_ylim((0, 1)) ax.set_yticks(np.arange(0, 1, 0.2)) ax.set_xlabel("# Cumulated Executed Jobs") ax.set_ylabel("$R^2$ of pred.\nExec. Time") ax.legend() return ax def show_uncertainty(results, show_errors=False): data_size = results["data_size"] IQRs_RMSE = results["model_uncertainty"] IQRs_RMSE = np.array([np.mean(np.exp(I["uncertainty_high"]) - np.exp(I["uncertainty_low"])) for I in results["iterations_results"]]) IQRs_std = np.array([np.std(np.exp(I["uncertainty_high"]) - np.exp(I["uncertainty_low"])) for I in results["iterations_results"]]) fig, ax = plt.subplots(figsize=(8, 2)) if show_errors: ax.errorbar(np.arange(len(IQRs_RMSE)), IQRs_RMSE, yerr=IQRs_std, fmt='o', label="Uncertainty") else: ax.plot(IQRs_RMSE, marker="o", label="Uncertainty") ax.set_xticks(list(range(data_size.__len__()))) ax.set_xticklabels(data_size, rotation=60) ax.set_xlabel("# Cumulated Executed Jobs") ax.set_ylabel("Model\nUncertainty [ms]") final_th = 0.1 count = 0 min_u = IQRs_RMSE[0] min_local_u = IQRs_RMSE[0] stops = [] for i in range(1, len(data_size)): #print(i, " -> min_local_u", min_local_u) r = IQRs_RMSE[i] / min_local_u #print(r) if (r > 1) or (IQRs_RMSE[i]>min_u): pass elif (1-r) < final_th: pass else: print(i, data_size[i], "-> STOP!") count += 1 stops.append({"iteration": i, "data_size": data_size[i], "uncertainty": IQRs_RMSE[i], "uncertainty_std": IQRs_std[i], "cost": np.sum(np.exp(results["iterations_results"][i]["train_labels"])) }) print("--------------------------------") min_u = min(IQRs_RMSE[:i+1]) min_local_u = min(IQRs_RMSE[i-1:i+1]) #min_cost_id = np.argwhere(IQRs_RMSE == min_cost) if len(stops) == 0: stops.append({"iteration": len(data_size)-1, "data_size": data_size[len(data_size)-1], "cost": np.sum(np.exp(results["iterations_results"][len(data_size)-1]["train_labels"])) }) ax.errorbar([s["iteration"] for s in stops], [s["uncertainty"] for s in stops], color="red", label="Early stop", linewidth=0, marker="o" ) ax.legend() print(pd.DataFrame(stops)) return ax def show_iteration(results, iteration_to_show, exp=False, drop_outliers=False): y_test = results["iterations_results"][iteration_to_show]["test_labels"] y_pred = results["iterations_results"][iteration_to_show]["pred_labels"] y_pred_lower = results["iterations_results"][iteration_to_show]["uncertainty_low"] y_pred_upper = results["iterations_results"][iteration_to_show]["uncertainty_high"] p = y_test.argsort() if drop_outliers: q = np.quantile(y_test, 0.97) print(q) out_mask = y_test < q print(out_mask.shape) y_test = y_test[out_mask] y_pred = y_pred[out_mask] y_pred_lower = y_pred_lower[out_mask] y_pred_upper = y_pred_upper[out_mask] p = y_test.argsort() fig, ax = plt.subplots(figsize=(6, 3)) if exp: y_test = np.exp(y_test) y_pred = np.exp(y_pred) y_pred_lower = np.exp(y_pred_lower) y_pred_upper = np.exp(y_pred_upper) if drop_outliers: new_r2 = r2_score(y_test, y_pred) print("NEW R2 without outliers:", new_r2) ax.plot(y_test[p], marker=".", linewidth=1, label="Real", color="#777777", alpha=0.5) ax.errorbar(np.arange(len(y_pred)),y_pred[p], yerr=np.array([y_pred[p] - y_pred_lower[p], y_pred_upper[p] - y_pred[p]]), linewidth=0.5, fmt='.', color="#ff7f0e", label="Pred. + Interval", alpha=0.5) #ax.plot(np.arange(len(y_pred)), (y_pred_lower[p]+y_pred_upper[p])/2, marker=".", linewidth=0, label="smooth", color="green") ax.set_ylabel("Exec. Time [ms]") # ax.ticklabel_format(axis='y', style='sci', scilimits=(0, 3)) #ax.set_yscale("log") ax.set_xlabel("Non-executed Jobs") ax.legend() print(results["test_scores_exp"][iteration_to_show]) else: ax.plot(y_test[p], marker=".", linewidth=1, label="Real", color="#777777", alpha=0.5) ax.errorbar(np.arange(len(y_pred)), y_pred[p], yerr=np.array([y_pred[p] - y_pred_lower[p], y_pred_upper[p] - y_pred[p]]), linewidth=0.5, fmt='.', color="#ff7f0e", label="Pred. + Interval", alpha=0.5) ax.set_ylabel("Log(Exec. Time)") ax.set_xlabel("Non-executed Jobs") ax.legend() print(results["test_scores"][iteration_to_show]) return ax def show_iteration_2(results, iteration_to_show, drop_outliers=False): y_test = results["iterations_results"][iteration_to_show]["test_labels"] y_pred = results["iterations_results"][iteration_to_show]["pred_labels"] y_pred_lower = results["iterations_results"][iteration_to_show]["uncertainty_low"] y_pred_upper = results["iterations_results"][iteration_to_show]["uncertainty_high"] p = y_test.argsort() new_r2 = r2_score(y_test, y_pred) print("NEW R2 log with outliers:", new_r2) if drop_outliers: q = np.quantile(y_test, 0.97) print(q) out_mask = y_test < q print(out_mask.shape) y_test = y_test[out_mask] y_pred = y_pred[out_mask] y_pred_lower = y_pred_lower[out_mask] y_pred_upper = y_pred_upper[out_mask] p = y_test.argsort() fig, ax = plt.subplots(figsize=(6, 6)) y_test = np.exp(y_test) y_pred = np.exp(y_pred) y_pred_lower = np.exp(y_pred_lower) y_pred_upper = np.exp(y_pred_upper) if drop_outliers: new_r2 = r2_score(y_test, y_pred) print("NEW R2 without outliers:", new_r2) ax.plot(y_test[p], y_test[p], marker=".", linewidth=1, label="Real", color="#777777", alpha=0.5) ax.errorbar(y_test[p],y_pred[p], yerr=np.array([y_pred[p] - y_pred_lower[p], y_pred_upper[p] - y_pred[p]]), linewidth=0.5, fmt='.', color="#ff7f0e", label="Pred. + Interval", alpha=0.5) ax.set_ylabel("Forecasted Exec. Time [ms] (Log scale)") ax.set_yscale("log") ax.set_xlabel("Real Exec. Time [ms] (Log scale)") ax.set_xscale("log") ax.legend() return ax def show_td_gen(results, iteration_to_show): y_test = results[list(results.keys())[iteration_to_show]]["test_labels"] y_pred = results[list(results.keys())[iteration_to_show]]["pred_labels"] from sklearn.metrics import r2_score score = r2_score(y_test, y_pred) print("R2 score:", score) p = y_test.argsort() fig, ax = plt.subplots(figsize=(6, 3)) ax.plot(y_test[p], y_test[p], marker=".", linewidth=1, label="Real", color="#777777", alpha=0.5) ax.plot(y_test[p], y_pred[p], marker=".", linewidth=0, label="TDGen Pred.", color=sns.color_palette()[4], alpha=0.5) ax.set_ylabel("Forecasted Exec. Time [ms] (Log scale)") ax.set_yscale("log") ax.set_xlabel("Real Exec. Time [ms] (Log scale)") ax.set_xscale("log") ax.legend() return ax def show_our_and_td_gen(our_results, td_gen_results, iteration_to_show): our_y_test = np.exp(our_results["iterations_results"][iteration_to_show]["test_labels"]) our_y_pred = np.exp(our_results["iterations_results"][iteration_to_show]["pred_labels"]) y_test = td_gen_results[list(td_gen_results.keys())[iteration_to_show]]["test_labels"] y_pred = td_gen_results[list(td_gen_results.keys())[iteration_to_show]]["pred_labels"] from sklearn.metrics import r2_score score = r2_score(y_test, y_pred) print("R2 score:", score) p = y_test.argsort() our_p = our_y_test.argsort() fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(y_test[p], y_test[p], marker="", linewidth=1, label="Real", color="#777777", alpha=0.5) ax.plot(our_y_test[our_p], our_y_pred[our_p], marker=".", linewidth=0, label="Our solution", color=sns.color_palette()[1], alpha=0.2) ax.plot(y_test[p], y_pred[p], marker=".", linewidth=0, label="TDGen Pred.", color=sns.color_palette()[4], alpha=0.2) ax.set_ylabel("Forecasted Exec. Time [ms] (Log scale)") ax.set_yscale("log") ax.set_xlabel("Real Exec. Time [ms] (Log scale)") ax.set_xscale("log") ax.legend() return ax def compare_td_gen_r2(results, results_td_gen): data_size = results["data_size"] test_scores = results["test_scores_exp"] from sklearn.metrics import r2_score td_gen_scores = [] x = [] for k, v in results_td_gen.items(): y_test = v["test_labels"] y_pred = v["pred_labels"] score = r2_score(y_test, y_pred) print(k ,"R2 score:", score) td_gen_scores.append(score) x.append(k) fig, ax = plt.subplots(figsize=(8, 2)) ax.plot(td_gen_scores, linestyle="--", marker="o", label="TDGen", color=sns.color_palette()[4]) ax.plot(list(map(lambda x: x["r2"], test_scores)), marker="o", label="Our solution", color="#111111") ax.set_xticks(list(range(data_size.__len__()))) ax.set_xticklabels(data_size, rotation=60) print(np.array(list(map(lambda x: x["r2"], test_scores)))/np.array(td_gen_scores)) #ax.set_ylim((0, 1)) #ax.set_yticks(np.arange(0, 1, 0.1)) ax.set_xlabel("# Cumulated Executed Jobs") ax.set_ylabel("$R^2$ of pred. Exec. Time") ax.legend() return ax def show_centerd_uncertainty(data, iteration, exp=False): print(data["iterations_results"][iteration].keys()) if exp: preds = np.exp(np.array(data["iterations_results"][iteration]["pred_labels"])) upper = np.exp(np.array(data["iterations_results"][iteration]["uncertainty_high"])) lower = np.exp(np.array(data["iterations_results"][iteration]["uncertainty_low"])) else: preds = np.array(data["iterations_results"][iteration]["pred_labels"]) upper = np.array(data["iterations_results"][iteration]["uncertainty_high"]) lower = np.array(data["iterations_results"][iteration]["uncertainty_low"]) IQR_interval = upper - lower sort_ind = np.argsort(IQR_interval) # y_true_all = y_true_all[sort_ind] preds = preds[sort_ind] upper = upper[sort_ind] lower = lower[sort_ind] mean = (upper + lower) / 2 std = np.std((upper + lower)) # Center such that the mean of the prediction interval is at 0.0 # y_true_all_centered = y_true_all.copy() upper_centered = upper.copy() lower_centered = lower.copy() preds_centered = preds.copy() # y_true_all_centered -= mean upper_centered = (upper_centered - mean) # /std lower_centered = (lower_centered - mean) # /std preds_centered = (preds_centered - mean) # /std IRQ_th = np.quantile(IQR_interval, 0.95) print(IRQ_th) x_idx = np.arange(len(upper_centered)) cut = x_idx[IQR_interval[sort_ind] > IRQ_th] print(cut) fig, ax = plt.subplots(1, 1, figsize=(8, 4)) # ax.plot(y_true_all_centered, "ro", markersize=1) ax.plot(preds_centered, marker=".", color="#ff7f0e", linewidth=0) ax.fill_between( np.arange(len(upper_centered)), lower_centered, upper_centered, alpha=0.2, color="#ff7f0e", label="Pred. interval (centerd)") ax.axvline(cut[0], color="red", linestyle="--", label="Threshold $\eta$") ax.set_xlabel("Non-executed jobs sorted by uncertainty.") ax.set_ylabel("Predicted values (centered)") ax.legend() #  ax.set_yscale("symlog") #  ax.set_ylim([-1.5, 1.5]) def compute_stats_on_pred_errors(results, iteration_to_show): y_train = results["iterations_results"][iteration_to_show]["train_labels"] y_test = results["iterations_results"][iteration_to_show]["test_labels"] y_pred = results["iterations_results"][iteration_to_show]["pred_labels"] y_pred_lower = results["iterations_results"][iteration_to_show]["uncertainty_low"] y_pred_upper = results["iterations_results"][iteration_to_show]["uncertainty_high"] y_train = np.exp(y_train) y_test = np.exp(y_test) y_pred = np.exp(y_pred) y_pred_lower = np.exp(y_pred_lower) y_pred_upper = np.exp(y_pred_upper) print("Real values") print(pd.Series(np.hstack((y_train, y_test)) / 1000).describe()) print("highest 5:", np.sort(np.hstack((y_train, y_test)))[-5:]/1000) print() print("\nAverage Prediction Error") print(pd.Series(np.abs(y_test - y_pred) / 1000).describe()) # count_true = (y_test <= y_pred_upper) & (y_test >= y_pred_lower) # print(len(count_true),len(count_true[count_true==True]))
38.203608
208
0.644134
[ "MIT" ]
researchuser7/QWAugmenter
generator_labeler/paper_results/custom_plots.py
14,825
Python
### # Copyright (c) 2004, Daniel DiPaolo # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### """ Quotegrabs are like IRC sound bites. When someone says something funny, incriminating, stupid, outrageous, ... anything that might be worth remembering, you can grab that quote for that person. With this plugin, you can store many quotes per person and display their most recent quote, as well as see who "grabbed" the quote in the first place. """ import supybot import supybot.world as world # Use this for the version of this plugin. You may wish to put a CVS keyword # in here if you're keeping the plugin in CVS or some similar system. __version__ = "%%VERSION%%" # XXX Replace this with an appropriate author or supybot.Author instance. __author__ = supybot.authors.strike # This is a dictionary mapping supybot.Author instances to lists of # contributions. __contributors__ = {} from . import config from . import plugin from imp import reload reload(plugin) # In case we're being reloaded. if world.testing: from . import test Class = plugin.Class configure = config.configure # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
40.8
79
0.768854
[ "BSD-3-Clause" ]
Alcheri/Limnoria
plugins/QuoteGrabs/__init__.py
2,652
Python
#!/usr/bin/python # configure mini-split heat pumps for E files # uses NRCan CSV list converted to TSV # https://oee.nrcan.gc.ca/pml-lmp/index.cfm?language_langue=en&action=app.search-recherche&appliance=ASHP2_GH import math, os, sys import xml.etree.ElementTree as ET if len(sys.argv) < 3: print(sys.argv[0], "E-file.h2k AHRI heads|0(ducted)") sys.exit() e_file = sys.argv[1] ahri = sys.argv[2] heads = sys.argv[3] t = ET.parse(e_file) # tsv field list: # Brand Outside model Inside model Furnace model HSPF (Region IV) Rated heating capacity (Btu/hour) Grant amount AHRI / Verification reference AHRI Classification Series name/product line (if applicable) SEER Rated cooling capacity (Btu/hour) Coefficient of Performance (COP) at -15 °C (5 °F) (at maximum capacity) Capacity Maintenance % (Max -15°C/5°F ÷ Rated 8.3°C/47°F) cchp_search = "grep '" + ahri + "' ccashp.tsv" #d = os.popen(cchp_search).read().split('\t') d = os.popen(cchp_search).read().rstrip('\n').split('\t') # 1 kW = 3412 BTU/hr (mfr, model, head_mdl, size_kw, hspf, seer, cop, fraction) = \ d[0], d[1], d[2], str(float(d[5])/3412), d[4], d[10], d[12], d[13] #(ahri, size_kw, hspf, cop, seer) = cols[9], str(float(cols[5])/3412), cols[4], cols[13], cols[12] e = t.find("./ProgramInformation/Information") info = ET.Element("Info", {"code": "Info. 5"}) # no NEEP until spreadsheet and/or H2K is fixed if (int(heads) > 0): info.text = "MSHP-" + heads else: info.text = "CENTRAL-HP" e.append(info) # GHG instructions are to use Info 6 when more than 1 ccASHP system is installed # but ENS wants all heat pumps in Info 6 info = ET.Element("Info", {"code": "Info. 6"}) info.text = mfr + ";AHRI-" + ahri + ';' + model + ';' + head_mdl e.append(info) #print(info, info.attrib, info.text) # Type 2 CCHP heating system type2 = ET.parse("Type2.xml").getroot() ahp = type2.find("AirHeatPump") ei = ahp.find("EquipmentInformation") ei.attrib["AHRI"] = ahri ei.find("Manufacturer").text = mfr ei.find("Model").text = model ahp.find("Equipment").attrib["numberOfHeads"] = heads specs = ahp.find("Specifications") specs.find("OutputCapacity").attrib["value"] = size_kw # use ASHP HSPF/SEER until NEEP spreadsheet or H2K is fixed for ccHP specs.find("HeatingEfficiency").attrib["value"] = str(float(hspf)/1.15) specs.find("CoolingEfficiency").attrib["value"] = seer cchp = ahp.find("ColdClimateHeatPump") cchp.attrib["heatingEfficiency"] = hspf cchp.attrib["coolingEfficiency"] = seer cchp.attrib["capacity"] = size_kw cchp.attrib["cop"] = cop cchp.attrib["capacityMaintenance"] = fraction hc = t.find("./House/HeatingCooling") hc.remove(hc.find("Type2")) hc.append(type2) #outfile = "MSHP-out.h2k" outfile = e_file t.write(outfile, "UTF-8", True)
36.533333
373
0.693796
[ "MIT" ]
nerdralph/h2k
ghwiz/mshp.py
2,747
Python
from __future__ import absolute_import, unicode_literals from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.core.urlresolvers import reverse from tracpro.test.cases import TracProDataTest class ManageUserCreateTest(TracProDataTest): def test_create_as_non_superuser(self): # Non-superuser cannot use this view url = reverse('profiles.admin_create') self.login(self.admin) # Not a superuser # Post something that would be an error (empty form) and would be a 200 # status if we had access. response = self.url_post('unicef', url, dict()) # We get redirected to login self.assertEqual(response.status_code, 302, response) self.assertIn('login', response['Location']) def test_create_with_fields_missing(self): # An error case url = reverse('profiles.admin_create') self.login(self.superuser) # submit with no fields entered response = self.url_post('unicef', url, dict()) self.assertEqual(response.status_code, 200, response) error_dict = response.context['form'].errors self.assertEqual(4, len(error_dict), repr(error_dict)) self.assertFormError( response, 'form', 'full_name', 'This field is required.') self.assertFormError( response, 'form', 'email', 'This field is required.') self.assertFormError( response, 'form', 'password', 'This field is required.') self.assertFormError( response, 'form', '__all__', 'Email address already taken.' # FIXME: this error makes no sense in this context ) def test_create_successfully(self): # create non-superuser url = reverse('profiles.admin_create') self.login(self.superuser) data = { 'full_name': "Mo Polls", 'email': "[email protected]", 'password': "abc123xy", 'confirm_password': "abc123xy", 'is_active': True, 'is_superuser': False, } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302, response) user = User.objects.get(email='[email protected]') self.assertEqual(user.profile.full_name, 'Mo Polls') self.assertTrue(user.is_active) self.assertFalse(user.is_superuser) self.assertEqual(user, authenticate(username=user.username, password="abc123xy")) def test_create_superuser(self): # create superuser url = reverse('profiles.admin_create') self.login(self.superuser) data = { 'full_name': "Mo Polls", 'email': "[email protected]", 'password': "abc123xy", 'confirm_password': "abc123xy", 'is_active': True, 'is_superuser': True, } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302, response) user = User.objects.get(email='[email protected]') self.assertEqual(user.profile.full_name, 'Mo Polls') self.assertTrue(user.is_active) self.assertTrue(user.is_superuser) class ManageUserUpdateTest(TracProDataTest): def test_update_as_non_superuser(self): # Non-superuser cannot use this view self.login(self.admin) url = reverse('profiles.admin_update', args=[self.user1.pk]) response = self.url_post('unicef', url, dict()) self.assertEqual(response.status_code, 302) self.assertIn('login', response['Location']) def test_update(self): # Change non-superuser to superuser, change their password, etc etc. self.login(self.superuser) url = reverse('profiles.admin_update', args=[self.user1.pk]) data = { 'full_name': "Mo Polls", 'email': "[email protected]", 'new_password': "abc123xy", 'confirm_password': "abc123xy", 'is_active': False, 'is_superuser': True, } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302) user = User.objects.get(email='[email protected]') self.assertEqual(user.profile.full_name, "Mo Polls") self.assertFalse(user.is_active) self.assertTrue(user.is_superuser) self.assertEqual(user, authenticate(username=user.username, password="abc123xy")) # and back. changing password optional. data = { 'full_name': "Mo Polls", 'email': "[email protected]", # 'password': "abc123xy", # 'confirm_password': "abc123xy", 'is_active': True, 'is_superuser': False, } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302) user = User.objects.get(email='[email protected]') self.assertEqual(user.profile.full_name, "Mo Polls") self.assertTrue(user.is_active) self.assertFalse(user.is_superuser) self.assertEqual(user, authenticate(username=user.username, password="abc123xy")) class UserCRUDLTest(TracProDataTest): def test_create(self): url = reverse('profiles.user_create') # log in as an org administrator self.login(self.admin) # submit with no fields entered response = self.url_post('unicef', url, dict()) self.assertEqual(response.status_code, 200) self.assertFormError( response, 'form', 'full_name', 'This field is required.') self.assertFormError( response, 'form', 'email', 'This field is required.') self.assertFormError( response, 'form', 'password', 'This field is required.') # submit again with all required fields but invalid password data = { 'full_name': "Mo Polls", 'email': "[email protected]", 'password': "123", 'confirm_password': "123", } response = self.url_post('unicef', url, data) self.assertFormError( response, 'form', 'password', "Ensure this value has at least 8 characters (it has 3).") # submit again with valid password but mismatched confirmation data = { 'full_name': "Mo Polls", 'email': "[email protected]", 'password': "Qwerty123", 'confirm_password': "123", } response = self.url_post('unicef', url, data) self.assertFormError( response, 'form', 'confirm_password', "Passwords don't match.") # submit again with valid password and confirmation data = { 'full_name': "Mo Polls", 'email': "[email protected]", 'password': "Qwerty123", 'confirm_password': "Qwerty123", } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302) # check new user and profile user = User.objects.get(email="[email protected]") self.assertEqual(user.profile.full_name, "Mo Polls") self.assertEqual(user.email, "[email protected]") self.assertEqual(user.username, "[email protected]") # try again with same email address data = { 'full_name': "Mo Polls II", 'email': "[email protected]", 'password': "Qwerty123", 'confirm_password': "Qwerty123", } response = self.url_post('unicef', url, data) self.assertFormError( response, 'form', None, "Email address already taken.") def test_update(self): url = reverse('profiles.user_update', args=[self.user1.pk]) # log in as an org administrator self.login(self.admin) response = self.url_get('unicef', url) self.assertEqual(response.status_code, 200) # can assign to any org region self.assertEqual(len(response.context['form'].fields['regions'].choices), 3) # submit with no fields entered response = self.url_post('unicef', url, dict()) self.assertEqual(response.status_code, 200) self.assertFormError( response, 'form', 'full_name', 'This field is required.') self.assertFormError( response, 'form', 'email', 'This field is required.') # submit with all fields entered data = { 'full_name': "Morris", 'email': "[email protected]", 'regions': [self.region3.pk], 'is_active': True, } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302) # check updated user and profile user = User.objects.get(pk=self.user1.pk) self.assertEqual(user.profile.full_name, "Morris") self.assertEqual(user.email, "[email protected]") self.assertEqual(user.username, "[email protected]") self.assertEqual(list(user.regions.all()), [self.region3]) # submit again for good measure data = { 'full_name': "Morris", 'email': "[email protected]", 'regions': [self.region3.pk], 'is_active': True, } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302) # try giving user someone else's email address data = { 'full_name': "Morris", 'email': "[email protected]", 'password': "Qwerty123", 'confirm_password': "Qwerty123", } response = self.url_post('unicef', url, data) self.assertFormError( response, 'form', None, "Email address already taken.") # check de-activating user data = { 'full_name': "Morris", 'email': "[email protected]", 'regions': [], 'is_active': False, } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302) # check user object is inactive user = User.objects.get(pk=self.user1.pk) self.assertFalse(user.is_active) def test_read(self): # log in as an org administrator self.login(self.admin) # view our own profile response = self.url_get( 'unicef', reverse('profiles.user_read', args=[self.admin.pk])) self.assertEqual(response.status_code, 200) self.assertEqual( response.context['edit_button_url'], reverse('profiles.user_self')) # view other user's profile response = self.url_get( 'unicef', reverse('profiles.user_read', args=[self.user1.pk])) self.assertEqual(response.status_code, 200) self.assertEqual( response.context['edit_button_url'], reverse('profiles.user_update', args=[self.user1.pk])) # try to view user from other org response = self.url_get( 'unicef', reverse('profiles.user_read', args=[self.user3.pk])) self.assertEqual(response.status_code, 404) # log in as a user self.login(self.user1) # view other user's profile response = self.url_get( 'unicef', reverse('profiles.user_read', args=[self.admin.pk])) self.assertEqual(response.status_code, 200) self.assertIsNone(response.context['edit_button_url']) def test_list(self): url = reverse('profiles.user_list') response = self.url_get('unicef', url) self.assertLoginRedirect(response, 'unicef', url) # log in as a non-administrator self.login(self.user1) response = self.url_get('unicef', url) self.assertLoginRedirect(response, 'unicef', url) # log in as an org administrator self.login(self.admin) response = self.url_get('unicef', url) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['object_list']), 2) def test_self(self): url = reverse('profiles.user_self') # try as unauthenticated response = self.url_get('unicef', url) self.assertLoginRedirect(response, 'unicef', url) # try as superuser (doesn't have a chat profile) self.login(self.superuser) response = self.url_get('unicef', url) self.assertEqual(response.status_code, 404) # log in as an org administrator self.login(self.admin) response = self.url_get('unicef', url) self.assertEqual(response.status_code, 200) # log in as a user self.login(self.user1) response = self.url_get('unicef', url) self.assertEqual(response.status_code, 200) # submit with no fields entered response = self.url_post('unicef', url, dict()) self.assertEqual(response.status_code, 200) self.assertFormError( response, 'form', 'full_name', 'This field is required.') self.assertFormError( response, 'form', 'email', 'This field is required.') # submit with all required fields entered data = dict(full_name="Morris", email="[email protected]") response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302) # check updated user and profile user = User.objects.get(pk=self.user1.pk) self.assertEqual(user.profile.full_name, "Morris") self.assertEqual(user.email, "[email protected]") self.assertEqual(user.username, "[email protected]") self.assertEqual(list(user.regions.all()), [self.region1]) # submit with all required fields entered and password fields old_password_hash = user.password data = { 'full_name': "Morris", 'email': "[email protected]", 'new_password': "Qwerty123", 'confirm_password': "Qwerty123", } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302) # check password has been changed user = User.objects.get(pk=self.user1.pk) self.assertNotEqual(user.password, old_password_hash) # check when user is being forced to change their password old_password_hash = user.password self.user1.profile.change_password = True self.user1.profile.save() # submit without password data = dict(full_name="Morris", email="[email protected]") response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 200) self.assertFormError( response, 'form', 'password', 'This field is required.') # submit again with password but no confirmation data = { 'full_name': "Morris", 'email': "[email protected]", 'password': "Qwerty123", } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 200) self.assertFormError( response, 'form', 'confirm_password', "Passwords don't match.") # submit again with password and confirmation data = { 'full_name': "Morris", 'email': "[email protected]", 'password': "Qwerty123", 'confirm_password': "Qwerty123", } response = self.url_post('unicef', url, data) self.assertEqual(response.status_code, 302) # check password has changed and no longer has to be changed user = User.objects.get(pk=self.user1.pk) self.assertFalse(user.profile.change_password) self.assertNotEqual(user.password, old_password_hash) class DashUserCRUDLTest(TracProDataTest): def test_login(self): url = reverse('users.user_login') # login without org subdomain response = self.url_post(None, url, { 'username': '[email protected]', 'password': '[email protected]', }) self.assertRedirects( response, 'http://testserver/', fetch_redirect_response=False) # login with org subdomain response = self.url_post('unicef', url, { 'username': '[email protected]', 'password': '[email protected]', }) self.assertRedirects( response, 'http://unicef.testserver/', fetch_redirect_response=False)
36.324561
94
0.594482
[ "BSD-3-Clause" ]
rapidpro/tracpro
tracpro/profiles/tests/test_views.py
16,564
Python
from machin.parallel.thread import Thread, ThreadException import time def test1(): time.sleep(1) print("Exception occurred at {}".format(time.time())) raise RuntimeError("Error") if __name__ == "__main__": t1 = Thread(target=test1) t1.start() while True: try: t1.watch() except ThreadException as e: print("Exception caught at {}".format(time.time())) print("Exception is: {}".format(e)) break t1.join()
22.772727
63
0.590818
[ "MIT" ]
ikamensh/machin
examples/tutorials/parallel_distributed/mth_exception.py
501
Python
from libra_client.cli.command import Command, blocking_cmd class AccountCommand(Command): def get_aliases(self): return ["account", "a"] def get_description(self): return "Account operations" def execute(self, client, params, **kwargs): commands = [ AccountCommandCreate(), AccountCommandListAccounts(), AccountCommandRecoverWallet(), AccountCommandWriteRecovery(), AccountCommandMint() ] self.subcommand_execute(params[0], commands, client, params[1:], **kwargs) class AccountCommandCreate(Command): def get_aliases(self): return ["create", "c"] def get_description(self): return "Create an account. Returns reference ID to use in other operations" def execute(self, client, params, **kwargs): print(">> Creating/retrieving next account from wallet") index, account = client.create_next_account() print( "Created/retrieved account #{} address {}".format( index, account.address.hex() ) ) class AccountCommandListAccounts(Command): def get_aliases(self): return ["list", "la"] def get_description(self): return "Print all accounts that were created or loaded" def execute(self, client, params, **kwargs): client.print_all_accounts() class AccountCommandRecoverWallet(Command): def get_aliases(self): return ["recover", "r"] def get_params_help(self): return "<file_path>" def get_description(self): return "Recover Libra wallet from the file path" def execute(self, client, params, **kwargs): print(">> Recovering Wallet") accounts = client.recover_wallet_accounts(params[1]) print(f"Wallet recovered and the first {len(accounts)} child accounts were derived") for index, data in enumerate(accounts): print("#{} address {}".format(index, data.address.hex())) class AccountCommandWriteRecovery(Command): def get_aliases(self): return ["write", "w"] def get_params_help(self): return "<file_path>" def get_description(self): return "Save Libra wallet mnemonic recovery seed to disk" def execute(self, client, params, **kwargs): print(">> Saving Libra wallet mnemonic recovery seed to disk") client.write_recovery(params[1]) print("Saved mnemonic seed to disk") class AccountCommandMint(Command): def get_aliases(self): return ["mint", "mintb", "m", "mb"] def get_params_help(self): return "<receiver_account_ref_id>|<receiver_account_address> <number_of_coins>" def get_description(self): return "Mint coins to the account. Suffix 'b' is for blocking" def execute(self, client, params, **kwargs): print(">> Minting coins") is_blocking = blocking_cmd(params[0]) client.mint_coins(params[1], params[2], is_blocking) if is_blocking: print("Finished minting!") else: print("Mint request submitted")
31.436893
93
0.617356
[ "MIT" ]
yuan-xy/libra-client
libra_client/shell/account_commands.py
3,238
Python
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Monitors allow user instrumentation of the training process. Monitors are useful to track training, report progress, request early stopping and more. Monitors use the observer pattern and notify at the following points: - when training begins - before a training step - after a training step - when training ends Monitors are not intended to be reusable. There are a few pre-defined monitors: - CaptureVariable: saves a variable's values - GraphDump: intended for debug only - saves all tensor values - PrintTensor: outputs one or more tensor values to log - SummarySaver: saves summaries to a summary writer - ValidationMonitor: runs model validation, by periodically calculating eval metrics on a separate data set; supports optional early stopping For more specific needs, you can create custom monitors by extending one of the following classes: - BaseMonitor: the base class for all monitors - EveryN: triggers a callback every N training steps Example: class ExampleMonitor(monitors.BaseMonitor): def __init__(self): print 'Init' def begin(self, max_steps): print 'Starting run. Will train until step %d.' % max_steps def end(self): print 'Completed run.' def step_begin(self, step): print 'About to run step %d...' % step return ['loss_1:0'] def step_end(self, step, outputs): print 'Done running step %d. The value of "loss" tensor: %s' % ( step, outputs['loss_1:0']) linear_regressor = LinearRegressor() example_monitor = ExampleMonitor() linear_regressor.fit( x, y, steps=2, batch_size=1, monitors=[example_monitor]) @@get_default_monitors @@BaseMonitor @@CaptureVariable @@CheckpointSaver @@EveryN @@ExportMonitor @@GraphDump @@LoggingTrainable @@NanLoss @@PrintTensor @@StepCounter @@StopAtStep @@SummarySaver @@ValidationMonitor """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import os import time import numpy as np import six from tensorflow.contrib.framework import deprecated_arg_values from tensorflow.contrib.framework.python.ops import variables as contrib_variables from tensorflow.contrib.learn.python.learn import session_run_hook from tensorflow.contrib.learn.python.learn.summary_writer_cache import SummaryWriterCache from tensorflow.core.framework.summary_pb2 import Summary from tensorflow.core.util.event_pb2 import SessionLog from tensorflow.python.framework import ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import saver as saver_lib from tensorflow.python.training import summary_io # TODO(ptucker): Split each monitor class into a separate file. # TODO(ptucker): Fail if epoch or step does not monotonically increase? class BaseMonitor(object): """Base class for Monitors. Defines basic interfaces of Monitors. Monitors can either be run on all workers or, more commonly, restricted to run exclusively on the elected chief worker. """ def __init__(self): self._begun = False self._current_epoch = None self._current_step = None self._max_steps = None self._estimator = None self._estimator_locked = False @property def run_on_all_workers(self): return False def set_estimator(self, estimator): """A setter called automatically by the target estimator. If the estimator is locked, this method does nothing. Args: estimator: the estimator that this monitor monitors. Raises: ValueError: if the estimator is None. """ if self._estimator_locked: return if estimator is None: raise ValueError("Missing estimator.") # TODO(mdan): This should fail if called twice with the same estimator. self._estimator = estimator def _lock_estimator(self): """Locks the estimator until _unlock_estimator is called.""" self._estimator_locked = True def _unlock_estimator(self): """Unlocks the estimator.""" self._estimator_locked = False def begin(self, max_steps=None): """Called at the beginning of training. When called, the default graph is the one we are executing. Args: max_steps: `int`, the maximum global step this training will run until. Raises: ValueError: if we've already begun a run. """ if self._begun: raise ValueError("begin called twice without end.") self._max_steps = max_steps self._begun = True def end(self, session=None): """Callback at the end of training/evaluation. Args: session: A `tf.Session` object that can be used to run ops. Raises: ValueError: if we've not begun a run. """ _ = session if not self._begun: raise ValueError("end called without begin.") self._max_steps = None self._begun = False def epoch_begin(self, epoch): """Begin epoch. Args: epoch: `int`, the epoch number. Raises: ValueError: if we've already begun an epoch, or `epoch` < 0. """ if self._current_epoch is not None: raise ValueError("epoch_begin called twice without epoch_end.") if epoch < 0: raise ValueError("Invalid epoch %s." % epoch) self._current_epoch = epoch def epoch_end(self, epoch): """End epoch. Args: epoch: `int`, the epoch number. Raises: ValueError: if we've not begun an epoch, or `epoch` number does not match. """ if self._current_epoch != epoch: raise ValueError( "epoch_end expected %s but got %s.", self._current_epoch, epoch) self._current_epoch = None def step_begin(self, step): """Callback before training step begins. You may use this callback to request evaluation of additional tensors in the graph. Args: step: `int`, the current value of the global step. Returns: List of `Tensor` objects or string tensor names to be run. Raises: ValueError: if we've already begun a step, or `step` < 0, or `step` > `max_steps`. """ if (step < 0) or ( (self._max_steps is not None) and (step > self._max_steps)): raise ValueError("Invalid step %s." % step) self._current_step = step return [] def step_end(self, step, output): # pylint: disable=unused-argument """Callback after training step finished. This callback provides access to the tensors/ops evaluated at this step, including the additional tensors for which evaluation was requested in `step_begin`. In addition, the callback has the opportunity to stop training by returning `True`. This is useful for early stopping, for example. Note that this method is not called if the call to `Session.run()` that followed the last call to `step_begin()` failed. Args: step: `int`, the current value of the global step. output: `dict` mapping `string` values representing tensor names to the value resulted from running these tensors. Values may be either scalars, for scalar tensors, or Numpy `array`, for non-scalar tensors. Returns: `bool`. True if training should stop. Raises: ValueError: if we've not begun a step, or `step` number does not match. """ if self._current_step != step: raise ValueError( "step_end expected %s but got %s.", self._current_step, step) self._current_step = None return False def post_step(self, step, session): # pylint: disable=unused-argument """Callback after the step is finished. Called after step_end and receives session to perform extra session.run calls. If failure occurred in the process, will be called as well. Args: step: `int`, global step of the model. session: `Session` object. """ _ = step, session def _extract_output(outputs, request): if request in outputs: return outputs[request] return outputs[request.name] class EveryN(BaseMonitor): """Base class for monitors that execute callbacks every N steps. This class adds three new callbacks: - every_n_step_begin - every_n_step_end - every_n_post_step The callbacks are executed every n steps, or optionally every step for the first m steps, where m and n can both be user-specified. When extending this class, note that if you wish to use any of the `BaseMonitor` callbacks, you must call their respective super implementation: def step_begin(self, step): super(ExampleMonitor, self).step_begin(step) return [] Failing to call the super implementation will cause unpredictible behavior. The `every_n_post_step()` callback is also called after the last step if it was not already called through the regular conditions. Note that `every_n_step_begin()` and `every_n_step_end()` do not receive that special treatment. """ # TODO(ipolosukhin): Add also every n seconds. def __init__(self, every_n_steps=100, first_n_steps=1): """Initializes an `EveryN` monitor. Args: every_n_steps: `int`, the number of steps to allow between callbacks. first_n_steps: `int`, specifying the number of initial steps during which the callbacks will always be executed, regardless of the value of `every_n_steps`. Note that this value is relative to the global step """ super(EveryN, self).__init__() self._every_n_steps = every_n_steps self._first_n_steps = first_n_steps # Last step in the model. self._last_successful_step = None # Last step at which we called one of the every_n methods self._last_active_step = 0 self._every_n_step_begin_called = False def every_n_step_begin(self, step): # pylint: disable=unused-argument """Callback before every n'th step begins. Args: step: `int`, the current value of the global step. Returns: A `list` of tensors that will be evaluated at this step. """ return [] def every_n_step_end(self, step, outputs): # pylint: disable=unused-argument """Callback after every n'th step finished. This callback provides access to the tensors/ops evaluated at this step, including the additional tensors for which evaluation was requested in `step_begin`. In addition, the callback has the opportunity to stop training by returning `True`. This is useful for early stopping, for example. Args: step: `int`, the current value of the global step. outputs: `dict` mapping `string` values representing tensor names to the value resulted from running these tensors. Values may be either scalars, for scalar tensors, or Numpy `array`, for non-scalar tensors. Returns: `bool`. True if training should stop. """ return False def every_n_post_step(self, step, session): """Callback after a step is finished or `end()` is called. Args: step: `int`, the current value of the global step. session: `Session` object. """ pass def step_begin(self, step): """Overrides `BaseMonitor.step_begin`. When overriding this method, you must call the super implementation. Args: step: `int`, the current value of the global step. Returns: A `list`, the result of every_n_step_begin, if that was called this step, or an empty list otherwise. Raises: ValueError: if called more than once during a step. """ super(EveryN, self).step_begin(step) if (step <= self._first_n_steps or step >= (self._every_n_steps + self._last_active_step) or step == self._max_steps): # Note: max_steps can be None here. self._every_n_step_begin_called = True return self.every_n_step_begin(step) self._every_n_step_begin_called = False return [] def step_end(self, step, output): """Overrides `BaseMonitor.step_end`. When overriding this method, you must call the super implementation. Args: step: `int`, the current value of the global step. output: `dict` mapping `string` values representing tensor names to the value resulted from running these tensors. Values may be either scalars, for scalar tensors, or Numpy `array`, for non-scalar tensors. Returns: `bool`, the result of every_n_step_end, if that was called this step, or `False` otherwise. """ super(EveryN, self).step_end(step, output) if self._every_n_step_begin_called: return self.every_n_step_end(step, output) return False def post_step(self, step, session): super(EveryN, self).post_step(step, session) if self._every_n_step_begin_called: self.every_n_post_step(step, session) self._last_active_step = step self._last_successful_step = step def end(self, session=None): super(EveryN, self).end(session=session) if self._last_successful_step != self._last_active_step: self.every_n_post_step(self._last_successful_step, session) class StopAtStep(BaseMonitor): """Monitor to request stop at a specified step.""" def __init__(self, num_steps=None, last_step=None): """Create a StopAtStep monitor. This monitor requests stop after either a number of steps have been executed or a last step has been reached. Only of the two options can be specified. if `num_steps` is specified, it indicates the number of steps to execute after `begin()` is called. If instead `last_step` is specified, it indicates the last step we want to execute, as passed to the `step_begin()` call. Args: num_steps: Number of steps to execute. last_step: Step after which to stop. Raises: ValueError: If one of the arguments is invalid. """ super(StopAtStep, self).__init__() if num_steps is None and last_step is None: raise ValueError("One of num_steps or last_step must be specified.") if num_steps is not None and last_step is not None: raise ValueError("Only one of num_steps or last_step can be specified.") self._num_steps = num_steps self._last_step = last_step @property def run_on_all_workers(self): return True def step_begin(self, step): super(StopAtStep, self).step_begin(step) if self._last_step is None: self._last_step = step + self._num_steps - 1 return [] def step_end(self, step, output): super(StopAtStep, self).step_end(step, output) return step >= self._last_step # TODO(ptucker): Rename to LoggingTensor since it's not writing to stdout. class PrintTensor(EveryN): """Prints given tensors every N steps. This is an `EveryN` monitor and has consistent semantic for `every_n` and `first_n`. The tensors will be printed to the log, with `INFO` severity. """ def __init__(self, tensor_names, every_n=100, first_n=1): """Initializes a PrintTensor monitor. Args: tensor_names: `dict` of tag to tensor names or `iterable` of tensor names (strings). every_n: `int`, print every N steps. See `PrintN.` first_n: `int`, also print the first N steps. See `PrintN.` """ super(PrintTensor, self).__init__(every_n, first_n) if not isinstance(tensor_names, dict): tensor_names = {item: item for item in tensor_names} self._tensor_names = tensor_names def every_n_step_begin(self, step): super(PrintTensor, self).every_n_step_begin(step) return list(self._tensor_names.values()) def every_n_step_end(self, step, outputs): super(PrintTensor, self).every_n_step_end(step, outputs) stats = [] for tag, tensor_name in six.iteritems(self._tensor_names): if tensor_name in outputs: stats.append("%s = %s" % (tag, str(_extract_output(outputs, tensor_name)))) logging.info("Step %d: %s", step, ", ".join(stats)) class LoggingTrainable(EveryN): """Writes trainable variable values into log every N steps. Write the tensors in trainable variables `every_n` steps, starting with the `first_n`th step. """ def __init__(self, scope=None, every_n=100, first_n=1): """Initializes LoggingTrainable monitor. Args: scope: An optional string to match variable names using re.match. every_n: Print every N steps. first_n: Print first N steps. """ super(LoggingTrainable, self).__init__(every_n, first_n) self._scope = scope def every_n_step_begin(self, step): super(LoggingTrainable, self).every_n_step_begin(step) # Get a list of trainable variables at the begining of every N steps. # We cannot get this in __init__ because train_op has not been generated. trainables = ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES, scope=self._scope) self._names = {} for var in trainables: self._names[var.name] = var.value().name return list(self._names.values()) def every_n_step_end(self, step, outputs): super(LoggingTrainable, self).every_n_step_end(step, outputs) stats = [] for tag, tensor_name in six.iteritems(self._names): if tensor_name in outputs: stats.append("%s = %s" % (tag, str(_extract_output(outputs, tensor_name)))) logging.info("Logging Trainable: Step %d: %s", step, ", ".join(stats)) class SummarySaver(EveryN): """Saves summaries every N steps.""" def __init__(self, summary_op, save_steps=100, output_dir=None, summary_writer=None, scaffold=None): """Initializes a `SummarySaver` monitor. Args: summary_op: `Tensor` of type `string`. A serialized `Summary` protocol buffer, as output by TF summary methods like `scalar_summary` or `merge_all_summaries`. save_steps: `int`, save summaries every N steps. See `EveryN`. output_dir: `string`, the directory to save the summaries to. Only used if no `summary_writer` is supplied. summary_writer: `SummaryWriter`. If `None` and an `output_dir` was passed, one will be created accordingly. scaffold: `Scaffold` to get summary_op if it's not provided. """ # TODO(ipolosukhin): Implement every N seconds. super(SummarySaver, self).__init__(every_n_steps=save_steps) self._summary_op = summary_op self._summary_writer = summary_writer if summary_writer is None and output_dir: self._summary_writer = summary_io.SummaryWriter(output_dir) self._scaffold = scaffold # TODO(mdan): Throw an error if output_dir and summary_writer are None. def set_estimator(self, estimator): super(SummarySaver, self).set_estimator(estimator) # TODO(mdan): This line looks redundant. if self._summary_writer is None: self._summary_writer = summary_io.SummaryWriter(estimator.model_dir) def every_n_step_begin(self, step): super(SummarySaver, self).every_n_step_begin(step) if self._summary_op is None and self._scaffold is not None: self._summary_op = self._scaffold.summary_op if self._summary_op is not None: return [self._summary_op] return [] def every_n_step_end(self, step, outputs): super(SummarySaver, self).every_n_step_end(step, outputs) if self._summary_op is not None: summary_strs = _extract_output(outputs, self._summary_op) if self._summary_writer: self._summary_writer.add_summary(summary_strs, step) return False def end(self, session=None): super(SummarySaver, self).end(session=session) if self._summary_writer: self._summary_writer.flush() class ValidationMonitor(EveryN): """Runs evaluation of a given estimator, at most every N steps. Note that the evaluation is done based on the saved checkpoint, which will usually be older than the current step. Can do early stopping on validation metrics if `early_stopping_rounds` is provided. """ def __init__(self, x=None, y=None, input_fn=None, batch_size=None, eval_steps=None, every_n_steps=100, metrics=None, early_stopping_rounds=None, early_stopping_metric="loss", early_stopping_metric_minimize=True, name=None): """Initializes a ValidationMonitor. Args: x: See `BaseEstimator.evaluate`. y: See `BaseEstimator.evaluate`. input_fn: See `BaseEstimator.evaluate`. batch_size: See `BaseEstimator.evaluate`. eval_steps: See `BaseEstimator.evaluate`. every_n_steps: Check for new checkpoints to evaluate every N steps. If a new checkpoint is found, it is evaluated. See `EveryN`. metrics: See `BaseEstimator.evaluate`. early_stopping_rounds: `int`. If the metric indicated by `early_stopping_metric` does not change according to `early_stopping_metric_minimize` for this many steps, then training will be stopped. early_stopping_metric: `string`, name of the metric to check for early stopping. early_stopping_metric_minimize: `bool`, True if `early_stopping_metric` is expected to decrease (thus early stopping occurs when this metric stops decreasing), False if `early_stopping_metric` is expected to increase. Typically, `early_stopping_metric_minimize` is True for loss metrics like mean squared error, and False for performance metrics like accuracy. name: See `BaseEstimator.evaluate`. Raises: ValueError: If both x and input_fn are provided. """ super(ValidationMonitor, self).__init__(every_n_steps=every_n_steps, first_n_steps=-1) # TODO(mdan): Checks like this are already done by evaluate. if x is None and input_fn is None: raise ValueError("Either x or input_fn should be provided.") self.x = x self.y = y self.input_fn = input_fn self.batch_size = batch_size self.eval_steps = eval_steps self.metrics = metrics self.early_stopping_rounds = early_stopping_rounds self.early_stopping_metric = early_stopping_metric self.early_stopping_metric_minimize = early_stopping_metric_minimize self.name = name self._best_value_step = None self._best_value = None self._early_stopped = False self._latest_path = None self._latest_path_step = None @property def early_stopped(self): """Returns True if this monitor caused an early stop.""" return self._early_stopped @property def best_step(self): """Returns the step at which the best early stopping metric was found.""" return self._best_value_step @property def best_value(self): """Returns the best early stopping metric value found so far.""" return self._best_value def every_n_step_end(self, step, outputs): super(ValidationMonitor, self).every_n_step_end(step, outputs) # TODO(mdan): The use of step below is probably misleading. # The code should probably use the step from the checkpoint, because # that's what is being evaluated. if self._estimator is None: raise ValueError("Missing call to set_estimator.") # Check that we are not running evaluation on the same checkpoint. latest_path = saver_lib.latest_checkpoint(self._estimator.model_dir) if latest_path is None: logging.debug("Skipping evaluation since model has not been saved yet " "at step %d.", step) return False if latest_path is not None and latest_path == self._latest_path: logging.debug("Skipping evaluation due to same checkpoint %s for step %d " "as for step %d.", latest_path, step, self._latest_path_step) return False self._latest_path = latest_path self._latest_path_step = step # Run evaluation and log it. validation_outputs = self._estimator.evaluate( x=self.x, y=self.y, input_fn=self.input_fn, batch_size=self.batch_size, steps=self.eval_steps, metrics=self.metrics, name=self.name) stats = [] for name in validation_outputs: stats.append("%s = %s" % (name, str(validation_outputs[name]))) logging.info("Validation (step %d): %s", step, ", ".join(stats)) # Early stopping logic. if self.early_stopping_rounds is not None: if self.early_stopping_metric not in validation_outputs: raise ValueError("Metric %s missing from outputs %s." % ( self.early_stopping_metric, set(validation_outputs.keys()))) current_value = validation_outputs[self.early_stopping_metric] if (self._best_value is None or (self.early_stopping_metric_minimize and (current_value < self._best_value)) or (not self.early_stopping_metric_minimize and (current_value > self._best_value))): self._best_value = current_value self._best_value_step = step stop_now = (step - self._best_value_step >= self.early_stopping_rounds) if stop_now: logging.info("Stopping. Best step: {} with {} = {}." .format(self._best_value_step, self.early_stopping_metric, self._best_value)) self._early_stopped = True return True return False # TODO(ptucker): This really reads any tensor, not just vars, and requires the # ':0' suffix on var_name. class CaptureVariable(EveryN): """Captures a variable's values into a collection. This monitor is useful for unit testing. You should exercise caution when using this monitor in production, since it never discards values. This is an `EveryN` monitor and has consistent semantic for `every_n` and `first_n`. """ def __init__(self, var_name, every_n=100, first_n=1): """Initializes a CaptureVariable monitor. Args: var_name: `string`. The variable name, including suffix (typically ":0"). every_n: `int`, print every N steps. See `PrintN.` first_n: `int`, also print the first N steps. See `PrintN.` """ super(CaptureVariable, self).__init__(every_n, first_n) self._var_name = var_name self._var_values = {} @property def values(self): """Returns the values captured so far. Returns: `dict` mapping `int` step numbers to that values of the variable at the respective step. """ return self._var_values def every_n_step_begin(self, step): super(CaptureVariable, self).every_n_step_begin(step) return [self._var_name] def every_n_step_end(self, step, outputs): super(CaptureVariable, self).every_n_step_end(step, outputs) self._var_values[step] = _extract_output(outputs, self._var_name) def get_default_monitors(loss_op=None, summary_op=None, save_summary_steps=100, output_dir=None, summary_writer=None): """Returns a default set of typically-used monitors. Args: loss_op: `Tensor`, the loss tensor. This will be printed using `PrintTensor` at the default interval. summary_op: See `SummarySaver`. save_summary_steps: See `SummarySaver`. output_dir: See `SummarySaver`. summary_writer: See `SummarySaver`. Returns: `list` of monitors. """ monitors = [] if loss_op is not None: monitors.append(PrintTensor(tensor_names={"loss": loss_op.name})) if summary_op is not None: monitors.append(SummarySaver(summary_op, save_steps=save_summary_steps, output_dir=output_dir, summary_writer=summary_writer)) return monitors class GraphDump(BaseMonitor): """Dumps almost all tensors in the graph at every step. Note, this is very expensive, prefer `PrintTensor` in production. """ IGNORE_OPS = ["Const", "Assign", "Identity", "Placeholder", "RandomUniform", "Cast", "RestoreSlice"] def __init__(self, ignore_ops=None): """Initializes GraphDump monitor. Args: ignore_ops: `list` of `string`. Names of ops to ignore. If None, `GraphDump.IGNORE_OPS` is used. """ super(GraphDump, self).__init__() self._ignore_ops = ignore_ops or GraphDump.IGNORE_OPS self._data = {} def begin(self, max_steps=None): super(GraphDump, self).begin(max_steps=max_steps) self._tensors = [] graph = ops.get_default_graph() graph_def = graph.as_graph_def() for node in graph_def.node: if node.op in self._ignore_ops: continue logging.info("op=%s name=%s.", node.op, node.name) try: self._tensors.append(graph.get_tensor_by_name(node.name + ":0")) except KeyError: pass def step_begin(self, step): super(GraphDump, self).step_begin(step) return self._tensors def step_end(self, step, output): super(GraphDump, self).step_end(step, output) self._data[step] = output @property def data(self): return self._data # TODO(ptucker): Handle keys that are in one but not the other. def compare(self, other_dump, step, atol=1e-06): """Compares two `GraphDump` monitors and returns differences. Args: other_dump: Another `GraphDump` monitor. step: `int`, step to compare on. atol: `float`, absolute tolerance in comparison of floating arrays. Returns: Returns tuple: matched: `list` of keys that matched. non_matched: `dict` of keys to tuple of 2 mismatched values. Raises: ValueError: if a key in `data` is missing from `other_dump` at `step`. """ non_matched = {} matched = [] this_output = self.data[step] if step in self.data else {} other_output = other_dump.data[step] if step in other_dump.data else {} for key in this_output: if not isinstance(key, str) and not isinstance(key, unicode): continue if key not in other_output: raise ValueError("%s missing at step %s.", (key, step)) value1 = _extract_output(this_output, key) value2 = _extract_output(other_output, key) if isinstance(value1, str): continue if isinstance(value1, np.ndarray): if not np.allclose(value1, value2, atol=atol): non_matched[key] = value1 - value2 else: matched.append(key) else: if value1 != value2: non_matched[key] = (value1, value2) else: matched.append(key) return matched, non_matched class ExportMonitor(EveryN): """Monitor that exports Estimator every N steps.""" # TODO(philstahlfeld): Investigate switching export.export_estimator # configuration values to **kwargs so that updates to the export_estimator # function don't have to be reflected here. @deprecated_arg_values( "2016-09-23", "The signature of the input_fn accepted by export is changing to be " "consistent with what's used by tf.Learn Estimator's train/evaluate. " "input_fn (and in most cases, input_feature_key) will both become " "required args.", input_fn=None) def __init__(self, every_n_steps, export_dir, input_fn=None, input_feature_key=None, exports_to_keep=5, signature_fn=None, default_batch_size=1): """Initializes ExportMonitor. Args: every_n_steps: Run monitor every N steps. export_dir: str, folder to export. input_fn: A function that takes no argument and returns a tuple of (features, targets), where features is a dict of string key to `Tensor` and targets is a `Tensor` that's currently not used (and so can be `None`). input_feature_key: String key into the features dict returned by `input_fn` that corresponds to the raw `Example` strings `Tensor` that the exported model will take as input. Can only be `None` if you're using a custom `signature_fn` that does not use the first arg (examples). exports_to_keep: int, number of exports to keep. signature_fn: Function that returns a default signature and a named signature map, given `Tensor` of `Example` strings, `dict` of `Tensor`s for features and `dict` of `Tensor`s for predictions. default_batch_size: Default batch size of the `Example` placeholder. Raises: ValueError: If `input_fn` and `input_feature_key` are not both defined or are not both `None`. """ super(ExportMonitor, self).__init__(every_n_steps=every_n_steps) self._export_dir = export_dir self._input_fn = input_fn self._input_feature_key = input_feature_key self._use_deprecated_input_fn = input_fn is None self._exports_to_keep = exports_to_keep self._signature_fn = signature_fn self._default_batch_size = default_batch_size self._last_export_dir = None @property def export_dir(self): return self._export_dir @property def exports_to_keep(self): return self._exports_to_keep @property def signature_fn(self): return self._signature_fn @property def last_export_dir(self): """Returns the directory containing the last completed export. Returns: The string path to the exported directory. NB: this functionality was added on 2016/09/25; clients that depend on the return value may need to handle the case where this function returns None because the estimator being fitted does not yet return a value during export. """ return self._last_export_dir def every_n_step_end(self, step, outputs): super(ExportMonitor, self).every_n_step_end(step, outputs) try: self._last_export_dir = self._estimator.export( self.export_dir, exports_to_keep=self.exports_to_keep, signature_fn=self.signature_fn, input_fn=self._input_fn, default_batch_size=self._default_batch_size, input_feature_key=self._input_feature_key, use_deprecated_input_fn=self._use_deprecated_input_fn) except RuntimeError: # Currently we are not syncronized with saving checkpoints, which leads to # runtime errors when we are calling export on the same global step. # Exports depend on saved checkpoints for constructing the graph and # getting the global step from the graph instance saved in the checkpoint. # If the checkpoint is stale with respect to current step, the global step # is taken to be the last saved checkpoint's global step and exporter # doesn't export the same checkpoint again with the following error. logging.info("Skipping exporting because the existing checkpoint has " "already been exported. " "Consider exporting less frequently.") def end(self, session=None): super(ExportMonitor, self).end(session=session) latest_path = saver_lib.latest_checkpoint(self._estimator.model_dir) if latest_path is None: logging.info("Skipping export at the end since model has not been saved " "yet.") return try: self._last_export_dir = self._estimator.export( self.export_dir, exports_to_keep=self.exports_to_keep, signature_fn=self.signature_fn, input_fn=self._input_fn, default_batch_size=self._default_batch_size, input_feature_key=self._input_feature_key, use_deprecated_input_fn=self._use_deprecated_input_fn) except RuntimeError: logging.info("Skipping exporting for the same step.") class CheckpointSaver(BaseMonitor): """Saves checkpoints every N steps.""" def __init__(self, checkpoint_dir, save_secs=None, save_steps=None, saver=None, checkpoint_basename="model.ckpt", scaffold=None): """Initialize CheckpointSaver monitor. Args: checkpoint_dir: `str`, base directory for the checkpoint files. save_secs: `int`, save every N secs. save_steps: `int`, save every N steps. saver: `Saver` object, used for saving. checkpoint_basename: `str`, base name for the checkpoint files. scaffold: `Scaffold`, use to get saver object. Raises: ValueError: If both `save_steps` and `save_secs` are not `None`. ValueError: If both `save_steps` and `save_secs` are `None`. """ logging.info("Create CheckpointSaver.") super(CheckpointSaver, self).__init__() self._saver = saver self._summary_writer = SummaryWriterCache.get(checkpoint_dir) self._save_path = os.path.join(checkpoint_dir, checkpoint_basename) self._scaffold = scaffold self._save_secs = save_secs self._save_steps = save_steps self._last_saved_time = None self._last_begin_step = None self._last_saved_step = None if save_steps is None and save_secs is None: raise ValueError("Either save_steps or save_secs should be provided") if (save_steps is not None) and (save_secs is not None): raise ValueError("Can not provide both save_steps and save_secs.") def begin(self, max_steps=None): super(CheckpointSaver, self).begin(max_steps) self._last_saved_time = None self._last_begin_step = None self._last_saved_step = None def step_begin(self, step): super(CheckpointSaver, self).step_begin(step) self._last_begin_step = step def post_step(self, step, session): super(CheckpointSaver, self).post_step(step, session) if self._last_saved_time is None: self._save(step, session) if self._save_steps is not None: if step >= self._last_saved_step + self._save_steps: self._save(step, session) if self._save_secs is not None: if time.time() >= self._last_saved_time + self._save_secs: self._save(step, session) def end(self, session=None): super(CheckpointSaver, self).end(session) self._save(self._last_begin_step, session) def _save(self, step, session): """Saves the latest checkpoint.""" if step == self._last_saved_step: return logging.info("Saving checkpoints for %d into %s.", step, self._save_path) self._last_saved_time = time.time() self._last_saved_step = step if self._saver is None: self._scaffold.saver.save(session, self._save_path, global_step=step) else: self._saver.save(session, self._save_path, global_step=step) self._summary_writer.add_session_log( SessionLog( status=SessionLog.CHECKPOINT, checkpoint_path=self._save_path), step) class StepCounter(EveryN): """Steps per second monitor.""" def __init__(self, every_n_steps=100, output_dir=None, summary_writer=None): super(StepCounter, self).__init__(every_n_steps=every_n_steps) self._summary_tag = "global_step/sec" self._last_reported_step = None self._last_reported_time = None self._summary_writer = summary_writer if summary_writer is None and output_dir: self._summary_writer = SummaryWriterCache.get(output_dir) def set_estimator(self, estimator): super(StepCounter, self).set_estimator(estimator) if self._summary_writer is None: self._summary_writer = SummaryWriterCache.get(estimator.model_dir) def every_n_step_end(self, current_step, outputs): current_time = time.time() if self._last_reported_time is not None and self._summary_writer: added_steps = current_step - self._last_reported_step elapsed_time = current_time - self._last_reported_time steps_per_sec = added_steps / elapsed_time summary = Summary(value=[Summary.Value(tag=self._summary_tag, simple_value=steps_per_sec)]) self._summary_writer.add_summary(summary, current_step) self._last_reported_step = current_step self._last_reported_time = current_time class NanLossDuringTrainingError(RuntimeError): def __str__(self): return "NaN loss during training." class NanLoss(EveryN): """NaN Loss monitor. Monitors loss and stops training if loss is NaN. Can either fail with exception or just stop training. """ def __init__(self, loss_tensor, every_n_steps=100, fail_on_nan_loss=True): """Initializes NanLoss monitor. Args: loss_tensor: `Tensor`, the loss tensor. every_n_steps: `int`, run check every this many steps. fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN. """ super(NanLoss, self).__init__(every_n_steps=every_n_steps) self._loss_tensor = loss_tensor self._fail_on_nan_loss = fail_on_nan_loss def every_n_step_begin(self, step): super(NanLoss, self).every_n_step_begin(step) return [self._loss_tensor] def every_n_step_end(self, step, outputs): super(NanLoss, self).every_n_step_end(step, outputs) if np.isnan(_extract_output(outputs, self._loss_tensor)): failure_message = "Model diverged with loss = NaN." if self._fail_on_nan_loss: logging.error(failure_message) raise NanLossDuringTrainingError else: logging.warning(failure_message) # We don't raise an error but we return "should stop" so we stop, but # without an exception. return True class RunHookAdapterForMonitors(session_run_hook.SessionRunHook): """Wraps monitors into a SessionRunHook.""" def __init__(self, monitors): self._monitors = monitors def begin(self): self._last_step = None self._global_step_tensor = contrib_variables.get_global_step() for m in self._monitors: m.begin(max_steps=None) def before_run(self, run_context): if self._last_step is None: self._last_step = run_context.session.run(self._global_step_tensor) + 1 request = {self._global_step_tensor: self._global_step_tensor} monitor_fetches = [] for m in self._monitors: monitor_requests = m.step_begin(self._last_step) if monitor_requests: if not isinstance(monitor_requests, list): raise ValueError("Monitor.step_begin should return a list.") monitor_fetches.extend(monitor_requests) if monitor_fetches: request["monitors"] = dict( zip(monitor_fetches, [_as_graph_element(f) for f in monitor_fetches])) return session_run_hook.SessionRunArgs(request) def after_run(self, run_context, run_values): result = run_values.results[ "monitors"] if "monitors" in run_values.results else {} for m in self._monitors: induce_stop = m.step_end(self._last_step, result) if induce_stop: run_context.request_stop() for m in self._monitors: m.post_step(self._last_step, run_context.session) self._last_step = run_values.results[self._global_step_tensor] + 1 def end(self, session): self._last_step = None for m in self._monitors: if "session" in inspect.getargspec(m.end).args: m.end(session=session) else: m.end() def _as_graph_element(obj): """Retrieves Graph element.""" graph = ops.get_default_graph() if not isinstance(obj, six.string_types): if not hasattr(obj, "graph") or obj.graph != graph: raise ValueError("Passed %s should have graph attribute that is equal " "to current graph %s." % (obj, graph)) return obj if ":" in obj: element = graph.as_graph_element(obj) else: element = graph.as_graph_element(obj + ":0") # Check that there is no :1 (e.g. it's single output). try: graph.as_graph_element(obj + ":1") except (KeyError, ValueError): pass else: raise ValueError("Name %s is ambiguous, " "as this `Operation` has multiple outputs " "(at least 2)." % obj) return element
35.425719
89
0.69116
[ "Apache-2.0" ]
Najah-lshanableh/tensorflow
tensorflow/contrib/learn/python/learn/monitors.py
44,353
Python
''' Image ===== The :class:`Image` widget is used to display an image:: Example in python:: wimg = Image(source='mylogo.png') Kv Example:: Image: source: 'mylogo.png' size: self.texture_size Asynchronous Loading -------------------- To load an image asynchronously (for example from an external webserver), use the :class:`AsyncImage` subclass:: aimg = AsyncImage(source='http://mywebsite.com/logo.png') This can be useful as it prevents your application from waiting until the image is loaded. If you want to display large images or retrieve them from URL's, using :class:`AsyncImage` will allow these resources to be retrieved on a background thread without blocking your application. Alignment --------- By default, the image is centered and fits inside the widget bounding box. If you don't want that, you can set `allow_stretch` to True and `keep_ratio` to False. You can also inherit from Image and create your own style. For example, if you want your image to be greater than the size of your widget, you could do:: class FullImage(Image): pass And in your kivy language file:: <-FullImage>: canvas: Color: rgb: (1, 1, 1) Rectangle: texture: self.texture size: self.width + 20, self.height + 20 pos: self.x - 10, self.y - 10 ''' __all__ = ('Image', 'AsyncImage') from kivy.uix.widget import Widget from kivy.core.image import Image as CoreImage from kivy.resources import resource_find from kivy.properties import StringProperty, ObjectProperty, ListProperty, \ AliasProperty, BooleanProperty, NumericProperty, ColorProperty from kivy.logger import Logger # delayed imports Loader = None class Image(Widget): '''Image class, see module documentation for more information. ''' source = StringProperty(None) '''Filename / source of your image. :attr:`source` is a :class:`~kivy.properties.StringProperty` and defaults to None. ''' texture = ObjectProperty(None, allownone=True) '''Texture object of the image. The texture represents the original, loaded image texture. It is stretched and positioned during rendering according to the :attr:`allow_stretch` and :attr:`keep_ratio` properties. Depending of the texture creation, the value will be a :class:`~kivy.graphics.texture.Texture` or a :class:`~kivy.graphics.texture.TextureRegion` object. :attr:`texture` is an :class:`~kivy.properties.ObjectProperty` and defaults to None. ''' texture_size = ListProperty([0, 0]) '''Texture size of the image. This represents the original, loaded image texture size. .. warning:: The texture size is set after the texture property. So if you listen to the change on :attr:`texture`, the property texture_size will not be up-to-date. Use self.texture.size instead. ''' def get_image_ratio(self): if self.texture: return self.texture.width / float(self.texture.height) return 1. mipmap = BooleanProperty(False) '''Indicate if you want OpenGL mipmapping to be applied to the texture. Read :ref:`mipmap` for more information. .. versionadded:: 1.0.7 :attr:`mipmap` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' image_ratio = AliasProperty(get_image_ratio, bind=('texture',), cache=True) '''Ratio of the image (width / float(height). :attr:`image_ratio` is an :class:`~kivy.properties.AliasProperty` and is read-only. ''' color = ColorProperty([1, 1, 1, 1]) '''Image color, in the format (r, g, b, a). This attribute can be used to 'tint' an image. Be careful: if the source image is not gray/white, the color will not really work as expected. .. versionadded:: 1.0.6 :attr:`color` is a :class:`~kivy.properties.ColorProperty` and defaults to [1, 1, 1, 1]. .. versionchanged:: 2.0.0 Changed from :class:`~kivy.properties.ListProperty` to :class:`~kivy.properties.ColorProperty`. ''' allow_stretch = BooleanProperty(False) '''If True, the normalized image size will be maximized to fit in the image box. Otherwise, if the box is too tall, the image will not be stretched more than 1:1 pixels. .. versionadded:: 1.0.7 :attr:`allow_stretch` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' keep_ratio = BooleanProperty(True) '''If False along with allow_stretch being True, the normalized image size will be maximized to fit in the image box and ignores the aspect ratio of the image. Otherwise, if the box is too tall, the image will not be stretched more than 1:1 pixels. .. versionadded:: 1.0.8 :attr:`keep_ratio` is a :class:`~kivy.properties.BooleanProperty` and defaults to True. ''' keep_data = BooleanProperty(False) '''If True, the underlying _coreimage will store the raw image data. This is useful when performing pixel based collision detection. .. versionadded:: 1.3.0 :attr:`keep_data` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' anim_delay = NumericProperty(.25) '''Delay the animation if the image is sequenced (like an animated gif). If anim_delay is set to -1, the animation will be stopped. .. versionadded:: 1.0.8 :attr:`anim_delay` is a :class:`~kivy.properties.NumericProperty` and defaults to 0.25 (4 FPS). ''' anim_loop = NumericProperty(0) '''Number of loops to play then stop animating. 0 means keep animating. .. versionadded:: 1.9.0 :attr:`anim_loop` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. ''' nocache = BooleanProperty(False) '''If this property is set True, the image will not be added to the internal cache. The cache will simply ignore any calls trying to append the core image. .. versionadded:: 1.6.0 :attr:`nocache` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' def get_norm_image_size(self): if not self.texture: return list(self.size) ratio = self.image_ratio w, h = self.size tw, th = self.texture.size # ensure that the width is always maximized to the container width if self.allow_stretch: if not self.keep_ratio: return [w, h] iw = w else: iw = min(w, tw) # calculate the appropriate height ih = iw / ratio # if the height is too higher, take the height of the container # and calculate appropriate width. no need to test further. :) if ih > h: if self.allow_stretch: ih = h else: ih = min(h, th) iw = ih * ratio return [iw, ih] norm_image_size = AliasProperty(get_norm_image_size, bind=('texture', 'size', 'allow_stretch', 'image_ratio', 'keep_ratio'), cache=True) '''Normalized image size within the widget box. This size will always fit the widget size and will preserve the image ratio. :attr:`norm_image_size` is an :class:`~kivy.properties.AliasProperty` and is read-only. ''' def __init__(self, **kwargs): self._coreimage = None self._loops = 0 update = self.texture_update fbind = self.fbind fbind('source', update) fbind('mipmap', update) super().__init__(**kwargs) def texture_update(self, *largs): self.set_texture_from_resource(self.source) def set_texture_from_resource(self, resource): if not resource: self._clear_core_image() return source = resource_find(resource) if not source: Logger.error('Image: Not found <%s>' % resource) self._clear_core_image() return if self._coreimage: self._coreimage.unbind(on_texture=self._on_tex_change) try: self._coreimage = image = CoreImage( source, mipmap=self.mipmap, anim_delay=self.anim_delay, keep_data=self.keep_data, nocache=self.nocache ) except Exception: Logger.error('Image: Error loading <%s>' % resource) self._clear_core_image() image = self._coreimage if image: image.bind(on_texture=self._on_tex_change) self.texture = image.texture def on_anim_delay(self, instance, value): if self._coreimage is None: return self._coreimage.anim_delay = value if value < 0: self._coreimage.anim_reset(False) def on_texture(self, instance, value): self.texture_size = value.size if value else [0, 0] def _clear_core_image(self): if self._coreimage: self._coreimage.unbind(on_texture=self._on_tex_change) self.texture = None self._coreimage = None self._loops = 0 def _on_tex_change(self, *largs): # update texture from core image self.texture = self._coreimage.texture ci = self._coreimage if self.anim_loop and ci._anim_index == len(ci._image.textures) - 1: self._loops += 1 if self.anim_loop == self._loops: ci.anim_reset(False) self._loops = 0 def reload(self): '''Reload image from disk. This facilitates re-loading of images from disk in case the image content changes. .. versionadded:: 1.3.0 Usage:: im = Image(source = '1.jpg') # -- do something -- im.reload() # image will be re-loaded from disk ''' self.remove_from_cache() old_source = self.source self.source = '' self.source = old_source def remove_from_cache(self): '''Remove image from cache. .. versionadded:: 2.0.0 ''' if self._coreimage: self._coreimage.remove_from_cache() def on_nocache(self, *args): if self.nocache: self.remove_from_cache() if self._coreimage: self._coreimage._nocache = True class AsyncImage(Image): '''Asynchronous Image class. See the module documentation for more information. .. note:: The AsyncImage is a specialized form of the Image class. You may want to refer to the :mod:`~kivy.loader` documentation and in particular, the :class:`~kivy.loader.ProxyImage` for more detail on how to handle events around asynchronous image loading. .. note:: AsyncImage currently does not support properties :attr:`anim_loop` and :attr:`mipmap` and setting those properties will have no effect. ''' __events__ = ('on_error', 'on_load') def __init__(self, **kwargs): self._found_source = None self._coreimage = None global Loader if not Loader: from kivy.loader import Loader self.fbind('source', self._load_source) super().__init__(**kwargs) def _load_source(self, *args): source = self.source if not source: self._clear_core_image() return if not self.is_uri(source): source = resource_find(source) if not source: Logger.error('AsyncImage: Not found <%s>' % self.source) self._clear_core_image() return self._found_source = source self._coreimage = image = Loader.image( source, nocache=self.nocache, mipmap=self.mipmap, anim_delay=self.anim_delay ) image.bind( on_load=self._on_source_load, on_error=self._on_source_error, on_texture=self._on_tex_change ) self.texture = image.texture def _on_source_load(self, value): image = self._coreimage.image if not image: return self.texture = image.texture self.dispatch('on_load') def _on_source_error(self, instance, error=None): self.dispatch('on_error', error) def on_error(self, error): pass def on_load(self, *args): pass def is_uri(self, filename): proto = filename.split('://', 1)[0] return proto in ('http', 'https', 'ftp', 'smb', 'S3') def _clear_core_image(self): if self._coreimage: self._coreimage.unbind(on_load=self._on_source_load) super()._clear_core_image() self._found_source = None def _on_tex_change(self, *largs): if self._coreimage: self.texture = self._coreimage.texture def texture_update(self, *largs): pass def remove_from_cache(self): if self._found_source: Loader.remove_from_cache(self._found_source) super().remove_from_cache()
30.435185
140
0.625114
[ "MIT" ]
eman1can/kivy
kivy/uix/image.py
13,148
Python
#!/usr/bin/env python # # 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. """This example gets all activities. """ # Import appropriate modules from the client library. from googleads import ad_manager def main(client): # Initialize appropriate service. activity_service = client.GetService('ActivityService', version='v201811') # Create a statement to select activities. statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. while True: response = activity_service.getActivitiesByStatement(statement.ToStatement( )) if 'results' in response and len(response['results']): for activity in response['results']: # Print out some information for each activity. print('Activity with ID "%d" and name "%s" was found.\n' % (activity['id'], activity['name'])) statement.offset += statement.limit else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client)
34.72549
79
0.730661
[ "Apache-2.0" ]
SoungMo/googleads-python-lib
examples/ad_manager/v201811/activity_service/get_all_activities.py
1,771
Python
#!/usr/bin/env python from __future__ import print_function import sys from Configuration.PyReleaseValidation.MatrixReader import MatrixReader from Configuration.PyReleaseValidation.MatrixRunner import MatrixRunner from Configuration.PyReleaseValidation.MatrixInjector import MatrixInjector,performInjectionOptionTest # ================================================================================ def showRaw(opt): mrd = MatrixReader(opt) mrd.showRaw(opt.useInput, opt.refRel, opt.fromScratch, opt.raw, opt.step1Only, selected=opt.testList) return 0 # ================================================================================ def runSelected(opt): mrd = MatrixReader(opt) mrd.prepare(opt.useInput, opt.refRel, opt.fromScratch) # test for wrong input workflows if opt.testList: definedWF = [] for dwf in mrd.workFlows: definedWF.append(dwf.numId) for twf in opt.testList: if twf not in definedWF: raise ValueError('Not defined workflow ', twf , ' requested') ret = 0 if opt.show: mrd.show(opt.testList, opt.extended, opt.cafVeto) if opt.testList : print('testListected items:', opt.testList) else: mRunnerHi = MatrixRunner(mrd.workFlows, opt.nProcs, opt.nThreads) ret = mRunnerHi.runTests(opt) if opt.wmcontrol: if ret!=0: print('Cannot go on with wmagent injection with failing workflows') else: wfInjector = MatrixInjector(opt,mode=opt.wmcontrol,options=opt.wmoptions) ret= wfInjector.prepare(mrd, mRunnerHi.runDirs) if ret==0: wfInjector.upload() wfInjector.submit() return ret # ================================================================================ if __name__ == '__main__': #this can get out of here predefinedSet={ 'limited' : [5.1, #FastSim ttbar 7.3, #CosmicsSPLoose_UP17 8, #BH/Cosmic MC 25, #MC ttbar 4.22, #cosmic data 4.53, #run1 data + miniAOD 9.0, #Higgs200 charged taus 1000, #data+prompt 1001, #data+express 101.0, #SingleElectron120E120EHCAL 136.731, #2016B Photon data 136.7611, #2016E JetHT reMINIAOD from 80X legacy 136.8311, #2017F JetHT reMINIAOD from 94X reprocessing 136.788, #2017B Photon data 136.85, #2018A Egamma data 140.53, #2011 HI data 140.56, #2018 HI data 158.0, #2018 HI MC with pp-like reco 1306.0, #SingleMu Pt1 UP15 1325.7, #test NanoAOD from existing MINI 1330, #Run2 MC Zmm 135.4, #Run 2 Zee ttbar 10042.0, #2017 ZMM 10024.0, #2017 ttbar 10224.0, #2017 ttbar PU 10824.0, #2018 ttbar 11634.0, #2021 ttbar 12434.0, #2023 ttbar 20034.0, #2026D35 ttbar (MTD TDR baseline) 20434.0, #2026D41 ttbar (L1T TDR baseline) 21234.0, #2026D44 (exercise HF nose) 22034.0, #2026D46 ttbar (exercise V11 HGCal) 25202.0, #2016 ttbar UP15 PU 250202.181, #2018 ttbar stage1 + stage2 premix ], 'jetmc': [5.1, 13, 15, 25, 38, 39], #MC 'metmc' : [5.1, 15, 25, 37, 38, 39], #MC 'muonmc' : [5.1, 124.4, 124.5, 20, 21, 22, 23, 25, 30], #MC } import optparse usage = 'usage: runTheMatrix.py --show -s ' parser = optparse.OptionParser(usage) parser.add_option('-b','--batchName', help='relval batch: suffix to be appended to Campaign name', dest='batchName', default='' ) parser.add_option('-m','--memoryOffset', help='memory of the wf for single core', dest='memoryOffset', default=3000 ) parser.add_option('--addMemPerCore', help='increase of memory per each n > 1 core: memory(n_core) = memoryOffset + (n_core-1) * memPerCore', dest='memPerCore', default=1500 ) parser.add_option('-j','--nproc', help='number of processes. 0 Will use 4 processes, not execute anything but create the wfs', dest='nProcs', default=4 ) parser.add_option('-t','--nThreads', help='number of threads per process to use in cmsRun.', dest='nThreads', default=1 ) parser.add_option('-n','--showMatrix', help='Only show the worflows. Use --ext to show more', dest='show', default=False, action='store_true' ) parser.add_option('-e','--extended', help='Show details of workflows, used with --show', dest='extended', default=False, action='store_true' ) parser.add_option('-s','--selected', help='Run a pre-defined selected matrix of wf. Deprecated, please use -l limited', dest='restricted', default=False, action='store_true' ) parser.add_option('-l','--list', help='Coma separated list of workflow to be shown or ran. Possible keys are also '+str(predefinedSet.keys())+'. and wild card like muon, or mc', dest='testList', default=None ) parser.add_option('-r','--raw', help='Temporary dump the .txt needed for prodAgent interface. To be discontinued soon. Argument must be the name of the set (standard, pileup,...)', dest='raw' ) parser.add_option('-i','--useInput', help='Use recyling where available. Either all, or a coma separated list of wf number.', dest='useInput', default=None ) parser.add_option('-w','--what', help='Specify the set to be used. Argument must be the name of the set (standard, pileup,...)', dest='what', default='all' ) parser.add_option('--step1', help='Used with --raw. Limit the production to step1', dest='step1Only', default=False ) parser.add_option('--maxSteps', help='Only run maximum on maxSteps. Used when we are only interested in first n steps.', dest='maxSteps', default=9999, type="int" ) parser.add_option('--fromScratch', help='Coma separated list of wf to be run without recycling. all is not supported as default.', dest='fromScratch', default=None ) parser.add_option('--refRelease', help='Allow to modify the recycling dataset version', dest='refRel', default=None ) parser.add_option('--wmcontrol', help='Create the workflows for injection to WMAgent. In the WORKING. -wmcontrol init will create the the workflows, -wmcontrol test will dryRun a test, -wmcontrol submit will submit to wmagent', choices=['init','test','submit','force'], dest='wmcontrol', default=None, ) parser.add_option('--revertDqmio', help='When submitting workflows to wmcontrol, force DQM outout to use pool and not DQMIO', choices=['yes','no'], dest='revertDqmio', default='no', ) parser.add_option('--optionswm', help='Specify a few things for wm injection', default='', dest='wmoptions') parser.add_option('--keep', help='allow to specify for which coma separated steps the output is needed', default=None) parser.add_option('--label', help='allow to give a special label to the output dataset name', default='') parser.add_option('--command', help='provide a way to add additional command to all of the cmsDriver commands in the matrix', dest='command', default=None ) parser.add_option('--apply', help='allow to use the --command only for 1 coma separeated', dest='apply', default=None) parser.add_option('--workflow', help='define a workflow to be created or altered from the matrix', action='append', dest='workflow', default=None ) parser.add_option('--dryRun', help='do not run the wf at all', action='store_true', dest='dryRun', default=False ) parser.add_option('--testbed', help='workflow injection to cmswebtest (you need dedicated rqmgr account)', dest='testbed', default=False, action='store_true' ) parser.add_option('--noCafVeto', help='Run from any source, ignoring the CAF label', dest='cafVeto', default=True, action='store_false' ) parser.add_option('--overWrite', help='Change the content of a step for another. List of pairs.', dest='overWrite', default=None ) parser.add_option('--noRun', help='Remove all run list selection from wfs', dest='noRun', default=False, action='store_true') parser.add_option('--das-options', help='Options to be passed to dasgoclient.', dest='dasOptions', default="--limit 0", action='store') parser.add_option('--job-reports', help='Dump framework job reports', dest='jobReports', default=False, action='store_true') parser.add_option('--ibeos', help='Use IB EOS site configuration', dest='IBEos', default=False, action='store_true') opt,args = parser.parse_args() if opt.IBEos: import os from commands import getstatusoutput as run_cmd ibeos_cache = os.path.join(os.getenv("LOCALRT"), "ibeos_cache.txt") if not os.path.exists(ibeos_cache): err, out = run_cmd("curl -L -s -o %s https://raw.githubusercontent.com/cms-sw/cms-sw.github.io/master/das_queries/ibeos.txt" % ibeos_cache) if err: run_cmd("rm -f %s" % ibeos_cache) print("Error: Unable to download ibeos cache information") print(out) sys.exit(err) for cmssw_env in [ "CMSSW_BASE", "CMSSW_RELEASE_BASE" ]: cmssw_base = os.getenv(cmssw_env,None) if not cmssw_base: continue cmssw_base = os.path.join(cmssw_base,"src/Utilities/General/ibeos") if os.path.exists(cmssw_base): os.environ["PATH"]=cmssw_base+":"+os.getenv("PATH") os.environ["CMS_PATH"]="/cvmfs/cms-ib.cern.ch" os.environ["CMSSW_USE_IBEOS"]="true" print(">> WARNING: You are using SITECONF from /cvmfs/cms-ib.cern.ch") break if opt.restricted: print('Deprecated, please use -l limited') if opt.testList: opt.testList+=',limited' else: opt.testList='limited' def stepOrIndex(s): if s.isdigit(): return int(s) else: return s if opt.apply: opt.apply=map(stepOrIndex,opt.apply.split(',')) if opt.keep: opt.keep=map(stepOrIndex,opt.keep.split(',')) if opt.testList: testList=[] for entry in opt.testList.split(','): if not entry: continue mapped=False for k in predefinedSet: if k.lower().startswith(entry.lower()) or k.lower().endswith(entry.lower()): testList.extend(predefinedSet[k]) mapped=True break if not mapped: try: testList.append(float(entry)) except: print(entry,'is not a possible selected entry') opt.testList = list(set(testList)) if opt.useInput: opt.useInput = opt.useInput.split(',') if opt.fromScratch: opt.fromScratch = opt.fromScratch.split(',') if opt.nProcs: opt.nProcs=int(opt.nProcs) if opt.nThreads: opt.nThreads=int(opt.nThreads) if (opt.memoryOffset): opt.memoryOffset=int(opt.memoryOffset) if (opt.memPerCore): opt.memPerCore=int(opt.memPerCore) if opt.wmcontrol: performInjectionOptionTest(opt) if opt.overWrite: opt.overWrite=eval(opt.overWrite) if opt.raw and opt.show: ###prodAgent to be discontinued ret = showRaw(opt) else: ret = runSelected(opt) sys.exit(ret)
41.390313
216
0.489744
[ "Apache-2.0" ]
AdrianoDee/cmssw
Configuration/PyReleaseValidation/scripts/runTheMatrix.py
14,528
Python
import re import torch import torch.nn as nn import torch.nn.functional as F from models.networks.sync_batchnorm import SynchronizedBatchNorm2d import torch.nn.utils.spectral_norm as spectral_norm # Returns a function that creates a normalization function # that does not condition on semantic map def get_nonspade_norm_layer(opt, norm_type='instance'): # helper function to get # output channels of the previous layer def get_out_channel(layer): if hasattr(layer, 'out_channels'): return getattr(layer, 'out_channels') return layer.weight.size(0) # this function will be returned def add_norm_layer(layer): nonlocal norm_type if norm_type.startswith('spectral'): layer = spectral_norm(layer) subnorm_type = norm_type[len('spectral'):] if subnorm_type == 'none' or len(subnorm_type) == 0: return layer # remove bias in the previous layer, which is meaningless # since it has no effect after normalization if getattr(layer, 'bias', None) is not None: delattr(layer, 'bias') layer.register_parameter('bias', None) if subnorm_type == 'batch': norm_layer = nn.BatchNorm2d(get_out_channel(layer), affine=True) elif subnorm_type == 'sync_batch': norm_layer = SynchronizedBatchNorm2d(get_out_channel(layer), affine=True) elif subnorm_type == 'instance': norm_layer = nn.InstanceNorm2d(get_out_channel(layer), affine=False) else: raise ValueError('normalization layer %s is not recognized' % subnorm_type) return nn.Sequential(layer, norm_layer) return add_norm_layer class SPADE(nn.Module): def __init__(self, config_text, norm_nc, label_nc): super().__init__() assert config_text.startswith('spade') parsed = re.search('spade(\D+)(\d)x\d', config_text) param_free_norm_type = str(parsed.group(1)) ks = int(parsed.group(2)) if param_free_norm_type == 'instance': self.param_free_norm = nn.InstanceNorm2d(norm_nc, affine=False) elif param_free_norm_type == 'syncbatch': self.param_free_norm = SynchronizedBatchNorm2d(norm_nc, affine=False) elif param_free_norm_type == 'batch': self.param_free_norm = nn.BatchNorm2d(norm_nc, affine=False) else: raise ValueError('%s is not a recognized param-free norm type in SPADE' % param_free_norm_type) # The dimension of the intermediate embedding space. Yes, hardcoded. nhidden = 128 pw = ks // 2 self.mlp_shared = nn.Sequential( nn.Conv2d(label_nc, nhidden, kernel_size=ks, padding=pw), nn.ReLU() ) self.mlp_gamma = nn.Conv2d(nhidden, norm_nc, kernel_size=ks, padding=pw) self.mlp_beta = nn.Conv2d(nhidden, norm_nc, kernel_size=ks, padding=pw) def forward(self, x, segmap): # Part 1. generate parameter-free normalized activations normalized = self.param_free_norm(x) # Part 2. produce scaling and bias conditioned on semantic map segmap = F.interpolate(segmap, size=x.size()[2:], mode='nearest') actv = self.mlp_shared(segmap) gamma = self.mlp_gamma(actv) beta = self.mlp_beta(actv) # apply scale and bias out = normalized * (1 + gamma) + beta return out
38.098901
87
0.651284
[ "MIT" ]
atmacvit/meronymnet
baselines/scripts/segvae/models/networks/normalization.py
3,467
Python
from client.util.html.tooling.base.HTMLElement import HTMLElement class ScriptElement(HTMLElement): def __init__(self, src): super().__init__('script') self.set_attribute('src', src)
25.625
65
0.712195
[ "MIT" ]
vincihb/stock-price-predictor
client/util/html/tooling/base/document/ScriptElement.py
205
Python
import io import copy import uuid import numpy as np try: # pip install pycollada import collada except BaseException: collada = None try: import PIL.Image except ImportError: pass from .. import util from .. import visual from ..constants import log def load_collada(file_obj, resolver=None, **kwargs): """ Load a COLLADA (.dae) file into a list of trimesh kwargs. Parameters ---------- file_obj : file object Containing a COLLADA file resolver : trimesh.visual.Resolver or None For loading referenced files, like texture images kwargs : ** Passed to trimesh.Trimesh.__init__ Returns ------- loaded : list of dict kwargs for Trimesh constructor """ # load scene using pycollada c = collada.Collada(file_obj) # Create material map from Material ID to trimesh material material_map = {} for m in c.materials: effect = m.effect material_map[m.id] = _parse_material(effect, resolver) # name : kwargs meshes = {} # list of dict graph = [] for node in c.scene.nodes: _parse_node(node=node, parent_matrix=np.eye(4), material_map=material_map, meshes=meshes, graph=graph, resolver=resolver) # create kwargs for load_kwargs result = {'class': 'Scene', 'graph': graph, 'geometry': meshes} return result def export_collada(mesh, **kwargs): """ Export a mesh or a list of meshes as a COLLADA .dae file. Parameters ----------- mesh: Trimesh object or list of Trimesh objects The mesh(es) to export. Returns ----------- export: str, string of COLLADA format output """ meshes = mesh if not isinstance(mesh, (list, tuple, set, np.ndarray)): meshes = [mesh] c = collada.Collada() nodes = [] for i, m in enumerate(meshes): # Load uv, colors, materials uv = None colors = None mat = _unparse_material(None) if m.visual.defined: if m.visual.kind == 'texture': mat = _unparse_material(m.visual.material) uv = m.visual.uv elif m.visual.kind == 'vertex': colors = (m.visual.vertex_colors / 255.0)[:, :3] c.effects.append(mat.effect) c.materials.append(mat) # Create geometry object vertices = collada.source.FloatSource( 'verts-array', m.vertices.flatten(), ('X', 'Y', 'Z')) normals = collada.source.FloatSource( 'normals-array', m.vertex_normals.flatten(), ('X', 'Y', 'Z')) input_list = collada.source.InputList() input_list.addInput(0, 'VERTEX', '#verts-array') input_list.addInput(1, 'NORMAL', '#normals-array') arrays = [vertices, normals] if uv is not None: texcoords = collada.source.FloatSource( 'texcoords-array', uv.flatten(), ('U', 'V')) input_list.addInput(2, 'TEXCOORD', '#texcoords-array') arrays.append(texcoords) if colors is not None: idx = 2 if uv: idx = 3 colors = collada.source.FloatSource('colors-array', colors.flatten(), ('R', 'G', 'B')) input_list.addInput(idx, 'COLOR', '#colors-array') arrays.append(colors) geom = collada.geometry.Geometry( c, uuid.uuid4().hex, uuid.uuid4().hex, arrays ) indices = np.repeat(m.faces.flatten(), len(arrays)) matref = u'material{}'.format(i) triset = geom.createTriangleSet(indices, input_list, matref) geom.primitives.append(triset) c.geometries.append(geom) matnode = collada.scene.MaterialNode(matref, mat, inputs=[]) geomnode = collada.scene.GeometryNode(geom, [matnode]) node = collada.scene.Node(u'node{}'.format(i), children=[geomnode]) nodes.append(node) scene = collada.scene.Scene('scene', nodes) c.scenes.append(scene) c.scene = scene b = io.BytesIO() c.write(b) b.seek(0) return b.read() def _parse_node(node, parent_matrix, material_map, meshes, graph, resolver=None): """ Recursively parse COLLADA scene nodes. """ # Parse mesh node if isinstance(node, collada.scene.GeometryNode): geometry = node.geometry # Create local material map from material symbol to actual material local_material_map = {} for mn in node.materials: symbol = mn.symbol m = mn.target if m.id in material_map: local_material_map[symbol] = material_map[m.id] else: local_material_map[symbol] = _parse_material(m, resolver) # Iterate over primitives of geometry for i, primitive in enumerate(geometry.primitives): if isinstance(primitive, collada.polylist.Polylist): primitive = primitive.triangleset() if isinstance(primitive, collada.triangleset.TriangleSet): vertex = primitive.vertex vertex_index = primitive.vertex_index vertices = vertex[vertex_index].reshape( len(vertex_index) * 3, 3) # Get normals if present normals = None if primitive.normal is not None: normal = primitive.normal normal_index = primitive.normal_index normals = normal[normal_index].reshape( len(normal_index) * 3, 3) # Get colors if present colors = None s = primitive.sources if ('COLOR' in s and len(s['COLOR']) > 0 and len(primitive.index) > 0): color = s['COLOR'][0][4].data color_index = primitive.index[:, :, s['COLOR'][0][0]] colors = color[color_index].reshape( len(color_index) * 3, 3) faces = np.arange( vertices.shape[0]).reshape( vertices.shape[0] // 3, 3) # Get UV coordinates if possible vis = None if primitive.material in local_material_map: material = copy.copy( local_material_map[primitive.material]) uv = None if len(primitive.texcoordset) > 0: texcoord = primitive.texcoordset[0] texcoord_index = primitive.texcoord_indexset[0] uv = texcoord[texcoord_index].reshape( (len(texcoord_index) * 3, 2)) vis = visual.texture.TextureVisuals( uv=uv, material=material) primid = u'{}.{}'.format(geometry.id, i) meshes[primid] = { 'vertices': vertices, 'faces': faces, 'vertex_normals': normals, 'vertex_colors': colors, 'visual': vis} graph.append({'frame_to': primid, 'matrix': parent_matrix, 'geometry': primid}) # recurse down tree for nodes with children elif isinstance(node, collada.scene.Node): if node.children is not None: for child in node.children: # create the new matrix matrix = np.dot(parent_matrix, node.matrix) # parse the child node _parse_node( node=child, parent_matrix=matrix, material_map=material_map, meshes=meshes, graph=graph, resolver=resolver) elif isinstance(node, collada.scene.CameraNode): # TODO: convert collada cameras to trimesh cameras pass elif isinstance(node, collada.scene.LightNode): # TODO: convert collada lights to trimesh lights pass def _load_texture(file_name, resolver): """ Load a texture from a file into a PIL image. """ file_data = resolver.get(file_name) image = PIL.Image.open(util.wrap_as_stream(file_data)) return image def _parse_material(effect, resolver): """ Turn a COLLADA effect into a trimesh material. """ # Compute base color baseColorFactor = np.ones(4) baseColorTexture = None if isinstance(effect.diffuse, collada.material.Map): try: baseColorTexture = _load_texture( effect.diffuse.sampler.surface.image.path, resolver) except BaseException: log.warning('unable to load base texture', exc_info=True) elif effect.diffuse is not None: baseColorFactor = effect.diffuse # Compute emission color emissiveFactor = np.zeros(3) emissiveTexture = None if isinstance(effect.emission, collada.material.Map): try: emissiveTexture = _load_texture( effect.diffuse.sampler.surface.image.path, resolver) except BaseException: log.warning('unable to load emissive texture', exc_info=True) elif effect.emission is not None: emissiveFactor = effect.emission[:3] # Compute roughness roughnessFactor = 1.0 if (not isinstance(effect.shininess, collada.material.Map) and effect.shininess is not None): roughnessFactor = np.sqrt(2.0 / (2.0 + effect.shininess)) # Compute metallic factor metallicFactor = 0.0 # Compute normal texture normalTexture = None if effect.bumpmap is not None: try: normalTexture = _load_texture( effect.bumpmap.sampler.surface.image.path, resolver) except BaseException: log.warning('unable to load bumpmap', exc_info=True) # Compute opacity if (effect.transparent is not None and not isinstance(effect.transparent, collada.material.Map)): baseColorFactor = tuple(np.append(baseColorFactor[:3], effect.transparent[3])) return visual.material.PBRMaterial( emissiveFactor=emissiveFactor, emissiveTexture=emissiveTexture, normalTexture=normalTexture, baseColorTexture=baseColorTexture, baseColorFactor=baseColorFactor, metallicFactor=metallicFactor, roughnessFactor=roughnessFactor) def _unparse_material(material): """ Turn a trimesh material into a COLLADA material. """ # TODO EXPORT TEXTURES if isinstance(material, visual.material.PBRMaterial): diffuse = material.baseColorFactor if diffuse is not None: diffuse = list(diffuse) emission = material.emissiveFactor if emission is not None: emission = [float(emission[0]), float(emission[1]), float(emission[2]), 1.0] shininess = material.roughnessFactor if shininess is not None: shininess = 2.0 / shininess**2 - 2.0 effect = collada.material.Effect( uuid.uuid4().hex, params=[], shadingtype='phong', diffuse=diffuse, emission=emission, specular=[1.0, 1.0, 1.0, 1.0], shininess=float(shininess) ) material = collada.material.Material( uuid.uuid4().hex, 'pbrmaterial', effect ) else: effect = collada.material.Effect( uuid.uuid4().hex, params=[], shadingtype='phong' ) material = collada.material.Material( uuid.uuid4().hex, 'defaultmaterial', effect ) return material def load_zae(file_obj, resolver=None, **kwargs): """ Load a ZAE file, which is just a zipped DAE file. Parameters ------------- file_obj : file object Contains ZAE data resolver : trimesh.visual.Resolver Resolver to load additional assets kwargs : dict Passed to load_collada Returns ------------ loaded : dict Results of loading """ # a dict, {file name : file object} archive = util.decompress(file_obj, file_type='zip') # load the first file with a .dae extension file_name = next(i for i in archive.keys() if i.lower().endswith('.dae')) # a resolver so the loader can load textures / etc resolver = visual.resolvers.ZipResolver(archive) # run the regular collada loader loaded = load_collada(archive[file_name], resolver=resolver, **kwargs) return loaded # only provide loaders if `pycollada` is installed _collada_loaders = {} _collada_exporters = {} if collada is not None: _collada_loaders['dae'] = load_collada _collada_loaders['zae'] = load_zae _collada_exporters['dae'] = export_collada
32.231144
86
0.566619
[ "MIT" ]
BerkeleyAutomation/trimesh
trimesh/exchange/dae.py
13,247
Python
#!/usr/bin/env python """ Copyright (c) 2006-2019 sqlmap developers (http://sqlmap.org/) See the file 'LICENSE' for copying permission """ import string from lib.core.enums import PRIORITY __priority__ = PRIORITY.NORMAL def tamper(payload, **kwargs): """ Unicode-escapes non-encoded characters in a given payload (not processing already encoded) (e.g. SELECT -> \u0053\u0045\u004C\u0045\u0043\u0054) Notes: * Useful to bypass weak filtering and/or WAFs in JSON contexes >>> tamper('SELECT FIELD FROM TABLE') '\\\\u0053\\\\u0045\\\\u004C\\\\u0045\\\\u0043\\\\u0054\\\\u0020\\\\u0046\\\\u0049\\\\u0045\\\\u004C\\\\u0044\\\\u0020\\\\u0046\\\\u0052\\\\u004F\\\\u004D\\\\u0020\\\\u0054\\\\u0041\\\\u0042\\\\u004C\\\\u0045' """ retVal = payload if payload: retVal = "" i = 0 while i < len(payload): if payload[i] == '%' and (i < len(payload) - 2) and payload[i + 1:i + 2] in string.hexdigits and payload[i + 2:i + 3] in string.hexdigits: retVal += "\\u00%s" % payload[i + 1:i + 3] i += 3 else: retVal += '\\u%.4X' % ord(payload[i]) i += 1 return retVal
30.35
213
0.57084
[ "Unlicense" ]
6un9-h0-Dan/CTF-Heaven
Toolz/sqlmap/tamper/charunicodeescape.py
1,214
Python
# Copyright 2018 ZTE 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 rest_framework import serializers from .checksum import ChecksumSerializer class VnfPackageSoftwareImageInfoSerializer(serializers.Serializer): id = serializers.CharField( help_text="Identifier of the software image.", required=True, allow_null=False, allow_blank=False ) name = serializers.CharField( help_text="Name of the software image.", required=True, allow_null=True, allow_blank=False ) provider = serializers.CharField( help_text="Provider of the software image.", required=True, allow_null=True, allow_blank=False ) version = serializers.CharField( help_text="Version of the software image.", required=True, allow_null=True, allow_blank=False ) checksum = ChecksumSerializer( help_text="Checksum of the software image file.", required=True, allow_null=False ) containerFormat = serializers.ChoiceField( help_text="terminationType: Indicates whether forceful or graceful termination is requested.", choices=["AKI", "AMI", "ARI", "BARE", "DOCKER", "OVA", "OVF"], required=True, allow_null=True ) diskFormat = serializers.ChoiceField( help_text="Disk format of a software image is the format of the underlying disk image.", choices=["AKI", "AMI", "ARI", "ISO", "QCOW2", "RAW", "VDI", "VHD", "VHDX", "VMDK"], required=True, allow_null=True ) createdAt = serializers.DateTimeField( help_text="Time when this software image was created.", required=True, format=None, input_formats=None ) minDisk = serializers.IntegerField( help_text="The minimal disk for this software image in bytes.", required=True, allow_null=True ) minRam = serializers.IntegerField( help_text="The minimal RAM for this software image in bytes.", required=True, allow_null=True ) size = serializers.IntegerField( help_text="Size of this software image in bytes.", required=True, allow_null=True ) userMetadata = serializers.DictField( help_text="User-defined data.", child=serializers.CharField( help_text="KeyValue Pairs", allow_blank=True ), required=False, allow_null=True ) imagePath = serializers.CharField( help_text="Path in the VNF package.", required=True, allow_null=True, allow_blank=False )
32.896907
102
0.65246
[ "Apache-2.0" ]
onap/archive-vfc-nfvo-catalog
catalog/packages/serializers/vnf_pkg_software_image_info.py
3,191
Python
#!/usr/bin/env python import numpy as np import socket, curses, json, traceback, math, argparse, math, sys, os, stat from operator import itemgetter, attrgetter from configutils.dfmux_config_constructor import get_physical_id, sq_phys_id_to_info from configutils.dfmux_config_constructor import uniquifyList, generate_dfmux_lyrebird_config #from spt3g.util import genericutils as GU # not in the public S4 repo from spt3g import core, dfmux, calibration from functools import cmp_to_key import signal import warnings warnings.filterwarnings("ignore") def split_on_numbers(s): ''' Splits the string into a list where the numbers and the characters between numbers are each element Copied from spt3g_software to fix dependencies (sorry) ''' prevDig = False outList = [] for char in s: if char.isdigit(): if prevDig: outList[-1] += char else: prevDig = True outList.append(char) else: if not prevDig and len(outList)>0: outList[-1] += char else: prevDig = False outList.append(char) return outList def str_cmp_with_numbers_sorted(str1, str2): ''' Compares two strings where numbers are sorted according to value, so Sq12 ends up after Sq8, use in sorted function Copied from spt3g_software to fix dependencies (sorry) ''' if str1==str2: return 0 split1 = split_on_numbers(str1) split2 = split_on_numbers(str2) largestStr = 0 for l in [split1, split2]: for s in l: if s[0].isdigit(): largestStr = len(s) if len(s) > largestStr else largestStr for l in [split1, split2]: for i in range(len(l)): if l[i][0].isdigit(): l[i] = '0'*(largestStr-len(l[i])) +l[i] p1 = reduce(lambda x,y: x+y, split1) p2 = reduce(lambda x,y: x+y, split2) return -1 if p1<p2 else 1 @core.cache_frame_data(type = core.G3FrameType.Housekeeping, wiring_map = 'WiringMap', tf = 'DfMuxTransferFunction', system = 'ReadoutSystem') def AddVbiasAndCurrentConv(frame, wiring_map): hk_map = frame['DfMuxHousekeeping'] v_bias = core.G3MapDouble() i_conv = core.G3MapDouble() for k in wiring_map.keys(): vb = dfmux.unittransforms.bolo_bias_voltage_rms(wiring_map, hk_map, bolo = k, tf = tf, system = system) / core.G3Units.V ic = dfmux.unittransforms.counts_to_rms_amps(wiring_map, hk_map, bolo = k, tf = tf, system = system) / core.G3Units.amp v_bias[k] = vb i_conv[k] = ic frame['VoltageBias'] = v_bias frame['CurrentConv'] = i_conv def make_square_block(n_things): sq = n_things**0.5 if n_things == int(math.floor(sq))**2: return (sq,sq) else: sq = int(math.floor(sq)) return (sq, sq+1) def write_get_hk_script(fn, hostname, port): script = '''#!/bin/bash nc -w 1 %s %d ''' % (hostname, port) f = open(fn, 'w') f.write(script) f.close() st = os.stat(fn) os.chmod(fn, st.st_mode | stat.S_IXUSR) class BoloPropertiesFaker(object): def __init__(self): self.wiring_map = None self.bolo_props = None self.sent_off = False self.default_tf = 'spt3g_filtering_2017_full' return def __call__(self, frame): if 'DfMuxTransferFunction' in frame: self.default_tf = frame['DfMuxTransferFunction'] if frame.type == core.G3FrameType.Wiring: self.wiring_map = frame['WiringMap'] return self.send_off(frame) elif frame.type == core.G3FrameType.Calibration: if 'BolometerProperties' in frame: self.bolo_props = frame['BolometerProperties'] elif 'NominalBolometerProperties' in frame: self.bolo_props = frame['NominalBolometerProperties'] def send_off(self, frame): if not self.wiring_map is None and self.bolo_props is None: #faking the frame data self.bolo_props = calibration.BolometerPropertiesMap() n_chans = 0 squids = {} for k in self.wiring_map.keys(): wm = self.wiring_map[k] c = wm.channel + 1 if c > n_chans: n_chans = c sq = get_physical_id(wm.board_serial, wm.crate_serial, wm.board_slot, wm.module + 1) squids[sq] = 1 n_squids = len(squids.keys()) sq_layout = make_square_block(n_squids) ch_layout = make_square_block(n_chans) sq_x_sep = ch_layout[0] + 1 sq_y_sep = ch_layout[1] + 1 ch_x_sep = 1 ch_y_sep = 1 for i, sq in enumerate( sorted(squids.keys()) ): x = i % sq_layout[0] y = i // sq_layout[0] squids[sq] = (1.2 * x * ch_layout[0], 1.2* y * ch_layout[1]) #need nsquids #need nbolos per squid for k in self.wiring_map.keys(): wm = self.wiring_map[k] sq_id = get_physical_id(wm.board_serial, wm.crate_serial, wm.board_slot, wm.module + 1) w_id = get_physical_id(wm.board_serial, wm.crate_serial, wm.board_slot) sql = squids[sq_id] x = sql[0] + ((wm.channel) % ch_layout[0]) * ch_x_sep y = sql[1] + ((wm.channel) // ch_layout[0]) * ch_y_sep bp = calibration.BolometerProperties() bp.physical_name = k bp.band = 0 bp.pol_angle = 0 bp.pol_efficiency = 0 bp.wafer_id = w_id bp.squid_id = sq_id bp.x_offset = float(x) bp.y_offset = float(y) self.bolo_props[k] = bp out_frame = core.G3Frame(core.G3FrameType.Calibration) out_frame['BolometerProperties'] = self.bolo_props out_frame['DfMuxTransferFunction'] = self.default_tf return [out_frame, frame] else: return frame class BirdConfigGenerator(object): def __init__(self, lyrebird_output_file = '', get_hk_script_name= '', hostname = '', hk_hostname = '', port = 3, hk_port = 3, get_hk_port = 3, dv_buffer_size = 0, min_max_update_interval = 0, rendering_sub_sampling = 1, max_framerate = 0, mean_decay_factor = 0.01 ): self.l_fn = lyrebird_output_file self.get_hk_script_name = get_hk_script_name self.is_written = False self.bolo_props = None self.wiring_map = None self.hostname = hostname self.hk_hostname = hk_hostname self.port = port self.hk_port = hk_port self.get_hk_port = get_hk_port self.dv_buffer_size = dv_buffer_size self.min_max_update_interval = min_max_update_interval self.rendering_sub_sampling = rendering_sub_sampling self.max_framerate = max_framerate self.mean_decay_factor = mean_decay_factor def __call__(self, frame): if frame.type == core.G3FrameType.Calibration: if 'BolometerProperties' in frame: bp_id = 'BolometerProperties' elif 'NominalBolometerProperties' in frame: bp_id = 'NominalBolometerProperties' else: raise RuntimeError("BolometerProperties fucked") self.bolo_props = frame[bp_id] self.write_config() elif frame.type == core.G3FrameType.Wiring: self.wiring_map = frame['WiringMap'] self.write_config() def write_config(self): if self.wiring_map is None or self.bolo_props is None: return config_dic = generate_dfmux_lyrebird_config( self.l_fn, self.wiring_map, self.bolo_props, hostname = self.hostname, hk_hostname = self.hk_hostname, port = self.port, hk_port = self.hk_port, control_host = self.hostname, gcp_get_hk_port = self.get_hk_port, dv_buffer_size = self.dv_buffer_size, min_max_update_interval = self.min_max_update_interval, sub_sampling = self.rendering_sub_sampling, max_framerate = self.max_framerate, mean_decay_factor = self.mean_decay_factor ) write_get_hk_script(self.get_hk_script_name, self.hostname, self.get_hk_port) print("Done writing config file") class IdSerialMapper(object): def __init__(self, wiring_map): self.mp = {} self.mp_inv = {} for k in wiring_map.keys(): wm = wiring_map[k] board_id = get_physical_id(wm.board_serial, wm.crate_serial, wm.board_slot) self.mp[ wm.board_serial ] = board_id self.mp_inv[board_id] = wm.board_serial def get_id(self, serial): return self.mp[serial] def get_serial(self, id): return self.mp_inv[id] ########################### ## Squid display portion ## ########################### def add_timestamp_info(screen, y, x, ts, col_index): s = ts.Description() screen.addstr(y, x, s[:s.rfind('.')], curses.color_pair(col_index)) #need screen geometry and squid list and squid mapping def add_squid_info(screen, y, x, sq_label, sq_label_size, carrier_good, nuller_good, demod_good, temperature_good, voltage_good, max_size, bolometer_good, fir_stage, #routing_good, feedback_on, bolo_label = '', neutral_c = 3, good_c = 2, bad_c = 1): col_map = {True: curses.color_pair(good_c), False: curses.color_pair(bad_c) } current_index = x screen.addstr(y, current_index, sq_label, curses.color_pair(neutral_c)) current_index += sq_label_size screen.addstr(y, current_index, 'C', col_map[carrier_good]) current_index += 1 screen.addstr(y, current_index, 'N', col_map[nuller_good]) current_index += 1 screen.addstr(y, current_index, 'D', col_map[demod_good]) current_index += 1 screen.addstr(y, current_index, 'T', col_map[temperature_good]) current_index += 1 screen.addstr(y, current_index, 'V', col_map[voltage_good]) current_index += 1 screen.addstr(y, current_index, '%d'%fir_stage, col_map[fir_stage == 6]) current_index += 1 #screen.addstr(y, current_index, 'R', col_map[routing_good]) #current_index += 1 screen.addstr(y, current_index, 'F', col_map[feedback_on]) current_index += 1 if (not bolometer_good): screen.addstr(y, current_index, ' '+bolo_label[:(max_size - 7 - sq_label_size )], col_map[False]) def load_squid_info_from_hk( screen, y, x, hk_map, sq_dev_id, sq_label, sq_label_size, max_size, serial_mapper): carrier_good = False nuller_good = False demod_good = False temp_good = False volt_good = False bolometer_good = False full_label = 'NoData' fir_stage = 0 routing_good = False feedback_on = False board_id, mezz_num, module_num = sq_phys_id_to_info(sq_dev_id) board_serial = serial_mapper.get_serial(board_id) #code for loading hk info for display if (not hk_map is None) and board_serial in hk_map: board_info = hk_map[board_serial] mezz_info = hk_map[board_serial].mezz[mezz_num] module_info = hk_map[board_serial].mezz[mezz_num].modules[module_num] fir_stage = int(board_info.fir_stage) routing_good = module_info.routing_type.lower() == 'routing_nul' feedback_on = module_info.squid_feedback.lower() == 'squid_lowpass' carrier_good = not module_info.carrier_railed nuller_good = not module_info.nuller_railed demod_good = not module_info.demod_railed def dic_range_check(dr, dv): for k in dv.keys(): if (not k in dr): continue rng = dr[k] v = dv[k] if v < rng[0] or v > rng[1]: return False return True voltage_range = {'MOTHERBOARD_RAIL_VCC5V5': (5,6), 'MOTHERBOARD_RAIL_VADJ': (2,3), 'MOTHERBOARD_RAIL_VCC3V3': (3,3.6), 'MOTHERBOARD_RAIL_VCC1V0': (0.8, 1.2), 'MOTHERBOARD_RAIL_VCC1V2': (1, 1.5), 'MOTHERBOARD_RAIL_VCC12V0': (11, 13), 'MOTHERBOARD_RAIL_VCC1V8': (1.6, 2), 'MOTHERBOARD_RAIL_VCC1V5': (1.3, 1.7), 'MOTHERBOARD_RAIL_VCC1V0_GTX': (0.7, 1.3)} temp_range = {'MOTHERBOARD_TEMPERATURE_FPGA': (0,80), 'MOTHERBOARD_TEMPERATURE_POWER': (0,80), 'MOTHERBOARD_TEMPERATURE_ARM': (0,80), 'MOTHERBOARD_TEMPERATURE_PHY': (0,80)} #mezz voltages mezz_voltage_range = {'MEZZANINE_RAIL_VCC12V0': (11,13), 'MEZZANINE_RAIL_VADJ': (2,3), 'MEZZANINE_RAIL_VCC3V3': (3,4) } temp_good = dic_range_check( temp_range, board_info.temperatures) volt_good = ( dic_range_check( voltage_range, board_info.voltages) or dic_range_check( mezz_voltage_range, mezz_info.voltages) ) bolometer_good = True bolo_label = '' n_railed = 0 n_diff_freq = 0 n_dan_off = 0 for b in module_info.channels.keys(): chinfo = module_info.channels[b] if (chinfo.dan_railed): n_railed += 1 elif (chinfo.carrier_frequency != chinfo.demod_frequency): n_diff_freq += 1 elif ( (not (chinfo.dan_accumulator_enable and chinfo.dan_feedback_enable and chinfo.dan_streaming_enable ) ) and (chinfo.carrier_frequency > 0 and chinfo.carrier_amplitude > 0) ): n_dan_off += 1 bolometer_good = not (n_railed or n_diff_freq or n_dan_off) if not bolometer_good: if n_railed: full_label = "DanRail:%s"%(n_railed) elif n_diff_freq: full_label = "CDDiffFreq:%s"%(n_diff_freq) elif n_dan_off: full_label = "DanOff:%s"%(n_dan_off) else: full_label = '' add_squid_info(screen, y, x, sq_label, sq_label_size, carrier_good, nuller_good, demod_good, temp_good, volt_good, max_size, bolometer_good, fir_stage, #routing_good, feedback_on, bolo_label = full_label, ) def GetHousekeepingMessenger(frame, hostname, port): if frame.type == core.G3FrameType.Wiring: os.system( "nc %s %d" % (hostname, port) ) class SquidDisplay(object): def __init__(self, squids_per_col = 32, squid_col_width = 30): self.squids_list = None self.squids_per_col = squids_per_col self.squid_col_width = squid_col_width self.serial_mapper = None self.str_id_lst = [" Carrier", " Nuller", " Demod", " Temp", " Voltage", " fir#", " squid Feedback" ] self.highlight_index = [7 for s in self.str_id_lst] def init_squids(self, squids_list) : self.n_squids = len(squids_list) + len(self.str_id_lst) + 1 self.squids_list = squids_list self.sq_label_size = max(map(len, squids_list)) + 3 ncols = int(math.ceil(float(self.n_squids)/self.squids_per_col)) self.screen_size_x = ncols * self.squid_col_width self.screen_size_y = self.squids_per_col + 2 self.pos_map = {} #assign an x, y location to each squid for j, sq in enumerate(sorted(squids_list, key=cmp_to_key(str_cmp_with_numbers_sorted))): i = j + len(self.str_id_lst) + 1 y = i % self.squids_per_col + 1 x = 1 + self.squid_col_width * ( i // self.squids_per_col) self.pos_map[sq] = (x,y) self.stdscr = curses.initscr() curses.start_color() # Turn off echoing of keys, and enter cbreak mode, # where no buffering is performed on keyboard input curses.noecho() curses.cbreak() curses.curs_set(0) curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_WHITE) self.stdscr.clear() signal.signal(signal.SIGWINCH, signal.SIG_IGN) def __call__(self, frame): if frame.type == core.G3FrameType.Wiring: wiring_map = frame['WiringMap'] squid_ids = [] for k in wiring_map.keys(): wm = wiring_map[k] squid_ids.append( get_physical_id(wm.board_serial, wm.crate_serial, wm.board_slot, wm.module + 1) ) squid_ids = uniquifyList(squid_ids) self.init_squids(squid_ids) self.serial_mapper = IdSerialMapper(frame['WiringMap']) elif frame.type == core.G3FrameType.Housekeeping: if self.squids_list is None: return #do update if not frame is None: hk_data = frame['DfMuxHousekeeping'] else: hk_data = None self.stdscr.clear() y, x = self.stdscr.getmaxyx() if y < self.screen_size_y or x < self.screen_size_x: screen = self.stdscr.subwin(0, x, 0, 0) screen.addstr(0,0, 'Terminal is too small %d %d'%(y,x), curses.color_pair(1)) screen.refresh() return screen = self.stdscr.subwin(0, self.screen_size_x, 0, 0) screen.clear() #screen.box() #CNDTV6F if not hk_data is None: add_timestamp_info(screen, 0,2, hk_data[hk_data.keys()[0]].timestamp, 5) for i, s in enumerate(self.str_id_lst): offset = 4 screen.addstr(i+1, offset, s, curses.color_pair(2)) screen.addstr(i+1, offset + self.highlight_index[i], s[self.highlight_index[i]], curses.color_pair(3)) screen.hline(len(self.str_id_lst) + 1, 0, '-', self.squid_col_width) screen.vline(0, self.squid_col_width-1, '|', len(self.str_id_lst)+1) for i, s in enumerate(self.squids_list): p = self.pos_map[s] load_squid_info_from_hk( screen, p[1], p[0], hk_data, s, s, self.sq_label_size, self.squid_col_width, self.serial_mapper) screen.refresh() elif frame.type == core.G3FrameType.EndProcessing: if not self.squids_list is None: self.stdscr.keypad(0) curses.echo() curses.nocbreak() curses.endwin() if __name__=='__main__': parser = argparse.ArgumentParser() parser.add_argument('hostname') parser.add_argument('--port',type=int, default=8675) parser.add_argument('--local_ts_port',type=int, default=8676) parser.add_argument('--local_hk_port',type=int, default=8677) parser.add_argument('--gcp_signalled_hk_port', type=int, default=50011) parser.add_argument('--lyrebird_output_file', default = 'lyrebird_config_file.json') parser.add_argument('--get_hk_script', default = 'get_hk.sh') parser.add_argument('--timestream_buffer_size',type=int, default=1024) parser.add_argument('--min_max_update_interval', type=int, default = 300) parser.add_argument('--rendering_sub_sampling', type=int, default = 2) parser.add_argument('--max_framerate', type=int, default = 60) parser.add_argument("--mean_decay_factor", type = float, default = 0.01, help = "The mean filtered power has an exponential convolution form to the filter. It has a value in (0,1) exclusive. Increasing the value decreases the size of the exponential to it pushes the frequency of the HPF lower. Numbers close to one filter things very rapidly, close to 0 very slowly.") parser.add_argument('--debug_mode', action='store_true', help = "prevents the spawning on the curses display") parser.add_argument('--debug_logs', action='store_true', help = "store logs of stderr/out") parser.add_argument('--ignore_nominal_bias_props', action='store_true', help = "will align the bolometers into a grid") args = parser.parse_args() #core.set_log_level(core.G3LogLevel.LOG_DEBUG) script_path = os.path.dirname(os.path.realpath(__file__)) script_path = script_path + '/../bin/' lyrebird_output_file = script_path + args.lyrebird_output_file get_hk_script = script_path + args.get_hk_script pipe = core.G3Pipeline() pipe.Add(core.G3NetworkReceiver, hostname = args.hostname, port = args.port) if args.ignore_nominal_bias_props: pipe.Add(lambda fr: fr.type != core.G3FrameType.Calibration) pipe.Add(BoloPropertiesFaker) pipe.Add(AddVbiasAndCurrentConv) pipe.Add(BirdConfigGenerator, lyrebird_output_file = lyrebird_output_file, hostname = args.hostname, get_hk_script_name = get_hk_script, hk_hostname = '127.0.0.1', port = args.local_ts_port, hk_port = args.local_hk_port, get_hk_port = args.gcp_signalled_hk_port, dv_buffer_size = args.timestream_buffer_size, min_max_update_interval = args.min_max_update_interval, rendering_sub_sampling = args.rendering_sub_sampling, max_framerate = args.max_framerate, mean_decay_factor = args.mean_decay_factor ) pipe.Add(GetHousekeepingMessenger, hostname = args.hostname, port = args.gcp_signalled_hk_port) pipe.Add(core.G3ThrottledNetworkSender, hostname = '*', port = args.local_hk_port, frame_decimation = {core.G3FrameType.Timepoint: 10} ) pipe.Add(core.G3ThrottledNetworkSender, hostname = '*', port = args.local_ts_port, frame_decimation = {core.G3FrameType.Housekeeping: 0} ) if args.debug_logs: import sys sys.stderr = open('kookaburra_stderr.txt', 'w') sys.stdout = open('kookaburra_stdout.txt', 'w') if args.debug_mode: pipe.Add(core.Dump) pipe.Run() else: pipe.Add(SquidDisplay) try: pipe.Run() finally: traceback.print_exc() # Print the exception curses.curs_set(1) curses.echo() curses.nocbreak() curses.endwin()
37.401504
323
0.56051
[ "BSD-2-Clause" ]
simonsobs/lyrebird
bin/kookaburra.py
24,872
Python
import os from spirl.models.closed_loop_spirl_mdl import GoalClSPiRLMdl from spirl.components.logger import Logger from spirl.utils.general_utils import AttrDict from spirl.configs.default_data_configs.kitchen import data_spec from spirl.components.evaluator import TopOfNSequenceEvaluator from spirl.data.kitchen.src.kitchen_data_loader import KitchenStateSeqDataset current_dir = os.path.dirname(os.path.realpath(__file__)) fewshot_dataset = KitchenStateSeqDataset( data_path='data/kitchen/kitchen-demo-topknob_bottomknob_hinge_slide.hdf5', num_demo=1, subseq_len=10, ) env = AttrDict( task_list = ['top burner', 'bottom burner', 'hinge cabinet', 'slide cabinet'] ) contra_model_cf = AttrDict( state_dimension=data_spec.state_dim, hidden_size=128, feature_size=32, ) configuration = { 'model': GoalClSPiRLMdl, 'logger': Logger, 'data_dir': '.', 'epoch_cycles_train': 1, 'evaluator': TopOfNSequenceEvaluator, 'top_of_n_eval': 100, 'top_comp_metric': 'mse', 'batch_size': 128, 'num_epochs': 50, 'fewshot_data': fewshot_dataset, 'fewshot_batch_size': 128, 'contra_config': contra_model_cf, 'contra_ckpt': './experiments/contrastive/kitchen/exact-mixed-all/exact_model.pt', 'finetune_vae': True, } configuration = AttrDict(configuration) model_config = AttrDict( state_dim=data_spec.state_dim, action_dim=data_spec.n_actions, n_rollout_steps=10, kl_div_weight=5e-4, nz_enc=128, nz_mid=128, n_processing_layers=5, cond_decode=True, checkpt_path=f'{os.environ["EXP_DIR"]}/skill_prior_learning/kitchen/hierarchical_cl_gc_top_bot_excluded' ) # Dataset data_config = AttrDict() data_config.dataset_spec = data_spec data_config.dataset_spec['dataset_path'] = './data/kitchen/kitchen-mixed-top-bot-excluded.hdf5' data_config.dataset_spec.subseq_len = model_config.n_rollout_steps + 1 # flat last action from seq gets cropped
30.873016
112
0.759897
[ "BSD-3-Clause" ]
kouroshHakha/fist
spirl/configs/few_shot_imitation_learning/kitchen/hierarchical_cl_gc_top_bot_excluded_demo_topknob_bot_hinge_slide_oneshot/conf.py
1,945
Python
""" Script for copying back xml junit files from tests """ import argparse # pylint: disable=minimum-python-version import os import subprocess import paramiko import salt.utils.yaml class DownloadArtifacts: def __init__(self, instance, artifacts): self.instance = instance self.artifacts = artifacts self.transport = self.setup_transport() self.sftpclient = paramiko.SFTPClient.from_transport(self.transport) def setup_transport(self): # pylint: disable=minimum-python-version config = salt.utils.yaml.safe_load( subprocess.check_output( ["bundle", "exec", "kitchen", "diagnose", self.instance] ) ) # pylint: enable=minimum-python-version state = config["instances"][self.instance]["state_file"] tport = config["instances"][self.instance]["transport"] transport = paramiko.Transport( (state["hostname"], state.get("port", tport.get("port", 22))) ) pkey = paramiko.rsakey.RSAKey( filename=state.get("ssh_key", tport.get("ssh_key", "~/.ssh/id_rsa")) ) transport.connect( username=state.get("username", tport.get("username", "root")), pkey=pkey ) return transport def _set_permissions(self): """ Make sure all xml files are readable by the world so that anyone can grab them """ for remote, _ in self.artifacts: self.transport.open_session().exec_command( "sudo chmod -R +r {}".format(remote) ) def download(self): self._set_permissions() for remote, local in self.artifacts: if remote.endswith("/"): for fxml in self.sftpclient.listdir(remote): self._do_download( os.path.join(remote, fxml), os.path.join(local, os.path.basename(fxml)), ) else: self._do_download(remote, os.path.join(local, os.path.basename(remote))) def _do_download(self, remote, local): print("Copying from {} to {}".format(remote, local)) try: self.sftpclient.get(remote, local) except OSError: print("Failed to copy: {}".format(remote)) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Jenkins Artifact Download Helper") parser.add_argument( "--instance", required=True, action="store", help="Instance on Test Kitchen to pull from", ) parser.add_argument( "--download-artifacts", dest="artifacts", nargs=2, action="append", metavar=("REMOTE_PATH", "LOCAL_PATH"), help="Download remote artifacts", ) args = parser.parse_args() downloader = DownloadArtifacts(args.instance, args.artifacts) downloader.download()
33.033708
88
0.593537
[ "Apache-2.0" ]
0x416e746f6e/salt
tests/support/copyartifacts.py
2,940
Python
#!/usr/bin/env python """pattern.py: An example like <Rolling an image> in Pillow document. """ import os.path from PIL import Image def run(filepath): """Create a wallpaper image from a PNG file.""" src = Image.open(filepath) target = swap_quadrants(src) paste_with_alpha(target, src, (0, 0), 0x10) return target def swap_quadrants(img): """Quarter the image and swap two diagonal quadrant pairs.""" boxes = quarter_bbox(img) regions = [img.crop(box) for box in boxes] target = img.copy() paste_with_alpha(target, regions[3], (0, 0), 0x80) paste_with_alpha(target, regions[2], (regions[3].size[0], 0), 0x80) paste_with_alpha(target, regions[1], (0, regions[3].size[1]), 0x80) paste_with_alpha(target, regions[0], regions[3].size, 0x80) return target def paste_with_alpha(target, source, left_upper, opacity): """An alpha_composite-like operation.""" mask = Image.new('L', source.size, opacity) target.paste(source, left_upper, mask=mask) def quarter_bbox(img): """Quarter the bounding box of an image.""" (left, upper, right, bottom) = img.getbbox() xmid = (left + right - 1) // 2 ymid = (upper + bottom - 1) // 2 # Z return [ (left, upper, xmid, ymid), (xmid + 1, upper, right, ymid), (left, ymid + 1, xmid, bottom), (xmid + 1, ymid + 1, right, bottom),] if __name__ == '__main__': result = run(os.path.join( os.path.dirname(__file__), '../../_images/illvelo.png')) result.show()
28.943396
71
0.632334
[ "MIT" ]
showa-yojyo/note
source/_sample/pillow/pattern.py
1,534
Python
from rest_framework.permissions import BasePermission, SAFE_METHODS class IsOwnerOrReadOnly(BasePermission): message = 'You must be the owner of this object.' def has_object_permission(self, request, view, obj): # member = Membership.objects.get(user=user.request) # member.is_active if request.method in SAFE_METHODS: return True return obj.user == request.user
37.818182
67
0.706731
[ "MIT" ]
imran110219/Book_Review_App
Book/api/permissions.py
416
Python
"""View representations of Product Active docs pages""" from widgetastic_patternfly4 import PatternflyTable from widgetastic.widget import View, Text from testsuite.ui.views.admin.product import BaseProductView from testsuite.ui.widgets.buttons import ThreescaleDeleteButton, ThreescaleEditButton from testsuite.ui.widgets import ActiveDocV2Section, ActiveDocV3Section from testsuite.ui.navigation import step class ActiveDocsView(BaseProductView): """View representation of Active Docs list page""" path_pattern = '/apiconfig/services/{product_id}/api_docs' active_docs_table = PatternflyTable(locator="//*[@id='content']/table") @step("ActiveDocsDetailView") def detail(self, active_doc): """Navigate to active doc detail/preview page""" self.active_docs_table.row(name=active_doc["name"]).name.click() def prerequisite(self): return BaseProductView @property def is_displayed(self): return BaseProductView.is_displayed.fget(self) and self.active_docs_table.is_displayed and \ self.path in self.browser.url class ActiveDocsDetailView(BaseProductView): """View representation of Active Docs Detail page""" path_pattern = '/apiconfig/services/{product_id}/api_docs/{active_doc_id}/preview' delete_btn = ThreescaleDeleteButton() edit_btn = ThreescaleEditButton() def __init__(self, parent, product, active_doc): super().__init__(parent, product, active_doc_id=active_doc.entity_id) @View.nested # pylint: disable=invalid-name class oas2(View): """OAS version 2 section""" expand_operations_link = Text(locator="//*[contains(@class, 'expandResource')]") collapse_operations_link = Text(locator="//*[contains(@class, 'collapseResource')]") active_docs_section = ActiveDocV2Section() def make_request(self, endpoint): """ Make request on preview page :param endpoint: string of endpoint which should be tried :return: """ self.expand_operations_link.click() self.active_docs_section.try_it_out(endpoint) @View.nested # pylint: disable=invalid-name class oas3(View): """OAS version 3 section""" active_docs_section = ActiveDocV3Section() server = Text("//label[@for='servers']/select/option") def make_request(self, method, path, key): """ Make request on preview page :param path string eg. /post, /get :param method string eg. GET, POST :param key string name of application :return: """ self.active_docs_section.try_it_out(method, path, key) def prerequisite(self): return ActiveDocsView @property def is_displayed(self): return BaseProductView.is_displayed.fget(self) and self.edit_btn.is_displayed and \ self.delete_btn.is_displayed and self.path in self.browser.url
37.6
100
0.683178
[ "Apache-2.0" ]
3scale-qe/3scale-tests
testsuite/ui/views/admin/product/active_docs.py
3,008
Python
import os import json import logging import serial from serial.tools import list_ports import time CONFIG_FILENAME_DEFAULT = 'olfa_config.json' def get_olfa_config(config_filename=''): """ Find and parse olfactometer configuration JSON. :param config_filename: string with path to configuration. :return: returns a tuple with (config_fn, config_dict) :rtype: tuple """ if not config_filename: logging.info("No olfa config file specified, looking for default in OLFA_CONFIG os variable") config_filename = os.environ.get("OLFA_CONFIG") #if it didnt find it there, it tries the legacy default if not config_filename: config_filename = CONFIG_FILENAME_DEFAULT logging.info("No OLFA_CONFIG os variable, trying with legacy default " + CONFIG_FILENAME_DEFAULT) if os.path.exists(config_filename): with open(config_filename) as f: config = json.load(f) else: raise Exception('No olfactometer configuration file found at {0}'.format(config_filename)) return config_filename, config def flatten_dictionary(dictionary, separator=':', flattened_dict=None, parent_string=''): """ Flattens nested dictionary into a single dictionary: {'hello': {'world': 1, 'moon': 2}} becomes: {'hello:world': 1, 'hello:moon': 2} Uses recursion to flatten as many layers as exist in your dictionary. :param dictionary: nested dictionary you wish to flatten. :param flattened_dict: (used for recursion) current flattened dictionary to add to :param parent_string: (used for recursion) current key string to use as prefix for :return: flattened dictionary :type dictionary: dict :type flattened_dict: dict :type parent_string: str :rtype: dict """ if flattened_dict is None: # dicts are mutable, so we shouldn't use a dict as the default argument!!! flattened_dict = {} # instead, redeclare an empty dictionary here. for k, v in dictionary.items(): if parent_string: full_key = "{0}{1}{2}".format(parent_string, separator, k) else: full_key = k if isinstance(v, dict): # use recursion to flatten and add nested dictionaries to the product. _ = flatten_dictionary(v, flattened_dict=flattened_dict, parent_string=full_key) else: flattened_dict[full_key] = v return flattened_dict def connect_serial(port, baudrate=115200, timeout=1, writeTimeout=1): """ Return Serial object after making sure that the port is accessible and that the port is expressed as a string. :param port: str or int (ie "COM4" or 4 for Windows). :param baudrate: baudrate. :param timeout: read timeout in seconds, default 1 sec. :param writeTimeout: write timeout in seconds, default 1 sec. :return: serial port object. :rtype: serial.Serial """ if isinstance(port, int): port = "COM{0}".format(port) names_list = list() for i in list_ports.comports(): names_list.append(i[0]) if port not in names_list: print(("Serial not found on {0}.".format(port))) print('Listing current serial ports with devices:') for ser in list_ports.comports(): ser_str = '\t{0}: {1}'.format(ser[0], ser[1]) print(ser_str) time.sleep(.01) # just to let the above lines print before the exemption is raised. cleans console output. raise serial.SerialException('Requested COM port: {0} is not listed as connected.'.format(port)) else: return serial.Serial(port, baudrate=baudrate, timeout=timeout, writeTimeout=writeTimeout) class OlfaException(Exception): pass
36.921569
115
0.674456
[ "MIT" ]
mohamedelgohary1/PyBpodGUI
olfactometry/utils.py
3,766
Python
# 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. """ Parser package. """ from .specification import implements_specification, iter_specifications MODULES = ( 'consumption', 'loading', 'modeling', 'presentation', 'reading', 'validation') __all__ = ( 'MODULES', 'implements_specification', 'iter_specifications')
30.971429
74
0.74262
[ "Apache-2.0" ]
enricorusso/incubator-ariatosca
aria/parser/__init__.py
1,084
Python
import os, sys CHOICES = 'ignore', 'fail', 'warn', 'warn_once' DEFAULT = 'warn_once' ACTION = None HELP = """ Specify what to do when a project uses deprecated features: ignore: do nothing warn: print warning messages for each feature warn_once: print a warning message, but only once for each type of feature fail: throw an exception """ DEPRECATED = set() FLAG = '--deprecated' V4_FLAG = '--v4' ENVIRONMENT_VARIABLE = 'BP_DEPRECATED' V4_HELP = """\ Run BiblioPixel in v4 compatibility mode, to see if it will work with future releases v4.x """ def add_arguments(parser): parser.add_argument(V4_FLAG, action='store_true', help=V4_HELP) def allowed(): _compute_action() return ACTION != 'fail' def deprecated(msg, *args, **kwds): _compute_action() if ACTION == 'ignore': return if ACTION == 'warn_once' and msg in DEPRECATED: return formatted = msg.format(*args, **kwds) if ACTION == 'fail': raise ValueError(formatted) DEPRECATED.add(msg) from . import log log.warning(formatted) def _compute_action(): global ACTION if ACTION: return if FLAG in sys.argv: raise ValueError('%s needs an argument (one of %s)' % (FLAG, ', '.join(CHOICES))) if V4_FLAG in sys.argv: ACTION = 'fail' d = [i for i, v in enumerate(sys.argv) if v.startswith(FLAG + '=')] if len(d) > 1: raise ValueError('Only one %s argument can be used' % FLAG) if not d: ACTION = os.getenv(ENVIRONMENT_VARIABLE, ACTION or DEFAULT) else: arg = sys.argv.pop(d[0]) _, *rest = arg.split('=') if len(rest) > 1: raise ValueError('Extra = in flag %s' % arg) if not (rest and rest[0].strip()): raise ValueError('%s needs an argument (one of %s)' % (FLAG, ', '.join(CHOICES))) ACTION = rest[0] if ACTION not in CHOICES: ACTION = None raise ValueError('Unknown deprecation value (must be one of %s)' % ', '.join(CHOICES))
23.696629
76
0.598388
[ "MIT" ]
8cH9azbsFifZ/BiblioPixel
bibliopixel/util/deprecated.py
2,109
Python
#!/usr/bin/env python ''' Created on Apr 12, 2017 @author: Brian Jimenez-Garcia @contact: [email protected] ''' import sys import os if len(sys.argv[1:]) != 2: raise SystemExit("usage: %s pdb_file1 pdb_file2" % os.path.basename(sys.argv[0])) pdb_file1 = sys.argv[1] pdb_file2 = sys.argv[2] # Panda3D imports from pandac.PandaModules import loadPrcFileData from emol import EMol width = 1400 height = 900 # Change window properties loadPrcFileData("", "window-title Energy Visualizer") loadPrcFileData("", "fullscreen 0") loadPrcFileData("", "win-size %s %s" % (width, height)) from direct.showbase.ShowBase import ShowBase base = ShowBase() # Set up a loading screen from direct.gui.OnscreenText import OnscreenText,TextNode loadingText=OnscreenText("Loading molecules...",1,fg=(1,1,1,1), pos=(0,0),align=TextNode.ACenter, scale=.07,mayChange=1) # Render three frames to avoid black screen base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() # Load the game visualizer = EMol(width, height, pdb_file1, pdb_file2) # Hide loading loadingText.cleanup() base.run()
23.196078
85
0.715976
[ "MIT" ]
brianjimenez/emol
launch.py
1,183
Python
# (c) Copyright [2018-2021] Micro Focus or one of its affiliates. # 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. # # |_ |~) _ _| _ /~\ _ |. # |_)\/ |_)(_|(_|| \_/|_|(_||| # / # ____________ ______ # / __ `\ / / # | \/ / / / # |______ / / / # |____/ / / # _____________ / / # \ / / / # \ / / / # \_______/ / / # ______ / / # \ / / / # \ / / / # \/ / / # / / # / / # \ / # \ / # \/ # _ # \ / _ __|_. _ _ |_) # \/ (/_| | |(_(_|| \/ # / # VerticaPy is a Python library with scikit-like functionality to use to conduct # data science projects on data stored in Vertica, taking advantage Vertica’s # speed and built-in analytics and machine learning features. It supports the # entire data science life cycle, uses a ‘pipeline’ mechanism to sequentialize # data transformation operations, and offers beautiful graphical options. # # VerticaPy aims to solve all of these problems. The idea is simple: instead # of moving data around for processing, VerticaPy brings the logic to the data. # # # Modules # # Standard Python Modules import math, warnings from typing import Union # VerticaPy Modules from verticapy.learn.vmodel import * from verticapy.learn.linear_model import LinearRegression from verticapy import vDataFrame from verticapy.plot import gen_colors from verticapy.learn.tools import * # Other Python Modules from dateutil.parser import parse import matplotlib.pyplot as plt # ---# class SARIMAX(Regressor): """ --------------------------------------------------------------------------- [Beta Version] Creates an SARIMAX object using the Vertica Linear Regression algorithm on the data. Parameters ---------- name: str Name of the the model. The model will be stored in the DB. cursor: DBcursor, optional Vertica database cursor. p: int, optional Order of the AR (Auto-Regressive) part. d: int, optional Order of the I (Integrated) part. q: int, optional Order of the MA (Moving-Average) part. P: int, optional Order of the seasonal AR (Auto-Regressive) part. D: int, optional Order of the seasonal I (Integrated) part. Q: int, optional Order of the seasonal MA (Moving-Average) part. s: int, optional Span of the seasonality. tol: float, optional Determines whether the algorithm has reached the specified accuracy result. max_iter: int, optional Determines the maximum number of iterations the algorithm performs before achieving the specified accuracy result. solver: str, optional The optimizer method to use to train the model. Newton : Newton Method BFGS : Broyden Fletcher Goldfarb Shanno max_pik: int, optional Number of inverse MA coefficient used to approximate the MA. papprox_ma: int, optional the p of the AR(p) used to approximate the MA coefficients. """ def __init__( self, name: str, cursor=None, p: int = 0, d: int = 0, q: int = 0, P: int = 0, D: int = 0, Q: int = 0, s: int = 0, tol: float = 1e-4, max_iter: int = 1000, solver: str = "Newton", max_pik: int = 100, papprox_ma: int = 200, ): check_types([("name", name, [str],)]) self.type, self.name = "SARIMAX", name self.set_params( { "p": p, "d": d, "q": q, "P": P, "D": D, "Q": Q, "s": s, "tol": tol, "max_iter": max_iter, "solver": solver, "max_pik": max_pik, "papprox_ma": papprox_ma, } ) if self.parameters["s"] == 0: assert ( self.parameters["D"] == 0 and self.parameters["P"] == 0 and self.parameters["Q"] == 0 ), ParameterError( "In case of non-seasonality (s = 0), all the parameters P, D or Q must be equal to 0." ) else: assert ( self.parameters["D"] > 0 or self.parameters["P"] > 0 or self.parameters["Q"] > 0 ), ParameterError( "In case of seasonality (s > 0), at least one of the parameters P, D or Q must be strictly greater than 0." ) cursor = check_cursor(cursor)[0] self.cursor = cursor version(cursor=cursor, condition=[8, 0, 0]) # ---# def deploySQL(self): """ --------------------------------------------------------------------------- Returns the SQL code needed to deploy the model. Returns ------- str the SQL code needed to deploy the model. """ sql = self.deploy_predict_ if (self.parameters["d"] > 0) or ( self.parameters["D"] > 0 and self.parameters["s"] > 0 ): for i in range(0, self.parameters["d"] + 1): for k in range( 0, max((self.parameters["D"] + 1) * min(1, self.parameters["s"]), 1) ): if (k, i) != (0, 0): comb_i_d = ( math.factorial(self.parameters["d"]) / math.factorial(self.parameters["d"] - i) / math.factorial(i) ) comb_k_D = ( math.factorial(self.parameters["D"]) / math.factorial(self.parameters["D"] - k) / math.factorial(k) ) sql += " + {} * LAG(VerticaPy_y_copy, {}) OVER (ORDER BY [VerticaPy_ts])".format( (-1) ** (i + k + 1) * comb_i_d * comb_k_D, i + self.parameters["s"] * k, ) return sql # ---# def fpredict(self, L: list): """ --------------------------------------------------------------------------- Computes the prediction. Parameters ---------- L: list List containing the data. It must be a two-dimensional list containing multiple rows. Each row must include as first element the ordered predictor and as nth elements the nth - 1 exogenous variable (nth > 2). Returns ------- float the prediction. """ def sub_arp(L: list): L_final = [] for i in range(len(L)): result = L[-i] for i in range(len(self.coef_.values["coefficient"])): elem = self.coef_.values["predictor"][i] if elem.lower() == "intercept": result -= self.coef_.values["coefficient"][i] elif elem.lower()[0:2] == "ar": nb = int(elem[2:]) try: result -= self.coef_.values["coefficient"][i] * L[-nb] except: result = None L_final = [result] + L_final return L_final def fepsilon(L: list): if self.parameters["p"] > 0 or self.parameters["P"] > 0: L_tmp = sub_arp(L) else: L_tmp = L try: result = L_tmp[-1] - self.ma_avg_ for i in range(1, self.parameters["max_pik"]): result -= self.ma_piq_.values["coefficient"][i] * ( L_tmp[-i] - self.ma_avg_ ) return result except: return 0 if ( self.parameters["p"] == 0 and self.parameters["q"] == 0 and self.parameters["d"] == 0 and self.parameters["s"] == 0 and not (self.exogenous) ): return self.ma_avg_ try: yt = [elem[0] for elem in L] yt_copy = [elem[0] for elem in L] yt.reverse() if self.parameters["d"] > 0: for i in range(self.parameters["d"]): yt = [yt[i - 1] - yt[i] for i in range(1, len(yt))] if self.parameters["D"] > 0 and self.parameters["s"] > 0: for i in range(self.parameters["D"]): yt = [ yt[i - self.parameters["s"]] - yt[i] for i in range(self.parameters["s"], len(yt)) ] yt.reverse() result, j = 0, 1 for i in range(len(self.coef_.values["coefficient"])): elem = self.coef_.values["predictor"][i] if elem.lower() == "intercept": result += self.coef_.values["coefficient"][i] elif elem.lower()[0:2] == "ar": nb = int(elem[2:]) result += self.coef_.values["coefficient"][i] * yt[-nb] elif elem.lower()[0:2] == "ma": nb = int(elem[2:]) result += self.coef_.values["coefficient"][i] * fepsilon( yt[: -nb - 1] ) else: result += self.coef_.values["coefficient"][i] * L[-1][j] j += 1 for i in range(0, self.parameters["d"] + 1): for k in range( 0, max((self.parameters["D"] + 1) * min(1, self.parameters["s"]), 1) ): if (k, i) != (0, 0): comb_i_d = ( math.factorial(self.parameters["d"]) / math.factorial(self.parameters["d"] - i) / math.factorial(i) ) comb_k_D = ( math.factorial(self.parameters["D"]) / math.factorial(self.parameters["D"] - k) / math.factorial(k) ) result += ( (-1) ** (i + k + 1) * comb_i_d * comb_k_D * yt_copy[-(i + self.parameters["s"] * k)] ) return result except: return None # ---# def fit( self, input_relation: Union[vDataFrame, str], y: str, ts: str, X: list = [], test_relation: Union[vDataFrame, str] = "", ): """ --------------------------------------------------------------------------- Trains the model. Parameters ---------- input_relation: str/vDataFrame Training relation. y: str Response column. ts: str vcolumn used to order the data. X: list, optional exogenous columns used to fit the model. test_relation: str/vDataFrame, optional Relation used to test the model. Returns ------- object model """ check_types( [ ("input_relation", input_relation, [str, vDataFrame],), ("y", y, [str],), ("test_relation", test_relation, [str, vDataFrame],), ("ts", ts, [str],), ] ) self.cursor = check_cursor(self.cursor, input_relation, True)[0] # Initialization does_model_exist(name=self.name, cursor=self.cursor, raise_error=True) self.input_relation = ( input_relation if isinstance(input_relation, str) else input_relation.__genSQL__() ) if isinstance(test_relation, vDataFrame): self.test_relation = test_relation.__genSQL__() elif test_relation: self.test_relation = test_relation else: self.test_relation = self.input_relation self.y, self.ts, self.deploy_predict_ = str_column(y), str_column(ts), "" self.coef_ = tablesample({"predictor": [], "coefficient": []}) self.ma_avg_, self.ma_piq_ = None, None X, schema = [str_column(elem) for elem in X], schema_relation(self.name)[0] self.X, self.exogenous = [], X relation = ( "(SELECT *, [VerticaPy_y] AS VerticaPy_y_copy FROM {}) VERTICAPY_SUBTABLE " ) model = LinearRegression( name=self.name, solver=self.parameters["solver"], max_iter=self.parameters["max_iter"], tol=self.parameters["tol"], ) if ( self.parameters["p"] == 0 and self.parameters["q"] == 0 and self.parameters["d"] == 0 and self.parameters["s"] == 0 and not (self.exogenous) ): query = "SELECT AVG({}) FROM {}".format(self.y, self.input_relation) self.ma_avg_ = self.cursor.execute(query).fetchone()[0] self.deploy_predict_ = str(self.ma_avg_) # I(d) if self.parameters["d"] > 0: for i in range(self.parameters["d"]): relation = "(SELECT [VerticaPy_y] - LAG([VerticaPy_y], 1) OVER (ORDER BY [VerticaPy_ts]) AS [VerticaPy_y], VerticaPy_y_copy[VerticaPy_key_columns] FROM {}) VERTICAPY_SUBTABLE".format( relation ) if self.parameters["D"] > 0 and self.parameters["s"] > 0: for i in range(self.parameters["D"]): relation = "(SELECT [VerticaPy_y] - LAG([VerticaPy_y], {}) OVER (ORDER BY [VerticaPy_ts]) AS [VerticaPy_y], VerticaPy_y_copy[VerticaPy_key_columns] FROM {}) VERTICAPY_SUBTABLE".format( self.parameters["s"], relation ) def drop_temp_elem(self, schema): try: with warnings.catch_warnings(record=True) as w: drop( "{}.VERTICAPY_TEMP_MODEL_LINEAR_REGRESSION_VIEW_{}".format( schema, get_session(self.cursor) ), cursor=self.cursor, method="view", ) except: pass # AR(p) if self.parameters["p"] > 0 or self.parameters["P"] > 0: columns = [ "LAG([VerticaPy_y], {}) OVER (ORDER BY [VerticaPy_ts]) AS AR{}".format( i, i ) for i in range(1, self.parameters["p"] + 1) ] AR = ["AR{}".format(i) for i in range(1, self.parameters["p"] + 1)] if self.parameters["s"] > 0: for i in range(1, self.parameters["P"] + 1): if (i * self.parameters["s"]) not in ( range(1, self.parameters["p"] + 1) ): columns += [ "LAG([VerticaPy_y], {}) OVER (ORDER BY [VerticaPy_ts]) AS AR{}".format( i * self.parameters["s"], i * self.parameters["s"] ) ] AR += ["AR{}".format(i * self.parameters["s"])] relation = "(SELECT *, {} FROM {}) VERTICAPY_SUBTABLE".format( ", ".join(columns), relation ) drop_temp_elem(self, schema) query = "CREATE VIEW {}.VERTICAPY_TEMP_MODEL_LINEAR_REGRESSION_VIEW_{} AS SELECT * FROM {}".format( schema, get_session(self.cursor), relation.format(self.input_relation) .replace("[VerticaPy_ts]", self.ts) .replace("[VerticaPy_y]", self.y) .replace("[VerticaPy_key_columns]", ", " + ", ".join([self.ts] + X)), ) try: self.cursor.execute(query) self.X += AR + X model.fit( input_relation="{}.VERTICAPY_TEMP_MODEL_LINEAR_REGRESSION_VIEW_{}".format( schema, get_session(self.cursor) ), X=self.X, y=self.y, ) except: drop_temp_elem(self, schema) raise drop_temp_elem(self, schema) self.coef_.values["predictor"] = model.coef_.values["predictor"] self.coef_.values["coefficient"] = model.coef_.values["coefficient"] alphaq = model.coef_.values["coefficient"] model.drop() epsilon_final = ( "[VerticaPy_y] - " + str(alphaq[0]) + " - " + " - ".join( [ str(alphaq[i]) + " * " + "LAG([VerticaPy_y], {}) OVER (ORDER BY [VerticaPy_ts])".format( i ) for i in range(1, self.parameters["p"] + 1) ] ) ) self.deploy_predict_ = ( str(alphaq[0]) + " + " + " + ".join( [ str(alphaq[i]) + " * " + "LAG(VerticaPy_y_copy, {}) OVER (ORDER BY [VerticaPy_ts])".format( i ) for i in range(1, self.parameters["p"] + 1) ] ) ) if self.parameters["s"] > 0 and self.parameters["P"] > 0: epsilon_final += " - " + " - ".join( [ str(alphaq[i]) + " * " + "LAG([VerticaPy_y], {}) OVER (ORDER BY [VerticaPy_ts])".format( i * self.parameters["s"] ) for i in range( self.parameters["p"] + 1, self.parameters["p"] + (self.parameters["P"] if self.parameters["s"] > 0 else 0) + 1, ) ] ) self.deploy_predict_ += " + " + " + ".join( [ str(alphaq[i]) + " * " + "LAG(VerticaPy_y_copy, {}) OVER (ORDER BY [VerticaPy_ts])".format( i * self.parameters["s"] ) for i in range( self.parameters["p"] + 1, self.parameters["p"] + (self.parameters["P"] if self.parameters["s"] > 0 else 0) + 1, ) ] ) for idx, elem in enumerate(X): epsilon_final += " - {} * [X{}]".format( alphaq[ idx + self.parameters["p"] + (self.parameters["P"] if self.parameters["s"] > 0 else 0) + 1 ], idx, ) self.deploy_predict_ += " + {} * [X{}]".format( alphaq[ idx + self.parameters["p"] + (self.parameters["P"] if self.parameters["s"] > 0 else 0) + 1 ], idx, ) relation = "(SELECT {} AS [VerticaPy_y], {}, VerticaPy_y_copy[VerticaPy_key_columns] FROM {}) VERTICAPY_SUBTABLE".format( epsilon_final, ", ".join(AR), relation ) # MA(q) if self.parameters["q"] > 0 or ( self.parameters["Q"] > 0 and self.parameters["s"] > 0 ): transform_relation = relation.replace("[VerticaPy_y]", y).replace( "[VerticaPy_ts]", ts ) transform_relation = transform_relation.replace( "[VerticaPy_key_columns]", ", " + ", ".join(X + [ts]) ) for idx, elem in enumerate(X): transform_relation = transform_relation.replace( "[X{}]".format(idx), elem ) query = "SELECT COUNT(*), AVG({}) FROM {}".format( self.y, transform_relation.format(self.input_relation) ) result = self.cursor.execute(query).fetchone() self.ma_avg_ = result[1] n = result[0] n = max( max( min(max(n ** (1.0 / 3.0), 8), self.parameters["papprox_ma"]), self.parameters["q"], ), self.parameters["Q"] * self.parameters["s"] + 1, ) n = int(n) columns = [ "LAG([VerticaPy_y], {}) OVER (ORDER BY [VerticaPy_ts]) AS ARq{}".format( i, i ) for i in range(1, n) ] ARq = ["ARq{}".format(i) for i in range(1, n)] tmp_relation = "(SELECT *, {} FROM {}) VERTICAPY_SUBTABLE".format( ", ".join(columns), relation ) for idx, elem in enumerate(X): tmp_relation = tmp_relation.replace("[X{}]".format(idx), elem) drop_temp_elem(self, schema) query = "CREATE VIEW {}.VERTICAPY_TEMP_MODEL_LINEAR_REGRESSION_VIEW_{} AS SELECT * FROM {}".format( schema, get_session(self.cursor), tmp_relation.format(self.input_relation) .replace("[VerticaPy_ts]", self.ts) .replace("[VerticaPy_y]", self.y) .replace("[VerticaPy_key_columns]", ", " + ", ".join([self.ts] + X)), ) try: self.cursor.execute(query) model.fit( input_relation="{}.VERTICAPY_TEMP_MODEL_LINEAR_REGRESSION_VIEW_{}".format( schema, get_session(self.cursor) ), X=ARq, y=self.y, ) except: drop_temp_elem(self, schema) raise drop_temp_elem(self, schema) if not (self.coef_.values["predictor"]): self.coef_.values["predictor"] += ["Intercept"] self.coef_.values["coefficient"] += [self.ma_avg_] self.deploy_predict_ = str(self.ma_avg_) alphaq = model.coef_.values["coefficient"][1:] model.drop() thetaq, piq = [], [-1] + [] for j in range(0, len(alphaq)): thetaq += [ sum([alphaq[j - i - 1] * thetaq[i] for i in range(0, j)]) + alphaq[j] ] for j in range(self.parameters["q"]): self.coef_.values["predictor"] += ["ma{}".format(j + 1)] self.coef_.values["coefficient"] += [thetaq[j]] self.deploy_predict_ += " + {} * MA{}".format(thetaq[j], j + 1) if self.parameters["s"] > 0: for j in range(1, self.parameters["Q"] + 1): self.coef_.values["predictor"] += [ "ma{}".format(self.parameters["s"] * j) ] self.coef_.values["coefficient"] += [ thetaq[self.parameters["s"] * j - 1] ] self.deploy_predict_ += " + {} * MA{}".format( thetaq[self.parameters["s"] * j - 1], self.parameters["s"] * j ) for j in range(0, self.parameters["max_pik"]): piq_tmp = 0 for i in range(0, self.parameters["q"]): if j - i > 0: piq_tmp -= thetaq[i] * piq[j - i] elif j - i == 0: piq_tmp -= thetaq[i] piq = piq + [piq_tmp] self.ma_piq_ = tablesample({"coefficient": piq}) epsilon = ( "[VerticaPy_y] - " + str(self.ma_avg_) + " - " + " - ".join( [ str((piq[i])) + " * " + "LAG([VerticaPy_y] - {}, {}) OVER (ORDER BY [VerticaPy_ts])".format( self.ma_avg_, i ) for i in range(1, self.parameters["max_pik"]) ] ) ) epsilon += " AS MA0" relation = "(SELECT *, {} FROM {}) VERTICAPY_SUBTABLE".format( epsilon, relation ) columns = [ "LAG(MA0, {}) OVER (ORDER BY [VerticaPy_ts]) AS MA{}".format(i, i) for i in range(1, self.parameters["q"] + 1) ] MA = ["MA{}".format(i) for i in range(1, self.parameters["q"] + 1)] if self.parameters["s"] > 0: columns += [ "LAG(MA0, {}) OVER (ORDER BY [VerticaPy_ts]) AS MA{}".format( i * self.parameters["s"], i * self.parameters["s"] ) for i in range(1, self.parameters["Q"] + 1) ] MA += [ "MA{}".format(i * self.parameters["s"]) for i in range(1, self.parameters["Q"] + 1) ] relation = "(SELECT *, {} FROM {}) VERTICAPY_SUBTABLE".format( ", ".join(columns), relation ) self.X += MA transform_relation = relation.replace("[VerticaPy_y]", y).replace( "[VerticaPy_ts]", ts ) transform_relation = transform_relation.replace( "[VerticaPy_key_columns]", ", " + ", ".join(X + [ts]) ) for idx, elem in enumerate(X): transform_relation = transform_relation.replace( "[X{}]".format(idx), elem ) self.transform_relation = relation model_save = { "type": "SARIMAX", "input_relation": self.input_relation, "test_relation": self.test_relation, "transform_relation": self.transform_relation, "deploy_predict": self.deploy_predict_, "ma_avg": self.ma_avg_, "ma_piq": self.ma_piq_.values if (self.ma_piq_) else None, "X": self.X, "y": self.y, "ts": self.ts, "exogenous": self.exogenous, "coef": self.coef_.values, "p": self.parameters["p"], "d": self.parameters["d"], "q": self.parameters["q"], "P": self.parameters["P"], "D": self.parameters["D"], "Q": self.parameters["Q"], "s": self.parameters["s"], "tol": self.parameters["tol"], "max_iter": self.parameters["max_iter"], "solver": self.parameters["solver"], "max_pik": self.parameters["max_pik"], "papprox_ma": self.parameters["papprox_ma"], } insert_verticapy_schema( model_name=self.name, model_type="SARIMAX", model_save=model_save, cursor=self.cursor, ) return self # ---# def plot( self, vdf: vDataFrame = None, y: str = "", ts: str = "", X: list = [], dynamic: bool = False, one_step: bool = True, observed: bool = True, confidence: bool = True, nlead: int = 10, nlast: int = 0, limit: int = 1000, ax=None, **style_kwds, ): """ --------------------------------------------------------------------------- Draws the SARIMAX model. Parameters ---------- vdf: vDataFrame, optional Object to use to run the prediction. y: str, optional Response column. ts: str, optional vcolumn used to order the data. X: list, optional exogenous vcolumns. dynamic: bool, optional If set to True, the dynamic forecast will be drawn. one_step: bool, optional If set to True, the one step ahead forecast will be drawn. observed: bool, optional If set to True, the observation will be drawn. confidence: bool, optional If set to True, the confidence ranges will be drawn. nlead: int, optional Number of predictions computed by the dynamic forecast after the last ts date. nlast: int, optional The dynamic forecast will start nlast values before the last ts date. limit: int, optional Maximum number of past elements to use. ax: Matplotlib axes object, optional The axes to plot on. **style_kwds Any optional parameter to pass to the Matplotlib functions. Returns ------- ax Matplotlib axes object """ if not (vdf): vdf = vdf_from_relation(relation=self.input_relation, cursor=self.cursor) check_types( [ ("limit", limit, [int, float],), ("nlead", nlead, [int, float],), ("dynamic", dynamic, [bool],), ("observed", observed, [bool],), ("one_step", one_step, [bool],), ("confidence", confidence, [bool],), ("vdf", vdf, [vDataFrame],), ], ) delta_limit, limit = ( limit, max( max( limit, self.parameters["p"] + 1 + nlast, self.parameters["P"] * self.parameters["s"] + 1 + nlast, ), 200, ), ) delta_limit = max(limit - delta_limit - nlast, 0) assert dynamic or one_step or observed, ParameterError( "No option selected.\n You should set either dynamic, one_step or observed to True." ) assert nlead + nlast > 0 or not (dynamic), ParameterError( "Dynamic Plots are only possible if either parameter 'nlead' is greater than 0 or parameter 'nlast' is greater than 0, and parameter 'dynamic' is set to True." ) if dynamic: assert not (self.exogenous), Exception( "Dynamic Plots are only possible for SARIMA models (no exegenous variables), not SARIMAX." ) if not (y): y = self.y if not (ts): ts = self.ts if not (X): X = self.exogenous result = self.predict( vdf=vdf, y=y, ts=ts, X=X, nlead=0, name="_verticapy_prediction_" ) error_eps = 1.96 * math.sqrt(self.score(method="mse")) print_info = verticapy.options["print_info"] verticapy.options["print_info"] = False try: result = ( result.select([ts, y, "_verticapy_prediction_"]) .dropna() .sort([ts]) .tail(limit) .values ) except: verticapy.options["print_info"] = print_info raise verticapy.options["print_info"] = print_info columns = [elem for elem in result] if isinstance(result[columns[0]][0], str): result[columns[0]] = [parse(elem) for elem in result[columns[0]]] true_value = [result[columns[0]], result[columns[1]]] one_step_ahead = [result[columns[0]], result[columns[2]]] lower_osa, upper_osa = ( [ float(elem) - error_eps if elem != None else None for elem in one_step_ahead[1] ], [ float(elem) + error_eps if elem != None else None for elem in one_step_ahead[1] ], ) if dynamic: deltat = result[columns[0]][-1] - result[columns[0]][-2] lead_time_list = [] if nlast > 0: lead_list = [[elem] for elem in result[columns[1]][:-nlast]] else: lead_list = [[elem] for elem in result[columns[1]]] for i in range(nlast): lead_list += [[self.fpredict(lead_list)]] lead_time_list += [result[columns[0]][i - nlast]] if lead_time_list: start_time = lead_time_list[-1] else: start_time = result[columns[0]][-1] for i in range(nlead): lead_list += [[self.fpredict(lead_list)]] lead_time_list += [start_time + (i + 1) * deltat] dynamic_forecast = ( [result[columns[0]][-nlast - 1]] + lead_time_list, [result[columns[1]][-nlast - 1]] + [elem[0] for elem in lead_list[-nlast - nlead :]], ) lower_d, upper_d = [], [] for i in range(len(dynamic_forecast[1])): if ( self.parameters["s"] > 0 and self.parameters["p"] == 0 and self.parameters["d"] == 0 and self.parameters["q"] == 0 ): delta_error = error_eps * math.sqrt( int(i / self.parameters["s"]) + 1 ) else: delta_error = error_eps * math.sqrt(i + 1) lower_d += [float(dynamic_forecast[1][i]) - delta_error] upper_d += [float(dynamic_forecast[1][i]) + delta_error] else: lower_d, upper_d, dynamic_forecast = [], [], ([], []) alpha = 0.3 if not (ax): fig, ax = plt.subplots() if isnotebook(): fig.set_size_inches(10, 6) ax.grid() colors = gen_colors() param1 = { "color": colors[2], "linewidth": 2, } param2 = { "color": colors[3], "linewidth": 2, "linestyle": ":", } param3 = { "color": colors[0], "linewidth": 2, "linestyle": "dashed", } if dynamic: ax.fill_between( dynamic_forecast[0], 1.02 * float(min(true_value[1] + dynamic_forecast[1] + one_step_ahead[1])), 1.02 * float(max(true_value[1] + dynamic_forecast[1] + one_step_ahead[1])), alpha=0.04, color=updated_dict(param3, style_kwds, 2)["color"], ) if confidence: ax.fill_between( dynamic_forecast[0], lower_d, upper_d, alpha=0.08, color="#555555" ) ax.plot(dynamic_forecast[0], lower_d, alpha=0.08, color="#000000") ax.plot(dynamic_forecast[0], upper_d, alpha=0.08, color="#000000") ax.plot( dynamic_forecast[0], dynamic_forecast[1], label="Dynamic Forecast", **updated_dict(param3, style_kwds, 2), ) if one_step: if confidence: ax.fill_between( one_step_ahead[0][delta_limit:], lower_osa[delta_limit:], upper_osa[delta_limit:], alpha=0.04, color="#555555", ) ax.plot( one_step_ahead[0][delta_limit:], lower_osa[delta_limit:], alpha=0.04, color="#000000", ) ax.plot( one_step_ahead[0][delta_limit:], upper_osa[delta_limit:], alpha=0.04, color="#000000", ) ax.plot( one_step_ahead[0][delta_limit:], one_step_ahead[1][delta_limit:], label="One-step ahead Forecast", **updated_dict(param2, style_kwds, 1), ) if observed: ax.plot( true_value[0][delta_limit:], true_value[1][delta_limit:], label="Observed", **updated_dict(param1, style_kwds, 0), ) ax.set_title( "SARIMAX({},{},{})({},{},{})_{}".format( self.parameters["p"], self.parameters["d"], self.parameters["q"], self.parameters["P"], self.parameters["D"], self.parameters["Q"], self.parameters["s"], ) ) ax.set_xlabel(ts) ax.legend(loc="center left", bbox_to_anchor=[1, 0.5]) ax.set_ylim( 1.02 * float(min(true_value[1] + dynamic_forecast[1] + one_step_ahead[1])), 1.02 * float(max(true_value[1] + dynamic_forecast[1] + one_step_ahead[1])), ) for tick in ax.get_xticklabels(): tick.set_rotation(90) return ax # ---# def predict( self, vdf: vDataFrame, y: str = "", ts: str = "", X: list = [], nlead: int = 0, name: str = "", ): """ --------------------------------------------------------------------------- Predicts using the input relation. Parameters ---------- vdf: vDataFrame Object to use to run the prediction. y: str, optional Response column. ts: str, optional vcolumn used to order the data. X: list, optional exogenous vcolumns. nlead: int, optional Number of records to predict after the last ts date. name: str, optional Name of the added vcolumn. If empty, a name will be generated. Returns ------- vDataFrame object including the prediction. """ check_types( [ ("name", name, [str],), ("y", y, [str],), ("ts", ts, [str],), ("X", X, [list],), ("nlead", nlead, [int, float],), ("vdf", vdf, [vDataFrame],), ], ) if not (y): y = self.y if not (ts): ts = self.ts if not (X): X = self.exogenous columns_check([y, ts], vdf) y, ts = vdf_columns_names([y, ts], vdf) name = ( "{}_".format(self.type) + "".join(ch for ch in self.name if ch.isalnum()) if not (name) else name ) key_columns = ", " + ", ".join(vdf.get_columns(exclude_columns=[y])) transform_relation = self.transform_relation.replace( "[VerticaPy_y]", y ).replace("[VerticaPy_ts]", ts) transform_relation = transform_relation.replace( "[VerticaPy_key_columns]", key_columns ) predictSQL = self.deploySQL().replace("[VerticaPy_y]", y).replace( "[VerticaPy_ts]", ts ) + " AS {}".format(name) for idx, elem in enumerate(X): transform_relation = transform_relation.replace("[X{}]".format(idx), elem) predictSQL = predictSQL.replace("[X{}]".format(idx), elem) columns = ( vdf.get_columns(exclude_columns=[y]) + [predictSQL] + ["VerticaPy_y_copy AS {}".format(y)] ) relation = vdf.__genSQL__() for i in range(nlead): query = "SELECT ({} - LAG({}, 1) OVER (ORDER BY {}))::VARCHAR FROM {} ORDER BY {} DESC LIMIT 1".format( ts, ts, ts, relation, ts ) deltat = vdf._VERTICAPY_VARIABLES_["cursor"].execute(query).fetchone()[0] query = "SELECT (MAX({}) + '{}'::interval)::VARCHAR FROM {}".format( ts, deltat, relation ) next_t = vdf._VERTICAPY_VARIABLES_["cursor"].execute(query).fetchone()[0] if i == 0: first_t = next_t new_line = "SELECT '{}'::TIMESTAMP AS {}, {}".format( next_t, ts, ", ".join( [ "NULL AS {}".format(column) for column in vdf.get_columns(exclude_columns=[ts]) ] ), ) relation_tmp = "(SELECT {} FROM {} UNION ALL ({})) VERTICAPY_SUBTABLE".format( ", ".join([ts] + vdf.get_columns(exclude_columns=[ts])), relation, new_line, ) query = "SELECT {} FROM {} ORDER BY {} DESC LIMIT 1".format( self.deploySQL() .replace("[VerticaPy_y]", y) .replace("[VerticaPy_ts]", ts), transform_relation.format(relation_tmp), ts, ) prediction = ( vdf._VERTICAPY_VARIABLES_["cursor"].execute(query).fetchone()[0] ) columns_tmp = vdf.get_columns(exclude_columns=[ts, y]) new_line = "SELECT '{}'::TIMESTAMP AS {}, {} AS {} {}".format( next_t, ts, prediction, y, (", " if (columns_tmp) else "") + ", ".join(["NULL AS {}".format(column) for column in columns_tmp]), ) relation = "(SELECT {} FROM {} UNION ALL ({})) VERTICAPY_SUBTABLE".format( ", ".join([ts, y] + vdf.get_columns(exclude_columns=[ts, y])), relation, new_line, ) final_relation = "(SELECT {} FROM {}) VERTICAPY_SUBTABLE".format( ", ".join(columns), transform_relation.format(relation) ) result = vdf_from_relation(final_relation, "SARIMAX", self.cursor,) if nlead > 0: result[y].apply( "CASE WHEN {} >= '{}' THEN NULL ELSE {} END".format(ts, first_t, "{}") ) return result # ---# class VAR(Regressor): """ --------------------------------------------------------------------------- [Beta Version] Creates an VAR object using the Vertica Linear Regression algorithm on the data. Parameters ---------- name: str Name of the the model. The model will be stored in the DB. cursor: DBcursor, optional Vertica database cursor. p: int, optional Order of the AR (Auto-Regressive) part. tol: float, optional Determines whether the algorithm has reached the specified accuracy result. max_iter: int, optional Determines the maximum number of iterations the algorithm performs before achieving the specified accuracy result. solver: str, optional The optimizer method to use to train the model. Newton : Newton Method BFGS : Broyden Fletcher Goldfarb Shanno """ def __init__( self, name: str, cursor=None, p: int = 1, tol: float = 1e-4, max_iter: int = 1000, solver: str = "Newton", ): check_types([("name", name, [str],)]) self.type, self.name = "VAR", name assert p > 0, ParameterError( "Parameter 'p' must be greater than 0 to build a VAR model." ) self.set_params( {"p": p, "tol": tol, "max_iter": max_iter, "solver": solver,} ) cursor = check_cursor(cursor)[0] self.cursor = cursor version(cursor=cursor, condition=[8, 0, 0]) # ---# def deploySQL(self): """ --------------------------------------------------------------------------- Returns the SQL code needed to deploy the model. Returns ------- str the SQL code needed to deploy the model. """ sql = [] for idx, coefs in enumerate(self.coef_): coefs_tmp = coefs.values["coefficient"] predictors_tmp = coefs.values["predictor"] sql += [ str(coefs_tmp[0]) + " + " + " + ".join( [ str(coefs_tmp[i]) + " * " + str(predictors_tmp[i]) for i in range(1, len(coefs_tmp)) ] ) ] return sql # ---# def features_importance( self, X_idx: int = 0, ax=None, show: bool = True, **style_kwds, ): """ --------------------------------------------------------------------------- Computes the model's features importance. Parameters ---------- X_idx: int/str, optional Index of the main vector vcolumn used to draw the features importance. It can also be the name of a predictor vcolumn. ax: Matplotlib axes object, optional The axes to plot on. show: bool If set to True, draw the features importance. **style_kwds Any optional parameter to pass to the Matplotlib functions. Returns ------- ax Matplotlib axes object """ check_types([("X_idx", X_idx, [int, float, str],), ("show", show, [bool],),],) if isinstance(X_idx, str): X_idx = str_column(X_idx).lower() for idx, elem in enumerate(self.X): if str_column(elem).lower() == X_idx: X_idx = idx break assert ( isinstance(X_idx, (float, int)) and len(self.X) > X_idx >= 0 ), ParameterError( "The index of the vcolumn to draw 'X_idx' must be between 0 and {}. It can also be the name of a predictor vcolumn.".format( len(self.X) ) ) relation = self.transform_relation.replace("[VerticaPy_ts]", self.ts).format( self.test_relation ) for idx, elem in enumerate(self.X): relation = relation.replace("[X{}]".format(idx), elem) min_max = ( vdf_from_relation(relation=self.input_relation, cursor=self.cursor) .agg(func=["min", "max"], columns=self.X) .transpose() ) coefficient = self.coef_[X_idx].values coeff_importances = {} coeff_sign = {} for idx, coef in enumerate(coefficient["predictor"]): if idx > 0: predictor = int(coef.split("_")[0].replace("ar", "")) predictor = str_column(self.X[predictor]) minimum, maximum = min_max[predictor] val = coefficient["coefficient"][idx] coeff_importances[coef] = abs(val) * (maximum - minimum) coeff_sign[coef] = 1 if val >= 0 else -1 total = sum([coeff_importances[elem] for elem in coeff_importances]) for elem in coeff_importances: coeff_importances[elem] = 100 * coeff_importances[elem] / total if show: plot_importance( coeff_importances, coeff_sign, print_legend=True, ax=ax, **style_kwds, ) importances = {"index": ["importance", "sign"]} for elem in coeff_importances: importances[elem] = [coeff_importances[elem], coeff_sign[elem]] return tablesample(values=importances).transpose() # ---# def fit( self, input_relation: Union[vDataFrame, str], X: list, ts: str, test_relation: Union[vDataFrame, str] = "", ): """ --------------------------------------------------------------------------- Trains the model. Parameters ---------- input_relation: str/vDataFrame Training relation. X: list List of the response columns. ts: str vcolumn used to order the data. test_relation: str/vDataFrame, optional Relation used to test the model. Returns ------- object self """ check_types( [ ("input_relation", input_relation, [str, vDataFrame],), ("X", X, [list],), ("ts", ts, [str],), ("test_relation", test_relation, [str, vDataFrame],), ] ) self.cursor = check_cursor(self.cursor, input_relation, True)[0] # Initialization does_model_exist(name=self.name, cursor=self.cursor, raise_error=True) self.input_relation = ( input_relation if isinstance(input_relation, str) else input_relation.__genSQL__() ) if isinstance(test_relation, vDataFrame): self.test_relation = test_relation.__genSQL__() elif test_relation: self.test_relation = test_relation else: self.test_relation = self.input_relation self.ts, self.deploy_predict_ = str_column(ts), [] self.X, schema = [str_column(elem) for elem in X], schema_relation(self.name)[0] model = LinearRegression( name=self.name, solver=self.parameters["solver"], max_iter=self.parameters["max_iter"], tol=self.parameters["tol"], ) # AR(p) columns, AR = [], [] for idx, elem in enumerate(self.X): for i in range(1, self.parameters["p"] + 1): columns += [ "LAG([X{}], {}) OVER (ORDER BY [VerticaPy_ts]) AS AR{}_{}".format( idx, i, idx, i ) ] AR += ["AR{}_{}".format(idx, i)] self.transform_relation = "(SELECT *, {} FROM {}) VERTICAPY_SUBTABLE".format( ", ".join(columns), "{}" ) relation = self.transform_relation.replace("[VerticaPy_ts]", self.ts).format( self.input_relation ) for idx, elem in enumerate(self.X): relation = relation.replace("[X{}]".format(idx), elem) def drop_temp_elem(self, schema): try: with warnings.catch_warnings(record=True) as w: drop( "{}.VERTICAPY_TEMP_MODEL_LINEAR_REGRESSION_VIEW_{}".format( schema, get_session(self.cursor) ), cursor=self.cursor, method="view", ) except: pass drop_temp_elem(self, schema) try: query = "CREATE VIEW {}.VERTICAPY_TEMP_MODEL_LINEAR_REGRESSION_VIEW_{} AS SELECT * FROM {}".format( schema, get_session(self.cursor), relation ) self.cursor.execute(query) self.coef_ = [] for elem in X: model.fit( input_relation="{}.VERTICAPY_TEMP_MODEL_LINEAR_REGRESSION_VIEW_{}".format( schema, get_session(self.cursor) ), X=AR, y=elem, ) self.coef_ += [model.coef_] model.drop() except: drop_temp_elem(self, schema) raise drop_temp_elem(self, schema) model_save = { "type": "VAR", "input_relation": self.input_relation, "test_relation": self.test_relation, "transform_relation": self.transform_relation, "deploy_predict": self.deploy_predict_, "X": self.X, "ts": self.ts, "p": self.parameters["p"], "tol": self.parameters["tol"], "max_iter": self.parameters["max_iter"], "solver": self.parameters["solver"], } for idx, elem in enumerate(self.coef_): model_save["coef_{}".format(idx)] = elem.values insert_verticapy_schema( model_name=self.name, model_type="VAR", model_save=model_save, cursor=self.cursor, ) return self # ---# def fpredict(self, L: list): """ --------------------------------------------------------------------------- Computes the prediction. Parameters ---------- L: list List containing the data. It must be a two-dimensional list containing multiple rows. Each row must include as first element the ordered predictor and as nth elements the nth - 1 exogenous variable (nth > 2). Returns ------- float the prediction. """ try: result = [] result_tmp = 0 for i in range(len(self.X)): result_tmp = 0 for j in range(len(self.coef_[i].values["coefficient"])): elem = self.coef_[i].values["predictor"][j] if elem.lower() == "intercept": result_tmp += self.coef_[i].values["coefficient"][j] else: ni, nj = elem[2:].split("_") ni, nj = int(ni), int(nj) result_tmp += ( self.coef_[i].values["coefficient"][j] * L[-nj][ni] ) result += [result_tmp] return result except: return None # ---# def plot( self, vdf: vDataFrame = None, X: list = [], ts: str = "", X_idx: int = 0, dynamic: bool = False, one_step: bool = True, observed: bool = True, confidence: bool = True, nlead: int = 10, nlast: int = 0, limit: int = 1000, ax=None, **style_kwds, ): """ --------------------------------------------------------------------------- Draws the VAR model. Parameters ---------- vdf: vDataFrame Object to use to run the prediction. X: list, optional List of the response columns. ts: str, optional vcolumn used to order the data. X_idx: int, optional Index of the main vector vcolumn to draw. It can also be the name of a predictor vcolumn. dynamic: bool, optional If set to True, the dynamic forecast will be drawn. one_step: bool, optional If set to True, the one step ahead forecast will be drawn. observed: bool, optional If set to True, the observation will be drawn. confidence: bool, optional If set to True, the confidence ranges will be drawn. nlead: int, optional Number of predictions computed by the dynamic forecast after the last ts date. nlast: int, optional The dynamic forecast will start nlast values before the last ts date. limit: int, optional Maximum number of past elements to use. ax: Matplotlib axes object, optional The axes to plot on. **style_kwds Any optional parameter to pass to the Matplotlib functions. Returns ------- ax Matplotlib axes object """ if not (vdf): vdf = vdf_from_relation(relation=self.input_relation, cursor=self.cursor) check_types( [ ("limit", limit, [int, float],), ("nlead", nlead, [int, float],), ("X_idx", X_idx, [int, float, str],), ("dynamic", dynamic, [bool],), ("observed", observed, [bool],), ("one_step", one_step, [bool],), ("confidence", confidence, [bool],), ("vdf", vdf, [vDataFrame],), ], ) delta_limit, limit = ( limit, max(max(limit, self.parameters["p"] + 1 + nlast), 200), ) delta_limit = max(limit - delta_limit - nlast, 0) if not (ts): ts = self.ts if not (X): X = self.X assert dynamic or one_step or observed, ParameterError( "No option selected.\n You should set either dynamic, one_step or observed to True." ) assert nlead + nlast > 0 or not (dynamic), ParameterError( "Dynamic Plots are only possible if either parameter 'nlead' is greater than 0 or parameter 'nlast' is greater than 0, and parameter 'dynamic' is set to True." ) if isinstance(X_idx, str): X_idx = str_column(X_idx).lower() for idx, elem in enumerate(X): if str_column(elem).lower() == X_idx: X_idx = idx break assert ( isinstance(X_idx, (float, int)) and len(self.X) > X_idx >= 0 ), ParameterError( "The index of the vcolumn to draw 'X_idx' must be between 0 and {}. It can also be the name of a predictor vcolumn.".format( len(self.X) ) ) result_all = self.predict( vdf=vdf, X=X, ts=ts, nlead=0, name=[ "_verticapy_prediction_{}_".format(idx) for idx in range(len(self.X)) ], ) y, prediction = X[X_idx], "_verticapy_prediction_{}_".format(X_idx) error_eps = 1.96 * math.sqrt(self.score(method="mse").values["mse"][X_idx]) print_info = verticapy.options["print_info"] verticapy.options["print_info"] = False try: result = ( result_all.select([ts, y, prediction]) .dropna() .sort([ts]) .tail(limit) .values ) except: verticapy.options["print_info"] = print_info raise verticapy.options["print_info"] = print_info columns = [elem for elem in result] if isinstance(result[columns[0]][0], str): result[columns[0]] = [parse(elem) for elem in result[columns[0]]] true_value = [result[columns[0]], result[columns[1]]] one_step_ahead = [result[columns[0]], result[columns[2]]] lower_osa, upper_osa = ( [ float(elem) - error_eps if elem != None else None for elem in one_step_ahead[1] ], [ float(elem) + error_eps if elem != None else None for elem in one_step_ahead[1] ], ) if dynamic: print_info = verticapy.options["print_info"] verticapy.options["print_info"] = False try: result = ( result_all.select([ts] + X).dropna().sort([ts]).tail(limit).values ) except: verticapy.options["print_info"] = print_info raise verticapy.options["print_info"] = print_info columns = [elem for elem in result] if isinstance(result[columns[0]][0], str): result[columns[0]] = [parse(elem) for elem in result[columns[0]]] deltat = result[columns[0]][-1] - result[columns[0]][-2] lead_time_list, lead_list = [], [] if nlast > 0: for i in range(len(result[columns[0]][:-nlast])): lead_list += [[result[elem][i] for elem in columns[1:]]] else: for i in range(len(result[columns[0]])): lead_list += [[result[elem][i] for elem in columns[1:]]] for i in range(nlast): lead_list += [self.fpredict(lead_list)] lead_time_list += [result[columns[0]][i - nlast]] if lead_time_list: start_time = lead_time_list[-1] else: start_time = result[columns[0]][-1] for i in range(nlead): lead_list += [self.fpredict(lead_list)] lead_time_list += [start_time + (i + 1) * deltat] dynamic_forecast = ( [result[columns[0]][-nlast - 1]] + lead_time_list, [result[columns[1 + X_idx]][-nlast - 1]] + [elem[X_idx] for elem in lead_list[-nlast - nlead :]], ) lower_d, upper_d = [], [] for i in range(len(dynamic_forecast[1])): delta_error = error_eps * math.sqrt(i + 1) lower_d += [float(dynamic_forecast[1][i]) - delta_error] upper_d += [float(dynamic_forecast[1][i]) + delta_error] else: lower_d, upper_d, dynamic_forecast = [], [], ([], []) alpha = 0.3 if not (ax): fig, ax = plt.subplots() if isnotebook(): fig.set_size_inches(10, 6) ax.grid() colors = gen_colors() param1 = { "color": colors[2], "linewidth": 2, } param2 = { "color": colors[3], "linewidth": 2, "linestyle": ":", } param3 = { "color": colors[0], "linewidth": 2, "linestyle": "dashed", } if dynamic: ax.fill_between( dynamic_forecast[0], 1.02 * float(min(true_value[1] + dynamic_forecast[1] + one_step_ahead[1])), 1.02 * float(max(true_value[1] + dynamic_forecast[1] + one_step_ahead[1])), alpha=0.04, color=updated_dict(param3, style_kwds, 2)["color"], ) if confidence: ax.fill_between( dynamic_forecast[0], lower_d, upper_d, alpha=0.08, color="#555555" ) ax.plot(dynamic_forecast[0], lower_d, alpha=0.08, color="#000000") ax.plot(dynamic_forecast[0], upper_d, alpha=0.08, color="#000000") ax.plot( dynamic_forecast[0], dynamic_forecast[1], label="Dynamic Forecast", **updated_dict(param3, style_kwds, 2), ) if one_step: if confidence: ax.fill_between( one_step_ahead[0][delta_limit:], lower_osa[delta_limit:], upper_osa[delta_limit:], alpha=0.04, color="#555555", ) ax.plot( one_step_ahead[0][delta_limit:], lower_osa[delta_limit:], alpha=0.04, color="#000000", ) ax.plot( one_step_ahead[0][delta_limit:], upper_osa[delta_limit:], alpha=0.04, color="#000000", ) ax.plot( one_step_ahead[0][delta_limit:], one_step_ahead[1][delta_limit:], label="One-step ahead Forecast", **updated_dict(param2, style_kwds, 1), ) if observed: ax.plot( true_value[0][delta_limit:], true_value[1][delta_limit:], label="Observed", **updated_dict(param1, style_kwds, 0), ) ax.set_title("VAR({}) [{}]".format(self.parameters["p"], y)) ax.set_xlabel(ts) ax.legend(loc="center left", bbox_to_anchor=[1, 0.5]) ax.set_ylim( 1.02 * float(min(true_value[1] + dynamic_forecast[1] + one_step_ahead[1])), 1.02 * float(max(true_value[1] + dynamic_forecast[1] + one_step_ahead[1])), ) for tick in ax.get_xticklabels(): tick.set_rotation(90) return ax # ---# def predict( self, vdf: vDataFrame, X: list = [], ts: str = "", nlead: int = 0, name: list = [], ): """ --------------------------------------------------------------------------- Predicts using the input relation. Parameters ---------- vdf: vDataFrame Object to use to run the prediction. X: list, optional List of the response columns. ts: str, optional vcolumn used to order the data. nlead: int, optional Number of records to predict after the last ts date. name: list, optional Names of the added vcolumns. If empty, names will be generated. Returns ------- vDataFrame object including the prediction. """ check_types( [ ("name", name, [list],), ("ts", ts, [str],), ("nlead", nlead, [int, float],), ("X", X, [list],), ("vdf", vdf, [vDataFrame],), ], ) if not (ts): ts = self.ts if not (X): X = self.X columns_check(X + [ts], vdf) X = vdf_columns_names(X, vdf) ts = vdf_columns_names([ts], vdf)[0] all_pred, names = [], [] transform_relation = self.transform_relation.replace("[VerticaPy_ts]", self.ts) for idx, elem in enumerate(X): name_tmp = ( "{}_".format(self.type) + "".join(ch for ch in elem if ch.isalnum()) if len(name) != len(X) else name[idx] ) all_pred += ["{} AS {}".format(self.deploySQL()[idx], name_tmp)] transform_relation = transform_relation.replace("[X{}]".format(idx), elem) columns = vdf.get_columns() + all_pred relation = vdf.__genSQL__() for i in range(nlead): query = "SELECT ({} - LAG({}, 1) OVER (ORDER BY {}))::VARCHAR FROM {} ORDER BY {} DESC LIMIT 1".format( ts, ts, ts, relation, ts ) deltat = vdf._VERTICAPY_VARIABLES_["cursor"].execute(query).fetchone()[0] query = "SELECT (MAX({}) + '{}'::interval)::VARCHAR FROM {}".format( ts, deltat, relation ) next_t = vdf._VERTICAPY_VARIABLES_["cursor"].execute(query).fetchone()[0] if i == 0: first_t = next_t new_line = "SELECT '{}'::TIMESTAMP AS {}, {}".format( next_t, ts, ", ".join( [ "NULL AS {}".format(column) for column in vdf.get_columns(exclude_columns=[ts]) ] ), ) relation_tmp = "(SELECT {} FROM {} UNION ALL ({})) VERTICAPY_SUBTABLE".format( ", ".join([ts] + vdf.get_columns(exclude_columns=[ts])), relation, new_line, ) query = "SELECT {} FROM {} ORDER BY {} DESC LIMIT 1".format( ", ".join(self.deploySQL()), transform_relation.format(relation_tmp), ts ) prediction = vdf._VERTICAPY_VARIABLES_["cursor"].execute(query).fetchone() for idx, elem in enumerate(X): prediction[idx] = "{} AS {}".format(prediction[idx], elem) columns_tmp = vdf.get_columns(exclude_columns=[ts] + X) new_line = "SELECT '{}'::TIMESTAMP AS {}, {} {}".format( next_t, ts, ", ".join(prediction), (", " if (columns_tmp) else "") + ", ".join(["NULL AS {}".format(column) for column in columns_tmp]), ) relation = "(SELECT {} FROM {} UNION ALL ({})) VERTICAPY_SUBTABLE".format( ", ".join([ts] + X + vdf.get_columns(exclude_columns=[ts] + X)), relation, new_line, ) final_relation = "(SELECT {} FROM {}) VERTICAPY_SUBTABLE".format( ", ".join(columns), transform_relation.format(relation) ) result = vdf_from_relation(final_relation, "VAR", self.cursor,) if nlead > 0: for elem in X: result[elem].apply( "CASE WHEN {} >= '{}' THEN NULL ELSE {} END".format( ts, first_t, "{}" ) ) return result
37.536295
200
0.462391
[ "Apache-2.0" ]
MiConnell/VerticaPy
verticapy/learn/tsa.py
69,298
Python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 14 08:23:08 2017 Author: Zachary W. Mikus """ #These are testing variables d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70} def f(x, y): k = x + y return k def commonKeys(longerList, shorterList): commonKeyList = [] #Variables #intersectDictionary = The final returned intersect dictionary #commonKeyList = The list of keys that appear in both dictionaries for i in range(len(longerList)): if longerList[i] in shorterList: commonKeyList.append(longerList[i]) return commonKeyList def differentKeys(longerList, shorterList): #This function uses similar logic to the commonKeys function #Except it will see if the index is NOT in the other list and remove it #This runs the loop twice once through each loop to find the missing numbers #in each list differentKeyList = [] for i in range(len(longerList)): if longerList[i] not in shorterList: differentKeyList.append(longerList[i]) for i in range(len(shorterList)): if shorterList[i] not in longerList: differentKeyList.append(shorterList[i]) return differentKeyList def intersect(commonList, d1, d2): intersectDict = {} #This function takes the common list of keys, grabs the common values in #both dictionaries and performs the f(x, y) function on them for i in range(len(commonList)): #currentIndex is the index in the dictionary, it will move currentIndex = commonList[i] x = d1[currentIndex] y = d2[currentIndex] functionValue = f(x, y) intersectDict[currentIndex] = functionValue return intersectDict def difference(differentKeyList, d1, d2): differenceDict = {} #This function takes the different list of keys, grabs the relevant values and #creates a dictionary #searches d for i in range(len(differentKeyList)): currentIndex = differentKeyList[i] if currentIndex in d1: differenceDict[currentIndex] = d1[currentIndex] if currentIndex in d2: differenceDict[currentIndex] = d2[currentIndex] return differenceDict def diff_dictionary(d1, d2): differentKeyList = [] #Turns key values in lists and finds the longest #keyListD1 = list of keys in d1 #keyListD2 = list of keys in d2 keyListD1 = list(d1.keys()) keyListD2 = list(d2.keys()) #determines which of the two lists is the longest and assigned it values #for the common list function if len(keyListD1) > len(keyListD2): longerList = keyListD1 shorterList = keyListD2 else: longerList = keyListD2 shorterList = keyListD1 #Finds the common keys commonList = commonKeys(longerList, shorterList) #Makes the intersect dictionary intersectDict = intersect(commonList, d1, d2) #Finds the different keys differentKeyList = differentKeys(longerList, shorterList) #Makes the different key dictionary differenceDict = difference(differentKeyList, d1, d2) #This now creates a list of the dictionaries put together return (intersectDict, differenceDict) ''' #This is for calculating the difference dictionary. #The difference dictionary consists of every #KEY VALUE# in the dictionaries that does not exist #in the other dictionary. ''' #Variables #differenceDictionary = The final returned difference dictionary print(diff_dictionary(d1, d2))
31.633929
82
0.686988
[ "MIT" ]
Zafara1/MITx-6.00.1x
dict_interdiff.py
3,543
Python
n1 = float(input('Digite sua primera nota: ')) n2 = float(input('Digite sua segunda nota: ')) media = (n1 + n2) / 2 if media <= 5: print('Sua média é {} e você está REPROVADO!'.format(media)) elif media >= 7: print('Sua média é {} e você está APROVADO!'.format(media)) elif media >5 or media <6.9: print('Sua média é {} e você está de RECUPERAÇÃO '.format(media))
37.6
69
0.646277
[ "MIT" ]
tiagosm1/Pyhton_CEV
Desafios/Desafio 040.py
390
Python
# Generated by Django 4.0 on 2021-10-12 22:38 import blog.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200, unique=True)), ('slug', models.SlugField(max_length=200, unique=True)), ('updated_on', models.DateTimeField(auto_now=True)), ('summary', models.TextField(max_length=250)), ('content', models.TextField()), ('created_on', models.DateTimeField(auto_now_add=True)), ('status', models.IntegerField(choices=[(0, 'Draft'), (1, 'Publish')], default=0)), ('cover_image', models.ImageField(blank=True, null=True, upload_to=blog.models.get_unique_path)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog_posts', to='auth.user')), ], options={ 'ordering': ['-created_on'], }, ), ]
38
134
0.590643
[ "MIT" ]
Nemwel-Boniface/Farmblr
farmblr/blog/migrations/0001_initial.py
1,368
Python
import urllib.parse from datetime import datetime from unittest.mock import patch from django.contrib.auth.models import User from django.test import TestCase from django.utils import timezone from dfirtrack_artifacts.models import ( Artifact, Artifactpriority, Artifactstatus, Artifacttype, ) from dfirtrack_config.models import Statushistory from dfirtrack_main.models import ( Analysisstatus, Case, Casepriority, Casestatus, System, Systemstatus, Task, Taskname, Taskpriority, Taskstatus, ) class StatusViewTestCase(TestCase): """ status view tests """ @classmethod def setUpTestData(cls): # create user test_user = User.objects.create_user(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # create object artifactstatus_1 = Artifactstatus.objects.create(artifactstatus_name='artifactstatus_1') # create object artifacttype_1 = Artifacttype.objects.create(artifacttype_name='artifacttype_1') # create object casepriority_1 = Casepriority.objects.create(casepriority_name='casepriority_1') # create object casestatus_1 = Casestatus.objects.create(casestatus_name='casestatus_1') # create object systemstatus_1 = Systemstatus.objects.create(systemstatus_name='systemstatus_1') # create object taskname_1 = Taskname.objects.create(taskname_name='taskname_1') # create object taskpriority_1 = Taskpriority.objects.create(taskpriority_name='prio_1') # create object taskstatus_1 = Taskstatus.objects.create(taskstatus_name='taskstatus_1') # create object system_1 = System.objects.create( system_name = 'system_1', systemstatus = systemstatus_1, system_created_by_user_id = test_user, system_modified_by_user_id = test_user, ) System.objects.create( system_name = 'system_2', systemstatus = systemstatus_1, system_created_by_user_id = test_user, system_modified_by_user_id = test_user, ) System.objects.create( system_name = 'system_3', systemstatus = systemstatus_1, system_created_by_user_id = test_user, system_modified_by_user_id = test_user, ) # create object Task.objects.create( taskname = taskname_1, taskpriority = taskpriority_1, taskstatus = taskstatus_1, task_modify_time = timezone.now(), task_created_by_user_id = test_user, task_modified_by_user_id = test_user, ) # create object Artifact.objects.create( artifact_name = 'artifact_1', artifactstatus = artifactstatus_1, artifacttype = artifacttype_1, system = system_1, artifact_created_by_user_id = test_user, artifact_modified_by_user_id = test_user, ) Artifact.objects.create( artifact_name = 'artifact_2', artifactstatus = artifactstatus_1, artifacttype = artifacttype_1, system = system_1, artifact_created_by_user_id = test_user, artifact_modified_by_user_id = test_user, ) # create object Case.objects.create( case_name = 'case_1', casepriority = casepriority_1, casestatus = casestatus_1, case_is_incident = True, case_created_by_user_id = test_user, ) Case.objects.create( case_name = 'case_2', casepriority = casepriority_1, casestatus = casestatus_1, case_is_incident = True, case_created_by_user_id = test_user, ) Case.objects.create( case_name = 'case_3', casepriority = casepriority_1, casestatus = casestatus_1, case_is_incident = True, case_created_by_user_id = test_user, ) Case.objects.create( case_name = 'case_4', casepriority = casepriority_1, casestatus = casestatus_1, case_is_incident = True, case_created_by_user_id = test_user, ) # mock timezone.now() t_1 = datetime(2020, 11, 22, 11, 22, 33, tzinfo=timezone.utc) with patch.object(timezone, 'now', return_value=t_1): # create empty object (for simple testing get request for empty detail view this should be sufficient) Statushistory.objects.create() def test_status_view_not_logged_in(self): """ test status view """ # create url destination = '/login/?next=' + urllib.parse.quote('/config/status/', safe='') # get response response = self.client.get('/config/status/', follow=True) # compare self.assertRedirects(response, destination, status_code=302, target_status_code=200) def test_status_view_logged_in(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # get response response = self.client.get('/config/status/') # compare self.assertEqual(response.status_code, 200) def test_status_view_template(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # get response response = self.client.get('/config/status/') # compare self.assertTemplateUsed(response, 'dfirtrack_config/status/status.html') def test_status_view_get_user_context(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # get response response = self.client.get('/config/status/') # compare self.assertEqual(str(response.context['user']), 'testuser_status') def test_status_view_redirect(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # create url destination = urllib.parse.quote('/config/status/', safe='/') # get response response = self.client.get('/config/status', follow=True) # compare self.assertRedirects(response, destination, status_code=301, target_status_code=200) def test_status_view_get_object_context(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # get response response = self.client.get('/config/status/') # get querysets analysisstatus_all = Analysisstatus.objects.all().order_by('analysisstatus_name') artifactpriority_all = Artifactpriority.objects.all().order_by('artifactpriority_name') artifactstatus_all = Artifactstatus.objects.all().order_by('artifactstatus_name') casepriority_all = Casepriority.objects.all().order_by('casepriority_name') casestatus_all = Casestatus.objects.all().order_by('casestatus_name') systemstatus_all = Systemstatus.objects.all().order_by('systemstatus_name') taskstatus_all = Taskstatus.objects.all().order_by('taskstatus_name') taskpriority_all = Taskpriority.objects.all().order_by('taskpriority_name') # compare self.assertEqual(response.context['artifacts_number'], 2) self.assertEqual(response.context['cases_number'], 4) self.assertEqual(response.context['systems_number'], 3) self.assertEqual(response.context['tasks_number'], 1) self.assertEqual(type(response.context['analysisstatus_all']), type(analysisstatus_all)) self.assertEqual(type(response.context['artifactpriority_all']), type(artifactpriority_all)) self.assertEqual(type(response.context['artifactstatus_all']), type(artifactstatus_all)) self.assertEqual(type(response.context['casepriority_all']), type(casepriority_all)) self.assertEqual(type(response.context['casestatus_all']), type(casestatus_all)) self.assertEqual(type(response.context['systemstatus_all']), type(systemstatus_all)) self.assertEqual(type(response.context['taskpriority_all']), type(taskpriority_all)) self.assertEqual(type(response.context['taskstatus_all']), type(taskstatus_all)) def test_status_view_get_statushistory_entry_numbers_context(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # get response response = self.client.get('/config/status/') # compare self.assertEqual(type(response.context['statushistory_all']), type(reversed(Statushistory.objects.all()))) # TODO: test number of queryset elements in context element 'statushistory_all' according to 'statushistory_last_entrys' in MainConfigModel # TODO: number also depends on available statushistory elements # TODO: find a way to count reversed queryset #self.assertEqual(response.context['statushistory_all'].count(), 2) def test_status_detail_view_not_logged_in(self): """ test status view """ # get time t_1 = datetime(2020, 11, 22, 11, 22, 33, tzinfo=timezone.utc) # get object statushistory_id = Statushistory.objects.get(statushistory_time=t_1).statushistory_id # create url destination = '/login/?next=' + urllib.parse.quote('/config/status/' + str(statushistory_id) + '/', safe='') # get response response = self.client.get('/config/status/' + str(statushistory_id) + '/', follow=True) # compare self.assertRedirects(response, destination, status_code=302, target_status_code=200) def test_status_detail_view_logged_in(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # get time t_1 = datetime(2020, 11, 22, 11, 22, 33, tzinfo=timezone.utc) # get object statushistory_id = Statushistory.objects.get(statushistory_time=t_1).statushistory_id # get response response = self.client.get('/config/status/' + str(statushistory_id) + '/') # compare self.assertEqual(response.status_code, 200) def test_status_detail_view_template(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # get time t_1 = datetime(2020, 11, 22, 11, 22, 33, tzinfo=timezone.utc) # get object statushistory_id = Statushistory.objects.get(statushistory_time=t_1).statushistory_id # get response response = self.client.get('/config/status/' + str(statushistory_id) + '/') # compare self.assertTemplateUsed(response, 'dfirtrack_config/status/status_detail.html') def test_status_detail_view_get_user_context(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # get time t_1 = datetime(2020, 11, 22, 11, 22, 33, tzinfo=timezone.utc) # get object statushistory_id = Statushistory.objects.get(statushistory_time=t_1).statushistory_id # get response response = self.client.get('/config/status/' + str(statushistory_id) + '/') # compare self.assertEqual(str(response.context['user']), 'testuser_status') def test_status_detail_view_redirect(self): """ test status view """ # login testuser self.client.login(username='testuser_status', password='D9lPsoHFXeCNKEzM3IgE') # get time t_1 = datetime(2020, 11, 22, 11, 22, 33, tzinfo=timezone.utc) # get object statushistory_id = Statushistory.objects.get(statushistory_time=t_1).statushistory_id # create url destination = urllib.parse.quote('/config/status/' + str(statushistory_id) + '/', safe='/') # get response response = self.client.get('/config/status/' + str(statushistory_id), follow=True) # compare self.assertRedirects(response, destination, status_code=301, target_status_code=200)
39.993651
147
0.658358
[ "Apache-2.0" ]
cclauss/dfirtrack
dfirtrack_config/tests/status/test_status_views.py
12,598
Python
import sys import getopt import os import subprocess import shutil import logging as log def Initialize(platform): print "Initializing Workspace" global workspace workspace = os.environ['WORKSPACE'] if platform == "windows": # Jenkins puts quotes in the path, which is wrong. Remove quotes. os.environ['PATH'] = os.environ['PATH'].replace('"','') return workspace def ParseArgs(argv): print "Parsing arguments for compile" try: opts, args = getopt.getopt(argv, "t:p:a:v", ["target=", "platform=", "arch=", "verbose","noclean"]) except getopt.GetoptError: print "ERROR: \n\t usage: python compile.py --target <target> --platform <windows|linux> --arch <arch> [--verbose] [--noclean]" return 2,"","","",True verbose = False cleanUp = True acceptedPlatforms = ['windows','linux'] for opt, arg in opts: if opt in ("-t", "--target"): target = arg elif opt in ("-p", "--platform"): if arg.lower() not in acceptedPlatforms: print "ERROR: " + arg + "not an accepted platform. Use windows or linux." sys.exit(2) platform = arg.lower() elif opt in ("-a", "--arch"): arch = arg elif opt in ("-v", "--verbose"): verbose = True elif opt in ("-c", "--noclean"): cleanUp = False if verbose: log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG) log.info("In verbose mode.") else: log.basicConfig(format="%(levelname)s: %(message)s") if target == "" or platform == "" or arch == "": # must specify target, project and arch log.error("Must specify target, project and arch") return 2,"","","",True return 0,target,platform,arch,cleanUp def SetupDirectories(target, arch, platform): log.info("Setting up directories") global rootdir global builddir global fullBuildDirPath rootdir = "build" if not os.path.isdir(rootdir): os.mkdir(rootdir) os.chdir(rootdir) builddir = "build-" + platform if platform == "windows": builddir = builddir + "-" + arch + "-" + target if os.path.isdir(builddir): shutil.rmtree(builddir) os.mkdir(builddir) os.chdir(builddir) fullbuilddirpath = workspace + "/" + rootdir + "/" + builddir return fullbuilddirpath def Cleanup(cleanUp,workspace): print "\n==================================================\n" print "Cleaning Up." print "\n==================================================\n" if cleanUp: os.chdir(workspace + "/" + rootdir) shutil.rmtree(builddir) os.chdir("..") shutil.rmtree(rootdir) log.shutdown() return 0
28.714286
135
0.563255
[ "MIT" ]
AaronRobinsonMSFT/coreclr
src/pal/automation/util.py
2,814
Python
#games module import Kabaddi.raider Kabaddi.raider.name_raider()
16.25
28
0.830769
[ "MIT" ]
Anancha/Programming-Techniques-using-Python
Chapter 05/Chap05_Example5.33.py
65
Python
import robocup import constants import main import math import skills.touch_ball import skills._kick import skills.pass_receive ## AngleReceive accepts a receive_point as a parameter and gets setup there to catch the ball # It transitions to the 'aligned' state once it's there within its error thresholds and is steady # Set its 'ball_kicked' property to True to tell it to dynamically update its position based on where # the ball is moving and attempt to catch it. # It will move to the 'completed' state if it catches the ball, otherwise it will go to 'failed'. # Kick is a single_robot_behavior, so no need to import both class AngleReceive(skills.pass_receive.PassReceive): def __init__(self): super().__init__( captureFunction=(lambda: skills.touch_ball.TouchBall())) self._target_point = None self.kick_power = 1 self.target_point = constants.Field.TheirGoalSegment.center() self.ball_kicked = False self.target_angle = 0 ## The point that the receiver should expect the ball to hit it's mouth # Default: constants.Field.TheirGoalSegment.center() @property def target_point(self): return self._target_point @target_point.setter def target_point(self, value): self._target_point = value self.recalculate() ## Returns an adjusted angle with account for ball speed # # First finds the rejection, which is the X component of the ball's velocity in the reference # frame of the robot, with the mouth facing the y axis. Then we calculate the angle required to # offset this rejection angle (if possible). def adjust_angle(self, target_angle, ball_angle=None, ball_speed=None): ball = main.ball() if ball_angle == None: ball_angle = (ball.vel).angle() if ball_speed == None: ball_speed = ball.vel.mag() angle_diff = target_angle - ball_angle rejection = math.sin(angle_diff) * ball_speed # The min/max is to bound the value by -1 and 1. adjust = math.asin(min(1, max(-1, rejection / constants.Robot.MaxKickSpeed))) return adjust + target_angle # calculates: # self._pass_line - the line from the ball along where we think we're going # self._target_pos - where the bot should be # self._angle_error - difference in where we're facing and where we want to face (in radians) # self._x_error # self._y_error def recalculate(self): # can't do squat if we don't know what we're supposed to do if self.receive_point == None or self.robot == None or self.target_point == None: return ball = main.ball() if self.ball_kicked: # when the ball's in motion, the line is based on the ball's velocity self._pass_line = robocup.Line(ball.pos, ball.pos + ball.vel * 10) # After kicking, apply angle calculations target_angle_rad = self.adjust_angle((self.target_point - self.robot.pos).angle()) # Removes angle adjustment # target_angle_rad = (self.target_point - self.robot.pos).angle() self._kick_line = robocup.Line(self.robot.pos, robocup.Point( self.robot.pos.x + math.cos(self.robot.angle) * 10, self.robot.pos.y + math.sin(self.robot.angle) * 10)) else: # if the ball hasn't been kicked yet, we assume it's going to go through the receive point self._pass_line = robocup.Line(ball.pos, self.receive_point) # Assume ball is kicked at max speed and is coming from the ball point to the location of our robot. Then average this with the target angle. target_angle_rad = self.adjust_angle( (self.target_point - self.robot.pos).angle(), (self.robot.pos - main.ball().pos).angle(), constants.Robot.MaxKickSpeed) # TODO make this faster by caching the .angle() part target_angle_rad = ( target_angle_rad + (self.target_point - self.robot.pos).angle()) / 2 self._kick_line = robocup.Line(self.receive_point, self.target_point) self._angle_facing = target_angle_rad self.target_angle = target_angle_rad angle_rad = self.robot.angle self._angle_error = target_angle_rad - angle_rad if self.ball_kicked: receive_before_adjust = self._pass_line.nearest_point( self.robot.pos) else: receive_before_adjust = self.receive_point # Make the receive point be the mouth, rather than the center of the robot. # Assumes mouth of robot is at the edge. self._target_pos = receive_before_adjust - robocup.Point( constants.Robot.Radius * math.cos(self.robot.angle), constants.Robot.Radius * math.sin(self.robot.angle)) # Code to provide slipback when receiving the ball # pass_line_dir = (self._pass_line.get_pt(1) - self._pass_line.get_pt(0)).normalized() # self._target_pos = actual_receive_point + pass_line_dir * constants.Robot.Radius # vector pointing down the pass line toward the kicker self._x_error = self._target_pos.x - self.robot.pos.x self._y_error = self._target_pos.y - self.robot.pos.y def execute_running(self): super().execute_running() self.recalculate() self.robot.face(self.robot.pos + robocup.Point( math.cos(self._angle_facing), math.sin(self._angle_facing))) if self._kick_line != None: main.system_state().draw_line(self._kick_line, constants.Colors.Red, "Shot") def execute_receiving(self): super().execute_receiving() self.ball_kicked = True # Kick the ball! self.robot.kick(self.kick_power) if self.target_point != None: main.system_state().draw_circle(self.target_point, 0.03, constants.Colors.Blue, "Target")
42.691781
153
0.636932
[ "Apache-2.0" ]
Alex-Gurung/robocup-software
soccer/gameplay/skills/angle_receive.py
6,233
Python
import argparse import functools import operator import os import numpy as np import tensorflow as tf from kungfu.tensorflow.v1.helpers.mnist import load_datasets from tensorflow.python.util import deprecation deprecation._PRINT_DEPRECATION_WARNINGS = False def parse_args(): p = argparse.ArgumentParser(description='Example.') p.add_argument('--data-dir', type=str, default='.', help='') p.add_argument('--model-dir', type=str, default='.', help='') p.add_argument('--kf-optimizer', type=str, default='sync_sgd', help='') p.add_argument('--batch-size', type=int, default=100, help='') p.add_argument('--num-epochs', type=int, default=1, help='') p.add_argument('--learning-rate', type=float, default=0.01, help='') return p.parse_args() def slp(x, logits): n = functools.reduce(operator.mul, [int(d) for d in x.shape[1:]], 1) output = tf.layers.dense(inputs=tf.reshape(x, [-1, n]), units=logits) return output, tf.argmax(output, axis=1) def model_fn(features, labels, mode): output, predictions = slp(features['x'], 10) loss = tf.losses.sparse_softmax_cross_entropy(tf.cast(labels, tf.int32), output) eval_metric_ops = { 'accuracy': tf.metrics.accuracy(labels=labels, predictions=predictions) } optimizer = tf.train.GradientDescentOptimizer(0.1) from kungfu.tensorflow.optimizers import SynchronousSGDOptimizer optimizer = SynchronousSGDOptimizer(optimizer) train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op, eval_metric_ops=eval_metric_ops) def input_fn(ds, batch_size, epochs=1, shuffle=True): features = {'x': ds.images} return tf.estimator.inputs.numpy_input_fn(x=features, y=ds.labels, batch_size=batch_size, num_epochs=epochs, shuffle=shuffle) def get_model_dir(args): from kungfu.python import uid x = uid() port = (x >> 16) & 0xffff version = x & 0xffff suffix = '%d.%d' % (port, version) return os.path.join(args.model_dir, suffix) MNIST_DATA_SIZE = 60000 def main(do_eval=True): args = parse_args() model_dir = get_model_dir(args) data = load_datasets(args.data_dir, normalize=True) classifier = tf.estimator.Estimator(model_fn, model_dir=model_dir) from kungfu.tensorflow.experimental.hook import ElasticHook hooks = [ElasticHook(args.batch_size, args.num_epochs, MNIST_DATA_SIZE)] classifier.train(input_fn(data.train, args.batch_size, epochs=args.num_epochs), hooks=hooks) if not do_eval: import time time.sleep(1) return results = classifier.evaluate(input_fn(data.test, args.batch_size, shuffle=False), hooks=[], steps=1) print('results: %s' % (results, )) if __name__ == '__main__': print('main started') main(False) print('main finished')
34.58
79
0.589358
[ "Apache-2.0" ]
DingtongHan/KungFu-1
examples/mnist_elastic_docker/mnist_slp_estimator.py
3,458
Python
from big_ol_pile_of_manim_imports import * import os import pyclbr class Shapes(Scene): #A few simple shapes #Python 2.7 version runs in Python 3.7 without changes def construct(self): #circle = Circle() #square = Square() line=Line(UP,DOWN) #line2=Line #triangle=Polygon(np.array([0,0,0]),np.array([1,1,0]),np.array([1,-1,0])) self.add(line) #self.play(ShowCreation(circle)) #self.play(FadeOut(circle)) #self.play(GrowFromCenter(square)) #self.play(Transform(square,triangle)) class MoreShapes(Scene): #A few more simple shapes #2.7 version runs in 3.7 without any changes #Note: I fixed my 'play command not found' issue by installing sox def construct(self): circle = Circle(color=PURPLE_A) square = Square(fill_color=GOLD_B, fill_opacity=1, color=GOLD_A) square.move_to(UP+LEFT) circle.surround(square) rectangle = Rectangle(height=2, width=3) ellipse=Ellipse(width=3, height=1, color=RED) ellipse.shift(2*DOWN+2*RIGHT) pointer = CurvedArrow(2*RIGHT,5*RIGHT,color=MAROON_C) arrow = Arrow(LEFT,UP) arrow.next_to(circle,DOWN+LEFT) rectangle.next_to(arrow,DOWN+LEFT) ring=Annulus(inner_radius=.5, outer_radius=1, color=BLUE) ring.next_to(ellipse, RIGHT) self.play(FadeIn(square)) self.play(Rotating(square),FadeIn(circle)) self.play(GrowArrow(arrow)) self.play(GrowFromCenter(rectangle), GrowFromCenter(ellipse), GrowFromCenter(ring)) self.add(pointer) class MovingShapes(Scene): #Show the difference between .shift() and .move_to def construct(self): circle=Circle(color=TEAL_A) circle.move_to(LEFT) square=Circle() square.move_to(LEFT+3*DOWN) self.play(GrowFromCenter(circle), GrowFromCenter(square), rate=5) self.play(ApplyMethod(circle.move_to,RIGHT), ApplyMethod(square.shift,RIGHT)) self.play(ApplyMethod(circle.move_to,RIGHT+UP), ApplyMethod(square.shift,RIGHT+UP)) self.play(ApplyMethod(circle.move_to,LEFT+UP), ApplyMethod(square.shift,LEFT+UP)) class AddingText(Scene): #Adding text on the screen def construct(self): my_first_text=TextMobject("Writing with manim is fun") second_line=TextMobject("and easy to do!") second_line.next_to(my_first_text,DOWN) third_line=TextMobject("for me and you!") third_line.next_to(my_first_text,DOWN) self.add(my_first_text, second_line) self.wait(2) self.play(Transform(second_line,third_line)) self.wait(2) second_line.shift(3*DOWN) self.play(ApplyMethod(my_first_text.shift,3*UP)) ###Try uncommenting the following### #self.play(ApplyMethod(second_line.move_to, LEFT_SIDE-2*LEFT)) #self.play(ApplyMethod(my_first_text.next_to,second_line)) class AddingMoreText(Scene): #Playing around with text properties def construct(self): quote = TextMobject("Imagination is more important than knowledge") quote.set_color(RED) quote.to_edge(UP) quote2 = TextMobject("A person who never made a mistake never tried anything new") quote2.set_color(YELLOW) author=TextMobject("-Albert Einstein") author.scale(0.75) author.next_to(quote.get_corner(DOWN+RIGHT),DOWN) self.add(quote) self.add(author) self.wait(2) self.play(Transform(quote,quote2),ApplyMethod(author.move_to,quote2.get_corner(DOWN+RIGHT)+DOWN+2*LEFT)) self.play(ApplyMethod(author.scale,1.5)) author.match_color(quote2) self.play(FadeOut(quote)) class RotateAndHighlight(Scene): #Rotation of text and highlighting with surrounding geometries def construct(self): square=Square(side_length=5,fill_color=YELLOW, fill_opacity=1) label=TextMobject("Text at an angle") label.bg=BackgroundRectangle(label,fill_opacity=1) label_group=VGroup(label.bg,label) #Order matters label_group.rotate(TAU/8) label2=TextMobject("Boxed text",color=BLACK) label2.bg=SurroundingRectangle(label2,color=BLUE,fill_color=RED, fill_opacity=.5) label2_group=VGroup(label2,label2.bg) label2_group.next_to(label_group,DOWN) label3=TextMobject("Rainbow") label3.scale(2) label3.set_color_by_gradient(RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE) label3.to_edge(DOWN) self.add(square) self.play(FadeIn(label_group)) self.play(FadeIn(label2_group)) self.play(FadeIn(label3)) class BasicEquations(Scene): #A short script showing how to use Latex commands def construct(self): eq1=TextMobject("$\\vec{X}_0 \\cdot \\vec{Y}_1 = 3$") eq1.shift(2*UP) eq2=TexMobject(r"\vec{F}_{net} = \sum_i \vec{F}_i") eq2.shift(2*DOWN) self.play(Write(eq1)) self.play(Write(eq2)) class ColoringEquations(Scene): #Grouping and coloring parts of equations def construct(self): line1=TexMobject(r"\text{The vector } \vec{F}_{net} \text{ is the net }",r"\text{force }",r"\text{on object of mass }") line2=TexMobject("m", "\\text{ and acceleration }", "\\vec{a}", ". ") sentence=VGroup(line1,line2) sentence.arrange_submobjects(DOWN, buff=MED_LARGE_BUFF) self.play(Write(sentence)) class UsingBraces(Scene): #Using braces to group text together def construct(self): eq1A = TextMobject("4x + 3y") eq1B = TextMobject("=") eq1C = TextMobject("0") eq2A = TextMobject("5x -2y") eq2B = TextMobject("=") eq2C = TextMobject("3") eq1B.next_to(eq1A,RIGHT) eq1C.next_to(eq1B,RIGHT) eq2A.shift(DOWN) eq2B.shift(DOWN) eq2C.shift(DOWN) eq2A.align_to(eq1A,LEFT) eq2B.align_to(eq1B,LEFT) eq2C.align_to(eq1C,LEFT) eq_group=VGroup(eq1A,eq2A) braces=Brace(eq_group,LEFT) eq_text = braces.get_text("A pair of equations") self.add(eq1A, eq1B, eq1C) self.add(eq2A, eq2B, eq2C) self.play(GrowFromCenter(braces),Write(eq_text)) class UsingBracesConcise(Scene): #A more concise block of code with all columns aligned def construct(self): eq1_text=["4","x","+","3","y","=","0"] eq2_text=["5","x","-","2","y","=","3"] eq1_mob=TexMobject(*eq1_text) eq2_mob=TexMobject(*eq2_text) eq1_mob.set_color_by_tex_to_color_map({ "x":RED_B, "y":GREEN_C }) eq2_mob.set_color_by_tex_to_color_map({ "x":RED_B, "y":GREEN_C }) for i,item in enumerate(eq2_mob): item.align_to(eq1_mob[i],LEFT) eq1=VGroup(*eq1_mob) eq2=VGroup(*eq2_mob) eq2.shift(DOWN) eq_group=VGroup(eq1,eq2) braces=Brace(eq_group,LEFT) eq_text = braces.get_text("A pair of equations") self.play(Write(eq1),Write(eq2)) self.play(GrowFromCenter(braces),Write(eq_text)) class PlotFunctions(GraphScene): CONFIG = { "x_min" : -10, "x_max" : 10.3, "y_min" : -1.5, "y_max" : 1.5, "graph_origin" : ORIGIN , "function_color" : RED , "axes_color" : GREEN, "x_labeled_nums" :range(-10,12,2), } def construct(self): self.setup_axes(animate=True) func_graph=self.get_graph(self.func_to_graph,self.function_color) func_graph2=self.get_graph(self.func_to_graph2) vert_line = self.get_vertical_line_to_graph(TAU,func_graph,color=YELLOW) graph_lab = self.get_graph_label(func_graph, label = "\\cos(x)") graph_lab2=self.get_graph_label(func_graph2,label = "\\sin(x)", x_val=-10, direction=UP/2) two_pi = TexMobject("x = 2 \\pi") label_coord = self.input_to_graph_point(TAU,func_graph) two_pi.next_to(label_coord,RIGHT+UP) self.play(ShowCreation(func_graph),ShowCreation(func_graph2)) self.play(ShowCreation(vert_line), ShowCreation(graph_lab), ShowCreation(graph_lab2),ShowCreation(two_pi)) def func_to_graph(self,x): return np.cos(x) def func_to_graph2(self,x): return np.sin(x) class ExampleApproximation(GraphScene): CONFIG = { "function" : lambda x : np.cos(x), "function_color" : BLUE, "taylor" : [lambda x: 1, lambda x: 1-x**2/2, lambda x: 1-x**2/math.factorial(2)+x**4/math.factorial(4), lambda x: 1-x**2/2+x**4/math.factorial(4)-x**6/math.factorial(6), lambda x: 1-x**2/math.factorial(2)+x**4/math.factorial(4)-x**6/math.factorial(6)+x**8/math.factorial(8), lambda x: 1-x**2/math.factorial(2)+x**4/math.factorial(4)-x**6/math.factorial(6)+x**8/math.factorial(8) - x**10/math.factorial(10)], "center_point" : 0, "approximation_color" : GREEN, "x_min" : -10, "x_max" : 10, "y_min" : -1, "y_max" : 1, "graph_origin" : ORIGIN , "x_labeled_nums" :range(-10,12,2), } def construct(self): self.setup_axes(animate=True) func_graph = self.get_graph( self.function, self.function_color, ) approx_graphs = [ self.get_graph( f, self.approximation_color ) for f in self.taylor ] term_num = [ TexMobject("n = " + str(n),aligned_edge=TOP) for n in range(0,8)] #[t.to_edge(BOTTOM,buff=SMALL_BUFF) for t in term_num] #term = TexMobject("") #term.to_edge(BOTTOM,buff=SMALL_BUFF) term = VectorizedPoint(3*DOWN) approx_graph = VectorizedPoint( self.input_to_graph_point(self.center_point, func_graph) ) self.play( ShowCreation(func_graph), ) for n,graph in enumerate(approx_graphs): self.play( Transform(approx_graph, graph, run_time = 2), Transform(term,term_num[n]) ) self.wait() class DrawAnAxis(Scene): CONFIG = { "plane_kwargs" : { "x_line_frequency" : 2, "y_line_frequency" :2 } } def construct(self): my_plane = NumberPlane(**self.plane_kwargs) my_plane.add(my_plane.get_axis_labels()) self.add(my_plane) #self.wait() class SimpleField(Scene): CONFIG = { "plane_kwargs" : { "color" : RED }, } def construct(self): plane = NumberPlane(**self.plane_kwargs) #Create axes and grid plane.add(plane.get_axis_labels()) #add x and y label self.add(plane) #Place grid on screen points = [x*RIGHT+y*UP for x in np.arange(-5,5,1) for y in np.arange(-5,5,1) ] #List of vectors pointing to each grid point vec_field = [] #Empty list to use in for loop for point in points: field = 0.5*RIGHT + 0.5*UP #Constant field up and to right result = Vector(field).shift(point) #Create vector and shift it to grid point vec_field.append(result) #Append to list draw_field = VGroup(*vec_field) #Pass list of vectors to create a VGroup self.play(ShowCreation(draw_field)) #Draw VGroup on screen class FieldWithAxes(Scene): CONFIG = { "plane_kwargs" : { "color" : RED_B }, "point_charge_loc" : 0.5*RIGHT-1.5*UP, } def construct(self): plane = NumberPlane(**self.plane_kwargs) plane.main_lines.fade(.9) plane.add(plane.get_axis_labels()) self.add(plane) field = VGroup(*[self.calc_field(x*RIGHT+y*UP) for x in np.arange(-9,9,1) for y in np.arange(-5,5,1) ]) self.play(ShowCreation(field)) def calc_field(self,point): #This calculates the field at a single point. x,y = point[:2] Rx,Ry = self.point_charge_loc[:2] r = math.sqrt((x-Rx)**2 + (y-Ry)**2) efield = (point - self.point_charge_loc)/r**3 #efield = np.array((-y,x,0))/math.sqrt(x**2+y**2) #Try one of these two fields #efield = np.array(( -2*(y%2)+1 , -2*(x%2)+1 , 0 ))/3 #Try one of these two fields return Vector(efield).shift(point) class ExampleThreeD(ThreeDScene): CONFIG = { "plane_kwargs" : { "color" : RED_B }, "point_charge_loc" : 0.5*RIGHT-1.5*UP, } def construct(self): #self.set_camera_position(0, -np.pi/2) #Old code plane = NumberPlane(**self.plane_kwargs) plane.main_lines.fade(.9) plane.add(plane.get_axis_labels()) self.add(plane) field2D = VGroup(*[self.calc_field2D(x*RIGHT+y*UP) for x in np.arange(-9,9,1) for y in np.arange(-5,5,1) ]) self.set_camera_orientation(phi=PI/3,gamma=PI/5) self.play(ShowCreation(field2D)) self.wait() self.move_camera(gamma=0,run_time=1) self.move_camera(phi=3/4*PI, theta=-PI/2) self.begin_ambient_camera_rotation(rate=0.1) self.wait(6) def calc_field2D(self,point): x,y = point[:2] Rx,Ry = self.point_charge_loc[:2] r = math.sqrt((x-Rx)**2 + (y-Ry)**2) efield = (point - self.point_charge_loc)/r**3 return Vector(efield).shift(point) class EFieldInThreeD(ThreeDScene): CONFIG = { "plane_kwargs" : { "color" : RED_B }, "point_charge_loc" : 0.5*RIGHT-1.5*UP, } def construct(self): plane = NumberPlane(**self.plane_kwargs) plane.main_lines.fade(.9) plane.add(plane.get_axis_labels()) self.add(plane) field2D = VGroup(*[self.calc_field2D(x*RIGHT+y*UP) for x in np.arange(-9,9,1) for y in np.arange(-5,5,1) ]) field3D = VGroup(*[self.calc_field3D(x*RIGHT+y*UP+z*OUT) for x in np.arange(-9,9,1) for y in np.arange(-5,5,1) for z in np.arange(-5,5,1)]) self.play(ShowCreation(field3D)) self.wait() self.move_camera(0.8*np.pi/2, -0.45*np.pi) self.begin_ambient_camera_rotation() self.wait(6) def calc_field2D(self,point): x,y = point[:2] Rx,Ry = self.point_charge_loc[:2] r = math.sqrt((x-Rx)**2 + (y-Ry)**2) efield = (point - self.point_charge_loc)/r**3 return Vector(efield).shift(point) def calc_field3D(self,point): x,y,z = point Rx,Ry,Rz = self.point_charge_loc r = math.sqrt((x-Rx)**2 + (y-Ry)**2+(z-Rz)**2) efield = (point - self.point_charge_loc)/r**3 #efield = np.array((-y,x,z))/math.sqrt(x**2+y**2+z**2) return Vector(efield).shift(point) class MovingCharges(Scene): CONFIG = { "plane_kwargs" : { "color" : RED_B }, "point_charge_loc" : 0.5*RIGHT-1.5*UP, } def construct(self): plane = NumberPlane(**self.plane_kwargs) plane.main_lines.fade(.9) plane.add(plane.get_axis_labels()) self.add(plane) field = VGroup(*[self.calc_field(x*RIGHT+y*UP) for x in np.arange(-9,9,1) for y in np.arange(-5,5,1) ]) self.field=field source_charge = self.Positron().move_to(self.point_charge_loc) self.play(FadeIn(source_charge)) self.play(ShowCreation(field)) self.moving_charge() def calc_field(self,point): x,y = point[:2] Rx,Ry = self.point_charge_loc[:2] r = math.sqrt((x-Rx)**2 + (y-Ry)**2) efield = (point - self.point_charge_loc)/r**3 return Vector(efield).shift(point) def moving_charge(self): numb_charges=4 possible_points = [v.get_start() for v in self.field] points = random.sample(possible_points, numb_charges) particles = VGroup(*[ self.Positron().move_to(point) for point in points ]) for particle in particles: particle.velocity = np.array((0,0,0)) self.play(FadeIn(particles)) self.moving_particles = particles self.add_foreground_mobjects(self.moving_particles ) self.always_continually_update = True self.wait(10) def field_at_point(self,point): x,y = point[:2] Rx,Ry = self.point_charge_loc[:2] r = math.sqrt((x-Rx)**2 + (y-Ry)**2) efield = (point - self.point_charge_loc)/r**3 return efield def continual_update(self, *args, **kwargs): if hasattr(self, "moving_particles"): dt = self.frame_duration for p in self.moving_particles: accel = self.field_at_point(p.get_center()) p.velocity = p.velocity + accel*dt p.shift(p.velocity*dt) class Positron(Circle): CONFIG = { "radius" : 0.2, "stroke_width" : 3, "color" : RED, "fill_color" : RED, "fill_opacity" : 0.5, } def __init__(self, **kwargs): Circle.__init__(self, **kwargs) plus = TexMobject("+") plus.scale(0.7) plus.move_to(self) self.add(plus) class FieldOfMovingCharge(Scene): CONFIG = { "plane_kwargs" : { "color" : RED_B }, "point_charge_start_loc" : 5.5*LEFT-1.5*UP, } def construct(self): plane = NumberPlane(**self.plane_kwargs) plane.main_lines.fade(.9) plane.add(plane.get_axis_labels()) self.add(plane) field = VGroup(*[self.create_vect_field(self.point_charge_start_loc,x*RIGHT+y*UP) for x in np.arange(-9,9,1) for y in np.arange(-5,5,1) ]) self.field=field self.source_charge = self.Positron().move_to(self.point_charge_start_loc) self.source_charge.velocity = np.array((1,0,0)) self.play(FadeIn(self.source_charge)) self.play(ShowCreation(field)) self.moving_charge() def create_vect_field(self,source_charge,observation_point): return Vector(self.calc_field(source_charge,observation_point)).shift(observation_point) def calc_field(self,source_point,observation_point): x,y,z = observation_point Rx,Ry,Rz = source_point r = math.sqrt((x-Rx)**2 + (y-Ry)**2 + (z-Rz)**2) if r<0.0000001: #Prevent divide by zero efield = np.array((0,0,0)) else: efield = (observation_point - source_point)/r**3 return efield def moving_charge(self): numb_charges=3 possible_points = [v.get_start() for v in self.field] points = random.sample(possible_points, numb_charges) particles = VGroup(self.source_charge, *[ self.Positron().move_to(point) for point in points ]) for particle in particles[1:]: particle.velocity = np.array((0,0,0)) self.play(FadeIn(particles[1:])) self.moving_particles = particles self.add_foreground_mobjects(self.moving_particles ) self.always_continually_update = True self.wait(10) def continual_update(self, *args, **kwargs): Scene.continual_update(self, *args, **kwargs) if hasattr(self, "moving_particles"): dt = self.frame_duration for v in self.field: field_vect=np.zeros(3) for p in self.moving_particles: field_vect = field_vect + self.calc_field(p.get_center(), v.get_start()) v.put_start_and_end_on(v.get_start(), field_vect+v.get_start()) for p in self.moving_particles: accel = np.zeros(3) p.velocity = p.velocity + accel*dt p.shift(p.velocity*dt) class Positron(Circle): CONFIG = { "radius" : 0.2, "stroke_width" : 3, "color" : RED, "fill_color" : RED, "fill_opacity" : 0.5, } def __init__(self, **kwargs): Circle.__init__(self, **kwargs) plus = TexMobject("+") plus.scale(0.7) plus.move_to(self) self.add(plus) HEAD_INDEX = 0 BODY_INDEX = 1 ARMS_INDEX = 2 LEGS_INDEX = 3 class StickMan(SVGMobject): CONFIG = { "color" : BLUE_E, "file_name_prefix": "stick_man", "stroke_width" : 2, "stroke_color" : WHITE, "fill_opacity" : 1.0, "height" : 3, } def __init__(self, mode = "plain", **kwargs): digest_config(self, kwargs) self.mode = mode self.parts_named = False try: svg_file = os.path.join( SVG_IMAGE_DIR, "%s_%s.svg" % (self.file_name_prefix, mode) ) SVGMobject.__init__(self, file_name=svg_file, **kwargs) except: warnings.warn("No %s design with mode %s" % (self.file_name_prefix, mode)) svg_file = os.path.join( SVG_IMAGE_DIR, "stick_man_plain.svg", ) SVGMobject.__init__(self, mode="plain", file_name=svg_file, **kwargs) def name_parts(self): self.head = self.submobjects[HEAD_INDEX] self.body = self.submobjects[BODY_INDEX] self.arms = self.submobjects[ARMS_INDEX] self.legs = self.submobjects[LEGS_INDEX] self.parts_named = True def init_colors(self): SVGMobject.init_colors(self) if not self.parts_named: self.name_parts() self.head.set_fill(self.color, opacity = 1) self.body.set_fill(RED, opacity = 1) self.arms.set_fill(YELLOW, opacity = 1) self.legs.set_fill(BLUE, opacity = 1) return self class Waving(Scene): def construct(self): start_man = StickMan() plain_man = StickMan() waving_man = StickMan("wave") self.add(start_man) self.wait() self.play(Transform(start_man,waving_man)) self.play(Transform(start_man,plain_man)) self.wait() class CirclesAndSquares(SVGMobject): CONFIG = { "color" : BLUE_E, "file_name_prefix": "circles_and_squares", "stroke_width" : 2, "stroke_color" : WHITE, "fill_opacity" : 1.0, "height" : 3, "start_corner" : None, "circle_index" : 0, "line1_index" :1, "line2_index" : 2, "square1_index" : 3, "square2_index" : 4, } def __init__(self, mode = "plain", **kwargs): digest_config(self, kwargs) self.mode = mode self.parts_named = False try: svg_file = os.path.join( SVG_IMAGE_DIR, "%s_%s.svg" % (self.file_name_prefix, mode) ) SVGMobject.__init__(self, file_name=svg_file, **kwargs) except: warnings.warn("No %s design with mode %s" % (self.file_name_prefix, mode)) svg_file = os.path.join( SVG_IMAGE_DIR, "circles_and_squares_plain.svg", ) SVGMobject.__init__(self, mode="plain", file_name=svg_file, **kwargs) def name_parts(self): self.circle = self.submobjects[self.circle_index] self.line1 = self.submobjects[self.line1_index] self.line2 = self.submobjects[self.line2_index] self.square1 = self.submobjects[self.square1_index] self.square2 = self.submobjects[self.square2_index] self.parts_named = True def init_colors(self): SVGMobject.init_colors(self) self.name_parts() self.circle.set_fill(RED, opacity = 1) self.line1.set_fill(self.color, opacity = 0) self.line2.set_fill(self.color, opacity = 0) self.square1.set_fill(GREEN, opacity = 1) self.square2.set_fill(BLUE, opacity = 1) return self class SVGCircleAndSquare(Scene): def construct(self): thingy = CirclesAndSquares() self.add(thingy) self.wait() if __name__ == "__main__": # Call this file at command line to make sure all scenes work with version of manim # type "python manim_tutorial_P37.py" at command line to run all scenes in this file #Must have "import os" and "import pyclbr" at start of file to use this ###Using Python class browser to determine which classes are defined in this file module_name = 'manim_tutorial_P37' #Name of current file module_info = pyclbr.readmodule(module_name) for item in module_info.values(): if item.module==module_name: print(item.name) os.system("python -m manim manim_tutorial_P37.py %s -l" % item.name) #Does not play files
33.250333
245
0.593528
[ "MIT" ]
CadenScharpf/manim-cs
examples/tutorial.py
24,971
Python
#!/usr/bin/env python # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Run this script from the root of the repository to update all translations from transifex. It will do the following automatically: - fetch all translations using the tx tool - post-process them into valid and committable format - remove invalid control characters - remove location tags (makes diffs less noisy) TODO: - auto-add new translations to the build system according to the translation process ''' from __future__ import division, print_function import subprocess import re import sys import os import io import xml.etree.ElementTree as ET # Name of transifex tool TX = 'tx' # Name of source language file SOURCE_LANG = 'elli_en.ts' # Directory with locale files LOCALE_DIR = 'src/qt/locale' # Minimum number of messages for translation to be considered at all MIN_NUM_MESSAGES = 10 def check_at_repository_root(): if not os.path.exists('.git'): print('No .git directory found') print('Execute this script at the root of the repository', file=sys.stderr) exit(1) def fetch_all_translations(): if subprocess.call([TX, 'pull', '-f', '-a']): print('Error while fetching translations', file=sys.stderr) exit(1) def find_format_specifiers(s): '''Find all format specifiers in a string.''' pos = 0 specifiers = [] while True: percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifier') pos = percent+2 return specifiers def split_format_specifiers(specifiers): '''Split format specifiers between numeric (Qt) and others (strprintf)''' numeric = [] other = [] for s in specifiers: if s in {'1','2','3','4','5','6','7','8','9'}: numeric.append(s) else: other.append(s) # If both numeric format specifiers and "others" are used, assume we're dealing # with a Qt-formatted message. In the case of Qt formatting (see https://doc.qt.io/qt-5/qstring.html#arg) # only numeric formats are replaced at all. This means "(percentage: %1%)" is valid, without needing # any kind of escaping that would be necessary for strprintf. Without this, this function # would wrongly detect '%)' as a printf format specifier. if numeric: other = [] # numeric (Qt) can be present in any order, others (strprintf) must be in specified order return set(numeric),other def sanitize_string(s): '''Sanitize string for printing''' return s.replace('\n',' ') def check_format_specifiers(source, translation, errors, numerus): source_f = split_format_specifiers(find_format_specifiers(source)) # assert that no source messages contain both Qt and strprintf format specifiers # if this fails, go change the source as this is hacky and confusing! assert(not(source_f[0] and source_f[1])) try: translation_f = split_format_specifiers(find_format_specifiers(translation)) except IndexError: errors.append("Parse error in translation for '%s': '%s'" % (sanitize_string(source), sanitize_string(translation))) return False else: if source_f != translation_f: if numerus and source_f == (set(), ['n']) and translation_f == (set(), []) and translation.find('%') == -1: # Allow numerus translations to omit %n specifier (usually when it only has one possible value) return True errors.append("Mismatch between '%s' and '%s'" % (sanitize_string(source), sanitize_string(translation))) return False return True def all_ts_files(suffix=''): for filename in os.listdir(LOCALE_DIR): # process only language files, and do not process source language if not filename.endswith('.ts'+suffix) or filename == SOURCE_LANG+suffix: continue if suffix: # remove provided suffix filename = filename[0:-len(suffix)] filepath = os.path.join(LOCALE_DIR, filename) yield(filename, filepath) FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]') def remove_invalid_characters(s): '''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s) # Override cdata escape function to make our output match Qt's (optional, just for cleaner diffs for # comparison, disable by default) _orig_escape_cdata = None def escape_cdata(text): text = _orig_escape_cdata(text) text = text.replace("'", '&apos;') text = text.replace('"', '&quot;') return text def postprocess_translations(reduce_diff_hacks=False): print('Checking and postprocessing...') if reduce_diff_hacks: global _orig_escape_cdata _orig_escape_cdata = ET._escape_cdata ET._escape_cdata = escape_cdata for (filename,filepath) in all_ts_files(): os.rename(filepath, filepath+'.orig') have_errors = False for (filename,filepath) in all_ts_files('.orig'): # pre-fixups to cope with transifex output parser = ET.XMLParser(encoding='utf-8') # need to override encoding because 'utf8' is not understood only 'utf-8' with open(filepath + '.orig', 'rb') as f: data = f.read() # remove control characters; this must be done over the entire file otherwise the XML parser will fail data = remove_invalid_characters(data) tree = ET.parse(io.BytesIO(data), parser=parser) # iterate over all messages in file root = tree.getroot() for context in root.findall('context'): for message in context.findall('message'): numerus = message.get('numerus') == 'yes' source = message.find('source').text translation_node = message.find('translation') # pick all numerusforms if numerus: translations = [i.text for i in translation_node.findall('numerusform')] else: translations = [translation_node.text] for translation in translations: if translation is None: continue errors = [] valid = check_format_specifiers(source, translation, errors, numerus) for error in errors: print('%s: %s' % (filename, error)) if not valid: # set type to unfinished and clear string if invalid translation_node.clear() translation_node.set('type', 'unfinished') have_errors = True # Remove location tags for location in message.findall('location'): message.remove(location) # Remove entire message if it is an unfinished translation if translation_node.get('type') == 'unfinished': context.remove(message) # check if document is (virtually) empty, and remove it if so num_messages = 0 for context in root.findall('context'): for message in context.findall('message'): num_messages += 1 if num_messages < MIN_NUM_MESSAGES: print('Removing %s, as it contains only %i messages' % (filepath, num_messages)) continue # write fixed-up tree # if diff reduction requested, replace some XML to 'sanitize' to qt formatting if reduce_diff_hacks: out = io.BytesIO() tree.write(out, encoding='utf-8') out = out.getvalue() out = out.replace(b' />', b'/>') with open(filepath, 'wb') as f: f.write(out) else: tree.write(filepath, encoding='utf-8') return have_errors if __name__ == '__main__': check_at_repository_root() fetch_all_translations() postprocess_translations()
38.620853
124
0.63382
[ "MIT" ]
ALLMINER/elli
contrib/devtools/update-translations.py
8,149
Python
# Copyright 2020 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for wipeout service.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules import datetime import logging from constants import constants from core.domain import auth_services from core.domain import collection_services from core.domain import email_manager from core.domain import exp_services from core.domain import question_domain from core.domain import question_services from core.domain import rights_domain from core.domain import rights_manager from core.domain import skill_domain from core.domain import skill_services from core.domain import story_domain from core.domain import story_services from core.domain import subtopic_page_domain from core.domain import subtopic_page_services from core.domain import topic_domain from core.domain import topic_services from core.domain import user_domain from core.domain import user_services from core.domain import wipeout_domain from core.domain import wipeout_service from core.platform import models from core.tests import test_utils import feconf import python_utils ( auth_models, base_models, collection_models, config_models, email_models, exp_models, feedback_models, improvements_models, question_models, skill_models, story_models, subtopic_models, suggestion_models, topic_models, user_models ) = models.Registry.import_models([ models.NAMES.auth, models.NAMES.base_model, models.NAMES.collection, models.NAMES.config, models.NAMES.email, models.NAMES.exploration, models.NAMES.feedback, models.NAMES.improvements, models.NAMES.question, models.NAMES.skill, models.NAMES.story, models.NAMES.subtopic, models.NAMES.suggestion, models.NAMES.topic, models.NAMES.user ]) datastore_services = models.Registry.import_datastore_services() class WipeoutServiceHelpersTests(test_utils.GenericTestBase): """Provides testing of the pre-deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' def setUp(self): super(WipeoutServiceHelpersTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_1_role = user_services.get_user_settings(self.user_1_id).role self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.user_2_role = user_services.get_user_settings(self.user_2_id).role def test_gets_pending_deletion_request(self): wipeout_service.save_pending_deletion_requests( [ wipeout_domain.PendingDeletionRequest.create_default( self.user_1_id, self.USER_1_EMAIL, self.user_1_role) ] ) pending_deletion_request = ( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertEqual(pending_deletion_request.user_id, self.user_1_id) self.assertEqual(pending_deletion_request.email, self.USER_1_EMAIL) self.assertEqual(pending_deletion_request.deletion_complete, False) self.assertEqual( pending_deletion_request.pseudonymizable_entity_mappings, {}) def test_get_number_of_pending_deletion_requests_returns_correct_number( self): number_of_pending_deletion_requests = ( wipeout_service.get_number_of_pending_deletion_requests()) self.assertEqual(number_of_pending_deletion_requests, 0) wipeout_service.save_pending_deletion_requests( [ wipeout_domain.PendingDeletionRequest.create_default( self.user_1_id, self.USER_1_EMAIL, self.user_1_role), wipeout_domain.PendingDeletionRequest.create_default( self.user_2_id, self.USER_2_EMAIL, self.user_2_role) ] ) number_of_pending_deletion_requests = ( wipeout_service.get_number_of_pending_deletion_requests()) self.assertEqual(number_of_pending_deletion_requests, 2) def test_saves_pending_deletion_request_when_new(self): pending_deletion_request = ( wipeout_domain.PendingDeletionRequest.create_default( self.user_1_id, self.USER_1_EMAIL, self.user_1_role)) wipeout_service.save_pending_deletion_requests( [pending_deletion_request]) pending_deletion_request_model = ( user_models.PendingDeletionRequestModel.get_by_id(self.user_1_id)) self.assertEqual(pending_deletion_request_model.id, self.user_1_id) self.assertEqual( pending_deletion_request_model.email, self.USER_1_EMAIL) self.assertEqual( pending_deletion_request_model.deletion_complete, False) self.assertEqual( pending_deletion_request_model.pseudonymizable_entity_mappings, {}) def test_saves_pending_deletion_request_when_already_existing(self): pending_deletion_request_model_old = ( user_models.PendingDeletionRequestModel( id=self.user_1_id, email=self.USER_1_EMAIL, role=self.user_1_role, deletion_complete=False, pseudonymizable_entity_mappings={} ) ) pending_deletion_request_model_old.put() pending_deletion_request = ( wipeout_domain.PendingDeletionRequest.create_default( self.user_1_id, self.USER_1_EMAIL, self.user_1_role) ) pending_deletion_request.deletion_complete = True pending_deletion_request.pseudonymizable_entity_mappings = { 'story': {'story_id': 'user_id'} } wipeout_service.save_pending_deletion_requests( [pending_deletion_request]) pending_deletion_request_model_new = ( user_models.PendingDeletionRequestModel.get_by_id(self.user_1_id)) self.assertEqual(pending_deletion_request_model_new.id, self.user_1_id) self.assertEqual( pending_deletion_request_model_new.email, self.USER_1_EMAIL) self.assertEqual( pending_deletion_request_model_new.deletion_complete, True) self.assertEqual( pending_deletion_request_model_new.pseudonymizable_entity_mappings, {'story': {'story_id': 'user_id'}}) self.assertEqual( pending_deletion_request_model_old.created_on, pending_deletion_request_model_new.created_on) class WipeoutServicePreDeleteTests(test_utils.GenericTestBase): """Provides testing of the pre-deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' USER_3_EMAIL = '[email protected]' USER_3_USERNAME = 'username3' def setUp(self): super(WipeoutServicePreDeleteTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.set_user_role(self.USER_1_USERNAME, feconf.ROLE_ID_TOPIC_MANAGER) self.user_1_auth_id = self.get_auth_id_from_email(self.USER_1_EMAIL) self.user_1_actions = user_services.UserActionsInfo(self.user_1_id) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.user_1_auth_id = self.get_auth_id_from_email(self.USER_1_EMAIL) user_data_dict = { 'schema_version': 1, 'display_alias': 'display_alias', 'pin': '12345', 'preferred_language_codes': [constants.DEFAULT_LANGUAGE_CODE], 'preferred_site_language_code': None, 'preferred_audio_language_code': None, 'user_id': self.user_1_id, } new_user_data_dict = { 'schema_version': 1, 'display_alias': 'display_alias3', 'pin': '12345', 'preferred_language_codes': [constants.DEFAULT_LANGUAGE_CODE], 'preferred_site_language_code': None, 'preferred_audio_language_code': None, 'user_id': None, } self.modifiable_user_data = ( user_domain.ModifiableUserData.from_raw_dict(user_data_dict)) self.modifiable_new_user_data = ( user_domain.ModifiableUserData.from_raw_dict(new_user_data_dict)) user_services.update_multiple_users_data( [self.modifiable_user_data]) self.modifiable_user_data.display_alias = 'name' self.modifiable_user_data.pin = '123' self.profile_user_id = user_services.create_new_profiles( self.user_1_auth_id, self.USER_1_EMAIL, [self.modifiable_new_user_data] )[0].user_id def tearDown(self): pending_deletion_request_models = ( user_models.PendingDeletionRequestModel.get_all()) for pending_deletion_request_model in pending_deletion_request_models: pending_deletion_request = ( wipeout_service.get_pending_deletion_request( pending_deletion_request_model.id)) self.assertEqual( wipeout_service.run_user_deletion(pending_deletion_request), wipeout_domain.USER_DELETION_SUCCESS) self.assertEqual( wipeout_service.run_user_deletion_completion( pending_deletion_request), wipeout_domain.USER_VERIFICATION_SUCCESS) def test_pre_delete_user_email_subscriptions(self): email_preferences = user_services.get_email_preferences(self.user_1_id) self.assertEqual( email_preferences.can_receive_email_updates, feconf.DEFAULT_EMAIL_UPDATES_PREFERENCE) self.assertEqual( email_preferences.can_receive_editor_role_email, feconf.DEFAULT_EDITOR_ROLE_EMAIL_PREFERENCE) self.assertEqual( email_preferences.can_receive_feedback_message_email, feconf.DEFAULT_FEEDBACK_MESSAGE_EMAIL_PREFERENCE) self.assertEqual( email_preferences.can_receive_subscription_email, feconf.DEFAULT_SUBSCRIPTION_EMAIL_PREFERENCE) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() email_preferences = user_services.get_email_preferences(self.user_1_id) self.assertFalse(email_preferences.can_receive_email_updates) self.assertFalse(email_preferences.can_receive_editor_role_email) self.assertFalse(email_preferences.can_receive_feedback_message_email) self.assertFalse(email_preferences.can_receive_subscription_email) def test_pre_delete_profile_users_works_correctly(self): user_settings = user_services.get_user_settings(self.profile_user_id) self.assertFalse(user_settings.deleted) self.assertFalse(user_settings.deleted) wipeout_service.pre_delete_user(self.profile_user_id) self.process_and_flush_pending_tasks() user_settings = user_models.UserSettingsModel.get_by_id( self.profile_user_id) self.assertTrue(user_settings.deleted) user_auth_details = ( auth_models.UserAuthDetailsModel.get_by_id(self.profile_user_id)) self.assertTrue(user_auth_details.deleted) def test_pre_delete_user_for_full_user_also_deletes_all_profiles(self): user_settings = user_services.get_user_settings(self.user_1_id) self.assertFalse(user_settings.deleted) profile_user_settings = user_services.get_user_settings( self.profile_user_id) self.assertFalse(profile_user_settings.deleted) profile_auth_details = user_services.get_user_settings( self.profile_user_id) self.assertFalse(profile_auth_details.deleted) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() user_settings = user_models.UserSettingsModel.get_by_id(self.user_1_id) self.assertTrue(user_settings.deleted) user_auth_details = ( auth_models.UserAuthDetailsModel.get_by_id(self.profile_user_id)) self.assertTrue(user_auth_details.deleted) profile_user_settings = user_models.UserSettingsModel.get_by_id( self.profile_user_id) self.assertTrue(profile_user_settings.deleted) profile_auth_details = ( auth_models.UserAuthDetailsModel.get_by_id(self.profile_user_id)) self.assertTrue(profile_auth_details.deleted) def test_pre_delete_user_without_activities_works_correctly(self): user_models.UserSubscriptionsModel( id=self.user_1_id, exploration_ids=[], collection_ids=[] ).put() user_settings = user_services.get_user_settings(self.user_1_id) self.assertFalse(user_settings.deleted) user_auth_details = auth_models.UserAuthDetailsModel.get(self.user_1_id) self.assertFalse(user_auth_details.deleted) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() user_settings = user_models.UserSettingsModel.get_by_id(self.user_1_id) self.assertTrue(user_settings.deleted) self.assertIsNone( auth_services.get_auth_id_from_user_id(self.user_1_id)) pending_deletion_model = ( user_models.PendingDeletionRequestModel.get_by_id(self.user_1_id)) self.assertIsNotNone(pending_deletion_model) def test_pre_delete_username_is_not_saved_for_user_younger_than_week(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() pending_deletion_request = ( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertIsNone( pending_deletion_request.normalized_long_term_username) def test_pre_delete_username_is_saved_for_user_older_than_week(self): date_10_days_ago = ( datetime.datetime.utcnow() - datetime.timedelta(days=10)) with self.mock_datetime_utcnow(date_10_days_ago): self.signup(self.USER_3_EMAIL, self.USER_3_USERNAME) user_3_id = self.get_user_id_from_email(self.USER_3_EMAIL) wipeout_service.pre_delete_user(user_3_id) self.process_and_flush_pending_tasks() pending_deletion_request = ( wipeout_service.get_pending_deletion_request(user_3_id)) self.assertEqual( pending_deletion_request.normalized_long_term_username, self.USER_3_USERNAME) def test_pre_delete_user_with_activities_multiple_owners(self): user_services.update_user_role( self.user_1_id, feconf.ROLE_ID_COLLECTION_EDITOR) self.save_new_valid_exploration('exp_id', self.user_1_id) rights_manager.assign_role_for_exploration( self.user_1_actions, 'exp_id', self.user_2_id, rights_domain.ROLE_OWNER) self.save_new_valid_collection( 'col_id', self.user_1_id, exploration_id='exp_id') rights_manager.assign_role_for_collection( self.user_1_actions, 'col_id', self.user_2_id, rights_domain.ROLE_OWNER) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() pending_deletion_model = ( user_models.PendingDeletionRequestModel.get_by_id(self.user_1_id)) self.assertIsNotNone(pending_deletion_model) def test_pre_delete_user_collection_is_marked_deleted(self): self.save_new_valid_collection('col_id', self.user_1_id) collection_model = collection_models.CollectionModel.get_by_id('col_id') self.assertFalse(collection_model.deleted) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() self.assertIsNone(collection_models.CollectionModel.get_by_id('col_id')) def test_pre_delete_user_exploration_is_marked_deleted(self): self.save_new_valid_exploration('exp_id', self.user_1_id) exp_model = exp_models.ExplorationModel.get_by_id('exp_id') self.assertFalse(exp_model.deleted) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() self.assertIsNone(exp_models.ExplorationModel.get_by_id('exp_id')) def test_pre_delete_user_collection_ownership_is_released(self): self.save_new_valid_collection('col_id', self.user_1_id) self.publish_collection(self.user_1_id, 'col_id') rights_manager.assign_role_for_collection( user_services.get_system_user(), 'col_id', self.user_2_id, feconf.ROLE_EDITOR) collection_summary_model = ( collection_models.CollectionSummaryModel.get_by_id('col_id')) self.assertFalse(collection_summary_model.community_owned) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() collection_summary_model = ( collection_models.CollectionSummaryModel.get_by_id('col_id')) self.assertTrue(collection_summary_model.community_owned) def test_pre_delete_user_exploration_ownership_is_released(self): self.save_new_valid_exploration('exp_id', self.user_1_id) self.publish_exploration(self.user_1_id, 'exp_id') rights_manager.assign_role_for_exploration( user_services.get_system_user(), 'exp_id', self.user_2_id, feconf.ROLE_EDITOR) exp_summary_model = exp_models.ExpSummaryModel.get_by_id('exp_id') self.assertFalse(exp_summary_model.community_owned) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() exp_summary_model = exp_models.ExpSummaryModel.get_by_id('exp_id') self.assertTrue(exp_summary_model.community_owned) def test_pre_delete_user_collection_user_is_deassigned(self): self.save_new_valid_collection('col_id', self.user_1_id) rights_manager.assign_role_for_collection( user_services.get_system_user(), 'col_id', self.user_2_id, feconf.ROLE_EDITOR) collection_summary_model = ( collection_models.CollectionSummaryModel.get_by_id('col_id')) self.assertEqual(collection_summary_model.editor_ids, [self.user_2_id]) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() collection_summary_model = ( collection_models.CollectionSummaryModel.get_by_id('col_id')) self.assertEqual(collection_summary_model.editor_ids, []) def test_pre_delete_user_exploration_user_is_deassigned(self): self.save_new_valid_exploration('exp_id', self.user_1_id) rights_manager.assign_role_for_exploration( user_services.get_system_user(), 'exp_id', self.user_2_id, feconf.ROLE_EDITOR) exp_summary_model = exp_models.ExpSummaryModel.get_by_id('exp_id') self.assertEqual(exp_summary_model.editor_ids, [self.user_2_id]) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() exp_summary_model = exp_models.ExpSummaryModel.get_by_id('exp_id') self.assertEqual(exp_summary_model.editor_ids, []) def test_pre_delete_user_user_is_deassigned_from_topics(self): self.save_new_topic('top_id', self.user_1_id) topic_services.assign_role( user_services.get_system_user(), self.user_1_actions, feconf.ROLE_MANAGER, 'top_id') top_rights_model = topic_models.TopicRightsModel.get_by_id('top_id') self.assertEqual(top_rights_model.manager_ids, [self.user_1_id]) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() top_rights_model = topic_models.TopicRightsModel.get_by_id('top_id') self.assertEqual(top_rights_model.manager_ids, []) class WipeoutServiceRunFunctionsTests(test_utils.GenericTestBase): """Provides testing of the pre-deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' def setUp(self): super(WipeoutServiceRunFunctionsTests, self).setUp() date_10_days_ago = ( datetime.datetime.utcnow() - datetime.timedelta(days=10)) with self.mock_datetime_utcnow(date_10_days_ago): self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.set_user_role(self.USER_1_USERNAME, feconf.ROLE_ID_TOPIC_MANAGER) self.user_1_actions = user_services.UserActionsInfo(self.user_1_id) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() self.pending_deletion_request = ( wipeout_service.get_pending_deletion_request(self.user_1_id)) def test_run_user_deletion_with_user_not_deleted(self): self.assertEqual( wipeout_service.run_user_deletion(self.pending_deletion_request), wipeout_domain.USER_DELETION_SUCCESS ) def test_run_user_deletion_with_user_already_deleted(self): wipeout_service.run_user_deletion(self.pending_deletion_request) self.assertEqual( wipeout_service.run_user_deletion(self.pending_deletion_request), wipeout_domain.USER_DELETION_ALREADY_DONE ) def test_run_user_deletion_completion_with_user_not_yet_deleted(self): self.assertEqual( wipeout_service.run_user_deletion_completion( self.pending_deletion_request), wipeout_domain.USER_VERIFICATION_NOT_DELETED) self.assertIsNotNone( user_models.UserSettingsModel.get_by_id(self.user_1_id)) self.assertIsNotNone( user_models.PendingDeletionRequestModel.get_by_id(self.user_1_id)) def test_run_user_deletion_completion_with_user_properly_deleted(self): wipeout_service.run_user_deletion(self.pending_deletion_request) self.assertEqual( wipeout_service.run_user_deletion_completion( self.pending_deletion_request), wipeout_domain.USER_VERIFICATION_SUCCESS ) self.assertIsNotNone( user_models.DeletedUserModel.get_by_id(self.user_1_id)) self.assertTrue(user_services.is_username_taken(self.USER_1_USERNAME)) self.assertIsNone( user_models.UserSettingsModel.get_by_id(self.user_1_id)) self.assertIsNone( user_models.PendingDeletionRequestModel.get_by_id(self.user_1_id)) # Pre-deleted auth associations will return None. self.assertIsNone( auth_services.get_auth_id_from_user_id(self.user_1_id)) self.assertTrue( auth_services.verify_external_auth_associations_are_deleted( self.user_1_id)) def test_run_user_deletion_completion_with_user_wrongly_deleted(self): wipeout_service.run_user_deletion(self.pending_deletion_request) user_models.CompletedActivitiesModel( id=self.user_1_id, exploration_ids=[], collection_ids=[] ).put() email_content = ( 'The Wipeout process failed for the user with ID \'%s\' ' 'and email \'%s\'.' % (self.user_1_id, self.USER_1_EMAIL) ) send_email_swap = self.swap_with_checks( email_manager, 'send_mail_to_admin', lambda x, y: None, expected_args=[('WIPEOUT: Account deletion failed', email_content)] ) with send_email_swap: self.assertEqual( wipeout_service.run_user_deletion_completion( self.pending_deletion_request), wipeout_domain.USER_VERIFICATION_FAILURE) self.assertIsNotNone( user_models.UserSettingsModel.get_by_id(self.user_1_id)) self.assertIsNotNone( auth_models.UserAuthDetailsModel.get_by_id(self.user_1_id)) self.assertIsNotNone( user_models.PendingDeletionRequestModel.get_by_id(self.user_1_id)) class WipeoutServiceDeleteConfigModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' CONFIG_1_ID = 'config_1_id' CONFIG_2_ID = 'config_2_id' def setUp(self): super(WipeoutServiceDeleteConfigModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) config_models.ConfigPropertyModel( id=self.CONFIG_1_ID, value='a' ).commit(self.user_1_id, [{'cmd': 'command'}]) wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_one_config_property_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. config_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.config] ) metadata_model = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-1' % self.CONFIG_1_ID) ) self.assertEqual( metadata_model.committer_id, config_mappings[self.CONFIG_1_ID]) def test_one_config_property_when_the_deletion_is_repeated_is_pseudonymized( self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Return metadata model to the original user ID. metadata_model = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-1' % self.CONFIG_1_ID) ) metadata_model.committer_id = self.user_1_id metadata_model.put_for_human() # Run the user deletion again. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify that both the commit and the metadata have the same # pseudonymous user ID. config_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.config] ) self.assertEqual( metadata_model.committer_id, config_mappings[self.CONFIG_1_ID]) def test_multiple_config_properties_are_pseudonymized(self): config_models.ConfigPropertyModel( id=self.CONFIG_2_ID, value='b' ).commit(self.user_1_id, [{'cmd': 'command'}]) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) config_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.config] ) metadata_model_1 = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-1' % self.CONFIG_1_ID) ) self.assertEqual( metadata_model_1.committer_id, config_mappings[self.CONFIG_1_ID]) metadata_model_2 = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-1' % self.CONFIG_2_ID) ) self.assertEqual( metadata_model_2.committer_id, config_mappings[self.CONFIG_2_ID]) def test_multiple_config_properties_with_multiple_users_are_pseudonymized( self): config_models.ConfigPropertyModel( id=self.CONFIG_2_ID, value='b' ).commit(self.user_2_id, [{'cmd': 'command'}]) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. config_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.config] ) metadata_model_1 = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-1' % self.CONFIG_1_ID) ) self.assertEqual( metadata_model_1.committer_id, config_mappings_1[self.CONFIG_1_ID]) # Verify second user is not yet deleted. metadata_model_2 = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-1' % self.CONFIG_2_ID) ) self.assertEqual( metadata_model_2.committer_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. config_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.config] ) metadata_model_3 = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-1' % self.CONFIG_2_ID) ) self.assertEqual( metadata_model_3.committer_id, config_mappings_2[self.CONFIG_2_ID]) def test_one_config_property_with_multiple_users_is_pseudonymized(self): config_models.ConfigPropertyModel.get_by_id( self.CONFIG_1_ID ).commit(self.user_2_id, [{'cmd': 'command'}]) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. config_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.config] ) metadata_model_1 = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-1' % self.CONFIG_1_ID) ) self.assertEqual( metadata_model_1.committer_id, config_mappings_1[self.CONFIG_1_ID]) # Verify second user is not yet deleted. metadata_model_2 = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-2' % self.CONFIG_1_ID) ) self.assertEqual(metadata_model_2.committer_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. config_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.config] ) metadata_model_3 = ( config_models.ConfigPropertySnapshotMetadataModel.get_by_id( '%s-2' % self.CONFIG_1_ID) ) self.assertEqual( metadata_model_3.committer_id, config_mappings_2[self.CONFIG_1_ID]) class WipeoutServiceVerifyDeleteConfigModelsTests(test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' CONFIG_1_ID = 'config_1_id' CONFIG_2_ID = 'config_2_id' def setUp(self): super(WipeoutServiceVerifyDeleteConfigModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) config_model = config_models.ConfigPropertyModel( id=self.CONFIG_2_ID, value='a' ) config_model.commit(self.user_1_id, [{'cmd': 'command'}]) config_model.commit(self.user_1_id, [{'cmd': 'command_2'}]) config_models.ConfigPropertyModel( id=self.CONFIG_2_ID, value='a' ).commit(self.user_1_id, [{'cmd': 'command'}]) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_verify_user_delete_when_user_is_deleted_returns_true(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verify_user_delete_when_user_is_not_deleted_returns_false(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) config_models.ConfigPropertyModel( id=self.CONFIG_2_ID, value='a' ).commit(self.user_1_id, [{'cmd': 'command'}]) self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) class WipeoutServiceDeleteCollectionModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' COL_1_ID = 'col_1_id' COL_2_ID = 'col_2_id' def setUp(self): super(WipeoutServiceDeleteCollectionModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.save_new_valid_collection(self.COL_1_ID, self.user_1_id) self.publish_collection(self.user_1_id, self.COL_1_ID) rights_manager.assign_role_for_collection( user_services.UserActionsInfo(self.user_1_id), self.COL_1_ID, self.user_2_id, feconf.ROLE_OWNER) def test_one_collection_snapshot_metadata_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. collection_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.collection] ) metadata_model = ( collection_models.CollectionSnapshotMetadataModel.get_by_id( '%s-1' % self.COL_1_ID) ) self.assertEqual( metadata_model.committer_id, collection_mappings[self.COL_1_ID]) rights_metadata_model_1 = ( collection_models.CollectionRightsSnapshotMetadataModel.get_by_id( '%s-1' % self.COL_1_ID) ) self.assertEqual( rights_metadata_model_1.committer_id, collection_mappings[self.COL_1_ID]) self.assertEqual( rights_metadata_model_1.content_user_ids, [collection_mappings[self.COL_1_ID]]) self.assertEqual(rights_metadata_model_1.commit_cmds_user_ids, []) rights_metadata_model_2 = ( collection_models.CollectionRightsSnapshotMetadataModel.get_by_id( '%s-2' % self.COL_1_ID) ) self.assertEqual( rights_metadata_model_2.committer_id, collection_mappings[self.COL_1_ID]) self.assertEqual( rights_metadata_model_2.content_user_ids, [collection_mappings[self.COL_1_ID]]) self.assertEqual(rights_metadata_model_2.commit_cmds_user_ids, []) def test_one_collection_snapshot_content_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. collection_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.collection] ) rights_content_model_1 = ( collection_models.CollectionRightsSnapshotContentModel.get_by_id( '%s-1' % self.COL_1_ID) ) self.assertEqual( rights_content_model_1.content['owner_ids'], [collection_mappings[self.COL_1_ID]]) rights_content_model_2 = ( collection_models.CollectionRightsSnapshotContentModel.get_by_id( '%s-3' % self.COL_1_ID) ) self.assertItemsEqual( rights_content_model_2.content['owner_ids'], [ collection_mappings[self.COL_1_ID], self.user_2_id ]) def test_one_collection_commit_log_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. collection_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.collection] ) commit_log_model_1 = ( collection_models.CollectionCommitLogEntryModel.get_by_id( 'rights-%s-2' % self.COL_1_ID) ) self.assertEqual( commit_log_model_1.user_id, collection_mappings[self.COL_1_ID]) commit_log_model_2 = ( collection_models.CollectionCommitLogEntryModel.get_by_id( 'rights-%s-3' % self.COL_1_ID) ) self.assertEqual( commit_log_model_2.user_id, collection_mappings[self.COL_1_ID]) def test_one_collection_with_missing_snapshot_is_pseudonymized(self): collection_models.CollectionCommitLogEntryModel( id='collection-%s-1' % self.COL_2_ID, collection_id=self.COL_2_ID, user_id=self.user_1_id, commit_type='create_new', commit_cmds=[{}], post_commit_status=constants.ACTIVITY_STATUS_PUBLIC, version=1 ).put_for_human() with self.capture_logging(min_level=logging.ERROR) as log_messages: wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertItemsEqual( log_messages, [ '[WIPEOUT] The commit log model ' '\'CollectionCommitLogEntryModel\' and ' 'snapshot models [\'CollectionSnapshotMetadataModel\', ' '\'CollectionRightsSnapshotMetadataModel\'] IDs differ. ' 'Snapshots without commit logs: [], ' 'commit logs without snapshots: [u\'%s\'].' % self.COL_2_ID, '[WIPEOUT] The commit log model ' '\'ExplorationCommitLogEntryModel\' and ' 'snapshot models [\'ExplorationSnapshotMetadataModel\', ' '\'ExplorationRightsSnapshotMetadataModel\'] IDs differ. ' 'Snapshots without commit logs: [], ' 'commit logs without snapshots: [u\'an_exploration_id\'].' ] ) # Verify user is deleted. collection_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.collection] ) metadata_model = ( collection_models.CollectionSnapshotMetadataModel.get_by_id( '%s-1' % self.COL_1_ID ) ) self.assertEqual( metadata_model.committer_id, collection_mappings[self.COL_1_ID]) commit_log_model_1 = ( collection_models.CollectionCommitLogEntryModel.get_by_id( 'collection-%s-1' % self.COL_1_ID ) ) self.assertEqual( commit_log_model_1.user_id, collection_mappings[self.COL_1_ID]) commit_log_model_2 = ( collection_models.CollectionCommitLogEntryModel.get_by_id( 'collection-%s-1' % self.COL_2_ID ) ) self.assertEqual( commit_log_model_2.user_id, collection_mappings[self.COL_2_ID]) def test_one_collection_when_the_deletion_is_repeated_is_pseudonymized( self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Return metadata model to the original user ID. metadata_model = ( collection_models.CollectionSnapshotMetadataModel.get_by_id( '%s-1' % self.COL_1_ID ) ) metadata_model.committer_id = self.user_1_id metadata_model.put_for_human() # Run the user deletion again. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify that both the commit and the metadata have the same # pseudonymous user ID. collection_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.collection] ) metadata_model = ( collection_models.CollectionSnapshotMetadataModel.get_by_id( '%s-1' % self.COL_1_ID ) ) self.assertEqual( metadata_model.committer_id, collection_mappings[self.COL_1_ID]) commit_log_model = ( collection_models.CollectionCommitLogEntryModel.get_by_id( 'collection-%s-1' % self.COL_1_ID) ) self.assertEqual( commit_log_model.user_id, collection_mappings[self.COL_1_ID]) def test_collection_user_is_removed_from_contributors(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) old_summary_model = ( collection_models.CollectionSummaryModel.get_by_id(self.COL_1_ID)) self.assertNotIn(self.user_1_id, old_summary_model.contributor_ids) self.assertNotIn(self.user_1_id, old_summary_model.contributors_summary) old_summary_model.contributor_ids = [self.user_1_id] old_summary_model.contributors_summary = {self.user_1_id: 2} old_summary_model.put() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) new_summary_model = ( collection_models.CollectionSummaryModel.get_by_id(self.COL_1_ID)) self.assertNotIn(self.user_1_id, new_summary_model.contributor_ids) self.assertNotIn(self.user_1_id, new_summary_model.contributors_summary) def test_col_user_is_removed_from_contributor_ids_when_missing_from_summary( self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) old_summary_model = ( collection_models.CollectionSummaryModel.get_by_id(self.COL_1_ID)) self.assertNotIn(self.user_1_id, old_summary_model.contributor_ids) self.assertNotIn(self.user_1_id, old_summary_model.contributors_summary) old_summary_model.contributor_ids = [self.user_1_id] old_summary_model.contributors_summary = {} old_summary_model.put() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) new_summary_model = ( collection_models.CollectionSummaryModel.get_by_id(self.COL_1_ID)) self.assertNotIn(self.user_1_id, new_summary_model.contributor_ids) self.assertNotIn(self.user_1_id, new_summary_model.contributors_summary) def test_delete_exp_where_user_has_role_when_rights_model_marked_as_deleted( self): self.save_new_valid_collection(self.COL_2_ID, self.user_1_id) collection_services.delete_collection(self.user_1_id, self.COL_2_ID) collection_rights_model = ( collection_models.CollectionRightsModel.get_by_id(self.COL_2_ID)) self.assertTrue(collection_rights_model.deleted) collection_model = ( collection_models.CollectionModel.get_by_id(self.COL_2_ID)) self.assertTrue(collection_model.deleted) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertIsNone( collection_models.CollectionRightsModel.get_by_id(self.COL_2_ID)) self.assertIsNone( collection_models.CollectionModel.get_by_id(self.COL_2_ID)) def test_multiple_collections_are_pseudonymized(self): self.save_new_valid_collection(self.COL_2_ID, self.user_1_id) self.publish_collection(self.user_1_id, self.COL_2_ID) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) collection_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.collection] ) metadata_model = ( collection_models.CollectionSnapshotMetadataModel.get_by_id( '%s-1' % self.COL_1_ID ) ) self.assertEqual( metadata_model.committer_id, collection_mappings[self.COL_1_ID]) commit_log_model = ( collection_models.CollectionCommitLogEntryModel.get_by_id( 'collection-%s-1' % self.COL_1_ID ) ) self.assertEqual( commit_log_model.user_id, collection_mappings[self.COL_1_ID]) metadata_model = ( collection_models.CollectionSnapshotMetadataModel.get_by_id( '%s-1' % self.COL_2_ID ) ) self.assertEqual( metadata_model.committer_id, collection_mappings[self.COL_2_ID]) commit_log_model = ( collection_models.CollectionCommitLogEntryModel.get_by_id( 'collection-%s-1' % self.COL_2_ID ) ) self.assertEqual( commit_log_model.user_id, collection_mappings[self.COL_2_ID]) class WipeoutServiceVerifyDeleteCollectionModelsTests( test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' COL_1_ID = 'col_1_id' COL_2_ID = 'col_2_id' def setUp(self): super(WipeoutServiceVerifyDeleteCollectionModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.save_new_valid_collection(self.COL_1_ID, self.user_1_id) self.save_new_valid_collection(self.COL_2_ID, self.user_1_id) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_verify_user_delete_when_user_is_deleted_returns_true(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verify_user_delete_when_user_is_not_deleted_returns_false(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) collection_models.CollectionSnapshotMetadataModel( id='%s-1' % self.COL_1_ID, committer_id=self.user_1_id, commit_message='123', commit_type='create', commit_cmds={} ).put_for_human() self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) class WipeoutServiceDeleteExplorationModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' EXP_1_ID = 'exp_1_id' EXP_2_ID = 'exp_2_id' def setUp(self): super(WipeoutServiceDeleteExplorationModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.save_new_valid_exploration(self.EXP_1_ID, self.user_1_id) self.publish_exploration(self.user_1_id, self.EXP_1_ID) rights_manager.assign_role_for_exploration( user_services.UserActionsInfo(self.user_1_id), self.EXP_1_ID, self.user_2_id, feconf.ROLE_OWNER) def test_one_exploration_snapshot_metadata_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. exploration_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.exploration] ) metadata_model = ( exp_models.ExplorationSnapshotMetadataModel.get_by_id( '%s-1' % self.EXP_1_ID) ) self.assertEqual( metadata_model.committer_id, exploration_mappings[self.EXP_1_ID]) rights_metadata_model_1 = ( exp_models.ExplorationRightsSnapshotMetadataModel.get_by_id( '%s-1' % self.EXP_1_ID) ) self.assertEqual( rights_metadata_model_1.committer_id, exploration_mappings[self.EXP_1_ID]) self.assertEqual( rights_metadata_model_1.content_user_ids, [exploration_mappings[self.EXP_1_ID]]) self.assertEqual(rights_metadata_model_1.commit_cmds_user_ids, []) rights_metadata_model_2 = ( exp_models.ExplorationRightsSnapshotMetadataModel.get_by_id( '%s-2' % self.EXP_1_ID) ) self.assertEqual( rights_metadata_model_2.committer_id, exploration_mappings[self.EXP_1_ID]) self.assertEqual( rights_metadata_model_2.content_user_ids, [exploration_mappings[self.EXP_1_ID]]) self.assertEqual(rights_metadata_model_2.commit_cmds_user_ids, []) def test_one_exploration_snapshot_content_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. exploration_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.exploration] ) rights_content_model_1 = ( exp_models.ExplorationRightsSnapshotContentModel.get_by_id( '%s-1' % self.EXP_1_ID) ) self.assertEqual( rights_content_model_1.content['owner_ids'], [exploration_mappings[self.EXP_1_ID]]) rights_content_model_2 = ( exp_models.ExplorationRightsSnapshotContentModel.get_by_id( '%s-3' % self.EXP_1_ID) ) self.assertItemsEqual( rights_content_model_2.content['owner_ids'], [ exploration_mappings[self.EXP_1_ID], self.user_2_id ]) def test_one_exploration_commit_log_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. exploration_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.exploration] ) commit_log_model_1 = ( exp_models.ExplorationCommitLogEntryModel.get_by_id( 'rights-%s-2' % self.EXP_1_ID) ) self.assertEqual( commit_log_model_1.user_id, exploration_mappings[self.EXP_1_ID]) commit_log_model_2 = ( exp_models.ExplorationCommitLogEntryModel.get_by_id( 'rights-%s-3' % self.EXP_1_ID) ) self.assertEqual( commit_log_model_2.user_id, exploration_mappings[self.EXP_1_ID]) def test_one_exploration_with_missing_snapshot_is_pseudonymized(self): exp_models.ExplorationCommitLogEntryModel( id='exploration-%s-1' % self.EXP_2_ID, exploration_id=self.EXP_2_ID, user_id=self.user_1_id, commit_type='create_new', commit_cmds=[{}], post_commit_status=constants.ACTIVITY_STATUS_PUBLIC, version=1 ).put_for_human() with self.capture_logging(min_level=logging.ERROR) as log_messages: wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertItemsEqual( log_messages, [ '[WIPEOUT] The commit log model ' '\'ExplorationCommitLogEntryModel\' and ' 'snapshot models [\'ExplorationSnapshotMetadataModel\', ' '\'ExplorationRightsSnapshotMetadataModel\'] IDs differ. ' 'Snapshots without commit logs: [], ' 'commit logs without snapshots: [u\'%s\'].' % self.EXP_2_ID ] ) # Verify user is deleted. exploration_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.exploration] ) metadata_model = ( exp_models.ExplorationSnapshotMetadataModel.get_by_id( '%s-1' % self.EXP_1_ID ) ) self.assertEqual( metadata_model.committer_id, exploration_mappings[self.EXP_1_ID]) commit_log_model_1 = ( exp_models.ExplorationCommitLogEntryModel.get_by_id( 'exploration-%s-1' % self.EXP_1_ID ) ) self.assertEqual( commit_log_model_1.user_id, exploration_mappings[self.EXP_1_ID]) commit_log_model_2 = ( exp_models.ExplorationCommitLogEntryModel.get_by_id( 'exploration-%s-1' % self.EXP_2_ID ) ) self.assertEqual( commit_log_model_2.user_id, exploration_mappings[self.EXP_2_ID]) def test_one_exploration_when_the_deletion_is_repeated_is_pseudonymized( self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Return metadata model to the original user ID. metadata_model = ( exp_models.ExplorationSnapshotMetadataModel.get_by_id( '%s-1' % self.EXP_1_ID ) ) metadata_model.committer_id = self.user_1_id metadata_model.put_for_human() # Run the user deletion again. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify that both the commit and the metadata have the same # pseudonymous user ID. exploration_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.exploration] ) metadata_model = ( exp_models.ExplorationSnapshotMetadataModel.get_by_id( '%s-1' % self.EXP_1_ID ) ) self.assertEqual( metadata_model.committer_id, exploration_mappings[self.EXP_1_ID]) commit_log_model = ( exp_models.ExplorationCommitLogEntryModel.get_by_id( 'exploration-%s-1' % self.EXP_1_ID) ) self.assertEqual( commit_log_model.user_id, exploration_mappings[self.EXP_1_ID]) def test_exploration_user_is_removed_from_contributors(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) old_summary_model = exp_models.ExpSummaryModel.get_by_id(self.EXP_1_ID) self.assertNotIn(self.user_1_id, old_summary_model.contributor_ids) self.assertNotIn(self.user_1_id, old_summary_model.contributors_summary) old_summary_model.contributor_ids = [self.user_1_id] old_summary_model.contributors_summary = {self.user_1_id: 2} old_summary_model.put() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) new_summary_model = exp_models.ExpSummaryModel.get_by_id(self.EXP_1_ID) self.assertNotIn(self.user_1_id, new_summary_model.contributor_ids) self.assertNotIn(self.user_1_id, new_summary_model.contributors_summary) def test_exp_user_is_removed_from_contributor_ids_when_missing_from_summary( self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) old_summary_model = exp_models.ExpSummaryModel.get_by_id(self.EXP_1_ID) self.assertNotIn(self.user_1_id, old_summary_model.contributor_ids) self.assertNotIn(self.user_1_id, old_summary_model.contributors_summary) old_summary_model.contributor_ids = [self.user_1_id] old_summary_model.contributors_summary = {} old_summary_model.put() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) new_summary_model = exp_models.ExpSummaryModel.get_by_id(self.EXP_1_ID) self.assertNotIn(self.user_1_id, new_summary_model.contributor_ids) self.assertNotIn(self.user_1_id, new_summary_model.contributors_summary) def test_delete_exp_where_user_has_role_when_rights_model_marked_as_deleted( self): self.save_new_valid_exploration(self.EXP_2_ID, self.user_1_id) exp_services.delete_exploration(self.user_1_id, self.EXP_2_ID) exp_rights_model = ( exp_models.ExplorationRightsModel.get_by_id(self.EXP_2_ID)) self.assertTrue(exp_rights_model.deleted) exp_model = ( exp_models.ExplorationRightsModel.get_by_id(self.EXP_2_ID)) self.assertTrue(exp_model.deleted) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertIsNone( exp_models.ExplorationRightsModel.get_by_id(self.EXP_2_ID)) self.assertIsNone( exp_models.ExplorationModel.get_by_id(self.EXP_2_ID)) def test_multiple_explorations_are_pseudonymized(self): self.save_new_valid_exploration(self.EXP_2_ID, self.user_1_id) self.publish_exploration(self.user_1_id, self.EXP_2_ID) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) exploration_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.exploration] ) metadata_model = ( exp_models.ExplorationSnapshotMetadataModel.get_by_id( '%s-1' % self.EXP_1_ID ) ) self.assertEqual( metadata_model.committer_id, exploration_mappings[self.EXP_1_ID]) commit_log_model = ( exp_models.ExplorationCommitLogEntryModel.get_by_id( 'exploration-%s-1' % self.EXP_1_ID ) ) self.assertEqual( commit_log_model.user_id, exploration_mappings[self.EXP_1_ID]) metadata_model = ( exp_models.ExplorationSnapshotMetadataModel.get_by_id( '%s-1' % self.EXP_2_ID ) ) self.assertEqual( metadata_model.committer_id, exploration_mappings[self.EXP_2_ID]) commit_log_model = ( exp_models.ExplorationCommitLogEntryModel.get_by_id( 'exploration-%s-1' % self.EXP_2_ID ) ) self.assertEqual( commit_log_model.user_id, exploration_mappings[self.EXP_2_ID]) class WipeoutServiceVerifyDeleteExplorationModelsTests( test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' EXP_1_ID = 'exp_1_id' EXP_2_ID = 'exp_2_id' def setUp(self): super(WipeoutServiceVerifyDeleteExplorationModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.save_new_valid_exploration(self.EXP_1_ID, self.user_1_id) self.save_new_valid_exploration(self.EXP_2_ID, self.user_1_id) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_verify_user_delete_when_user_is_deleted_returns_true(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verify_user_delete_when_user_is_not_deleted_returns_false(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) exp_models.ExplorationSnapshotMetadataModel( id='%s-1' % self.EXP_1_ID, committer_id=self.user_1_id, commit_message='123', commit_type='create', commit_cmds={} ).put_for_human() self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) class WipeoutServiceDeleteEmailModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' THREAD_1_ID = 'thread_1_id' THREAD_2_ID = 'thread_2_id' REPLY_1_ID = 'reply_1_id' REPLY_2_ID = 'reply_2_id' def setUp(self): super(WipeoutServiceDeleteEmailModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) email_models.GeneralFeedbackEmailReplyToIdModel( id='%s.%s' % (self.user_1_id, self.THREAD_1_ID), user_id=self.user_1_id, thread_id=self.THREAD_1_ID, reply_to_id=self.REPLY_1_ID ).put() wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_one_email_is_deleted(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertIsNone( email_models.GeneralFeedbackEmailReplyToIdModel.get_by_id( '%s.%s' % (self.user_1_id, self.THREAD_1_ID))) def test_multiple_emails_are_deleted(self): email_models.GeneralFeedbackEmailReplyToIdModel( id='%s.%s' % (self.user_1_id, self.THREAD_2_ID), user_id=self.user_1_id, thread_id=self.THREAD_2_ID, reply_to_id=self.REPLY_2_ID ).put() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertIsNone( email_models.GeneralFeedbackEmailReplyToIdModel.get_by_id( '%s.%s' % (self.user_1_id, self.THREAD_1_ID))) self.assertIsNone( email_models.GeneralFeedbackEmailReplyToIdModel.get_by_id( '%s.%s' % (self.user_1_id, self.THREAD_2_ID))) def test_multiple_emails_from_multiple_users_are_deleted(self): email_models.GeneralFeedbackEmailReplyToIdModel( id='%s.%s' % (self.user_2_id, self.THREAD_2_ID), user_id=self.user_2_id, thread_id=self.THREAD_2_ID, reply_to_id=self.REPLY_2_ID ).put() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertIsNone( email_models.GeneralFeedbackEmailReplyToIdModel.get_by_id( '%s.%s' % (self.user_1_id, self.THREAD_1_ID))) self.assertIsNotNone( email_models.GeneralFeedbackEmailReplyToIdModel.get_by_id( '%s.%s' % (self.user_2_id, self.THREAD_2_ID))) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) self.assertIsNone( email_models.GeneralFeedbackEmailReplyToIdModel.get_by_id( '%s.%s' % (self.user_2_id, self.THREAD_2_ID))) class WipeoutServiceVerifyDeleteEmailModelsTests(test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' THREAD_1_ID = 'thread_1_id' THREAD_2_ID = 'thread_2_id' REPLY_1_ID = 'reply_1_id' REPLY_2_ID = 'reply_2_id' def setUp(self): super(WipeoutServiceVerifyDeleteEmailModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) email_models.GeneralFeedbackEmailReplyToIdModel( id='%s.%s' % (self.user_1_id, self.THREAD_1_ID), user_id=self.user_1_id, thread_id=self.THREAD_1_ID, reply_to_id=self.REPLY_1_ID ).put() wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_verify_user_delete_when_user_is_deleted_returns_true(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verify_user_delete_when_user_is_not_deleted_returns_false(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) email_models.GeneralFeedbackEmailReplyToIdModel( id='%s.%s' % (self.user_1_id, self.THREAD_1_ID), user_id=self.user_1_id, thread_id=self.THREAD_1_ID, reply_to_id=self.REPLY_1_ID ).put() self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) class WipeoutServiceDeleteFeedbackModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" FEEDBACK_1_ID = 'feedback_1_id' FEEDBACK_2_ID = 'feedback_2_id' MESSAGE_1_ID = 'message_1_id' MESSAGE_2_ID = 'message_2_id' EXP_1_ID = 'exp_1_id' EXP_2_ID = 'exp_2_id' USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' NUMBER_OF_MODELS = 150 def setUp(self): super(WipeoutServiceDeleteFeedbackModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) feedback_models.GeneralFeedbackThreadModel( id=self.FEEDBACK_1_ID, entity_type=feconf.ENTITY_TYPE_EXPLORATION, entity_id=self.EXP_1_ID, original_author_id=self.user_1_id, subject='Wrong state name', has_suggestion=True, last_nonempty_message_text='Some text', last_nonempty_message_author_id=self.user_2_id ).put_for_human() feedback_models.GeneralFeedbackMessageModel( id=self.MESSAGE_1_ID, thread_id=self.FEEDBACK_1_ID, message_id=0, author_id=self.user_2_id, text='Some text' ).put_for_human() suggestion_models.GeneralSuggestionModel( id=self.FEEDBACK_1_ID, suggestion_type=( feconf.SUGGESTION_TYPE_EDIT_STATE_CONTENT), target_type=feconf.ENTITY_TYPE_EXPLORATION, target_id=self.EXP_1_ID, target_version_at_submission=1, status=suggestion_models.STATUS_IN_REVIEW, author_id=self.user_1_id, final_reviewer_id=self.user_2_id, change_cmd={}, score_category=suggestion_models.SCORE_TYPE_CONTENT ).put_for_human() wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_one_feedback_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is pseudonymized. feedback_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.feedback] ) feedback_thread_model = ( feedback_models.GeneralFeedbackThreadModel.get_by_id( self.FEEDBACK_1_ID) ) self.assertEqual( feedback_thread_model.original_author_id, feedback_mappings[self.FEEDBACK_1_ID] ) suggestion_model_model = ( suggestion_models.GeneralSuggestionModel.get_by_id( self.FEEDBACK_1_ID) ) self.assertEqual( suggestion_model_model.author_id, feedback_mappings[self.FEEDBACK_1_ID] ) def test_one_feedback_when_the_deletion_is_repeated_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Return feedback thread model to the original user ID. feedback_thread_model = ( feedback_models.GeneralFeedbackThreadModel.get_by_id( self.FEEDBACK_1_ID) ) feedback_thread_model.original_author_id = self.user_1_id feedback_thread_model.put_for_human() # Run the user deletion again. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify that both the feedback thread and the suggestion have the same # pseudonymous user ID. feedback_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.feedback] ) new_feedback_thread_model = ( feedback_models.GeneralFeedbackThreadModel.get_by_id( self.FEEDBACK_1_ID) ) self.assertEqual( new_feedback_thread_model.original_author_id, feedback_mappings[self.FEEDBACK_1_ID] ) def test_multiple_feedbacks_are_pseudonymized(self): feedback_thread_models = [] for i in python_utils.RANGE(self.NUMBER_OF_MODELS): feedback_thread_models.append( feedback_models.GeneralFeedbackThreadModel( id='feedback-%s' % i, entity_type=feconf.ENTITY_TYPE_EXPLORATION, entity_id=self.EXP_1_ID, original_author_id=self.user_1_id, subject='Too short exploration', last_nonempty_message_text='Some text', last_nonempty_message_author_id=self.user_2_id ) ) feedback_message_models = [] for i in python_utils.RANGE(self.NUMBER_OF_MODELS): feedback_message_models.append( feedback_models.GeneralFeedbackMessageModel( id='message-%s' % i, thread_id='feedback-%s' % i, message_id=i, author_id=self.user_1_id, text='Some text' ) ) base_models.BaseHumanMaintainedModel.put_multi_for_human( feedback_thread_models + feedback_message_models) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) feedback_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.feedback] ) pseudonymized_feedback_thread_models = ( feedback_models.GeneralFeedbackThreadModel.get_multi( [model.id for model in feedback_thread_models] ) ) for feedback_thread_model in pseudonymized_feedback_thread_models: self.assertEqual( feedback_thread_model.original_author_id, feedback_mappings[feedback_thread_model.id] ) pseudonymized_feedback_message_models = ( feedback_models.GeneralFeedbackMessageModel.get_multi( [model.id for model in feedback_message_models] ) ) for feedback_message_model in pseudonymized_feedback_message_models: self.assertEqual( feedback_message_model.author_id, feedback_mappings[feedback_message_model.thread_id] ) def test_one_feedback_with_multiple_users_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) feedback_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.feedback] ) # Verify first user is pseudonymized. feedback_thread_model = ( feedback_models.GeneralFeedbackThreadModel.get_by_id( self.FEEDBACK_1_ID) ) self.assertEqual( feedback_thread_model.original_author_id, feedback_mappings_1[self.FEEDBACK_1_ID] ) # Verify second user is not yet pseudonymized. self.assertEqual( feedback_thread_model.last_nonempty_message_author_id, self.user_2_id ) # Delete second user. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) feedback_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.feedback] ) # Verify second user is pseudonymized. self.assertEqual( feedback_thread_model.last_nonempty_message_author_id, feedback_mappings_2[self.FEEDBACK_1_ID] ) class WipeoutServiceVerifyDeleteFeedbackModelsTests(test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' FEEDBACK_1_ID = 'feedback_1_id' MESSAGE_1_ID = 'message_1_id' EXP_1_ID = 'exp_1_id' def setUp(self): super(WipeoutServiceVerifyDeleteFeedbackModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) feedback_models.GeneralFeedbackThreadModel( id=self.FEEDBACK_1_ID, entity_type=feconf.ENTITY_TYPE_EXPLORATION, entity_id=self.EXP_1_ID, original_author_id=self.user_1_id, subject='Wrong state name', has_suggestion=True, last_nonempty_message_text='Some text', last_nonempty_message_author_id=self.user_1_id ).put_for_human() feedback_models.GeneralFeedbackMessageModel( id=self.MESSAGE_1_ID, thread_id=self.FEEDBACK_1_ID, message_id=0, author_id=self.user_1_id, text='Some text' ).put_for_human() suggestion_models.GeneralSuggestionModel( id=self.FEEDBACK_1_ID, suggestion_type=( feconf.SUGGESTION_TYPE_EDIT_STATE_CONTENT), target_type=feconf.ENTITY_TYPE_EXPLORATION, target_id=self.EXP_1_ID, target_version_at_submission=1, status=suggestion_models.STATUS_IN_REVIEW, author_id=self.user_1_id, final_reviewer_id=self.user_1_id, change_cmd={}, score_category=suggestion_models.SCORE_TYPE_CONTENT ).put_for_human() wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_verify_user_delete_when_user_is_deleted_returns_true(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verify_user_delete_when_user_is_not_deleted_returns_false(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) feedback_models.GeneralFeedbackThreadModel( id=self.FEEDBACK_1_ID, entity_type=feconf.ENTITY_TYPE_EXPLORATION, entity_id=self.EXP_1_ID, original_author_id=self.user_1_id, subject='Wrong state name', has_suggestion=True, last_nonempty_message_text='Some text', last_nonempty_message_author_id=self.user_1_id ).put_for_human() self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) class WipeoutServiceDeleteImprovementsModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' EXP_1_ID = 'exp_1_id' EXP_2_ID = 'exp_2_id' def setUp(self): super(WipeoutServiceDeleteImprovementsModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.improvements_model_1_id = ( improvements_models.TaskEntryModel.create( entity_type=constants.TASK_ENTITY_TYPE_EXPLORATION, entity_id=self.EXP_1_ID, entity_version=1, task_type=constants.TASK_TYPE_HIGH_BOUNCE_RATE, target_type=constants.TASK_TARGET_TYPE_STATE, target_id='State', issue_description=None, status=constants.TASK_STATUS_RESOLVED, resolver_id=self.user_1_id ) ) self.improvements_model_2_id = ( improvements_models.TaskEntryModel.create( entity_type=constants.TASK_ENTITY_TYPE_EXPLORATION, entity_id=self.EXP_2_ID, entity_version=1, task_type=constants.TASK_TYPE_HIGH_BOUNCE_RATE, target_type=constants.TASK_TARGET_TYPE_STATE, target_id='State', issue_description=None, status=constants.TASK_STATUS_RESOLVED, resolver_id=self.user_1_id ) ) def test_delete_user_is_successful(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() self.assertIsNotNone( improvements_models.TaskEntryModel.get_by_id( self.improvements_model_1_id)) self.assertIsNotNone( improvements_models.TaskEntryModel.get_by_id( self.improvements_model_2_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertIsNone( improvements_models.TaskEntryModel.get_by_id( self.improvements_model_1_id)) self.assertIsNone( improvements_models.TaskEntryModel.get_by_id( self.improvements_model_2_id)) class WipeoutServiceVerifyDeleteImprovementsModelsTests( test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' EXP_1_ID = 'exp_1_id' EXP_2_ID = 'exp_2_id' EXP_3_ID = 'exp_3_id' def setUp(self): super(WipeoutServiceVerifyDeleteImprovementsModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) improvements_models.TaskEntryModel.create( entity_type=constants.TASK_ENTITY_TYPE_EXPLORATION, entity_id=self.EXP_1_ID, entity_version=1, task_type=constants.TASK_TYPE_HIGH_BOUNCE_RATE, target_type=constants.TASK_TARGET_TYPE_STATE, target_id='State', issue_description=None, status=constants.TASK_STATUS_RESOLVED, resolver_id=self.user_1_id ) improvements_models.TaskEntryModel.create( entity_type=constants.TASK_ENTITY_TYPE_EXPLORATION, entity_id=self.EXP_2_ID, entity_version=1, task_type=constants.TASK_TYPE_HIGH_BOUNCE_RATE, target_type=constants.TASK_TARGET_TYPE_STATE, target_id='State', issue_description=None, status=constants.TASK_STATUS_RESOLVED, resolver_id=self.user_1_id ) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_verify_user_delete_when_user_is_deleted_returns_true(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verify_user_delete_when_user_is_not_deleted_returns_false(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) improvements_models.TaskEntryModel.create( entity_type=constants.TASK_ENTITY_TYPE_EXPLORATION, entity_id=self.EXP_3_ID, entity_version=1, task_type=constants.TASK_TYPE_HIGH_BOUNCE_RATE, target_type=constants.TASK_TARGET_TYPE_STATE, target_id='State', issue_description=None, status=constants.TASK_STATUS_RESOLVED, resolver_id=self.user_1_id ) self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) class WipeoutServiceDeleteQuestionModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" SKILL_1_ID = 'skill_1_id' QUESTION_1_ID = 'question_1_id' QUESTION_2_ID = 'question_2_id' USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' def setUp(self): super(WipeoutServiceDeleteQuestionModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.set_admins((self.USER_1_USERNAME, self.USER_2_USERNAME)) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.save_new_skill(self.SKILL_1_ID, self.user_1_id) self.save_new_question( self.QUESTION_1_ID, self.user_1_id, self._create_valid_question_data('ABC'), [self.SKILL_1_ID] ) wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_one_question_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. question_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.question] ) metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_1_ID) ) self.assertEqual( metadata_model.committer_id, question_mappings[self.QUESTION_1_ID]) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_1_ID) ) self.assertEqual( commit_log_model.user_id, question_mappings[self.QUESTION_1_ID]) def test_one_question_with_missing_snapshot_is_pseudonymized(self): question_models.QuestionCommitLogEntryModel( id='question-%s-1' % self.QUESTION_2_ID, question_id=self.QUESTION_2_ID, user_id=self.user_1_id, commit_type='create_new', commit_cmds=[{}], post_commit_status=constants.ACTIVITY_STATUS_PUBLIC, version=1 ).put_for_human() with self.capture_logging(min_level=logging.ERROR) as log_messages: wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertEqual( log_messages, ['[WIPEOUT] The commit log model \'QuestionCommitLogEntryModel\' ' 'and snapshot models [\'QuestionSnapshotMetadataModel\'] IDs ' 'differ. Snapshots without commit logs: [], ' 'commit logs without snapshots: [u\'%s\'].' % self.QUESTION_2_ID]) # Verify user is deleted. question_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.question] ) metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( metadata_model.committer_id, question_mappings[self.QUESTION_1_ID]) commit_log_model_1 = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( commit_log_model_1.user_id, question_mappings[self.QUESTION_1_ID]) commit_log_model_2 = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_2_ID ) ) self.assertEqual( commit_log_model_2.user_id, question_mappings[self.QUESTION_2_ID]) def test_one_question_when_the_deletion_is_repeated_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Return metadata model to the original user ID. metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_1_ID ) ) metadata_model.committer_id = self.user_1_id metadata_model.put_for_human() # Run the user deletion again. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify that both the commit and the metadata have the same # pseudonymous user ID. question_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.question] ) metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( metadata_model.committer_id, question_mappings[self.QUESTION_1_ID]) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( commit_log_model.user_id, question_mappings[self.QUESTION_1_ID]) def test_multiple_questions_are_pseudonymized(self): self.save_new_question( self.QUESTION_2_ID, self.user_1_id, self._create_valid_question_data('ABC'), [self.SKILL_1_ID] ) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) question_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.question] ) metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( metadata_model.committer_id, question_mappings[self.QUESTION_1_ID]) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( commit_log_model.user_id, question_mappings[self.QUESTION_1_ID]) metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_2_ID ) ) self.assertEqual( metadata_model.committer_id, question_mappings[self.QUESTION_2_ID]) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_2_ID ) ) self.assertEqual( commit_log_model.user_id, question_mappings[self.QUESTION_2_ID]) def test_multiple_questions_with_multiple_users_are_pseudonymized(self): self.save_new_question( self.QUESTION_2_ID, self.user_2_id, self._create_valid_question_data('ABC'), [self.SKILL_1_ID] ) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. question_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.question] ) metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( metadata_model.committer_id, question_mappings_1[self.QUESTION_1_ID] ) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( commit_log_model.user_id, question_mappings_1[self.QUESTION_1_ID]) # Verify second user is not yet deleted. metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_2_ID ) ) self.assertEqual(metadata_model.committer_id, self.user_2_id) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_2_ID ) ) self.assertEqual(commit_log_model.user_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. question_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.question] ) metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_2_ID ) ) self.assertEqual( metadata_model.committer_id, question_mappings_2[self.QUESTION_2_ID] ) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_2_ID ) ) self.assertEqual( commit_log_model.user_id, question_mappings_2[self.QUESTION_2_ID]) def test_one_question_with_multiple_users_is_pseudonymized(self): question_services.update_question( self.user_2_id, self.QUESTION_1_ID, [question_domain.QuestionChange({ 'cmd': question_domain.CMD_UPDATE_QUESTION_PROPERTY, 'property_name': ( question_domain.QUESTION_PROPERTY_LANGUAGE_CODE), 'new_value': 'cs', 'old_value': 'en' })], 'Change language.' ) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. question_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.question] ) metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( metadata_model.committer_id, question_mappings_1[self.QUESTION_1_ID] ) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-1' % self.QUESTION_1_ID ) ) self.assertEqual( commit_log_model.user_id, question_mappings_1[self.QUESTION_1_ID]) # Verify second user is not yet deleted. metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-2' % self.QUESTION_1_ID ) ) self.assertEqual(metadata_model.committer_id, self.user_2_id) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-2' % self.QUESTION_1_ID ) ) self.assertEqual(commit_log_model.user_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. question_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.question] ) metadata_model = ( question_models.QuestionSnapshotMetadataModel.get_by_id( '%s-2' % self.QUESTION_1_ID ) ) self.assertEqual( metadata_model.committer_id, question_mappings_2[self.QUESTION_1_ID] ) commit_log_model = ( question_models.QuestionCommitLogEntryModel.get_by_id( 'question-%s-2' % self.QUESTION_1_ID ) ) self.assertEqual( commit_log_model.user_id, question_mappings_2[self.QUESTION_1_ID]) class WipeoutServiceVerifyDeleteQuestionModelsTests(test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" SKILL_1_ID = 'SKILL_1_ID' QUESTION_1_ID = 'QUESTION_1_ID' QUESTION_2_ID = 'QUESTION_2_ID' USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' def setUp(self): super(WipeoutServiceVerifyDeleteQuestionModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.set_admins((self.USER_1_USERNAME, self.USER_2_USERNAME)) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.save_new_skill(self.SKILL_1_ID, self.user_1_id) self.save_new_question( self.QUESTION_1_ID, self.user_1_id, self._create_valid_question_data('ABC'), [self.SKILL_1_ID] ) self.save_new_question( self.QUESTION_2_ID, self.user_2_id, self._create_valid_question_data('ABC'), [self.SKILL_1_ID] ) wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_verification_is_successful(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verification_when_deletion_failed_is_unsuccessful(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_2_id)) question_services.update_question( self.user_2_id, self.QUESTION_2_ID, [question_domain.QuestionChange({ 'cmd': question_domain.CMD_UPDATE_QUESTION_PROPERTY, 'property_name': ( question_domain.QUESTION_PROPERTY_LANGUAGE_CODE), 'new_value': 'cs', 'old_value': 'en' })], 'Change language.' ) class WipeoutServiceDeleteSkillModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" SKILL_1_ID = 'skill_1_id' SKILL_2_ID = 'skill_2_id' USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' def setUp(self): super(WipeoutServiceDeleteSkillModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.set_admins((self.USER_1_USERNAME, self.USER_2_USERNAME)) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.save_new_skill(self.SKILL_1_ID, self.user_1_id) wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_one_skill_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. skill_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.skill] ) metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_1_ID) self.assertEqual( metadata_model.committer_id, skill_mappings[self.SKILL_1_ID]) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_1_ID) self.assertEqual( commit_log_model.user_id, skill_mappings[self.SKILL_1_ID]) def test_one_skill_with_missing_snapshot_is_pseudonymized(self): skill_models.SkillCommitLogEntryModel( id='skill-%s-1' % self.SKILL_2_ID, skill_id=self.SKILL_2_ID, user_id=self.user_1_id, commit_type='create_new', commit_cmds=[{}], post_commit_status=constants.ACTIVITY_STATUS_PUBLIC, version=1 ).put_for_human() with self.capture_logging(min_level=logging.ERROR) as log_messages: wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertEqual( log_messages, ['[WIPEOUT] The commit log model \'SkillCommitLogEntryModel\' and ' 'snapshot models [\'SkillSnapshotMetadataModel\'] IDs differ. ' 'Snapshots without commit logs: [], ' 'commit logs without snapshots: [u\'%s\'].' % self.SKILL_2_ID]) # Verify user is deleted. skill_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.skill] ) metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_1_ID) self.assertEqual( metadata_model.committer_id, skill_mappings[self.SKILL_1_ID]) commit_log_model_1 = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_1_ID) self.assertEqual( commit_log_model_1.user_id, skill_mappings[self.SKILL_1_ID]) commit_log_model_2 = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_2_ID) self.assertEqual( commit_log_model_2.user_id, skill_mappings[self.SKILL_2_ID]) def test_one_skill_when_the_deletion_is_repeated_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Return metadata model to the original user ID. metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_1_ID) metadata_model.committer_id = self.user_1_id metadata_model.put_for_human() # Run the user deletion again. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify that both the commit and the metadata have the same # pseudonymous user ID. skill_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.skill] ) metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_1_ID) self.assertEqual( metadata_model.committer_id, skill_mappings[self.SKILL_1_ID]) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_1_ID) self.assertEqual( commit_log_model.user_id, skill_mappings[self.SKILL_1_ID]) def test_multiple_skills_are_pseudonymized(self): self.save_new_skill(self.SKILL_2_ID, self.user_1_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) skill_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.skill] ) metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_1_ID) self.assertEqual( metadata_model.committer_id, skill_mappings[self.SKILL_1_ID]) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_1_ID) self.assertEqual( commit_log_model.user_id, skill_mappings[self.SKILL_1_ID]) metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_2_ID) self.assertEqual( metadata_model.committer_id, skill_mappings[self.SKILL_2_ID]) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_2_ID) self.assertEqual( commit_log_model.user_id, skill_mappings[self.SKILL_2_ID]) def test_multiple_skills_with_multiple_users_are_pseudonymized(self): self.save_new_skill(self.SKILL_2_ID, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. skill_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.skill] ) metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_1_ID) self.assertEqual( metadata_model.committer_id, skill_mappings_1[self.SKILL_1_ID]) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_1_ID) self.assertEqual( commit_log_model.user_id, skill_mappings_1[self.SKILL_1_ID]) # Verify second user is not yet deleted. metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_2_ID) self.assertEqual(metadata_model.committer_id, self.user_2_id) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_2_ID) self.assertEqual(commit_log_model.user_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. skill_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.skill] ) metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_2_ID) self.assertEqual( metadata_model.committer_id, skill_mappings_2[self.SKILL_2_ID]) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_2_ID) self.assertEqual( commit_log_model.user_id, skill_mappings_2[self.SKILL_2_ID]) def test_one_skill_with_multiple_users_is_pseudonymized(self): skill_services.update_skill( self.user_2_id, self.SKILL_1_ID, [skill_domain.SkillChange({ 'cmd': skill_domain.CMD_UPDATE_SKILL_PROPERTY, 'property_name': skill_domain.SKILL_PROPERTY_LANGUAGE_CODE, 'new_value': 'cs', 'old_value': 'en' })], 'Change language.' ) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. skill_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.skill] ) metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-1' % self.SKILL_1_ID) self.assertEqual( metadata_model.committer_id, skill_mappings_1[self.SKILL_1_ID]) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-1' % self.SKILL_1_ID) self.assertEqual( commit_log_model.user_id, skill_mappings_1[self.SKILL_1_ID]) # Verify second user is not yet deleted. metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-2' % self.SKILL_1_ID) self.assertEqual(metadata_model.committer_id, self.user_2_id) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-2' % self.SKILL_1_ID) self.assertEqual(commit_log_model.user_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. skill_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.skill] ) metadata_model = skill_models.SkillSnapshotMetadataModel.get_by_id( '%s-2' % self.SKILL_1_ID) self.assertEqual( metadata_model.committer_id, skill_mappings_2[self.SKILL_1_ID]) commit_log_model = skill_models.SkillCommitLogEntryModel.get_by_id( 'skill-%s-2' % self.SKILL_1_ID) self.assertEqual( commit_log_model.user_id, skill_mappings_2[self.SKILL_1_ID]) class WipeoutServiceVerifyDeleteSkillModelsTests(test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" SKILL_1_ID = 'skill_1_id' SKILL_2_ID = 'skill_2_id' USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' def setUp(self): super(WipeoutServiceVerifyDeleteSkillModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.set_admins((self.USER_1_USERNAME, self.USER_2_USERNAME)) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.save_new_skill(self.SKILL_1_ID, self.user_1_id) self.save_new_skill(self.SKILL_2_ID, self.user_2_id) wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_verification_is_successful(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verification_when_deletion_failed_is_unsuccessful(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_2_id)) skill_services.update_skill( self.user_2_id, self.SKILL_2_ID, [skill_domain.SkillChange({ 'cmd': skill_domain.CMD_UPDATE_SKILL_PROPERTY, 'property_name': skill_domain.SKILL_PROPERTY_LANGUAGE_CODE, 'new_value': 'cs', 'old_value': 'en' })], 'Change language.' ) self.assertFalse(wipeout_service.verify_user_deleted(self.user_2_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_2_id)) class WipeoutServiceDeleteStoryModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" TOPIC_1_ID = 'topic_1_id' STORY_1_ID = 'story_1_id' STORY_2_ID = 'story_2_id' USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' def setUp(self): super(WipeoutServiceDeleteStoryModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.save_new_topic( self.TOPIC_1_ID, self.user_1_id, abbreviated_name='abbrev-one', url_fragment='frag-one', canonical_story_ids=[self.STORY_1_ID]) self.save_new_story(self.STORY_1_ID, self.user_1_id, self.TOPIC_1_ID) wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_one_story_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. story_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.story] ) metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_1_ID) self.assertEqual( metadata_model.committer_id, story_mappings[self.STORY_1_ID]) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_1_ID) self.assertEqual( commit_log_model.user_id, story_mappings[self.STORY_1_ID]) def test_one_story_with_missing_snapshot_is_pseudonymized(self): story_models.StoryCommitLogEntryModel( id='story-%s-1' % self.STORY_2_ID, story_id=self.STORY_2_ID, user_id=self.user_1_id, commit_type='create_new', commit_cmds=[{}], post_commit_status=constants.ACTIVITY_STATUS_PUBLIC, version=1 ).put_for_human() with self.capture_logging(min_level=logging.ERROR) as log_messages: wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertEqual( log_messages, ['[WIPEOUT] The commit log model \'StoryCommitLogEntryModel\' and ' 'snapshot models [\'StorySnapshotMetadataModel\'] IDs differ. ' 'Snapshots without commit logs: [], ' 'commit logs without snapshots: [u\'%s\'].' % self.STORY_2_ID]) # Verify user is deleted. story_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.story] ) metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_1_ID) self.assertEqual( metadata_model.committer_id, story_mappings[self.STORY_1_ID]) commit_log_model_1 = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_1_ID) self.assertEqual( commit_log_model_1.user_id, story_mappings[self.STORY_1_ID]) commit_log_model_2 = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_2_ID) self.assertEqual( commit_log_model_2.user_id, story_mappings[self.STORY_2_ID]) def test_one_story_when_the_deletion_is_repeated_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Return metadata model to the original user ID. metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_1_ID) metadata_model.committer_id = self.user_1_id metadata_model.put_for_human() # Run the user deletion again. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify that both the commit and the metadata have the same # pseudonymous user ID. story_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.story] ) metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_1_ID) self.assertEqual( metadata_model.committer_id, story_mappings[self.STORY_1_ID]) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_1_ID) self.assertEqual( commit_log_model.user_id, story_mappings[self.STORY_1_ID]) def test_multiple_stories_are_pseudonymized(self): self.save_new_topic( self.TOPIC_1_ID, self.user_1_id, name='Topic 2', abbreviated_name='abbrev-two', url_fragment='frag-two') self.save_new_story(self.STORY_2_ID, self.user_1_id, self.TOPIC_1_ID) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) story_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.story] ) metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_1_ID) self.assertEqual( metadata_model.committer_id, story_mappings[self.STORY_1_ID]) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_1_ID) self.assertEqual( commit_log_model.user_id, story_mappings[self.STORY_1_ID]) metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_2_ID) self.assertEqual( metadata_model.committer_id, story_mappings[self.STORY_2_ID]) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_2_ID) self.assertEqual( commit_log_model.user_id, story_mappings[self.STORY_2_ID]) def test_multiple_stories_with_multiple_users_are_pseudonymized(self): self.save_new_topic( self.TOPIC_1_ID, self.user_2_id, name='Topic 2', abbreviated_name='abbrev-three', url_fragment='frag-three') self.save_new_story(self.STORY_2_ID, self.user_2_id, self.TOPIC_1_ID) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. story_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.story] ) metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_1_ID) self.assertEqual( metadata_model.committer_id, story_mappings_1[self.STORY_1_ID]) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_1_ID) self.assertEqual( commit_log_model.user_id, story_mappings_1[self.STORY_1_ID]) # Verify second user is not yet deleted. metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_2_ID) self.assertEqual(metadata_model.committer_id, self.user_2_id) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_2_ID) self.assertEqual(commit_log_model.user_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. story_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.story] ) metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_2_ID) self.assertEqual( metadata_model.committer_id, story_mappings_2[self.STORY_2_ID]) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_2_ID) self.assertEqual( commit_log_model.user_id, story_mappings_2[self.STORY_2_ID]) def test_one_story_with_multiple_users_is_pseudonymized(self): story_services.update_story( self.user_2_id, self.STORY_1_ID, [story_domain.StoryChange({ 'cmd': story_domain.CMD_ADD_STORY_NODE, 'node_id': 'node_1', 'title': 'Title 2' })], 'Add node.' ) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. story_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.story] ) metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-1' % self.STORY_1_ID) self.assertEqual( metadata_model.committer_id, story_mappings_1[self.STORY_1_ID]) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-1' % self.STORY_1_ID) self.assertEqual( commit_log_model.user_id, story_mappings_1[self.STORY_1_ID]) # Verify second user is not yet deleted. metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-2' % self.STORY_1_ID) self.assertEqual(metadata_model.committer_id, self.user_2_id) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-2' % self.STORY_1_ID) self.assertEqual(commit_log_model.user_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. story_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.story] ) metadata_model = story_models.StorySnapshotMetadataModel.get_by_id( '%s-2' % self.STORY_1_ID) self.assertEqual( metadata_model.committer_id, story_mappings_2[self.STORY_1_ID]) commit_log_model = story_models.StoryCommitLogEntryModel.get_by_id( 'story-%s-2' % self.STORY_1_ID) self.assertEqual( commit_log_model.user_id, story_mappings_2[self.STORY_1_ID]) class WipeoutServiceVerifyDeleteStoryModelsTests(test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" TOPIC_1_ID = 'topic_1_id' TOPIC_2_ID = 'topic_2_id' STORY_1_ID = 'story_1_id' STORY_2_ID = 'story_2_id' USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' def setUp(self): super(WipeoutServiceVerifyDeleteStoryModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.save_new_topic( self.TOPIC_1_ID, self.user_1_id, abbreviated_name='abbrev-four', url_fragment='frag-four') self.save_new_story(self.STORY_1_ID, self.user_1_id, self.TOPIC_1_ID) self.save_new_topic( self.TOPIC_2_ID, self.user_2_id, name='Topic 2', abbreviated_name='abbrev-five', url_fragment='frag-five', canonical_story_ids=[self.STORY_2_ID]) self.save_new_story(self.STORY_2_ID, self.user_2_id, self.TOPIC_2_ID) wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_verification_is_successful(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verification_when_deletion_failed_is_unsuccessful(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_2_id)) story_services.update_story( self.user_2_id, self.STORY_2_ID, [story_domain.StoryChange({ 'cmd': story_domain.CMD_ADD_STORY_NODE, 'node_id': 'node_1', 'title': 'Title 2' })], 'Add node.' ) self.assertFalse(wipeout_service.verify_user_deleted(self.user_2_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_2_id)) class WipeoutServiceDeleteSubtopicModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' TOP_1_ID = 'top_1_id' SUBTOP_1_ID = 'subtop_1_id' SUBTOP_2_ID = 'subtop_2_id' def setUp(self): super(WipeoutServiceDeleteSubtopicModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.save_new_topic(self.TOP_1_ID, self.user_1_id) self.subtopic_page = self.save_new_subtopic( self.SUBTOP_1_ID, self.user_1_id, self.TOP_1_ID) wipeout_service.pre_delete_user(self.user_1_id) wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_one_subtopic_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. subtopic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.subtopic] ) metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( metadata_model.committer_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( commit_log_model.user_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) def test_one_subtopic_with_missing_snapshot_is_pseudonymized(self): subtopic_models.SubtopicPageCommitLogEntryModel( id='%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_2_ID), subtopic_page_id=self.SUBTOP_2_ID, user_id=self.user_1_id, commit_type='create_new', commit_cmds=[{}], post_commit_status=constants.ACTIVITY_STATUS_PUBLIC, version=1 ).put_for_human() with self.capture_logging(min_level=logging.ERROR) as log_messages: wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertEqual( log_messages, ['[WIPEOUT] The commit log model ' '\'SubtopicPageCommitLogEntryModel\' and snapshot models ' '[\'SubtopicPageSnapshotMetadataModel\'] IDs differ. ' 'Snapshots without commit logs: [], ' 'commit logs without snapshots: [u\'%s\'].' % self.SUBTOP_2_ID]) # Verify user is deleted. subtopic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.subtopic] ) metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( metadata_model.committer_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( commit_log_model.user_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) def test_one_subtopic_when_the_deletion_is_repeated_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Return metadata model to the original user ID. metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) metadata_model.committer_id = self.user_1_id metadata_model.put_for_human() # Run the user deletion again. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify that both the commit and the metadata have the same # pseudonymous user ID. subtopic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.subtopic] ) metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( metadata_model.committer_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( commit_log_model.user_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) def test_multiple_subtopics_are_pseudonymized(self): self.save_new_subtopic(self.SUBTOP_2_ID, self.user_1_id, self.TOP_1_ID) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) subtopic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.subtopic] ) metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( metadata_model.committer_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( commit_log_model.user_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_2_ID))) self.assertEqual( metadata_model.committer_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_2_ID)]) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_2_ID))) self.assertEqual( commit_log_model.user_id, subtopic_mappings['%s-%s' % (self.TOP_1_ID, self.SUBTOP_2_ID)]) def test_multiple_subtopics_with_multiple_users_are_pseudonymized(self): self.save_new_subtopic(self.SUBTOP_2_ID, self.user_2_id, self.TOP_1_ID) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. subtopic_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.subtopic] ) metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( metadata_model.committer_id, subtopic_mappings_1['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( commit_log_model.user_id, subtopic_mappings_1['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) # Verify second user is not yet deleted. metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_2_ID))) self.assertEqual(metadata_model.committer_id, self.user_2_id) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_2_ID))) self.assertEqual(commit_log_model.user_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. subtopic_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.subtopic] ) metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_2_ID))) self.assertEqual( metadata_model.committer_id, subtopic_mappings_2['%s-%s' % (self.TOP_1_ID, self.SUBTOP_2_ID)]) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_2_ID))) self.assertEqual( commit_log_model.user_id, subtopic_mappings_2['%s-%s' % (self.TOP_1_ID, self.SUBTOP_2_ID)]) def test_one_subtopic_with_multiple_users_is_pseudonymized(self): subtopic_page_services.save_subtopic_page( self.user_2_id, self.subtopic_page, 'Change subtopic', [ subtopic_page_domain.SubtopicPageChange({ 'cmd': ( subtopic_page_domain.CMD_UPDATE_SUBTOPIC_PAGE_PROPERTY), 'property_name': ( subtopic_page_domain .SUBTOPIC_PAGE_PROPERTY_PAGE_CONTENTS_HTML), 'new_value': 'new value', 'old_value': 'old value', 'subtopic_id': self.SUBTOP_1_ID }) ] ) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify first user is deleted. subtopic_mappings_1 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.subtopic] ) metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( metadata_model.committer_id, subtopic_mappings_1['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( commit_log_model.user_id, subtopic_mappings_1['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) # Verify second user is not yet deleted. metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-2' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual(metadata_model.committer_id, self.user_2_id) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-2' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual(commit_log_model.user_id, self.user_2_id) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) # Verify second user is deleted. subtopic_mappings_2 = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_2_id ).pseudonymizable_entity_mappings[models.NAMES.subtopic] ) metadata_model = ( subtopic_models.SubtopicPageSnapshotMetadataModel.get_by_id( '%s-%s-2' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( metadata_model.committer_id, subtopic_mappings_2['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) commit_log_model = ( subtopic_models.SubtopicPageCommitLogEntryModel.get_by_id( 'subtopicpage-%s-%s-2' % (self.TOP_1_ID, self.SUBTOP_1_ID))) self.assertEqual( commit_log_model.user_id, subtopic_mappings_2['%s-%s' % (self.TOP_1_ID, self.SUBTOP_1_ID)]) class WipeoutServiceVerifyDeleteSubtopicModelsTests(test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' TOP_1_ID = 'top_1_id' SUBTOP_1_ID = 'subtop_1_id' def setUp(self): super(WipeoutServiceVerifyDeleteSubtopicModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.save_new_topic(self.TOP_1_ID, self.user_1_id) self.save_new_subtopic(self.SUBTOP_1_ID, self.user_1_id, self.TOP_1_ID) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_verification_is_successful(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verification_when_deletion_failed_is_unsuccessful(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) subtopic_models.SubtopicPageSnapshotMetadataModel( id='%s-%s-1' % (self.TOP_1_ID, self.SUBTOP_1_ID), committer_id=self.user_1_id, commit_message='123', commit_type='create', commit_cmds={} ).put_for_human() self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) class WipeoutServiceDeleteSuggestionModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' VOICEOVER_1_ID = 'voiceover_1_id' VOICEOVER_2_ID = 'voiceover_2_id' EXP_1_ID = 'exp_1_id' EXP_2_ID = 'exp_2_id' def setUp(self): super(WipeoutServiceDeleteSuggestionModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) suggestion_models.GeneralVoiceoverApplicationModel( id=self.VOICEOVER_1_ID, target_type=feconf.ENTITY_TYPE_EXPLORATION, target_id=self.EXP_1_ID, language_code='en', status=suggestion_models.STATUS_IN_REVIEW, content='Text', filename='filename.txt', author_id=self.user_1_id, final_reviewer_id=self.user_2_id, ).put() suggestion_models.GeneralVoiceoverApplicationModel( id=self.VOICEOVER_2_ID, target_type=feconf.ENTITY_TYPE_EXPLORATION, target_id=self.EXP_2_ID, language_code='en', status=suggestion_models.STATUS_IN_REVIEW, content='Text', filename='filename.txt', author_id=self.user_2_id, final_reviewer_id=self.user_1_id, ).put() wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_voiceover_application_is_pseudonymized(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) suggestion_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.suggestion] ) # Verify user is pseudonymized. voiceover_application_model_1 = ( suggestion_models.GeneralVoiceoverApplicationModel.get_by_id( self.VOICEOVER_1_ID) ) self.assertEqual( voiceover_application_model_1.author_id, suggestion_mappings[self.VOICEOVER_1_ID] ) voiceover_application_model_2 = ( suggestion_models.GeneralVoiceoverApplicationModel.get_by_id( self.VOICEOVER_2_ID) ) self.assertEqual( voiceover_application_model_2.final_reviewer_id, suggestion_mappings[self.VOICEOVER_2_ID] ) class WipeoutServiceVerifyDeleteSuggestionModelsTests( test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' VOICEOVER_1_ID = 'voiceover_1_id' VOICEOVER_2_ID = 'voiceover_2_id' EXP_1_ID = 'exp_1_id' EXP_2_ID = 'exp_2_id' def setUp(self): super(WipeoutServiceVerifyDeleteSuggestionModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) suggestion_models.GeneralVoiceoverApplicationModel( id=self.VOICEOVER_1_ID, target_type=feconf.ENTITY_TYPE_EXPLORATION, target_id=self.EXP_1_ID, language_code='en', status=suggestion_models.STATUS_IN_REVIEW, content='Text', filename='filename.txt', author_id=self.user_1_id, final_reviewer_id=self.user_2_id, ).put() suggestion_models.GeneralVoiceoverApplicationModel( id=self.VOICEOVER_2_ID, target_type=feconf.ENTITY_TYPE_EXPLORATION, target_id=self.EXP_2_ID, language_code='en', status=suggestion_models.STATUS_IN_REVIEW, content='Text', filename='filename.txt', author_id=self.user_2_id, final_reviewer_id=self.user_1_id, ).put() wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_verify_user_delete_when_user_is_deleted_returns_true(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verify_user_delete_when_user_is_not_deleted_returns_false(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) suggestion_models.GeneralVoiceoverApplicationModel( id=self.VOICEOVER_1_ID, target_type=feconf.ENTITY_TYPE_EXPLORATION, target_id=self.EXP_1_ID, language_code='en', status=suggestion_models.STATUS_IN_REVIEW, content='Text', filename='filename.txt', author_id=self.user_1_id, final_reviewer_id=self.user_2_id, ).put() self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) class WipeoutServiceDeleteTopicModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' TOP_1_ID = 'top_1_id' TOP_2_ID = 'top_2_id' def setUp(self): super(WipeoutServiceDeleteTopicModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) user_services.update_user_role( self.user_1_id, feconf.ROLE_ID_ADMIN) user_services.update_user_role( self.user_2_id, feconf.ROLE_ID_TOPIC_MANAGER) self.user_1_actions = user_services.UserActionsInfo(self.user_1_id) self.user_2_actions = user_services.UserActionsInfo(self.user_2_id) self.save_new_topic(self.TOP_1_ID, self.user_1_id) topic_services.assign_role( self.user_1_actions, self.user_1_actions, topic_domain.ROLE_MANAGER, self.TOP_1_ID) topic_services.assign_role( self.user_1_actions, self.user_2_actions, topic_domain.ROLE_MANAGER, self.TOP_1_ID) def test_one_topic_snapshot_metadata_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. topic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.topic] ) metadata_model = ( topic_models.TopicSnapshotMetadataModel.get_by_id( '%s-1' % self.TOP_1_ID) ) self.assertEqual( metadata_model.committer_id, topic_mappings[self.TOP_1_ID]) rights_metadata_model_1 = ( topic_models.TopicRightsSnapshotMetadataModel.get_by_id( '%s-1' % self.TOP_1_ID) ) self.assertEqual( rights_metadata_model_1.committer_id, topic_mappings[self.TOP_1_ID]) self.assertEqual( rights_metadata_model_1.content_user_ids, []) self.assertEqual(rights_metadata_model_1.commit_cmds_user_ids, []) rights_metadata_model_2 = ( topic_models.TopicRightsSnapshotMetadataModel.get_by_id( '%s-2' % self.TOP_1_ID) ) self.assertEqual( rights_metadata_model_2.committer_id, topic_mappings[self.TOP_1_ID]) self.assertEqual( rights_metadata_model_2.content_user_ids, [topic_mappings[self.TOP_1_ID]]) self.assertEqual( rights_metadata_model_2.commit_cmds_user_ids, [topic_mappings[self.TOP_1_ID]]) def test_one_topic_snapshot_content_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. topic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.topic] ) rights_content_model_1 = ( topic_models.TopicRightsSnapshotContentModel.get_by_id( '%s-1' % self.TOP_1_ID) ) self.assertEqual( rights_content_model_1.content['manager_ids'], []) rights_content_model_2 = ( topic_models.TopicRightsSnapshotContentModel.get_by_id( '%s-3' % self.TOP_1_ID) ) self.assertItemsEqual( rights_content_model_2.content['manager_ids'], [ topic_mappings[self.TOP_1_ID], self.user_2_id ]) def test_one_topic_commit_log_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify user is deleted. topic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.topic] ) commit_log_model_1 = ( topic_models.TopicCommitLogEntryModel.get_by_id( 'rights-%s-2' % self.TOP_1_ID) ) self.assertEqual( commit_log_model_1.user_id, topic_mappings[self.TOP_1_ID]) def test_one_topic_with_missing_snapshot_is_pseudonymized(self): topic_models.TopicCommitLogEntryModel( id='topic-%s-1' % self.TOP_2_ID, topic_id=self.TOP_2_ID, user_id=self.user_1_id, commit_type='create_new', commit_cmds=[{}], post_commit_status=constants.ACTIVITY_STATUS_PUBLIC, version=1 ).put_for_human() with self.capture_logging(min_level=logging.ERROR) as log_messages: wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertItemsEqual( log_messages, [ '[WIPEOUT] The commit log model \'TopicCommitLogEntryModel\' ' 'and snapshot models [\'TopicSnapshotMetadataModel\', ' '\'TopicRightsSnapshotMetadataModel\'] IDs differ. ' 'Snapshots without commit logs: [], ' 'commit logs without snapshots: [u\'%s\'].' % self.TOP_2_ID ] ) # Verify user is deleted. topic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.topic] ) metadata_model = ( topic_models.TopicSnapshotMetadataModel.get_by_id( '%s-1' % self.TOP_1_ID ) ) self.assertEqual( metadata_model.committer_id, topic_mappings[self.TOP_1_ID]) commit_log_model_1 = ( topic_models.TopicCommitLogEntryModel.get_by_id( 'topic-%s-1' % self.TOP_1_ID ) ) self.assertEqual( commit_log_model_1.user_id, topic_mappings[self.TOP_1_ID]) commit_log_model_2 = ( topic_models.TopicCommitLogEntryModel.get_by_id( 'topic-%s-1' % self.TOP_2_ID ) ) self.assertEqual( commit_log_model_2.user_id, topic_mappings[self.TOP_2_ID]) def test_one_topic_when_the_deletion_is_repeated_is_pseudonymized(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Return metadata model to the original user ID. metadata_model = ( topic_models.TopicSnapshotMetadataModel.get_by_id( '%s-1' % self.TOP_1_ID ) ) metadata_model.committer_id = self.user_1_id metadata_model.put_for_human() # Run the user deletion again. wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) # Verify that both the commit and the metadata have the same # pseudonymous user ID. topic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.topic] ) metadata_model = ( topic_models.TopicSnapshotMetadataModel.get_by_id( '%s-1' % self.TOP_1_ID ) ) self.assertEqual( metadata_model.committer_id, topic_mappings[self.TOP_1_ID]) commit_log_model = ( topic_models.TopicCommitLogEntryModel.get_by_id( 'topic-%s-1' % self.TOP_1_ID) ) self.assertEqual( commit_log_model.user_id, topic_mappings[self.TOP_1_ID]) def test_multiple_topics_are_pseudonymized(self): self.save_new_topic( self.TOP_2_ID, self.user_1_id, name='topic2', url_fragment='topic-two') wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) topic_mappings = ( user_models.PendingDeletionRequestModel.get_by_id( self.user_1_id ).pseudonymizable_entity_mappings[models.NAMES.topic] ) metadata_model = ( topic_models.TopicSnapshotMetadataModel.get_by_id( '%s-1' % self.TOP_1_ID ) ) self.assertEqual( metadata_model.committer_id, topic_mappings[self.TOP_1_ID]) commit_log_model = ( topic_models.TopicCommitLogEntryModel.get_by_id( 'topic-%s-1' % self.TOP_1_ID ) ) self.assertEqual( commit_log_model.user_id, topic_mappings[self.TOP_1_ID]) metadata_model = ( topic_models.TopicSnapshotMetadataModel.get_by_id( '%s-1' % self.TOP_2_ID ) ) self.assertEqual( metadata_model.committer_id, topic_mappings[self.TOP_2_ID]) commit_log_model = ( topic_models.TopicCommitLogEntryModel.get_by_id( 'topic-%s-1' % self.TOP_2_ID ) ) self.assertEqual( commit_log_model.user_id, topic_mappings[self.TOP_2_ID]) class WipeoutServiceVerifyDeleteTopicModelsTests(test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' TOP_1_ID = 'top_1_id' TOP_2_ID = 'top_2_id' SUBTOP_1_ID = 'subtop_1_id' def setUp(self): super(WipeoutServiceVerifyDeleteTopicModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.save_new_topic(self.TOP_1_ID, self.user_1_id) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() def test_verify_user_delete_when_user_is_deleted_returns_true(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) def test_verify_user_delete_when_user_is_not_deleted_returns_false(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) topic_models.TopicSnapshotMetadataModel( id='%s-1' % self.TOP_1_ID, committer_id=self.user_1_id, commit_message='123', commit_type='create', commit_cmds={} ).put_for_human() self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) class WipeoutServiceDeleteUserModelsTests(test_utils.GenericTestBase): """Provides testing of the deletion part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' COLLECTION_1_ID = 'col_1_id' COLLECTION_2_ID = 'col_2_id' EXPLORATION_1_ID = 'exp_1_id' EXPLORATION_2_ID = 'exp_2_id' def setUp(self): super(WipeoutServiceDeleteUserModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) user_models.CompletedActivitiesModel( id=self.user_2_id, exploration_ids=[], collection_ids=[] ).put() user_models.IncompleteActivitiesModel( id=self.user_2_id, exploration_ids=[], collection_ids=[] ).put() user_models.LearnerPlaylistModel( id=self.user_2_id, exploration_ids=[], collection_ids=[] ).put() self.user_1_auth_id = self.get_auth_id_from_email(self.USER_1_EMAIL) user_data_dict = { 'schema_version': 1, 'display_alias': 'display_alias', 'pin': '12345', 'preferred_language_codes': [constants.DEFAULT_LANGUAGE_CODE], 'preferred_site_language_code': None, 'preferred_audio_language_code': None, 'user_id': self.user_1_id, } new_user_data_dict = { 'schema_version': 1, 'display_alias': 'display_alias3', 'pin': '12345', 'preferred_language_codes': [constants.DEFAULT_LANGUAGE_CODE], 'preferred_site_language_code': None, 'preferred_audio_language_code': None, 'user_id': None, } self.modifiable_user_data = ( user_domain.ModifiableUserData.from_raw_dict(user_data_dict)) self.modifiable_new_user_data = ( user_domain.ModifiableUserData.from_raw_dict(new_user_data_dict)) user_services.update_multiple_users_data( [self.modifiable_user_data]) self.modifiable_new_user_data.display_alias = 'name' self.modifiable_new_user_data.pin = '123' self.profile_user_id = user_services.create_new_profiles( self.user_1_auth_id, self.USER_1_EMAIL, [self.modifiable_new_user_data] )[0].user_id user_models.CompletedActivitiesModel( id=self.profile_user_id, exploration_ids=[], collection_ids=[] ).put() user_models.IncompleteActivitiesModel( id=self.profile_user_id, exploration_ids=[], collection_ids=[] ).put() user_models.LearnerPlaylistModel( id=self.profile_user_id, exploration_ids=[], collection_ids=[] ).put() def test_delete_user_for_profile_user_is_successful(self): wipeout_service.pre_delete_user(self.profile_user_id) self.process_and_flush_pending_tasks() self.assertIsNone( auth_services.get_auth_id_from_user_id(self.profile_user_id)) self.assertTrue( auth_services.verify_external_auth_associations_are_deleted( self.profile_user_id)) self.assertIsNotNone( user_models.CompletedActivitiesModel.get_by_id( self.profile_user_id) ) self.assertIsNotNone( user_models.IncompleteActivitiesModel.get_by_id( self.profile_user_id) ) self.assertIsNotNone( user_models.LearnerPlaylistModel.get_by_id(self.profile_user_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.profile_user_id)) self.assertIsNone( user_models.CompletedActivitiesModel.get_by_id( self.profile_user_id) ) self.assertIsNone( user_models.IncompleteActivitiesModel.get_by_id( self.profile_user_id) ) self.assertIsNone( user_models.LearnerPlaylistModel.get_by_id(self.profile_user_id)) def test_delete_user_for_full_user_and_its_profiles_is_successful(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() self.assertIsNone( auth_services.get_auth_id_from_user_id(self.user_1_id)) # External auth associations should not have been deleted yet. self.assertFalse( auth_services.verify_external_auth_associations_are_deleted( self.user_1_id)) self.assertIsNotNone( user_models.CompletedActivitiesModel.get_by_id( self.profile_user_id)) self.assertIsNotNone( user_models.IncompleteActivitiesModel.get_by_id( self.profile_user_id)) self.assertIsNotNone( user_models.LearnerPlaylistModel.get_by_id(self.profile_user_id)) self.assertIsNotNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.profile_user_id)) self.assertIsNone( user_models.CompletedActivitiesModel.get_by_id( self.profile_user_id)) self.assertIsNone( user_models.IncompleteActivitiesModel.get_by_id( self.profile_user_id)) self.assertIsNone( user_models.LearnerPlaylistModel.get_by_id(self.profile_user_id)) self.assertIsNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_1_id)) def test_delete_user_with_collection_and_exploration_is_successful(self): self.save_new_valid_exploration( self.EXPLORATION_1_ID, self.user_1_id) self.save_new_valid_collection( self.COLLECTION_1_ID, self.user_1_id, exploration_id=self.EXPLORATION_1_ID) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() self.assertIsNone( collection_models.CollectionModel.get_by_id(self.COLLECTION_1_ID)) self.assertIsNone( exp_models.ExplorationModel.get_by_id(self.EXPLORATION_1_ID)) self.assertIsNotNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.profile_user_id)) self.assertIsNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_1_id)) def test_delete_user_with_collections_and_explorations_is_successful(self): self.save_new_valid_exploration( self.EXPLORATION_1_ID, self.user_1_id) self.save_new_valid_collection( self.COLLECTION_1_ID, self.user_1_id, exploration_id=self.EXPLORATION_1_ID) self.save_new_valid_exploration( self.EXPLORATION_2_ID, self.user_1_id) self.save_new_valid_collection( self.COLLECTION_2_ID, self.user_1_id, exploration_id=self.EXPLORATION_2_ID) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() self.assertIsNotNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_1_id)) self.assertIsNone( collection_models.CollectionModel.get_by_id(self.COLLECTION_1_ID)) self.assertIsNone( exp_models.ExplorationModel.get_by_id(self.EXPLORATION_1_ID)) self.assertIsNone( collection_models.CollectionModel.get_by_id(self.COLLECTION_2_ID)) self.assertIsNone( exp_models.ExplorationModel.get_by_id(self.EXPLORATION_2_ID)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.profile_user_id)) self.assertIsNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_1_id)) self.assertIsNone( collection_models.CollectionModel.get_by_id(self.COLLECTION_1_ID)) self.assertIsNone( exp_models.ExplorationModel.get_by_id(self.EXPLORATION_1_ID)) self.assertIsNone( collection_models.CollectionModel.get_by_id(self.COLLECTION_2_ID)) self.assertIsNone( exp_models.ExplorationModel.get_by_id(self.EXPLORATION_2_ID)) def test_delete_user_with_collection_and_exploration_repeated_is_successful( self): self.save_new_valid_exploration( self.EXPLORATION_1_ID, self.user_1_id) self.save_new_valid_collection( self.COLLECTION_1_ID, self.user_1_id, exploration_id=self.EXPLORATION_1_ID) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() self.assertIsNotNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_1_id)) self.assertIsNone( collection_models.CollectionModel.get_by_id(self.COLLECTION_1_ID)) self.assertIsNone( exp_models.ExplorationModel.get_by_id(self.EXPLORATION_1_ID)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertIsNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_1_id)) self.save_new_valid_exploration( self.EXPLORATION_1_ID, self.user_1_id) self.save_new_valid_collection( self.COLLECTION_1_ID, self.user_1_id, exploration_id=self.EXPLORATION_1_ID) self.assertIsNotNone( collection_models.CollectionModel.get_by_id(self.COLLECTION_1_ID)) self.assertIsNotNone( exp_models.ExplorationModel.get_by_id(self.EXPLORATION_1_ID)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertIsNone( collection_models.CollectionModel.get_by_id(self.COLLECTION_1_ID)) self.assertIsNone( exp_models.ExplorationModel.get_by_id(self.EXPLORATION_1_ID)) def test_delete_user_with_multiple_users_is_successful(self): wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() self.assertIsNotNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_2_id)) self.assertIsNotNone( user_models.CompletedActivitiesModel.get_by_id(self.user_2_id)) self.assertIsNotNone( user_models.IncompleteActivitiesModel.get_by_id(self.user_2_id)) self.assertIsNotNone( user_models.LearnerPlaylistModel.get_by_id(self.user_2_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) self.assertIsNone( user_models.UserEmailPreferencesModel.get_by_id(self.user_2_id)) self.assertIsNone( user_models.CompletedActivitiesModel.get_by_id(self.user_2_id)) self.assertIsNone( user_models.IncompleteActivitiesModel.get_by_id(self.user_2_id)) self.assertIsNone( user_models.LearnerPlaylistModel.get_by_id(self.user_2_id)) def test_after_deletion_user_and_its_profiles_cannot_do_anything(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.profile_user_id)) self.assertIsNone(user_services.get_user_settings(self.user_1_id)) self.assertIsNone(user_services.get_user_settings(self.profile_user_id)) with self.assertRaisesRegexp(Exception, 'User not found.'): # Try to do some action with the deleted user. user_services.update_preferred_language_codes( self.user_1_id, ['en']) with self.assertRaisesRegexp(Exception, 'User not found.'): # Try to do some action with the deleted user. user_services.update_preferred_language_codes( self.profile_user_id, ['en']) class WipeoutServiceVerifyDeleteUserModelsTests(test_utils.GenericTestBase): """Provides testing of the verification part of wipeout service.""" USER_1_EMAIL = '[email protected]' USER_1_USERNAME = 'username1' USER_2_EMAIL = '[email protected]' USER_2_USERNAME = 'username2' def setUp(self): super(WipeoutServiceVerifyDeleteUserModelsTests, self).setUp() self.signup(self.USER_1_EMAIL, self.USER_1_USERNAME) self.signup(self.USER_2_EMAIL, self.USER_2_USERNAME) self.user_1_id = self.get_user_id_from_email(self.USER_1_EMAIL) self.user_2_id = self.get_user_id_from_email(self.USER_2_EMAIL) self.user_1_auth_id = self.get_auth_id_from_email(self.USER_1_EMAIL) user_data_dict = { 'schema_version': 1, 'display_alias': 'display_alias', 'pin': '12345', 'preferred_language_codes': [constants.DEFAULT_LANGUAGE_CODE], 'preferred_site_language_code': None, 'preferred_audio_language_code': None, 'user_id': self.user_1_id, } new_user_data_dict = { 'schema_version': 1, 'display_alias': 'display_alias3', 'pin': '12345', 'preferred_language_codes': [constants.DEFAULT_LANGUAGE_CODE], 'preferred_site_language_code': None, 'preferred_audio_language_code': None, 'user_id': None, } self.modifiable_user_data = ( user_domain.ModifiableUserData.from_raw_dict(user_data_dict)) self.modifiable_new_user_data = ( user_domain.ModifiableUserData.from_raw_dict(new_user_data_dict)) user_services.update_multiple_users_data( [self.modifiable_user_data]) self.modifiable_new_user_data.display_alias = 'name' self.modifiable_new_user_data.pin = '123' self.profile_user_id = user_services.create_new_profiles( self.user_1_auth_id, self.USER_1_EMAIL, [self.modifiable_new_user_data] )[0].user_id wipeout_service.pre_delete_user(self.user_2_id) self.process_and_flush_pending_tasks() def test_verify_user_delete_when_profile_user_deleted_returns_true(self): wipeout_service.pre_delete_user(self.profile_user_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.profile_user_id)) self.assertTrue( wipeout_service.verify_user_deleted(self.profile_user_id)) def test_verify_user_delete_when_user_is_deleted_returns_true(self): wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_1_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.profile_user_id) ) self.assertTrue( wipeout_service.verify_user_deleted(self.profile_user_id)) def test_verify_user_delete_when_user_is_not_deleted_returns_false(self): wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_2_id)) user_models.CompletedActivitiesModel( id=self.user_2_id, exploration_ids=[], collection_ids=[] ).put() user_models.IncompleteActivitiesModel( id=self.user_2_id, exploration_ids=[], collection_ids=[] ).put() user_models.LearnerPlaylistModel( id=self.user_2_id, exploration_ids=[], collection_ids=[] ).put() self.assertFalse(wipeout_service.verify_user_deleted(self.user_2_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_2_id)) self.assertTrue(wipeout_service.verify_user_deleted(self.user_2_id)) def test_verify_user_delete_when_profile_user_not_deleted_is_false(self): wipeout_service.pre_delete_user(self.profile_user_id) self.process_and_flush_pending_tasks() wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.profile_user_id)) self.assertTrue( wipeout_service.verify_user_deleted(self.profile_user_id)) user_models.CompletedActivitiesModel( id=self.profile_user_id, exploration_ids=[], collection_ids=[] ).put() user_models.IncompleteActivitiesModel( id=self.profile_user_id, exploration_ids=[], collection_ids=[] ).put() user_models.LearnerPlaylistModel( id=self.profile_user_id, exploration_ids=[], collection_ids=[] ).put() self.assertFalse( wipeout_service.verify_user_deleted(self.profile_user_id)) wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.profile_user_id)) self.assertTrue( wipeout_service.verify_user_deleted(self.profile_user_id)) def test_verify_user_delete_when_external_auth_associations_are_not_deleted( self): self.assertFalse( auth_services.verify_external_auth_associations_are_deleted( self.user_1_id)) wipeout_service.pre_delete_user(self.user_1_id) self.process_and_flush_pending_tasks() delete_external_auth_associations_swap = self.swap_to_always_return( auth_services, 'delete_external_auth_associations') with delete_external_auth_associations_swap: wipeout_service.delete_user( wipeout_service.get_pending_deletion_request(self.user_1_id)) self.assertFalse(wipeout_service.verify_user_deleted(self.user_1_id))
41.629367
80
0.676327
[ "Apache-2.0" ]
kontesanjana/oppia
core/domain/wipeout_service_test.py
182,295
Python
from unittest.mock import call, PropertyMock, MagicMock import pytest from analytical_validation.exceptions import DataWasNotFitted from src.analytical_validation.validators.linearity_validator import LinearityValidator @pytest.fixture(scope='function') def fitted_result_obj(mocker): mock = mocker.Mock(create=True) mock.params = (mocker.Mock(), mocker.Mock()) mock.pvalues = (mocker.Mock(), mocker.Mock()) mock.ess = MagicMock() mock.ssr = MagicMock() mock.df_model = MagicMock() mock.df_resid = MagicMock() mock.resid = mocker.Mock() return mock @pytest.fixture(scope='function') def linearity_validator_obj(fitted_result_obj): analytical_data = [[0.100, 0.200, 0.150]] concentration_data = [[0.1, 0.2, 0.3]] linearity_validator = LinearityValidator(analytical_data, concentration_data) linearity_validator.fitted_result = fitted_result_obj return linearity_validator @pytest.fixture(scope='function') def linearity_validator_outlier_obj(): analytical_data = [[1.0, 1.0, 10.0], [2.0, 6.0, 2.0]] concentration_data = [[1.0, 2.0, 3.0], [8.0, 9.0, 10.0]] return LinearityValidator(analytical_data, concentration_data) @pytest.fixture(scope='function') def het_breuschpagan_mock(mocker): het_breuschpagan_mock = mocker.patch('analytical_validation.validators.linearity_validator.' 'statsmodelsapi.het_breuschpagan') het_breuschpagan_mock.return_value = (33, 42) return het_breuschpagan_mock @pytest.fixture(scope='function') def shapiro_mock(mocker, linearity_validator_obj): shapiro_mock = mocker.patch('analytical_validation.validators.linearity_validator.scipy.stats') shapiro_mock.shapiro(linearity_validator_obj.analytical_data).return_value = (0, 1) return shapiro_mock @pytest.fixture(scope='function') def durbin_watson_mock(mocker): durbin_watson_mock = mocker.patch('analytical_validation.validators.linearity_validator.stattools.durbin_watson') durbin_watson_mock.return_value = 1 return durbin_watson_mock @pytest.fixture(scope='function') def add_constant_mock(mocker): add_constant_mock = mocker.patch( 'analytical_validation.validators.linearity_validator.statsmodels.add_constant') return add_constant_mock @pytest.fixture(scope='function') def ordinary_least_squares_regression_mock(mocker): ordinary_least_squares_regression_mock = mocker.patch( 'analytical_validation.validators.linearity_validator.statsmodels.OLS') return ordinary_least_squares_regression_mock class TestLinearityValidator(object): def test_constructor_must_create_object_when_analytical_data_has_float_values(self, linearity_validator_obj): """Given analytical data The LinearityValidator Should create a list of floats """ # Assert assert linearity_validator_obj.analytical_data == [0.100, 0.200, 0.150] assert linearity_validator_obj.concentration_data == [0.1, 0.2, 0.3] def test_ordinary_least_squares_linear_regression_must_pass_float_when_given_correct_data(self, ordinary_least_squares_regression_mock, add_constant_mock, linearity_validator_obj): """Given concentration values = float The ordinary_least_squares_linear_regression Then must set properties""" # Act linearity_validator_obj.ordinary_least_squares_linear_regression() # Assert assert linearity_validator_obj.fitted_result == ordinary_least_squares_regression_mock.return_value.fit.return_value # Garante que a regressao e resultado do resultado do metodo statsmodels.OLS(), aplicado .fit(). assert ordinary_least_squares_regression_mock.called # Garante que o metodo ols esta sendo chamado assert ordinary_least_squares_regression_mock.call_args_list == [ call(linearity_validator_obj.analytical_data, add_constant_mock.return_value) # Garante que os arquivos de entrada definidos no call foram utilizados ] assert add_constant_mock.called assert add_constant_mock.call_args_list == [ call(linearity_validator_obj.concentration_data) ] def test_slope_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.slope == fitted_result_obj.params[1] def test_intercept_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.intercept == fitted_result_obj.params[0] def test_r_squared_adjusted_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.r_squared_adj == fitted_result_obj.rsquared_adj def test_r_squared_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.r_squared == fitted_result_obj.rsquared def test_regression_residues_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): """Given a regression model when regression_residues is called the regression residues must be created""" assert linearity_validator_obj.regression_residues == fitted_result_obj.resid.tolist() def test_sum_of_squares_model_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.sum_of_squares_model == fitted_result_obj.ess def test_sum_of_squares_total_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.sum_of_squares_total == fitted_result_obj.ess + fitted_result_obj.ssr def test_sum_of_squares_resid_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.sum_of_squares_resid == fitted_result_obj.ssr def test_degrees_of_freedom_model_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.degrees_of_freedom_model == fitted_result_obj.df_model def test_degrees_of_freedom_residues_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.degrees_of_freedom_residues == fitted_result_obj.df_resid def test_degrees_of_freedom_total_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.degrees_of_freedom_total == fitted_result_obj.df_model + fitted_result_obj.df_resid def test_mean_squared_error_model_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.mean_squared_error_model == fitted_result_obj.mse_model def test_mean_squared_error_residues_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.mean_squared_error_residues == fitted_result_obj.mse_resid def test_anova_f_value_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.anova_f_value == fitted_result_obj.fvalue def test_anova_f_pvalue_property_exists_when_fitted_result_not_none(self, linearity_validator_obj, fitted_result_obj): # Act & assert assert linearity_validator_obj.anova_f_pvalue == fitted_result_obj.f_pvalue @pytest.mark.parametrize('param_anova_f_pvalue, param_alpha, expected_result', [ (0.051, 0.05, False), (10, 0.1, False), (0.049, 0.05, True), (0.001, 0.10, True) ]) def test_valid_anova_f_pvalue_must_return_true_when_r_squared_is_greater_than_0990(self, param_alpha, linearity_validator_obj, param_anova_f_pvalue, expected_result): """Given data with an aceptable regression model When valid_anova_f_pvalue is called Then anova_f_pvalue < alpha must assert true""" # Arrange linearity_validator_obj.alpha = param_alpha linearity_validator_obj.fitted_result.f_pvalue = param_anova_f_pvalue # Act & Assert assert linearity_validator_obj.valid_anova_f_pvalue is expected_result @pytest.mark.parametrize('param_alpha, param_breusch_pagan_pvalue, expected_result', [ (1, -10, False), (0.05, 0.049, False), (0.10, 0.11, True), (0.05, 10, True) ]) def test_is_homokedastic_must_return_false_when_breusch_pagan_pvalue_is_smaller_than_alpha_otherwise_true(self, param_alpha, param_breusch_pagan_pvalue, expected_result): # Arrange analytical_data = [[0.100, 0.200, 0.150]] concentration_data = [[0.1, 0.2, 0.3]] linearity_validator = LinearityValidator(analytical_data, concentration_data, param_alpha) linearity_validator.breusch_pagan_pvalue = param_breusch_pagan_pvalue # Act & Assert assert linearity_validator.is_homoscedastic is expected_result @pytest.mark.parametrize('param_significant_slope, param_alpha, expected_result', [ (0.051, 0.05, False), (10, 0.1, False), (0.049, 0.05, True), (0.001, 0.10, True) ]) def test_significant_slope_must_return_true_when_slope_pvalue_is_smaller_than_alpha(self, linearity_validator_obj, param_significant_slope, param_alpha, expected_result): """Given homokedastic data When check_hypothesis is called Then slope_is_significant must assert true""" # Arrange linearity_validator_obj.alpha = param_alpha linearity_validator_obj.fitted_result.pvalues = ("mock value", param_significant_slope) # Act & Assert assert linearity_validator_obj.significant_slope is expected_result @pytest.mark.parametrize('param_insignificant_intercept, param_alpha, expected_result', [ (0.051, 0.05, True), (10, 0.1, True), (0.049, 0.05, False), (0.001, 0.10, False) ]) def test_insignificant_intercept_must_return_true_when_intercept_pvalue_is_greater_than_alpha(self, linearity_validator_obj, param_alpha, param_insignificant_intercept, expected_result): """Given homokedastic data When check_hypothesis is called Then intercept_not_significant must assert true""" # Arrange linearity_validator_obj.alpha = param_alpha linearity_validator_obj.fitted_result.pvalues = (param_insignificant_intercept, "mock value") # Act & Assert assert linearity_validator_obj.insignificant_intercept is expected_result @pytest.mark.parametrize('param_r_squared, expected_result', [ (1, True), (0.99, True), (0.98, False) ]) def test_valid_r_squared_must_return_true_when_r_squared_is_greater_than_0990(self, linearity_validator_obj, param_r_squared, expected_result): """Given homokedastic data When check_hypothesis is called Then r_squared > 0.990 must assert true""" # Arrange linearity_validator_obj.fitted_result.rsquared = param_r_squared # Act & Assert assert linearity_validator_obj.valid_r_squared is expected_result @pytest.mark.parametrize( 'param_significant_slope, param_insignificant_intercept, param_valid_r_squared, expected_result', [ (True, True, True, True), (True, False, False, False), (True, True, False, False), (False, True, True, False), (False, True, False, False), (False, False, False, False) ]) def test_valid_regression_model(self, mocker, param_significant_slope, param_insignificant_intercept, param_valid_r_squared, expected_result): # Arrange mocker.patch('unit.test_validators.test_linearity_validator.LinearityValidator.significant_slope', new_callable=PropertyMock, return_value=param_significant_slope) mocker.patch('unit.test_validators.test_linearity_validator.LinearityValidator.insignificant_intercept', new_callable=PropertyMock, return_value=param_insignificant_intercept) mocker.patch('unit.test_validators.test_linearity_validator.LinearityValidator.valid_r_squared', new_callable=PropertyMock, return_value=param_valid_r_squared) analytical_data = [[0.100, 0.200, 0.150]] concentration_data = [[0.2, 0.2, 0.3]] linearity_validator = LinearityValidator(analytical_data, concentration_data) # Act & Assert assert linearity_validator.valid_regression_model is expected_result def test_check_outliers_when_given_list_of_list_data(self, linearity_validator_outlier_obj): linearity_validator_outlier_obj.check_outliers() assert linearity_validator_outlier_obj.outliers == [[10.0], [6.0]] assert linearity_validator_outlier_obj.cleaned_analytical_data == [[1.0, 1.0], [2.0, 2.0]] assert linearity_validator_outlier_obj.cleaned_concentration_data == [[1.0, 2.0], [8.0, 10.0]] @pytest.mark.parametrize('param_shapiro_pvalue, param_alpha, expected_result', [ (10, 0.05, True), (0.01, 0.1, False), (0.0501, 0.05, True), (0.099, 0.1, False) ]) def test_is_normal_distribution(self, param_shapiro_pvalue, param_alpha, expected_result): analytical_data = [[0.100, 0.200, 0.150]] concentration_data = [[0.2, 0.2, 0.3]] validator = LinearityValidator(analytical_data, concentration_data, param_alpha) validator.shapiro_pvalue = param_shapiro_pvalue # Assert assert validator.is_normal_distribution is expected_result def test_run_breusch_pagan_test_must_raise_exception_when_model_is_none(self): """Not given a model parameter The check_homokedasticity Should raise exception""" # Arrange analytical_data = [[0.100, 0.200, 0.150]] concentration_data = [[0.2, 0.2, 0.3]] # Act & Assert with pytest.raises(DataWasNotFitted): LinearityValidator(analytical_data, concentration_data).run_breusch_pagan_test() def test_run_breusch_pagan_test(self, linearity_validator_obj, het_breuschpagan_mock): """Given heterokedastic data When check_homokedasticity is called Then must return false""" # Act linearity_validator_obj.run_breusch_pagan_test() # Assert assert linearity_validator_obj.breusch_pagan_pvalue == 42 assert het_breuschpagan_mock.called assert het_breuschpagan_mock.call_args_list == [ call(linearity_validator_obj.fitted_result.resid, linearity_validator_obj.fitted_result.model.exog) ] @pytest.mark.parametrize('durbin_watson_pvalue', [ 0.1, 1, 2, 2.5, 3, 3.9 ]) def test_check_residual_autocorrelation(self, linearity_validator_obj, durbin_watson_mock, durbin_watson_pvalue): """Given data When residual_autocorrelation is called Then must create durbin_watson_value""" # Arrange durbin_watson_mock.return_value = durbin_watson_pvalue # Act linearity_validator_obj.check_residual_autocorrelation() # Assert assert linearity_validator_obj.durbin_watson_value == durbin_watson_mock.return_value assert durbin_watson_mock.called assert durbin_watson_mock.call_args_list == [ call(linearity_validator_obj.fitted_result.resid) ] def test_check_residual_autocorrelation_must_raise_exception_when_data_not_fitted(self, linearity_validator_obj): """Given data, if no regression was calculated Should raise an exception""" # Arrange linearity_validator_obj.fitted_result = None # Act & assert with pytest.raises(DataWasNotFitted): linearity_validator_obj.check_residual_autocorrelation() @pytest.mark.parametrize('durbin_watson_pvalue', [ -1, 10, 4.1 ]) def test_check_residual_autocorrelation_must_pass_when_durbin_watson_value_is_between_0_and_4(self, linearity_validator_obj, durbin_watson_mock, durbin_watson_pvalue): """Given data, When check_residual is called after fitting the model Should pass creating 0 < durbin_watson_value < 4""" # Arrange durbin_watson_mock.return_value = durbin_watson_pvalue # Act & Assert assert linearity_validator_obj.durbin_watson_value is None
54.140884
222
0.643247
[ "MIT" ]
abxsantos/analytical-validation
tests/unit/test_validators/test_linearity_validator.py
19,599
Python
# 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 json import logging import time from copy import copy from datetime import datetime from typing import Any, Dict, Optional from flask_babel import lazy_gettext as _ from sqlalchemy.orm import make_transient, Session from superset import ConnectorRegistry, db from superset.commands.base import BaseCommand from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn from superset.datasets.commands.importers.v0 import import_dataset from superset.exceptions import DashboardImportException from superset.models.dashboard import Dashboard from superset.models.slice import Slice from superset.models.core import Database from superset.utils.dashboard_filter_scopes_converter import ( convert_filter_scopes, copy_filter_scopes, ) logger = logging.getLogger(__name__) def import_chart( slc_to_import: Slice, slc_to_override: Optional[Slice], import_time: Optional[int] = None, ) -> int: """Inserts or overrides slc in the database. remote_id and import_time fields in params_dict are set to track the slice origin and ensure correct overrides for multiple imports. Slice.perm is used to find the datasources and connect them. :param Slice slc_to_import: Slice object to import :param Slice slc_to_override: Slice to replace, id matches remote_id :returns: The resulting id for the imported slice :rtype: int """ session = db.session make_transient(slc_to_import) slc_to_import.dashboards = [] slc_to_import.alter_params(remote_id=slc_to_import.id, import_time=import_time) slc_to_import = slc_to_import.copy() slc_to_import.reset_ownership() params = slc_to_import.params_dict datasource = ConnectorRegistry.get_datasource_by_name( session, slc_to_import.datasource_type, params["datasource_name"], params["schema"], params["database_name"], ) slc_to_import.datasource_id = datasource.id # type: ignore if slc_to_override: slc_to_override.override(slc_to_import) session.flush() return slc_to_override.id session.add(slc_to_import) logger.info("Final slice: %s", str(slc_to_import.to_json())) session.flush() return slc_to_import.id def import_dashboard( # pylint: disable=too-many-locals,too-many-statements dashboard_to_import: Dashboard, dataset_id_mapping: Optional[Dict[int, int]] = None, import_time: Optional[int] = None, database_id: Optional[int] = None, ) -> int: """Imports the dashboard from the object to the database. Once dashboard is imported, json_metadata field is extended and stores remote_id and import_time. It helps to decide if the dashboard has to be overridden or just copies over. Slices that belong to this dashboard will be wired to existing tables. This function can be used to import/export dashboards between multiple superset instances. Audit metadata isn't copied over. """ def alter_positions( dashboard: Dashboard, old_to_new_slc_id_dict: Dict[int, int] ) -> None: """Updates slice_ids in the position json. Sample position_json data: { "DASHBOARD_VERSION_KEY": "v2", "DASHBOARD_ROOT_ID": { "type": "DASHBOARD_ROOT_TYPE", "id": "DASHBOARD_ROOT_ID", "children": ["DASHBOARD_GRID_ID"] }, "DASHBOARD_GRID_ID": { "type": "DASHBOARD_GRID_TYPE", "id": "DASHBOARD_GRID_ID", "children": ["DASHBOARD_CHART_TYPE-2"] }, "DASHBOARD_CHART_TYPE-2": { "type": "CHART", "id": "DASHBOARD_CHART_TYPE-2", "children": [], "meta": { "width": 4, "height": 50, "chartId": 118 } }, } """ position_data = json.loads(dashboard.position_json) position_json = position_data.values() for value in position_json: if ( isinstance(value, dict) and value.get("meta") and value.get("meta", {}).get("chartId") ): old_slice_id = value["meta"]["chartId"] if old_slice_id in old_to_new_slc_id_dict: value["meta"]["chartId"] = old_to_new_slc_id_dict[old_slice_id] dashboard.position_json = json.dumps(position_data) def alter_native_filters(dashboard: Dashboard) -> None: json_metadata = json.loads(dashboard.json_metadata) native_filter_configuration = json_metadata.get("native_filter_configuration") if not native_filter_configuration: return for native_filter in native_filter_configuration: for target in native_filter.get("targets", []): old_dataset_id = target.get("datasetId") if dataset_id_mapping and old_dataset_id is not None: target["datasetId"] = dataset_id_mapping.get( old_dataset_id, old_dataset_id, ) dashboard.json_metadata = json.dumps(json_metadata) logger.info("Started import of the dashboard: %s", dashboard_to_import.to_json()) session = db.session logger.info("Dashboard has %d slices", len(dashboard_to_import.slices)) # copy slices object as Slice.import_slice will mutate the slice # and will remove the existing dashboard - slice association slices = copy(dashboard_to_import.slices) # Clearing the slug to avoid conflicts dashboard_to_import.slug = None old_json_metadata = json.loads(dashboard_to_import.json_metadata or "{}") old_to_new_slc_id_dict: Dict[int, int] = {} new_timed_refresh_immune_slices = [] new_expanded_slices = {} new_filter_scopes = {} i_params_dict = dashboard_to_import.params_dict remote_id_slice_map = { slc.params_dict["remote_id"]: slc for slc in session.query(Slice) .filter(Slice.datasource_id.in_(list(dataset_id_mapping.values()))) .all() if "remote_id" in slc.params_dict } for slc in slices: logger.info( "Importing slice %s from the dashboard: %s", slc.to_json(), dashboard_to_import.dashboard_title, ) # Change database name in params due to using new database for imported dashboard if database_id: database_name = session.query(Database).filter(Database.id == database_id).first().name slc.alter_params(database_name=database_name) remote_slc = remote_id_slice_map.get(slc.id) new_slc_id = import_chart(slc, remote_slc, import_time=import_time) old_to_new_slc_id_dict[slc.id] = new_slc_id # update json metadata that deals with slice ids new_slc_id_str = str(new_slc_id) old_slc_id_str = str(slc.id) if ( "timed_refresh_immune_slices" in i_params_dict and old_slc_id_str in i_params_dict["timed_refresh_immune_slices"] ): new_timed_refresh_immune_slices.append(new_slc_id_str) if ( "expanded_slices" in i_params_dict and old_slc_id_str in i_params_dict["expanded_slices"] ): new_expanded_slices[new_slc_id_str] = i_params_dict["expanded_slices"][ old_slc_id_str ] # since PR #9109, filter_immune_slices and filter_immune_slice_fields # are converted to filter_scopes # but dashboard create from import may still have old dashboard filter metadata # here we convert them to new filter_scopes metadata first filter_scopes = {} if ( "filter_immune_slices" in i_params_dict or "filter_immune_slice_fields" in i_params_dict ): filter_scopes = convert_filter_scopes(old_json_metadata, slices) if "filter_scopes" in i_params_dict: filter_scopes = old_json_metadata.get("filter_scopes") # then replace old slice id to new slice id: if filter_scopes: new_filter_scopes = copy_filter_scopes( old_to_new_slc_id_dict=old_to_new_slc_id_dict, old_filter_scopes=filter_scopes, ) # override the dashboard existing_dashboard = None for dash in session.query(Dashboard).all(): if ( "remote_id" in dash.params_dict and dash.params_dict["remote_id"] == dashboard_to_import.id ): existing_dashboard = dash dashboard_to_import = dashboard_to_import.copy() dashboard_to_import.id = None dashboard_to_import.reset_ownership() # position_json can be empty for dashboards # with charts added from chart-edit page and without re-arranging if dashboard_to_import.position_json: alter_positions(dashboard_to_import, old_to_new_slc_id_dict) dashboard_to_import.alter_params(import_time=import_time) dashboard_to_import.remove_params(param_to_remove="filter_immune_slices") dashboard_to_import.remove_params(param_to_remove="filter_immune_slice_fields") if new_filter_scopes: dashboard_to_import.alter_params(filter_scopes=new_filter_scopes) if new_expanded_slices: dashboard_to_import.alter_params(expanded_slices=new_expanded_slices) if new_timed_refresh_immune_slices: dashboard_to_import.alter_params( timed_refresh_immune_slices=new_timed_refresh_immune_slices ) alter_native_filters(dashboard_to_import) new_slices = ( session.query(Slice).filter(Slice.id.in_(old_to_new_slc_id_dict.values())).all() ) if existing_dashboard: existing_dashboard.override(dashboard_to_import) existing_dashboard.slices = new_slices session.flush() return existing_dashboard.id dashboard_to_import.slices = new_slices session.add(dashboard_to_import) session.flush() return dashboard_to_import.id # type: ignore def decode_dashboards( # pylint: disable=too-many-return-statements o: Dict[str, Any] ) -> Any: """ Function to be passed into json.loads obj_hook parameter Recreates the dashboard object from a json representation. """ # pylint: disable=import-outside-toplevel from superset.connectors.druid.models import ( DruidCluster, DruidColumn, DruidDatasource, DruidMetric, ) if "__Dashboard__" in o: return Dashboard(**o["__Dashboard__"]) if "__Slice__" in o: return Slice(**o["__Slice__"]) if "__TableColumn__" in o: return TableColumn(**o["__TableColumn__"]) if "__SqlaTable__" in o: return SqlaTable(**o["__SqlaTable__"]) if "__SqlMetric__" in o: return SqlMetric(**o["__SqlMetric__"]) if "__DruidCluster__" in o: return DruidCluster(**o["__DruidCluster__"]) if "__DruidColumn__" in o: return DruidColumn(**o["__DruidColumn__"]) if "__DruidDatasource__" in o: return DruidDatasource(**o["__DruidDatasource__"]) if "__DruidMetric__" in o: return DruidMetric(**o["__DruidMetric__"]) if "__datetime__" in o: return datetime.strptime(o["__datetime__"], "%Y-%m-%dT%H:%M:%S") return o def import_dashboards( session: Session, content: str, database_id: Optional[int] = None, import_time: Optional[int] = None, ) -> None: """Imports dashboards from a stream to databases""" current_tt = int(time.time()) import_time = current_tt if import_time is None else import_time data = json.loads(content, object_hook=decode_dashboards) if not data: raise DashboardImportException(_("No data in file")) dataset_id_mapping: Dict[int, int] = {} for table in data["datasources"]: new_dataset_id = import_dataset(table, database_id, import_time=import_time) params = json.loads(table.params) dataset_id_mapping[params["remote_id"]] = new_dataset_id session.commit() for dashboard in data["dashboards"]: import_dashboard(dashboard, dataset_id_mapping, import_time=import_time, database_id=database_id) session.commit() class ImportDashboardsCommand(BaseCommand): """ Import dashboard in JSON format. This is the original unversioned format used to export and import dashboards in Superset. """ # pylint: disable=unused-argument def __init__( self, contents: Dict[str, str], database_id: Optional[int] = None, **kwargs: Any ): self.contents = contents self.database_id = database_id def run(self) -> None: self.validate() for file_name, content in self.contents.items(): logger.info("Importing dashboard from file %s", file_name) import_dashboards(db.session, content, self.database_id) def validate(self) -> None: # ensure all files are JSON for content in self.contents.values(): try: json.loads(content) except ValueError: logger.exception("Invalid JSON file") raise
37.509383
99
0.67715
[ "Apache-2.0" ]
Jacob-ru/superset
superset/dashboards/commands/importers/v0.py
13,991
Python
from datetime import datetime from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.backends import RemoteUserBackend from django.contrib.auth.middleware import RemoteUserMiddleware from django.contrib.auth.models import User from django.contrib.auth.tests.utils import skipIfCustomUser from django.test import TestCase, override_settings from django.utils import timezone @skipIfCustomUser @override_settings(ROOT_URLCONF='django.contrib.auth.tests.urls') class RemoteUserTest(TestCase): middleware = 'django.contrib.auth.middleware.RemoteUserMiddleware' backend = 'django.contrib.auth.backends.RemoteUserBackend' header = 'REMOTE_USER' # Usernames to be passed in REMOTE_USER for the test_known_user test case. known_user = 'knownuser' known_user2 = 'knownuser2' def setUp(self): self.curr_middleware = settings.MIDDLEWARE_CLASSES self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.MIDDLEWARE_CLASSES += (self.middleware,) settings.AUTHENTICATION_BACKENDS += (self.backend,) def test_no_remote_user(self): """ Tests requests where no remote user is specified and insures that no users get created. """ num_users = User.objects.count() response = self.client.get('/remote_user/') self.assertTrue(response.context['user'].is_anonymous()) self.assertEqual(User.objects.count(), num_users) response = self.client.get('/remote_user/', **{self.header: None}) self.assertTrue(response.context['user'].is_anonymous()) self.assertEqual(User.objects.count(), num_users) response = self.client.get('/remote_user/', **{self.header: ''}) self.assertTrue(response.context['user'].is_anonymous()) self.assertEqual(User.objects.count(), num_users) def test_unknown_user(self): """ Tests the case where the username passed in the header does not exist as a User. """ num_users = User.objects.count() response = self.client.get('/remote_user/', **{self.header: 'newuser'}) self.assertEqual(response.context['user'].username, 'newuser') self.assertEqual(User.objects.count(), num_users + 1) User.objects.get(username='newuser') # Another request with same user should not create any new users. response = self.client.get('/remote_user/', **{self.header: 'newuser'}) self.assertEqual(User.objects.count(), num_users + 1) def test_known_user(self): """ Tests the case where the username passed in the header is a valid User. """ User.objects.create(username='knownuser') User.objects.create(username='knownuser2') num_users = User.objects.count() response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(response.context['user'].username, 'knownuser') self.assertEqual(User.objects.count(), num_users) # Test that a different user passed in the headers causes the new user # to be logged in. response = self.client.get('/remote_user/', **{self.header: self.known_user2}) self.assertEqual(response.context['user'].username, 'knownuser2') self.assertEqual(User.objects.count(), num_users) def test_last_login(self): """ Tests that a user's last_login is set the first time they make a request but not updated in subsequent requests with the same session. """ user = User.objects.create(username='knownuser') # Set last_login to something so we can determine if it changes. default_login = datetime(2000, 1, 1) if settings.USE_TZ: default_login = default_login.replace(tzinfo=timezone.utc) user.last_login = default_login user.save() response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertNotEqual(default_login, response.context['user'].last_login) user = User.objects.get(username='knownuser') user.last_login = default_login user.save() response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(default_login, response.context['user'].last_login) def test_header_disappears(self): """ Tests that a logged in user is logged out automatically when the REMOTE_USER header disappears during the same browser session. """ User.objects.create(username='knownuser') # Known user authenticates response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(response.context['user'].username, 'knownuser') # During the session, the REMOTE_USER header disappears. Should trigger logout. response = self.client.get('/remote_user/') self.assertEqual(response.context['user'].is_anonymous(), True) # verify the remoteuser middleware will not remove a user # authenticated via another backend User.objects.create_user(username='modeluser', password='foo') self.client.login(username='modeluser', password='foo') authenticate(username='modeluser', password='foo') response = self.client.get('/remote_user/') self.assertEqual(response.context['user'].username, 'modeluser') def test_user_switch_forces_new_login(self): """ Tests that if the username in the header changes between requests that the original user is logged out """ User.objects.create(username='knownuser') # Known user authenticates response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(response.context['user'].username, 'knownuser') # During the session, the REMOTE_USER changes to a different user. response = self.client.get('/remote_user/', **{self.header: "newnewuser"}) # Ensure that the current user is not the prior remote_user # In backends that create a new user, username is "newnewuser" # In backends that do not create new users, it is '' (anonymous user) self.assertNotEqual(response.context['user'].username, 'knownuser') def tearDown(self): """Restores settings to avoid breaking other tests.""" settings.MIDDLEWARE_CLASSES = self.curr_middleware settings.AUTHENTICATION_BACKENDS = self.curr_auth class RemoteUserNoCreateBackend(RemoteUserBackend): """Backend that doesn't create unknown users.""" create_unknown_user = False @skipIfCustomUser class RemoteUserNoCreateTest(RemoteUserTest): """ Contains the same tests as RemoteUserTest, but using a custom auth backend class that doesn't create unknown users. """ backend = 'django.contrib.auth.tests.test_remote_user.RemoteUserNoCreateBackend' def test_unknown_user(self): num_users = User.objects.count() response = self.client.get('/remote_user/', **{self.header: 'newuser'}) self.assertTrue(response.context['user'].is_anonymous()) self.assertEqual(User.objects.count(), num_users) class CustomRemoteUserBackend(RemoteUserBackend): """ Backend that overrides RemoteUserBackend methods. """ def clean_username(self, username): """ Grabs username before the @ character. """ return username.split('@')[0] def configure_user(self, user): """ Sets user's email address. """ user.email = '[email protected]' user.save() return user @skipIfCustomUser class RemoteUserCustomTest(RemoteUserTest): """ Tests a custom RemoteUserBackend subclass that overrides the clean_username and configure_user methods. """ backend = 'django.contrib.auth.tests.test_remote_user.CustomRemoteUserBackend' # REMOTE_USER strings with email addresses for the custom backend to # clean. known_user = '[email protected]' known_user2 = '[email protected]' def test_known_user(self): """ The strings passed in REMOTE_USER should be cleaned and the known users should not have been configured with an email address. """ super(RemoteUserCustomTest, self).test_known_user() self.assertEqual(User.objects.get(username='knownuser').email, '') self.assertEqual(User.objects.get(username='knownuser2').email, '') def test_unknown_user(self): """ The unknown user created should be configured with an email address. """ super(RemoteUserCustomTest, self).test_unknown_user() newuser = User.objects.get(username='newuser') self.assertEqual(newuser.email, '[email protected]') class CustomHeaderMiddleware(RemoteUserMiddleware): """ Middleware that overrides custom HTTP auth user header. """ header = 'HTTP_AUTHUSER' @skipIfCustomUser class CustomHeaderRemoteUserTest(RemoteUserTest): """ Tests a custom RemoteUserMiddleware subclass with custom HTTP auth user header. """ middleware = ( 'django.contrib.auth.tests.test_remote_user.CustomHeaderMiddleware' ) header = 'HTTP_AUTHUSER'
39.717842
87
0.66496
[ "BSD-3-Clause" ]
2roy999/django
django/contrib/auth/tests/test_remote_user.py
9,572
Python
import pandas as pd import numpy as np from torch.utils.data import Dataset import os from PIL import Image class CXRDataset(Dataset): def __init__( self, path_to_images, fold, transform=None, sample=0, finding="any",): self.transform = transform self.path_to_images = path_to_images self.df = pd.read_csv("nih/nih_labels.csv") self.df = self.df[self.df['fold'] == fold] # can limit to sample, useful for testing # if fold == "train" or fold =="val": sample=500 if(sample > 0 and sample < len(self.df)): self.df = self.df.sample(sample) if not finding == "any": # can filter for positive findings of the kind described; useful for evaluation if finding in self.df.columns: if len(self.df[self.df[finding] == 1]) > 0: self.df = self.df[self.df[finding] == 1] else: print("No positive cases exist for "+LABEL+", returning all unfiltered cases") else: print("cannot filter on finding " + finding + " as not in data - please check spelling") self.df = self.df.set_index("Image Index") self.PRED_LABEL = [ 'No Finding', 'Atelectasis', 'Cardiomegaly', 'Effusion', 'Infiltration', 'Lung Lesion', 'Pneumonia', 'Pneumothorax', 'Consolidation', 'Edema', 'Emphysema', 'Fibrosis', 'Pleural_Thickening', 'Hernia'] RESULT_PATH = "results/" def __len__(self): return len(self.df) def __getitem__(self, idx): image = Image.open( os.path.join( self.path_to_images, self.df.index[idx])) image = image.convert('RGB') label = np.zeros(len(self.PRED_LABEL), dtype=int) for i in range(0, len(self.PRED_LABEL)): # can leave zero if zero, else make one if(self.df[self.PRED_LABEL[i].strip()].iloc[idx].astype('int') > 0): label[i] = self.df[self.PRED_LABEL[i].strip() ].iloc[idx].astype('int') if self.transform: image = self.transform(image) return (image, label,self.df.index[idx])
31
113
0.518987
[ "Apache-2.0" ]
edupooch/cxr-domain-shift
nih/loader.py
2,449
Python
from job import * class NoncookingJob(Job): def __init__(self, name, prefs, maxMatches): Job.__init__(self, name, prefs, maxMatches) # remove pairs & underclassmen self.prefs = filter(lambda x: x.numPeople != 1 and x.semsCooked < 4, self.prefs) # sort all the people by number of semesters cooked, high to low prefs.sort(key=lambda x: x.semsCooked, reverse=True)
37.6
83
0.728723
[ "MIT" ]
vmlane/jobMatcher
noncookingjob.py
376
Python
import math import pandas as pd import spacy # Requires: python -m spacy download en_core_web_sm from spacy import displacy from nltk import sent_tokenize, word_tokenize, PorterStemmer from nltk.corpus import stopwords from data import load_model import streamlit as st class tf_idf(): nlp = load_model('en_core_web_md') def word_freq(self, text) -> dict: """ Create document word frequency table {w1:f1, ..., wN:fN}. Remove stop words, punct, etc. and lowercase :rtype: dict """ doc = self.nlp(text) word_freq_table = {} for token in doc: ignore = token.is_stop or token.is_punct or token.is_quote or token.is_oov or token.text in ['.',',',';',':','%','-'] if not ignore and token.text in word_freq_table: word_freq_table[token.lower_] += 1 elif not ignore: word_freq_table[token.lower_] = 1 return word_freq_table def sent_word_freq(self, text) -> dict: """ Create sentence word frequency table {s1:{w1:f1, ..., wN:fN}, ..., sN:{w1:f1, ..., wN:fN} }. :rtype: dict """ doc = self.nlp(text) sent_word_freq_table = {} for sent in doc.sents: word_freq_table = self.word_freq(sent.lower_) sent_word_freq_table[sent.lower_[:15]] = word_freq_table return sent_word_freq_table def tf_matrix(self, sent_word_freq_table) -> dict: tf_matrix = {} for sent, word_freq_table in sent_word_freq_table.items(): tf_table = {} sent_word_count = len(word_freq_table) for word, freq in word_freq_table.items(): tf_table[word] = freq / sent_word_count tf_matrix[sent] = tf_table return tf_matrix def global_word_freq(self, tf_matrix) -> dict: tf_global_matrix = {} for sent, f_table in tf_matrix.items(): for word, count in f_table.items(): if word in tf_global_matrix: tf_global_matrix[word] += count else: tf_global_matrix[word] = count return tf_global_matrix def idf(self, tf_matrix, tf_global_matrix) -> dict: total_documents = len(tf_matrix) idf_matrix = {} for sent, f_table in tf_matrix.items(): idf_table = {} for word in f_table.keys(): idf_table[word] = math.log10(total_documents / float(tf_global_matrix[word])) idf_matrix[sent] = idf_table return idf_matrix def tf_idf(self, tf_matrix, idf_matrix) -> dict: tf_idf_matrix = {} for (sent1, f_table1), (sent2, f_table2) in zip(tf_matrix.items(), idf_matrix.items()): tf_idf_table = {} for (word1, value1), (word2, value2) in zip(f_table1.items(),f_table2.items()): # here, keys are the same in both the table tf_idf_table[word1] = float(value1 * value2) tf_idf_matrix[sent1] = tf_idf_table return tf_idf_matrix def score_sentences(self, tf_idf_matrix) -> dict: # Score sentences by their word TFs # Algorithm: adds word TFs and divides by total no of words in sentence. Normalise scale in range [0..10] sentenceScores = {} for sent, f_table in tf_idf_matrix.items(): sent_word_count = len(f_table) scores = [score for _word, score in f_table.items()] if len(scores) > 0: maxScore = max(scores) normScores = [score/maxScore for score in scores] total_sent_score = sum(normScores) sentenceScores[sent] = total_sent_score / sent_word_count else: sentenceScores[sent] = 0.0 return sentenceScores def average_score(self, sentenceScores) -> int: sumScores = sum([sentenceScores[entry] for entry in sentenceScores]) # Average score of a sentence from original summary_text average = sumScores / len(sentenceScores) return average def generate_summary(self, sents, sentenceScores, threshold) -> str: summary = ' '.join([ sent.text.strip() for sent in sents if ((sent.lower_[:15] in sentenceScores) and (sentenceScores[sent.lower_[:15]] <= (threshold))) ]) return summary def summarize(self, text, threshold: float) -> str: doc = self.nlp(text) sents = doc.sents ''' Term frequency (TF) is how often a word appears in the document, divided by how many words there are in the document. ''' # 1 Calculate the term frequency matrix, by sentence tf_matrix = self.sent_word_freq(text) #st.write(pd.DataFrame(tf_matrix)) # 2 Calculate the term frequency matrix, global (all sentences) tf_global_matrix = self.global_word_freq(tf_matrix) #st.write(pd.DataFrame({'tf_global_matrix':tf_global_matrix})) ''' Inverse document frequency (IDF) is how unique or rare a word is. ''' # 3 Calculate IDF idf_matrix = self.idf(tf_matrix, tf_global_matrix) #st.write(pd.DataFrame(idf_matrix)) # 4 Calculate TF-IDF tf_idf_matrix = self.tf_idf(tf_matrix, idf_matrix) #st.write(pd.DataFrame(tf_idf_matrix)) # 5 Score sentences sentence_scores = self.score_sentences(tf_idf_matrix) #st.write(pd.DataFrame({'sentence_scores':sentence_scores})) # 6 Generate summary summary = self.generate_summary(sents, sentence_scores, threshold) return summary
35.704403
136
0.611414
[ "Apache-2.0" ]
asehmi/Data-Science-Meetup-Oxford
TextSummarization/TF_IDF.py
5,677
Python
from ttv_api import * @dataclass class Channel: broadcaster_id: str broadcaster_login: str broadcaster_name: str game_name: str game_id: str broadcaster_language: str title: str delay: int def get_channels(*channel_ids: str) -> Optional[list[Channel]]: params = "?" for channel_id in channel_ids: params += f"broadcaster_id={channel_id}&" http = urllib3.PoolManager() r = http.request( "GET", URL.channels.value + params, headers=HEADER, ) if r.status != 200: return None data = json.loads(r.data.decode("utf-8"))["data"] channels: list[Channel] = [] for channel in data: channels.append( Channel( channel["broadcaster_id"], channel["broadcaster_login"], channel["broadcaster_name"], channel["game_name"], channel["game_id"], channel["broadcaster_language"], channel["title"], channel["delay"], ) ) return channels
23.446809
63
0.554446
[ "MIT" ]
Atheridis/aptbot
ttv_api/channel.py
1,102
Python
""" ======================================================== Statistic the SV Stat after AGE Process ======================================================== Author: Shujia Huang & Siyang Liu Date : 2014-03-07 0idx:54:15 """ import sys import re import os import string import numpy as np import matplotlib.pyplot as plt def DrawFig(figureFile, distance, properDepth, imProperDepth, nr, aa, bb, mscore, misprob, aveIden, inbCoe): fig = plt.figure(num=None, figsize=(16, 30), facecolor='w', edgecolor='k') title = ['Distance distribution', 'NRatio', 'Perfect Depth', 'Imperfect depth', '', '', ''] ylabel = ['The position of breakpoint', 'N Ratio of varints', \ 'Perfect Depth', 'Both ImPerfect Depth', 'InbreedCoefficient', \ 'Map score', 'Mismapping Probability' , 'Average Identity', \ 'ProperReadDepth', 'ImProperReadDepth'] al = 0.5 for i, data in enumerate ([distance, nr, aa, bb, inbCoe, mscore, misprob, aveIden, properDepth, imProperDepth ]): plt.subplot(10,2,2 * i + 1) #plt.title(title[i], fontsize=16) P = data[:,0] == 1; N = data[:,0] == 2; X = data[:,0] == 3 plt.scatter(data[:,1][N], data[:,2][N], marker='o', c = 'r', alpha=al, linewidths = 0.1, label = 'Negative(%d)'%len(data[:,1][N])) # Negative plt.scatter(data[:,1][P], data[:,2][P], marker='o', c = 'g', alpha=al, linewidths = 0.1, label = 'Positive(%d)'%len(data[:,1][P])) # Positive plt.scatter(data[:,1][X], data[:,2][X], marker='*', c = 'Y', alpha=al, linewidths = 0.1, label = 'Positive->Negative(%d)' % len(data[:,1][X])) # Positive->Negative plt.legend(loc='upper right') plt.xlim(-10, 50) if i == 9: plt.xlabel('Score', fontsize=16) plt.ylabel(ylabel[i], fontsize=16) plt.subplot(10, 2, 2*i + 2) NEW = data[:,0] == 0 good = data[:,1][NEW] >= VQ_CUTOFF bad = data[:,1][NEW] < VQ_CUTOFF plt.scatter(data[:,1][NEW][bad], data[:,2][NEW][bad], marker='o', c = 'm', alpha=al, linewidths = 0.1, label = 'bad(%d)' % len(data[:,1][NEW][bad])) # bad plt.scatter(data[:,1][NEW][good], data[:,2][NEW][good], marker='o', c = 'b', alpha=al, linewidths = 0.1, label = 'good(%d)' % len(data[:,1][NEW][good])) # good plt.xlim(-3, 30) plt.legend(loc='upper right') if i == 9: plt.xlabel('Score', fontsize=16) fig.savefig(figureFile + '.png') #fig.savefig(figureFile + '.pdf') def DrawPhredScale (figureFile, phredScal): fig = plt.figure() ylabel = ['Phred Scale'] for i, data in enumerate ([phredScal ]): plt.subplot(2, 1, 2 * i + 1) P = data[:,0] == 1; N = data[:,0] == 2; X = data[:,0] == 3 plt.scatter(data[:,1][N], data[:,2][N], marker='o', c = 'r', alpha=0.5, linewidths = 0, label = 'Negative(%d)'%len(data[:,1][N])) # Negative plt.scatter(data[:,1][P], data[:,2][P], marker='o', c = 'g', alpha=0.5, linewidths = 0, label = 'Positive(%d)'%len(data[:,1][P])) # Positive plt.scatter(data[:,1][X], data[:,2][X], marker='o', c = 'Y', alpha=0.5, linewidths = 0, label = 'Positive->Negative(%d)' % len(data[:,1][X])) # Positive->Negative plt.legend(loc='upper left') plt.ylabel(ylabel[i], fontsize=16) plt.subplot(2, 1, 2*i + 2) NEW = data[:,0] == 0 good = data[:,1][NEW] >= VQ_CUTOFF bad = data[:,1][NEW] < VQ_CUTOFF plt.scatter(data[:,1][NEW][bad] , data[:,2][NEW][bad] , marker='o', c = 'm', alpha=0.5, linewidths = 0, label = 'bad(%d)' % len(data[:,1][NEW][bad])) # bad plt.scatter(data[:,1][NEW][good], data[:,2][NEW][good], marker='o', c = 'b', alpha=0.5, linewidths = 0, label = 'good(%d)' % len(data[:,1][NEW][good])) # good plt.legend(loc='upper left') plt.xlabel('Score' , fontsize=16) plt.ylabel(ylabel[i], fontsize=16) fig.savefig(figureFile + '.png') #fig.savefig(figureFile + '.pdf') def Accum (data, isBig = False): tmpD= data k = sorted(tmpD.keys(), key = lambda d: float(d)) dat = [] for i in range(len(k)): if isBig: for j in range(i,len(k)): tmpD[k[i]][1] += tmpD[k[j]][0] else: for j in range(i+1): tmpD[k[i]][1] += tmpD[k[j]][0] dat.append([float(k[i]), float(tmpD[k[i]][0]), float(tmpD[k[i]][1]) ]) return dat def SampleFaLen (faLenFile): if faLenFile[-3:] == '.gz': I = os.popen('gzip -dc %s' % faLenFile) else : I = open(faLenFile) data = {} while 1: lines = I.readlines (100000) if not lines: break for line in lines: col = line.strip('\n').split() data[col[0]] = string.atoi(col[1]) I.close() return data def LoadFaLen (faLenLstFile): data = {} I = open (faLenLstFile) for line in I.readlines(): if len(line.strip('\n').split()) != 2: raise ValueError('[ERROR] The format of Fa length list maybe not right. It could just be: "sample FalenghtFile", but found',line) sampleId, fileName = line.strip('\n').split() if sampleId not in data: data[sampleId] = {} data[sampleId] = SampleFaLen(fileName) I.close() return data def main (argv): qFaLen = LoadFaLen(argv[1]) figPrefix = 'test' if len(argv) > 2: figPrefix = argv[2] if argv[0][-3:] == '.gz': I = os.popen('gzip -dc %s' % argv[0]) else: I = open (argv[0]) s, annotations, mark = set(), [], [] print '#Chr\tPosition\tDistance\tLeftIden\tRightIden\tAveIden\tN-Ratio\tAA' while 1: # VCF format lines = I.readlines(100000) if not lines: break for line in lines: col = line.strip('\n').split() if re.search(r'^#CHROM', line): col2sam = { i+9:sam for i,sam in enumerate(col[9:]) } if re.search(r'^#', line): continue key = col[0] + ':' + col[1] if key in s: continue s.add(key) #if re.search(r'^PASS', col[6]): continue #if not re.search(r'_TRAIN_SITE', col[7]): continue #if not re.search(r'^PASS', col[6]): continue isbad = False for i, sample in enumerate (col[9:]): if re.search(r'NULL', sample): isbad = True if isbad: continue fmat = { k:i for i,k in enumerate(col[8].split(':')) } if 'VS' not in fmat or 'QR' not in fmat: continue if 'AGE' not in fmat: continue if len(annotations) == 0: annotations = [[] for _ in col[9:] ] vcfinfo = { d.split('=')[0]: d.split('=')[1] for d in col[7].split(';') if len(d.split('=')) == 2 } vq = string.atof(vcfinfo['VQ']) inb = string.atof(vcfinfo['InbCoeff']) if ('POSITIVE_TRAIN_SITE' in col[7]) and ('NEGATIVE_TRAIN_SITE' in col[7]): mark.append([3, vq, inb]) elif 'POSITIVE_TRAIN_SITE' in col[7]: mark.append([1, vq, inb]) elif 'NEGATIVE_TRAIN_SITE' in col[7]: mark.append([2, vq, inb]) else: mark.append([0, vq, inb]) # GT:AA:AE:FN:MIP:MS:QR:RR:VS:VT for i, sample in enumerate (col[9:]): sampleId = col2sam[9+i] field = sample.split(':') if sample == './.' or len(field) < fmat['QR'] + 1 or field[fmat['QR']].split(',')[-1] == '.' or field[fmat['AS']] == '.': annotations[i].append([0, 0, 0, 0, 0, 0, 0, 0, 0]) continue qr = field[fmat['QR']].split(',')[-1] qregion = np.array(qr.split('-')) if len(qregion) > 3: qId = qregion[0] + '-' + qregion[1] else : qId = qregion[0] qSta = string.atoi(qregion[-2]) qEnd = string.atoi(qregion[-1]) if sampleId not in qFaLen: raise ValueError ('[ERROR] The sample name $s(in vcf) is not in the name of Fa list.' % sampleId) if qId not in qFaLen[sampleId]: raise ValueError ('[ERROR]', qId, 'is not been found in file', opt.qFalen, '\n') qSta= int(qSta * 100 / qFaLen[sampleId][qId] + 0.5) qEnd= int(qEnd * 100 / qFaLen[sampleId][qId] + 0.5) if qSta > 100 or qEnd > 100: raise ValueError ('[ERROR] Query size Overflow! sample: %s; scaffold: %s' % (sampleId, qId)) leg = qSta if 100 - qEnd < qSta: leg = qEnd nn = string.atof(sample.split(':')[fmat['NR']]) n = round(1000 * nn) / 10.0 # N ratio alt = string.atoi(sample.split(':')[fmat['AA']].split(',')[1]) # Alternate perfect bot = string.atoi(sample.split(':')[fmat['AA']].split(',')[3]) # Both imperfect pro, ipr = [0,0] ms = string.atoi(sample.split(':')[fmat['AS']]) # Mapping score mip = string.atof(sample.split(':')[fmat['MS']]) # Mismapping probability if sample.split(':')[fmat['AGE']] != '.': aveI = string.atoi(sample.split(':')[fmat['AGE']].split(',')[3]) # ave_iden in AGE else: aveI = 0 annotations[i].append([leg, n, alt, bot, pro, ipr, ms, mip, aveI]) I.close() print >> sys.stderr, '# Number of Positions: %d' % len(mark) if len(mark) != len(annotations[0]): raise ValueError ('[ERROR] The size is not match mark=%d, annotations=%d!' % (len(mark), len(annotations))) annotations = np.array(annotations); sampleNum = len(annotations) data, distance, properDepth, imProperDepth, nr, aa, bb, mscore, misprob, aveIden = [],[],[],[],[],[],[],[],[],[] inbreedCoe, phredScal = [], [] for i in range(len(annotations[0])): anno = np.array([annotations[s][i] for s in range(sampleNum) if len(annotations[s][i][annotations[s][i]!=0]) > 0 ]) # each person in the same position score = np.array([annotations[s][i][-3] for s in range(sampleNum) if annotations[s][i][-3] > 0 ]) msprob = np.array([annotations[s][i][-2] for s in range(sampleNum) if annotations[s][i][-3] > 0 ]) phred = -10 * np.log10(1.0 - score.sum() / np.sum(score/(1.0 - msprob))) # Phred scale if len(anno) == 0: continue leg, n, alt, bot, pro,ipr, ms, mip, aveI = np.median(anno, axis=0) distance.append ([mark[i][0], mark[i][1], leg ]) properDepth.append ([mark[i][0], mark[i][1], pro ]) imProperDepth.append ([mark[i][0], mark[i][1], ipr ]) nr.append ([mark[i][0], mark[i][1], n ]) aa.append ([mark[i][0], mark[i][1], alt ]) bb.append ([mark[i][0], mark[i][1], bot ]) mscore.append ([mark[i][0], mark[i][1], ms ]) misprob.append ([mark[i][0], mark[i][1], mip ]) aveIden.append ([mark[i][0], mark[i][1], aveI]) phredScal.append ([mark[i][0], mark[i][1], phred]) inbreedCoe.append ([mark[i][0], mark[i][1], mark[i][2]]) data.append([leg, alt, pro, ipr, n, bot]) print mark[i][0], mark[i][1], mark[i][2], '\t', leg, '\t', pro, '\t', ipr,'\t', n, '\t', alt, '\t', bot data = np.array(data) print >> sys.stderr, '\nPosition\tALTernatePerfect\tLeftIdentity\tRightIdentity\tAveIden\tNRatio\tBothImperfect' print >> sys.stderr, 'Means: ', data.mean(axis=0), '\nstd : ', data.std(axis=0), '\nMedian: ', np.median(data, axis=0) print >> sys.stderr, '25 Percentile:', np.percentile(data, 25,axis=0), '\n50 Percentile:', np.percentile(data, 50,axis=0), '\n75 Percentile:', np.percentile(data, 75,axis=0) DrawFig(figPrefix, \ np.array (distance ), \ np.array (properDepth ), \ np.array (imProperDepth), \ np.array (nr ), \ np.array (aa ), \ np.array (bb ), \ np.array (mscore ), \ np.array (misprob ), \ np.array (aveIden ), \ np.array (inbreedCoe ) ) DrawPhredScale (figPrefix + '.phred', np.array(phredScal)) if __name__ == '__main__': VQ_CUTOFF = 3.0 main(sys.argv[1:])
46.207407
177
0.511783
[ "MIT" ]
ShujiaHuang/AsmVar
src/AsmvarVarScore/FeatureToScore2.py
12,476
Python
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class WorkSubmissionKey(object): """ Work Submission Identifier """ def __init__(self, **kwargs): """ Initializes a new WorkSubmissionKey object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param work_submission_key: The value to assign to the work_submission_key property of this WorkSubmissionKey. :type work_submission_key: str """ self.swagger_types = { 'work_submission_key': 'str' } self.attribute_map = { 'work_submission_key': 'workSubmissionKey' } self._work_submission_key = None @property def work_submission_key(self): """ **[Required]** Gets the work_submission_key of this WorkSubmissionKey. Work Submission Identifier :return: The work_submission_key of this WorkSubmissionKey. :rtype: str """ return self._work_submission_key @work_submission_key.setter def work_submission_key(self, work_submission_key): """ Sets the work_submission_key of this WorkSubmissionKey. Work Submission Identifier :param work_submission_key: The work_submission_key of this WorkSubmissionKey. :type: str """ self._work_submission_key = work_submission_key def __repr__(self): return formatted_flat_dict(self) def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
31.253521
245
0.68274
[ "Apache-2.0", "BSD-3-Clause" ]
LaudateCorpus1/oci-python-sdk
src/oci/management_agent/models/work_submission_key.py
2,219
Python
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import iso8601 from lxml import etree import webob from nova.api.openstack import compute from nova.api.openstack.compute import extensions as compute_extensions from nova.api.openstack import extensions as base_extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import flags from nova.openstack.common import jsonutils from nova import test from nova.tests.api.openstack import fakes FLAGS = flags.FLAGS NS = "{http://docs.openstack.org/common/api/v1.0}" ATOMNS = "{http://www.w3.org/2005/Atom}" response_body = "Try to say this Mr. Knox, sir..." extension_body = "I am not a fox!" class StubController(object): def __init__(self, body): self.body = body def index(self, req): return self.body def create(self, req): msg = 'All aboard the fail train!' raise webob.exc.HTTPBadRequest(explanation=msg) def show(self, req, id): raise webob.exc.HTTPNotFound() class StubActionController(wsgi.Controller): def __init__(self, body): self.body = body @wsgi.action('fooAction') def _action_foo(self, req, id, body): return self.body class StubControllerExtension(base_extensions.ExtensionDescriptor): name = 'twaadle' def __init__(self): pass class StubEarlyExtensionController(wsgi.Controller): def __init__(self, body): self.body = body @wsgi.extends def index(self, req): yield self.body @wsgi.extends(action='fooAction') def _action_foo(self, req, id, body): yield self.body class StubLateExtensionController(wsgi.Controller): def __init__(self, body): self.body = body @wsgi.extends def index(self, req, resp_obj): return self.body @wsgi.extends(action='fooAction') def _action_foo(self, req, resp_obj, id, body): return self.body class StubExtensionManager(object): """Provides access to Tweedle Beetles""" name = "Tweedle Beetle Extension" alias = "TWDLBETL" def __init__(self, resource_ext=None, action_ext=None, request_ext=None, controller_ext=None): self.resource_ext = resource_ext self.action_ext = action_ext self.request_ext = request_ext self.controller_ext = controller_ext self.extra_resource_ext = None def get_resources(self): resource_exts = [] if self.resource_ext: resource_exts.append(self.resource_ext) if self.extra_resource_ext: resource_exts.append(self.extra_resource_ext) return resource_exts def get_actions(self): action_exts = [] if self.action_ext: action_exts.append(self.action_ext) return action_exts def get_request_extensions(self): request_extensions = [] if self.request_ext: request_extensions.append(self.request_ext) return request_extensions def get_controller_extensions(self): controller_extensions = [] if self.controller_ext: controller_extensions.append(self.controller_ext) return controller_extensions class ExtensionTestCase(test.TestCase): def setUp(self): super(ExtensionTestCase, self).setUp() ext_list = FLAGS.osapi_compute_extension[:] fox = ('nova.tests.api.openstack.compute.extensions.' 'foxinsocks.Foxinsocks') if fox not in ext_list: ext_list.append(fox) self.flags(osapi_compute_extension=ext_list) class ExtensionControllerTest(ExtensionTestCase): def setUp(self): super(ExtensionControllerTest, self).setUp() self.ext_list = [ "AdminActions", "Aggregates", "AvailabilityZone", "Certificates", "Cloudpipe", "ConsoleOutput", "Consoles", "Createserverext", "DeferredDelete", "DiskConfig", "ExtendedStatus", "ExtendedServerAttributes", "FlavorAccess", "FlavorDisabled", "FlavorExtraSpecs", "FlavorExtraData", "FlavorManage", "FlavorRxtx", "FlavorSwap", "FloatingIps", "FloatingIpDns", "FloatingIpPools", "Fox In Socks", "Hosts", "Keypairs", "Multinic", "MultipleCreate", "Networks", "QuotaClasses", "Quotas", "Rescue", "SchedulerHints", "SecurityGroups", "ServerDiagnostics", "ServerStartStop", "SimpleTenantUsage", "UsedLimits", "UserData", "VirtualInterfaces", "Volumes", "VolumeTypes", ] self.ext_list.sort() def test_list_extensions_json(self): app = compute.APIRouter() request = webob.Request.blank("/fake/extensions") response = request.get_response(app) self.assertEqual(200, response.status_int) # Make sure we have all the extensions, extra extensions being OK. data = jsonutils.loads(response.body) names = [str(x['name']) for x in data['extensions'] if str(x['name']) in self.ext_list] names.sort() self.assertEqual(names, self.ext_list) # Ensure all the timestamps are valid according to iso8601 for ext in data['extensions']: iso8601.parse_date(ext['updated']) # Make sure that at least Fox in Sox is correct. (fox_ext, ) = [ x for x in data['extensions'] if x['alias'] == 'FOXNSOX'] self.assertEqual(fox_ext, { 'namespace': 'http://www.fox.in.socks/api/ext/pie/v1.0', 'name': 'Fox In Socks', 'updated': '2011-01-22T13:25:27-06:00', 'description': 'The Fox In Socks Extension', 'alias': 'FOXNSOX', 'links': [] }, ) for ext in data['extensions']: url = '/fake/extensions/%s' % ext['alias'] request = webob.Request.blank(url) response = request.get_response(app) output = jsonutils.loads(response.body) self.assertEqual(output['extension']['alias'], ext['alias']) def test_get_extension_json(self): app = compute.APIRouter() request = webob.Request.blank("/fake/extensions/FOXNSOX") response = request.get_response(app) self.assertEqual(200, response.status_int) data = jsonutils.loads(response.body) self.assertEqual(data['extension'], { "namespace": "http://www.fox.in.socks/api/ext/pie/v1.0", "name": "Fox In Socks", "updated": "2011-01-22T13:25:27-06:00", "description": "The Fox In Socks Extension", "alias": "FOXNSOX", "links": []}) def test_get_non_existing_extension_json(self): app = compute.APIRouter() request = webob.Request.blank("/fake/extensions/4") response = request.get_response(app) self.assertEqual(404, response.status_int) def test_list_extensions_xml(self): app = compute.APIRouter() request = webob.Request.blank("/fake/extensions") request.accept = "application/xml" response = request.get_response(app) self.assertEqual(200, response.status_int) root = etree.XML(response.body) self.assertEqual(root.tag.split('extensions')[0], NS) # Make sure we have all the extensions, extras extensions being OK. exts = root.findall('{0}extension'.format(NS)) self.assert_(len(exts) >= len(self.ext_list)) # Make sure that at least Fox in Sox is correct. (fox_ext, ) = [x for x in exts if x.get('alias') == 'FOXNSOX'] self.assertEqual(fox_ext.get('name'), 'Fox In Socks') self.assertEqual(fox_ext.get('namespace'), 'http://www.fox.in.socks/api/ext/pie/v1.0') self.assertEqual(fox_ext.get('updated'), '2011-01-22T13:25:27-06:00') self.assertEqual(fox_ext.findtext('{0}description'.format(NS)), 'The Fox In Socks Extension') xmlutil.validate_schema(root, 'extensions') def test_get_extension_xml(self): app = compute.APIRouter() request = webob.Request.blank("/fake/extensions/FOXNSOX") request.accept = "application/xml" response = request.get_response(app) self.assertEqual(200, response.status_int) xml = response.body root = etree.XML(xml) self.assertEqual(root.tag.split('extension')[0], NS) self.assertEqual(root.get('alias'), 'FOXNSOX') self.assertEqual(root.get('name'), 'Fox In Socks') self.assertEqual(root.get('namespace'), 'http://www.fox.in.socks/api/ext/pie/v1.0') self.assertEqual(root.get('updated'), '2011-01-22T13:25:27-06:00') self.assertEqual(root.findtext('{0}description'.format(NS)), 'The Fox In Socks Extension') xmlutil.validate_schema(root, 'extension') class ResourceExtensionTest(ExtensionTestCase): def test_no_extension_present(self): manager = StubExtensionManager(None) app = compute.APIRouter(manager) request = webob.Request.blank("/blah") response = request.get_response(app) self.assertEqual(404, response.status_int) def test_get_resources(self): res_ext = base_extensions.ResourceExtension('tweedles', StubController(response_body)) manager = StubExtensionManager(res_ext) app = compute.APIRouter(manager) request = webob.Request.blank("/fake/tweedles") response = request.get_response(app) self.assertEqual(200, response.status_int) self.assertEqual(response_body, response.body) def test_get_resources_with_controller(self): res_ext = base_extensions.ResourceExtension('tweedles', StubController(response_body)) manager = StubExtensionManager(res_ext) app = compute.APIRouter(manager) request = webob.Request.blank("/fake/tweedles") response = request.get_response(app) self.assertEqual(200, response.status_int) self.assertEqual(response_body, response.body) def test_bad_request(self): res_ext = base_extensions.ResourceExtension('tweedles', StubController(response_body)) manager = StubExtensionManager(res_ext) app = compute.APIRouter(manager) request = webob.Request.blank("/fake/tweedles") request.method = "POST" response = request.get_response(app) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) body = jsonutils.loads(response.body) expected = { "badRequest": { "message": "All aboard the fail train!", "code": 400 } } self.assertDictMatch(expected, body) def test_non_exist_resource(self): res_ext = base_extensions.ResourceExtension('tweedles', StubController(response_body)) manager = StubExtensionManager(res_ext) app = compute.APIRouter(manager) request = webob.Request.blank("/fake/tweedles/1") response = request.get_response(app) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) body = jsonutils.loads(response.body) expected = { "itemNotFound": { "message": "The resource could not be found.", "code": 404 } } self.assertDictMatch(expected, body) class InvalidExtension(object): alias = "THIRD" class ExtensionManagerTest(ExtensionTestCase): response_body = "Try to say this Mr. Knox, sir..." def test_get_resources(self): app = compute.APIRouter() request = webob.Request.blank("/fake/foxnsocks") response = request.get_response(app) self.assertEqual(200, response.status_int) self.assertEqual(response_body, response.body) def test_invalid_extensions(self): # Don't need the serialization middleware here because we're # not testing any serialization app = compute.APIRouter() ext_mgr = compute_extensions.ExtensionManager() ext_mgr.register(InvalidExtension()) self.assertTrue(ext_mgr.is_loaded('FOXNSOX')) self.assertFalse(ext_mgr.is_loaded('THIRD')) class ActionExtensionTest(ExtensionTestCase): def _send_server_action_request(self, url, body): app = compute.APIRouter() request = webob.Request.blank(url) request.method = 'POST' request.content_type = 'application/json' request.body = jsonutils.dumps(body) response = request.get_response(app) return response def test_extended_action(self): body = dict(add_tweedle=dict(name="test")) url = "/fake/servers/abcd/action" response = self._send_server_action_request(url, body) self.assertEqual(200, response.status_int) self.assertEqual("Tweedle Beetle Added.", response.body) body = dict(delete_tweedle=dict(name="test")) response = self._send_server_action_request(url, body) self.assertEqual(200, response.status_int) self.assertEqual("Tweedle Beetle Deleted.", response.body) def test_invalid_action(self): body = dict(blah=dict(name="test")) # Doesn't exist url = "/fake/servers/abcd/action" response = self._send_server_action_request(url, body) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) body = jsonutils.loads(response.body) expected = { "badRequest": { "message": "There is no such action: blah", "code": 400 } } self.assertDictMatch(expected, body) def test_non_exist_action(self): body = dict(blah=dict(name="test")) url = "/fake/fdsa/1/action" response = self._send_server_action_request(url, body) self.assertEqual(404, response.status_int) def test_failed_action(self): body = dict(fail=dict(name="test")) url = "/fake/servers/abcd/action" response = self._send_server_action_request(url, body) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) body = jsonutils.loads(response.body) expected = { "badRequest": { "message": "Tweedle fail", "code": 400 } } self.assertDictMatch(expected, body) class RequestExtensionTest(ExtensionTestCase): def test_get_resources_with_stub_mgr(self): class GooGoose(wsgi.Controller): @wsgi.extends def show(self, req, resp_obj, id): # only handle JSON responses resp_obj.obj['flavor']['googoose'] = req.GET.get('chewing') req_ext = base_extensions.ControllerExtension( StubControllerExtension(), 'flavors', GooGoose()) manager = StubExtensionManager(None, None, None, req_ext) app = fakes.wsgi_app(ext_mgr=manager) request = webob.Request.blank("/v2/fake/flavors/1?chewing=bluegoo") request.environ['api.version'] = '2' response = request.get_response(app) self.assertEqual(200, response.status_int) response_data = jsonutils.loads(response.body) self.assertEqual('bluegoo', response_data['flavor']['googoose']) def test_get_resources_with_mgr(self): app = fakes.wsgi_app() request = webob.Request.blank("/v2/fake/flavors/1?chewing=newblue") request.environ['api.version'] = '2' response = request.get_response(app) self.assertEqual(200, response.status_int) response_data = jsonutils.loads(response.body) self.assertEqual('newblue', response_data['flavor']['googoose']) self.assertEqual("Pig Bands!", response_data['big_bands']) class ControllerExtensionTest(ExtensionTestCase): def test_controller_extension_early(self): controller = StubController(response_body) res_ext = base_extensions.ResourceExtension('tweedles', controller) ext_controller = StubEarlyExtensionController(extension_body) extension = StubControllerExtension() cont_ext = base_extensions.ControllerExtension(extension, 'tweedles', ext_controller) manager = StubExtensionManager(resource_ext=res_ext, controller_ext=cont_ext) app = compute.APIRouter(manager) request = webob.Request.blank("/fake/tweedles") response = request.get_response(app) self.assertEqual(200, response.status_int) self.assertEqual(extension_body, response.body) def test_controller_extension_late(self): # Need a dict for the body to convert to a ResponseObject controller = StubController(dict(foo=response_body)) res_ext = base_extensions.ResourceExtension('tweedles', controller) ext_controller = StubLateExtensionController(extension_body) extension = StubControllerExtension() cont_ext = base_extensions.ControllerExtension(extension, 'tweedles', ext_controller) manager = StubExtensionManager(resource_ext=res_ext, controller_ext=cont_ext) app = compute.APIRouter(manager) request = webob.Request.blank("/fake/tweedles") response = request.get_response(app) self.assertEqual(200, response.status_int) self.assertEqual(extension_body, response.body) def test_controller_extension_late_inherited_resource(self): # Need a dict for the body to convert to a ResponseObject controller = StubController(dict(foo=response_body)) parent_ext = base_extensions.ResourceExtension('tweedles', controller) ext_controller = StubLateExtensionController(extension_body) extension = StubControllerExtension() cont_ext = base_extensions.ControllerExtension(extension, 'tweedles', ext_controller) manager = StubExtensionManager(resource_ext=parent_ext, controller_ext=cont_ext) child_ext = base_extensions.ResourceExtension('beetles', controller, inherits='tweedles') manager.extra_resource_ext = child_ext app = compute.APIRouter(manager) request = webob.Request.blank("/fake/beetles") response = request.get_response(app) self.assertEqual(200, response.status_int) self.assertEqual(extension_body, response.body) def test_controller_action_extension_early(self): controller = StubActionController(response_body) actions = dict(action='POST') res_ext = base_extensions.ResourceExtension('tweedles', controller, member_actions=actions) ext_controller = StubEarlyExtensionController(extension_body) extension = StubControllerExtension() cont_ext = base_extensions.ControllerExtension(extension, 'tweedles', ext_controller) manager = StubExtensionManager(resource_ext=res_ext, controller_ext=cont_ext) app = compute.APIRouter(manager) request = webob.Request.blank("/fake/tweedles/foo/action") request.method = 'POST' request.headers['Content-Type'] = 'application/json' request.body = jsonutils.dumps(dict(fooAction=True)) response = request.get_response(app) self.assertEqual(200, response.status_int) self.assertEqual(extension_body, response.body) def test_controller_action_extension_late(self): # Need a dict for the body to convert to a ResponseObject controller = StubActionController(dict(foo=response_body)) actions = dict(action='POST') res_ext = base_extensions.ResourceExtension('tweedles', controller, member_actions=actions) ext_controller = StubLateExtensionController(extension_body) extension = StubControllerExtension() cont_ext = base_extensions.ControllerExtension(extension, 'tweedles', ext_controller) manager = StubExtensionManager(resource_ext=res_ext, controller_ext=cont_ext) app = compute.APIRouter(manager) request = webob.Request.blank("/fake/tweedles/foo/action") request.method = 'POST' request.headers['Content-Type'] = 'application/json' request.body = jsonutils.dumps(dict(fooAction=True)) response = request.get_response(app) self.assertEqual(200, response.status_int) self.assertEqual(extension_body, response.body) class ExtensionsXMLSerializerTest(test.TestCase): def test_serialize_extension(self): serializer = base_extensions.ExtensionTemplate() data = {'extension': { 'name': 'ext1', 'namespace': 'http://docs.rack.com/servers/api/ext/pie/v1.0', 'alias': 'RS-PIE', 'updated': '2011-01-22T13:25:27-06:00', 'description': 'Adds the capability to share an image.', 'links': [{'rel': 'describedby', 'type': 'application/pdf', 'href': 'http://docs.rack.com/servers/api/ext/cs.pdf'}, {'rel': 'describedby', 'type': 'application/vnd.sun.wadl+xml', 'href': 'http://docs.rack.com/servers/api/ext/cs.wadl'}]}} xml = serializer.serialize(data) root = etree.XML(xml) ext_dict = data['extension'] self.assertEqual(root.findtext('{0}description'.format(NS)), ext_dict['description']) for key in ['name', 'namespace', 'alias', 'updated']: self.assertEqual(root.get(key), ext_dict[key]) link_nodes = root.findall('{0}link'.format(ATOMNS)) self.assertEqual(len(link_nodes), 2) for i, link in enumerate(ext_dict['links']): for key, value in link.items(): self.assertEqual(link_nodes[i].get(key), value) xmlutil.validate_schema(root, 'extension') def test_serialize_extensions(self): serializer = base_extensions.ExtensionsTemplate() data = {"extensions": [{ "name": "Public Image Extension", "namespace": "http://foo.com/api/ext/pie/v1.0", "alias": "RS-PIE", "updated": "2011-01-22T13:25:27-06:00", "description": "Adds the capability to share an image.", "links": [{"rel": "describedby", "type": "application/pdf", "type": "application/vnd.sun.wadl+xml", "href": "http://foo.com/api/ext/cs-pie.pdf"}, {"rel": "describedby", "type": "application/vnd.sun.wadl+xml", "href": "http://foo.com/api/ext/cs-pie.wadl"}]}, {"name": "Cloud Block Storage", "namespace": "http://foo.com/api/ext/cbs/v1.0", "alias": "RS-CBS", "updated": "2011-01-12T11:22:33-06:00", "description": "Allows mounting cloud block storage.", "links": [{"rel": "describedby", "type": "application/pdf", "href": "http://foo.com/api/ext/cs-cbs.pdf"}, {"rel": "describedby", "type": "application/vnd.sun.wadl+xml", "href": "http://foo.com/api/ext/cs-cbs.wadl"}]}]} xml = serializer.serialize(data) root = etree.XML(xml) ext_elems = root.findall('{0}extension'.format(NS)) self.assertEqual(len(ext_elems), 2) for i, ext_elem in enumerate(ext_elems): ext_dict = data['extensions'][i] self.assertEqual(ext_elem.findtext('{0}description'.format(NS)), ext_dict['description']) for key in ['name', 'namespace', 'alias', 'updated']: self.assertEqual(ext_elem.get(key), ext_dict[key]) link_nodes = ext_elem.findall('{0}link'.format(ATOMNS)) self.assertEqual(len(link_nodes), 2) for i, link in enumerate(ext_dict['links']): for key, value in link.items(): self.assertEqual(link_nodes[i].get(key), value) xmlutil.validate_schema(root, 'extensions')
39.098507
79
0.612193
[ "Apache-2.0" ]
NewpTone/stacklab-nova
debian/python-nova/usr/lib/python2.7/dist-packages/nova/tests/api/openstack/compute/test_extensions.py
90
Python
VERSION = __version__ = '0.1.1'
16
31
0.65625
[ "BSD-3-Clause" ]
adailson2/linguist
linguist/__init__.py
32
Python
#!/usr/bin/env python # # Author: Qiming Sun <[email protected]> # from pyscf import gto from pyscf import scf from pyscf import mcscf from pyscf.dmrgscf import dmrgci ''' Block code for active space N-particle density matrices. ''' b = 1.2 mol = gto.M( verbose = 4, atom = 'N 0 0 0; N 0 0 %f'%b, basis = 'cc-pvdz', symmetry = True, ) m = scf.RHF(mol) m.kernel() mc = mcscf.CASSCF(m, 8, 8) mc.fcisolver = dmrgci.DMRGCI(mol) mc.kernel() dm1 = mc.fcisolver.make_rdm1(0, mc.ncas, mc.nelecas) dm2 = mc.fcisolver.make_rdm12(0, mc.ncas, mc.nelecas)[1] dm3 = mc.fcisolver.make_rdm123(0, mc.ncas, mc.nelecas)[2] # # or computing DMs all together in one DMRG call # dm1, dm2 = mc.fcisolver.make_rdm12(0, mc.ncas, mc.nelecas) dm1, dm2, dm3 = mc.fcisolver.make_rdm123(0, mc.ncas, mc.nelecas)
20.2
64
0.679455
[ "BSD-2-Clause" ]
gmwang18/pyscf
examples/dmrg/03-density_matrix.py
808
Python
import os import re import shutil import sys import urllib.error import urllib.parse import urllib.request from zipfile import ZipFile import helpers.config as config from helpers.logger import Logger class Updater: __instance = None @staticmethod def Get(): if Updater.__instance is None: return Updater() return Updater.__instance def __init__(self): if Updater.__instance is not None: return else: self.log = Logger("pyLaunch.Frontend.Updater", "frontend.log") self.DeleteFolders = ["src"] self.UpdateFolder = "updatefiles" def Automatic(self) -> bool: if not self.CheckConnection(): return False UpdateAvailable = self.CheckVersions() if UpdateAvailable: print(f"An update is available! [v{'.'.join(self.Versions[1])}]") if not 'n' in input(f"Would you like to update from [{'.'.join(self.Versions[0])}]? (Y/n) > "): if self.DownloadUpdate(): return self.InstallUpdate() return False def CheckConnection(self) -> str: if config.CONFIGURATION['Update']['SkipCheck']: return "Skipping update check" try: urllib.request.urlopen('http://google.com') return True except Exception as e: return "Unable to connect to the internet" # Unable to connect to the internet def DownloadUpdate(self) -> bool: response = None try: response = urllib.request.urlopen(f"https://api.github.com/repos/{config.CONFIGURATION['Update']['Organization']}/{config.CONFIGURATION['Update']['Repository']}/zipball/{config.CONFIGURATION['Update']['Branch']}") except urllib.error.HTTPError as e: print(f"Unable to download update from GitHub: {e}") input("Press enter to continue...") return False if not os.path.exists(f"{config.PATH_ROOT}{os.sep}{self.UpdateFolder}"): os.mkdir(f"{config.PATH_ROOT}{os.sep}{self.UpdateFolder}") with open(f"{config.PATH_ROOT}{os.sep}{self.UpdateFolder}{os.sep}gh_download.zip", "wb") as f: f.write(response.read()) # Zip is downloaded, now extract os.chdir(f"{config.PATH_ROOT}{os.sep}{self.UpdateFolder}") zipFileContent = dict() zipFileContentSize = 0 with ZipFile(f"gh_download.zip", 'r') as zipFile: for name in zipFile.namelist(): zipFileContent[name] = zipFile.getinfo(name).file_size zipFileContentSize = sum(zipFileContent.values()) extractedContentSize = 0 for zippedFileName, zippedFileSize in zipFileContent.items(): UnzippedFilePath = os.path.abspath(f"{zippedFileName}") os.makedirs(os.path.dirname(UnzippedFilePath), exist_ok=True) if os.path.isfile(UnzippedFilePath): zipFileContentSize -= zippedFileSize else: zipFile.extract(zippedFileName, path="", pwd=None) extractedContentSize += zippedFileSize try: done = int(50*extractedContentSize/zipFileContentSize) percentage = (extractedContentSize / zipFileContentSize) * 100 except ZeroDivisionError: done = 50 percentage = 100 sys.stdout.write('\r[{}{}] {:.2f}%'.format('█' * done, '.' * (50-done), percentage)) sys.stdout.flush() sys.stdout.write('\n') os.chdir(config.PATH_ROOT) return True def InstallUpdate(self) -> bool: print("Installing new version") for file in os.listdir(config.CONFIGURATION['Launch']['ProjectRoot']): if os.path.isdir(f"{config.CONFIGURATION['Launch']['ProjectRoot']}{os.sep}{file}"): if file in self.DeleteFolders: shutil.rmtree(f"{config.CONFIGURATION['Launch']['ProjectRoot']}{os.sep}{file}") else: # Files os.remove(f"{config.CONFIGURATION['Launch']['ProjectRoot']}{os.sep}{file}") # Old version is deleted for file in os.listdir(f"{config.PATH_ROOT}{os.sep}{self.UpdateFolder}"): os.rename(f"{config.PATH_ROOT}{os.sep}{self.UpdateFolder}{os.sep}{file}", f"{config.CONFIGURATION['Launch']['ProjectRoot']}{os.sep}{file}") shutil.rmtree(f"{config.PATH_ROOT}{os.sep}{self.UpdateFolder}") return True def CheckVersions(self): # Sucessful return: bool # Unsuccessful: list[message: str, continue: bool] self.Versions = self._GetVersions() if type(self.Versions[1]) == bool: return self.Versions self.Versions[0] = self._GetVersionAsInt(self.Versions[0]) self.Versions[1] = self._GetVersionAsInt(self.Versions[1]) self.Difference = [] for installed, checked in zip(self.Versions[0], self.Versions[1]): self.Difference.append(checked - installed) for section in self.Difference: if section < 0: # When working on project and updating locally return False elif section > 0: return True return False def _GetVersions(self) -> list: # Sucessful return: list[InstalledVersion: str, CheckedVersion: str] # Unsucessful: list[message: str, continue: bool] if not os.path.exists(f"{config.CONFIGURATION['Launch']['ProjectRoot']}{os.sep}{config.CONFIGURATION['Update']['VersionPath']}"): # This means either the configuration is incorrect, or pyLaunch isn't where it should be # continue is False, because the project cannot be launched return [f"Unable to locate installed version at {config.CONFIGURATION['Update']['VersionPath']}", False] InstalledVersion = None # Local Version CheckedVersion = None # Version on GitHub with open(f"{config.CONFIGURATION['Launch']['ProjectRoot']}{os.sep}{config.CONFIGURATION['Update']['VersionPath']}", "r") as f: lines = f.readlines() InstalledVersion = self._GetVersionFromStr(lines) try: response = urllib.request.urlopen(f"https://raw.githubusercontent.com/{config.CONFIGURATION['Update']['Organization']}/{config.CONFIGURATION['Update']['Repository']}/{config.CONFIGURATION['Update']['Branch']}{config.CONFIGURATION['Update']['VersionPath']}") content = response.read().decode("UTF-8").split("\n") CheckedVersion = self._GetVersionFromStr(content) except urllib.error.HTTPError as e: # The Project URL is invalid (cannot find Org/Repo/Branch/VersionPath) or, # raw.githubusercontent is down, continue is True, the project can still be launched return ["Project URL does not exist or githubusercontent is down", True] # URL doesn't exist or something went wrong if CheckedVersion is None: # Some other error, just to be safe. return ["Unable to get current version from GitHub", True] return [InstalledVersion, CheckedVersion] def _GetVersionFromStr(self, lines: str) -> str: ver = None for line in lines: line = line.strip() if config.CONFIGURATION['Update']['Find'] in line: ver = line[len(config.CONFIGURATION['Update']['Find']):].strip('"') match = re.match(r"\d+\.\d+\.\d+", ver) # > #.#.# if match: return ver[match.start():match.end()] return None def _GetVersionAsInt(self, version: str) -> list: version = version.split(".") intVer = [] for section in version: if section.isalnum(): newSection = "" for char in section: if char.isnumeric(): newSection += char section = newSection intVer.append(int(section)) return intVer
44.213115
269
0.602645
[ "MIT" ]
daavofficial/Launcher
frontend/update.py
8,093
Python
from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ from my_site.users.forms import UserAdminChangeForm, UserAdminCreationForm User = get_user_model() @admin.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserAdminChangeForm add_form = UserAdminCreationForm fieldsets = ( (None, {"fields": ("username", "password")}), (_("Personal info"), {"fields": ("name", "email")}), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) list_display = ["username", "name", "is_superuser"] search_fields = ["name"]
29.057143
74
0.564405
[ "MIT" ]
pshortt/my_site
my_site/users/admin.py
1,017
Python
# -*- coding:utf-8 -*- # # Author : TangHanYi # E-mail : [email protected] # Create Date : 2016-12-11 09:33:17 AM # Last modified : 2016-12-11 10:48:50 AM # File Name : Super_Pow.py # Desc : class Solution(object): def superPow(self, a, b): if len(b) == 0: return a tmp = a ret = 1 n = len(b) k = 0 while k != n - 1: if b[-1] % 2 == 1: ret = (ret * tmp) % 1337 tmp = (tmp * tmp) % 1337 pre = 0 for i in range(k, n): pre_b = (pre * 10 + b[i]) % 2 b[i] = (pre * 10 + b[i]) / 2 pre = pre_b if k == i and b[i] == 0: k += 1 return ret if __name__ == "__main__": s = Solution() a = 434576 b = [6,4,0,4,4,0,3,9,4,9,9,6,2,0,2,5,4,2,1,7,9,2,5,9,5,2,5,6,2,9,2,4,4,4,8,0,7,4,9,1,3,9,9,7,1,1,2,7,5,5,4,5,7,1,4,4,4,9,1,8,0,5,4,6,2,3,7,9,9,6,0,2,7,1,0,0,3,4,7,8,2,4,3,9,5,9,6,1,8,9,0,9,6,4,5,8,9,4,7,8,1,9,1,0,3,3,1,6,9,8,6,1,4,0,3,0,1,9,1,0,0,1,1,6,8,8,5,7,3,4,6,6,6,9,6,9,2,9,7,3,0,3,7,4,5,0,4,7,1,8,7,1,1,0,9,9,0,4,9,5,1,5,3,7,4,0,8,8,1,5,1,1,8,8,6,4,0,2,1,3,0,0,4,4,2,6,5,2,0,4,0,1,9,3,0,5,5,8,5,7,5,7,0,4,7,6,0,8,1,1,1,3,3,8,7,5,4,3,9,6,7,9,0,9,5,0,6,0,1,2,9,6,1,0,2,8,8,2,6,9,5,0,3,8,8,0,3,4,5,5,0,5,6,0,6,1,3,2,4,4,6,3,2,7,5,5,8,4,9,6,3,5,6,8,3,6,9,9,0,6,4,1,1,2,3,7,4,6,2,0,0,0,5,5,0,1,0,8,7,9,4,2,6,3,1,0,9,2,1,2,8,7,5,0,9,8,9,5,5,1,5,7,4,3,2,4,6,4,2,3,6,8,5,4,1,8,4,1,0,7,3,9,4,8,1,4,8,0,1,5,4,9,3,8,2,7,2,8,4,6,1,2,4,8,6,8,9,3,1,9,0,6,8,5,6,1,1,4,2,2,0,8,1,5,6,5,2,0,3,8,8,6,2,4,7,9,2,6,4,3,5,4,1,6,1,7,7,2,2,1,7,4,9,0,9,7,6,3,9,1,2,7,8,4,2,7,5,6,3,9,2,0,6,3,8,7,1,8,2,5,9,9,9,1,9,8,8,7,1,8,9,5,7,9,2,9,6,7,8,1,9,0,3,5,3,4,4,4,2,6,9,3,5,8,4,7,8,5,4,2,5,5,7,2,6,9,4,4,9,2,5,0,2,1,7,5,5,1,2,9,8,3,2,5,4,9,4,2,4,9,4,9,6,4,3,3,5,7,7,6,9,5,8,3,8,5,1,3,9,3,2,7,8,6,4,2,5,9,7,9,0,3,0,6,9,4,1,5,3,1,1,3,6,0,6,4,7,9,9,6,2,3,5,3,9,0,7,7,1,4,6,1,0,9,9,9,5,1,6,8,2,8,1,0,0,0,6,9,9,5,6,4,0,1,9,9,3,6,8,4,3,7,5,3,6,7,4,1,0,1,9,4,1,3,4,1,5,0,2,6,7,8,0,9,2,1,0,7,8,9,2,1,6,9,6,2,6,0,5,8,1,6,2,2,9,6,5,6,8,8,3,7,8,5,6,0,7,7,8,5,6,2,8,2,1,4,6,0,4,1,8,6,7,1,8,9,9,4,5,0,4,8,9,2,6,6,5,3,5,5,8,3,7,6,7,0,0,3,2,4,6,3,2,5,6,1,4,5,7,2,7,1,2,7,3,8,3,8,1,0,5,1,3,2,9,0,5,1,3,7,8,1,0,0,6,6,3,3,4,0,7,1,3,9,0,7,8,5,7,1,5,3,3,8,7,4,0,2,6,5,2,4,6,2,4,5,1,8,8,7,0,5,0,4,6,1,3,4,6,0,8,2,5,3,2,5,7,3,7,5,8,1,9,7,6,6,2,7,6,0,6,6,7,6,2,3,7,5,0,6,8,8,0,5,3,2,0,0,7,0,8,8,1,7,5,7,5,7,6,1,7,4,0,4,1,2,9,0,8,9,6,6,9,6,1,2,1,4,5,8,4,3,6,7,2,3,5,8,0,3,9,7,8,9,3,1,2,5,1,2,4,0,8,6,8,1,8,9,5,5,0,1,0,8,9,3,2,6,1,4,9,2,2,9,4,7,0,8,2,4,0,9,6,0,7,4,3,5,6,1,3,8,2,3,8,1,6,2,7,9,7,9,4,1,0,0,0,1,8,3,7,0,4,3,2,1,9,5,8,7,6,1,5,1,7,6,2,5,8,2,7,5,1,1,8,3,1,9,4,1,4,3,1,0,8,5,1,0,0,1,7,9,5,5,0,2,1,2,9,1,6,6,9,9,9,7,3,0,6,9,3,0,3,6,0,3,1,3,3,2,7] print s.superPow(a, b)
69.358974
2,008
0.497597
[ "MIT" ]
thydeyx/LeetCode-Python
Super_Pow.py
2,705
Python
""" Création des images pour la tâche de détermination numérique (pour évaluer l'impact de la configuration sur le subitizing) Victor ANTOINE - [email protected] """ import pygame from random import sample from numpy import random, sort from os import path from itertools import product W, H = 960, 540 pygame.init() screen = pygame.display.set_mode((W, H), pygame.DOUBLEBUF) screen.fill((0, 0, 0)) #création des images en disposition aléatoire origin_x, origin_y = random.randint(50, 910), random.randint(50, 490) list_coord_random_x = list_coords_random_y = [] def create_liste_coord_random(axe, origin): coord1 = coord2 = origin liste = [] liste.append(origin) while coord1 <= axe - 160: coord1 += 80 liste.append(coord1) while coord2 >= 110: coord2 -= 80 liste.append(coord2) liste = list(sort(liste)) return liste list_coord_random_x = create_liste_coord_random(W, origin_x) list_coord_random_y = create_liste_coord_random(H, origin_y) system_coord_random = list(product(list_coord_random_x, list_coord_random_y)) for version in list(range(1, 11)): for points_number in list(range(1, 11)): screen.fill((0, 0, 0)) for (x, y) in sample(system_coord_random, points_number): pygame.draw.circle(screen, (255, 255, 255), (x, y), 30, 0) pygame.image.save(screen, path.join("pictures", "random", \ str(points_number) + "_" + str(version) + ".png")) #création des images en dispostion configurationnelle def create_slot_coord_config(top, left): liste_coord = [] for position in [(1, 1), (3, 1), (2, 2), (1, 3), (3, 3)]: liste_coord.append((top + position[0] * ((W - 270)/8),\ left + position[1] * ((H - 270)/4))) return liste_coord coord_left_side = create_slot_coord_config(130, 130) coord_mid_side = create_slot_coord_config(303, 130) coord_right_side = create_slot_coord_config(475, 130) system_coord_config = [] position = [[2], [1, 3], [1, 2, 3], [0, 1, 3, 4], [0, 1, 2, 3, 4]] for number in range(1, 11): list_coord = [] if number <= 5: positions = position[number-1] for circle in positions: list_coord.append(coord_mid_side[circle]) system_coord_config.append(list_coord) else: for circle in position[4]: list_coord.append(coord_left_side[circle]) positions = position[number-6] for circle in positions: list_coord.append(coord_right_side[circle]) system_coord_config.append(list_coord) number_index = 1 for number in system_coord_config: screen.fill((0, 0, 0)) for (x, y) in number: pygame.draw.circle(screen, (255, 255, 255), (int(x), int(y)), 30, 0) pygame.image.save(screen, path.join("pictures", "config", \ str(number_index) + ".png")) number_index += 1
32.505495
80
0.64165
[ "MIT" ]
Vantoine2019/PCBS_experience_subitizing
create_pictures.py
2,966
Python
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2014 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import time from xmlrpc.client import ServerProxy from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import QPushButton from electrum_zcash import bitcoin, util from electrum_zcash import transaction from electrum_zcash.plugins import BasePlugin, hook from electrum_zcash.i18n import _ from electrum_zcash.wallet import Multisig_Wallet from electrum_zcash.util import bh2u, bfh from electrum_zcash_gui.qt.transaction_dialog import show_transaction import sys import traceback server = ServerProxy('https://cosigner.electrum.org/', allow_none=True) class Listener(util.DaemonThread): def __init__(self, parent): util.DaemonThread.__init__(self) self.daemon = True self.parent = parent self.received = set() self.keyhashes = [] def set_keyhashes(self, keyhashes): self.keyhashes = keyhashes def clear(self, keyhash): server.delete(keyhash) self.received.remove(keyhash) def run(self): while self.running: if not self.keyhashes: time.sleep(2) continue for keyhash in self.keyhashes: if keyhash in self.received: continue try: message = server.get(keyhash) except Exception as e: self.print_error("cannot contact cosigner pool") time.sleep(30) continue if message: self.received.add(keyhash) self.print_error("received message for", keyhash) self.parent.obj.cosigner_receive_signal.emit( keyhash, message) # poll every 30 seconds time.sleep(30) class QReceiveSignalObject(QObject): cosigner_receive_signal = pyqtSignal(object, object) class Plugin(BasePlugin): def __init__(self, parent, config, name): BasePlugin.__init__(self, parent, config, name) self.listener = None self.obj = QReceiveSignalObject() self.obj.cosigner_receive_signal.connect(self.on_receive) self.keys = [] self.cosigner_list = [] @hook def init_qt(self, gui): for window in gui.windows: self.on_new_window(window) @hook def on_new_window(self, window): self.update(window) @hook def on_close_window(self, window): self.update(window) def is_available(self): return True def update(self, window): wallet = window.wallet if type(wallet) != Multisig_Wallet: return if self.listener is None: self.print_error("starting listener") self.listener = Listener(self) self.listener.start() elif self.listener: self.print_error("shutting down listener") self.listener.stop() self.listener = None self.keys = [] self.cosigner_list = [] for key, keystore in wallet.keystores.items(): xpub = keystore.get_master_public_key() K = bitcoin.deserialize_xpub(xpub)[-1] _hash = bh2u(bitcoin.Hash(K)) if not keystore.is_watching_only(): self.keys.append((key, _hash, window)) else: self.cosigner_list.append((window, xpub, K, _hash)) if self.listener: self.listener.set_keyhashes([t[1] for t in self.keys]) @hook def transaction_dialog(self, d): d.cosigner_send_button = b = QPushButton(_("Send to cosigner")) b.clicked.connect(lambda: self.do_send(d.tx)) d.buttons.insert(0, b) self.transaction_dialog_update(d) @hook def transaction_dialog_update(self, d): if d.tx.is_complete() or d.wallet.can_sign(d.tx): d.cosigner_send_button.hide() return for window, xpub, K, _hash in self.cosigner_list: if window.wallet == d.wallet and self.cosigner_can_sign(d.tx, xpub): d.cosigner_send_button.show() break else: d.cosigner_send_button.hide() def cosigner_can_sign(self, tx, cosigner_xpub): from electrum_zcash.keystore import is_xpubkey, parse_xpubkey xpub_set = set([]) for txin in tx.inputs(): for x_pubkey in txin['x_pubkeys']: if is_xpubkey(x_pubkey): xpub, s = parse_xpubkey(x_pubkey) xpub_set.add(xpub) return cosigner_xpub in xpub_set def do_send(self, tx): for window, xpub, K, _hash in self.cosigner_list: if not self.cosigner_can_sign(tx, xpub): continue raw_tx_bytes = bfh(str(tx)) message = bitcoin.encrypt_message(raw_tx_bytes, bh2u(K)).decode('ascii') try: server.put(_hash, message) except Exception as e: traceback.print_exc(file=sys.stdout) window.show_message("Failed to send transaction to cosigning pool.") return window.show_message("Your transaction was sent to the cosigning pool.\nOpen your cosigner wallet to retrieve it.") def on_receive(self, keyhash, message): self.print_error("signal arrived for", keyhash) for key, _hash, window in self.keys: if _hash == keyhash: break else: self.print_error("keyhash not found") return wallet = window.wallet if wallet.has_keystore_encryption(): password = window.password_dialog('An encrypted transaction was retrieved from cosigning pool.\nPlease enter your password to decrypt it.') if not password: return else: password = None if not window.question(_("An encrypted transaction was retrieved from cosigning pool.\nDo you want to open it now?")): return xprv = wallet.keystore.get_master_private_key(password) if not xprv: return try: k = bh2u(bitcoin.deserialize_xprv(xprv)[-1]) EC = bitcoin.EC_KEY(bfh(k)) message = bh2u(EC.decrypt_message(message)) except Exception as e: traceback.print_exc(file=sys.stdout) window.show_message(str(e)) return self.listener.clear(keyhash) tx = transaction.Transaction(message) show_transaction(tx, window, prompt_if_unsaved=True)
35.177273
151
0.628117
[ "MIT" ]
KomodoPlatform/electrum-komodo
plugins/cosigner_pool/qt.py
7,739
Python
"""mgear.core.vector test""" def test_get_distance(run_with_maya_pymel, setup_path): # Maya imports from maya import OpenMaya import pymel.core as pm # mGear imports from mgear.core.vector import get_distance v_1 = [0, 0, 0] v_2 = [1, 0, 0] assert get_distance(v_1, v_2) == 1.0 v_1 = OpenMaya.MVector(0, 0, 0) v_2 = OpenMaya.MVector(1, 0, 0) assert get_distance(v_1, v_2) == 1.0 pm.newFile(force=True) v_1 = pm.createNode("transform") v_2 = pm.createNode("transform") v_2.translate.set(10, 5, 7) distance = pm.createNode("distanceBetween") v_1.worldMatrix >> distance.inMatrix1 v_2.worldMatrix >> distance.inMatrix2 distance_value = distance.distance.get() assert get_distance(v_1, v_2) == distance_value def test_get_plane_binormal(run_with_maya_pymel, setup_path): # Maya imports from maya import OpenMaya # mGear imports from mgear.core.vector import get_plane_binormal vector_a = OpenMaya.MVector(0, 0, 0) vector_b = OpenMaya.MVector(-1, 0, 0) vector_c = OpenMaya.MVector(0, 0, 1) result = get_plane_binormal(vector_a, vector_b, vector_c) assert type(result) == OpenMaya.MVector assert [result[0], result[1], result[2]] == [0, 0, -1] def test_get_plane_normal(run_with_maya_pymel, setup_path): # Maya imports from maya import OpenMaya import pymel.core as pm # mGear imports from mgear.core.vector import get_plane_normal vector_a = OpenMaya.MVector(0, 0, 0) vector_b = OpenMaya.MVector(1, 0, 0) vector_c = OpenMaya.MVector(0, 0, 1) result = get_plane_normal(vector_a, vector_b, vector_c) assert type(result) == OpenMaya.MVector assert [result[0], result[1], result[2]] == [0, 1, 0] pm.newFile(force=True) vector_a = pm.createNode("transform") vector_b = pm.createNode("transform") vector_c = pm.createNode("transform") vector_b.translate.set(-1, 0, 0) vector_c.translate.set(0, 0, 1) result = get_plane_normal(vector_a, vector_b, vector_c) assert [result[0], result[1], result[2]] == [0, -1, 0] result = get_plane_normal(list(vector_a.getTranslation()), list(vector_b.getTranslation()), list(vector_c.getTranslation())) assert [result[0], result[1], result[2]] == [0, -1, 0] def test_linear_interpolate(run_with_maya_pymel, setup_path): # Maya imports from maya import OpenMaya import pymel.core as pm # mGear imports from mgear.core.vector import linear_interpolate _value = [2, 5, 8] v_1 = [0, 0, 0] v_2 = _value result = linear_interpolate(v_1, v_2) assert type(result) == OpenMaya.MVector assert [result[0], result[1], result[2]] == [1, 2.5, 4] pm.newFile(force=True) v_1 = pm.createNode("transform") v_2 = pm.createNode("transform") v_2.translate.set(_value[0], _value[1], _value[2]) result = linear_interpolate(v_1, v_2) assert [result[0], result[1], result[2]] == [1, 2.5, 4]
31.989474
62
0.657782
[ "MIT" ]
FXTD-ODYSSEY/mgear4
tests/test_mgear/test_core/test_vector.py
3,039
Python
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay from sklearn.metrics import accuracy_score from sklearn.model_selection import TimeSeriesSplit from keras.layers import Dropout from keras.layers import Dense, LSTM from keras.models import Sequential import numpy as np from sklearn.preprocessing import StandardScaler from matplotlib import pyplot as plt from datetime import timedelta from datetime import datetime import pandas as pd import datetime from dateutil.relativedelta import relativedelta from pandas_datareader import data as pdr from sklearn.metrics import r2_score, mean_squared_error # pandasのインポート # データの読み込み #df = pd.read_csv('finance_dataset.csv') # データフレームの表示 #df code = '6976' # '6976'#6758 #2021年から今日までの1年間のデータを取得しましょう。期日を決めて行きます。 # (2021, 1, 1) # 教師データ(今までのデータ) #start_train = datetime.date(2022, 1, 1) # 教師データ(今までのデータ) start_train=datetime.date.today() + relativedelta(days=-700) #dowstart_train = datetime.date(2022, 1, 5)#start_train + relativedelta(days=+3) # 昨日分(today-1日)まで取得できる(当日分は変動しているため) end_train = datetime.date.today() + relativedelta(days=-1) data = pdr.get_data_yahoo(f'{code}.T', start_train, end_train) # 教師データを読み込む。 Dow_df = pdr.get_data_yahoo('^DJI', start_train, end_train) # 試験データのcsvファイルを読み込む。 Nikkei_df = pdr.get_data_yahoo('^N225', start_train, end_train) # 試験データのcsvファイルを読み込む。 #データの前処理 #欠損データがあるので、欠損値NaNを除外する #df_NikkeiAll_drop = df_NikkeiAll.dropna() #df_NikkeiAll_drop.head() # 先頭の5行を表形式で表示 print(data.head()) ''' png インデックスが0から13966までの連番で、カラムに 日付('Date')、最高値('High')、最安値('Low')、始値('Open')、終値('Close')が設定されたデータフレームである事が確認できます。 日付('Date)は1965年1月5日から2021年10月21日までとなっています。 後に詳しく説明を行いますが、予測モデル作成に対して、目的変数の追加や、週ごとにデータを纏める必要があります。 そのために、曜日情報や初めの週を基準として何週目となるか等の情報と、今回の目的変数である木曜日の終値から翌日金曜日の始値が上がるかどうかの’Up’(上がる場合は'1', 同じ又は下がる場合は'0')を追加していきます。 次に、infoメソッドを用いて、欠損値の有無やカラムのデータ型の確認を行います。 ''' # 各カラムの詳細確認 data.info() ''' png 各カラム欠損値なしである事がわかります。 日付('Date')が’object'型となっています。今回の様な時系列データを用いる際には、'datetime64'型を用いる方が利便性が高い為、pandasの'to_datetime'メソッドを用いてデータ型の変換を行います。 ''' # 日付インデックスをりセット data.reset_index(drop=False,inplace=True) Dow_df.reset_index(drop=False,inplace=True) Nikkei_df.reset_index(drop=False, inplace=True) # Dateのデータ型をを'datetime'型へ変更 data['Date'] = pd.to_datetime(data['Date']) Dow_df['Date'] = pd.to_datetime(Dow_df['Date']) Nikkei_df['Date'] = pd.to_datetime(Nikkei_df['Date']) data.info() ''' png 'Date'のカラムが'object'型から'datetime64'型へ代わっていることが確認できます。 次に曜日情報のカラムを追加します。'datetime64'型は'dt.weekday'メソッドを用いて、曜日情報を取得する事ができます。月曜日を0として連番の数字を設定されます。実行結果をdfに'weekday'カラムを追加して入力し、実行結果を確認します。 ''' # 曜日情報を追加(月曜:0, 火曜:1, 水曜:2, 木曜:3, 金曜:4、土曜:5、日曜:6) data['weekday'] = data['Date'].dt.weekday #data['Dowweekday'] = Dow_df['Date'].dt.weekday #data['DowDate'] = Dow_df['Date'] #data['Nikkeiweekday'] = Nikkei_df['Date'].dt.weekday print(data) ''' png 'weekday'のカラムが追加され0から4の数字が入力されている事がわかります。 また、株取引の行われない土曜日: 5と日曜日: 6のデータは存在していない事もわかります。 次に、1965年1月5日の週を基準に何周目となるのかの情報を追加します。 1965年1月5日が火曜日である事がわかるので、その週の頭の月曜日となる1965年1月4日を基準として、何日目となるのかの情報を追加します。 datetimeのライブラリからdatetimeとtimedeltaをインポートします。 基準となる日の1965年1月4日をdatetime関数を使って、変数startに代入します。 dfの'Date'カラムから基準のstartと引き算をすることで、何日目となるのかを計算します。これをtimedelta関数を用いて1週間となる7日周期で割ることで何週目かを計算する事ができます。 timedelta(weeks=1)と設定することで1週間となります。 この計算結果を'weeks'というカラムをdfに追加します。実行することで初めの週は0から始まり最後の2021年10月18日の週は2963となっている事が分かります。 ''' # 初めの月曜日となる1965/1/4を基準に日数を追加 start = start_train+relativedelta(days=-2) # datetime(1965, 1, 4) start = pd.to_datetime(start) #data['weeks'] = (data['Date'] - start) // timedelta(weeks=1) #data['Dowweeks'] = (Dow_df['Date'] - start) // timedelta(weeks=1) #data['Nikkiweeks'] = (Nikkei_df['Date'] - start) // timedelta(weeks=1) #print(data) #data.to_csv('data/stocks_price_data/KinoCode_data.csv') # csv書き出し ''' png 日付の情報の'Date', 'weekday', 'weeks'のカラムが分かれて表示されているので、見栄えを整理する目的で、一旦カラムの並び替えを行います。 先頭に日付の情報をまとめます。 並び替えたい順序でカラムを記述しdfを置き換えます。 実行する事で、並び替えられている事がわかります。 ''' # Closeの列のデータのみを取り出し data['NikkiClose'] = Nikkei_df['Close'].values # カラムの並べ替え df = data[['Date', 'weekday','High', 'Low', 'Open', 'Close', 'NikkiClose']] #df_dow = Dow_df[['Date', 'weeks', 'weekday', 'High', 'Low', 'Open', 'Close']] #df_nikkei = Nikkei_df[['Date', 'weeks', 'weekday', 'High', 'Low', 'Open', 'Close']] print(df) df.to_csv('data/stocks_price_data/KinoCode_data.csv') # csv書き出し ''' png 今回のような時系列データを処理する際には、set_indexメソッドを使ってindexを日付に設定します。念のためにsort_valuesメソッドを使って日付順に並び替えを行います。実行する事で、日付の'Date'がindexに設定されている事がわかります。 ''' # データの並び替え df.sort_values(by='Date', ascending=True, inplace=True) # 日付をインデックスにセット df.set_index(keys='Date', inplace=True) print(df) ''' png 次に今回予測したい翌日の終値が本日の終値よりも上がるのかどうかの情報を追加します。shiftメソッドを用いてカラムの情報をずらすdfを作成する事ができるので、それを用いて計算を行います。 shift(-1)とする事で、カラムの情報を1行上にずらしたデータフレームを作成する事ができます。 dfを1行分上にずらしたものをdf_shiftとして作成します。実行する事でカラムの情報が1行分上にシフトしている事がわかります。一番下のカラムは欠損値となります。 ''' #カラム情報を1行上にずらしたデータフレームを作成する df_shift = df.shift(-1) df_shift #png #このdf_shiftを用いて、翌日の終値と本日の終値を引き算し、その結果を'delta_Close'というカラムを追加しdfに入力します。 #翌日の始値と本日の終値の差分を追加する df['delta_Close'] = df_shift['Close'] - df['Close'] df ''' png この'delta_Close'が上がる場合1、それ以外を0として目的変数となる'Up'のカラムを追加します。同時に'delta_Close'カラムの削除も行います。 ''' #目的変数Upを追加する(翌日の終値が上がる場合1、それ以外は0とする)、'delta_Close'カラムの削除 df['Up'] = 0 df['Up'][df['delta_Close'] > 0] = 1 df = df.drop('delta_Close', axis=1) df ''' png ここまでで、下準備となる週番号、曜日、目的変数の追加が終わりました。 データの全体像をつかむ 時系列データをグラフで表示する事で、株価変動の大まかなイメージを掴みます。 'Open', 'High', 'Low', 'Close'を抜き出しdf_newを作成後に、pyplotを用いてグラフ化行います。 matplotlibのライブラリからpyplotをpltという名前でインポートします。 df_newにplotメソッドを用いて、引数'kind=line'とする事で折れ線グラフが作成されます。pyplotのshowメソッドでグラフを表示します。 初めの1965年から1990年頃までは、上昇傾向となっています。その後は下がる傾向となり、2010頃より再度上昇傾向である事がわかります。 ''' # 'Open', 'High', 'Low', 'Close'グラフ化のためにカラム抽出 df_new = df[['Open', 'High', 'Low', 'Close']] # matplotlibのインポート # 時系列折れ線グラフの作成 df_new.plot(kind='line') plt.show() ''' png 特徴量を追加する 予測を正しく行えるようにする為の情報量(特徴量)を追加します。現在dfに入っている始値、終値、最高値、最安値の情報だけを用いて予測する事も可能ですが、株価の変動に影響すると言われている一般的な情報を追加していきます。 終値の前日比率と、始値と終値の差分カラムに追加します。 まず終値の前日比率ですが、本日の終値が前日から何%変動したのかを表す値となります。 (今日の終値 - 前日の終値) ÷ 前日の終値 で計算します。 shiftメソッドを用いて、今度は1行したにずらしたデータフレームを作成し、終値の前日比率'Close_ratio'を計算しdfにカラムを追加します。 ''' # 終値の前日比の追加 df_shift = df.shift(1) df['Close_ratio'] = (df['Close'] - df_shift['Close']) / df_shift['Close'] df #png #次に、始値と終値の差分'Body'をdfに追加します。 # 始値と終値の差分を追加 df['Body'] = df['Open'] - df['Close'] df ''' png 特徴量の追加は以上になります。次に、不要なデータの削除を行います。今回、月曜日から木曜日までの情報を用いて、金曜日の始値が上がるか下がるのかを予測するモデルを作成するために、各週で月曜日から金曜日までのデータが揃っている週だけ使用します。祝日や年末年始など株取引が行われていない日はデータがない為、5日分のデータが揃っていない週が存在しています。 各週毎に何日分のデータが存在しているのかを調べて、5日分揃っている週のデータを持ってきます。 手順としては、週番号'weeks'のリストを作成します。その後リストから取り出した同じ週番号のデータ数をカウントして行き結果をdfに格納し、5日揃っている週だけ残す処理をします。 週番号は0から2963まで連番で有ると考えられ、0から順番に処理すれば良いと考えられますが、万が一抜けている週が存在して居ても処理が行えるように、あえて週番号を抜き出したリスト(list_weeks)を作成します。 ''' ''' # 週番号をリストに格納 list_weeks = [] list_weeks = df['weeks'].unique() list_weeks #png #リストに従い、for文を用いて、週毎の日数をカウントしたカラム'week_days'にカウント数を入力します。 # 各週ごとの日数を入力 df['week_days'] = 0 for i in list_weeks: df['week_days'][df['weeks'] == i] = len(df[df['weeks'] == i]) df #png #5日データの存在する週(week_daysが5)の週のデータを抜き出して、dfに入力します。 # 月曜〜金曜まで5日分データのある週だけデータを取り出す df = df[df['week_days'] == 5] df #png #予測に使用しない金曜日のデータ(weekdayが4)を削除します。 #金曜日のデータを削除する(weekday:4となるデータ) df = df[df['weekday'] != 4] df ''' #png #不要カラムの削除と並び替えを行います。 # 不要カラムの削除と並べ替え df = df[['weekday', 'High', 'Low', 'Open', 'Close', 'Close_ratio', 'Body', 'Up']] df ''' png ここまでで、データの準備は完了です。 学習データと検証データに分割する さて、ここからは直近の2018年以降のデータを使用します。 2018年から2020年を学習データ、2021年以降を検証データとして分割します。 datetime64型をindexに設定している時系列のデータフレームは、期間を設定してデータを抜き出す事ができます。 2018年1月1日から2020年12月31日までのデータを抜き出し、df_trainに入力します。 ''' # 学習データを2018-01-01〜2020-12-31の期間としdf_trainに入力する df_train = df['2018-01-01': '2020-12-31'] df_train #png #同様に、2021年1月1日以降のデータを抜き出し、df_valに入力します。 # 検証データを2021-01-01以降としてとしてdf_valに入力する df_val = df['2021-01-01':] df_val ''' png 学習データと検証データをそれぞれ、説明変数と目的変数に分けます。 説明変数のカラムは'weekday', 'High', 'Low', 'Open', 'Close', 'Close_ratio', 'Body'を 目的変数のカラムは'Up'になります。 学習データの説明変数をX_train、学習データの目的変数をy_trainとしてカラムを指定して、それぞれを入力します。また、表示することでX_train, y_trainそれぞれに指定した期間内のデータが入力されていることが分かります。 ''' # 学習データを説明変数(X_train)と目的変数(y_train)に分ける X_train = df_train[['weekday', 'High', 'Low', 'Open', 'Close', 'Close_ratio', 'Body']] y_train = df_train['Up'] # 学習データの説明変数と目的変数を確認 print(X_train) print(y_train) #png #png #同様に検証データの説明変数をX_val、目的変数をy_valとしてデータを入力し、確認します。 # 検証データを説明変数(X_val)と目的変数(y_val)に分ける X_val = df_val[['weekday', 'High', 'Low', 'Open', 'Close', 'Close_ratio', 'Body']] y_val = df_val['Up'] # 検証データの説明変数と目的変数を確認 print(X_val) print(y_val) #png #png #学習データと検証データの時系列グラフを作成し2021年前後でデータが分かれていることを目で確認します。2021年以前が学習データで青いグラフ、2021年以降が検証データでオレンジのグラフで示されている事が分かります。 # 学習データと検証データの終値(Close)の折れ線グラフ作成 X_train['Close'].plot(kind='line') X_val['Close'].plot(kind='line') # グラフの凡例を設定 plt.legend(['X_train', 'X_val']) # グラフの表示 plt.show() ''' png データを整える 予測モデルに学習をさせるために、データを整えます。 説明変数は各週毎の月曜日から木曜日の4日間をセットとして一つにまとめます。また、目的変数は翌日の金曜日の始値が上がるか下がるかを示す木曜日のデータを抜き出します。機械学習を行うためには説明変数と目的変数の数を揃える必要があります。 png 説明変数を抜き出す期間により、株価の金額や変動量が違っています。 例えば、2020年4月頃は株価が16000円程度であったのに対し、12月頃には25000円を超えていたり、同じ週でも株価の変動が大きい事もあります。 このように抜き出している期間内において、データの大きさや変動幅が大きく異なっている場合、機械学習では予測が正しく行えない事があります。このような場合に標準化という処理を行うことが有ります。 この処理を行うことで、平均が0で±3以内の範囲に収める事が出来るために、機械は計算の処理がし易くなり、また予測精度が向上する事もあります。 png この4日毎にデータを抜き出して、標準化を行うための処理を、sklearnのpreprocessingというライブラリのStandardScalerという関数を使って、for文の繰り返し処理を用いて次のような関数を定義します。 また今回、機械学習に使用する予測モデルはLSTMというニューラルネットのモデルを使用します。このモデルではnumpy配列という形式のデータを用います。 ''' # 標準化関数(StandardScaler)のインポート # numpyのインポート # 4日ごとにデータを抜き出して、標準化ととnumpy配列に変換する関数(std_to_np)の定義 def std_to_np(df): df_list = [] df = np.array(df) for i in range(0, len(df) - 3, 4): df_s = df[i:i+4] scl = StandardScaler() df_std = scl.fit_transform(df_s) df_list.append(df_std) return np.array(df_list) #標準化を行うStandardScalaerをsklearn.preprocessingから、numpyをnpとしてインポートします。 # 次に4日毎にデータを抜き出し、標準化を行い、numpy配列で出力する関数(std_to_np)を定義します。 #df_list = [] でまず空のリストを定義します。ここには標準化をおこなった後の、4日毎にまとまったデータを格納して行きます。 #df = np.array(df) で入力されたデータフレームをまずnumpy配列に変換します。 #この配列に対して、for文を用いて4日ずつのデータ抜き出して、df_sに入力(df_s=df[i:i+4])した後に、StandardScalerをインスタンス化し(scl= StandardScaler()) 標準化をおこなった結果をdf_stdに入力(df_std=scl.fit_transform(df_s))し、それをはじめに定義したdf_listにappendメソッドを用いて格納(df_list.append(df_std))して行きます。最後の4日分のデータまでこの繰り返し処理を行います。 #繰り返し処理が終了すると、df_listをnumpy配列で出力(return np.array(df_list))します。 #この関数をX_trainとX_valに適用してデータの型を確認します。 # 学習データと検証データの説明変数に関数(std_to_np)を実行 X_train_np_array = std_to_np(X_train) X_val_np_array = std_to_np(X_val) # 学習データと検証データの形の確認 print(X_train_np_array.shape) print(X_val_np_array.shape) ''' png 出力結果から、480日分あったX_trainが4分の1の120個のデータとなり、132日分あったX_valが4分の1の33個のデータになっている事がわかります。 それぞれの数に続く'4'は月曜から木曜の4日分のデータ数を表しており、'7'は説明変数('weekday', 'High', 'Low', 'Open', 'Close', 'Close_ratio', 'Body')のカラム数を表しています。 続いて、目的変数の木曜日のデータだけ抜き出します。抜き出す前に一旦、学習データと検証データのデータを確認します。 ''' # 学習データと検証データの目的変数を確認 print(y_train) print(y_val) #png #学習データは480個、検証データは132個有ることがわかります。 #これらのデータに対して、各週の4日目(木曜日)のデータを抜き出して確認します。 # 学習データ、検証データの目的変数の間引き # 週の4日目(木曜日)のデータだけ抜き出す y_train_new = y_train[3::4] y_val_new = y_val[3::4] # 間引き後の学習データと検証データの目的変数を確認 print(y_train_new) print(y_val_new) #学習データと検証データそれぞれ各週の4日目のデータのみになっており、個数は120個と33個となっており、4日毎にまとめた説明変数のデータ数と同じになっています。 #png #png #これで、機械学習を行うためのデータは整いました。 ''' 予測モデルの作成 ニューラルネットの1種のLSTMを用いて予測モデルの作成と、検証データを用いた予測精度の検証をします。 LSTMを使用するためにkerasのライブラリを使えるようにする必要があります。まずこのためにtensorflowをインストールします。個人の環境で、インストール済みの方は不要ですが、google colabolatoryを使用の方は毎回行う必要があります。インストールは次のコマンドで数秒で完了します。 ''' #!pip install tensorflow #続いて、kerasから必要な関数をインポートします。 # keras.modelsからSequentialのインポート # keras.layersからDense、LSTMのインポート # Dropoutのインポート #ニューラルネットの構築や、パラメータのチューニング方法の説明は省略させて頂きますが、 # 基本的な入力層、中間層と出力層からなるモデルをこのように構築することができます。 # また、このモデルをlstm_compという関数で定義しましょう。 # LSTM構築とコンパイル関数 def lstm_comp(df): # 入力層/中間層/出力層のネットワークを構築 model = Sequential() model.add(LSTM(256, activation='relu', batch_input_shape=( None, df.shape[1], df.shape[2]))) model.add(Dropout(0.2)) model.add(Dense(256, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(1, activation='sigmoid')) # ネットワークのコンパイル model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model ''' 次に、作成したモデルが本当に予測に使用できるのかを確認する方法として、交差検証をしましょう。正解の分かっている学習データを複数に分割して、交差検証を行うのが有効です。 交差検証の手法には複数存在しますが、今回の様な時系列のデータで過去のデータを用いて未来を予測する場合は、時系列分割の交差検証を用いるのが一般的です。 今回は学習データを5分割し、学習データと検証データが図の様なイメージの組み合わせで合計4回の学習、予測と精度検証を繰り返します。これらのスコアの平均値から、モデルが予測に使用できるかの判断を行います。 この手法では検証データよりも過去のデータのみを用いて学習を行ないます。 png まず、時系列分割交差検証を行うためのTimeSeriesSplitと、予測結果の精度(accuracy)を算出するためにaccuracy_scoreをインポートします。 # 時系列分割のためTimeSeriesSplitのインポート # accuracy算出のためaccuracy_scoreのインポート つぎに、4回分の交差検証の結果を代入する空のリストを作成します。そして、TimeSeriesSplitのインスタンス化を行い変数(tscv)に代入します。 ''' valid_scores = [] tscv = TimeSeriesSplit(n_splits=4) ''' for文を用いて、交差検証を4回繰り返します。 具体的にはこのような検証を実施します。 splitメソッドを用いて学習データを分割し、交差検証用の学習データと検証データを作成 先に定義したlstm_comp関数よりLSTMモデルを作成 交差検証用の学習データより学習 検証データの説明変数を用いて予測 予測結果の2値化 検証データの目的変数(正解データ)を用いて、予測結果の精度算出と表示 予測精度のスコアをリストに格納 ''' for fold, (train_indices, valid_indices) in enumerate(tscv.split(X_train_np_array)): X_train, X_valid = X_train_np_array[train_indices], X_train_np_array[valid_indices] y_train, y_valid = y_train_new[train_indices], y_train_new[valid_indices] # LSTM構築とコンパイル関数にX_trainを渡し、変数modelに代入 model = lstm_comp(X_train) '''# モデル学習''' hist = model.fit(X_train, y_train, epochs=10, batch_size=64) # loss(訓練データに対する判定結果)、val_loss(テストデータに対する判定結果)をプロットする #loss = hist.history['loss'] #val_loss = hist.history['val_loss'] #epochs = len(loss) '''''' # 予測 y_valid_pred = model.predict(X_valid) # 予測結果の2値化 y_valid_pred = np.where(y_valid_pred < 0.5, 0, 1) # 予測精度の算出と表示 score = accuracy_score(y_valid, y_valid_pred) print(f'fold {fold} MAE: {score}') # 予測精度スコアをリストに格納 valid_scores.append(score) #4回の交差検証が終了したら、予測精度のスコアが格納されたリストの表示し、スコアの平均値の算出と表示もしてみましょう。 #4回のそれぞれのスコアと、平均値はこのようになりました。 print(f'valid_scores: {valid_scores}') cv_score = np.mean(valid_scores) print(f'CV score: {cv_score}') ''' png 1回目:0.541 2回目:0.708 3回目:0.541 4回目:0.333 平均:0.531 今回のような上がるか下がるかの2値予測の場合、一般的にはスコアが0.5以上であればある程度使用できるという目安となります。 算出したスコアと平均値から、このモデルがある程度使用できるものと判断して次に進みましょう。 では、このモデルに対して、2018年から2020年の学習データを用いて学習をします。 流れは先ほどの交差検証と似ています。 まずは標準化した学習データでLSTMモデルを作成します。 ''' # LSTM構築とコンパイル関数にX_train_np_arrayを渡し、変数modelに代入 model = lstm_comp(X_train_np_array) #作成したモデルで、学習します。 #一瞬で学習が終了しました。 # モデルの学習の実行 result = model.fit(X_train_np_array, y_train_new, epochs=10, batch_size=64) #今度は学習したモデルを用いて、検証データについて予測を行い、先頭の10個を表示させてみましょう。 # 作成したモデルより検証データを用いて予測を行う pred = model.predict(X_val_np_array) pred[:10] ''' このように予測した結果が表示されます。 png この数値を、上がるか下がるかの0と1に変換します。numpyのwhereメソッドを用いて0.5を超えるものを1、それ以外を0と修正します。そして再度先頭の10個を表示します。 これで、上がるか下がるかの01どちらかの予測ができました。 ''' # 予測結果を0もしくは1に修正(0.5を境にして、1に近いほど株価が上昇、0に近いほど株価が上昇しない) pred = np.where(pred < 0.5, 0, 1) # 修正した予測結果の先頭10件を確認 pred[:10] ''' png 次に、予測モデルの精度確認を行います。この予測結果を実際の値となる検証データの目的変数と比較し、正解率を計算します。sklearnのaccuracy_scoreという関数を使うことで計算が行えます。 この結果を表示すると57%の正解率で有ることがわかります。今回の様な株価が上がるか下がるかの2値の予測では、直感的に予測を行う場合50%の正解率となります。機械学習を用いる事でそれを超える正解率となりました。 ''' # 実際の結果から予測値の正解率を計算する print('accuracy = ', accuracy_score(y_true=y_val_new, y_pred=pred)) ''' # モデルの精度を評価する # 決定係数とRMSEを計算する # 決定係数は1.0に、RMSEは0.0に近いほど、モデルの精度は高い r2_score = r2_score(y_test, predictions) rmse = np.sqrt(mean_squared_error(y_test, predictions)) print(f'r2_score: {r2_score:.4f}') print(f'rmse: {rmse:.4f}') ''' ''' png 最後に、予測結果と正解結果を混同行列を用いて確認します。 混同行列とは、このように2行2列の表で、真陽性、真陰性、偽陽性、偽陰性の数を表したものです。今回は、予測が0で結果も0、予測が1で結果も1であれば正解です。0と予測して結果が1、1と予測して結果が0なら不正解ということになります。全体の精度だけではなく、0と1それぞれの正解に対する精度を確認することができます。 jpg 混同行列を生成するために、sklern.mericsからconfusion_matrixとConfusionMatrixDisplayをインポートします。 また、視覚的にわかりやすい様に、ヒートマップで表示しましょう。 このように、正しく予測が行えているのは、右下の真陽性(TP)と左上の真陰性(TN)です。予測結果が、0か1のどちらかに極端に偏っている傾向ではなさそうですが、正しく予測できていないものも存在していることがわかります。予測精度を改善することで、偽陽性(FP)と偽陰性(FN)の数を減らすことができます。 ''' # 混同行列生成のためconfusion_matrixをインポート # 混同行列を表示 cm = confusion_matrix(y_val_new, pred) cmp = ConfusionMatrixDisplay(cm) cmp.plot(cmap=plt.cm.Reds) # グラフの表示 plt.show() ''' 今回は基本的な特徴量や、機械学習モデルの構築方法で予測を行いました。特徴量を追加することや、学習モデルの改良を行うことで、予測精度を向上させることが可能です。 とはいえ、データの期間が変わるだけでも精度も変わります。必ずいつも予測がうまくいくわけではありませんのでご注意ください。 ''' ''' Graphics parameter ''' # Closeの列のデータのみを取り出し TergetData = data['Close'].values # datetimeの列のデータのみを取り出し data = data.reset_index(drop=False) TergetDate = data['Date'].values #リシェイプ TergetData = TergetData.reshape(-1, 1) # float64 TergetDate = TergetDate.reshape(-1, 1) # datetime64[ns] # 読み込んだ日経平均をプロット k = 700 # 表示する数 i = TergetData.shape[0]-k j = TergetData.shape[0] xdata = TergetDate[i:j] ydata = TergetData[i:j] #描画するデータの読み込み fig = plt.figure(figsize=(15, 10), dpi=100) ax = fig.add_subplot(2, 1, 1) # 図全体のタイトル fig.suptitle( "Long Short-Term Memory (Deep Larning) of Artificial Intelligence[AI]", fontsize=20) plt.title("Test Graph", {"fontsize": 20}) ax1 = plt.subplot(2, 2, 1) # 2x2の1番目 ax1.plot(xdata, ydata) # 1番目に描画 ax1.legend(loc='best') ax1.grid() ax1.set_xlabel('Date') # 1番目にxラベルを追加 ax1.set_ylabel(f'{code}') # 1番目にyラベルを追加 ax2 = plt.subplot(2, 2, 2) # 2x2の1番目 ax2.plot(range(epochs), loss, marker='.', label='loss(training data)') # 1番目に描画 ax2.plot(range(epochs), val_loss, marker='.', label='val_loss(evaluation data)') # 1番目に追加描画 ax2.legend(loc='best') ax2.grid() ax2.set_xlabel('epoch') # 1番目にxラベルを追加 ax2.set_ylabel('loss') # 1番目にyラベルを追加 ax3 = plt.subplot(2, 2, 3) # 2x2の3番目 ax3.plot(datelabel, predicted_N, marker='.', label='predicted') # 1番目に描画 ax3.plot(datelabel, y_test_price_N, marker='.', label='y_test_price') # 1番目に追加描画 ax3.legend(loc='best') ax3.grid() ax3.set_xlabel('Date') ax3.set_ylabel(f'{code}') ax4 = plt.subplot(2, 2, 4) # 2x2の4番目 ax4.plot(range(len(predicted_futureN)), predicted_futureN, marker='.', label='future predicted') # 1番目に描画 ax4.plot(range(len(predicted_futureN[:10])), predicted_futureN[:10], marker='.', label='real data', color="0.5") # 1番目に追加描画 ax4.legend(loc='best') ax4.grid() ax4.set_xlabel('Date') # 1番目にxラベルを追加 ax4.set_ylabel(f'{code}') # 1番目にyラベルを追加 # グラフを表示する plt.show()
26.414141
254
0.781043
[ "MIT" ]
susumOyaji/chaquopy-matplotlib-master
app/src/main/python/KinoCode.py
33,041
Python
# # (C) Copyright 2020 Pavel Tisnovsky # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Pavel Tisnovsky # WIDTH = 480 HEIGHT = 480 BACKGROUND_COLOR = (0, 0x80, 0x80) TEXT_COLOR = "Orange" TEXT_LEFT = 10 TEXT_HEIGHT = 16 MESSAGES = ( "F - fast animation", "R - reset animation", "", "Esc - exit" ) sprite = Actor("sprite1.png") sprite.pos = (0, 240) def draw(): screen.fill(BACKGROUND_COLOR) sprite.draw() y = 10 for message in MESSAGES: screen.draw.text(message, (TEXT_LEFT, y), color=TEXT_COLOR) y += TEXT_HEIGHT def on_key_down(key, mod, unicode): if key == keys.ESCAPE: exit() if key == keys.R: sprite.x = 0 if key == keys.F: animate(sprite, x=WIDTH)
20.367347
72
0.624248
[ "EPL-1.0" ]
tisnik/most-popular-python-libs
pygame_zero/39_animation_framework.py
998
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2014 Daniel Standage <[email protected]> # Copyright (c) 2008 Sascha Steinbiss <[email protected]> # Copyright (c) 2008 Center for Bioinformatics, University of Hamburg # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # from gt.dlload import gtlib from gt.annotationsketch.rec_map import RecMap import math class ImageInfo: def __init__(self): self.ii = gtlib.gt_image_info_new() self._as_parameter_ = self.ii self.hotspots = None def __del__(self): try: gtlib.gt_image_info_delete(self.ii) except AttributeError: pass def from_param(cls, obj): if not (isinstance(obj, ImageInfo) or obj == None): raise TypeError, "argument must be an ImageInfo" if obj == None: return None return obj._as_parameter_ from_param = classmethod(from_param) def get_height(self): return gtlib.gt_image_info_get_height(self.ii) def num_of_rec_maps(self): return gtlib.gt_image_info_num_of_rec_maps(self.ii) def compare_hotspots(cls, hs1, hs2): if hs1[2] - hs1[0] + 1 > hs2[2] - hs2[0] + 1: return 1 elif hs1[2] - hs1[0] + 1 == hs2[2] - hs2[0] + 1: if hs1[3] > hs2[3]: return 1 elif hs1[3] == hs2[3]: return 0 else: return -1 else: return -1 compare_hotspots = classmethod(compare_hotspots) def each_hotspot(self): if not self.hotspots: self.hotspots = [] for i in range(self.num_of_rec_maps()): rm = RecMap(gtlib.gt_image_info_get_rec_map(self.ii, i)) self.hotspots.append([math.floor(rm.get_northwest_x()), math.floor(rm.get_northwest_y()), math.floor(rm.get_southeast_x()), math.floor(rm.get_southeast_y()), rm.get_genome_feature()]) self.hotspots.sort(ImageInfo.compare_hotspots) for hs in self.hotspots: yield (hs[0], hs[1], hs[2], hs[3], hs[4]) def register(cls, gtlib): from ctypes import c_void_p, c_ulong, c_uint gtlib.gt_image_info_delete.restype = None gtlib.gt_image_info_delete.argtypes = [c_void_p] gtlib.gt_image_info_get_rec_map.restype = c_void_p gtlib.gt_image_info_get_rec_map.argtypes = [c_void_p, c_ulong] gtlib.gt_image_info_num_of_rec_maps.restype = c_ulong gtlib.gt_image_info_num_of_rec_maps.argtypes = [c_void_p] gtlib.gt_image_info_get_height.restype = c_uint gtlib.gt_image_info_get_height.argtypes = [c_void_p] gtlib.gt_image_info_new.restype = c_void_p gtlib.gt_image_info_new.argtypes = [] register = classmethod(register)
37.178947
91
0.656569
[ "BSD-2-Clause" ]
ggonnella/genometools
gtpython/gt/annotationsketch/image_info.py
3,532
Python
# -*- coding: utf-8 -*- from __future__ import unicode_literals import six from django import http from django.urls import reverse from django.utils.http import unquote try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class AngularUrlMiddleware(MiddlewareMixin): """ If the request path is <ANGULAR_REVERSE> it should be resolved to actual view, otherwise return ``None`` and continue as usual. This must be the first middleware in the MIDDLEWARE_CLASSES tuple! """ ANGULAR_REVERSE = '/angular/reverse/' def process_request(self, request): """ Reads url name, args, kwargs from GET parameters, reverses the url and resolves view function Returns the result of resolved view function, called with provided args and kwargs Since the view function is called directly, it isn't ran through middlewares, so the middlewares must be added manually The final result is exactly the same as if the request was for the resolved view. Parametrized urls: djangoUrl.reverse can be used with parametrized urls of $resource In that case the reverse url is something like: /angular/reverse/?djng_url_name=orders&djng_url_kwarg_id=:id $resource can either replace the ':id' part with say 2 and we can proceed as usual, reverse with reverse('orders', kwargs={'id': 2}). If it's not replaced we want to reverse to url we get a request to url '/angular/reverse/?djng_url_name=orders&djng_url_kwarg_id=' which gives a request.GET QueryDict {u'djng_url_name': [u'orders'], u'djng_url_kwarg_id': [u'']} In that case we want to ignore the id param and only reverse to url with name 'orders' and no params. So we ignore args and kwargs that are empty strings. """ if request.path == self.ANGULAR_REVERSE: url_name = request.GET.get('djng_url_name') url_args = request.GET.getlist('djng_url_args', []) url_kwargs = {} # Remove falsy values (empty strings) url_args = filter(lambda x: x, url_args) # Read kwargs for param in request.GET: if param.startswith('djng_url_kwarg_'): # Ignore kwargs that are empty strings if request.GET[param]: url_kwargs[param[15:]] = request.GET[param] # [15:] to remove 'djng_url_kwarg' prefix url = unquote(reverse(url_name, args=url_args, kwargs=url_kwargs)) assert not url.startswith(self.ANGULAR_REVERSE), "Prevent recursive requests" # rebuild the request object with a different environ request.path = request.path_info = url request.environ['PATH_INFO'] = url query = request.GET.copy() for key in request.GET: if key.startswith('djng_url'): query.pop(key, None) if six.PY3: request.environ['QUERY_STRING'] = query.urlencode() else: request.environ['QUERY_STRING'] = query.urlencode().encode('utf-8') # Reconstruct GET QueryList in the same way WSGIRequest.GET function works request.GET = http.QueryDict(request.environ['QUERY_STRING'])
45.391892
116
0.650789
[ "MIT" ]
BluABK/django-angular
djng/middleware.py
3,359
Python
import pytest from migri.backends.postgresql import PostgreSQLConnection from test import QUERIES @pytest.mark.parametrize( "query_element,expected_query,expected_values", [ (QUERIES[0], "INSERT INTO mytable (a) VALUES ($1), ($2)", [150, 300]), (QUERIES[1], "UPDATE tbl SET info=$2 WHERE id=$1", [39, "ok"]), (QUERIES[2], "SELECT * FROM school", []), ( QUERIES[3], "SELECT * FROM val WHERE (value < $1 AND status = $3) " "OR (value > $2 AND status = $3)", [20, 100, "ok"], ), ], ) def test_compile(query_element, expected_query, expected_values): backend = PostgreSQLConnection("postgres") assert backend._compile(query_element) == { "query": expected_query, "values": expected_values, }
30.333333
78
0.589744
[ "MIT" ]
RonquilloAeon/migri
test/asyncpg/test_postgresql.py
819
Python
from tests.base_case import ChatBotTestCase from chatterbot.logic import LogicAdapter from chatterbot.conversation import Statement class ChatterBotResponseTestCase(ChatBotTestCase): def test_conversation_values_persisted_to_response(self): response = self.chatbot.get_response('Hello', persist_values_to_response={ 'conversation': 'test 1' }) self.assertEqual(response.conversation, 'test 1') def test_tag_values_persisted_to_response(self): response = self.chatbot.get_response('Hello', persist_values_to_response={ 'tags': [ 'tag 1', 'tag 2' ] }) self.assertEqual(len(response.tags), 2) self.assertIn('tag 1', response.get_tags()) self.assertIn('tag 2', response.get_tags()) def test_in_response_to_provided(self): """ Test that the process of looking up the previous response in the conversation is ignored if a previous response is provided. """ self.chatbot.get_response( text='Hello', in_response_to='Unique previous response.' ) statement = self.chatbot.storage.filter( text='Hello', in_response_to='Unique previous response.' ) self.assertIsNotNone(statement) def test_get_initialization_functions(self): """ Test that the initialization functions are returned. """ functions = self.chatbot.get_initialization_functions() self.assertIn('download_nltk_stopwords', str(functions)) self.assertIn('download_nltk_wordnet', str(functions)) self.assertIn('download_nltk_averaged_perceptron_tagger', str(functions)) self.assertIsLength(functions, 3) def test_get_initialization_functions_spacy_similarity(self): """ Test that the initialization functions are returned. """ from chatterbot.comparisons import spacy_similarity list(self.chatbot.search_algorithms.values())[0].compare_statements = spacy_similarity functions = self.chatbot.get_initialization_functions() self.assertIn('download_nltk_stopwords', str(functions)) self.assertIn('download_nltk_wordnet', str(functions)) self.assertIn('download_nltk_averaged_perceptron_tagger', str(functions)) self.assertIsLength(functions, 3) def test_get_initialization_functions_jaccard_similarity(self): """ Test that the initialization functions are returned. """ from chatterbot.comparisons import jaccard_similarity list(self.chatbot.search_algorithms.values())[0].compare_statements = jaccard_similarity functions = self.chatbot.get_initialization_functions() self.assertIn('download_nltk_wordnet', str(functions)) self.assertIn('download_nltk_stopwords', str(functions)) self.assertIn('download_nltk_averaged_perceptron_tagger', str(functions)) self.assertIsLength(functions, 3) def test_no_statements_known(self): """ If there is no statements in the database, then the user's input is the only thing that can be returned. """ statement_text = 'How are you?' response = self.chatbot.get_response(statement_text) results = list(self.chatbot.storage.filter(text=statement_text)) self.assertEqual(response.text, statement_text) self.assertEqual(response.confidence, 0) # Make sure that the input and output were saved self.assertIsLength(results, 2) self.assertEqual(results[0].text, statement_text) self.assertEqual(results[1].text, statement_text) def test_one_statement_known_no_response(self): """ Test the case where a single statement is known, but it is not in response to any other statement. """ self.chatbot.storage.create(text='Hello', in_response_to=None) response = self.chatbot.get_response('Hi') self.assertEqual(response.confidence, 0) self.assertEqual(response.text, 'Hello') def test_one_statement_one_response_known(self): """ Test the case that one response is known and there is a response entry for it in the database. """ self.chatbot.storage.create(text='Hello', in_response_to='Hi') response = self.chatbot.get_response('Hi') self.assertEqual(response.confidence, 0) self.assertEqual(response.text, 'Hello') def test_two_statements_one_response_known(self): """ Test the case that one response is known and there is a response entry for it in the database. """ self.chatbot.storage.create(text='Hi', in_response_to=None) self.chatbot.storage.create(text='Hello', in_response_to='Hi') response = self.chatbot.get_response('Hi') self.assertEqual(response.confidence, 1) self.assertEqual(response.text, 'Hello') def test_three_statements_two_responses_known(self): self.chatbot.storage.create(text='Hi', in_response_to=None) self.chatbot.storage.create(text='Hello', in_response_to='Hi') self.chatbot.storage.create(text='How are you?', in_response_to='Hello') first_response = self.chatbot.get_response('Hi') second_response = self.chatbot.get_response('How are you?') self.assertEqual(first_response.confidence, 1) self.assertEqual(first_response.text, 'Hello') self.assertEqual(second_response.confidence, 0) def test_four_statements_three_responses_known(self): self.chatbot.storage.create(text='Hi', in_response_to=None) self.chatbot.storage.create(text='Hello', in_response_to='Hi') self.chatbot.storage.create(text='How are you?', in_response_to='Hello') self.chatbot.storage.create(text='I am well.', in_response_to='How are you?') first_response = self.chatbot.get_response('Hi') second_response = self.chatbot.get_response('How are you?') self.assertEqual(first_response.confidence, 1) self.assertEqual(first_response.text, 'Hello') self.assertEqual(second_response.confidence, 1) self.assertEqual(second_response.text, 'I am well.') def test_second_response_unknown(self): self.chatbot.storage.create(text='Hi', in_response_to=None) self.chatbot.storage.create(text='Hello', in_response_to='Hi') first_response = self.chatbot.get_response( text='Hi', conversation='test' ) second_response = self.chatbot.get_response( text='How are you?', conversation='test' ) results = list(self.chatbot.storage.filter(text='How are you?')) self.assertEqual(first_response.confidence, 1) self.assertEqual(first_response.text, 'Hello') self.assertEqual(first_response.in_response_to, 'Hi') self.assertEqual(second_response.confidence, 0) self.assertEqual(second_response.in_response_to, 'How are you?') # Make sure that the second response was saved to the database self.assertIsLength(results, 1) self.assertEqual(results[0].in_response_to, 'Hi') def test_statement_added_to_conversation(self): """ An input statement should be added to the recent response list. """ statement = Statement(text='Wow!', conversation='test') response = self.chatbot.get_response(statement) self.assertEqual(statement.text, response.text) self.assertEqual(response.conversation, 'test') def test_get_response_additional_response_selection_parameters(self): self.chatbot.storage.create_many([ Statement('A', conversation='test_1'), Statement('B', conversation='test_1', in_response_to='A'), Statement('A', conversation='test_2'), Statement('C', conversation='test_2', in_response_to='A'), ]) statement = Statement(text='A', conversation='test_3') response = self.chatbot.get_response(statement, additional_response_selection_parameters={ 'conversation': 'test_2' }) self.assertEqual(response.text, 'C') self.assertEqual(response.conversation, 'test_3') def test_get_response_unicode(self): """ Test the case that a unicode string is passed in. """ response = self.chatbot.get_response(u'سلام') self.assertGreater(len(response.text), 0) def test_get_response_emoji(self): """ Test the case that the input string contains an emoji. """ response = self.chatbot.get_response(u'💩 ') self.assertGreater(len(response.text), 0) def test_get_response_non_whitespace(self): """ Test the case that a non-whitespace C1 control string is passed in. """ response = self.chatbot.get_response(u'€Ž‘’') self.assertGreater(len(response.text), 0) def test_get_response_two_byte_characters(self): """ Test the case that a string containing two-byte characters is passed in. """ response = self.chatbot.get_response(u'田中さんにあげて下さい') self.assertGreater(len(response.text), 0) def test_get_response_corrupted_text(self): """ Test the case that a string contains "corrupted" text. """ response = self.chatbot.get_response(u'Ṱ̺̺̕h̼͓̲̦̳̘̲e͇̣̰̦̬͎ ̢̼̻̱̘h͚͎͙̜̣̲ͅi̦̲̣̰̤v̻͍e̺̭̳̪̰-m̢iͅn̖̺̞̲̯̰d̵̼̟͙̩̼̘̳.̨̹͈̣') self.assertGreater(len(response.text), 0) def test_response_with_tags_added(self): """ If an input statement has tags added to it, that data should saved with the input statement. """ self.chatbot.get_response(Statement( text='Hello', in_response_to='Hi', tags=['test'] )) results = list(self.chatbot.storage.filter(text='Hello')) self.assertIsLength(results, 2) self.assertIn('test', results[0].get_tags()) self.assertEqual(results[1].get_tags(), []) def test_get_response_with_text_and_kwargs(self): self.chatbot.get_response('Hello', conversation='greetings') results = list(self.chatbot.storage.filter(text='Hello')) self.assertIsLength(results, 2) self.assertEqual(results[0].conversation, 'greetings') self.assertEqual(results[1].conversation, 'greetings') def test_get_response_missing_text(self): with self.assertRaises(self.chatbot.ChatBotException): self.chatbot.get_response() def test_get_response_missing_text_with_conversation(self): with self.assertRaises(self.chatbot.ChatBotException): self.chatbot.get_response(conversation='test') def test_generate_response(self): statement = Statement(text='Many insects adopt a tripedal gait for rapid yet stable walking.') response = self.chatbot.generate_response(statement) self.assertEqual(response.text, statement.text) self.assertEqual(response.confidence, 0) def test_learn_response(self): previous_response = Statement(text='Define Hemoglobin.') statement = Statement(text='Hemoglobin is an oxygen-transport metalloprotein.') self.chatbot.learn_response(statement, previous_response) results = list(self.chatbot.storage.filter(text=statement.text)) self.assertIsLength(results, 1) def test_get_response_does_not_add_new_statement(self): """ Test that a new statement is not learned if `read_only` is set to True. """ self.chatbot.read_only = True self.chatbot.get_response('Hi!') results = list(self.chatbot.storage.filter(text='Hi!')) self.assertIsLength(results, 0) def test_get_latest_response_from_zero_responses(self): response = self.chatbot.get_latest_response('invalid') self.assertIsNone(response) def test_get_latest_response_from_one_responses(self): self.chatbot.storage.create(text='A', conversation='test') self.chatbot.storage.create(text='B', conversation='test', in_response_to='A') response = self.chatbot.get_latest_response('test') self.assertEqual(response.text, 'A') def test_get_latest_response_from_two_responses(self): self.chatbot.storage.create(text='A', conversation='test') self.chatbot.storage.create(text='B', conversation='test', in_response_to='A') self.chatbot.storage.create(text='C', conversation='test', in_response_to='B') response = self.chatbot.get_latest_response('test') self.assertEqual(response.text, 'B') def test_get_latest_response_from_three_responses(self): self.chatbot.storage.create(text='A', conversation='test') self.chatbot.storage.create(text='B', conversation='test', in_response_to='A') self.chatbot.storage.create(text='C', conversation='test', in_response_to='B') self.chatbot.storage.create(text='D', conversation='test', in_response_to='C') response = self.chatbot.get_latest_response('test') self.assertEqual(response.text, 'C') def test_search_text_results_after_training(self): """ ChatterBot should return close matches to an input string when filtering using the search_text parameter. """ self.chatbot.storage.create_many([ Statement('Example A for search.'), Statement('Another example.'), Statement('Example B for search.'), Statement(text='Another statement.'), ]) results = list(self.chatbot.storage.filter( search_text=self.chatbot.storage.tagger.get_bigram_pair_string( 'Example A for search.' ) )) self.assertEqual('Example A for search.', results[0].text) self.assertEqual('Example B for search.', results[1].text) self.assertIsLength(results, 2) class TestAdapterA(LogicAdapter): def process(self, statement, additional_response_selection_parameters=None): response = Statement(text='Good morning.') response.confidence = 0.2 return response class TestAdapterB(LogicAdapter): def process(self, statement, additional_response_selection_parameters=None): response = Statement(text='Good morning.') response.confidence = 0.5 return response class TestAdapterC(LogicAdapter): def process(self, statement, additional_response_selection_parameters=None): response = Statement(text='Good night.') response.confidence = 0.7 return response class ChatBotLogicAdapterTestCase(ChatBotTestCase): def test_sub_adapter_agreement(self): """ In the case that multiple adapters agree on a given statement, this statement should be returned with the highest confidence available from these matching options. """ self.chatbot.logic_adapters = [ TestAdapterA(self.chatbot), TestAdapterB(self.chatbot), TestAdapterC(self.chatbot) ] statement = self.chatbot.generate_response(Statement(text='Howdy!')) self.assertEqual(statement.confidence, 0.5) self.assertEqual(statement.text, 'Good morning.') def test_chatbot_set_for_all_logic_adapters(self): for sub_adapter in self.chatbot.logic_adapters: self.assertEqual(sub_adapter.chatbot, self.chatbot) self.assertGreater( len(self.chatbot.logic_adapters), 0, msg='At least one logic adapter is expected for this test.' ) def test_response_persona_is_bot(self): """ The response returned from the chatbot should be set to the name of the chatbot. """ response = self.chatbot.get_response('Hey everyone!') self.assertEqual(response.persona, 'bot:Test Bot')
38.464115
123
0.668056
[ "BSD-3-Clause" ]
nadimpayak/ChatBot
tests/test_chatbot.py
16,176
Python
from django.contrib import admin from api.models import Citation class CitationAdmin(admin.ModelAdmin): list_display = ('id', 'citation_number', 'citation_date', 'first_name', 'last_name', 'date_of_birth', 'defendant_address', 'defendant_city', 'defendant_state', 'drivers_license_number', 'court_date', 'court_location', 'court_address') search_fields = ('id', 'first_name', 'last_name', 'court_location', 'drivers_license_number') admin.site.register(Citation, CitationAdmin) from api.models import Violation class ViolationAdmin(admin.ModelAdmin): list_display = ('id', 'citation_number', 'violation_number', 'violation_description', 'warrant_status', 'warrant_number', 'status', 'status_date', 'fine_amount', 'court_cost') list_filter = ('warrant_status',) search_fields = ('id', 'citation_number', 'violation_number', 'warrant_number') admin.site.register(Violation, ViolationAdmin)
60.666667
238
0.762637
[ "MIT" ]
emeth-/globalhack5-revamped
api/admin.py
910
Python
__I_MSG = { # ASMAxxxI 33 : lambda info, line: 'Storage alignment for {0} unfavorable'.format(line[info[1]:info[2]]), } __N_MSG = { # ASMAxxxN } __W_MSG = { # ASMAxxxW 45 : lambda info, line: 'Register or label not previously used - {0}'.format(line[info[1]:info[2]]), 140 : lambda info, line: 'END record missing', 163 : lambda info, line: 'Operand not properly enclosed in quotes', 165 : lambda info, line: 'Unexpected name field', 300 : lambda info, line: 'USING overridden by a prior active USING on statement number {0}'.format(info[1]), 301 : lambda info, line: 'Prior active USING on statement number {0} overridden by this USING'.format(info[1]), 302 : lambda info, line: 'USING specifies register 0 with a nonzero absolute or relocatable base address', 303 : lambda info, line: 'Multiple address resolutions may result from this USING and the USING on statement number {0}'.format(info[1]), } __E_MSG = { # ASMAxxxE 28 : lambda info, line: 'Invalid displacement', 29 : lambda info, line: 'Incorrect register specification - {0}'.format(line[info[1]:info[2]]), 30 : lambda info, line: 'Invalid literal usage - {0}'.format(line[info[1]:info[2]]), 32 : lambda info, line: 'Relocatable value or unresolved symbol found when absolute value required - {0}'.format(line[info[1]:info[2]]), 34 : lambda info, line: 'Operand {0} beyond active USING range'.format(line[info[1]:info[2]]), 41 : lambda info, line: 'Term expected; text is unclassifiable - {0}'.format(line[info[1]:info[2]]), 43 : lambda info, line: 'Previously defined symbol - {0}'.format(line[info[1]:info[2]]), 44 : lambda info, line: 'Undefined symbol - {0}'.format(line[info[1]:info[2]]), 57 : lambda info, line: 'Undefined operation code - {0}'.format(line[info[1]:info[2]]), 63 : lambda info, line: 'No ending apostrophe - {0}'.format(line[info[1]:info[2]]), 65 : lambda info, line: 'Unknown type - {0}'.format(line[info[1]:info[2]]), 74 : lambda info, line: 'Illegal syntax in expansion - {0}'.format(line[info[1]:info[2]]), 78 : lambda info, line: 'Operand 2 expansion complexly relocatable - {0}'.format(line[info[1]:info[2]]), 141 : lambda info, line: 'Bad character in operation code - {0}'.format(line[info[1]:info[2]]), 142 : lambda info, line: 'Operation code not complete on first record', 143 : lambda info, line: 'Bad character in name field - {0}'.format(line[info[1]:info[2]]), 145 : lambda info, line: 'Operator, right parenthesis, or end-of-expression expected - {0}'.format(line[info[1]:info[2]]), 146 : lambda info, line: 'Self-defining term too long or value too large - {0}'.format(line[info[1]:info[2]]), 150 : lambda info, line: 'Symbol has non-alphanumeric character or invalid delimiter - {0}'.format(line[info[1]:info[2]]), 305 : lambda info, line: 'Operand 1 does not refer to location within reference control section', 307 : lambda info, line: 'No active USING for operand {0}'.format(line[info[1]:info[2]]), 308 : lambda info, line: 'Repeated register {0}'.format(line[info[1]:info[2]]), } __S_MSG = { # ASMAxxxS 35 : lambda info, line: 'Invalid delimiter - {0}'.format(line[info[1]:info[2]]), 40 : lambda info, line: 'Missing operand', 173 : lambda info, line: 'Delimiter error, expected blank - {0}'.format(line[info[1]:info[2]]), 174 : lambda info, line: 'Delimiter error, expected blank or comma - {0}'.format(line[info[1]:info[2]]), 175 : lambda info, line: 'Delimiter error, expected comma - {0}'.format(line[info[1]:info[2]]), 178 : lambda info, line: 'Delimiter error, expected comma or right parenthesis - {0}'.format(line[info[1]:info[2]]), 179 : lambda info, line: 'Delimiter error, expected right parenthesis - {0}'.format(line[info[1]:info[2]]), 180 : lambda info, line: 'Operand must be absolute', } __MSG = { 'S' : __S_MSG, 'E' : __E_MSG, 'W' : __W_MSG, 'N' : __N_MSG, 'I' : __I_MSG, } def gen_msg(msg_type, info, line): if len(info) == 3: # standard info message return '** ASMA{0:0>3}{1} {2}\n'.format(info[0], msg_type, __MSG[msg_type][info[0]](info, line)) else: return '** AS{0}\n'.format(info) def search_msg_type(errno): for (k, v) in __MSG.iteritems(): if errno in v: return k return None
59.933333
141
0.63337
[ "BSD-3-Clause" ]
T-Tony-T/mainframe-env-simulator
zPE/base/pgm/asma90_err_code_rc.py
4,495
Python
import pytest from rate.users.forms import UserCreationForm from rate.users.tests.factories import UserFactory pytestmark = pytest.mark.django_db class TestUserCreationForm: def test_clean_username(self): # A user with proto_user params does not exist yet. proto_user = UserFactory.build() form = UserCreationForm( { "username": proto_user.username, "password1": proto_user._password, "password2": proto_user._password, } ) assert form.is_valid() assert form.clean_username() == proto_user.username # Creating a user. form.save() # The user with proto_user params already exists, # hence cannot be created. form = UserCreationForm( { "username": proto_user.username, "password1": proto_user._password, "password2": proto_user._password, } ) assert not form.is_valid() assert len(form.errors) == 1 assert "username" in form.errors
26.380952
59
0.590253
[ "MIT" ]
Jeongkiwon/rate_everything
rate/users/tests/test_forms.py
1,108
Python
"""Animations that try to transform Mobjects while keeping track of identical parts.""" __all__ = ["TransformMatchingShapes", "TransformMatchingTex"] from typing import TYPE_CHECKING, List, Optional import numpy as np from .._config import config from ..mobject.mobject import Group, Mobject from ..mobject.opengl_mobject import OpenGLGroup, OpenGLMobject from ..mobject.types.opengl_vectorized_mobject import OpenGLVGroup, OpenGLVMobject from ..mobject.types.vectorized_mobject import VGroup, VMobject from .composition import AnimationGroup from .fading import FadeIn, FadeOut from .transform import FadeTransformPieces, Transform if TYPE_CHECKING: from ..scene.scene import Scene class TransformMatchingAbstractBase(AnimationGroup): """Abstract base class for transformations that keep track of matching parts. Subclasses have to implement the two static methods :meth:`~.TransformMatchingAbstractBase.get_mobject_parts` and :meth:`~.TransformMatchingAbstractBase.get_mobject_key`. Basically, this transformation first maps all submobjects returned by the ``get_mobject_parts`` method to certain keys by applying the ``get_mobject_key`` method. Then, submobjects with matching keys are transformed into each other. Parameters ---------- mobject The starting :class:`~.Mobject`. target_mobject The target :class:`~.Mobject`. transform_mismatches Controls whether submobjects without a matching key are transformed into each other by using :class:`~.Transform`. Default: ``False``. fade_transform_mismatches Controls whether submobjects without a matching key are transformed into each other by using :class:`~.FadeTransform`. Default: ``False``. key_map Optional. A dictionary mapping keys belonging to some of the starting mobject's submobjects (i.e., the return values of the ``get_mobject_key`` method) to some keys belonging to the target mobject's submobjects that should be transformed although the keys don't match. kwargs All further keyword arguments are passed to the submobject transformations. Note ---- If neither ``transform_mismatches`` nor ``fade_transform_mismatches`` are set to ``True``, submobjects without matching keys in the starting mobject are faded out in the direction of the unmatched submobjects in the target mobject, and unmatched submobjects in the target mobject are faded in from the direction of the unmatched submobjects in the start mobject. """ def __init__( self, mobject: "Mobject", target_mobject: "Mobject", transform_mismatches: bool = False, fade_transform_mismatches: bool = False, key_map: Optional[dict] = None, **kwargs ): assert type(mobject) is type(target_mobject) if isinstance(mobject, OpenGLVMobject): group_type = OpenGLVGroup elif isinstance(mobject, OpenGLMobject): group_type = OpenGLGroup elif isinstance(mobject, VMobject): group_type = VGroup else: group_type = Group source_map = self.get_shape_map(mobject) target_map = self.get_shape_map(target_mobject) if key_map is None: key_map = {} # Create two mobjects whose submobjects all match each other # according to whatever keys are used for source_map and # target_map transform_source = group_type() transform_target = group_type() kwargs["final_alpha_value"] = 0 for key in set(source_map).intersection(target_map): transform_source.add(source_map[key]) transform_target.add(target_map[key]) anims = [Transform(transform_source, transform_target, **kwargs)] # User can manually specify when one part should transform # into another despite not matching by using key_map key_mapped_source = group_type() key_mapped_target = group_type() for key1, key2 in key_map.items(): if key1 in source_map and key2 in target_map: key_mapped_source.add(source_map[key1]) key_mapped_target.add(target_map[key2]) source_map.pop(key1, None) target_map.pop(key2, None) if len(key_mapped_source) > 0: anims.append( FadeTransformPieces(key_mapped_source, key_mapped_target, **kwargs) ) fade_source = group_type() fade_target = group_type() for key in set(source_map).difference(target_map): fade_source.add(source_map[key]) for key in set(target_map).difference(source_map): fade_target.add(target_map[key]) if transform_mismatches: if "replace_mobject_with_target_in_scene" not in kwargs: kwargs["replace_mobject_with_target_in_scene"] = True anims.append(Transform(fade_source, fade_target, **kwargs)) elif fade_transform_mismatches: anims.append(FadeTransformPieces(fade_source, fade_target, **kwargs)) else: anims.append(FadeOut(fade_source, target_position=fade_target, **kwargs)) anims.append( FadeIn(fade_target.copy(), target_position=fade_target, **kwargs) ) super().__init__(*anims) self.to_remove = mobject self.to_add = target_mobject def get_shape_map(self, mobject: "Mobject") -> dict: shape_map = {} for sm in self.get_mobject_parts(mobject): key = self.get_mobject_key(sm) if key not in shape_map: if config["renderer"] == "opengl": shape_map[key] = OpenGLVGroup() else: shape_map[key] = VGroup() shape_map[key].add(sm) return shape_map def clean_up_from_scene(self, scene: "Scene") -> None: for anim in self.animations: anim.interpolate(0) scene.remove(self.mobject) scene.remove(self.to_remove) scene.add(self.to_add) @staticmethod def get_mobject_parts(mobject: "Mobject"): raise NotImplementedError("To be implemented in subclass.") @staticmethod def get_mobject_key(mobject: "Mobject"): raise NotImplementedError("To be implemented in subclass.") class TransformMatchingShapes(TransformMatchingAbstractBase): """An animation trying to transform groups by matching the shape of their submobjects. Two submobjects match if the hash of their point coordinates after normalization (i.e., after translation to the origin, fixing the submobject height at 1 unit, and rounding the coordinates to three decimal places) matches. See also -------- :class:`~.TransformMatchingAbstractBase` Examples -------- .. manim:: Anagram class Anagram(Scene): def construct(self): src = Text("the morse code") tar = Text("here come dots") self.play(Write(src)) self.wait(0.5) self.play(TransformMatchingShapes(src, tar, path_arc=PI/2)) self.wait(0.5) """ def __init__( self, mobject: "Mobject", target_mobject: "Mobject", transform_mismatches: bool = False, fade_transform_mismatches: bool = False, key_map: Optional[dict] = None, **kwargs ): super().__init__( mobject, target_mobject, transform_mismatches=transform_mismatches, fade_transform_mismatches=fade_transform_mismatches, key_map=key_map, **kwargs ) @staticmethod def get_mobject_parts(mobject: "Mobject") -> List["Mobject"]: return mobject.family_members_with_points() @staticmethod def get_mobject_key(mobject: "Mobject") -> int: mobject.save_state() mobject.center() mobject.set_height(1) result = hash(np.round(mobject.points, 3).tobytes()) mobject.restore() return result class TransformMatchingTex(TransformMatchingAbstractBase): """A transformation trying to transform rendered LaTeX strings. Two submobjects match if their ``tex_string`` matches. See also -------- :class:`~.TransformMatchingAbstractBase` Examples -------- .. manim:: MatchingEquationParts class MatchingEquationParts(Scene): def construct(self): eq1 = MathTex("{{a^2}} + {{b^2}} = {{c^2}}") eq2 = MathTex("{{a^2}} = {{c^2}} - {{b^2}}") self.add(eq1) self.wait(0.5) self.play(TransformMatchingTex(eq1, eq2)) self.wait(0.5) """ def __init__( self, mobject: "Mobject", target_mobject: "Mobject", transform_mismatches: bool = False, fade_transform_mismatches: bool = False, key_map: Optional[dict] = None, **kwargs ): assert hasattr(mobject, "tex_string") assert hasattr(target_mobject, "tex_string") super().__init__( mobject, target_mobject, transform_mismatches=transform_mismatches, fade_transform_mismatches=fade_transform_mismatches, key_map=key_map, **kwargs ) @staticmethod def get_mobject_parts(mobject: "Mobject") -> List["Mobject"]: return mobject.submobjects @staticmethod def get_mobject_key(mobject: "Mobject") -> str: return mobject.tex_string
34.521277
87
0.642732
[ "MIT" ]
Pragyaan-6988/ManimCE
manim/animation/transform_matching_parts.py
9,735
Python
from pygin.components.animation import Animation from pygin.key_frame import KeyFrame class ParticleFadeAnimation(Animation): def __init__(self, game_obj, duration): key_frame_list = list() key_frame_list.append(KeyFrame(0.0, alpha=255, interpolation="in_cubic")) key_frame_list.append(KeyFrame(duration, alpha=0)) super().__init__(game_obj, key_frame_list, should_loop=False, unscaled=True)
35.916667
84
0.74942
[ "MIT" ]
CarlosMatheus/Engine
pygin/example_games/Balance/animations/particle_fade_animation.py
431
Python
"""Tests for distutils. The tests for distutils are defined in the distutils.tests package; the test_suite() function there returns a test suite that's ready to be run. """ import distutils.tests import test.support def load_tests(*_): # used by unittest return distutils.tests.test_suite() def tearDownModule(): test.support.reap_children() if __name__ == "__main__": unittest.main()
17.782609
68
0.731051
[ "Apache-2.0" ]
LawrenceZ1A/MultipurposeProject
pypy3.9-v7.3.9-win64/Lib/test/test_distutils.py
409
Python
import unittest from pyats.topology import loader from genie.libs.sdk.apis.iosxe.interface.get import get_interface_mac_address class TestGetInterfaceMacAddress(unittest.TestCase): @classmethod def setUpClass(self): testbed = """ devices: R1_xe: connections: defaults: class: unicon.Unicon a: command: mock_device_cli --os iosxe --mock_data_dir mock_data --state connect protocol: unknown os: iosxe platform: iosxe type: CSR1000v """ self.testbed = loader.load(testbed) self.device = self.testbed.devices['R1_xe'] self.device.connect() def test_get_interface_mac_address(self): result = get_interface_mac_address(self.device, 'GigabitEthernet1') expected_output = '5e01.4000.0000' self.assertEqual(result, expected_output)
30.483871
93
0.621164
[ "Apache-2.0" ]
CiscoTestAutomation/genielibs
pkgs/sdk-pkg/src/genie/libs/sdk/apis/tests/iosxe/interface/get/get_interface_mac_address/test_api_get_interface_mac_address.py
945
Python
# Copyright 2018 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from enum import IntEnum from abc import ABC, abstractmethod from .mycroft_skill import MycroftSkill class CQSMatchLevel(IntEnum): EXACT = 1 # Skill could find a specific answer for the question CATEGORY = 2 # Skill could find an answer from a category in the query GENERAL = 3 # The query could be processed as a general quer # Copy of CQSMatchLevel to use if the skill returns visual media CQSVisualMatchLevel = IntEnum('CQSVisualMatchLevel', [e.name for e in CQSMatchLevel]) def is_CQSVisualMatchLevel(match_level): return isinstance(match_level, type(CQSVisualMatchLevel.EXACT)) VISUAL_DEVICES = ['mycroft_mark_2'] def handles_visuals(platform): return platform in VISUAL_DEVICES class CommonQuerySkill(MycroftSkill, ABC): """Question answering skills should be based on this class. The skill author needs to implement `CQS_match_query_phrase` returning an answer and can optionally implement `CQS_action` to perform additional actions if the skill's answer is selected. This class works in conjunction with skill-query which collects answers from several skills presenting the best one available. """ def __init__(self, name=None, bus=None): super().__init__(name, bus) def bind(self, bus): """Overrides the default bind method of MycroftSkill. This registers messagebus handlers for the skill during startup but is nothing the skill author needs to consider. """ if bus: super().bind(bus) self.add_event('question:query', self.__handle_question_query) self.add_event('question:action', self.__handle_query_action) def __handle_question_query(self, message): search_phrase = message.data["phrase"] # First, notify the requestor that we are attempting to handle # (this extends a timeout while this skill looks for a match) self.bus.emit(message.response({"phrase": search_phrase, "skill_id": self.skill_id, "searching": True})) # Now invoke the CQS handler to let the skill perform its search result = self.CQS_match_query_phrase(search_phrase) if result: match = result[0] level = result[1] answer = result[2] callback = result[3] if len(result) > 3 else None confidence = self.__calc_confidence(match, search_phrase, level) self.bus.emit(message.response({"phrase": search_phrase, "skill_id": self.skill_id, "answer": answer, "callback_data": callback, "conf": confidence})) else: # Signal we are done (can't handle it) self.bus.emit(message.response({"phrase": search_phrase, "skill_id": self.skill_id, "searching": False})) def __calc_confidence(self, match, phrase, level): # Assume the more of the words that get consumed, the better the match consumed_pct = len(match.split()) / len(phrase.split()) if consumed_pct > 1.0: consumed_pct = 1.0 # Add bonus if match has visuals and the device supports them. platform = self.config_core.get('enclosure', {}).get('platform') if is_CQSVisualMatchLevel(level) and handles_visuals(platform): bonus = 0.1 else: bonus = 0 if int(level) == int(CQSMatchLevel.EXACT): return 0.9 + (consumed_pct / 10) + bonus elif int(level) == int(CQSMatchLevel.CATEGORY): return 0.6 + (consumed_pct / 10) + bonus elif int(level) == int(CQSMatchLevel.GENERAL): return 0.5 + (consumed_pct / 10) + bonus else: return 0.0 # should never happen def __handle_query_action(self, message): """Message handler for question:action. Extracts phrase and data from message forward this to the skills CQS_action method. """ if message.data["skill_id"] != self.skill_id: # Not for this skill! return phrase = message.data["phrase"] data = message.data.get("callback_data") # Invoke derived class to provide playback data self.CQS_action(phrase, data) @abstractmethod def CQS_match_query_phrase(self, phrase): """Analyze phrase to see if it is a play-able phrase with this skill. Needs to be implemented by the skill. Arguments: phrase (str): User phrase, "What is an aardwark" Returns: (match, CQSMatchLevel[, callback_data]) or None: Tuple containing a string with the appropriate matching phrase, the PlayMatch type, and optionally data to return in the callback if the match is selected. """ # Derived classes must implement this, e.g. return None def CQS_action(self, phrase, data): """Take additional action IF the skill is selected. The speech is handled by the common query but if the chosen skill wants to display media, set a context or prepare for sending information info over e-mail this can be implemented here. Args: phrase (str): User phrase uttered after "Play", e.g. "some music" data (dict): Callback data specified in match_query_phrase() """ # Derived classes may implement this if they use additional media # or wish to set context after being called. pass
39.288344
78
0.626327
[ "Apache-2.0" ]
AIIX/mycroft-core
mycroft/skills/common_query_skill.py
6,404
Python
import numpy as np from .. import ArrayStringReader def test_arraystringreader(): """here is my test code https://docs.pytest.org/en/stable/getting-started.html#create-your-first-test """ size = 8 sample_array = np.random.rand(size).astype('float32') text = ','.join([str(x) for x in sample_array]) reader = ArrayStringReader() crafted_doc = reader.craft(text, 0) assert crafted_doc['blob'].shape[0] == size np.testing.assert_array_equal(crafted_doc['blob'], sample_array)
25.95
81
0.687861
[ "Apache-2.0" ]
Gracegrx/jina-hub
crafters/numeric/ArrayStringReader/tests/test_arraystringreader.py
519
Python
from __future__ import unicode_literals import json import collections import string from django.http import JsonResponse, HttpResponseRedirect, HttpResponseNotFound from django.http import Http404 from django.shortcuts import render import threading import json from django.views.decorators.csrf import csrf_exempt from .forms import NameForm, RegionForm, PlaceForm, GetTweetsForm from .app_logic import handle_region_form, handle_place_form, get_user, \ init_tweet_accumulation_tweet_list, handle_search_form,\ generate_tweet_sendaway, generate_user_sendaway, word_trends_merge_jsons, replace_string_character, contains_whitespace,\ filter_strings, phrase_list_to_word_list, get_all_twitter_users_ids, slider_val_transform, convert_to_iso, \ get_tweet_list, user_ext_to_json, single_word_obj, generate_days_list, parse_parameters, generate_users_tweets import jsonpickle from .Analytics import QueriesManager from .classes import get_from_db, UserExtension, twitter_users_database_name, TweetExtension def index(request): if request.method == 'POST': form_user = NameForm(request.POST) if form_user.is_valid(): name = form_user.cleaned_data['your_name'] name = name.replace(" ", "_") return HttpResponseRedirect('/tweets/' + name) # if a GET (or any other method) we'll create a blank form else: form_user = NameForm() return render(request, 'index.html', {'form': form_user}) def dashboard(request, name): user = get_user(name) if request.method == 'POST': form_region = RegionForm(request.POST or None) regions = handle_region_form(form_region, user) place_form = PlaceForm(request.POST or None) print(place_form) handle_place_form(place_form, user) search_form = GetTweetsForm(request.POST or None) region, place = handle_search_form(search_form) if region != "": user.remove_location(region, place) user.save_me_to_db() user = get_user(name) regions = collections.OrderedDict(user.get_regions()) return render(request, 'dashboard.html', {'name': name, 'regions': regions, 'region_form': RegionForm(), 'place_form': PlaceForm(), 'tweets_form': GetTweetsForm()}) else: user = get_user(name) regions = collections.OrderedDict(user.get_regions()) return render(request, 'dashboard.html', {'name': name, 'regions': regions, 'region_form': RegionForm(), 'place_form': PlaceForm(), 'tweets_form': GetTweetsForm()}) def help_page(request, name): return render(request, 'help.html', {'name': name}) @csrf_exempt def get_regions_places_list(request): if request.method == 'POST': user_name = request.POST.get('user_name', None) user = get_user(user_name) region_place_dict = user.get_region_place_dict() return JsonResponse(region_place_dict, safe=False) else: empty = {} return JsonResponse(empty) @csrf_exempt def get_search_words(request): if request.method == 'POST': user_name = request.POST.get('user_name', None) user = get_user(user_name) word_to_add = request.POST.get('to_add', None) if word_to_add != "": word_to_add = word_to_add.replace('"', "") user.add_search_word(word_to_add) words_to_remove = jsonpickle.decode(request.POST.get('to_remove', None)) print(words_to_remove) if words_to_remove != "": words_to_remove = replace_string_character(words_to_remove) print(words_to_remove) user.remove_search_word(words_to_remove) print(user_name) print(word_to_add) print(user.all_search_words()) return JsonResponse(user.all_search_words(), safe=False) else: empty = {} return JsonResponse(empty) @csrf_exempt def accumulate_tweets(request): if request.method == 'POST': name, locations, start_date, end_date, word_list, logic, exact = parse_parameters(request) user = get_user(name) for loc in locations: init_tweet_accumulation_tweet_list(user, loc['region'], loc['place'], word_list) empty = {} return JsonResponse(empty) @csrf_exempt def get_query_links(request): if request.method == 'POST': name = request.POST.get('user_name', None) locations = jsonpickle.decode(request.POST.get('locations_list', None)) print(locations) user = get_user(name) results = [] for loc in locations: results.append(user.get_region(loc['region']).get_place_by_name(loc['place']).get_query_string()) print(results) return JsonResponse(results, safe=False) else: empty = {} return JsonResponse(empty) def show_tweets_list(request, name): user = get_user(name) print("in show_tweets_list") if request.method == 'POST': search_form = GetTweetsForm(request.POST) region, place = handle_search_form(search_form) #quary = init_tweet_accumulation_tweet_list(user, region, place) quary = "I am lish lash" region = user.get_region(region) place = region.get_place_by_name(place) return render(request, 'tweets.html', { 'quary': quary, 'region': region, 'place': place, 'user': name}) elif request.method == 'GET': quary = "I am lish lash" region = "Lash" place = "Lish" return render(request, 'tweets.html', { 'quary': quary, 'region': region, 'place': place, 'user': name}) @csrf_exempt def popular_users_get(request): print("popular_users_get") users_list = [] if request.method == 'POST': twitter_users, tweets = generate_users_tweets(request, tasdocs=True, uasdocs=True) if isinstance(twitter_users, Exception): return JsonResponse(str(twitter_users), safe=False, status=500) elif len(twitter_users) == 0: return JsonResponse("Error: No Tweets in location / date / search phrase (if included)", safe=False, status=500) slider_valus = slider_val_transform(jsonpickle.decode(request.POST.get('sliders_data', None))) print(len(twitter_users)) print(len(tweets)) # ["followers_slider", "retweet_slider", "favorites_slider", "tweets_slider"] # ["followers, statusses, favorites (likes), retweets] queriesManager = QueriesManager() params = ['Opinion_Leaders', [str(slider_valus[0][1])], [str(slider_valus[0][0])], [str(slider_valus[3][1])], [str(slider_valus[3][0])], [str(slider_valus[2][1])], [str(slider_valus[2][0])], [str(slider_valus[1][1])], [str(slider_valus[1][0])]] print(params) print(twitter_users[0].keys()) df = queriesManager.call_querie(params, tweets, twitter_users) print(df) if df.empty: return JsonResponse("Error: No opinion leaders found", safe=False) idlist = df['id'].tolist() print(len(idlist)) users_list = get_from_db(idlist, twitter_users_database_name, UserExtension) print(len(users_list)) user_ext_list = user_ext_to_json(users_list) return JsonResponse(user_ext_list, safe=False) @csrf_exempt def tweet_list_place(request): print("tweet_list_place") if request.method == 'POST': name, locations, start_date, end_date, word_list, logic, exact = parse_parameters(request) print("word list is: " + str(word_list)) print("logic is: " + logic) if start_date is not "" and end_date is not "": days_list = generate_days_list(start_date, end_date) else: days_list = None print(days_list) total_tweets = [] for loc in locations: place = get_user(name).get_region(loc['region']).get_place_by_name(loc['place']) mylist = place.get_tweets_directly(name, loc['region'], days_list, word_list, logic=logic, exact=exact) if isinstance(mylist, Exception): return JsonResponse(str(mylist), safe=False, status=500) #print(mylist) json_list = [] for l in mylist: result = generate_tweet_sendaway(l.tweet) """ this is the paid data from ibm watson result.append(l.category) result.append(l.concept) result.append(l.entities) result.append(l.entities_sentiment) result.append(l.keywords) result.append(l.keywords_sentiment) """ json_list.append(result) total_tweets = total_tweets + json_list #print(total_tweets) if len(total_tweets) == 0: return JsonResponse("Error: No Tweets in location / date / search phrase (if included)", safe=False, status=500) return JsonResponse(total_tweets, safe=False) else: empty = {} return JsonResponse(empty) @csrf_exempt def show_users_place(request): print("show_users_place") if request.method == 'POST': twitter_users, _ = generate_users_tweets(request) if isinstance(twitter_users, Exception): return JsonResponse(str(twitter_users), safe=False, status=500) elif len(twitter_users) == 0: return JsonResponse("Error: No Tweets in location and date", safe=False, status=500) return JsonResponse(user_ext_to_json(twitter_users), safe=False) else: empty = {} return JsonResponse(empty) @csrf_exempt def word_trends_get(request): print("word_trends_get") total_result = [] if request.method == 'POST': queriesManager = QueriesManager() name, locations, start_date, end_date, word_list, logic, exact = parse_parameters(request) days_list = generate_days_list(start_date, end_date) total_tweets = get_tweet_list(locations, get_user(name), days_list, word_list=word_list, asdocs=True, exact=exact) if isinstance(total_tweets, Exception): return JsonResponse(str(total_tweets), safe=False, status=500) elif len(total_tweets) == 0: return JsonResponse("Error: No Tweets in location and date", safe=False, status=500) word_list, pharses_list = filter_strings(word_list) if not exact: for word in word_list: pharses_list.append(word) word_list = [] params = ["Word_trend", word_list] print(params) print(len(total_tweets)) df = queriesManager.call_querie(params, total_tweets, []) phrase_dfs = [] for phrase in pharses_list: params = ['Phrase_trend', phrase] print(params) phrase_dfs.append({"df": queriesManager.call_querie(params, total_tweets, []), "phrase": phrase}) print(phrase_dfs) for word in word_list: total_result.append(single_word_obj(word, 'word', df, days_list)) for dic in phrase_dfs: total_result.append(single_word_obj(dic['phrase'], 'phrase', dic["df"], days_list)) print(total_result) return JsonResponse(total_result, safe=False) @csrf_exempt def top_words_per_date_get(request): print("top_words_per_date_get") words_list = [] counter_list = [] days_list = [] if request.method == 'POST': queriesManager = QueriesManager() name, locations, start_date, end_date, words_list, logic, exact = parse_parameters(request) days_list = generate_days_list(start_date, end_date) dates_counter = dict.fromkeys(days_list) print(days_list) total_tweets = get_tweet_list(locations, get_user(name), days_list, None, asdocs=True) if isinstance(total_tweets, Exception): return JsonResponse(str(total_tweets), safe=False, status=500) elif len(total_tweets) == 0: return JsonResponse("Error: No Tweets in location and date", safe=False, status=500) for k, _ in dates_counter.items(): dates_counter[k] = {'word': "", 'count': 0} params = ["Popular_word_per_date"] print(params) print(len(total_tweets)) df = queriesManager.call_querie(params, total_tweets, []) print(df) words_list = ["No Tweets"] * len(days_list) counter_list = [0] * len(days_list) for i, day in enumerate(days_list): print(day) col = df.loc[df['date'] == day] for index, row in col.iterrows(): words_list[i] = row['popular_word'] counter_list[i] = row['counter'] print(days_list) print(words_list) print(counter_list) return JsonResponse({'dates': days_list, 'words': words_list, 'counter': counter_list}, safe=False) @csrf_exempt def popularity_of_words_get(request): print("popularity_of_words_get") df = "" if request.method == 'POST': queriesManager = QueriesManager() name, locations, start_date, end_date, word_list, logic, exact = parse_parameters(request) word_list, pharase_list = filter_strings(word_list) word_list = word_list + phrase_list_to_word_list(pharase_list) days_list = generate_days_list(start_date, end_date) total_tweets = get_tweet_list(locations, get_user(name), days_list, word_list=word_list, asdocs=True, exact=exact) if isinstance(total_tweets, Exception): return JsonResponse(str(total_tweets), safe=False, status=500) elif len(total_tweets) == 0: return JsonResponse("Error: No Tweets in location and date", safe=False, status=500) params = ["Popularity_of_word_bank_per_place", word_list] print(params) print(len(total_tweets)) df = queriesManager.call_querie(params, total_tweets, []) if df.empty: return JsonResponse("Error: No appearances of search phrases in tweets", safe=False) rows = df.shape[0] df = df.to_json() df = df[:-1] df = df + ', "rows": ' + str(rows) df = df + ', "word_list": ' + str(word_list) + '}' print(df) df = df.replace("'", '"') print(df) return JsonResponse(df, safe=False) @csrf_exempt def most_popular_word_get(request): print("most_popular_word_get") place_list = [] word_list = [] counter_list = [] if request.method == 'POST': queriesManager = QueriesManager() name, locations, start_date, end_date, word_list, logic, exact = parse_parameters(request) days_list = generate_days_list(start_date, end_date) total_tweets = get_tweet_list(locations, get_user(name), days_list, None, asdocs=True) if isinstance(total_tweets, Exception): return JsonResponse(str(total_tweets), safe=False, status=500) elif len(total_tweets) == 0: return JsonResponse("Error: No Tweets in location and date", safe=False, status=500) params = ["Popular_word_per_place"] df = queriesManager.call_querie(params, total_tweets, []) print(df) for i, row in df.iterrows(): place_list.append(row['place_name']) word_list.append(row['popular_word']) counter_list.append(row['counter']) return JsonResponse({'places': place_list, 'words': word_list, 'counters': counter_list}, safe=False) @csrf_exempt def first_time_get(request): print("first_time_get") df_list = [] if request.method == 'POST': queriesManager = QueriesManager() name, locations, start_date, end_date, word_list, logic, exact = parse_parameters(request) max_results = request.POST.get('max_results', None) total_users, total_tweets = generate_users_tweets(request, use_words=True, tasdocs=True, uasdocs=True) if isinstance(total_users, Exception): return JsonResponse(str(total_users), safe=False, status=500) elif len(total_tweets) == 0: return JsonResponse("Error: No Tweets in location and date", safe=False, status=500) print(len(total_tweets)) print(len(total_users)) for word in word_list: if exact: params = ["First_Time", [" " + word + " "], [max_results]] else: params = ["First_Time", [word], [max_results]] print(params) df = queriesManager.call_querie(params, total_tweets, total_users) print(df) if df.empty: continue row_data = [] # [id, text, user_id, screen_name, full_date, time_rnk] for index, row in df.iterrows(): row_data.append([row["id"], row["text"], row["screen_name"], convert_to_iso(row["full_date"]), row["time_rnk"]]) df_list.append({"word": word, "len": df.shape[0], "row_data": row_data}) if len(df_list) == 0: return JsonResponse("Error: No Tweets in location and date contain search phrase", safe=False, status=500) return JsonResponse(df_list, safe=False) @csrf_exempt def most_retweeted_get(request): print("most_retweeted_get") row_data = [] if request.method == 'POST': queriesManager = QueriesManager() name, locations, start_date, end_date, word_list, logic, exact = parse_parameters(request) max_results = request.POST.get('max_results', None) total_users, total_tweets = generate_users_tweets(request, use_words=True, tasdocs=True, uasdocs=True) if isinstance(total_users, Exception): return JsonResponse(str(total_users), safe=False, status=500) elif len(total_tweets) == 0: return JsonResponse("Error: No Tweets in location and date", safe=False, status=500) print(len(total_tweets)) print(len(total_users)) for word in word_list: if exact: params = ["Most_Retweeted", [" " + word + " "], [max_results]] else: params = ["Most_Retweeted", [word], [max_results]] print(params) df = queriesManager.call_querie(params, total_tweets, total_users) print(df) if df.empty: continue # [phrase, id, text, user_id, screen_name, full_date, retweet_count, retweet_rnk for index, row in df.iterrows(): row_data.append([row["id"], row["text"], row["screen_name"], convert_to_iso(row["full_date"]), row["retweet_count"], row["retweet_rnk"], row["phrase"]]) print(row_data) if len(row_data) == 0: return JsonResponse("Error: No Tweets in location and date contain search phrase", safe=False, status=500) return JsonResponse(row_data, safe=False) def health(request): state = {"status": "UP"} return JsonResponse(state) def handler404(request): return render(request, '404.html', status=404) def handler500(request): return render(request, '500.html', status=500)
42.580931
145
0.64221
[ "Apache-2.0" ]
alonlevko/seminarmiddleeast
app/views.py
19,204
Python
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from openvino.tools.mo.front.extractor import FrontExtractorOp from openvino.tools.mo.ops.lrn import AttributedLRN class LRNExtractor(FrontExtractorOp): """ TF and IE(CAFFE) parameters in LRN differs in several places : region (IE) : in TF there is no such parameter, they just use last dimension (feature dimension in case of NHWC) local-size (IE) : it's the size of 1D vector in Caffe. In TF they have 'depth_radius' that eq '(local-size * 2) + 1' alpha (IE) : in Caffe 'alpha' divides on local-size, so we should multiply alpha on local-size Caffe ref : http://caffe.berkeleyvision.org/tutorial/layers/lrn.html TF ref : https://www.tensorflow.org/api_docs/python/tf/nn/local_response_normalization """ op = 'LRN' enabled = True @classmethod def extract(cls, node): pb = node.pb AttributedLRN.update_node_stat(node, { 'alpha': pb.attr['alpha'].f * (2. * pb.attr['depth_radius'].i + 1.), 'beta': pb.attr['beta'].f, 'bias': pb.attr['bias'].f, 'local_size': (2 * pb.attr['depth_radius'].i + 1), }) return cls.enabled
39.96875
124
0.630962
[ "Apache-2.0" ]
IndiraSalyahova/openvino
tools/mo/openvino/tools/mo/front/tf/lrn_ext.py
1,279
Python
import simpy import logging """ Recursive GraphQL schema for JSON StructureItem - passed as Python dictionary type StructureItem { id: ID! type: StructureType # optional annotation for a Branch annotation: String # reference UUID / Name / Num for: Function, Exit / ExitCondition (Exit), Replicate (DomainSet) types referenceID: String referenceName: String referenceNum: String structure: [StructureItem] } """ class StructureItem: """ The base class for all call StructureItems (Branch, Parallel, Select, Loop, Function, etc.) """ def __init__(self, env: simpy.Environment, logger: logging.Logger, construct_id: str, systemModel: dict, structureItem: dict): from .branch import Branch from .function import Function #from .exit import Exit, ExitCondition from .loop import Loop # , LoopExit from .parallel import Parallel #from .replicate import Replicate from .select import Select import simapp self.env = env self.logger = logger self.construct_id = construct_id self.systemModel = systemModel self.structureItem = structureItem self.structureItems = list() self.structureType = "" # overidden by subclass self.name = "" # overidden by subclass for num, struct in enumerate(self.structureItem['structure'], start=1): next_construct_id = self.construct_id + "." + str(num) if struct['type'] == "Branch": self.structureItems.append(Branch(self.env, self.logger, next_construct_id, self.systemModel, struct)) elif struct['type'] == "Function": try: # Check for override function override_class = getattr(simapp, struct['referenceName'].capitalize()) self.structureItems.append(override_class(self.env, self.logger, next_construct_id, self.systemModel, struct)) except AttributeError: # No function override exists self.structureItems.append(Function(self.env, self.logger, next_construct_id, self.systemModel, struct)) elif struct['type'] == "Loop": self.structureItems.append(Loop(self.env, self.logger, next_construct_id, self.systemModel, struct)) elif struct['type'] == "Parallel": self.structureItems.append(Parallel(self.env, self.logger, next_construct_id, self.systemModel, struct)) elif struct['type'] == "Select": self.structureItems.append(Select(self.env, self.logger, next_construct_id, self.systemModel, struct)) def __str__(self): """ Recursively print CallStructure """ # indent by construct_id depth (number of dots) stmt = ("\n" + "." * self.construct_id.count(".") + "Struct: %s: %s" % (self.construct_id, self.structureType)) for struct in self.structureItems: stmt += struct.__str__() return (stmt) def log_start(self): self.logger.info('SIM Time: %08.2f : %-20s:Start:%10s:%-s' % (self.env.now, self.construct_id, self.structureType, self.name)) def log_end(self): self.logger.info('SIM Time: %08.2f : %-20s: End:%10s:%-s' % (self.env.now, self.construct_id, self.structureType, self.name))
39.925532
103
0.572342
[ "BSD-3-Clause" ]
tsherburne/ma-simpy
simmbse/structure_item.py
3,753
Python
global_var = 'spam' def enclosing(p1, p2): x = 42 local(p1, x, 'foo') def local(p1, x, p): def nested(): print(p, x) print(p1, p)
11.357143
23
0.503145
[ "Apache-2.0" ]
06needhamt/intellij-community
python/testData/refactoring/makeFunctionTopLevel/localFunctionSimple.after.py
159
Python
import asyncio import contextlib import email.utils import functools import logging import os import time import unittest DATE = email.utils.formatdate(usegmt=True) class GeneratorTestCase(unittest.TestCase): def assertGeneratorRunning(self, gen): """ Check that a generator-based coroutine hasn't completed yet. """ next(gen) def assertGeneratorReturns(self, gen): """ Check that a generator-based coroutine completes and return its value. """ with self.assertRaises(StopIteration) as raised: next(gen) return raised.exception.value class AsyncioTestCase(unittest.TestCase): """ Base class for tests that sets up an isolated event loop for each test. """ def __init_subclass__(cls, **kwargs): """ Convert test coroutines to test functions. This supports asychronous tests transparently. """ super().__init_subclass__(**kwargs) for name in unittest.defaultTestLoader.getTestCaseNames(cls): test = getattr(cls, name) if asyncio.iscoroutinefunction(test): setattr(cls, name, cls.convert_async_to_sync(test)) @staticmethod def convert_async_to_sync(test): """ Convert a test coroutine to a test function. """ @functools.wraps(test) def test_func(self, *args, **kwargs): return self.loop.run_until_complete(test(self, *args, **kwargs)) return test_func def setUp(self): super().setUp() self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) def tearDown(self): self.loop.close() super().tearDown() def run_loop_once(self): # Process callbacks scheduled with call_soon by appending a callback # to stop the event loop then running it until it hits that callback. self.loop.call_soon(self.loop.stop) self.loop.run_forever() @contextlib.contextmanager def assertNoLogs(self, logger="websockets", level=logging.ERROR): """ No message is logged on the given logger with at least the given level. """ with self.assertLogs(logger, level) as logs: # We want to test that no log message is emitted # but assertLogs expects at least one log message. logging.getLogger(logger).log(level, "dummy") yield level_name = logging.getLevelName(level) self.assertEqual(logs.output, [f"{level_name}:{logger}:dummy"]) def assertDeprecationWarnings(self, recorded_warnings, expected_warnings): """ Check recorded deprecation warnings match a list of expected messages. """ self.assertEqual(len(recorded_warnings), len(expected_warnings)) for recorded, expected in zip(recorded_warnings, expected_warnings): actual = recorded.message self.assertEqual(str(actual), expected) self.assertEqual(type(actual), DeprecationWarning) # Unit for timeouts. May be increased on slow machines by setting the # WEBSOCKETS_TESTS_TIMEOUT_FACTOR environment variable. MS = 0.001 * int(os.environ.get("WEBSOCKETS_TESTS_TIMEOUT_FACTOR", 1)) # asyncio's debug mode has a 10x performance penalty for this test suite. if os.environ.get("PYTHONASYNCIODEBUG"): # pragma: no cover MS *= 10 # Ensure that timeouts are larger than the clock's resolution (for Windows). MS = max(MS, 2.5 * time.get_clock_info("monotonic").resolution)
30.698276
79
0.663016
[ "BSD-3-Clause" ]
LiaoSteve/websockets
tests/utils.py
3,561
Python
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. """Functional test suite testing decryption of known good test files encrypted using static RawMasterKeyProvider.""" import base64 import json import logging import os import sys from collections import defaultdict import attr import pytest import six import aws_encryption_sdk from aws_encryption_sdk.exceptions import InvalidKeyIdError from aws_encryption_sdk.identifiers import EncryptionKeyType, WrappingAlgorithm from aws_encryption_sdk.internal.crypto.wrapping_keys import WrappingKey from aws_encryption_sdk.internal.str_ops import to_bytes from aws_encryption_sdk.key_providers.raw import RawMasterKeyProvider pytestmark = [pytest.mark.accept] # Environment-specific test file locator. May not always exist. def _file_root(): return "." try: from .aws_test_file_finder import file_root except ImportError: file_root = _file_root _LOGGER = logging.getLogger() _WRAPPING_ALGORITHM_MAP = { b"AES": { 128: {b"": {b"": WrappingAlgorithm.AES_128_GCM_IV12_TAG16_NO_PADDING}}, 192: {b"": {b"": WrappingAlgorithm.AES_192_GCM_IV12_TAG16_NO_PADDING}}, 256: {b"": {b"": WrappingAlgorithm.AES_256_GCM_IV12_TAG16_NO_PADDING}}, }, b"RSA": defaultdict( lambda: { b"PKCS1": {b"": WrappingAlgorithm.RSA_PKCS1}, b"OAEP-MGF1": { b"SHA-1": WrappingAlgorithm.RSA_OAEP_SHA1_MGF1, b"SHA-256": WrappingAlgorithm.RSA_OAEP_SHA256_MGF1, b"SHA-384": WrappingAlgorithm.RSA_OAEP_SHA384_MGF1, b"SHA-512": WrappingAlgorithm.RSA_OAEP_SHA512_MGF1, }, } ), } _KEY_TYPES_MAP = {b"AES": EncryptionKeyType.SYMMETRIC, b"RSA": EncryptionKeyType.PRIVATE} _STATIC_KEYS = defaultdict(dict) class StaticStoredMasterKeyProvider(RawMasterKeyProvider): """Provides static key""" provider_id = "static-aws-xcompat" def _get_raw_key(self, key_id): """Finds a loaded raw key.""" try: algorithm, key_bits, padding_algorithm, padding_hash = key_id.upper().split(b".", 3) key_bits = int(key_bits) key_type = _KEY_TYPES_MAP[algorithm] wrapping_algorithm = _WRAPPING_ALGORITHM_MAP[algorithm][key_bits][padding_algorithm][padding_hash] static_key = _STATIC_KEYS[algorithm][key_bits] return WrappingKey( wrapping_algorithm=wrapping_algorithm, wrapping_key=static_key, wrapping_key_type=key_type ) except KeyError: _LOGGER.exception("Unknown Key ID: %s", key_id) raise InvalidKeyIdError("Unknown Key ID: {}".format(key_id)) @attr.s class RawKeyDescription(object): """Customer raw key descriptor used by StaticStoredMasterKeyProvider.""" encryption_algorithm = attr.ib(validator=attr.validators.instance_of(six.string_types)) key_bits = attr.ib(validator=attr.validators.instance_of(int)) padding_algorithm = attr.ib(validator=attr.validators.instance_of(six.string_types)) padding_hash = attr.ib(validator=attr.validators.instance_of(six.string_types)) @property def key_id(self): """Build a key ID from instance parameters.""" return ".".join([self.encryption_algorithm, str(self.key_bits), self.padding_algorithm, self.padding_hash]) @attr.s class Scenario(object): """Scenario details.""" plaintext_filename = attr.ib(validator=attr.validators.instance_of(six.string_types)) ciphertext_filename = attr.ib(validator=attr.validators.instance_of(six.string_types)) key_ids = attr.ib(validator=attr.validators.instance_of(list)) def _generate_test_cases(): # noqa=C901 try: root_dir = os.path.abspath(file_root()) except Exception: # pylint: disable=broad-except root_dir = os.getcwd() if not os.path.isdir(root_dir): root_dir = os.getcwd() base_dir = os.path.join(root_dir, "aws_encryption_sdk_resources") ciphertext_manifest_path = os.path.join(base_dir, "manifests", "ciphertext.manifest") if not os.path.isfile(ciphertext_manifest_path): # Make no test cases if the ciphertext file is not found return [] with open(ciphertext_manifest_path, encoding="utf-8") as f: ciphertext_manifest = json.load(f) _test_cases = [] # Collect keys from ciphertext manifest for algorithm, keys in ciphertext_manifest["test_keys"].items(): algorithm = to_bytes(algorithm.upper()) for key_bits, key_desc in keys.items(): key_desc = to_bytes(key_desc) key_bits = int(key_bits) raw_key = to_bytes(key_desc.get("line_separator", "").join(key_desc["key"])) if key_desc["encoding"].lower() in ("raw", "pem"): _STATIC_KEYS[algorithm][key_bits] = raw_key elif key_desc["encoding"].lower() == "base64": _STATIC_KEYS[algorithm][key_bits] = base64.b64decode(raw_key) else: raise Exception("TODO" + "Unknown key encoding") # Collect test cases from ciphertext manifest for test_case in ciphertext_manifest["test_cases"]: key_ids = [] algorithm = aws_encryption_sdk.Algorithm.get_by_id(int(test_case["algorithm"], 16)) for key in test_case["master_keys"]: sys.stderr.write("XC:: " + json.dumps(key) + "\n") if key["provider_id"] == StaticStoredMasterKeyProvider.provider_id: key_ids.append( RawKeyDescription( key["encryption_algorithm"], key.get("key_bits", algorithm.data_key_len * 8), key.get("padding_algorithm", ""), key.get("padding_hash", ""), ).key_id ) if key_ids: _test_cases.append( Scenario( os.path.join(base_dir, test_case["plaintext"]["filename"]), os.path.join(base_dir, test_case["ciphertext"]["filename"]), key_ids, ) ) return _test_cases @pytest.mark.parametrize("scenario", _generate_test_cases()) def test_decrypt_from_file(scenario): """Tests decrypt from known good files.""" with open(scenario.ciphertext_filename, "rb") as infile: ciphertext = infile.read() with open(scenario.plaintext_filename, "rb") as infile: plaintext = infile.read() key_provider = StaticStoredMasterKeyProvider() key_provider.add_master_keys_from_list(scenario.key_ids) decrypted_ciphertext, _header = aws_encryption_sdk.decrypt(source=ciphertext, key_provider=key_provider) assert decrypted_ciphertext == plaintext
39.336957
116
0.678088
[ "Apache-2.0" ]
alex-chew/aws-encryption-sdk-python
test/functional/test_f_xcompat.py
7,238
Python
import os import sys import gen_database as gendb import json from shutil import copyfile def run_cmd(cmd): cmd_pipe = os.popen(cmd) cmd_print = cmd_pipe.read() print(cmd_print) if __name__ == '__main__': print("") root_read_dir = sys.argv[1] if root_read_dir[-1] != r"/" or root_read_dir[-1] != "\\": root_read_dir = root_read_dir + "/" # Generate java doc by javadoc command run_cmd(r"javadoc -locale en -encoding UTF-8 -charset UTF-8 -sourcepath " + r"../src ../src/main/java/com/chillingvan/docsearcher/Foooo.java ../src/main/java/com/chillingvan/docsearcher/foo/SubFoo.java" + r" -subpackages com -overview ./overview.html -d ../build/doc_java") # copy js and css to target dir copyfile('search.html', root_read_dir + 'search.html') copyfile('docsearcher.css', root_read_dir + 'docsearcher.css') copyfile('searchlib.js', root_read_dir + 'searchlib.js') # Read the html documents under /com to generate json data to a .js database_dir = root_read_dir def on_read_file(path, resultArr): if 'html' in path: url = path[path.index(root_read_dir) + len(path):] url = url.replace('\\', '/') resultArr.extend(gendb.simple_read_one(path, url)) result_arr = [] gendb.read_files(root_read_dir + 'com/', on_read_file, result_arr) final_result_arr = [] gendb.remove_same(result_arr, final_result_arr) with open(database_dir + 'searchData.js', 'w') as fl: fl.write("var searchData = " + json.dumps(final_result_arr))
36.133333
141
0.642681
[ "Apache-2.0" ]
ChillingVan/LocalHtmlSearchBox
doc/gen_javadoc.py
1,626
Python
from django.core.validators import BaseValidator from django.utils.deconstruct import deconstructible from django.utils.translation import ungettext_lazy @deconstructible class ByteLengthValidator(BaseValidator): compare = lambda self, a, b: a > b clean = lambda self, x: len(x.encode('utf8')) message = ungettext_lazy( ('Ensure this value has at most %(limit_value)d byte ' '(it has %(show_value)d).'), ('Ensure this value has at most %(limit_value)d bytes ' '(it has %(show_value)d).'), 'limit_value') code = 'max_length'
34.352941
63
0.681507
[ "MIT" ]
motiejus/tictactoe
tictactoe/tools/validators.py
584
Python
# Copyright (C) 2011 Google Inc. All rights reserved. # Copyright (C) 2019 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import threading from webkitpy.common.host_mock import MockHost from webkitpy.common.net.buildbot.buildbot_mock import MockBuildBot from webkitpy.common.net.ewsserver_mock import MockEWSServer from webkitpy.common.net.irc.irc_mock import MockIRC # FIXME: Old-style "Ports" need to die and be replaced by modern layout_tests.port which needs to move to common. from webkitpy.common.config.ports_mock import MockPort # FIXME: We should just replace this with optparse.Values(default=kwargs) class MockOptions(object): """Mock implementation of optparse.Values.""" def __init__(self, **kwargs): # The caller can set option values using keyword arguments. We don't # set any values by default because we don't know how this # object will be used. Generally speaking unit tests should # subclass this or provider wrapper functions that set a common # set of options. self.update(**kwargs) def update(self, **kwargs): self.__dict__.update(**kwargs) return self def ensure_value(self, key, value): if getattr(self, key, None) == None: self.__dict__[key] = value return self.__dict__[key] # FIXME: This should be renamed MockWebKitPatch. class MockTool(MockHost): def __init__(self, *args, **kwargs): MockHost.__init__(self, *args, **kwargs) self._deprecated_port = MockPort() self.ews_server = MockEWSServer() self._irc = None self.irc_password = "MOCK irc password" self.wakeup_event = threading.Event() def deprecated_port(self): return self._deprecated_port def path(self): return "echo" def ensure_irc_connected(self, delegate): if not self._irc: self._irc = MockIRC() def irc(self): return self._irc
39.229885
113
0.730735
[ "BSD-2-Clause" ]
jacadcaps/webkitty
Tools/Scripts/webkitpy/tool/mocktool.py
3,413
Python
""" This script implements an outlier interpretation method of the following paper: "Beyond Outlier Detection: Outlier Interpretation by Attention-Guided Triplet Deviation Network". in WWW'21. @ Author: Hongzuo Xu @ email: [email protected] or [email protected] or [email protected] """ import numpy as np import torch from torch.utils.data import Dataset from sklearn.neighbors import NearestNeighbors class SingleTripletDataset(Dataset): def __init__(self, anom_idx, x, y, triplets_selector, transform=None): self.transform = transform self.data = x self.triplets = triplets_selector.get_triplets(anom_idx, x, y) def __getitem__(self, index): a_idx, p_idx, n_idx = self.triplets[index] anchor, positive, negative = self.data[a_idx], self.data[p_idx], self.data[n_idx] if self.transform is not None: anchor = self.transform(anchor) positive = self.transform(positive) negative = self.transform(negative) return anchor, positive, negative def __len__(self): return len(self.triplets) class SingleDataset(Dataset): def __init__(self, anom_idx, x, y, data_selector, transform=None): self.transform = transform self.selected_data = data_selector.get_data(anom_idx, x, y) def __getitem__(self, index): data = self.selected_data[0][index] target = self.selected_data[1][index] if self.transform is not None: data = self.transform(data) return data, target def __len__(self): return len(self.selected_data[0]) class SingleTripletDatasetClf(Dataset): def __init__(self, anom_idx, x, y, triplets_selector, transform=None): self.transform = transform self.data = x self.triplets, self.targets = triplets_selector.get_triplets(anom_idx, x, y) def __getitem__(self, index): a_idx, p_idx, n_idx = self.triplets[index] a_target, p_target, n_target = self.targets[index] anchor, positive, negative = self.data[a_idx], self.data[p_idx], self.data[n_idx] if self.transform is not None: anchor = self.transform(anchor) positive = self.transform(positive) negative = self.transform(negative) return anchor, positive, negative, a_target, p_target, n_target def __len__(self): return len(self.triplets) class MyHardSingleTripletSelector: def __init__(self, nbrs_num, rand_num, nbr_indices): self.x = None self.y = None self.nbrs_num = nbrs_num self.rand_num = rand_num self.nbr_indices = nbr_indices def get_triplets(self, anom_idx, x, y, normal_label=0): self.x = x.cpu().data.numpy() self.y = y.cpu().data.numpy() # anom_x = self.x[anom_idx] # x_noml = self.x[noml_idx] # n_neighbors = self.nbrs_num # nbrs_local = NearestNeighbors(n_neighbors=n_neighbors).fit(x_noml) # nbr_indices = noml_idx[nbrs_local.kneighbors([anom_x])[1].flatten()] noml_idx = np.where(self.y == normal_label)[0] nbr_indices = self.nbr_indices rand_num = self.rand_num rand_canddt = np.setdiff1d(noml_idx, nbr_indices) rand_indices = np.random.choice(rand_canddt, rand_num, replace=False) triplets = [[anchor, positive, anom_idx] for anchor in rand_indices for positive in nbr_indices] return torch.LongTensor(np.array(triplets)) class MyHardSingleSelectorClf: def __init__(self, nbrs_num, rand_num): self.nbrs_num = nbrs_num self.rand_num = rand_num def get_data(self, anom_idx, x, y, normal_label=0): x = x.cpu().data.numpy() y = y.cpu().data.numpy() anom_x = x[anom_idx] noml_idx = np.where(y == normal_label)[0] x_noml = x[noml_idx] nbrs_local = NearestNeighbors(n_neighbors=self.nbrs_num).fit(x_noml) nbr_indices = noml_idx[nbrs_local.kneighbors([anom_x])[1].flatten()] rand_canddt = np.setdiff1d(noml_idx, nbr_indices) rand_indices = np.random.choice(rand_canddt, self.rand_num, replace=False) # perturbation to augment dim = x.shape[1] anom_lst = [] anom_lst.append(anom_x) for i in range(self.rand_num + self.nbrs_num -1): new_anom_x = anom_x.copy() choose_f = np.random.choice(np.arange(dim), 3) for a in choose_f: new_anom_x[a] = anom_x[a] * 1.01 anom_lst.append(new_anom_x) data_idx = np.hstack([rand_indices, nbr_indices]) norm_data = x[data_idx] data = np.vstack([np.array(anom_lst), norm_data]) target = np.hstack([np.ones(10), np.zeros(len(rand_indices), dtype=int), np.zeros(len(nbr_indices), dtype=int)]) return torch.FloatTensor(data), torch.LongTensor(target) class MyHardSingleTripletSelectorClf: def __init__(self, nbrs_num, rand_num): self.x = None self.y = None self.nbrs_num = nbrs_num self.rand_num = rand_num def get_triplets(self, anom_idx, x, y, normal_label=0): self.x = x.cpu().data.numpy() self.y = y.cpu().data.numpy() anom_x = self.x[anom_idx] noml_idx = np.where(self.y == normal_label)[0] x_noml = self.x[noml_idx] n_neighbors = self.nbrs_num rand_num = self.rand_num nbrs_local = NearestNeighbors(n_neighbors=n_neighbors).fit(x_noml) nbr_indices = noml_idx[nbrs_local.kneighbors([anom_x])[1].flatten()] # nbr_dist = nbrs_local.kneighbors([anom_x])[0].flatten() rand_canddt = np.setdiff1d(noml_idx, nbr_indices) rand_indices = np.random.choice(rand_canddt, rand_num, replace=False) triplets = [[anchor, positive, anom_idx] for anchor in rand_indices for positive in nbr_indices] # print("Generate triplets Num: [%d]" % len(triplets)) target = [[0, 0, 1]] * len(triplets) return torch.LongTensor(np.array(triplets)), torch.LongTensor(np.array(target)) class MyHardSingleTripletSelector2: def __init__(self, nbrs_num, rand_num): self.x = None self.y = None self.nbrs_num = nbrs_num self.rand_num = rand_num def get_triplets(self, anom_idx, x, y, normal_label=0): self.x = x.cpu().data.numpy() self.y = y.cpu().data.numpy() n_neighbors = self.nbrs_num rand_num = self.rand_num anom_x = self.x[anom_idx] anom_indices = np.where(self.y != normal_label)[0] noml_indices = np.where(self.y == normal_label)[0] noml_x = self.x[noml_indices] nbrs_local = NearestNeighbors(n_neighbors=n_neighbors).fit(noml_x) nbr_indices = noml_indices[nbrs_local.kneighbors([anom_x])[1].flatten()] # nbr_dist = nbrs_local.kneighbors([anom_x])[0].flatten() rand_canddt_nor = np.setdiff1d(noml_indices, nbr_indices) rand_nor_indices = np.random.choice(rand_canddt_nor, rand_num, replace=False) triplets1 = [[anchor, positive, anom_idx] for anchor in rand_nor_indices for positive in nbr_indices] rand_canddt_ano = np.setdiff1d(anom_indices, anom_idx) if len(rand_canddt_ano) < rand_num: rand_ano_indices = rand_canddt_ano else: rand_ano_indices = np.random.choice(rand_canddt_ano, rand_num, replace=False) triplets2 = [[anchor, anom_idx, negative] for anchor in rand_ano_indices for negative in nbr_indices] triplets = triplets1 + triplets2 # print("Generate triplets Num: [%d]" % len(triplets)) target1 = [[0, 0, 1]] * len(triplets1) target2 = [[1, 1, 0]] * len(triplets2) target = target1 + target2 return torch.LongTensor(np.array(triplets)), torch.LongTensor(np.array(target))
36.135135
120
0.639616
[ "Apache-2.0" ]
xuhongzuo/Outlier-Interpretation
model_aton/datasets.py
8,022
Python
# Defines a bluetooth exception class BluetoothException(Exception): pass
25.666667
36
0.805195
[ "MIT" ]
jjoyce0510/autonomous-shipping-vessel
src/main/python/exceptions/BluetoothException.py
77
Python
from unittest import TestCase import torch from model.lstm2d_cell import LSTM2dCell class LSTM2dCellTest(TestCase): """ Unit tests for the 2D-LSTM cell. """ embed_dim = 50 encoder_state_dim = 20 input_dim = 2 * encoder_state_dim + embed_dim cell_state_dim = 25 batch_size = 42 def setUp(self): torch.manual_seed(42) self.x_j = torch.randn(self.batch_size, self.input_dim) self.s_prev_hor = torch.randn(self.batch_size, self.cell_state_dim) self.s_prev_ver = torch.randn(self.batch_size, self.cell_state_dim) self.c_prev_hor = torch.randn(self.batch_size, self.cell_state_dim) self.c_prev_ver = torch.randn(self.batch_size, self.cell_state_dim) self.device = torch.device('cpu') def test_dimensions(self): """ Tests if the input and output dimensions of the cell are as expected. """ cell = LSTM2dCell(self.input_dim, self.cell_state_dim, self.device) c_ji, s_ji = cell.forward(x=self.x_j, s_prev_hor=self.s_prev_hor, s_prev_ver=self.s_prev_ver, c_prev_hor=self.c_prev_hor, c_prev_ver=self.c_prev_ver) c_shape = list(c_ji.shape) s_shape = list(s_ji.shape) self.assertEqual(c_shape, [self.batch_size, self.cell_state_dim], 'Next cell state has unexpected shape') self.assertEqual(s_shape, [self.batch_size, self.cell_state_dim], 'Next hidden state has unexpected shape') def test_same_over_batch(self): """ Tests if the outputs of the cell are the same over the batch if the same input is fed in multiple times. """ toy_input_dim = 4 toy_batch_size = 7 toy_state_dim = 3 # create toy values and repeat them over the batch toy_x = torch.Tensor([1.5, 4.2, 3.1415, 2.71]).expand(toy_batch_size, toy_input_dim) toy_s_prev_hor = torch.Tensor([-.4, 1.2, 42.195]).expand(toy_batch_size, toy_state_dim) toy_s_prev_ver = torch.Tensor([2.3, 7.12, -3.14]).expand(toy_batch_size, toy_state_dim) toy_c_prev_hor = torch.Tensor([-10.1, 4.5, -0.1]).expand(toy_batch_size, toy_state_dim) toy_c_prev_ver = torch.Tensor([17, 1.001, -2.23]).expand(toy_batch_size, toy_state_dim) cell = LSTM2dCell(toy_input_dim, toy_state_dim, self.device) c, s = cell.forward(x=toy_x, s_prev_hor=toy_s_prev_hor, s_prev_ver=toy_s_prev_ver, c_prev_hor=toy_c_prev_hor, c_prev_ver=toy_c_prev_ver) # check if the cell and hidden state are the same across the whole batch c_first = c[0, :] repeated_c_first = c_first.expand(toy_batch_size, c_first.shape[-1]) self.assertTrue(repeated_c_first.allclose(c), 'Next cell state varies across same-input batch') s_first = s[0, :] repeated_s_first = s_first.expand(toy_batch_size, s_first.shape[-1]) self.assertTrue(repeated_s_first.allclose(s), 'Next hidden state varies across same-input batch')
42.450704
115
0.675514
[ "MIT" ]
FlorianPfisterer/2D-LSTM-Seq2Seq
test/test_lstm2d_cell.py
3,014
Python
# Copyright (c) 2020, NVIDIA CORPORATION. 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 abc import ABC, abstractmethod from typing import List, Optional, Union import editdistance import torch from pytorch_lightning.metrics import Metric from nemo.collections.asr.parts import rnnt_beam_decoding as beam_decode from nemo.collections.asr.parts import rnnt_greedy_decoding as greedy_decode from nemo.collections.asr.parts.rnnt_utils import Hypothesis, NBestHypotheses from nemo.utils import logging __all__ = ['RNNTDecoding', 'RNNTWER'] class AbstractRNNTDecoding(ABC): """ Used for performing RNN-T auto-regressive decoding of the Decoder+Joint network given the encoder state. Args: decoding_cfg: A dict-like object which contains the following key-value pairs. strategy: str value which represents the type of decoding that can occur. Possible values are : - greedy, greedy_batch (for greedy decoding). - beam, tsd, alsd (for beam search decoding). compute_hypothesis_token_set: A bool flag, which determines whether to compute a list of decoded tokens as well as the decoded string. Default is False in order to avoid double decoding unless required. The config may further contain the following sub-dictionaries: "greedy": max_symbols: int, describing the maximum number of target tokens to decode per timestep during greedy decoding. Setting to larger values allows longer sentences to be decoded, at the cost of increased execution time. "beam": beam_size: int, defining the beam size for beam search. Must be >= 1. If beam_size == 1, will perform cached greedy search. This might be slightly different results compared to the greedy search above. score_norm: optional bool, whether to normalize the returned beam score in the hypotheses. Set to True by default. return_best_hypothesis: optional bool, whether to return just the best hypothesis or all of the hypotheses after beam search has concluded. This flag is set by default. tsd_max_sym_exp: optional int, determines number of symmetric expansions of the target symbols per timestep of the acoustic model. Larger values will allow longer sentences to be decoded, at increased cost to execution time. alsd_max_target_len: optional int or float, determines the potential maximum target sequence length. If an integer is provided, it can decode sequences of that particular maximum length. If a float is provided, it can decode sequences of int(alsd_max_target_len * seq_len), where seq_len is the length of the acoustic model output (T). NOTE: If a float is provided, it can be greater than 1! By default, a float of 2.0 is used so that a target sequence can be at most twice as long as the acoustic model output length T. decoder: The Decoder/Prediction network module. joint: The Joint network module. blank_id: The id of the RNNT blank token. """ def __init__(self, decoding_cfg, decoder, joint, blank_id: int): super(AbstractRNNTDecoding, self).__init__() self.cfg = decoding_cfg self.blank_id = blank_id self.compute_hypothesis_token_set = self.cfg.get("compute_hypothesis_token_set", False) possible_strategies = ['greedy', 'greedy_batch', 'beam', 'tsd', 'alsd'] if self.cfg.strategy not in possible_strategies: raise ValueError(f"Decoding strategy must be one of {possible_strategies}") if self.cfg.strategy == 'greedy': self.decoding = greedy_decode.GreedyRNNTInfer( decoder_model=decoder, joint_model=joint, blank_index=self.blank_id, max_symbols_per_step=self.cfg.greedy.get('max_symbols', None), ) elif self.cfg.strategy == 'greedy_batch': self.decoding = greedy_decode.GreedyBatchedRNNTInfer( decoder_model=decoder, joint_model=joint, blank_index=self.blank_id, max_symbols_per_step=self.cfg.greedy.get('max_symbols', None), ) elif self.cfg.strategy == 'beam': self.decoding = beam_decode.BeamRNNTInfer( decoder_model=decoder, joint_model=joint, beam_size=self.cfg.beam.beam_size, return_best_hypothesis=decoding_cfg.beam.get('return_best_hypothesis', True), search_type='default', score_norm=self.cfg.beam.get('score_norm', True), ) elif self.cfg.strategy == 'tsd': self.decoding = beam_decode.BeamRNNTInfer( decoder_model=decoder, joint_model=joint, beam_size=self.cfg.beam.beam_size, return_best_hypothesis=decoding_cfg.beam.get('return_best_hypothesis', True), search_type='tsd', score_norm=self.cfg.beam.get('score_norm', True), tsd_max_sym_exp_per_step=self.cfg.beam.get('tsd_max_sym_exp', 50), ) elif self.cfg.strategy == 'alsd': self.decoding = beam_decode.BeamRNNTInfer( decoder_model=decoder, joint_model=joint, beam_size=self.cfg.beam.beam_size, return_best_hypothesis=decoding_cfg.beam.get('return_best_hypothesis', True), search_type='alsd', score_norm=self.cfg.beam.get('score_norm', True), alsd_max_target_len=self.cfg.beam.get('alsd_max_target_len', 2), ) def rnnt_decoder_predictions_tensor( self, encoder_output: torch.Tensor, encoded_lengths: torch.Tensor, return_hypotheses: bool = False ) -> (List[str], Optional[List[List[str]]], Optional[Union[Hypothesis, NBestHypotheses]]): """ Decode an encoder output by autoregressive decoding of the Decoder+Joint networks. Args: encoder_output: torch.Tensor of shape [B, D, T]. encoded_lengths: torch.Tensor containing lengths of the padded encoder outputs. Shape [B]. return_hypotheses: bool. If set to True it will return list of Hypothesis or NBestHypotheses Returns: If `return_best_hypothesis` is set: A tuple (hypotheses, None): hypotheses - list of Hypothesis (best hypothesis per sample). Look at rnnt_utils.Hypothesis for more information. If `return_best_hypothesis` is not set: A tuple(hypotheses, all_hypotheses) hypotheses - list of Hypothesis (best hypothesis per sample). Look at rnnt_utils.Hypothesis for more information. all_hypotheses - list of NBestHypotheses. Each NBestHypotheses further contains a sorted list of all the hypotheses of the model per sample. Look at rnnt_utils.NBestHypotheses for more information. """ # Compute hypotheses with torch.no_grad(): hypotheses_list = self.decoding( encoder_output=encoder_output, encoded_lengths=encoded_lengths ) # type: [List[Hypothesis]] # extract the hypotheses hypotheses_list = hypotheses_list[0] # type: List[Hypothesis] prediction_list = hypotheses_list if isinstance(prediction_list[0], NBestHypotheses): hypotheses = [] all_hypotheses = [] for nbest_hyp in prediction_list: # type: NBestHypotheses n_hyps = nbest_hyp.n_best_hypotheses # Extract all hypotheses for this sample decoded_hyps = self.decode_hypothesis(n_hyps) # type: List[str] hypotheses.append(decoded_hyps[0]) # best hypothesis all_hypotheses.append(decoded_hyps) if return_hypotheses: return hypotheses, all_hypotheses best_hyp_text = [h.text for h in hypotheses] all_hyp_text = [h.text for hh in all_hypotheses for h in hh] return best_hyp_text, all_hyp_text else: hypotheses = self.decode_hypothesis(prediction_list) # type: List[str] if return_hypotheses: return hypotheses, None best_hyp_text = [h.text for h in hypotheses] return best_hyp_text, None def decode_hypothesis(self, hypotheses_list: List[Hypothesis]) -> List[Union[Hypothesis, NBestHypotheses]]: """ Decode a list of hypotheses into a list of strings. Args: hypotheses_list: List of Hypothesis. Returns: A list of strings. """ for ind in range(len(hypotheses_list)): # Extract the integer encoded hypothesis prediction = hypotheses_list[ind].y_sequence if type(prediction) != list: prediction = prediction.tolist() # RNN-T sample level is already preprocessed by implicit CTC decoding # Simply remove any blank tokens prediction = [p for p in prediction if p != self.blank_id] # De-tokenize the integer tokens hypothesis = self.decode_tokens_to_str(prediction) hypotheses_list[ind].text = hypothesis if self.compute_hypothesis_token_set: hypotheses_list[ind].tokens = self.decode_ids_to_tokens(prediction) return hypotheses_list @abstractmethod def decode_tokens_to_str(self, tokens: List[int]) -> str: """ Implemented by subclass in order to decoder a token id list into a string. Args: tokens: List of int representing the token ids. Returns: A decoded string. """ raise NotImplementedError() @abstractmethod def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: """ Implemented by subclass in order to decode a token id list into a token list. A token list is the string representation of each token id. Args: tokens: List of int representing the token ids. Returns: A list of decoded tokens. """ raise NotImplementedError() class RNNTDecoding(AbstractRNNTDecoding): """ Used for performing RNN-T auto-regressive decoding of the Decoder+Joint network given the encoder state. Args: decoding_cfg: A dict-like object which contains the following key-value pairs. strategy: str value which represents the type of decoding that can occur. Possible values are : - greedy, greedy_batch (for greedy decoding). - beam, tsd, alsd (for beam search decoding). compute_hypothesis_token_set: A bool flag, which determines whether to compute a list of decoded tokens as well as the decoded string. Default is False in order to avoid double decoding unless required. The config may further contain the following sub-dictionaries: "greedy": max_symbols: int, describing the maximum number of target tokens to decode per timestep during greedy decoding. Setting to larger values allows longer sentences to be decoded, at the cost of increased execution time. "beam": beam_size: int, defining the beam size for beam search. Must be >= 1. If beam_size == 1, will perform cached greedy search. This might be slightly different results compared to the greedy search above. score_norm: optional bool, whether to normalize the returned beam score in the hypotheses. Set to True by default. return_best_hypothesis: optional bool, whether to return just the best hypothesis or all of the hypotheses after beam search has concluded. This flag is set by default. tsd_max_sym_exp: optional int, determines number of symmetric expansions of the target symbols per timestep of the acoustic model. Larger values will allow longer sentences to be decoded, at increased cost to execution time. alsd_max_target_len: optional int or float, determines the potential maximum target sequence length. If an integer is provided, it can decode sequences of that particular maximum length. If a float is provided, it can decode sequences of int(alsd_max_target_len * seq_len), where seq_len is the length of the acoustic model output (T). NOTE: If a float is provided, it can be greater than 1! By default, a float of 2.0 is used so that a target sequence can be at most twice as long as the acoustic model output length T. decoder: The Decoder/Prediction network module. joint: The Joint network module. vocabulary: The vocabulary (excluding the RNNT blank token) which will be used for decoding. """ def __init__( self, decoding_cfg, decoder, joint, vocabulary, ): blank_id = len(vocabulary) self.labels_map = dict([(i, vocabulary[i]) for i in range(len(vocabulary))]) super(RNNTDecoding, self).__init__(decoding_cfg=decoding_cfg, decoder=decoder, joint=joint, blank_id=blank_id) def decode_tokens_to_str(self, tokens: List[int]) -> str: """ Implemented by subclass in order to decoder a token list into a string. Args: tokens: List of int representing the token ids. Returns: A decoded string. """ hypothesis = ''.join([self.labels_map[c] for c in tokens if c != self.blank_id]) return hypothesis def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: """ Implemented by subclass in order to decode a token id list into a token list. A token list is the string representation of each token id. Args: tokens: List of int representing the token ids. Returns: A list of decoded tokens. """ token_list = [self.labels_map[c] for c in tokens if c != self.blank_id] return token_list class RNNTWER(Metric): """ This metric computes numerator and denominator for Overall Word Error Rate (WER) between prediction and reference texts. When doing distributed training/evaluation the result of res=WER(predictions, targets, target_lengths) calls will be all-reduced between all workers using SUM operations. Here contains two numbers res=[wer_numerator, wer_denominator]. WER=wer_numerator/wer_denominator. If used with PytorchLightning LightningModule, include wer_numerator and wer_denominators inside validation_step results. Then aggregate (sum) then at the end of validation epoch to correctly compute validation WER. Example: def validation_step(self, batch, batch_idx): ... wer_num, wer_denom = self.__wer(predictions, transcript, transcript_len) return {'val_loss': loss_value, 'val_wer_num': wer_num, 'val_wer_denom': wer_denom} def validation_epoch_end(self, outputs): ... wer_num = torch.stack([x['val_wer_num'] for x in outputs]).sum() wer_denom = torch.stack([x['val_wer_denom'] for x in outputs]).sum() tensorboard_logs = {'validation_loss': val_loss_mean, 'validation_avg_wer': wer_num / wer_denom} return {'val_loss': val_loss_mean, 'log': tensorboard_logs} Args: decoding: RNNTDecoding object that will perform autoregressive decoding of the RNNT model. batch_dim_index: Index of the batch dimension. use_cer: Whether to use Character Error Rate isntead of Word Error Rate. log_prediction: Whether to log a single decoded sample per call. Returns: res: a torch.Tensor object with two elements: [wer_numerator, wer_denominator]. To correctly compute average text word error rate, compute wer=wer_numerator/wer_denominator """ def __init__( self, decoding: RNNTDecoding, batch_dim_index=0, use_cer=False, log_prediction=True, dist_sync_on_step=False ): super(RNNTWER, self).__init__(dist_sync_on_step=dist_sync_on_step, compute_on_step=False) self.decoding = decoding self.batch_dim_index = batch_dim_index self.use_cer = use_cer self.log_prediction = log_prediction self.blank_id = self.decoding.blank_id self.labels_map = self.decoding.labels_map self.add_state("scores", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) self.add_state("words", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) def update( self, encoder_output: torch.Tensor, encoded_lengths: torch.Tensor, targets: torch.Tensor, target_lengths: torch.Tensor, ) -> torch.Tensor: words = 0.0 scores = 0.0 references = [] with torch.no_grad(): # prediction_cpu_tensor = tensors[0].long().cpu() targets_cpu_tensor = targets.long().cpu() tgt_lenths_cpu_tensor = target_lengths.long().cpu() # iterate over batch for ind in range(targets_cpu_tensor.shape[self.batch_dim_index]): tgt_len = tgt_lenths_cpu_tensor[ind].item() target = targets_cpu_tensor[ind][:tgt_len].numpy().tolist() reference = self.decoding.decode_tokens_to_str(target) references.append(reference) hypotheses, _ = self.decoding.rnnt_decoder_predictions_tensor(encoder_output, encoded_lengths) if self.log_prediction: logging.info(f"\n") logging.info(f"reference :{references[0]}") logging.info(f"predicted :{hypotheses[0]}") for h, r in zip(hypotheses, references): if self.use_cer: h_list = list(h) r_list = list(r) else: h_list = h.split() r_list = r.split() words += len(r_list) # Compute Levenshtein's distance scores += editdistance.eval(h_list, r_list) self.scores += torch.tensor(scores, device=self.scores.device, dtype=self.scores.dtype) self.words += torch.tensor(words, device=self.words.device, dtype=self.words.dtype) # return torch.tensor([scores, words]).to(predictions.device) def compute(self): wer = self.scores.float() / self.words return wer, self.scores.detach(), self.words.detach()
45.308219
125
0.639153
[ "Apache-2.0" ]
JINHXu/NeMo
nemo/collections/asr/metrics/rnnt_wer.py
19,845
Python
''' Created on 2021-08-19 @author: wf ''' from unittest import TestCase import time import getpass import os class BaseTest(TestCase): ''' base test case ''' def setUp(self,debug=False,profile=True): ''' setUp test environment ''' TestCase.setUp(self) self.debug=debug self.profile=profile msg=f"test {self._testMethodName}, debug={self.debug}" self.profiler=Profiler(msg,profile=self.profile) def tearDown(self): TestCase.tearDown(self) self.profiler.time() @staticmethod def inPublicCI(): ''' are we running in a public Continuous Integration Environment? ''' publicCI=getpass.getuser() in ["travis", "runner"] jenkins= "JENKINS_HOME" in os.environ; return publicCI or jenkins class Profiler: ''' simple profiler ''' def __init__(self,msg,profile=True): ''' construct me with the given msg and profile active flag Args: msg(str): the message to show if profiling is active profile(bool): True if messages should be shown ''' self.msg=msg self.profile=profile self.starttime=time.time() if profile: print(f"Starting {msg} ...") def time(self,extraMsg=""): ''' time the action and print if profile is active ''' elapsed=time.time()-self.starttime if self.profile: print(f"{self.msg}{extraMsg} took {elapsed:5.1f} s") return elapsed
25.25
70
0.571782
[ "Apache-2.0" ]
WolfgangFahl/pyOnlineSpreadSheetEditing
tests/basetest.py
1,616
Python
# Auto-generated at 2021-09-27T17:12:31.553030+08:00 # from: Justice Iam Service (4.1.0) # Copyright (c) 2018 - 2021 AccelByte Inc. All Rights Reserved. # This is licensed software from AccelByte Inc, for limitations # and restrictions contact your company contract manager. # pylint: disable=duplicate-code # pylint: disable=line-too-long # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=too-many-arguments # pylint: disable=too-many-branches # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-lines # pylint: disable=too-many-locals # pylint: disable=too-many-public-methods # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements # pylint: disable=unused-import from __future__ import annotations from typing import Any, Dict, List, Optional, Tuple, Union from ....core import Model from ..models.accountcommon_pagination_v3 import AccountcommonPaginationV3 from ..models.model_user_response_v3 import ModelUserResponseV3 class ModelGetUsersResponseWithPaginationV3(Model): """Model get users response with pagination V3 Properties: data: (data) REQUIRED List[ModelUserResponseV3] paging: (paging) REQUIRED AccountcommonPaginationV3 """ # region fields data: List[ModelUserResponseV3] # REQUIRED paging: AccountcommonPaginationV3 # REQUIRED # endregion fields # region with_x methods def with_data(self, value: List[ModelUserResponseV3]) -> ModelGetUsersResponseWithPaginationV3: self.data = value return self def with_paging(self, value: AccountcommonPaginationV3) -> ModelGetUsersResponseWithPaginationV3: self.paging = value return self # endregion with_x methods # region to methods def to_dict(self, include_empty: bool = False) -> dict: result = {} if hasattr(self, "data") and self.data: result["data"] = [i0.to_dict(include_empty=include_empty) for i0 in self.data] elif include_empty: result["data"] = [] if hasattr(self, "paging") and self.paging: result["paging"] = self.paging.to_dict(include_empty=include_empty) elif include_empty: result["paging"] = AccountcommonPaginationV3() return result # endregion to methods # region static methods @classmethod def create( cls, data: List[ModelUserResponseV3], paging: AccountcommonPaginationV3, ) -> ModelGetUsersResponseWithPaginationV3: instance = cls() instance.data = data instance.paging = paging return instance @classmethod def create_from_dict(cls, dict_: dict, include_empty: bool = False) -> ModelGetUsersResponseWithPaginationV3: instance = cls() if not dict_: return instance if "data" in dict_ and dict_["data"] is not None: instance.data = [ModelUserResponseV3.create_from_dict(i0, include_empty=include_empty) for i0 in dict_["data"]] elif include_empty: instance.data = [] if "paging" in dict_ and dict_["paging"] is not None: instance.paging = AccountcommonPaginationV3.create_from_dict(dict_["paging"], include_empty=include_empty) elif include_empty: instance.paging = AccountcommonPaginationV3() return instance @staticmethod def get_field_info() -> Dict[str, str]: return { "data": "data", "paging": "paging", } # endregion static methods
33.540541
123
0.665861
[ "MIT" ]
encyphered/accelbyte-python-sdk
accelbyte_py_sdk/api/iam/models/model_get_users_response_with_pagination_v3.py
3,723
Python
from svs.models import Customer from django.db import models from django.utils import timezone from svs.models import Customer, Machine from core.models import CoreUser from markdownx.models import MarkdownxField STATUSES = ( ("pending_our", "Pending - Our Side"), ("pending_their", "Pending - Their Side"), ("timeout", "More Than a Week"), ("closed", "Closed 😁"), ) class Issue(models.Model): created_at = models.DateTimeField(default=timezone.now) title = models.CharField(max_length=255) contact = models.CharField(max_length=255) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) user = models.ForeignKey(CoreUser, on_delete=models.CASCADE) machine = models.ForeignKey(Machine, on_delete=models.CASCADE) description = MarkdownxField() status = models.CharField( max_length=20, choices=STATUSES, null=False, default="pending_ours" ) def __str__(self) -> str: return self.title class IssueEntry(models.Model): issue = models.ForeignKey(Issue, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) title = models.CharField(max_length=255) description = MarkdownxField() def __str__(self) -> str: return self.title class Meta: verbose_name_plural = "Entries"
30.744186
75
0.715582
[ "MIT" ]
mariofix/optisortcreator
issues/models.py
1,325
Python
# Generated by Django 2.1.3 on 2019-01-07 17:44 import django.contrib.postgres.fields.jsonb from django.db import migrations, models import services.models import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Service', fields=[ ('create_date', models.DateTimeField(auto_now_add=True)), ('update_date', models.DateTimeField(auto_now=True)), ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('slug', models.SlugField(max_length=255, unique=True)), ('name', models.CharField(max_length=255, verbose_name='Name')), ('data', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=services.models.default_data)), ('params', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=dict)), ], options={ 'abstract': False, }, ), ]
33.333333
123
0.606364
[ "MIT" ]
KeoH/orchestrapi
services/migrations/0001_initial.py
1,100
Python
from flask_alembic import Alembic from flask_sqlalchemy import SQLAlchemy database = SQLAlchemy() alembic = Alembic()
19.833333
39
0.823529
[ "BSD-3-Clause" ]
wikimedia/cloud-metricsinfra-prometheus-manager
prometheus_manager/database.py
119
Python
#!/usr/bin/python3 import pymysql db = pymysql.connect("localhost","root","123456","tboxdb" ) cursor = db.cursor() #create table cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" cursor.execute(sql) #insert sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" #sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ # LAST_NAME, AGE, SEX, INCOME) \ # VALUES ('%s', '%s', '%d', '%c', '%d' )" % \ # ('Mac', 'Mohan', 20, 'M', 2000) try: cursor.execute(sql) db.commit() except: db.rollback() #query sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > '%d'" % (1000) try: cursor.execute(sql) results = cursor.fetchall() for row in results: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \ (fname, lname, age, sex, income )) except: print ("Error: unable to fetch data") #update sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try: cursor.execute(sql) db.commit() except: db.rollback() #delete sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20) try: cursor.execute(sql) db.commit() except: db.rollback() db.close()
21.109589
67
0.53926
[ "Apache-2.0" ]
harveywangdao/car
scripts/mysql.py
1,541
Python
# Copyright (C) 2002, Thomas Hamelryck ([email protected]) # # This file is part of the Biopython distribution and governed by your # choice of the "Biopython License Agreement" or the "BSD 3-Clause License". # Please see the LICENSE file that should have been included as part of this # package. """The structure class, representing a macromolecular structure.""" from Bio.PDB.Entity import Entity from Bio.PDB.internal_coords import IC_Chain class Structure(Entity): """The Structure class contains a collection of Model instances.""" def __init__(self, id): """Initialize the class.""" self.level = "S" Entity.__init__(self, id) def __repr__(self): """Return the structure identifier.""" return "<Structure id=%s>" % self.get_id() def get_models(self): """Return models.""" yield from self def get_chains(self): """Return chains from models.""" for m in self.get_models(): yield from m def get_residues(self): """Return residues from chains.""" for c in self.get_chains(): yield from c def get_atoms(self): """Return atoms from residue.""" for r in self.get_residues(): yield from r def atom_to_internal_coordinates(self, verbose: bool = False) -> None: """Create/update internal coordinates from Atom X,Y,Z coordinates. Internal coordinates are bond length, angle and dihedral angles. :param verbose bool: default False describe runtime problems """ for chn in self.get_chains(): chn.atom_to_internal_coordinates(verbose) def internal_to_atom_coordinates(self, verbose: bool = False) -> None: """Create/update atom coordinates from internal coordinates. :param verbose bool: default False describe runtime problems :raises Exception: if any chain does not have .pic attribute """ for chn in self.get_chains(): chn.internal_to_atom_coordinates(verbose)
31.029851
76
0.647908
[ "BSD-3-Clause" ]
AaronLi/biopython
Bio/PDB/Structure.py
2,079
Python
import unittest from code import instance as i from code import datamapping as dm class TestProblemInstance(unittest.TestCase): def setUp(self): raw_data = dm.Importer() raw_data.import_data("./tests/cvrp1.test") data = dm.DataMapper(raw_data) self.problem = i.ProblemInstance(data) def test_(self): pass if __name__ == "__main__": unittest.main()
19.380952
50
0.668305
[ "MIT" ]
Antash696/VRP
tests/tests_instance.py
407
Python
#!/usr/bin/env python import os from matplotlib.path import Path import numpy as np import pandas as pd from scipy.interpolate import griddata from qcore import geo DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "zdata") # constant regions and max bounds for faster processing POLYGONS = [ (os.path.join(DATA, "AucklandPolgonOutline_Points_WGS84.txt"), 0.13), (os.path.join(DATA, "ChristchurchPolgonOutline_Points_WGS84.txt"), 0.3), (os.path.join(DATA, "NorthlandPolgonOutline_Points_WGS84.txt"), 0.1), ] CITY_RADIUS_SEARCH = 2 # contours Z_VALS = [0.13, 0.15, 0.175, 0.188, 0.20, 0.25, 0.275, 0.30, 0.325, 0.35, 0.375, 0.40, 0.415, 0.425, 0.45, 0.475, 0.50, 0.525, 0.55, 0.575, 0.60] Z_FORMAT = os.path.join(DATA, "Z_%.3f_points_WGS84.txt") def ll2z(locations, radius_search=CITY_RADIUS_SEARCH): """Computes the z-value for the given lon, lat tuple or list of lon, lat tuples :param locations: :param radius_search: Checks to see if a city is within X km from the given location, removes the search if value is set to 0 :return: Array of z-values, one for each location specified """ try: multi = bool(len(locations[0])) except TypeError: multi = False locations = [locations] out = np.zeros(len(locations)) # check if in polygon for p in POLYGONS: c = Path( geo.path_from_corners( corners=np.loadtxt(p[0]).tolist(), output=None, min_edge_points=4 ) ).contains_points(locations) out = np.where(c, p[1], out) # check if within specified radius from city if radius_search > 0: cities = pd.read_csv(os.path.join(DATA, 'cities_z.csv'), header=None, names=['lon', 'lat', 'city', 'z_value']) cities_ll = cities[['lon', 'lat']].values for i, location in enumerate(locations): dists = geo.get_distances(cities_ll, location[0], location[1]) if np.any(dists < radius_search): cities['dist'] = dists city_idx = cities.dist.idxmin() out[i] = cities.loc[city_idx].z_value # interpolate contours nz = [] points_all = [] for z in Z_VALS: points = np.atleast_2d(np.loadtxt(Z_FORMAT % z)) nz.append(len(points)) points_all.append(points) points = np.concatenate(points_all) del points_all z = griddata(points, np.repeat(Z_VALS, nz), locations, method="linear") return np.where(out == 0, np.where(np.isnan(z), 0.13, z), out) if __name__ == "__main__": from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("lon", type=float) parser.add_argument("lat", type=float) a = parser.parse_args() print(ll2z((a.lon, a.lat)))
32.37931
145
0.636493
[ "MIT" ]
ucgmsim/gmhazard
calculation/gmhazard_calc/gmhazard_calc/nz_code/nzs1170p5/nzs_zfactor_2016/ll2z.py
2,817
Python
#!/usr/bin/env python3 # Copyright (c) 2019 MindAffect B.V. # Author: Jason Farquhar <[email protected]> # This file is part of pymindaffectBCI <https://github.com/mindaffect/pymindaffectBCI>. # # pymindaffectBCI is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # pymindaffectBCI is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with pymindaffectBCI. If not, see <http://www.gnu.org/licenses/> from mindaffectBCI.utopiaclient import UtopiaClient, Subscribe, StimulusEvent, NewTarget, Selection, DataPacket, UtopiaMessage, SignalQuality from collections import deque from mindaffectBCI.decoder.utils import RingBuffer, extract_ringbuffer_segment from mindaffectBCI.decoder.lower_bound_tracker import lower_bound_tracker from mindaffectBCI.decoder.linear_trend_tracker import linear_trend_tracker from time import sleep import numpy as np class UtopiaDataInterface: """Adaptor class for interfacing between the decoder logic and the data source This class provides functionality to wrap a real time data and stimulus stream to make it easier to implement standard machine learning pipelines. In particular it provides streamed pre-processing for both EEG and stimulus streams, and ring-buffers for the same with time-stamp based indexing. """ # TODO [X] : infer valid data time-stamps # TODO [X] : smooth and de-jitter the data time-stamps # TODO [] : expose a (potentially blocking) message generator interface # TODO [X] : ring-buffer for the stimulus-state also, so fast random access # TODO [X] : rate limit waiting to reduce computational load VERBOSITY = 1 def __init__(self, datawindow_ms=60000, msgwindow_ms=60000, data_preprocessor=None, stimulus_preprocessor=None, send_signalquality=True, timeout_ms=100, mintime_ms=50, fs=None, U=None, sample2timestamp='lower_bound_tracker', clientid=None): # rate control self.timeout_ms = timeout_ms self.mintime_ms = mintime_ms # minimum time to spend in update => max processing rate # amout of data in the ring-buffer self.datawindow_ms = datawindow_ms self.msgwindow_ms = msgwindow_ms # connect to the mindaffectDecoder self.host = None self.port = -1 self.U = UtopiaClient(clientid) if U is None else U self.t0 = self.getTimeStamp() # init the buffers # Messages self.msg_ringbuffer = deque() self.msg_timestamp = None # ts of most recent processed message # DataPackets self.data_ringbuffer = None # init later... self.data_timestamp = None # ts of last data packet seen self.sample2timestamp = sample2timestamp # sample tracker to de-jitter time-stamp information self.data_preprocessor = data_preprocessor # function to pre-process the incomming data # StimulusEvents self.stimulus_ringbuffer = None # init later... self.stimulus_timestamp = None # ts of most recent processed data self.stimulus_preprocessor = stimulus_preprocessor # function to pre-process the incomming data # Info about the data sample rate -- estimated from packet rates.. self.raw_fs = fs self.fs = None self.newmsgs = [] # list new unprocssed messages since last update call # BODGE: running statistics for sig2noise estimation # TODO []: move into it's own Sig2Noise computation class self.send_signalquality = send_signalquality self.last_sigquality_ts = None self.last_log_ts = None self.send_sigquality_interval = 1000 # send signal qualities every 1000ms = 1Hz # noise2sig estimate halflife_ms, running-offset, de-trended power self.noise2sig_halflife_ms = (5000, 500) # 10s for offset, .5s for power # TODO [x]: move into a exp-move-ave power est class self.raw_power = None self.preproc_power = None def connect(self, host=None, port=-1, queryifhostnotfound=True): """[make a connection to the utopia host] Args: host ([type], optional): [description]. Defaults to None. port (int, optional): [description]. Defaults to -1. queryifhostnotfound (bool, optional): [description]. Defaults to True. Returns: [type]: [description] """ if host: self.host = host if port > 0: self.port = port self.U.autoconnect(self.host, self.port, timeout_ms=5000, queryifhostnotfound=queryifhostnotfound) if self.U.isConnected: # subscribe to messages: data, stim, mode, selection self.U.sendMessage(Subscribe(None, "DEMSN")) return self.U.isConnected def isConnected(self): """[summary] Returns: [type]: [description] """ return self.U.isConnected if self.U is not None else False def getTimeStamp(self): """[summary] Returns: [type]: [description] """ return self.U.getTimeStamp() def sendMessage(self, msg: UtopiaMessage): """[send a UtopiaMessage to the utopia hub] Args: msg (UtopiaMessage): [description] """ self.U.sendMessage(msg) def getNewMessages(self, timeout_ms=0): """[get new messages from the UtopiaHub] Args: timeout_ms (int, optional): [description]. Defaults to 0. Returns: [type]: [description] """ return self.U.getNewMessages(timeout_ms) def initDataRingBuffer(self): """[initialize the data ring buffer, by getting some seed messages and datapackets to get the data sizes etc.] Returns: [type]: [description] """ print("geting some initial data to setup the ring buffer") # get some initial data to get data shape and sample rate databuf = [] nmsg = 0 iter = 0 data_start_ts = None data_ts = 0 while data_start_ts is None or data_ts - data_start_ts < 3000: msgs = self.getNewMessages(100) for m in msgs: m = self.preprocess_message(m) if m.msgID == DataPacket.msgID: # data-packets are special if len(m.samples) > 0: databuf.append(m) # append raw data if data_start_ts is None: data_start_ts = m.timestamp data_ts = m.timestamp else: print("Huh? got empty data packet: {}".format(m)) else: self.msg_ringbuffer.append(m) self.msg_timestamp = m.timestamp nmsg = nmsg+1 nsamp = [len(m.samples) for m in databuf] data_ts = [ m.timestamp for m in databuf] if self.raw_fs is None: self.raw_fs = np.median( np.array(nsamp[1:]) / np.diff(data_ts) * 1000.0) print('Estimated sample rate {} samp in {} s ={}'.format(sum(nsamp),(data_ts[-1]-data_ts[0])/1000.0,self.raw_fs)) # init the pre-processor (if one) if self.data_preprocessor: self.data_preprocessor.fit(np.array(databuf[0].samples)[0:1,:], fs=self.raw_fs) # tell it the sample rate # apply the data packet pre-processing -- to get the info # on the data state after pre-processing tmpdatabuf = [self.processDataPacket(m) for m in databuf] # strip empty packets tmpdatabuf = [d for d in tmpdatabuf if d.shape[0]>0] # estimate the sample rate of the pre-processed data pp_nsamp = [m.shape[0] for m in tmpdatabuf] pp_ts = [ m[-1,-1] for m in tmpdatabuf] self.fs = np.median( np.array(pp_nsamp[1:]) / np.diff(pp_ts) * 1000.0)# fs = nSamp/time print('Estimated pre-processed sample rate={}'.format(self.fs)) # create the ring buffer, big enough to store the pre-processed data if self.data_ringbuffer: print("Warning: re-init data ring buffer") # TODO []: why does the datatype of the ring buffer matter so much? Is it because of uss? # Answer[]: it's the time-stamps, float32 rounds time-stamps to 24bits self.data_ringbuffer = RingBuffer(maxsize=self.fs*self.datawindow_ms/1000, shape=tmpdatabuf[0].shape[1:], dtype=np.float32) # insert the warmup data into the ring buffer self.data_timestamp=None # reset last seen data nsamp=0 # re-init the preprocessor for consistency with off-line if self.data_preprocessor: self.data_preprocessor.fit(np.array(databuf[0].samples)[0:1,:], fs=self.raw_fs) # use linear trend tracker to de-jitter the sample timestamps if self.sample2timestamp is None or isinstance(self.sample2timestamp,str): self.sample2timestamp = timestamp_interpolation(fs=self.fs, sample2timestamp=self.sample2timestamp) for m in databuf: # apply the pre-processing again (this time with fs estimated) d = self.processDataPacket(m) self.data_ringbuffer.extend(d) nsamp = nsamp + d.shape[0] return (nsamp, nmsg) def initStimulusRingBuffer(self): '''initialize the data ring buffer, by getting some seed messages and datapackets to get the data sizes etc.''' # TODO []: more efficient memory use, with different dtype for 'real' data and the time-stamps? self.stimulus_ringbuffer = RingBuffer(maxsize=self.fs*self.datawindow_ms/1000, shape=(257,), dtype=np.float32) def preprocess_message(self, m:UtopiaMessage): """[apply pre-processing to topia message before any more work] Args: m (UtopiaMessage): [description] Returns: [type]: [description] """ # WARNING BODGE: fit time-stamp in 24bits for float32 ring buffer # Note: this leads to wrap-arroung in (1<<24)/1000/3600 = 4.6 hours # but that shouldn't matter..... m.timestamp = m.timestamp % (1<<24) return m def processDataPacket(self, m: DataPacket): """[pre-process a datapacket message ready to be inserted into the ringbuffer] Args: m (DataPacket): [description] Returns: [type]: [description] """ #print("DP: {}".format(m)) # extract the raw data d = np.array(m.samples, dtype=np.float32) # process as singles # apply the pre-processor, if one was given if self.data_preprocessor: d_raw = d.copy() # warning-- with agressive downsample this may not produce any data! d = self.data_preprocessor.transform(d) # BODGE: running estimate of the electrode-quality, ONLY after initialization! if self.send_signalquality and self.data_ringbuffer is not None: self.update_and_send_ElectrodeQualities(d_raw, d, m.timestamp) #if self.VERBOSITY > 0 and self.data_ringbuffer is not None: # self.plot_raw_preproc_data(d_raw,d,m.timestamp) if d.size > 0 : # If have data to add to the ring-buffer, guarding for time-stamp wrap-around # TODO [ ]: de-jitter and better timestamp interpolation # guard for wrap-around! if self.data_timestamp is not None and m.timestamp < self.data_timestamp: print("Warning: Time-stamp wrap-around detected!!") d = self.add_sample_timestamps(d,m.timestamp,self.fs) # update the last time-stamp tracking self.data_timestamp= m.timestamp return d def add_sample_timestamps(self,d:np.ndarray,timestamp:float,fs:float): """add per-sample timestamp information to the data matrix Args: d (np.ndarray): (t,d) the data matrix to attach time stamps to timestamp (float): the timestamp of the last sample of d fs (float): the nomional sample rate of d Returns: np.ndarray: (t,d+1) data matrix with attached time-stamp channel """ if self.sample2timestamp is not None and not isinstance(self.sample2timestamp,str): sample_ts = self.sample2timestamp.transform(timestamp, len(d)) else: # all the same ts sample_ts = np.ones((len(d),),dtype=int)*timestamp # combine data with timestamps, ensuring type is preserved d = np.append(np.array(d), sample_ts[:, np.newaxis], -1).astype(d.dtype) return d def plot_raw_preproc_data(self, d_raw, d_preproc, ts): """[debugging function to check the diff between the raw and pre-processed data] Args: d_raw ([type]): [description] d_preproc ([type]): [description] ts ([type]): [description] """ if not hasattr(self,'rawringbuffer'): self.preprocringbuffer=RingBuffer(maxsize=self.fs*3,shape=(d_preproc.shape[-1]+1,)) self.rawringbuffer=RingBuffer(maxsize=self.raw_fs*3,shape=(d_raw.shape[-1]+1,)) d_preproc = self.add_sample_timestamps(d_preproc,ts,self.fs) self.preprocringbuffer.extend(d_preproc) d_raw = self.add_sample_timestamps(d_raw,ts,self.raw_fs) self.rawringbuffer.extend(d_raw) if self.last_sigquality_ts is None or ts > self.last_sigquality_ts + self.send_sigquality_interval: import matplotlib.pyplot as plt plt.figure(10);plt.clf(); idx = np.flatnonzero(self.rawringbuffer[:,-1])[0] plt.subplot(211); plt.cla(); plt.plot(self.rawringbuffer[idx:,-1],self.rawringbuffer[idx:,:-1]) idx = np.flatnonzero(self.preprocringbuffer[:,-1])[0] plt.subplot(212); plt.cla(); plt.plot(self.preprocringbuffer[idx:,-1],self.preprocringbuffer[idx:,:-1]) plt.show(block=False) def processStimulusEvent(self, m: StimulusEvent): """[pre-process a StimulusEvent message ready to be inserted into the stimulus ringbuffer] Args: m (StimulusEvent): [description] Returns: [type]: [description] """ # get the vector to hold the stimulus info d = np.zeros((257,),dtype=np.float32) if self.stimulus_ringbuffer is not None and self.stimulus_timestamp is not None: # hold value of used objIDs from previous time stamp d[:] = self.stimulus_ringbuffer[-1,:] # insert the updated state d[m.objIDs] = m.objState d[-1] = m.timestamp # apply the pre-processor, if one was given if self.stimulus_preprocessor: d = self.stimulus_preprocessor.transform(d) # update the last time-stamp tracking self.stimulus_timestamp= m.timestamp return d def update_and_send_ElectrodeQualities(self, d_raw: np.ndarray, d_preproc: np.ndarray, ts: int): """[compute running estimate of electrode qality and stream it] Args: d_raw (np.ndarray): [description] d_preproc (np.ndarray): [description] ts (int): [description] """ raw_power, preproc_power = self.update_electrode_powers(d_raw, d_preproc) # convert to average amplitude raw_amp = np.sqrt(raw_power) preproc_amp = np.sqrt(preproc_power) # noise2signal estimated as removed raw amplitude (assumed=noise) to preprocessed amplitude (assumed=signal) noise2sig = np.maximum(float(1e-6), np.abs(raw_amp - preproc_amp)) / np.maximum(float(1e-8),preproc_amp) # hack - detect disconnected channels noise2sig[ raw_power < 1e-6 ] = 100 # hack - detect filter artifacts = preproc power is too big.. noise2sig[ preproc_amp > raw_amp*10 ] = 100 # hack - cap to 100 noise2sig = np.minimum(noise2sig,100) # rate limit sending of signal-quality messages if self.last_sigquality_ts is None or ts > self.last_sigquality_ts + self.send_sigquality_interval: print("SigQ:\nraw_power=({}/{})\npp_power=({}/{})\nnoise2sig={}".format( raw_amp,d_raw.shape[0], preproc_amp,d_preproc.shape[0], noise2sig)) print("Q",end='') # N.B. use *our* time-stamp for outgoing messages! self.sendMessage(SignalQuality(None, noise2sig)) self.last_sigquality_ts = ts if self.VERBOSITY>2: # plot the sample time-stamp jitter... import matplotlib.pyplot as plt plt.figure(10) ts = self.data_ringbuffer[:,-1] idx = np.flatnonzero(ts) if len(idx)>0: ts = ts[idx[0]:] plt.subplot(211); plt.cla(); plt.plot(np.diff(ts)); plt.title('diff time-sample') plt.subplot(212); plt.cla(); plt.plot((ts-ts[0])-np.arange(len(ts))*1000.0/self.fs); plt.title('regression against sample-number') plt.show(block=False) def update_electrode_powers(self, d_raw: np.ndarray, d_preproc:np.ndarray): """[track exp-weighted-moving average centered power for 2 input streams] Args: d_raw (np.ndarray): [description] d_preproc (np.ndarray): [description] Returns: [type]: [description] """ if self.raw_power is None: mu_hl, pow_hl = self.noise2sig_halflife_ms self.raw_power = power_tracker(mu_hl, pow_hl, self.raw_fs) self.preproc_power = power_tracker(mu_hl, pow_hl, self.fs) self.raw_power.transform(d_raw) self.preproc_power.transform(d_preproc) return (self.raw_power.power(), self.preproc_power.power()) def update(self, timeout_ms=None, mintime_ms=None): '''Update the tracking state w.r.t. the data source By adding data to the data_ringbuffer, stimulus info to the stimulus_ringbuffer, and other messages to the messages ring buffer. Args timeout_ms : int max block waiting for messages before returning mintime_ms : int min time to accumulate messages before returning Returns newmsgs : [newMsgs :UtopiaMessage] list of the *new* utopia messages from the server nsamp: int number of new data samples in this call Note: use data_ringbuffer[-nsamp:,...] to get the new data nstimulus : int number of new stimulus events in this call Note: use stimulus_ringbuffer[-nstimulus:,...] to get the new data ''' if timeout_ms is None: timeout_ms = self.timeout_ms if mintime_ms is None: mintime_ms = self.mintime_ms if not self.isConnected(): self.connect() if not self.isConnected(): return [],0,0 t0 = self.getTimeStamp() nsamp = 0 nmsg = 0 nstimulus = 0 if self.data_ringbuffer is None: # do special init stuff if not done nsamp, nmsg = self.initDataRingBuffer() if self.stimulus_ringbuffer is None: # do special init stuff if not done self.initStimulusRingBuffer() if self.last_log_ts is None: self.last_log_ts = self.getTimeStamp() if t0 is None: t0 = self.getTimeStamp() # record the list of new messages from this call newmsgs = self.newmsgs # start with any left-overs from old calls self.newmsgs=[] # clear the left-over messages stack ttg = timeout_ms - (self.getTimeStamp() - t0) # time-to-go in the update loop while ttg > 0: # rate limit if ttg >= mintime_ms: sleep(mintime_ms/1000.0) ttg = timeout_ms - (self.getTimeStamp() - t0) # udate time-to-go # get the new messages msgs = self.getNewMessages(ttg) # process the messages - basically to split datapackets from the rest print(".",end='') #print("{} in {}".format(len(msgs),self.getTimeStamp()-t0),end='',flush=True) for m in msgs: m = self.preprocess_message(m) print("{:c}".format(m.msgID), end='', flush=True) if m.msgID == DataPacket.msgID: # data-packets are special d = self.processDataPacket(m) # (samp x ...) self.data_ringbuffer.extend(d) nsamp = nsamp + d.shape[0] elif m.msgID == StimulusEvent.msgID: # as are stmiuluse events d = self.processStimulusEvent(m) # (nY x ...) self.stimulus_ringbuffer.append(d) nstimulus = nstimulus + 1 else: # NewTarget/Selection are also special in that they clear stimulus state... if m.msgID == NewTarget.msgID or m.msgID == Selection.msgID : # Make a dummy stim-event to reset all objIDs to off d = self.processStimulusEvent(StimulusEvent(m.timestamp, np.arange(255,dtype=np.int32), np.zeros(255,dtype=np.int8))) self.stimulus_ringbuffer.append(d) self.stimulus_timestamp= m.timestamp if len(self.msg_ringbuffer)>0 and m.timestamp > self.msg_ringbuffer[0].timestamp + self.msgwindow_ms: # slide msg buffer self.msg_ringbuffer.popleft() self.msg_ringbuffer.append(m) newmsgs.append(m) nmsg = nmsg+1 self.msg_timestamp = m.timestamp # update time-to-go ttg = timeout_ms - (self.getTimeStamp() - t0) # new line if self.getTimeStamp() > self.last_log_ts + 2000: print("",flush=True) self.last_log_ts = self.getTimeStamp() # return new messages, and count new samples/stimulus return (newmsgs, nsamp, nstimulus) def push_back_newmsgs(self,oldmsgs): """[put unprocessed messages back onto the newmessages queue] Args: oldmsgs ([type]): [description] """ # TODO []: ensure this preserves message time-stamp order? self.newmsgs.extend(oldmsgs) def extract_data_segment(self, bgn_ts, end_ts=None): """extract a segment of data based on a start and end time-stamp Args: bgn_ts (float): segment start time-stamp end_ts (float, optional): segment end time-stamp. Defaults to None. Returns: (np.ndarray): the data between these time-stamps, or None if timestamps invalid """ return extract_ringbuffer_segment(self.data_ringbuffer,bgn_ts,end_ts) def extract_stimulus_segment(self, bgn_ts, end_ts=None): """extract a segment of the stimulus stream based on a start and end time-stamp Args: bgn_ts (float): segment start time-stamp end_ts (float, optional): segment end time-stamp. Defaults to None. Returns: (np.ndarray): the stimulus events between these time-stamps, or None if timestamps invalid """ return extract_ringbuffer_segment(self.stimulus_ringbuffer,bgn_ts,end_ts) def extract_msgs_segment(self, bgn_ts, end_ts=None): """[extract the messages between start/end time stamps] Args: bgn_ts ([type]): [description] end_ts ([type], optional): [description]. Defaults to None. Returns: [type]: [description] """ msgs = [] # store the trial stimEvents for m in reversed(self.msg_ringbuffer): if m.timestamp <= bgn_ts: # stop as soon as earlier than bgn_ts break if end_ts is None or m.timestamp < end_ts: msgs.append(m) # reverse back to input order msgs.reverse() return msgs def run(self, timeout_ms=30000): """[test run the interface forever, just getting and storing data] Args: timeout_ms (int, optional): [description]. Defaults to 30000. """ t0 = self.getTimeStamp() # test getting 5s data tstart = self.data_timestamp trlen_ms = 5000 while self.getTimeStamp() < t0+timeout_ms: self.update() # test getting a data segment if tstart is None : tstart = self.data_timestamp if tstart and self.data_timestamp > tstart + trlen_ms: X = self.extract_data_segment(tstart, tstart+trlen_ms) print("Got data: {}->{}\n{}".format(tstart, tstart+trlen_ms, X[:, -1])) Y = self.extract_stimulus_segment(tstart, tstart+trlen_ms) print("Got stimulus: {}->{}\n{}".format(tstart, tstart+trlen_ms, Y[:, -1])) tstart = self.data_timestamp + 5000 print('.', flush=True) try: from sklearn.base import TransformerMixin except: # fake the class if sklearn is not available, e.g. Android/iOS class TransformerMixin: def __init__(): pass def fit(self,X): pass def transform(self,X): pass #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- from mindaffectBCI.decoder.utils import sosfilt, butter_sosfilt, sosfilt_zi_warmup class butterfilt_and_downsample(TransformerMixin): """Incremental streaming transformer to provide filtering and downsampling data transformations Args: TransformerMixin ([type]): sklearn compatible transformer """ def __init__(self, stopband=((0,5),(5,-1)), order:int=6, fs:float =250, fs_out:float =60, ftype='butter'): self.stopband = stopband self.fs = fs self.fs_out = fs_out if fs_out is not None and fs_out < fs else fs self.order = order self.axis = -2 if not self.axis == -2: raise ValueError("axis != -2 is not yet supported!") self.nsamp = 0 self.ftype = ftype def fit(self, X, fs:float =None, zi=None): """[summary] Args: X ([type]): [description] fs (float, optional): [description]. Defaults to None. zi ([type], optional): [description]. Defaults to None. Returns: [type]: [description] """ if fs is not None: # parameter overrides stored fs self.fs = fs # preprocess -> spectral filter if isinstance(self.stopband, str): import pickle import os # load coefficients from file -- when scipy isn't available if os.path.isfile(self.stopband): fn = self.stopband else: # try relative to our py file fn = os.path.join(os.path.dirname(os.path.abspath(__file__)),self.stopband) with open(fn,'rb') as f: self.sos_ = pickle.load(f) self.zi_ = pickle.load(f) f.close() # tweak the shape/scale of zi to the actual data shape self.zi_ = sosfilt_zi_warmup(self.zi_, X, self.axis) print("X={} zi={}".format(X.shape,self.zi_.shape)) else: # estimate them from the given information X, self.sos_, self.zi_ = butter_sosfilt(X, self.stopband, self.fs, order=self.order, axis=self.axis, zi=zi, ftype=self.ftype) # preprocess -> downsample self.nsamp = 0 self.resamprate_ = int(round(self.fs*2.0/self.fs_out))/2.0 if self.fs_out is not None else 1 self.out_fs_ = self.fs/self.resamprate_ print("resample: {}->{}hz rsrate={}".format(self.fs, self.out_fs_, self.resamprate_)) return self def transform(self, X, Y=None): """[summary] Args: X ([type]): [description] Y ([type], optional): [description]. Defaults to None. Returns: [type]: [description] """ # propogate the filter coefficients between calls if not hasattr(self,'sos_'): self.fit(X[0:1,:]) if self.sos_ is not None: X, self.zi_ = sosfilt(self.sos_, X, axis=self.axis, zi=self.zi_) nsamp = self.nsamp self.nsamp = self.nsamp + X.shape[self.axis] # track *raw* sample counter # preprocess -> downsample @60hz if self.resamprate_ > 1: # number samples through this cycle due to remainder of last block resamp_start = nsamp%self.resamprate_ # convert to number samples needed to complete this cycle # this is then the sample to take for the next cycle if resamp_start > 0: resamp_start = self.resamprate_ - resamp_start # allow non-integer resample rates idx = np.arange(resamp_start,X.shape[self.axis],self.resamprate_) if self.resamprate_%1 > 0 and idx.size>0 : # non-integer re-sample, interpolate idx_l = np.floor(idx).astype(int) # sample above idx_u = np.ceil(idx).astype(int) # sample below # BODGE: guard for packet ending at sample boundary. idx_u[-1] = idx_u[-1] if idx_u[-1]<X.shape[self.axis] else X.shape[self.axis]-1 w_u = idx - idx_l # linear weight of the upper sample X = X[...,idx_u,:] * w_u[:,np.newaxis] + X[...,idx_l,:] * (1-w_u[:,np.newaxis]) # linear interpolation if Y is not None: Y = Y[...,idx_u,:] * w_u[:,np.newaxis] + Y[...,idx_l,:] * (1-w_u[:,np.newaxis]) else: idx = idx.astype(int) X = X[..., idx, :] # decimate X (trl, samp, d) if Y is not None: Y = Y[..., idx, :] # decimate Y (trl, samp, y) return X if Y is None else (X, Y) @staticmethod def testcase(): ''' test the filt+downsample transformation filter by incremental calling ''' #X=np.cumsum(np.random.randn(100,1),axis=0) X=np.sin(np.arange(100)[:,np.newaxis]*2*np.pi/30) xs = np.arange(X.shape[0])[:,np.newaxis] # high-pass and decimate bands = ((0,20,'bandpass')) fs = 200 fs_out = 130 fds = butterfilt_and_downsample(stopband=bands,fs=fs,fs_out=fs_out) print("single step") fds.fit(X[0:1,:]) m0,xs0 = fds.transform(X,xs) # (samp,ny,ne) print("M0 -> {}".format(m0[:20])) step=6 print("Step size = {}".format(step)) fds.fit(X[0:1,:]) m1=np.zeros(m0.shape,m0.dtype) xs1 = np.zeros(xs0.shape,xs0.dtype) t=0 for i in range(0,len(X),step): idx=np.arange(i,min(i+step,len(X))) mm, idx1=fds.transform(X[idx,:],idx[:,np.newaxis]) m1[t:t+mm.shape[0],:]=mm xs1[t:t+mm.shape[0]]=idx1 t = t +mm.shape[0] print("M1 -> {}".format(m1[:20])) print("diff: {}".format(np.max(np.abs(m0-m1)))) import matplotlib.pyplot as plt plt.plot(xs,X,'*-',label='X') plt.plot(xs0,m0,'*-',label='{} {}->{}Hz single'.format(bands,fs,fs_out)) plt.plot(xs1,m1,'*-',label='{} {}->{}Hz incremental'.format(bands,fs,fs_out)) plt.legend() plt.show() #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- from mindaffectBCI.decoder.stim2event import stim2event class stim2eventfilt(TransformerMixin): ''' Incremental streaming transformer to transform a sequence of stimulus states to a brain event sequence For example by transforming a sequence of stimulus intensities, to rising and falling edge events. ''' def __init__(self, evtlabs=None, histlen=20): self.evtlabs = evtlabs self.histlen = histlen self.prevX = None def fit(self, X): """[summary] Args: X ([type]): [description] Returns: [type]: [description] """ return self def transform(self, X): """[transform Stimulus-encoded to brain-encoded] Args: X ([type]): [description] Returns: [type]: [description] """ if X is None: return None # keep old fitler state for the later transformation call prevX = self.prevX # grab the new filter state (if wanted) if self.histlen>0: #print('prevX={}'.format(prevX)) #print("X={}".format(X)) if X.shape[0] >= self.histlen or prevX is None: self.prevX = X else: self.prevX = np.append(prevX, X, 0) # only keep the last bit -- copy in case gets changed in-place self.prevX = self.prevX[-self.histlen:,:].copy() #print('new_prevX={}'.format(self.prevX)) # convert from stimulus coding to brain response coding, with old state X = stim2event(X, self.evtlabs, axis=-2, oM=prevX) return X def testcase(): ''' test the stimulus transformation filter by incremental calling ''' M=np.array([0,0,0,1,0,0,1,1,0,1])[:,np.newaxis] # samp,nY s2ef = stim2eventfilt(evtlabs=('re','fe'),histlen=3) print("single step") m0=s2ef.transform(M) # (samp,ny,ne) print("{} -> {}".format(M,m0)) print("Step size = 1") m1=np.zeros(m0.shape,m0.dtype) for i in range(len(M)): idx=slice(i,i+1) mm=s2ef.transform(M[idx,:]) m1[idx,...]=mm print("{} {} -> {}".format(i,M[idx,...],mm)) print("Step size=4") m4=np.zeros(m0.shape,m0.dtype) for i in range(0,len(M),4): idx=slice(i,i+4) mm=s2ef.transform(M[idx,:]) m4[idx,...]=mm print("{} {} -> {}".format(i,M[idx,...],mm)) print("m0={}\nm1={}\n,m4={}\n".format(m0,m1,m4)) #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- class power_tracker(TransformerMixin): """Incremental streaming transformer from raw n-channel data, to exponientially smoothed channel powers Args: TransformerMixin ([type]): sklearn compatiable transformer """ def __init__(self,halflife_mu_ms, halflife_power_ms, fs, car=True): # convert to per-sample decay factor self.alpha_mu = self.hl2alpha(fs * halflife_mu_ms / 1000.0 ) self.alpha_power= self.hl2alpha(fs * halflife_power_ms / 1000.0 ) self.car = car self.sX_N = None self.sX = None self.sXX_N = None self.sXX = None def hl2alpha(self,hl): """[summary] Args: hl ([type]): [description] Returns: [type]: [description] """ return np.exp(np.log(.5)/hl) def fit(self,X): """[summary] Args: X ([type]): [description] Returns: [type]: [description] """ self.sX_N = X.shape[0] if self.car and X.shape[-1]>4: X = X.copy() - np.mean(X,-1,keepdims=True) self.sX = np.sum(X,axis=0) self.sXX_N = X.shape[0] self.sXX = np.sum((X-(self.sX/self.sX_N))**2,axis=0) return self.power() def transform(self, X: np.ndarray): """[compute the exponientially weighted centered power of X] Args: X (np.ndarray): [description] Returns: [type]: [description] """ if self.sX is None: # not fitted yet! return self.fit(X) if self.car and X.shape[-1]>4: ch_power = self.power() # identify the active channels, i.e. are attached and have some signal act_ch = ch_power > np.max(ch_power)*1e-3 X = X.copy() - np.mean(X[...,act_ch], -1, keepdims=True) # compute updated mean alpha_mu = self.alpha_mu ** X.shape[0] self.sX_N = self.sX_N*alpha_mu + X.shape[0] self.sX = self.sX*alpha_mu + np.sum(X, axis=0) # center and compute updated power alpha_pow = self.alpha_power ** X.shape[0] self.sXX_N = self.sXX_N*alpha_pow + X.shape[0] self.sXX = self.sXX*alpha_pow + np.sum((X-(self.sX/self.sX_N))**2, axis=0) return self.power() def mean(self): """[summary] Returns: [type]: [description] """ return self.sX / self.sX_N def power(self): """[summary] Returns: [type]: [description] """ return self.sXX / self.sXX_N def testcase(self): """[summary] """ import matplotlib.pyplot as plt X = np.random.randn(10000,2) #X = np.cumsum(X,axis=0) pt = power_tracker(100,100,100) print("All at once: power={}".format(pt.transform(X))) # all at once pt = power_tracker(100,1000,1000) print("alpha_mu={} alpha_pow={}".format(pt.alpha_mu,pt.alpha_power) ) step = 30 idxs = list(range(step,X.shape[0],step)) powers = np.zeros((len(idxs),X.shape[-1])) mus = np.zeros((len(idxs),X.shape[-1])) for i,j in enumerate(idxs): powers[i,:] = np.sqrt(pt.transform(X[j-step:j,:])) mus[i,:]=pt.mean() for d in range(X.shape[-1]): plt.subplot(X.shape[-1],1,d+1) plt.plot(X[:,d]) plt.plot(idxs,mus[:,d]) plt.plot(idxs,powers[:,d]) #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- class timestamp_interpolation(TransformerMixin): """Incremental streaming tranformer to transform from per-packet time-stamps to per-sample timestamps with time-stamp smoothing, de-jittering, and dropped-sample detection. """ def __init__(self,fs=None,sample2timestamp=None, max_delta=200): """tranform from per-packet (i.e. multiple-samples) to per-sample timestamps Args: fs (float): default sample rate, used when no other timing info is available sample2timestamp (transformer, optional): class to de-jitter timestamps based on sample-count. Defaults to None. """ self.fs=fs a0 = 1000/self.fs if self.fs is not None else 1 # BODGE: special cases for particular mapping functions so can include the prior slope if sample2timestamp=='lower_bound_tracker': self.sample2timestamp = lower_bound_tracker(a0=a0) elif sample2timestamp=='linear_trend_tracker': self.sample2timestamp = linear_trend_tracker(a0=a0) else: self.sample2timestamp = sample2timestamp self.max_delta = max_delta def fit(self,ts,nsamp=1): """[summary] Args: ts ([type]): [description] nsamp (int, optional): [description]. Defaults to 1. """ self.last_sample_timestamp_ = ts self.n_ = 0 def transform(self,timestamp:float,nsamp:int=1): """add per-sample timestamp information to the data matrix Args: timestamp (float): the timestamp of the last sample of d nsamp(int): number of samples to interpolate Returns: np.ndarray: (nsamp) the interpolated time-stamps """ if not hasattr(self,'last_sample_timestamp_'): self.fit(timestamp,nsamp) # update tracking number samples processed self.n_ = self.n_ + nsamp if self.last_sample_timestamp_ < timestamp or self.sample2timestamp is not None: # update the tracker for the sample-number to sample timestamp mapping if self.sample2timestamp is not None: #print("n={} ts={}".format(n,timestamp)) newtimestamp = self.sample2timestamp.transform(self.n_, timestamp) #print("ts={} newts={} diff={}".format(timestamp,newtimestamp,timestamp-newtimestamp)) # use the corrected de-jittered time-stamp -- if it's not tooo different if abs(timestamp-newtimestamp) < self.max_delta: timestamp = int(newtimestamp) # simple linear interpolation for the sample time-stamps samples_ts = np.linspace(self.last_sample_timestamp_, timestamp, nsamp+1, endpoint=True, dtype=int) samples_ts = samples_ts[1:] else: if self.fs : # interpolate with the estimated sample rate samples_ts = np.arange(-nsamp+1,1,dtype=int)*(1000/self.fs) + timestamp else: # give all same timestamp samples_ts = np.ones(nsamp,dtype=int)*timestamp # update the tracking info self.last_sample_timestamp_ = timestamp return samples_ts def testcase(self, npkt=1000, fs=100): """[summary] Args: npkt (int, optional): [description]. Defaults to 1000. fs (int, optional): [description]. Defaults to 100. """ # generate random packet sizes nsamp = np.random.random_integers(0,10,size=(npkt,)) # generate true sample timestamps ts_true = np.arange(np.sum(nsamp))*1000/fs # packet end indices idx = np.cumsum(nsamp)-1 # packet end time-stamps pkt_ts = ts_true[idx] # add some time-stamp jitter, always positive.. pkt_ts = pkt_ts + np.random.uniform(0,.5*1000/fs,size=pkt_ts.shape) # apply the time-stamp interplotation sts=[] tsfn = timestamp_interpolation(fs=fs,sample2timestamp = 'lower_bound_tracker') for i,(n,t) in enumerate(zip(nsamp,pkt_ts)): samp_ts = tsfn.transform(t,n) sts.extend(samp_ts) # plot the result. import matplotlib.pyplot as plt plt.plot(ts_true - sts) plt.show() #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- from mindaffectBCI.decoder.preprocess import temporally_decorrelate class temporal_decorrelator(TransformerMixin): """Incremental streaming tranformer to decorrelate temporally channels in an input stream """ def __init__(self, order=10, reg=1e-4, eta=1e-5, axis=-2): self.reg=reg self.eta=eta self.axis=axis def fit(self,X): """[summary] Args: X ([type]): [description] """ self.W_ = np.zeros((self.order,X.shape[-1]),dtype=X.dtype) self.W_[-1,:]=1 _, self.W_ = self.transform(X[1:,:]) def transform(self,X): """add per-sample timestamp information to the data matrix Args: X (float): the data to decorrelate nsamp(int): number of samples to interpolate Returns: np.ndarray: the decorrelated data """ if not hasattr(self,'W_'): self.fit(X) X, self.W_ = temporally_decorrelate(X, W=self.W_, reg=self.reg, eta=self.eta, axis=self.axis) return X def testcase(self, dur=3, fs=100, blksize=10): """[summary] Args: dur (int, optional): [description]. Defaults to 3. fs (int, optional): [description]. Defaults to 100. blksize (int, optional): [description]. Defaults to 10. """ import numpy as np import matplotlib.pyplot as plt from mindaffectBCI.decoder.preprocess import plot_grand_average_spectrum fs=100 X = np.random.standard_normal((2,fs*dur,2)) # flat spectrum #X = X + np.sin(np.arange(X.shape[-2])*2*np.pi/10)[:,np.newaxis] X = X[:,:-1,:]+X[:,1:,:] # weak low-pass #X = np.cumsum(X,-2) # 1/f spectrum print("X={}".format(X.shape)) plt.figure(1) plot_grand_average_spectrum(X, fs) plt.suptitle('Raw') plt.show(block=False) tdc = temporal_decorrelator() wX = np.zeros(X.shape,X.dtype) for i in range(0,X.shape[-1],blksize): idx = range(i,i+blksize) wX[idx,:] = tdc.transform(X[idx,:]) # compare raw vs summed filterbank plt.figure(2) plot_grand_average_spectrum(wX,fs) plt.suptitle('Decorrelated') plt.show() #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- from mindaffectBCI.decoder.preprocess import standardize_channel_power class channel_power_standardizer(TransformerMixin): """Incremental streaming tranformer to channel power normalization in an input stream """ def __init__(self, reg=1e-4, axis=-2): self.reg=reg self.axis=axis def fit(self,X): """[summary] Args: X ([type]): [description] """ self.sigma2_ = np.zeros((X.shape[-1],), dtype=X.dtype) self.sigma2_ = X[0,:]*X[0,:] # warmup with 1st sample power self.transform(X[1:,:]) def transform(self,X): """add per-sample timestamp information to the data matrix Args: X (float): the data to decorrelate Returns: np.ndarray: the decorrelated data """ if not hasattr(self,'sigma2_'): self.fit(X) X, self.W_ = standardize_channel_power(X, sigma2=self.sigma2_, reg=self.reg, axis=self.axis) return X def testcase(self, dur=3, fs=100, blksize=10): """[summary] Args: dur (int, optional): [description]. Defaults to 3. fs (int, optional): [description]. Defaults to 100. blksize (int, optional): [description]. Defaults to 10. """ import numpy as np import matplotlib.pyplot as plt from mindaffectBCI.decoder.preprocess import plot_grand_average_spectrum fs=100 X = np.random.standard_normal((2,fs*dur,2)) # flat spectrum #X = X + np.sin(np.arange(X.shape[-2])*2*np.pi/10)[:,np.newaxis] X = X[:,:-1,:]+X[:,1:,:] # weak low-pass #X = np.cumsum(X,-2) # 1/f spectrum print("X={}".format(X.shape)) plt.figure(1) plot_grand_average_spectrum(X, fs) plt.suptitle('Raw') plt.show(block=False) cps = channel_power_standardizer() wX = np.zeros(X.shape,X.dtype) for i in range(0,X.shape[-1],blksize): idx = range(i,i+blksize) wX[idx,:] = cps.transform(X[idx,:]) # compare raw vs summed filterbank plt.figure(2) plot_grand_average_spectrum(wX,fs) plt.suptitle('Decorrelated') plt.show() def testRaw(): """[summary] """ # test with raw ui = UtopiaDataInterface() ui.connect() sigViewer(ui,30000) # 30s sigviewer def testPP(): """[summary] """ from sigViewer import sigViewer # test with a filter + downsampler ppfn= butterfilt_and_downsample(order=4, stopband=((0,1),(25,-1)), fs_out=100) #ppfn= butterfilt_and_downsample(order=4, stopband='butter_stopband((0, 5), (25, -1))_fs200.pk', fs_out=80) ui = UtopiaDataInterface(data_preprocessor=ppfn, stimulus_preprocessor=None) ui.connect() sigViewer(ui) def testFileProxy(filename,fs_out=999): """[summary] Args: filename ([type]): [description] fs_out (int, optional): [description]. Defaults to 999. """ from mindaffectBCI.decoder.FileProxyHub import FileProxyHub U = FileProxyHub(filename) from sigViewer import sigViewer # test with a filter + downsampler #ppfn= butterfilt_and_downsample(order=4, stopband=((0,3),(25,-1)), fs_out=fs_out) ppfn= butterfilt_and_downsample(order=4, stopband=(1,15,'bandpass'), fs_out=fs_out) #ppfn = None ui = UtopiaDataInterface(data_preprocessor=ppfn, stimulus_preprocessor=None, mintime_ms=0, U=U) ui.connect() sigViewer(ui) def testFileProxy2(filename): """[summary] Args: filename ([type]): [description] """ from mindaffectBCI.decoder.FileProxyHub import FileProxyHub U = FileProxyHub(filename) fs = 200 fs_out = 200 # test with a filter + downsampler ppfn= butterfilt_and_downsample(order=4, stopband=((45,65),(0,3),(25,-1)), fs=fs, fs_out=fs_out) ui = UtopiaDataInterface(data_preprocessor=ppfn, stimulus_preprocessor=None, mintime_ms=0, U=U, fs=fs) ui.connect() # run in bits.. data=[] stim=[] emptycount = 0 while True: newmsg, nsamp, nstim = ui.update() if len(newmsg) == 0 and nsamp == 0 and nstim == 0: emptycount = emptycount + 1 if emptycount > 10: break else: emptycount=0 if nsamp > 0: data.append(ui.data_ringbuffer[-nsamp:,:].copy()) if nstim > 0: stim.append(ui.stimulus_ringbuffer[-nstim:,:].copy()) # convert to single data block data = np.vstack(data) stim = np.vstack(stim) # dump as pickle import pickle if ppfn is None: pickle.dump(dict(data=data,stim=stim),open('raw_udi.pk','wb')) else: pickle.dump(dict(data=data,stim=stim),open('pp_udi.pk','wb')) def testERP(): """[summary] """ ui = UtopiaDataInterface() ui.connect() erpViewer(ui,evtlabs=None) # 30s sigviewer def testElectrodeQualities(X,fs=200,pktsize=20): """[summary] Args: X ([type]): [description] fs (int, optional): [description]. Defaults to 200. pktsize (int, optional): [description]. Defaults to 20. Returns: [type]: [description] """ # recurse if more dims than we want... if X.ndim>2: sigq=[] for i in range(X.shape[0]): sigqi = testElectrodeQualities(X[i,...],fs,pktsize) sigq.append(sigqi) sigq=np.concatenate(sigq,0) return sigq ppfn= butterfilt_and_downsample(order=6, stopband='butter_stopband((0, 5), (25, -1))_fs200.pk', fs_out=100) ppfn.fit(X[:10,:],fs=200) noise2sig = np.zeros((int(X.shape[0]/pktsize),X.shape[-1]),dtype=np.float32) for pkti in range(noise2sig.shape[0]): t = pkti*pktsize Xi = X[t:t+pktsize,:] Xip = ppfn.transform(Xi) raw_power, preproc_power = UtopiaDataInterface.update_electrode_powers(Xi,Xip) noise2sig[pkti,:] = np.maximum(float(1e-6), (raw_power - preproc_power)) / np.maximum(float(1e-8),preproc_power) return noise2sig if __name__ == "__main__": #timestamp_interpolation().testcase() #butterfilt_and_downsample.testcase() #testRaw() #testPP() #testERP() filename="~/Desktop/mark/mindaffectBCI_*.txt" testFileProxy(filename) #testFileProxy2(filename) # "C:\\Users\\Developer\\Downloads\\mark\\mindaffectBCI_brainflow_200911_1229_90cal.txt") #"..\..\Downloads\khash\mindaffectBCI_noisetag_bci_200907_1433.txt"
38.649677
150
0.566207
[ "MIT" ]
CkiChen/pymindaffectBCI
mindaffectBCI/decoder/UtopiaDataInterface.py
53,839
Python
""" Module to read / write wav files using NumPy arrays Functions --------- `read`: Return the sample rate (in samples/sec) and data from a WAV file. `write`: Write a NumPy array as a WAV file. """ from __future__ import division, print_function, absolute_import import sys import numpy import struct import warnings __all__ = [ 'WavFileWarning', 'read', 'write' ] class WavFileWarning(UserWarning): pass WAVE_FORMAT_PCM = 0x0001 WAVE_FORMAT_IEEE_FLOAT = 0x0003 WAVE_FORMAT_EXTENSIBLE = 0xfffe KNOWN_WAVE_FORMATS = (WAVE_FORMAT_PCM, WAVE_FORMAT_IEEE_FLOAT) # assumes file pointer is immediately # after the 'fmt ' id def _read_fmt_chunk(fid, is_big_endian): """ Returns ------- size : int size of format subchunk in bytes (minus 8 for "fmt " and itself) format_tag : int PCM, float, or compressed format channels : int number of channels fs : int sampling frequency in samples per second bytes_per_second : int overall byte rate for the file block_align : int bytes per sample, including all channels bit_depth : int bits per sample """ if is_big_endian: fmt = '>' else: fmt = '<' size = res = struct.unpack(fmt+'I', fid.read(4))[0] bytes_read = 0 if size < 16: raise ValueError("Binary structure of wave file is not compliant") res = struct.unpack(fmt+'HHIIHH', fid.read(16)) bytes_read += 16 format_tag, channels, fs, bytes_per_second, block_align, bit_depth = res if format_tag == WAVE_FORMAT_EXTENSIBLE and size >= (16+2): ext_chunk_size = struct.unpack(fmt+'H', fid.read(2))[0] bytes_read += 2 if ext_chunk_size >= 22: extensible_chunk_data = fid.read(22) bytes_read += 22 raw_guid = extensible_chunk_data[2+4:2+4+16] # GUID template {XXXXXXXX-0000-0010-8000-00AA00389B71} (RFC-2361) # MS GUID byte order: first three groups are native byte order, # rest is Big Endian if is_big_endian: tail = b'\x00\x00\x00\x10\x80\x00\x00\xAA\x00\x38\x9B\x71' else: tail = b'\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71' if raw_guid.endswith(tail): format_tag = struct.unpack(fmt+'I', raw_guid[:4])[0] else: raise ValueError("Binary structure of wave file is not compliant") if format_tag not in KNOWN_WAVE_FORMATS: raise ValueError("Unknown wave file format") # move file pointer to next chunk if size > (bytes_read): fid.read(size - bytes_read) return (size, format_tag, channels, fs, bytes_per_second, block_align, bit_depth) # assumes file pointer is immediately after the 'data' id def _read_data_chunk(fid, format_tag, channels, bit_depth, is_big_endian, mmap=False): if is_big_endian: fmt = '>I' else: fmt = '<I' # Size of the data subchunk in bytes size = struct.unpack(fmt, fid.read(4))[0] # Number of bytes per sample bytes_per_sample = bit_depth//8 if bit_depth == 8: dtype = 'u1' else: if is_big_endian: dtype = '>' else: dtype = '<' if format_tag == WAVE_FORMAT_PCM: dtype += 'i%d' % bytes_per_sample else: dtype += 'f%d' % bytes_per_sample if not mmap: data = numpy.frombuffer(fid.read(size), dtype=dtype) else: start = fid.tell() data = numpy.memmap(fid, dtype=dtype, mode='c', offset=start, shape=(size//bytes_per_sample,)) fid.seek(start + size) if channels > 1: data = data.reshape(-1, channels) return data def _skip_unknown_chunk(fid, is_big_endian): if is_big_endian: fmt = '>I' else: fmt = '<I' data = fid.read(4) # call unpack() and seek() only if we have really read data from file # otherwise empty read at the end of the file would trigger # unnecessary exception at unpack() call # in case data equals somehow to 0, there is no need for seek() anyway if data: size = struct.unpack(fmt, data)[0] fid.seek(size, 1) def _read_riff_chunk(fid): str1 = fid.read(4) # File signature if str1 == b'RIFF': is_big_endian = False fmt = '<I' elif str1 == b'RIFX': is_big_endian = True fmt = '>I' else: # There are also .wav files with "FFIR" or "XFIR" signatures? raise ValueError("File format {}... not " "understood.".format(repr(str1))) # Size of entire file file_size = struct.unpack(fmt, fid.read(4))[0] + 8 str2 = fid.read(4) if str2 != b'WAVE': raise ValueError("Not a WAV file.") return file_size, is_big_endian def read(filename, mmap=False): """ Open a WAV file Return the sample rate (in samples/sec) and data from a WAV file. Parameters ---------- filename : string or open file handle Input wav file. mmap : bool, optional Whether to read data as memory-mapped. Only to be used on real files (Default: False). .. versionadded:: 0.12.0 Returns ------- rate : int Sample rate of wav file. data : numpy array Data read from wav file. Data-type is determined from the file; see Notes. Notes ----- This function cannot read wav files with 24-bit data. Common data types: [1]_ ===================== =========== =========== ============= WAV format Min Max NumPy dtype ===================== =========== =========== ============= 32-bit floating-point -1.0 +1.0 float32 32-bit PCM -2147483648 +2147483647 int32 16-bit PCM -32768 +32767 int16 8-bit PCM 0 255 uint8 ===================== =========== =========== ============= Note that 8-bit PCM is unsigned. References ---------- .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming Interface and Data Specifications 1.0", section "Data Format of the Samples", August 1991 http://www.tactilemedia.com/info/MCI_Control_Info.html Examples -------- >>> from os.path import dirname, join as pjoin >>> import scipy.io as sio Get the filename for an example .wav file from the tests/data directory. >>> data_dir = pjoin(dirname(sio.__file__), 'tests', 'data') >>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav') Load the .wav file contents. >>> samplerate, data = sio.wavfile.read(wav_fname) >>> print(f"number of channels = {data.shape[1]}") number of channels = 2 >>> length = data.shape[0] / samplerate >>> print(f"length = {length}s") length = 0.01s Plot the waveform. >>> import matplotlib.pyplot as plt >>> import numpy as np >>> time = np.linspace(0., length, data.shape[0]) >>> plt.plot(time, data[:, 0], label="Left channel") >>> plt.plot(time, data[:, 1], label="Right channel") >>> plt.legend() >>> plt.xlabel("Time [s]") >>> plt.ylabel("Amplitude") >>> plt.show() """ if hasattr(filename, 'read'): fid = filename mmap = False else: fid = open(filename, 'rb') try: file_size, is_big_endian = _read_riff_chunk(fid) fmt_chunk_received = False data_chunk_received = False channels = 1 bit_depth = 8 format_tag = WAVE_FORMAT_PCM while fid.tell() < file_size: # read the next chunk chunk_id = fid.read(4) if not chunk_id: if data_chunk_received: # End of file but data successfully read warnings.warn( "Reached EOF prematurely; finished at {:d} bytes, " "expected {:d} bytes from header." .format(fid.tell(), file_size), WavFileWarning, stacklevel=2) break else: raise ValueError("Unexpected end of file.") elif len(chunk_id) < 4: raise ValueError("Incomplete wav chunk.") if chunk_id == b'fmt ': fmt_chunk_received = True fmt_chunk = _read_fmt_chunk(fid, is_big_endian) format_tag, channels, fs = fmt_chunk[1:4] bit_depth = fmt_chunk[6] if bit_depth not in (8, 16, 32, 64, 96, 128): raise ValueError("Unsupported bit depth: the wav file " "has {}-bit data.".format(bit_depth)) elif chunk_id == b'fact': _skip_unknown_chunk(fid, is_big_endian) elif chunk_id == b'data': data_chunk_received = True if not fmt_chunk_received: raise ValueError("No fmt chunk before data") data = _read_data_chunk(fid, format_tag, channels, bit_depth, is_big_endian, mmap) elif chunk_id == b'LIST': # Someday this could be handled properly but for now skip it _skip_unknown_chunk(fid, is_big_endian) elif chunk_id in (b'JUNK', b'Fake'): # Skip alignment chunks without warning _skip_unknown_chunk(fid, is_big_endian) else: warnings.warn("Chunk (non-data) not understood, skipping it.", WavFileWarning, stacklevel=2) _skip_unknown_chunk(fid, is_big_endian) finally: if not hasattr(filename, 'read'): fid.close() else: fid.seek(0) return fs, data def write(filename, rate, data): """ Write a NumPy array as a WAV file. Parameters ---------- filename : string or open file handle Output wav file. rate : int The sample rate (in samples/sec). data : ndarray A 1-D or 2-D NumPy array of either integer or float data-type. Notes ----- * Writes a simple uncompressed WAV file. * To write multiple-channels, use a 2-D array of shape (Nsamples, Nchannels). * The bits-per-sample and PCM/float will be determined by the data-type. Common data types: [1]_ ===================== =========== =========== ============= WAV format Min Max NumPy dtype ===================== =========== =========== ============= 32-bit floating-point -1.0 +1.0 float32 32-bit PCM -2147483648 +2147483647 int32 16-bit PCM -32768 +32767 int16 8-bit PCM 0 255 uint8 ===================== =========== =========== ============= Note that 8-bit PCM is unsigned. References ---------- .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming Interface and Data Specifications 1.0", section "Data Format of the Samples", August 1991 http://www.tactilemedia.com/info/MCI_Control_Info.html Examples -------- Create a 100Hz sine wave, sampled at 44100Hz. Write to 16-bit PCM, Mono. >>> from scipy.io.wavfile import write >>> samplerate = 44100; fs = 100 >>> t = np.linspace(0., 1., samplerate) >>> amplitude = np.iinfo(np.int16).max >>> data = amplitude * np.sin(2. * np.pi * fs * t) >>> write("example.wav", samplerate, data) """ if hasattr(filename, 'write'): fid = filename else: fid = open(filename, 'wb') fs = rate try: dkind = data.dtype.kind if not (dkind == 'i' or dkind == 'f' or (dkind == 'u' and data.dtype.itemsize == 1)): raise ValueError("Unsupported data type '%s'" % data.dtype) header_data = b'' header_data += b'RIFF' header_data += b'\x00\x00\x00\x00' header_data += b'WAVE' # fmt chunk header_data += b'fmt ' if dkind == 'f': format_tag = WAVE_FORMAT_IEEE_FLOAT else: format_tag = WAVE_FORMAT_PCM if data.ndim == 1: channels = 1 else: channels = data.shape[1] bit_depth = data.dtype.itemsize * 8 bytes_per_second = fs*(bit_depth // 8)*channels block_align = channels * (bit_depth // 8) fmt_chunk_data = struct.pack('<HHIIHH', format_tag, channels, fs, bytes_per_second, block_align, bit_depth) if not (dkind == 'i' or dkind == 'u'): # add cbSize field for non-PCM files fmt_chunk_data += b'\x00\x00' header_data += struct.pack('<I', len(fmt_chunk_data)) header_data += fmt_chunk_data # fact chunk (non-PCM files) if not (dkind == 'i' or dkind == 'u'): header_data += b'fact' header_data += struct.pack('<II', 4, data.shape[0]) # check data size (needs to be immediately before the data chunk) if ((len(header_data)-4-4) + (4+4+data.nbytes)) > 0xFFFFFFFF: raise ValueError("Data exceeds wave file size limit") fid.write(header_data) # data chunk fid.write(b'data') fid.write(struct.pack('<I', data.nbytes)) if data.dtype.byteorder == '>' or (data.dtype.byteorder == '=' and sys.byteorder == 'big'): data = data.byteswap() _array_tofile(fid, data) # Determine file size and place it in correct # position at start of the file. size = fid.tell() fid.seek(4) fid.write(struct.pack('<I', size-8)) finally: if not hasattr(filename, 'write'): fid.close() else: fid.seek(0) if sys.version_info[0] >= 3: def _array_tofile(fid, data): # ravel gives a c-contiguous buffer fid.write(data.ravel().view('b').data) else: def _array_tofile(fid, data): fid.write(data.tostring())
31.334783
78
0.548009
[ "BSD-3-Clause" ]
AKuederle/scipy
scipy/io/wavfile.py
14,414
Python
def module_name(): print("Soy el módulo 4") if __name__ == "__main__": print(module_name())
20
28
0.65
[ "MIT" ]
soytupadrrre/Master_Python_Eip
programacion_avanzada/06.paquetes_y_modulos/package/sub_package2/mod4.py
101
Python
class Config: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') ACL = 'public-read' FLASKS3_BUCKET_NAME = os.environ.get('FLASKS3_BUCKET_NAME') FLASKS3_REGION = os.environ.get('FLASKS3_REGION')
47.166667
67
0.756184
[ "MIT" ]
adrianaarcia/YPool
serverless/flask-server/config.py
283
Python