hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
f72d0628837767bf0423dbc36d367e46cce6f424
3,323
py
Python
src/logistic_regression.py
MehdiAbbanaBennani/statistical-optimisation
0de96661ca7ab857639ad14127b97af39321762e
[ "MIT" ]
null
null
null
src/logistic_regression.py
MehdiAbbanaBennani/statistical-optimisation
0de96661ca7ab857639ad14127b97af39321762e
[ "MIT" ]
null
null
null
src/logistic_regression.py
MehdiAbbanaBennani/statistical-optimisation
0de96661ca7ab857639ad14127b97af39321762e
[ "MIT" ]
null
null
null
import numpy as np from tqdm import tqdm from gradient import Gradient class LogisticRegression: def __init__(self, type, mu, gradient_param, data, d=100, theta=None): if theta is None: self.theta = np.random.rand(d) * 2 - 1 else: self.theta = theta self.type = type self.gradient = Gradient(gradient_param) self.mat = data self.n_samples = data["Xtrain"].shape[0] self.mu = mu @staticmethod def sigmoid(z): return 1 / (1 + np.exp(- z)) def error(self, X, y_true): N = len(y_true) return sum([self.single_error(X[i], y_true[i]) for i in range(N)]) / N def single_error(self, X, y_true): # y_pred = round(self.predict(X)) y_pred = self.predict_label(X) return abs(y_true - y_pred) / 2 def loss(self, X, y_true): N = len(y_true) return sum([self.single_loss(X[i], y_true[i]) for i in range(N)]) / N def single_loss(self, X, y_true): y_pred = self.predict(X) if self.type == "square": return (y_pred - y_true) ** 2 if self.type == "logistic": return np.log(1 + np.exp(- y_true * y_pred)) # return - y_true * np.log(y_pred) - (1 - y_true) * np.log(1 - y_pred) def predict(self, X): # return self.sigmoid(np.dot(X, self.theta)) return np.dot(X, self.theta) def predict_label(self, X): y_pred = self.predict(X) if y_pred < 0 : return -1 else : return 1 def log(self, log_dict, it, log_freq): log_dict["train_losses"].append(self.loss(X=self.mat["Xtrain"], y_true=self.mat["ytrain"])) log_dict["test_losses"].append(self.loss(X=self.mat["Xtest"], y_true=self.mat["ytest"])) log_dict["train_errors"].append(self.error(X=self.mat["Xtrain"], y_true=self.mat["ytrain"])) log_dict["test_errors"].append(self.error(X=self.mat["Xtest"], y_true=self.mat["ytest"])) if log_freq == "epoch" : log_dict["iterations"].append(it / self.n_samples) else : log_dict["iterations"].append(it) def compute_n_iter(self, n_epoch): return n_epoch * (self.n_samples // self.gradient.batch_size) def log_freq_to_iter(self, log_freq): if log_freq == "epoch" : return self.n_samples else : return log_freq def run_optimizer(self, n_epoch, log_freq, optimizer): log_dict = {"train_losses": [], "test_losses": [], "iterations": [], "train_errors": [], "test_errors": []} n_iter = self.compute_n_iter(n_epoch) for it in tqdm(range(n_iter)): if optimizer == "sgd" : self.gradient.sgd_step(model=self, it=it) if optimizer == "sag": self.gradient.sag_step(model=self, it=it) if it % self.log_freq_to_iter(log_freq) == 0: self.log(log_dict, it, log_freq) return log_dict
33.908163
82
0.520012
import numpy as np from tqdm import tqdm from gradient import Gradient class LogisticRegression: def __init__(self, type, mu, gradient_param, data, d=100, theta=None): if theta is None: self.theta = np.random.rand(d) * 2 - 1 else: self.theta = theta self.type = type self.gradient = Gradient(gradient_param) self.mat = data self.n_samples = data["Xtrain"].shape[0] self.mu = mu @staticmethod def sigmoid(z): return 1 / (1 + np.exp(- z)) def error(self, X, y_true): N = len(y_true) return sum([self.single_error(X[i], y_true[i]) for i in range(N)]) / N def single_error(self, X, y_true): y_pred = self.predict_label(X) return abs(y_true - y_pred) / 2 def loss(self, X, y_true): N = len(y_true) return sum([self.single_loss(X[i], y_true[i]) for i in range(N)]) / N def single_loss(self, X, y_true): y_pred = self.predict(X) if self.type == "square": return (y_pred - y_true) ** 2 if self.type == "logistic": return np.log(1 + np.exp(- y_true * y_pred)) def predict(self, X): return np.dot(X, self.theta) def predict_label(self, X): y_pred = self.predict(X) if y_pred < 0 : return -1 else : return 1 def log(self, log_dict, it, log_freq): log_dict["train_losses"].append(self.loss(X=self.mat["Xtrain"], y_true=self.mat["ytrain"])) log_dict["test_losses"].append(self.loss(X=self.mat["Xtest"], y_true=self.mat["ytest"])) log_dict["train_errors"].append(self.error(X=self.mat["Xtrain"], y_true=self.mat["ytrain"])) log_dict["test_errors"].append(self.error(X=self.mat["Xtest"], y_true=self.mat["ytest"])) if log_freq == "epoch" : log_dict["iterations"].append(it / self.n_samples) else : log_dict["iterations"].append(it) def compute_n_iter(self, n_epoch): return n_epoch * (self.n_samples // self.gradient.batch_size) def log_freq_to_iter(self, log_freq): if log_freq == "epoch" : return self.n_samples else : return log_freq def run_optimizer(self, n_epoch, log_freq, optimizer): log_dict = {"train_losses": [], "test_losses": [], "iterations": [], "train_errors": [], "test_errors": []} n_iter = self.compute_n_iter(n_epoch) for it in tqdm(range(n_iter)): if optimizer == "sgd" : self.gradient.sgd_step(model=self, it=it) if optimizer == "sag": self.gradient.sag_step(model=self, it=it) if it % self.log_freq_to_iter(log_freq) == 0: self.log(log_dict, it, log_freq) return log_dict
true
true
f72d0638d4148f7ac1513563b596e331e42a1b8a
1,461
py
Python
Advance_Python/Linked_List/Search_Ele_In_SLL.py
siddharth-143/Python
293f4643a3a13e3b82d23fd8922db54dbb0f12bc
[ "MIT" ]
null
null
null
Advance_Python/Linked_List/Search_Ele_In_SLL.py
siddharth-143/Python
293f4643a3a13e3b82d23fd8922db54dbb0f12bc
[ "MIT" ]
null
null
null
Advance_Python/Linked_List/Search_Ele_In_SLL.py
siddharth-143/Python
293f4643a3a13e3b82d23fd8922db54dbb0f12bc
[ "MIT" ]
null
null
null
""" Python program to search for an element in the linked list using recursion """ class Node: def __init__(self, data): self.data = data self.next = None class Linked_list: def __init__(self): self.head = None self.last_node = None def append(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next def display(self): current = self.head while current is not None: print(current.data, end=" ") current = current.next def find_index(self, key): return self.find_index_helper(key, 0, self.head) def find_index_helper(self, key, start, node): if node is None: return -1 if node.data == key: return start else: return self.find_index_helper(key, start + 1, node.next) a_llist = Linked_list() n = int(input("How many elements would you like to add : ")) for i in range(n): data = int(input("Enter data item : ")) a_llist.append(data) print("The lined list : ", end=" ") a_llist.display() print() key = int(input("What data item would you like to search : ")) index = a_llist.find_index(key) if index == -1: print(str(key) + ' was not found') else: print(str(key) + "is at index" + str(index) + ".")
26.563636
78
0.590691
class Node: def __init__(self, data): self.data = data self.next = None class Linked_list: def __init__(self): self.head = None self.last_node = None def append(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next def display(self): current = self.head while current is not None: print(current.data, end=" ") current = current.next def find_index(self, key): return self.find_index_helper(key, 0, self.head) def find_index_helper(self, key, start, node): if node is None: return -1 if node.data == key: return start else: return self.find_index_helper(key, start + 1, node.next) a_llist = Linked_list() n = int(input("How many elements would you like to add : ")) for i in range(n): data = int(input("Enter data item : ")) a_llist.append(data) print("The lined list : ", end=" ") a_llist.display() print() key = int(input("What data item would you like to search : ")) index = a_llist.find_index(key) if index == -1: print(str(key) + ' was not found') else: print(str(key) + "is at index" + str(index) + ".")
true
true
f72d0862c33d21e1bd9da9c2c2fa5d10f09f06f4
4,140
py
Python
pystratis/api/federation/tests/test_federation.py
madrazzl3/pystratis
8b78552e753ae1d12f2afb39e9a322a270fbb7b3
[ "MIT" ]
null
null
null
pystratis/api/federation/tests/test_federation.py
madrazzl3/pystratis
8b78552e753ae1d12f2afb39e9a322a270fbb7b3
[ "MIT" ]
null
null
null
pystratis/api/federation/tests/test_federation.py
madrazzl3/pystratis
8b78552e753ae1d12f2afb39e9a322a270fbb7b3
[ "MIT" ]
null
null
null
import pytest from pytest_mock import MockerFixture from pystratis.api.federation.responsemodels import * from pystratis.api.federation import Federation from pystratis.core.networks import StraxMain, CirrusMain def test_all_strax_endpoints_implemented(strax_swagger_json): paths = [key.lower() for key in strax_swagger_json['paths']] for endpoint in paths: if Federation.route + '/' in endpoint: assert endpoint in Federation.endpoints def test_all_cirrus_endpoints_implemented(cirrus_swagger_json): paths = [key.lower() for key in cirrus_swagger_json['paths']] for endpoint in paths: if Federation.route + '/' in endpoint: assert endpoint in Federation.endpoints def test_all_interfluxstrax_endpoints_implemented(interfluxstrax_swagger_json): paths = [key.lower() for key in interfluxstrax_swagger_json['paths']] for endpoint in paths: if Federation.route + '/' in endpoint: assert endpoint in Federation.endpoints def test_all_interfluxcirrus_endpoints_implemented(interfluxcirrus_swagger_json): paths = [key.lower() for key in interfluxcirrus_swagger_json['paths']] for endpoint in paths: if Federation.route + '/' in endpoint: assert endpoint in Federation.endpoints @pytest.mark.parametrize('network', [StraxMain(), CirrusMain()], ids=['StraxMain', 'CirrusMain']) def test_reconstruct(mocker: MockerFixture, network): data = "Reconstruction flag set, please restart the node." mocker.patch.object(Federation, 'put', return_value=data) federation = Federation(network=network, baseuri=mocker.MagicMock(), session=mocker.MagicMock()) response = federation.reconstruct() assert response == data # noinspection PyUnresolvedReferences federation.put.assert_called_once() @pytest.mark.parametrize('network', [StraxMain(), CirrusMain()], ids=['StraxMain', 'CirrusMain']) def test_members_current(mocker: MockerFixture, network, generate_compressed_pubkey, get_datetime): data = { "pollStartBlockHeight": None, "pollNumberOfVotesAcquired": None, "pollFinishedBlockHeight": None, "pollWillFinishInBlocks": None, "pollExecutedBlockHeight": None, "memberWillStartMiningAtBlockHeight": None, "memberWillStartEarningRewardsEstimateHeight": None, "pollType": None, "rewardEstimatePerBlock": 0.05, "pubkey": generate_compressed_pubkey, "collateralAmount": 50000, "lastActiveTime": get_datetime(5), "periodOfInactivity": "00:02:32.9200000" } mocker.patch.object(Federation, 'get', return_value=data) federation = Federation(network=network, baseuri=mocker.MagicMock(), session=mocker.MagicMock()) response = federation.members_current() assert response == FederationMemberDetailedModel(**data) # noinspection PyUnresolvedReferences federation.get.assert_called_once() @pytest.mark.parametrize('network', [StraxMain(), CirrusMain()], ids=['StraxMain', 'CirrusMain']) def test_member(mocker: MockerFixture, network, generate_compressed_pubkey, get_datetime): data = [ { "pubkey": generate_compressed_pubkey, "collateralAmount": 50000, "lastActiveTime": get_datetime(5), "periodOfInactivity": "00:02:32.9200000" }, { "pubkey": generate_compressed_pubkey, "collateralAmount": 50000, "lastActiveTime": get_datetime(5), "periodOfInactivity": "00:02:33.9200000" }, { "pubkey": generate_compressed_pubkey, "collateralAmount": 50000, "lastActiveTime": get_datetime(5), "periodOfInactivity": "00:02:34.9200000" } ] mocker.patch.object(Federation, 'get', return_value=data) federation = Federation(network=network, baseuri=mocker.MagicMock(), session=mocker.MagicMock()) response = federation.members() assert response == [FederationMemberModel(**x) for x in data] # noinspection PyUnresolvedReferences federation.get.assert_called_once()
38.333333
100
0.700966
import pytest from pytest_mock import MockerFixture from pystratis.api.federation.responsemodels import * from pystratis.api.federation import Federation from pystratis.core.networks import StraxMain, CirrusMain def test_all_strax_endpoints_implemented(strax_swagger_json): paths = [key.lower() for key in strax_swagger_json['paths']] for endpoint in paths: if Federation.route + '/' in endpoint: assert endpoint in Federation.endpoints def test_all_cirrus_endpoints_implemented(cirrus_swagger_json): paths = [key.lower() for key in cirrus_swagger_json['paths']] for endpoint in paths: if Federation.route + '/' in endpoint: assert endpoint in Federation.endpoints def test_all_interfluxstrax_endpoints_implemented(interfluxstrax_swagger_json): paths = [key.lower() for key in interfluxstrax_swagger_json['paths']] for endpoint in paths: if Federation.route + '/' in endpoint: assert endpoint in Federation.endpoints def test_all_interfluxcirrus_endpoints_implemented(interfluxcirrus_swagger_json): paths = [key.lower() for key in interfluxcirrus_swagger_json['paths']] for endpoint in paths: if Federation.route + '/' in endpoint: assert endpoint in Federation.endpoints @pytest.mark.parametrize('network', [StraxMain(), CirrusMain()], ids=['StraxMain', 'CirrusMain']) def test_reconstruct(mocker: MockerFixture, network): data = "Reconstruction flag set, please restart the node." mocker.patch.object(Federation, 'put', return_value=data) federation = Federation(network=network, baseuri=mocker.MagicMock(), session=mocker.MagicMock()) response = federation.reconstruct() assert response == data federation.put.assert_called_once() @pytest.mark.parametrize('network', [StraxMain(), CirrusMain()], ids=['StraxMain', 'CirrusMain']) def test_members_current(mocker: MockerFixture, network, generate_compressed_pubkey, get_datetime): data = { "pollStartBlockHeight": None, "pollNumberOfVotesAcquired": None, "pollFinishedBlockHeight": None, "pollWillFinishInBlocks": None, "pollExecutedBlockHeight": None, "memberWillStartMiningAtBlockHeight": None, "memberWillStartEarningRewardsEstimateHeight": None, "pollType": None, "rewardEstimatePerBlock": 0.05, "pubkey": generate_compressed_pubkey, "collateralAmount": 50000, "lastActiveTime": get_datetime(5), "periodOfInactivity": "00:02:32.9200000" } mocker.patch.object(Federation, 'get', return_value=data) federation = Federation(network=network, baseuri=mocker.MagicMock(), session=mocker.MagicMock()) response = federation.members_current() assert response == FederationMemberDetailedModel(**data) federation.get.assert_called_once() @pytest.mark.parametrize('network', [StraxMain(), CirrusMain()], ids=['StraxMain', 'CirrusMain']) def test_member(mocker: MockerFixture, network, generate_compressed_pubkey, get_datetime): data = [ { "pubkey": generate_compressed_pubkey, "collateralAmount": 50000, "lastActiveTime": get_datetime(5), "periodOfInactivity": "00:02:32.9200000" }, { "pubkey": generate_compressed_pubkey, "collateralAmount": 50000, "lastActiveTime": get_datetime(5), "periodOfInactivity": "00:02:33.9200000" }, { "pubkey": generate_compressed_pubkey, "collateralAmount": 50000, "lastActiveTime": get_datetime(5), "periodOfInactivity": "00:02:34.9200000" } ] mocker.patch.object(Federation, 'get', return_value=data) federation = Federation(network=network, baseuri=mocker.MagicMock(), session=mocker.MagicMock()) response = federation.members() assert response == [FederationMemberModel(**x) for x in data] federation.get.assert_called_once()
true
true
f72d089f873a7c0b075b4dd30a15b63980100580
20,269
py
Python
tools/ami-creator/scripts/win2019_cuda11_installer.py
mseth10/incubator-mxnet-ci
36a5050b9c7bd720a4aa87d225738400083d611d
[ "Apache-2.0" ]
10
2019-08-19T17:12:52.000Z
2021-11-07T21:25:32.000Z
tools/ami-creator/scripts/win2019_cuda11_installer.py
mseth10/incubator-mxnet-ci
36a5050b9c7bd720a4aa87d225738400083d611d
[ "Apache-2.0" ]
16
2019-10-22T17:07:40.000Z
2022-02-08T23:33:27.000Z
tools/ami-creator/scripts/win2019_cuda11_installer.py
mseth10/incubator-mxnet-ci
36a5050b9c7bd720a4aa87d225738400083d611d
[ "Apache-2.0" ]
15
2019-08-25T18:44:54.000Z
2021-11-07T21:25:25.000Z
# 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. """Dependency installer for Windows""" __author__ = 'Pedro Larroy, Chance Bair, Joe Evans' __version__ = '0.4' import argparse import errno import logging import os import psutil import shutil import subprocess import urllib import stat import tempfile import zipfile from time import sleep from urllib.error import HTTPError import logging from subprocess import check_output, check_call, call import re import sys import urllib.request import contextlib import glob import ssl ssl._create_default_https_context = ssl._create_unverified_context log = logging.getLogger(__name__) DEPS = { 'openblas': 'https://windows-post-install.s3-us-west-2.amazonaws.com/OpenBLAS-windows-v0_2_19.zip', 'opencv': 'https://windows-post-install.s3-us-west-2.amazonaws.com/opencv-windows-4.1.2-vc14_vc15.zip', 'cudnn7': 'https://windows-post-install.s3-us-west-2.amazonaws.com/cudnn-10.2-windows10-x64-v7.6.5.32.zip', 'cudnn8': 'https://windows-post-install.s3-us-west-2.amazonaws.com/cudnn-11.0-windows-x64-v8.0.3.33.zip', 'perl': 'http://strawberryperl.com/download/5.30.1.1/strawberry-perl-5.30.1.1-64bit.msi', 'clang': 'https://github.com/llvm/llvm-project/releases/download/llvmorg-9.0.1/LLVM-9.0.1-win64.exe', } DEFAULT_SUBPROCESS_TIMEOUT = 3600 @contextlib.contextmanager def remember_cwd(): ''' Restore current directory when exiting context ''' curdir = os.getcwd() try: yield finally: os.chdir(curdir) def retry(target_exception, tries=4, delay_s=1, backoff=2): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param target_exception: the exception to check. may be a tuple of exceptions to check :type target_exception: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay_s: initial delay between retries in seconds :type delay_s: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int """ import time from functools import wraps def decorated_retry(f): @wraps(f) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay_s while mtries > 1: try: return f(*args, **kwargs) except target_exception as e: logging.warning("Exception: %s, Retrying in %d seconds...", str(e), mdelay) time.sleep(mdelay) mtries -= 1 mdelay *= backoff return f(*args, **kwargs) return f_retry # true decorator return decorated_retry @retry((ValueError, OSError, HTTPError), tries=5, delay_s=2, backoff=5) def download(url, dest=None, progress=False) -> str: from urllib.request import urlopen from urllib.parse import (urlparse, urlunparse) import progressbar import http.client class ProgressCB(): def __init__(self): self.pbar = None def __call__(self, block_num, block_size, total_size): if not self.pbar and total_size > 0: self.pbar = progressbar.bar.ProgressBar(max_value=total_size) downloaded = block_num * block_size if self.pbar: if downloaded < total_size: self.pbar.update(downloaded) else: self.pbar.finish() if dest and os.path.isdir(dest): local_file = os.path.split(urlparse(url).path)[1] local_path = os.path.normpath(os.path.join(dest, local_file)) else: local_path = dest with urlopen(url) as c: content_length = c.getheader('content-length') length = int(content_length) if content_length and isinstance(c, http.client.HTTPResponse) else None if length and local_path and os.path.exists(local_path) and os.stat(local_path).st_size == length: log.debug(f"download('{url}'): Already downloaded.") return local_path log.debug(f"download({url}, {local_path}): downloading {length} bytes") if local_path: with tempfile.NamedTemporaryFile(delete=False) as tmpfd: urllib.request.urlretrieve(url, filename=tmpfd.name, reporthook=ProgressCB() if progress else None) shutil.move(tmpfd.name, local_path) else: (local_path, _) = urllib.request.urlretrieve(url, reporthook=ProgressCB()) log.debug(f"download({url}, {local_path}'): done.") return local_path # Takes arguments and runs command on host. Shell is disabled by default. # TODO: Move timeout to args def run_command(*args, shell=False, timeout=DEFAULT_SUBPROCESS_TIMEOUT, **kwargs): try: logging.info("Issuing command: {}".format(args)) res = subprocess.check_output(*args, shell=shell, timeout=timeout).decode("utf-8").replace("\r\n", "\n") logging.info("Output: {}".format(res)) except subprocess.CalledProcessError as e: raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) return res # Copies source directory recursively to destination. def copy(src, dest): try: shutil.copytree(src, dest) logging.info("Moved {} to {}".format(src, dest)) except OSError as e: # If the error was caused because the source wasn't a directory if e.errno == errno.ENOTDIR: shutil.copy(src, dest) logging.info("Moved {} to {}".format(src, dest)) else: raise RuntimeError("copy return with error: {}".format(e)) # Workaround for windows readonly attribute error def on_rm_error(func, path, exc_info): # path contains the path of the file that couldn't be removed # let's just assume that it's read-only and unlink it. os.chmod(path, stat.S_IWRITE) os.unlink(path) def reboot_system(): logging.info("Rebooting system now...") run_command("shutdown -r -t 5") exit(0) def shutdown_system(): logging.info("Shutting down system now...") # wait 20 sec so we can capture the install logs run_command("shutdown -s -t 20") exit(0) def install_vs(): if os.path.exists("C:\\Program Files (x86)\\Microsoft Visual Studio\\2019"): logging.info("MSVS already installed, skipping.") return False # Visual Studio 2019 # Components: https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community?view=vs-2019#visual-studio-core-editor-included-with-visual-studio-community-2019 logging.info("Installing Visual Studio 2019...") vs_file_path = download('https://windows-post-install.s3-us-west-2.amazonaws.com/vs_community__1246179388.1585201415.exe') run_command("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(vs_file_path, vs_file_path.split('\\')[-1]), shell=True) vs_file_path = vs_file_path + '.exe' logging.info("Installing VisualStudio 2019.....") ret = call(vs_file_path + ' --add Microsoft.VisualStudio.Workload.ManagedDesktop' ' --add Microsoft.VisualStudio.Workload.NetCoreTools' ' --add Microsoft.VisualStudio.Workload.NetWeb' ' --add Microsoft.VisualStudio.Workload.Node' ' --add Microsoft.VisualStudio.Workload.Office' ' --add Microsoft.VisualStudio.Component.TypeScript.2.0' ' --add Microsoft.VisualStudio.Component.TestTools.WebLoadTest' ' --add Component.GitHub.VisualStudio' ' --add Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core' ' --add Microsoft.VisualStudio.Component.Static.Analysis.Tools' ' --add Microsoft.VisualStudio.Component.VC.CMake.Project' ' --add Microsoft.VisualStudio.Component.VC.140' ' --add Microsoft.VisualStudio.Component.Windows10SDK.18362.Desktop' ' --add Microsoft.VisualStudio.Component.Windows10SDK.18362.UWP' ' --add Microsoft.VisualStudio.Component.Windows10SDK.18362.UWP.Native' ' --add Microsoft.VisualStudio.ComponentGroup.Windows10SDK.18362' ' --add Microsoft.VisualStudio.Component.Windows10SDK.16299' ' --wait' ' --passive' ' --norestart' ) if ret == 3010 or ret == 0: # 3010 is restart required logging.info("VS install successful.") else: raise RuntimeError("VS failed to install, exit status {}".format(ret)) # Workaround for --wait sometimes ignoring the subprocesses doing component installs def vs_still_installing(): return {'vs_installer.exe', 'vs_installershell.exe', 'vs_setup_bootstrapper.exe'} & set(map(lambda process: process.name(), psutil.process_iter())) timer = 0 while vs_still_installing() and timer < DEFAULT_SUBPROCESS_TIMEOUT: logging.warning("VS installers still running for %d s", timer) if timer % 60 == 0: logging.info("Waiting for Visual Studio to install for the last {} seconds".format(str(timer))) sleep(1) timer += 1 if vs_still_installing(): logging.warning("VS install still running after timeout (%d)", DEFAULT_SUBPROCESS_TIMEOUT) else: logging.info("Visual studio install complete.") return True def install_perl(): if os.path.exists("C:\\Strawberry\\perl\\bin\\perl.exe"): logging.info("Perl already installed, skipping.") return False logging.info("Installing Perl") with tempfile.TemporaryDirectory() as tmpdir: perl_file_path = download(DEPS['perl'], tmpdir) check_call(['msiexec ', '/n', '/passive', '/i', perl_file_path]) logging.info("Perl install complete") return True def install_clang(): if os.path.exists("C:\\Program Files\\LLVM"): logging.info("Clang already installed, skipping.") return False logging.info("Installing Clang") with tempfile.TemporaryDirectory() as tmpdir: clang_file_path = download(DEPS['clang'], tmpdir) run_command(clang_file_path + " /S /D=C:\\Program Files\\LLVM") logging.info("Clang install complete") return True def install_openblas(): if os.path.exists("C:\\Program Files\\OpenBLAS-windows-v0_2_19"): logging.info("OpenBLAS already installed, skipping.") return False logging.info("Installing OpenBLAS") local_file = download(DEPS['openblas']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall("C:\\Program Files") run_command("PowerShell Set-ItemProperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name OpenBLAS_HOME -Value 'C:\\Program Files\\OpenBLAS-windows-v0_2_19'") logging.info("Openblas Install complete") return True def install_mkl(): if os.path.exists("C:\\Program Files (x86)\\IntelSWTools"): logging.info("Intel MKL already installed, skipping.") return False logging.info("Installing MKL 2019.3.203...") file_path = download("http://registrationcenter-download.intel.com/akdlm/irc_nas/tec/15247/w_mkl_2019.3.203.exe") run_command("{} --silent --remove-extracted-files yes --a install -output=C:\mkl-install-log.txt -eula=accept".format(file_path)) logging.info("MKL Install complete") return True def install_opencv(): if os.path.exists("C:\\Program Files\\opencv"): logging.info("OpenCV already installed, skipping.") return False logging.info("Installing OpenCV") with tempfile.TemporaryDirectory() as tmpdir: local_file = download(DEPS['opencv']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall(tmpdir) copy(f'{tmpdir}\\opencv\\build', r'c:\Program Files\opencv') run_command("PowerShell Set-ItemProperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name OpenCV_DIR -Value 'C:\\Program Files\\opencv'") logging.info("OpenCV install complete") return True def install_cudnn7(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin\\cudnn64_7.dll"): logging.info("cuDNN7 already installed, skipping.") return False # cuDNN logging.info("Installing cuDNN7") with tempfile.TemporaryDirectory() as tmpdir: local_file = download(DEPS['cudnn7']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall(tmpdir) for f in glob.glob(tmpdir+"\\cuda\\bin\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin") for f in glob.glob(tmpdir+"\\cuda\\include\\*.h"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\include") for f in glob.glob(tmpdir+"\\cuda\\lib\\x64\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\lib\\x64") logging.info("cuDNN7 install complete") return True def install_cudnn8(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\bin\\cudnn64_8.dll"): logging.info("cuDNN7 already installed, skipping.") return False # cuDNN logging.info("Installing cuDNN8") with tempfile.TemporaryDirectory() as tmpdir: local_file = download(DEPS['cudnn8']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall(tmpdir) for f in glob.glob(tmpdir+"\\cuda\\bin\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\bin") for f in glob.glob(tmpdir+"\\cuda\\include\\*.h"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\include") for f in glob.glob(tmpdir+"\\cuda\\lib\\x64\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\lib\\x64") logging.info("cuDNN8 install complete") return True def instance_family(): return urllib.request.urlopen('http://instance-data/latest/meta-data/instance-type').read().decode().split('.')[0] CUDA_COMPONENTS=[ 'nvcc', 'cublas', 'cublas_dev', 'cudart', 'cufft', 'cufft_dev', 'curand', 'curand_dev', 'cusolver', 'cusolver_dev', 'cusparse', 'cusparse_dev', 'npp', 'npp_dev', 'nvrtc', 'nvrtc_dev', 'nvml_dev' ] def install_cuda110(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\bin"): logging.info("CUDA 11.0 already installed, skipping.") return False logging.info("Downloadinng CUDA 11.0...") cuda_file_path = download( 'http://developer.download.nvidia.com/compute/cuda/11.0.3/network_installers/cuda_11.0.3_win10_network.exe') try: check_call("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(cuda_file_path, cuda_file_path.split('\\')[-1]), shell=True) except subprocess.CalledProcessError as e: logging.exception("Rename file failed") cuda_file_path = cuda_file_path + '.exe' logging.info("Installing CUDA 11.0...") check_call(cuda_file_path + ' -s') #check_call(cuda_file_path + ' -s ' + " ".join([p + "_11.0" for p in CUDA_COMPONENTS])) logging.info("Done installing CUDA 11.0.") return True def install_cuda102(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin"): logging.info("CUDA 10.2 already installed, skipping.") return False logging.info("Downloading CUDA 10.2...") cuda_file_path = download( 'http://developer.download.nvidia.com/compute/cuda/10.2/Prod/network_installers/cuda_10.2.89_win10_network.exe') try: check_call("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(cuda_file_path, cuda_file_path.split('\\')[-1]), shell=True) except subprocess.CalledProcessError as e: logging.exception("Rename file failed") cuda_file_path = cuda_file_path + '.exe' logging.info("Installing CUDA 10.2...") check_call(cuda_file_path + ' -s') #check_call(cuda_file_path + ' -s ' + " ".join([p + "_10.2" for p in CUDA_COMPONENTS])) logging.info("Downloading CUDA 10.2 patch...") patch_file_path = download( 'http://developer.download.nvidia.com/compute/cuda/10.2/Prod/patches/1/cuda_10.2.1_win10.exe') try: check_call("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(patch_file_path, patch_file_path.split('\\')[-1]), shell=True) except subprocess.CalledProcessError as e: logging.exception("Rename patch failed") patch_file_path = patch_file_path + '.exe' logging.info("Installing CUDA patch...") check_call(patch_file_path + ' -s ') logging.info("Done installing CUDA 10.2 and patches.") return True def schedule_aws_userdata(): logging.info("Scheduling AWS init so userdata will run on next boot...") run_command("PowerShell C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Scripts\\InitializeInstance.ps1 -Schedule") def add_paths(): # TODO: Add python paths (python -> C:\\Python37\\python.exe, python2 -> C:\\Python27\\python.exe) logging.info("Adding Windows Kits to PATH...") current_path = run_command( "PowerShell (Get-Itemproperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name Path).Path") current_path = current_path.rstrip() logging.debug("current_path: {}".format(current_path)) new_path = current_path + \ ";C:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.16299.0\\x86;C:\\Program Files\\OpenBLAS-windows-v0_2_19\\bin;C:\\Program Files\\LLVM\\bin;C:\\Program Files\\opencv\\bin;C:\\Program Files\\opencv\\x64\\vc15\\bin" logging.debug("new_path: {}".format(new_path)) run_command("PowerShell Set-ItemProperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name Path -Value '" + new_path + "'") def script_name() -> str: """:returns: script name with leading paths removed""" return os.path.split(sys.argv[0])[1] def remove_install_task(): logging.info("Removing stage2 startup task...") run_command("PowerShell Unregister-ScheduledTask -TaskName 'Stage2Install' -Confirm:$false") def main(): logging.getLogger().setLevel(os.environ.get('LOGLEVEL', logging.DEBUG)) logging.basicConfig(filename="C:\\install.log", format='{}: %(asctime)sZ %(levelname)s %(message)s'.format(script_name())) # install all necessary software and reboot after some components # for CUDA, the last version you install will be the default, based on PATH variable if install_cuda110(): reboot_system() install_cudnn8() #if install_cuda102(): # reboot_system() #install_cudnn7() if install_vs(): reboot_system() install_openblas() install_mkl() install_opencv() install_perl() install_clang() add_paths() remove_install_task() schedule_aws_userdata() shutdown_system() if __name__ == "__main__": exit(main())
42.852008
227
0.660763
__author__ = 'Pedro Larroy, Chance Bair, Joe Evans' __version__ = '0.4' import argparse import errno import logging import os import psutil import shutil import subprocess import urllib import stat import tempfile import zipfile from time import sleep from urllib.error import HTTPError import logging from subprocess import check_output, check_call, call import re import sys import urllib.request import contextlib import glob import ssl ssl._create_default_https_context = ssl._create_unverified_context log = logging.getLogger(__name__) DEPS = { 'openblas': 'https://windows-post-install.s3-us-west-2.amazonaws.com/OpenBLAS-windows-v0_2_19.zip', 'opencv': 'https://windows-post-install.s3-us-west-2.amazonaws.com/opencv-windows-4.1.2-vc14_vc15.zip', 'cudnn7': 'https://windows-post-install.s3-us-west-2.amazonaws.com/cudnn-10.2-windows10-x64-v7.6.5.32.zip', 'cudnn8': 'https://windows-post-install.s3-us-west-2.amazonaws.com/cudnn-11.0-windows-x64-v8.0.3.33.zip', 'perl': 'http://strawberryperl.com/download/5.30.1.1/strawberry-perl-5.30.1.1-64bit.msi', 'clang': 'https://github.com/llvm/llvm-project/releases/download/llvmorg-9.0.1/LLVM-9.0.1-win64.exe', } DEFAULT_SUBPROCESS_TIMEOUT = 3600 @contextlib.contextmanager def remember_cwd(): curdir = os.getcwd() try: yield finally: os.chdir(curdir) def retry(target_exception, tries=4, delay_s=1, backoff=2): import time from functools import wraps def decorated_retry(f): @wraps(f) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay_s while mtries > 1: try: return f(*args, **kwargs) except target_exception as e: logging.warning("Exception: %s, Retrying in %d seconds...", str(e), mdelay) time.sleep(mdelay) mtries -= 1 mdelay *= backoff return f(*args, **kwargs) return f_retry return decorated_retry @retry((ValueError, OSError, HTTPError), tries=5, delay_s=2, backoff=5) def download(url, dest=None, progress=False) -> str: from urllib.request import urlopen from urllib.parse import (urlparse, urlunparse) import progressbar import http.client class ProgressCB(): def __init__(self): self.pbar = None def __call__(self, block_num, block_size, total_size): if not self.pbar and total_size > 0: self.pbar = progressbar.bar.ProgressBar(max_value=total_size) downloaded = block_num * block_size if self.pbar: if downloaded < total_size: self.pbar.update(downloaded) else: self.pbar.finish() if dest and os.path.isdir(dest): local_file = os.path.split(urlparse(url).path)[1] local_path = os.path.normpath(os.path.join(dest, local_file)) else: local_path = dest with urlopen(url) as c: content_length = c.getheader('content-length') length = int(content_length) if content_length and isinstance(c, http.client.HTTPResponse) else None if length and local_path and os.path.exists(local_path) and os.stat(local_path).st_size == length: log.debug(f"download('{url}'): Already downloaded.") return local_path log.debug(f"download({url}, {local_path}): downloading {length} bytes") if local_path: with tempfile.NamedTemporaryFile(delete=False) as tmpfd: urllib.request.urlretrieve(url, filename=tmpfd.name, reporthook=ProgressCB() if progress else None) shutil.move(tmpfd.name, local_path) else: (local_path, _) = urllib.request.urlretrieve(url, reporthook=ProgressCB()) log.debug(f"download({url}, {local_path}'): done.") return local_path # Takes arguments and runs command on host. Shell is disabled by default. # TODO: Move timeout to args def run_command(*args, shell=False, timeout=DEFAULT_SUBPROCESS_TIMEOUT, **kwargs): try: logging.info("Issuing command: {}".format(args)) res = subprocess.check_output(*args, shell=shell, timeout=timeout).decode("utf-8").replace("\r\n", "\n") logging.info("Output: {}".format(res)) except subprocess.CalledProcessError as e: raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) return res # Copies source directory recursively to destination. def copy(src, dest): try: shutil.copytree(src, dest) logging.info("Moved {} to {}".format(src, dest)) except OSError as e: # If the error was caused because the source wasn't a directory if e.errno == errno.ENOTDIR: shutil.copy(src, dest) logging.info("Moved {} to {}".format(src, dest)) else: raise RuntimeError("copy return with error: {}".format(e)) def on_rm_error(func, path, exc_info): # let's just assume that it's read-only and unlink it. os.chmod(path, stat.S_IWRITE) os.unlink(path) def reboot_system(): logging.info("Rebooting system now...") run_command("shutdown -r -t 5") exit(0) def shutdown_system(): logging.info("Shutting down system now...") # wait 20 sec so we can capture the install logs run_command("shutdown -s -t 20") exit(0) def install_vs(): if os.path.exists("C:\\Program Files (x86)\\Microsoft Visual Studio\\2019"): logging.info("MSVS already installed, skipping.") return False # Visual Studio 2019 # Components: https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community?view=vs-2019#visual-studio-core-editor-included-with-visual-studio-community-2019 logging.info("Installing Visual Studio 2019...") vs_file_path = download('https://windows-post-install.s3-us-west-2.amazonaws.com/vs_community__1246179388.1585201415.exe') run_command("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(vs_file_path, vs_file_path.split('\\')[-1]), shell=True) vs_file_path = vs_file_path + '.exe' logging.info("Installing VisualStudio 2019.....") ret = call(vs_file_path + ' --add Microsoft.VisualStudio.Workload.ManagedDesktop' ' --add Microsoft.VisualStudio.Workload.NetCoreTools' ' --add Microsoft.VisualStudio.Workload.NetWeb' ' --add Microsoft.VisualStudio.Workload.Node' ' --add Microsoft.VisualStudio.Workload.Office' ' --add Microsoft.VisualStudio.Component.TypeScript.2.0' ' --add Microsoft.VisualStudio.Component.TestTools.WebLoadTest' ' --add Component.GitHub.VisualStudio' ' --add Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core' ' --add Microsoft.VisualStudio.Component.Static.Analysis.Tools' ' --add Microsoft.VisualStudio.Component.VC.CMake.Project' ' --add Microsoft.VisualStudio.Component.VC.140' ' --add Microsoft.VisualStudio.Component.Windows10SDK.18362.Desktop' ' --add Microsoft.VisualStudio.Component.Windows10SDK.18362.UWP' ' --add Microsoft.VisualStudio.Component.Windows10SDK.18362.UWP.Native' ' --add Microsoft.VisualStudio.ComponentGroup.Windows10SDK.18362' ' --add Microsoft.VisualStudio.Component.Windows10SDK.16299' ' --wait' ' --passive' ' --norestart' ) if ret == 3010 or ret == 0: # 3010 is restart required logging.info("VS install successful.") else: raise RuntimeError("VS failed to install, exit status {}".format(ret)) # Workaround for --wait sometimes ignoring the subprocesses doing component installs def vs_still_installing(): return {'vs_installer.exe', 'vs_installershell.exe', 'vs_setup_bootstrapper.exe'} & set(map(lambda process: process.name(), psutil.process_iter())) timer = 0 while vs_still_installing() and timer < DEFAULT_SUBPROCESS_TIMEOUT: logging.warning("VS installers still running for %d s", timer) if timer % 60 == 0: logging.info("Waiting for Visual Studio to install for the last {} seconds".format(str(timer))) sleep(1) timer += 1 if vs_still_installing(): logging.warning("VS install still running after timeout (%d)", DEFAULT_SUBPROCESS_TIMEOUT) else: logging.info("Visual studio install complete.") return True def install_perl(): if os.path.exists("C:\\Strawberry\\perl\\bin\\perl.exe"): logging.info("Perl already installed, skipping.") return False logging.info("Installing Perl") with tempfile.TemporaryDirectory() as tmpdir: perl_file_path = download(DEPS['perl'], tmpdir) check_call(['msiexec ', '/n', '/passive', '/i', perl_file_path]) logging.info("Perl install complete") return True def install_clang(): if os.path.exists("C:\\Program Files\\LLVM"): logging.info("Clang already installed, skipping.") return False logging.info("Installing Clang") with tempfile.TemporaryDirectory() as tmpdir: clang_file_path = download(DEPS['clang'], tmpdir) run_command(clang_file_path + " /S /D=C:\\Program Files\\LLVM") logging.info("Clang install complete") return True def install_openblas(): if os.path.exists("C:\\Program Files\\OpenBLAS-windows-v0_2_19"): logging.info("OpenBLAS already installed, skipping.") return False logging.info("Installing OpenBLAS") local_file = download(DEPS['openblas']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall("C:\\Program Files") run_command("PowerShell Set-ItemProperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name OpenBLAS_HOME -Value 'C:\\Program Files\\OpenBLAS-windows-v0_2_19'") logging.info("Openblas Install complete") return True def install_mkl(): if os.path.exists("C:\\Program Files (x86)\\IntelSWTools"): logging.info("Intel MKL already installed, skipping.") return False logging.info("Installing MKL 2019.3.203...") file_path = download("http://registrationcenter-download.intel.com/akdlm/irc_nas/tec/15247/w_mkl_2019.3.203.exe") run_command("{} --silent --remove-extracted-files yes --a install -output=C:\mkl-install-log.txt -eula=accept".format(file_path)) logging.info("MKL Install complete") return True def install_opencv(): if os.path.exists("C:\\Program Files\\opencv"): logging.info("OpenCV already installed, skipping.") return False logging.info("Installing OpenCV") with tempfile.TemporaryDirectory() as tmpdir: local_file = download(DEPS['opencv']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall(tmpdir) copy(f'{tmpdir}\\opencv\\build', r'c:\Program Files\opencv') run_command("PowerShell Set-ItemProperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name OpenCV_DIR -Value 'C:\\Program Files\\opencv'") logging.info("OpenCV install complete") return True def install_cudnn7(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin\\cudnn64_7.dll"): logging.info("cuDNN7 already installed, skipping.") return False # cuDNN logging.info("Installing cuDNN7") with tempfile.TemporaryDirectory() as tmpdir: local_file = download(DEPS['cudnn7']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall(tmpdir) for f in glob.glob(tmpdir+"\\cuda\\bin\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin") for f in glob.glob(tmpdir+"\\cuda\\include\\*.h"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\include") for f in glob.glob(tmpdir+"\\cuda\\lib\\x64\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\lib\\x64") logging.info("cuDNN7 install complete") return True def install_cudnn8(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\bin\\cudnn64_8.dll"): logging.info("cuDNN7 already installed, skipping.") return False # cuDNN logging.info("Installing cuDNN8") with tempfile.TemporaryDirectory() as tmpdir: local_file = download(DEPS['cudnn8']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall(tmpdir) for f in glob.glob(tmpdir+"\\cuda\\bin\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\bin") for f in glob.glob(tmpdir+"\\cuda\\include\\*.h"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\include") for f in glob.glob(tmpdir+"\\cuda\\lib\\x64\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\lib\\x64") logging.info("cuDNN8 install complete") return True def instance_family(): return urllib.request.urlopen('http://instance-data/latest/meta-data/instance-type').read().decode().split('.')[0] CUDA_COMPONENTS=[ 'nvcc', 'cublas', 'cublas_dev', 'cudart', 'cufft', 'cufft_dev', 'curand', 'curand_dev', 'cusolver', 'cusolver_dev', 'cusparse', 'cusparse_dev', 'npp', 'npp_dev', 'nvrtc', 'nvrtc_dev', 'nvml_dev' ] def install_cuda110(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\bin"): logging.info("CUDA 11.0 already installed, skipping.") return False logging.info("Downloadinng CUDA 11.0...") cuda_file_path = download( 'http://developer.download.nvidia.com/compute/cuda/11.0.3/network_installers/cuda_11.0.3_win10_network.exe') try: check_call("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(cuda_file_path, cuda_file_path.split('\\')[-1]), shell=True) except subprocess.CalledProcessError as e: logging.exception("Rename file failed") cuda_file_path = cuda_file_path + '.exe' logging.info("Installing CUDA 11.0...") check_call(cuda_file_path + ' -s') #check_call(cuda_file_path + ' -s ' + " ".join([p + "_11.0" for p in CUDA_COMPONENTS])) logging.info("Done installing CUDA 11.0.") return True def install_cuda102(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin"): logging.info("CUDA 10.2 already installed, skipping.") return False logging.info("Downloading CUDA 10.2...") cuda_file_path = download( 'http://developer.download.nvidia.com/compute/cuda/10.2/Prod/network_installers/cuda_10.2.89_win10_network.exe') try: check_call("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(cuda_file_path, cuda_file_path.split('\\')[-1]), shell=True) except subprocess.CalledProcessError as e: logging.exception("Rename file failed") cuda_file_path = cuda_file_path + '.exe' logging.info("Installing CUDA 10.2...") check_call(cuda_file_path + ' -s') #check_call(cuda_file_path + ' -s ' + " ".join([p + "_10.2" for p in CUDA_COMPONENTS])) logging.info("Downloading CUDA 10.2 patch...") patch_file_path = download( 'http://developer.download.nvidia.com/compute/cuda/10.2/Prod/patches/1/cuda_10.2.1_win10.exe') try: check_call("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(patch_file_path, patch_file_path.split('\\')[-1]), shell=True) except subprocess.CalledProcessError as e: logging.exception("Rename patch failed") patch_file_path = patch_file_path + '.exe' logging.info("Installing CUDA patch...") check_call(patch_file_path + ' -s ') logging.info("Done installing CUDA 10.2 and patches.") return True def schedule_aws_userdata(): logging.info("Scheduling AWS init so userdata will run on next boot...") run_command("PowerShell C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Scripts\\InitializeInstance.ps1 -Schedule") def add_paths(): # TODO: Add python paths (python -> C:\\Python37\\python.exe, python2 -> C:\\Python27\\python.exe) logging.info("Adding Windows Kits to PATH...") current_path = run_command( "PowerShell (Get-Itemproperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name Path).Path") current_path = current_path.rstrip() logging.debug("current_path: {}".format(current_path)) new_path = current_path + \ ";C:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.16299.0\\x86;C:\\Program Files\\OpenBLAS-windows-v0_2_19\\bin;C:\\Program Files\\LLVM\\bin;C:\\Program Files\\opencv\\bin;C:\\Program Files\\opencv\\x64\\vc15\\bin" logging.debug("new_path: {}".format(new_path)) run_command("PowerShell Set-ItemProperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name Path -Value '" + new_path + "'") def script_name() -> str: return os.path.split(sys.argv[0])[1] def remove_install_task(): logging.info("Removing stage2 startup task...") run_command("PowerShell Unregister-ScheduledTask -TaskName 'Stage2Install' -Confirm:$false") def main(): logging.getLogger().setLevel(os.environ.get('LOGLEVEL', logging.DEBUG)) logging.basicConfig(filename="C:\\install.log", format='{}: %(asctime)sZ %(levelname)s %(message)s'.format(script_name())) # install all necessary software and reboot after some components # for CUDA, the last version you install will be the default, based on PATH variable if install_cuda110(): reboot_system() install_cudnn8() #if install_cuda102(): # reboot_system() #install_cudnn7() if install_vs(): reboot_system() install_openblas() install_mkl() install_opencv() install_perl() install_clang() add_paths() remove_install_task() schedule_aws_userdata() shutdown_system() if __name__ == "__main__": exit(main())
true
true
f72d09e2fff6278a2ca4a3ec916f0240a3598469
2,143
py
Python
tests/examples/test_examples.py
ibraheemmmoosa/lightning-flash
c60fef81b27174543d7ad3a4d841faf71ad8536c
[ "Apache-2.0" ]
2
2021-06-25T08:42:36.000Z
2021-06-25T08:49:29.000Z
tests/examples/test_examples.py
edenlightning/lightning-flash
841986aa0081bdeaf785d1ed4c48dd108fa69a78
[ "Apache-2.0" ]
null
null
null
tests/examples/test_examples.py
edenlightning/lightning-flash
841986aa0081bdeaf785d1ed4c48dd108fa69a78
[ "Apache-2.0" ]
null
null
null
# Copyright The PyTorch Lightning team. # # 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 subprocess import sys from pathlib import Path from typing import List, Optional, Tuple import pytest root = Path(__file__).parent.parent.parent def call_script(filepath: str, args: Optional[List[str]] = None, timeout: Optional[int] = 60 * 5) -> Tuple[int, str, str]: if args is None: args = [] args = [str(a) for a in args] command = [sys.executable, filepath] + args print(" ".join(command)) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: stdout, stderr = p.communicate(timeout=timeout) except subprocess.TimeoutExpired: p.kill() stdout, stderr = p.communicate() stdout = stdout.decode("utf-8") stderr = stderr.decode("utf-8") return p.returncode, stdout, stderr def run_test(filepath): code, stdout, stderr = call_script(filepath) assert not code print(f"{filepath} STDOUT: {stdout}") print(f"{filepath} STDERR: {stderr}") @pytest.mark.parametrize( "step,file", [ ("finetuning", "image_classification.py"), ("finetuning", "tabular_classification.py"), ("predict", "classify_image.py"), ("predict", "classify_tabular.py"), # "classify_text.py" TODO: takes too long ] ) def test_finetune_example(tmpdir, step, file): with tmpdir.as_cwd(): run_test(str(root / "flash_examples" / step / file)) def test_generic_example(tmpdir): with tmpdir.as_cwd(): run_test(str(root / "flash_examples" / "generic_task.py"))
31.514706
81
0.674755
import subprocess import sys from pathlib import Path from typing import List, Optional, Tuple import pytest root = Path(__file__).parent.parent.parent def call_script(filepath: str, args: Optional[List[str]] = None, timeout: Optional[int] = 60 * 5) -> Tuple[int, str, str]: if args is None: args = [] args = [str(a) for a in args] command = [sys.executable, filepath] + args print(" ".join(command)) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: stdout, stderr = p.communicate(timeout=timeout) except subprocess.TimeoutExpired: p.kill() stdout, stderr = p.communicate() stdout = stdout.decode("utf-8") stderr = stderr.decode("utf-8") return p.returncode, stdout, stderr def run_test(filepath): code, stdout, stderr = call_script(filepath) assert not code print(f"{filepath} STDOUT: {stdout}") print(f"{filepath} STDERR: {stderr}") @pytest.mark.parametrize( "step,file", [ ("finetuning", "image_classification.py"), ("finetuning", "tabular_classification.py"), ("predict", "classify_image.py"), ("predict", "classify_tabular.py"), ] ) def test_finetune_example(tmpdir, step, file): with tmpdir.as_cwd(): run_test(str(root / "flash_examples" / step / file)) def test_generic_example(tmpdir): with tmpdir.as_cwd(): run_test(str(root / "flash_examples" / "generic_task.py"))
true
true
f72d0a505a4a11b305a59432ae84c13cac527366
1,848
py
Python
tests/functional/tests/rbd-mirror/test_rbd_mirror.py
u-kosmonaft-u/ceph-ansible
14c472707c165f77def05826b22885480af3e8f9
[ "Apache-2.0" ]
1,570
2015-01-03T08:38:22.000Z
2022-03-31T09:24:37.000Z
tests/functional/tests/rbd-mirror/test_rbd_mirror.py
u-kosmonaft-u/ceph-ansible
14c472707c165f77def05826b22885480af3e8f9
[ "Apache-2.0" ]
4,964
2015-01-05T10:41:44.000Z
2022-03-31T07:59:49.000Z
tests/functional/tests/rbd-mirror/test_rbd_mirror.py
u-kosmonaft-u/ceph-ansible
14c472707c165f77def05826b22885480af3e8f9
[ "Apache-2.0" ]
1,231
2015-01-04T11:48:16.000Z
2022-03-31T12:15:28.000Z
import pytest import json class TestRbdMirrors(object): @pytest.mark.no_docker def test_rbd_mirror_is_installed(self, node, host): assert host.package("rbd-mirror").is_installed def test_rbd_mirror_service_enabled_and_running(self, node, host): service_name = "ceph-rbd-mirror@rbd-mirror.{hostname}".format( hostname=node["vars"]["inventory_hostname"] ) s = host.service(service_name) assert s.is_enabled assert s.is_running def test_rbd_mirror_is_up(self, node, host, setup): hostname = node["vars"]["inventory_hostname"] cluster = setup["cluster_name"] container_binary = setup["container_binary"] daemons = [] if node['docker']: container_exec_cmd = '{container_binary} exec ceph-rbd-mirror-{hostname}'.format( # noqa E501 hostname=hostname, container_binary=container_binary) else: container_exec_cmd = '' hostname = node["vars"]["inventory_hostname"] cluster = setup['cluster_name'] cmd = "sudo {container_exec_cmd} ceph --name client.bootstrap-rbd-mirror --keyring /var/lib/ceph/bootstrap-rbd-mirror/{cluster}.keyring --cluster={cluster} --connect-timeout 5 -f json -s".format( # noqa E501 container_exec_cmd=container_exec_cmd, hostname=hostname, cluster=cluster ) output = host.check_output(cmd) status = json.loads(output) daemon_ids = [i for i in status["servicemap"]["services"] ["rbd-mirror"]["daemons"].keys() if i != "summary"] for daemon_id in daemon_ids: daemons.append(status["servicemap"]["services"]["rbd-mirror"] ["daemons"][daemon_id]["metadata"]["hostname"]) assert hostname in daemons
42
216
0.62987
import pytest import json class TestRbdMirrors(object): @pytest.mark.no_docker def test_rbd_mirror_is_installed(self, node, host): assert host.package("rbd-mirror").is_installed def test_rbd_mirror_service_enabled_and_running(self, node, host): service_name = "ceph-rbd-mirror@rbd-mirror.{hostname}".format( hostname=node["vars"]["inventory_hostname"] ) s = host.service(service_name) assert s.is_enabled assert s.is_running def test_rbd_mirror_is_up(self, node, host, setup): hostname = node["vars"]["inventory_hostname"] cluster = setup["cluster_name"] container_binary = setup["container_binary"] daemons = [] if node['docker']: container_exec_cmd = '{container_binary} exec ceph-rbd-mirror-{hostname}'.format( hostname=hostname, container_binary=container_binary) else: container_exec_cmd = '' hostname = node["vars"]["inventory_hostname"] cluster = setup['cluster_name'] cmd = "sudo {container_exec_cmd} ceph --name client.bootstrap-rbd-mirror --keyring /var/lib/ceph/bootstrap-rbd-mirror/{cluster}.keyring --cluster={cluster} --connect-timeout 5 -f json -s".format( container_exec_cmd=container_exec_cmd, hostname=hostname, cluster=cluster ) output = host.check_output(cmd) status = json.loads(output) daemon_ids = [i for i in status["servicemap"]["services"] ["rbd-mirror"]["daemons"].keys() if i != "summary"] for daemon_id in daemon_ids: daemons.append(status["servicemap"]["services"]["rbd-mirror"] ["daemons"][daemon_id]["metadata"]["hostname"]) assert hostname in daemons
true
true
f72d0b8d703a8988d4c6fdaaab16ad16480f62ab
10,785
py
Python
src/summarycode/summarizer.py
sthagen/nexB-scancode-toolkit
12cc1286df78af898fae76fa339da2bb50ad51b9
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
src/summarycode/summarizer.py
sthagen/nexB-scancode-toolkit
12cc1286df78af898fae76fa339da2bb50ad51b9
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
src/summarycode/summarizer.py
sthagen/nexB-scancode-toolkit
12cc1286df78af898fae76fa339da2bb50ad51b9
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
# # Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/scancode-toolkit for support or download. # See https://aboutcode.org for more information about nexB OSS projects. # from collections import defaultdict import attr import fingerprints from commoncode.cliutils import POST_SCAN_GROUP, PluggableCommandLineOption from license_expression import Licensing from plugincode.post_scan import PostScanPlugin, post_scan_impl from cluecode.copyrights import CopyrightDetector from packagedcode.utils import combine_expressions from packagedcode import models from summarycode.score import compute_license_score from summarycode.score import get_field_values_from_codebase_resources from summarycode.score import unique from summarycode.tallies import compute_codebase_tallies # Tracing flags TRACE = False TRACE_LIGHT = False def logger_debug(*args): pass if TRACE or TRACE_LIGHT: import logging import sys logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stdout) logger.setLevel(logging.DEBUG) def logger_debug(*args): return logger.debug(' '.join(isinstance(a, str) and a or repr(a) for a in args)) """ Create summarized scan data. """ @post_scan_impl class ScanSummary(PostScanPlugin): """ Summarize a scan at the codebase level. """ sort_order = 10 codebase_attributes = dict(summary=attr.ib(default=attr.Factory(dict))) options = [ PluggableCommandLineOption( ('--summary',), is_flag=True, default=False, help='Summarize scans by providing declared origin ' 'information and other detected origin info at the ' 'codebase attribute level.', help_group=POST_SCAN_GROUP, required_options=['classify'], ) ] def is_enabled(self, summary, **kwargs): return summary def process_codebase(self, codebase, summary, **kwargs): if TRACE_LIGHT: logger_debug('ScanSummary:process_codebase') # Get tallies tallies = compute_codebase_tallies(codebase, keep_details=False, **kwargs) license_expressions_tallies = tallies.get('license_expressions') or [] holders_tallies = tallies.get('holders') or [] programming_language_tallies = tallies.get('programming_language') or [] # Determine declared license expression, declared holder, and primary # language from Package data at the top level. declared_license_expression = None declared_holders = None primary_language = None # use top level packages if hasattr(codebase.attributes, 'packages'): top_level_packages = codebase.attributes.packages ( declared_license_expression, declared_holders, primary_language, ) = get_origin_info_from_top_level_packages( top_level_packages=top_level_packages, codebase=codebase, ) if declared_license_expression: scoring_elements, _ = compute_license_score(codebase) else: # If we did not get a declared license expression from detected # package data, then we use the results from `compute_license_score` scoring_elements, declared_license_expression = compute_license_score(codebase) other_license_expressions = remove_from_tallies( declared_license_expression, license_expressions_tallies ) if not declared_holders: declared_holders = get_declared_holders(codebase, holders_tallies) other_holders = remove_from_tallies(declared_holders, holders_tallies) declared_holder = ', '.join(declared_holders) if not primary_language: primary_language = get_primary_language(programming_language_tallies) other_languages = remove_from_tallies(primary_language, programming_language_tallies) # Save summary info to codebase codebase.attributes.summary['declared_license_expression'] = declared_license_expression codebase.attributes.summary['license_clarity_score'] = scoring_elements.to_dict() codebase.attributes.summary['declared_holder'] = declared_holder codebase.attributes.summary['primary_language'] = primary_language codebase.attributes.summary['other_license_expressions'] = other_license_expressions codebase.attributes.summary['other_holders'] = other_holders codebase.attributes.summary['other_languages'] = other_languages def remove_from_tallies(entry, tallies): """ Return an list containing the elements of `tallies`, without `entry` """ pruned_tallies = [] for t in tallies: if ( isinstance(entry, dict) and t == entry or isinstance(entry, (list, tuple)) and t in entry or isinstance(entry, (list, tuple)) and t.get('value') in entry or t.get('value') == entry ): continue pruned_tallies.append(t) return pruned_tallies def get_declared_holders(codebase, holders_tallies): """ Return a list of declared holders from a codebase using the holders detected from key files. A declared holder is a copyright holder present in the key files who has the highest amount of refrences throughout the codebase. """ entry_by_holders = { fingerprints.generate(entry['value']): entry for entry in holders_tallies if entry['value'] } key_file_holders = get_field_values_from_codebase_resources( codebase, 'holders', key_files_only=True ) entry_by_key_file_holders = { fingerprints.generate(entry['holder']): entry for entry in key_file_holders if entry['holder'] } unique_key_file_holders = unique(entry_by_key_file_holders.keys()) unique_key_file_holders_entries = [ entry_by_holders[holder] for holder in unique_key_file_holders ] holder_by_counts = defaultdict(list) for holder_entry in unique_key_file_holders_entries: count = holder_entry.get('count') if count: holder = holder_entry.get('value') holder_by_counts[count].append(holder) declared_holders = [] if holder_by_counts: highest_count = max(holder_by_counts) declared_holders = holder_by_counts[highest_count] # If we could not determine a holder, then we return a list of all the # unique key file holders if not declared_holders: declared_holders = [entry['value'] for entry in unique_key_file_holders_entries] return declared_holders def get_primary_language(programming_language_tallies): """ Return the most common detected programming language as the primary language. """ programming_languages_by_count = { entry['count']: entry['value'] for entry in programming_language_tallies } primary_language = '' if programming_languages_by_count: highest_count = max(programming_languages_by_count) primary_language = programming_languages_by_count[highest_count] or '' return primary_language def get_origin_info_from_top_level_packages(top_level_packages, codebase): """ Return a 3-tuple containing the strings of declared license expression, copyright holder, and primary programming language from a ``top_level_packages`` list of detected top-level packages mapping and a ``codebase``. """ if not top_level_packages: return '', '', '' license_expressions = [] programming_languages = [] copyrights = [] parties = [] for package_mapping in top_level_packages: package = models.Package.from_dict(package_mapping) # we are only interested in key packages if not is_key_package(package, codebase): continue license_expression = package.license_expression if license_expression: license_expressions.append(license_expression) programming_language = package.primary_language if programming_language: programming_languages.append(programming_language) copyright_statement = package.copyright if copyright_statement: copyrights.append(copyright_statement) parties.extend(package.parties or []) # Combine license expressions unique_license_expressions = unique(license_expressions) combined_declared_license_expression = combine_expressions( expressions=unique_license_expressions, relation='AND', ) declared_license_expression = '' if combined_declared_license_expression: declared_license_expression = str( Licensing().parse(combined_declared_license_expression).simplify() ) # Get holders holders = list(get_holders_from_copyright(copyrights)) declared_holders = [] if holders: declared_holders = holders elif parties: declared_holders = [party.name for party in parties or []] declared_holders = unique(declared_holders) # Programming language unique_programming_languages = unique(programming_languages) primary_language = '' if len(unique_programming_languages) == 1: primary_language = unique_programming_languages[0] return declared_license_expression, declared_holders, primary_language def get_holders_from_copyright(copyright): """ Yield holders detected from a `copyright` string or list. """ numbered_lines = [] if isinstance(copyright, list): for i, c in enumerate(copyright): numbered_lines.append((i, c)) else: numbered_lines.append((0, copyright)) holder_detections = CopyrightDetector().detect( numbered_lines, include_copyrights=False, include_holders=True, include_authors=False, ) for holder_detection in holder_detections: yield holder_detection.holder def is_key_package(package, codebase): """ Return True if the ``package`` Package is a key, top-level package. """ # get the datafile_paths of the package # get the top level files in the codebase # return True if any datafile_paths is also a top level files? or key file? datafile_paths = set(package.datafile_paths or []) for resource in codebase.walk(topdown=True): if not resource.is_top_level: break if resource.path in datafile_paths: return True return False
33.915094
99
0.697636
from collections import defaultdict import attr import fingerprints from commoncode.cliutils import POST_SCAN_GROUP, PluggableCommandLineOption from license_expression import Licensing from plugincode.post_scan import PostScanPlugin, post_scan_impl from cluecode.copyrights import CopyrightDetector from packagedcode.utils import combine_expressions from packagedcode import models from summarycode.score import compute_license_score from summarycode.score import get_field_values_from_codebase_resources from summarycode.score import unique from summarycode.tallies import compute_codebase_tallies TRACE = False TRACE_LIGHT = False def logger_debug(*args): pass if TRACE or TRACE_LIGHT: import logging import sys logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stdout) logger.setLevel(logging.DEBUG) def logger_debug(*args): return logger.debug(' '.join(isinstance(a, str) and a or repr(a) for a in args)) @post_scan_impl class ScanSummary(PostScanPlugin): sort_order = 10 codebase_attributes = dict(summary=attr.ib(default=attr.Factory(dict))) options = [ PluggableCommandLineOption( ('--summary',), is_flag=True, default=False, help='Summarize scans by providing declared origin ' 'information and other detected origin info at the ' 'codebase attribute level.', help_group=POST_SCAN_GROUP, required_options=['classify'], ) ] def is_enabled(self, summary, **kwargs): return summary def process_codebase(self, codebase, summary, **kwargs): if TRACE_LIGHT: logger_debug('ScanSummary:process_codebase') tallies = compute_codebase_tallies(codebase, keep_details=False, **kwargs) license_expressions_tallies = tallies.get('license_expressions') or [] holders_tallies = tallies.get('holders') or [] programming_language_tallies = tallies.get('programming_language') or [] declared_license_expression = None declared_holders = None primary_language = None if hasattr(codebase.attributes, 'packages'): top_level_packages = codebase.attributes.packages ( declared_license_expression, declared_holders, primary_language, ) = get_origin_info_from_top_level_packages( top_level_packages=top_level_packages, codebase=codebase, ) if declared_license_expression: scoring_elements, _ = compute_license_score(codebase) else: scoring_elements, declared_license_expression = compute_license_score(codebase) other_license_expressions = remove_from_tallies( declared_license_expression, license_expressions_tallies ) if not declared_holders: declared_holders = get_declared_holders(codebase, holders_tallies) other_holders = remove_from_tallies(declared_holders, holders_tallies) declared_holder = ', '.join(declared_holders) if not primary_language: primary_language = get_primary_language(programming_language_tallies) other_languages = remove_from_tallies(primary_language, programming_language_tallies) codebase.attributes.summary['declared_license_expression'] = declared_license_expression codebase.attributes.summary['license_clarity_score'] = scoring_elements.to_dict() codebase.attributes.summary['declared_holder'] = declared_holder codebase.attributes.summary['primary_language'] = primary_language codebase.attributes.summary['other_license_expressions'] = other_license_expressions codebase.attributes.summary['other_holders'] = other_holders codebase.attributes.summary['other_languages'] = other_languages def remove_from_tallies(entry, tallies): pruned_tallies = [] for t in tallies: if ( isinstance(entry, dict) and t == entry or isinstance(entry, (list, tuple)) and t in entry or isinstance(entry, (list, tuple)) and t.get('value') in entry or t.get('value') == entry ): continue pruned_tallies.append(t) return pruned_tallies def get_declared_holders(codebase, holders_tallies): entry_by_holders = { fingerprints.generate(entry['value']): entry for entry in holders_tallies if entry['value'] } key_file_holders = get_field_values_from_codebase_resources( codebase, 'holders', key_files_only=True ) entry_by_key_file_holders = { fingerprints.generate(entry['holder']): entry for entry in key_file_holders if entry['holder'] } unique_key_file_holders = unique(entry_by_key_file_holders.keys()) unique_key_file_holders_entries = [ entry_by_holders[holder] for holder in unique_key_file_holders ] holder_by_counts = defaultdict(list) for holder_entry in unique_key_file_holders_entries: count = holder_entry.get('count') if count: holder = holder_entry.get('value') holder_by_counts[count].append(holder) declared_holders = [] if holder_by_counts: highest_count = max(holder_by_counts) declared_holders = holder_by_counts[highest_count] if not declared_holders: declared_holders = [entry['value'] for entry in unique_key_file_holders_entries] return declared_holders def get_primary_language(programming_language_tallies): programming_languages_by_count = { entry['count']: entry['value'] for entry in programming_language_tallies } primary_language = '' if programming_languages_by_count: highest_count = max(programming_languages_by_count) primary_language = programming_languages_by_count[highest_count] or '' return primary_language def get_origin_info_from_top_level_packages(top_level_packages, codebase): if not top_level_packages: return '', '', '' license_expressions = [] programming_languages = [] copyrights = [] parties = [] for package_mapping in top_level_packages: package = models.Package.from_dict(package_mapping) if not is_key_package(package, codebase): continue license_expression = package.license_expression if license_expression: license_expressions.append(license_expression) programming_language = package.primary_language if programming_language: programming_languages.append(programming_language) copyright_statement = package.copyright if copyright_statement: copyrights.append(copyright_statement) parties.extend(package.parties or []) unique_license_expressions = unique(license_expressions) combined_declared_license_expression = combine_expressions( expressions=unique_license_expressions, relation='AND', ) declared_license_expression = '' if combined_declared_license_expression: declared_license_expression = str( Licensing().parse(combined_declared_license_expression).simplify() ) holders = list(get_holders_from_copyright(copyrights)) declared_holders = [] if holders: declared_holders = holders elif parties: declared_holders = [party.name for party in parties or []] declared_holders = unique(declared_holders) unique_programming_languages = unique(programming_languages) primary_language = '' if len(unique_programming_languages) == 1: primary_language = unique_programming_languages[0] return declared_license_expression, declared_holders, primary_language def get_holders_from_copyright(copyright): numbered_lines = [] if isinstance(copyright, list): for i, c in enumerate(copyright): numbered_lines.append((i, c)) else: numbered_lines.append((0, copyright)) holder_detections = CopyrightDetector().detect( numbered_lines, include_copyrights=False, include_holders=True, include_authors=False, ) for holder_detection in holder_detections: yield holder_detection.holder def is_key_package(package, codebase): datafile_paths = set(package.datafile_paths or []) for resource in codebase.walk(topdown=True): if not resource.is_top_level: break if resource.path in datafile_paths: return True return False
true
true
f72d0b98b7272d4c524f74d442bb17b81bda3d2a
1,257
py
Python
salt/pillar/varstack_pillar.py
preoctopus/salt
aceaaa0e2f2f2ff29a694393bd82bba0d88fa44d
[ "Apache-2.0" ]
3
2015-04-16T18:42:35.000Z
2017-10-30T16:57:49.000Z
salt/pillar/varstack_pillar.py
preoctopus/salt
aceaaa0e2f2f2ff29a694393bd82bba0d88fa44d
[ "Apache-2.0" ]
16
2015-11-18T00:44:03.000Z
2018-10-29T20:48:27.000Z
salt/pillar/varstack_pillar.py
preoctopus/salt
aceaaa0e2f2f2ff29a694393bd82bba0d88fa44d
[ "Apache-2.0" ]
4
2020-11-04T06:28:05.000Z
2022-02-09T10:54:49.000Z
# -*- coding: utf-8 -*- ''' Use `Varstack <https://github.com/conversis/varstack>`_ data as a Pillar source Configuring Varstack ==================== Using varstack in Salt is fairly simple. Just put the following into the config file of your master: .. code-block:: yaml ext_pillar: - varstack: /etc/varstack.yaml Varstack will then use /etc/varstack.yaml to determine which configuration data to return as pillar information. From there you can take a look at the `README <https://github.com/conversis/varstack/blob/master/README.md>`_ of varstack on how this file is evaluated. ''' from __future__ import absolute_import # Import python libs import logging HAS_VARSTACK = False try: import varstack HAS_VARSTACK = True except ImportError: pass # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'varstack' def __virtual__(): if not HAS_VARSTACK: return False return __virtualname__ def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 conf): ''' Parse varstack data and return the result ''' vs = varstack.Varstack(config_filename=conf) return vs.evaluate(__grains__)
22.854545
79
0.703262
from __future__ import absolute_import import logging HAS_VARSTACK = False try: import varstack HAS_VARSTACK = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'varstack' def __virtual__(): if not HAS_VARSTACK: return False return __virtualname__ def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 conf): vs = varstack.Varstack(config_filename=conf) return vs.evaluate(__grains__)
true
true
f72d0c4a82e81d1e634b40b84dd34a80b3db88c1
113
py
Python
Codeforces/637B Nastya and Door.py
a3X3k/Competitive-programing-hacktoberfest-2021
bc3997997318af4c5eafad7348abdd9bf5067b4f
[ "Unlicense" ]
12
2021-06-05T09:40:10.000Z
2021-10-07T17:59:51.000Z
Codeforces/637B Nastya and Door.py
a3X3k/Competitive-programing-hacktoberfest-2021
bc3997997318af4c5eafad7348abdd9bf5067b4f
[ "Unlicense" ]
21
2020-10-10T10:41:03.000Z
2020-10-31T10:41:23.000Z
Codeforces/637B Nastya and Door.py
a3X3k/Competitive-programing-hacktoberfest-2021
bc3997997318af4c5eafad7348abdd9bf5067b4f
[ "Unlicense" ]
67
2021-08-01T10:04:52.000Z
2021-10-10T00:25:04.000Z
t = int(input()) for t in range(t): m,d=map(int,input().split()) l = list(map(int,input().split()))
22.6
38
0.530973
t = int(input()) for t in range(t): m,d=map(int,input().split()) l = list(map(int,input().split()))
true
true
f72d0cd7918505dd6a72b02b05dfa02f870e64c9
710
py
Python
News163_Spider/News163_Spider/pipelines.py
a904919863/Spiders_Collection
970aef563971eba5c9dca5dfe1cd8790561941be
[ "MIT" ]
3
2022-02-23T02:44:47.000Z
2022-02-28T06:41:26.000Z
News163_Spider/News163_Spider/pipelines.py
a904919863/Spiders_Collection
970aef563971eba5c9dca5dfe1cd8790561941be
[ "MIT" ]
null
null
null
News163_Spider/News163_Spider/pipelines.py
a904919863/Spiders_Collection
970aef563971eba5c9dca5dfe1cd8790561941be
[ "MIT" ]
null
null
null
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter class News163SpiderPipeline: fp = None def open_spider(self,spider): print('开始爬虫......') self.fp = open('./news163.txt','w',encoding='utf-8') def process_item(self, item, spider): author = item['title'] content = item['content'] self.fp.write(author+":"+content+"\n") return item def close_spider(self,spider): print('结束爬虫!') self.fp.close()
25.357143
66
0.64507
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter class News163SpiderPipeline: fp = None def open_spider(self,spider): print('开始爬虫......') self.fp = open('./news163.txt','w',encoding='utf-8') def process_item(self, item, spider): author = item['title'] content = item['content'] self.fp.write(author+":"+content+"\n") return item def close_spider(self,spider): print('结束爬虫!') self.fp.close()
true
true
f72d0f27a1d1b5199bb5a8833ffec4a28cd377c8
2,104
py
Python
PasswordManager/LoginDialog.py
whymatter/PasswordManager
86070a1f998362cfa026e6e6e9b820a2d7ad5f06
[ "MIT" ]
null
null
null
PasswordManager/LoginDialog.py
whymatter/PasswordManager
86070a1f998362cfa026e6e6e9b820a2d7ad5f06
[ "MIT" ]
null
null
null
PasswordManager/LoginDialog.py
whymatter/PasswordManager
86070a1f998362cfa026e6e6e9b820a2d7ad5f06
[ "MIT" ]
null
null
null
import sys import os.path from PyQt5 import QtWidgets, uic from PyQt5.QtWidgets import QApplication, QTableWidgetItem from Crypto.Cipher import AES import json from constants import FILE_NAME, KEY_ENCODING from PwWindow import PwWindow # -*- coding: utf-8 -*- """ Created on Fri Nov 17 13:53:56 2017 @author: seitz """ class LoginDialog(QtWidgets.QDialog): def __init__(self, parent=None, key=None): super(LoginDialog, self).__init__(parent) self.pw_window = None # load and show the user interface created with the designer. uic.loadUi('../login_dialog.ui', self) self.login_button.clicked.connect(self.login) self.show() def get_key(self): return self.key_lineedit.text().encode(KEY_ENCODING) def login(self): if not os.path.isfile(FILE_NAME): cipher = AES.new(self.get_key(), AES.MODE_EAX) ciphertext, tag = cipher.encrypt_and_digest(json.dumps([]).encode(KEY_ENCODING)) with open(FILE_NAME, "wb") as file_out: [ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ] if self.load_data(FILE_NAME, self.get_key()): self.hide() self.pw_window = PwWindow(key=self.get_key()) def load_data(self, filename, key): try: with open(filename, 'rb') as file_in: print(file_in) nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ] # let's assume that the key is somehow available again cipher = AES.new(key, AES.MODE_EAX, nonce) jsontext = cipher.decrypt_and_verify(ciphertext, tag) data = json.loads(jsontext) return True except Exception as e: print("Your file contains errors") print(e) return False def _main(): app = QApplication(sys.argv) m = LoginDialog() sys.exit(app.exec_()) if __name__ == '__main__': _main()
30.492754
93
0.586502
import sys import os.path from PyQt5 import QtWidgets, uic from PyQt5.QtWidgets import QApplication, QTableWidgetItem from Crypto.Cipher import AES import json from constants import FILE_NAME, KEY_ENCODING from PwWindow import PwWindow class LoginDialog(QtWidgets.QDialog): def __init__(self, parent=None, key=None): super(LoginDialog, self).__init__(parent) self.pw_window = None uic.loadUi('../login_dialog.ui', self) self.login_button.clicked.connect(self.login) self.show() def get_key(self): return self.key_lineedit.text().encode(KEY_ENCODING) def login(self): if not os.path.isfile(FILE_NAME): cipher = AES.new(self.get_key(), AES.MODE_EAX) ciphertext, tag = cipher.encrypt_and_digest(json.dumps([]).encode(KEY_ENCODING)) with open(FILE_NAME, "wb") as file_out: [ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ] if self.load_data(FILE_NAME, self.get_key()): self.hide() self.pw_window = PwWindow(key=self.get_key()) def load_data(self, filename, key): try: with open(filename, 'rb') as file_in: print(file_in) nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ] cipher = AES.new(key, AES.MODE_EAX, nonce) jsontext = cipher.decrypt_and_verify(ciphertext, tag) data = json.loads(jsontext) return True except Exception as e: print("Your file contains errors") print(e) return False def _main(): app = QApplication(sys.argv) m = LoginDialog() sys.exit(app.exec_()) if __name__ == '__main__': _main()
true
true
f72d0f3414639adbfb45b04d9d66268327301c51
380
py
Python
apps/db_data/migrations/0018_auto_20200723_2120.py
rhu2001/csua-backend
d2464c7eacfd1d675e0cc08f93f3b5083fa591dc
[ "MIT" ]
null
null
null
apps/db_data/migrations/0018_auto_20200723_2120.py
rhu2001/csua-backend
d2464c7eacfd1d675e0cc08f93f3b5083fa591dc
[ "MIT" ]
null
null
null
apps/db_data/migrations/0018_auto_20200723_2120.py
rhu2001/csua-backend
d2464c7eacfd1d675e0cc08f93f3b5083fa591dc
[ "MIT" ]
null
null
null
# Generated by Django 2.2.12 on 2020-07-24 04:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('db_data', '0017_notice'), ] operations = [ migrations.AlterField( model_name='officer', name='officer_since', field=models.DateField(blank=True), ), ]
20
48
0.592105
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('db_data', '0017_notice'), ] operations = [ migrations.AlterField( model_name='officer', name='officer_since', field=models.DateField(blank=True), ), ]
true
true
f72d0f3e5dbf9fe0132a52a219eaa07ffb21b9cc
4,297
py
Python
npy_append_array/npy_append_array.py
synapticarbors/npy-append-array
bf33483e7c2c50e13c9e55940878ca8217f4d4ad
[ "MIT" ]
null
null
null
npy_append_array/npy_append_array.py
synapticarbors/npy-append-array
bf33483e7c2c50e13c9e55940878ca8217f4d4ad
[ "MIT" ]
null
null
null
npy_append_array/npy_append_array.py
synapticarbors/npy-append-array
bf33483e7c2c50e13c9e55940878ca8217f4d4ad
[ "MIT" ]
null
null
null
import numpy as np import os.path from struct import pack, unpack from io import BytesIO def header_tuple_dict(tuple_in): return { 'shape': tuple_in[0], 'fortran_order': tuple_in[1], 'descr': np.lib.format.dtype_to_descr(tuple_in[2]) } def has_fortran_order(arr): return not arr.flags.c_contiguous and arr.flags.f_contiguous def peek(fp, length): pos = fp.tell() tmp = fp.read(length) fp.seek(pos) return tmp class NpyAppendArray: def __init__(self, filename): self.filename = filename self.fp = None self.__is_init = False if os.path.isfile(filename): self.__init() def __init(self): self.fp = open(self.filename, mode="rb+") fp = self.fp magic = np.lib.format.read_magic(fp) self.is_version_1 = magic[0] == 1 and magic[1] == 0 self.is_version_2 = magic[0] == 2 and magic[1] == 0 if not self.is_version_1 and not self.is_version_2: raise NotImplementedError( "version (%d, %d) not implemented"%magic ) self.header_length, = unpack("<H", peek(fp, 2)) if self.is_version_1 \ else unpack("<I", peek(fp, 4)) self.header = np.lib.format.read_array_header_1_0(fp) if \ self.is_version_1 else np.lib.format.read_array_header_2_0(fp) if self.header[1] != False: raise NotImplementedError("fortran_order not implemented") fp.seek(0) self.header_bytes = fp.read(self.header_length + ( 10 if self.is_version_1 else 12 )) fp.seek(0, 2) self.__is_init = True def __create_header_bytes(self, header_map, spare_space=False): io = BytesIO() np.lib.format.write_array_header_2_0(io, header_map) if spare_space: io.getbuffer()[8:12] = pack("<I", int( io.getbuffer().nbytes-12+64 )) io.getbuffer()[-1] = 32 io.write(b" "*64) io.getbuffer()[-1] = 10 return io.getbuffer() def append(self, arr): if not arr.flags.c_contiguous: raise NotImplementedError("ndarray needs to be c_contiguous") if has_fortran_order(arr): raise NotImplementedError("fortran_order not implemented") arr_descr = np.lib.format.dtype_to_descr(arr.dtype) if not self.__is_init: with open(self.filename, "wb") as fp0: fp0.write(self.__create_header_bytes({ 'descr': arr_descr, 'fortran_order': False, 'shape': arr.shape }, True)) arr.tofile(fp0) # np.save(self.filename, arr) self.__init() return descr = self.header[2] if arr_descr != descr: raise TypeError("incompatible ndarrays types %s and %s"%( arr_descr, descr )) shape = self.header[0] if len(arr.shape) != len(shape): raise TypeError("incompatible ndarrays shape lengths %s and %s"%( len(arr.shape), len(shape) )) for i, e in enumerate(shape): if i > 0 and e != arr.shape[i]: raise TypeError("ndarray shapes can only differ on zero axis") new_shape = list(shape) new_shape[0] += arr.shape[0] new_shape = tuple(new_shape) self.header = (new_shape, self.header[1], self.header[2]) self.fp.seek(0) new_header_map = header_tuple_dict(self.header) new_header_bytes = self.__create_header_bytes(new_header_map, True) header_length = len(self.header_bytes) if header_length != len(new_header_bytes): new_header_bytes = self.__create_header_bytes(new_header_map) if header_length != len(new_header_bytes): raise TypeError("header length mismatch, old: %d, new: %d"%( header_length, len(new_header_bytes) )) self.header_bytes = new_header_bytes self.fp.write(new_header_bytes) self.fp.seek(0, 2) arr.tofile(self.fp) def __del__(self): if self.fp is not None: self.fp.close()
29.431507
78
0.573191
import numpy as np import os.path from struct import pack, unpack from io import BytesIO def header_tuple_dict(tuple_in): return { 'shape': tuple_in[0], 'fortran_order': tuple_in[1], 'descr': np.lib.format.dtype_to_descr(tuple_in[2]) } def has_fortran_order(arr): return not arr.flags.c_contiguous and arr.flags.f_contiguous def peek(fp, length): pos = fp.tell() tmp = fp.read(length) fp.seek(pos) return tmp class NpyAppendArray: def __init__(self, filename): self.filename = filename self.fp = None self.__is_init = False if os.path.isfile(filename): self.__init() def __init(self): self.fp = open(self.filename, mode="rb+") fp = self.fp magic = np.lib.format.read_magic(fp) self.is_version_1 = magic[0] == 1 and magic[1] == 0 self.is_version_2 = magic[0] == 2 and magic[1] == 0 if not self.is_version_1 and not self.is_version_2: raise NotImplementedError( "version (%d, %d) not implemented"%magic ) self.header_length, = unpack("<H", peek(fp, 2)) if self.is_version_1 \ else unpack("<I", peek(fp, 4)) self.header = np.lib.format.read_array_header_1_0(fp) if \ self.is_version_1 else np.lib.format.read_array_header_2_0(fp) if self.header[1] != False: raise NotImplementedError("fortran_order not implemented") fp.seek(0) self.header_bytes = fp.read(self.header_length + ( 10 if self.is_version_1 else 12 )) fp.seek(0, 2) self.__is_init = True def __create_header_bytes(self, header_map, spare_space=False): io = BytesIO() np.lib.format.write_array_header_2_0(io, header_map) if spare_space: io.getbuffer()[8:12] = pack("<I", int( io.getbuffer().nbytes-12+64 )) io.getbuffer()[-1] = 32 io.write(b" "*64) io.getbuffer()[-1] = 10 return io.getbuffer() def append(self, arr): if not arr.flags.c_contiguous: raise NotImplementedError("ndarray needs to be c_contiguous") if has_fortran_order(arr): raise NotImplementedError("fortran_order not implemented") arr_descr = np.lib.format.dtype_to_descr(arr.dtype) if not self.__is_init: with open(self.filename, "wb") as fp0: fp0.write(self.__create_header_bytes({ 'descr': arr_descr, 'fortran_order': False, 'shape': arr.shape }, True)) arr.tofile(fp0) self.__init() return descr = self.header[2] if arr_descr != descr: raise TypeError("incompatible ndarrays types %s and %s"%( arr_descr, descr )) shape = self.header[0] if len(arr.shape) != len(shape): raise TypeError("incompatible ndarrays shape lengths %s and %s"%( len(arr.shape), len(shape) )) for i, e in enumerate(shape): if i > 0 and e != arr.shape[i]: raise TypeError("ndarray shapes can only differ on zero axis") new_shape = list(shape) new_shape[0] += arr.shape[0] new_shape = tuple(new_shape) self.header = (new_shape, self.header[1], self.header[2]) self.fp.seek(0) new_header_map = header_tuple_dict(self.header) new_header_bytes = self.__create_header_bytes(new_header_map, True) header_length = len(self.header_bytes) if header_length != len(new_header_bytes): new_header_bytes = self.__create_header_bytes(new_header_map) if header_length != len(new_header_bytes): raise TypeError("header length mismatch, old: %d, new: %d"%( header_length, len(new_header_bytes) )) self.header_bytes = new_header_bytes self.fp.write(new_header_bytes) self.fp.seek(0, 2) arr.tofile(self.fp) def __del__(self): if self.fp is not None: self.fp.close()
true
true
f72d0fdb931b1dcc84a293aeef05fc7e649e1c49
23
py
Python
prepack/__init__.py
CargoCodes/PreparePack
3d1d3623c0c86ab02a92a567ed954fb37e18b8fa
[ "MIT" ]
null
null
null
prepack/__init__.py
CargoCodes/PreparePack
3d1d3623c0c86ab02a92a567ed954fb37e18b8fa
[ "MIT" ]
null
null
null
prepack/__init__.py
CargoCodes/PreparePack
3d1d3623c0c86ab02a92a567ed954fb37e18b8fa
[ "MIT" ]
null
null
null
from .prepack import *
11.5
22
0.73913
from .prepack import *
true
true
f72d1029095787de77bafa202e5314c2ea6e90db
262
py
Python
examples/client.py
Scauting-Burgum/RemoteVar
bc3b1ffaace5defed1cd3a3e7042002717a3e44a
[ "MIT" ]
1
2018-06-14T14:59:56.000Z
2018-06-14T14:59:56.000Z
examples/client.py
Scauting-Burgum/ScautEvent-python
bc3b1ffaace5defed1cd3a3e7042002717a3e44a
[ "MIT" ]
null
null
null
examples/client.py
Scauting-Burgum/ScautEvent-python
bc3b1ffaace5defed1cd3a3e7042002717a3e44a
[ "MIT" ]
null
null
null
from ScautEvent.client import EventClient from ScautEvent.common import Event client = EventClient("localhost", 5000) client.listeners["message"] = print client.start() while True: message = input() event = Event("message", message) client.push(event)
18.714286
41
0.748092
from ScautEvent.client import EventClient from ScautEvent.common import Event client = EventClient("localhost", 5000) client.listeners["message"] = print client.start() while True: message = input() event = Event("message", message) client.push(event)
true
true
f72d105dd8903c3509596490416a261c9efa1878
7,239
py
Python
tests/gold_tests/tls/tls_tunnel_forward.test.py
masaori335/trafficserver
58e7e8675c96a5a4eb958a442942892f6e2a0ef4
[ "Apache-2.0" ]
1
2019-10-28T04:36:50.000Z
2019-10-28T04:36:50.000Z
tests/gold_tests/tls/tls_tunnel_forward.test.py
masaori335/trafficserver
58e7e8675c96a5a4eb958a442942892f6e2a0ef4
[ "Apache-2.0" ]
1
2021-06-27T23:06:33.000Z
2021-06-27T23:06:33.000Z
tests/gold_tests/tls/tls_tunnel_forward.test.py
masaori335/trafficserver
58e7e8675c96a5a4eb958a442942892f6e2a0ef4
[ "Apache-2.0" ]
null
null
null
''' ''' # 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 os Test.Summary = ''' Test tunneling and forwarding based on SNI ''' # Define default ATS ts = Test.MakeATSProcess("ts", select_ports=False) server_foo = Test.MakeOriginServer("server_foo", ssl=True) server_bar = Test.MakeOriginServer("server_bar", ssl=False) server_random = Test.MakeOriginServer("server_random", ssl=False) request_foo_header = {"headers": "GET / HTTP/1.1\r\nHost: foo.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""} request_bar_header = {"headers": "GET / HTTP/1.1\r\nHost: bar.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""} request_random_header = {"headers": "GET / HTTP/1.1\r\nHost: random.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""} response_foo_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": "ok foo"} response_bar_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": "ok bar"} response_random_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": "ok random"} server_foo.addResponse("sessionlog_foo.json", request_foo_header, response_foo_header) server_bar.addResponse("sessionlog_bar.json", request_bar_header, response_bar_header) server_random.addResponse("sessionlog_random.json", request_random_header, response_random_header) # add ssl materials like key, certificates for the server ts.addSSLfile("ssl/signed-foo.pem") ts.addSSLfile("ssl/signed-foo.key") ts.addSSLfile("ssl/signed-bar.pem") ts.addSSLfile("ssl/signed-bar.key") ts.addSSLfile("ssl/server.pem") ts.addSSLfile("ssl/server.key") ts.addSSLfile("ssl/signer.pem") ts.addSSLfile("ssl/signer.key") ts.Variables.ssl_port = 4443 # Need no remap rules. Everything should be proccessed by ssl_server_name # Make sure the TS server certs are different from the origin certs ts.Disk.ssl_multicert_config.AddLine( 'dest_ip=* ssl_cert_name=signed-foo.pem ssl_key_name=signed-foo.key' ) # Case 1, global config policy=permissive properties=signature # override for foo.com policy=enforced properties=all ts.Disk.records_config.update({ 'proxy.config.ssl.server.cert.path': '{0}'.format(ts.Variables.SSLDir), 'proxy.config.ssl.server.private_key.path': '{0}'.format(ts.Variables.SSLDir), # enable ssl port 'proxy.config.http.server_ports': '{0} {1}:proto=http2;http:ssl'.format(ts.Variables.port, ts.Variables.ssl_port), 'proxy.config.http.connect_ports': '{0} {1} {2} {3}'.format(ts.Variables.ssl_port, server_foo.Variables.SSL_Port, server_bar.Variables.Port, server_random.Variables.Port), 'proxy.config.ssl.server.cipher_suite': 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:RC4-SHA:RC4-MD5:AES128-SHA:AES256-SHA:DES-CBC3-SHA!SRP:!DSS:!PSK:!aNULL:!eNULL:!SSLv2', 'proxy.config.ssl.client.CA.cert.path': '{0}'.format(ts.Variables.SSLDir), 'proxy.config.ssl.client.CA.cert.filename': 'signer.pem', 'proxy.config.exec_thread.autoconfig.scale': 1.0, 'proxy.config.url_remap.pristine_host_hdr': 1 }) # foo.com should not terminate. Just tunnel to server_foo # bar.com should terminate. Forward its tcp stream to server_bar ts.Disk.ssl_server_name_yaml.AddLines([ "- fqdn: 'foo.com'", " tunnel_route: 'localhost:{0}'".format(server_foo.Variables.SSL_Port), "- fqdn: 'bar.com'", " forward_route: 'localhost:{0}'".format(server_bar.Variables.Port), "- fqdn: ''", #default case " forward_route: 'localhost:{0}'".format(server_random.Variables.Port), ]) tr = Test.AddTestRun("Tunnel-test") tr.Processes.Default.Command = "curl -v --resolve 'foo.com:{0}:127.0.0.1' -k https://foo.com:{0}".format(ts.Variables.ssl_port) tr.ReturnCode = 0 tr.Processes.Default.StartBefore(server_foo) tr.Processes.Default.StartBefore(server_bar) tr.Processes.Default.StartBefore(server_random) tr.Processes.Default.StartBefore(Test.Processes.ts, ready=When.PortOpen(ts.Variables.ssl_port)) tr.StillRunningAfter = ts tr.Processes.Default.Streams.All += Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded") tr.Processes.Default.Streams.All += Testers.ExcludesExpression("Not Found on Accelerato", "Should not try to remap on Traffic Server") tr.Processes.Default.Streams.All += Testers.ExcludesExpression("CN=foo.com", "Should not TLS terminate on Traffic Server") tr.Processes.Default.Streams.All += Testers.ContainsExpression("HTTP/1.1 200 OK", "Should get a successful response") tr.Processes.Default.Streams.All += Testers.ContainsExpression("ok foo", "Body is expected") tr2 = Test.AddTestRun("Forward-test") tr2.Processes.Default.Command = "curl -v --http1.1 -H 'host:bar.com' --resolve 'bar.com:{0}:127.0.0.1' -k https://bar.com:{0}".format(ts.Variables.ssl_port) tr2.ReturnCode = 0 tr2.StillRunningAfter = server_bar tr2.StillRunningAfter = ts tr2.Processes.Default.Streams.All += Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded") tr2.Processes.Default.Streams.All += Testers.ExcludesExpression("Not Found on Accelerato", "Should not try to remap on Traffic Server") tr2.Processes.Default.Streams.All += Testers.ContainsExpression("CN=foo.com", "Should TLS terminate on Traffic Server") tr2.Processes.Default.Streams.All += Testers.ContainsExpression("HTTP/1.1 200 OK", "Should get a successful response") tr2.Processes.Default.Streams.All += Testers.ContainsExpression("ok bar", "Body is expected") tr3 = Test.AddTestRun("no-sni-forward-test") tr3.Processes.Default.Command = "curl --http1.1 -v -k -H 'host:random.com' https://127.0.0.1:{0}".format(ts.Variables.ssl_port) tr3.ReturnCode = 0 tr3.StillRunningAfter = server_random tr3.StillRunningAfter = ts tr3.Processes.Default.Streams.All += Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded") tr3.Processes.Default.Streams.All += Testers.ExcludesExpression("Not Found on Accelerato", "Should not try to remap on Traffic Server") tr3.Processes.Default.Streams.All += Testers.ContainsExpression("CN=foo.com", "Should TLS terminate on Traffic Server") tr3.Processes.Default.Streams.All += Testers.ContainsExpression("HTTP/1.1 200 OK", "Should get a successful response") tr3.Processes.Default.Streams.All += Testers.ContainsExpression("ok random", "Body is expected")
60.325
332
0.754524
import os Test.Summary = ''' Test tunneling and forwarding based on SNI ''' ts = Test.MakeATSProcess("ts", select_ports=False) server_foo = Test.MakeOriginServer("server_foo", ssl=True) server_bar = Test.MakeOriginServer("server_bar", ssl=False) server_random = Test.MakeOriginServer("server_random", ssl=False) request_foo_header = {"headers": "GET / HTTP/1.1\r\nHost: foo.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""} request_bar_header = {"headers": "GET / HTTP/1.1\r\nHost: bar.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""} request_random_header = {"headers": "GET / HTTP/1.1\r\nHost: random.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""} response_foo_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": "ok foo"} response_bar_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": "ok bar"} response_random_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": "ok random"} server_foo.addResponse("sessionlog_foo.json", request_foo_header, response_foo_header) server_bar.addResponse("sessionlog_bar.json", request_bar_header, response_bar_header) server_random.addResponse("sessionlog_random.json", request_random_header, response_random_header) ts.addSSLfile("ssl/signed-foo.pem") ts.addSSLfile("ssl/signed-foo.key") ts.addSSLfile("ssl/signed-bar.pem") ts.addSSLfile("ssl/signed-bar.key") ts.addSSLfile("ssl/server.pem") ts.addSSLfile("ssl/server.key") ts.addSSLfile("ssl/signer.pem") ts.addSSLfile("ssl/signer.key") ts.Variables.ssl_port = 4443 ts.Disk.ssl_multicert_config.AddLine( 'dest_ip=* ssl_cert_name=signed-foo.pem ssl_key_name=signed-foo.key' ) ts.Disk.records_config.update({ 'proxy.config.ssl.server.cert.path': '{0}'.format(ts.Variables.SSLDir), 'proxy.config.ssl.server.private_key.path': '{0}'.format(ts.Variables.SSLDir), 'proxy.config.http.server_ports': '{0} {1}:proto=http2;http:ssl'.format(ts.Variables.port, ts.Variables.ssl_port), 'proxy.config.http.connect_ports': '{0} {1} {2} {3}'.format(ts.Variables.ssl_port, server_foo.Variables.SSL_Port, server_bar.Variables.Port, server_random.Variables.Port), 'proxy.config.ssl.server.cipher_suite': 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:RC4-SHA:RC4-MD5:AES128-SHA:AES256-SHA:DES-CBC3-SHA!SRP:!DSS:!PSK:!aNULL:!eNULL:!SSLv2', 'proxy.config.ssl.client.CA.cert.path': '{0}'.format(ts.Variables.SSLDir), 'proxy.config.ssl.client.CA.cert.filename': 'signer.pem', 'proxy.config.exec_thread.autoconfig.scale': 1.0, 'proxy.config.url_remap.pristine_host_hdr': 1 }) ts.Disk.ssl_server_name_yaml.AddLines([ "- fqdn: 'foo.com'", " tunnel_route: 'localhost:{0}'".format(server_foo.Variables.SSL_Port), "- fqdn: 'bar.com'", " forward_route: 'localhost:{0}'".format(server_bar.Variables.Port), "- fqdn: ''", " forward_route: 'localhost:{0}'".format(server_random.Variables.Port), ]) tr = Test.AddTestRun("Tunnel-test") tr.Processes.Default.Command = "curl -v --resolve 'foo.com:{0}:127.0.0.1' -k https://foo.com:{0}".format(ts.Variables.ssl_port) tr.ReturnCode = 0 tr.Processes.Default.StartBefore(server_foo) tr.Processes.Default.StartBefore(server_bar) tr.Processes.Default.StartBefore(server_random) tr.Processes.Default.StartBefore(Test.Processes.ts, ready=When.PortOpen(ts.Variables.ssl_port)) tr.StillRunningAfter = ts tr.Processes.Default.Streams.All += Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded") tr.Processes.Default.Streams.All += Testers.ExcludesExpression("Not Found on Accelerato", "Should not try to remap on Traffic Server") tr.Processes.Default.Streams.All += Testers.ExcludesExpression("CN=foo.com", "Should not TLS terminate on Traffic Server") tr.Processes.Default.Streams.All += Testers.ContainsExpression("HTTP/1.1 200 OK", "Should get a successful response") tr.Processes.Default.Streams.All += Testers.ContainsExpression("ok foo", "Body is expected") tr2 = Test.AddTestRun("Forward-test") tr2.Processes.Default.Command = "curl -v --http1.1 -H 'host:bar.com' --resolve 'bar.com:{0}:127.0.0.1' -k https://bar.com:{0}".format(ts.Variables.ssl_port) tr2.ReturnCode = 0 tr2.StillRunningAfter = server_bar tr2.StillRunningAfter = ts tr2.Processes.Default.Streams.All += Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded") tr2.Processes.Default.Streams.All += Testers.ExcludesExpression("Not Found on Accelerato", "Should not try to remap on Traffic Server") tr2.Processes.Default.Streams.All += Testers.ContainsExpression("CN=foo.com", "Should TLS terminate on Traffic Server") tr2.Processes.Default.Streams.All += Testers.ContainsExpression("HTTP/1.1 200 OK", "Should get a successful response") tr2.Processes.Default.Streams.All += Testers.ContainsExpression("ok bar", "Body is expected") tr3 = Test.AddTestRun("no-sni-forward-test") tr3.Processes.Default.Command = "curl --http1.1 -v -k -H 'host:random.com' https://127.0.0.1:{0}".format(ts.Variables.ssl_port) tr3.ReturnCode = 0 tr3.StillRunningAfter = server_random tr3.StillRunningAfter = ts tr3.Processes.Default.Streams.All += Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded") tr3.Processes.Default.Streams.All += Testers.ExcludesExpression("Not Found on Accelerato", "Should not try to remap on Traffic Server") tr3.Processes.Default.Streams.All += Testers.ContainsExpression("CN=foo.com", "Should TLS terminate on Traffic Server") tr3.Processes.Default.Streams.All += Testers.ContainsExpression("HTTP/1.1 200 OK", "Should get a successful response") tr3.Processes.Default.Streams.All += Testers.ContainsExpression("ok random", "Body is expected")
true
true
f72d1174e70c56ea9c0c9a435927929db9497bbd
1,820
py
Python
resources/WPy32/python-3.10.2/Lib/distutils/tests/test_bdist.py
eladkarako/yt-dlp_kit
6365651111ef4d2f94335cf38bf4d9b0136d42d2
[ "Unlicense" ]
1
2022-03-26T15:43:50.000Z
2022-03-26T15:43:50.000Z
resources/WPy32/python-3.10.2/Lib/distutils/tests/test_bdist.py
eladkarako/yt-dlp_kit
6365651111ef4d2f94335cf38bf4d9b0136d42d2
[ "Unlicense" ]
null
null
null
resources/WPy32/python-3.10.2/Lib/distutils/tests/test_bdist.py
eladkarako/yt-dlp_kit
6365651111ef4d2f94335cf38bf4d9b0136d42d2
[ "Unlicense" ]
1
2022-03-28T19:28:45.000Z
2022-03-28T19:28:45.000Z
"""Tests for distutils.command.bdist.""" import os import unittest from test.support import run_unittest import warnings with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) from distutils.command.bdist import bdist from distutils.tests import support class BuildTestCase(support.TempdirManager, unittest.TestCase): def test_formats(self): # let's create a command and make sure # we can set the format dist = self.create_dist()[1] cmd = bdist(dist) cmd.formats = ['msi'] cmd.ensure_finalized() self.assertEqual(cmd.formats, ['msi']) # what formats does bdist offer? formats = ['bztar', 'gztar', 'msi', 'rpm', 'tar', 'xztar', 'zip', 'ztar'] found = sorted(cmd.format_command) self.assertEqual(found, formats) def test_skip_build(self): # bug #10946: bdist --skip-build should trickle down to subcommands dist = self.create_dist()[1] cmd = bdist(dist) cmd.skip_build = 1 cmd.ensure_finalized() dist.command_obj['bdist'] = cmd names = ['bdist_dumb'] # bdist_rpm does not support --skip-build if os.name == 'nt': names.append('bdist_msi') for name in names: subcmd = cmd.get_finalized_command(name) if getattr(subcmd, '_unsupported', False): # command is not supported on this build continue self.assertTrue(subcmd.skip_build, '%s should take --skip-build from bdist' % name) def test_suite(): return unittest.makeSuite(BuildTestCase) if __name__ == '__main__': run_unittest(test_suite())
31.929825
77
0.591209
import os import unittest from test.support import run_unittest import warnings with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) from distutils.command.bdist import bdist from distutils.tests import support class BuildTestCase(support.TempdirManager, unittest.TestCase): def test_formats(self): # we can set the format dist = self.create_dist()[1] cmd = bdist(dist) cmd.formats = ['msi'] cmd.ensure_finalized() self.assertEqual(cmd.formats, ['msi']) # what formats does bdist offer? formats = ['bztar', 'gztar', 'msi', 'rpm', 'tar', 'xztar', 'zip', 'ztar'] found = sorted(cmd.format_command) self.assertEqual(found, formats) def test_skip_build(self): # bug #10946: bdist --skip-build should trickle down to subcommands dist = self.create_dist()[1] cmd = bdist(dist) cmd.skip_build = 1 cmd.ensure_finalized() dist.command_obj['bdist'] = cmd names = ['bdist_dumb'] # bdist_rpm does not support --skip-build if os.name == 'nt': names.append('bdist_msi') for name in names: subcmd = cmd.get_finalized_command(name) if getattr(subcmd, '_unsupported', False): # command is not supported on this build continue self.assertTrue(subcmd.skip_build, '%s should take --skip-build from bdist' % name) def test_suite(): return unittest.makeSuite(BuildTestCase) if __name__ == '__main__': run_unittest(test_suite())
true
true
f72d1185c8f7b68defcc43981f991746536dc0b5
484
py
Python
speedysvc/toolkit/py_ini/write/conv_to_str.py
mcyph/shmrpc
4e0e972657f677a845eb6e7acbf788535c07117a
[ "Unlicense", "MIT" ]
4
2020-02-11T04:20:57.000Z
2021-06-20T10:03:52.000Z
speedysvc/toolkit/py_ini/write/conv_to_str.py
mcyph/shmrpc
4e0e972657f677a845eb6e7acbf788535c07117a
[ "Unlicense", "MIT" ]
1
2020-09-16T23:18:30.000Z
2020-09-21T10:07:22.000Z
speedysvc/toolkit/py_ini/write/conv_to_str.py
mcyph/shmrpc
4e0e972657f677a845eb6e7acbf788535c07117a
[ "Unlicense", "MIT" ]
null
null
null
def conv_to_str(o): if isinstance(o, str): # Remove initial "u" chars before strings # if no Unicode in them if possible try: o = str(o) except: o = str(o) elif isinstance(o, (list, tuple)): is_tuple = isinstance(o, tuple) o = [conv_to_str(i) for i in o] if is_tuple: o = tuple(o) elif isinstance(o, dict): for k in o: o[k] = conv_to_str(o[k]) return o
23.047619
49
0.5
def conv_to_str(o): if isinstance(o, str): try: o = str(o) except: o = str(o) elif isinstance(o, (list, tuple)): is_tuple = isinstance(o, tuple) o = [conv_to_str(i) for i in o] if is_tuple: o = tuple(o) elif isinstance(o, dict): for k in o: o[k] = conv_to_str(o[k]) return o
true
true
f72d11981b4d9f232355f2e60ad86e0a43b91b4f
11,383
py
Python
tests/v16/test_enums.py
Jonas628/discovere_ocpp
6456e72a9d6725634725756e67fcfd5be007de79
[ "MIT" ]
null
null
null
tests/v16/test_enums.py
Jonas628/discovere_ocpp
6456e72a9d6725634725756e67fcfd5be007de79
[ "MIT" ]
null
null
null
tests/v16/test_enums.py
Jonas628/discovere_ocpp
6456e72a9d6725634725756e67fcfd5be007de79
[ "MIT" ]
null
null
null
# flake8: noqa from ocpp_d.v16.enums import * def test_authorization_status(): assert AuthorizationStatus.accepted == "Accepted" assert AuthorizationStatus.blocked == "Blocked" assert AuthorizationStatus.expired == "Expired" assert AuthorizationStatus.invalid == "Invalid" assert AuthorizationStatus.concurrent_tx == "ConcurrentTx" def test_availability_status(): assert AvailabilityStatus.accepted == "Accepted" assert AvailabilityStatus.rejected == "Rejected" assert AvailabilityStatus.scheduled == "Scheduled" def test_availability_type(): assert AvailabilityType.inoperative == "Inoperative" assert AvailabilityType.operative == "Operative" def test_cancel_reservation_status(): assert CancelReservationStatus.accepted == "Accepted" assert CancelReservationStatus.rejected == "Rejected" def test_charge_point_error_code(): assert (ChargePointErrorCode.connector_lock_failure == "ConnectorLockFailure") assert (ChargePointErrorCode.ev_communication_error == "EVCommunicationError") assert ChargePointErrorCode.ground_failure == "GroundFailure" assert (ChargePointErrorCode.high_temperature == "HighTemperature") assert ChargePointErrorCode.internal_error == "InternalError" assert (ChargePointErrorCode.local_list_conflict == "LocalListConflict") assert ChargePointErrorCode.no_error == "NoError" assert ChargePointErrorCode.other_error == "OtherError" assert (ChargePointErrorCode.over_current_failure == "OverCurrentFailure") assert ChargePointErrorCode.over_voltage == "OverVoltage" assert (ChargePointErrorCode.power_meter_failure == "PowerMeterFailure") assert (ChargePointErrorCode.power_switch_failure == "PowerSwitchFailure") assert ChargePointErrorCode.reader_failure == "ReaderFailure" assert ChargePointErrorCode.reset_failure == "ResetFailure" assert ChargePointErrorCode.under_voltage == "UnderVoltage" assert ChargePointErrorCode.weak_signal == "WeakSignal" def test_charge_point_status(): assert ChargePointStatus.available == 'Available' assert ChargePointStatus.preparing == 'Preparing' assert ChargePointStatus.charging == 'Charging' assert ChargePointStatus.suspended_evse == 'SuspendedEVSE' assert ChargePointStatus.suspended_ev == 'SuspendedEV' assert ChargePointStatus.finishing == 'Finishing' assert ChargePointStatus.reserved == 'Reserved' assert ChargePointStatus.unavailable == 'Unavailable' assert ChargePointStatus.faulted == 'Faulted' def test_charging_profile_kind_type(): assert ChargingProfileKindType.absolute == 'Absolute' assert ChargingProfileKindType.recurring == 'Recurring' assert ChargingProfileKindType.relative == 'Relative' def test_charging_profile_purpose_type(): assert (ChargingProfilePurposeType.charge_point_max_profile == 'ChargePointMaxProfile') assert (ChargingProfilePurposeType.tx_default_profile == 'TxDefaultProfile') assert ChargingProfilePurposeType.tx_profile == 'TxProfile' def test_charging_profile_status(): assert ChargingProfileStatus.accepted == "Accepted" assert ChargingProfileStatus.rejected == "Rejected" assert ChargingProfileStatus.not_supported == "NotSupported" def test_charging_rate_unit(): assert ChargingRateUnitType.watts == "W" assert ChargingRateUnitType.amps == "A" def test_clear_cache_status(): assert ClearCacheStatus.accepted == "Accepted" assert ClearCacheStatus.rejected == "Rejected" def test_clear_charging_profile_status(): assert ClearChargingProfileStatus.accepted == "Accepted" assert ClearChargingProfileStatus.unknown == "Unknown" def test_configuration_status(): assert ConfigurationStatus.accepted == "Accepted" assert ConfigurationStatus.rejected == "Rejected" assert ConfigurationStatus.reboot_required == "RebootRequired" assert ConfigurationStatus.not_supported == "NotSupported" def test_data_transfer_status(): assert DataTransferStatus.accepted == "Accepted" assert DataTransferStatus.rejected == "Rejected" assert (DataTransferStatus.unknown_message_id == "UnknownMessageId") assert DataTransferStatus.unknown_vendor_id == "UnknownVendorId" def test_diagnostics_status(): assert DiagnosticsStatus.idle == "Idle" assert DiagnosticsStatus.uploaded == "Uploaded" assert DiagnosticsStatus.upload_failed == "UploadFailed" assert DiagnosticsStatus.uploading == "Uploading" def test_firmware_status(): assert FirmwareStatus.downloaded == "Downloaded" assert FirmwareStatus.download_failed == "DownloadFailed" assert FirmwareStatus.downloading == "Downloading" assert FirmwareStatus.idle == "Idle" assert (FirmwareStatus.installation_failed == "InstallationFailed") assert FirmwareStatus.installing == "Installing" assert FirmwareStatus.installed == "Installed" def test_get_composite_schedule_status(): assert GetCompositeScheduleStatus.accepted == "Accepted" assert GetCompositeScheduleStatus.rejected == "Rejected" def test_location(): assert Location.inlet == "Inlet" assert Location.outlet == "Outlet" assert Location.body == "Body" assert Location.cable == "Cable" assert Location.ev == "EV" def test_measurand(): assert (Measurand.energy_active_export_register == "Energy.Active.Export.Register") assert (Measurand.energy_active_import_register == "Energy.Active.Import.Register") assert (Measurand.energy_reactive_export_register == "Energy.Reactive.Export.Register") assert (Measurand.energy_reactive_import_register == "Energy.Reactive.Import.Register") assert (Measurand.energy_active_export_interval == "Energy.Active.Export.Interval") assert (Measurand.energy_active_import_interval == "Energy.Active.Import.Interval") assert (Measurand.energy_reactive_export_interval == "Energy.Reactive.Export.Interval") assert (Measurand.energy_reactive_import_interval == "Energy.Reactive.Import.Interval") assert Measurand.frequency == "Frequency" assert Measurand.power_active_export == "Power.Active.Export" assert Measurand.power_active_import == "Power.Active.Import" assert Measurand.power_factor == "Power.Factor" assert Measurand.power_offered == "Power.Offered" assert (Measurand.power_reactive_export == "Power.Reactive.Export") assert (Measurand.power_reactive_import == "Power.Reactive.Import") assert Measurand.current_export == "Current.Export" assert Measurand.current_import == "Current.Import" assert Measurand.current_offered == "Current.Offered" assert Measurand.rpm == "RPM" assert Measurand.soc == "SoC" assert Measurand.voltage == "Voltage" assert Measurand.temperature == "Temperature" def test_message_trigger(): assert MessageTrigger.boot_notification == "BootNotification" assert (MessageTrigger.diagnostics_status_notification == "DiagnosticsStatusNotification") assert (MessageTrigger.firmware_status_notification == "FirmwareStatusNotification") assert MessageTrigger.heartbeat == "Heartbeat" assert MessageTrigger.meter_values == "MeterValues" assert (MessageTrigger.status_notification == "StatusNotification") def test_phase(): assert Phase.l1 == "L1" assert Phase.l2 == "L2" assert Phase.l3 == "L3" assert Phase.n == "N" assert Phase.l1_n == "L1-N" assert Phase.l2_n == "L2-N" assert Phase.l3_n == "L3-N" assert Phase.l1_l2 == "L1-L2" assert Phase.l2_l3 == "L2-L3" assert Phase.l3_l1 == "L3-L1" def test_reading_context(): assert (ReadingContext.interruption_begin == "Interruption.Begin") assert ReadingContext.interruption_end == "Interruption.End" assert ReadingContext.other == "Other" assert ReadingContext.sample_clock == "Sample.Clock" assert ReadingContext.sample_periodic == "Sample.Periodic" assert ReadingContext.transaction_begin == "Transaction.Begin" assert ReadingContext.transaction_end == "Transaction.End" assert ReadingContext.trigger == "Trigger" def test_reason(): assert Reason.emergency_stop == "EmergencyStop" assert Reason.ev_disconnected == "EVDisconnected" assert Reason.hard_reset == "HardReset" assert Reason.local == "Local" assert Reason.other == "Other" assert Reason.power_loss == "PowerLoss" assert Reason.reboot == "Reboot" assert Reason.remote == "Remote" assert Reason.soft_reset == "SoftReset" assert Reason.unlock_command == "UnlockCommand" assert Reason.de_authorized == "DeAuthorized" def test_recurrency_kind(): assert RecurrencyKind.daily == 'Daily' assert RecurrencyKind.weekly == 'Weekly' def test_registration_status(): assert RegistrationStatus.accepted == "Accepted" assert RegistrationStatus.pending == "Pending" assert RegistrationStatus.rejected == "Rejected" def test_remote_start_stop_status(): assert RemoteStartStopStatus.accepted == "Accepted" assert RemoteStartStopStatus.rejected == "Rejected" def test_reservation_status(): assert ReservationStatus.accepted == "Accepted" assert ReservationStatus.faulted == "Faulted" assert ReservationStatus.occupied == "Occupied" assert ReservationStatus.rejected == "Rejected" assert ReservationStatus.unavailable == "Unavailable" def test_reset_status(): assert ResetStatus.accepted == "Accepted" assert ResetStatus.rejected == "Rejected" def test_reset_type(): assert ResetType.hard == "Hard" assert ResetType.soft == "Soft" def test_trigger_message_status(): assert TriggerMessageStatus.accepted == "Accepted" assert TriggerMessageStatus.rejected == "Rejected" assert TriggerMessageStatus.not_implemented == "NotImplemented" def test_unit_of_measure(): assert UnitOfMeasure.wh == "Wh" assert UnitOfMeasure.kwh == "kWh" assert UnitOfMeasure.varh == "varh" assert UnitOfMeasure.kvarh == "kvarh" assert UnitOfMeasure.w == "W" assert UnitOfMeasure.kw == "kW" assert UnitOfMeasure.va == "VA" assert UnitOfMeasure.kva == "kVA" assert UnitOfMeasure.var == "var" assert UnitOfMeasure.kvar == "kvar" assert UnitOfMeasure.a == "A" assert UnitOfMeasure.v == "V" assert UnitOfMeasure.celsius == "Celsius" assert UnitOfMeasure.fahrenheit == "Fahrenheit" assert UnitOfMeasure.k == "K" assert UnitOfMeasure.percent == "Percent" assert UnitOfMeasure.hertz == "Hertz" def test_unlock_status(): assert UnlockStatus.unlocked == "Unlocked" assert UnlockStatus.unlock_failed == "UnlockFailed" assert UnlockStatus.not_supported == "NotSupported" def test_update_status(): assert UpdateStatus.accepted == "Accepted" assert UpdateStatus.failed == "Failed" assert UpdateStatus.not_supported == "NotSupported" assert UpdateStatus.version_mismatch == "VersionMismatch" def test_update_type(): assert UpdateType.differential == "Differential" assert UpdateType.full == "Full" def test_value_format(): assert ValueFormat.raw == "Raw" assert ValueFormat.signed_data == "SignedData"
36.136508
68
0.734516
from ocpp_d.v16.enums import * def test_authorization_status(): assert AuthorizationStatus.accepted == "Accepted" assert AuthorizationStatus.blocked == "Blocked" assert AuthorizationStatus.expired == "Expired" assert AuthorizationStatus.invalid == "Invalid" assert AuthorizationStatus.concurrent_tx == "ConcurrentTx" def test_availability_status(): assert AvailabilityStatus.accepted == "Accepted" assert AvailabilityStatus.rejected == "Rejected" assert AvailabilityStatus.scheduled == "Scheduled" def test_availability_type(): assert AvailabilityType.inoperative == "Inoperative" assert AvailabilityType.operative == "Operative" def test_cancel_reservation_status(): assert CancelReservationStatus.accepted == "Accepted" assert CancelReservationStatus.rejected == "Rejected" def test_charge_point_error_code(): assert (ChargePointErrorCode.connector_lock_failure == "ConnectorLockFailure") assert (ChargePointErrorCode.ev_communication_error == "EVCommunicationError") assert ChargePointErrorCode.ground_failure == "GroundFailure" assert (ChargePointErrorCode.high_temperature == "HighTemperature") assert ChargePointErrorCode.internal_error == "InternalError" assert (ChargePointErrorCode.local_list_conflict == "LocalListConflict") assert ChargePointErrorCode.no_error == "NoError" assert ChargePointErrorCode.other_error == "OtherError" assert (ChargePointErrorCode.over_current_failure == "OverCurrentFailure") assert ChargePointErrorCode.over_voltage == "OverVoltage" assert (ChargePointErrorCode.power_meter_failure == "PowerMeterFailure") assert (ChargePointErrorCode.power_switch_failure == "PowerSwitchFailure") assert ChargePointErrorCode.reader_failure == "ReaderFailure" assert ChargePointErrorCode.reset_failure == "ResetFailure" assert ChargePointErrorCode.under_voltage == "UnderVoltage" assert ChargePointErrorCode.weak_signal == "WeakSignal" def test_charge_point_status(): assert ChargePointStatus.available == 'Available' assert ChargePointStatus.preparing == 'Preparing' assert ChargePointStatus.charging == 'Charging' assert ChargePointStatus.suspended_evse == 'SuspendedEVSE' assert ChargePointStatus.suspended_ev == 'SuspendedEV' assert ChargePointStatus.finishing == 'Finishing' assert ChargePointStatus.reserved == 'Reserved' assert ChargePointStatus.unavailable == 'Unavailable' assert ChargePointStatus.faulted == 'Faulted' def test_charging_profile_kind_type(): assert ChargingProfileKindType.absolute == 'Absolute' assert ChargingProfileKindType.recurring == 'Recurring' assert ChargingProfileKindType.relative == 'Relative' def test_charging_profile_purpose_type(): assert (ChargingProfilePurposeType.charge_point_max_profile == 'ChargePointMaxProfile') assert (ChargingProfilePurposeType.tx_default_profile == 'TxDefaultProfile') assert ChargingProfilePurposeType.tx_profile == 'TxProfile' def test_charging_profile_status(): assert ChargingProfileStatus.accepted == "Accepted" assert ChargingProfileStatus.rejected == "Rejected" assert ChargingProfileStatus.not_supported == "NotSupported" def test_charging_rate_unit(): assert ChargingRateUnitType.watts == "W" assert ChargingRateUnitType.amps == "A" def test_clear_cache_status(): assert ClearCacheStatus.accepted == "Accepted" assert ClearCacheStatus.rejected == "Rejected" def test_clear_charging_profile_status(): assert ClearChargingProfileStatus.accepted == "Accepted" assert ClearChargingProfileStatus.unknown == "Unknown" def test_configuration_status(): assert ConfigurationStatus.accepted == "Accepted" assert ConfigurationStatus.rejected == "Rejected" assert ConfigurationStatus.reboot_required == "RebootRequired" assert ConfigurationStatus.not_supported == "NotSupported" def test_data_transfer_status(): assert DataTransferStatus.accepted == "Accepted" assert DataTransferStatus.rejected == "Rejected" assert (DataTransferStatus.unknown_message_id == "UnknownMessageId") assert DataTransferStatus.unknown_vendor_id == "UnknownVendorId" def test_diagnostics_status(): assert DiagnosticsStatus.idle == "Idle" assert DiagnosticsStatus.uploaded == "Uploaded" assert DiagnosticsStatus.upload_failed == "UploadFailed" assert DiagnosticsStatus.uploading == "Uploading" def test_firmware_status(): assert FirmwareStatus.downloaded == "Downloaded" assert FirmwareStatus.download_failed == "DownloadFailed" assert FirmwareStatus.downloading == "Downloading" assert FirmwareStatus.idle == "Idle" assert (FirmwareStatus.installation_failed == "InstallationFailed") assert FirmwareStatus.installing == "Installing" assert FirmwareStatus.installed == "Installed" def test_get_composite_schedule_status(): assert GetCompositeScheduleStatus.accepted == "Accepted" assert GetCompositeScheduleStatus.rejected == "Rejected" def test_location(): assert Location.inlet == "Inlet" assert Location.outlet == "Outlet" assert Location.body == "Body" assert Location.cable == "Cable" assert Location.ev == "EV" def test_measurand(): assert (Measurand.energy_active_export_register == "Energy.Active.Export.Register") assert (Measurand.energy_active_import_register == "Energy.Active.Import.Register") assert (Measurand.energy_reactive_export_register == "Energy.Reactive.Export.Register") assert (Measurand.energy_reactive_import_register == "Energy.Reactive.Import.Register") assert (Measurand.energy_active_export_interval == "Energy.Active.Export.Interval") assert (Measurand.energy_active_import_interval == "Energy.Active.Import.Interval") assert (Measurand.energy_reactive_export_interval == "Energy.Reactive.Export.Interval") assert (Measurand.energy_reactive_import_interval == "Energy.Reactive.Import.Interval") assert Measurand.frequency == "Frequency" assert Measurand.power_active_export == "Power.Active.Export" assert Measurand.power_active_import == "Power.Active.Import" assert Measurand.power_factor == "Power.Factor" assert Measurand.power_offered == "Power.Offered" assert (Measurand.power_reactive_export == "Power.Reactive.Export") assert (Measurand.power_reactive_import == "Power.Reactive.Import") assert Measurand.current_export == "Current.Export" assert Measurand.current_import == "Current.Import" assert Measurand.current_offered == "Current.Offered" assert Measurand.rpm == "RPM" assert Measurand.soc == "SoC" assert Measurand.voltage == "Voltage" assert Measurand.temperature == "Temperature" def test_message_trigger(): assert MessageTrigger.boot_notification == "BootNotification" assert (MessageTrigger.diagnostics_status_notification == "DiagnosticsStatusNotification") assert (MessageTrigger.firmware_status_notification == "FirmwareStatusNotification") assert MessageTrigger.heartbeat == "Heartbeat" assert MessageTrigger.meter_values == "MeterValues" assert (MessageTrigger.status_notification == "StatusNotification") def test_phase(): assert Phase.l1 == "L1" assert Phase.l2 == "L2" assert Phase.l3 == "L3" assert Phase.n == "N" assert Phase.l1_n == "L1-N" assert Phase.l2_n == "L2-N" assert Phase.l3_n == "L3-N" assert Phase.l1_l2 == "L1-L2" assert Phase.l2_l3 == "L2-L3" assert Phase.l3_l1 == "L3-L1" def test_reading_context(): assert (ReadingContext.interruption_begin == "Interruption.Begin") assert ReadingContext.interruption_end == "Interruption.End" assert ReadingContext.other == "Other" assert ReadingContext.sample_clock == "Sample.Clock" assert ReadingContext.sample_periodic == "Sample.Periodic" assert ReadingContext.transaction_begin == "Transaction.Begin" assert ReadingContext.transaction_end == "Transaction.End" assert ReadingContext.trigger == "Trigger" def test_reason(): assert Reason.emergency_stop == "EmergencyStop" assert Reason.ev_disconnected == "EVDisconnected" assert Reason.hard_reset == "HardReset" assert Reason.local == "Local" assert Reason.other == "Other" assert Reason.power_loss == "PowerLoss" assert Reason.reboot == "Reboot" assert Reason.remote == "Remote" assert Reason.soft_reset == "SoftReset" assert Reason.unlock_command == "UnlockCommand" assert Reason.de_authorized == "DeAuthorized" def test_recurrency_kind(): assert RecurrencyKind.daily == 'Daily' assert RecurrencyKind.weekly == 'Weekly' def test_registration_status(): assert RegistrationStatus.accepted == "Accepted" assert RegistrationStatus.pending == "Pending" assert RegistrationStatus.rejected == "Rejected" def test_remote_start_stop_status(): assert RemoteStartStopStatus.accepted == "Accepted" assert RemoteStartStopStatus.rejected == "Rejected" def test_reservation_status(): assert ReservationStatus.accepted == "Accepted" assert ReservationStatus.faulted == "Faulted" assert ReservationStatus.occupied == "Occupied" assert ReservationStatus.rejected == "Rejected" assert ReservationStatus.unavailable == "Unavailable" def test_reset_status(): assert ResetStatus.accepted == "Accepted" assert ResetStatus.rejected == "Rejected" def test_reset_type(): assert ResetType.hard == "Hard" assert ResetType.soft == "Soft" def test_trigger_message_status(): assert TriggerMessageStatus.accepted == "Accepted" assert TriggerMessageStatus.rejected == "Rejected" assert TriggerMessageStatus.not_implemented == "NotImplemented" def test_unit_of_measure(): assert UnitOfMeasure.wh == "Wh" assert UnitOfMeasure.kwh == "kWh" assert UnitOfMeasure.varh == "varh" assert UnitOfMeasure.kvarh == "kvarh" assert UnitOfMeasure.w == "W" assert UnitOfMeasure.kw == "kW" assert UnitOfMeasure.va == "VA" assert UnitOfMeasure.kva == "kVA" assert UnitOfMeasure.var == "var" assert UnitOfMeasure.kvar == "kvar" assert UnitOfMeasure.a == "A" assert UnitOfMeasure.v == "V" assert UnitOfMeasure.celsius == "Celsius" assert UnitOfMeasure.fahrenheit == "Fahrenheit" assert UnitOfMeasure.k == "K" assert UnitOfMeasure.percent == "Percent" assert UnitOfMeasure.hertz == "Hertz" def test_unlock_status(): assert UnlockStatus.unlocked == "Unlocked" assert UnlockStatus.unlock_failed == "UnlockFailed" assert UnlockStatus.not_supported == "NotSupported" def test_update_status(): assert UpdateStatus.accepted == "Accepted" assert UpdateStatus.failed == "Failed" assert UpdateStatus.not_supported == "NotSupported" assert UpdateStatus.version_mismatch == "VersionMismatch" def test_update_type(): assert UpdateType.differential == "Differential" assert UpdateType.full == "Full" def test_value_format(): assert ValueFormat.raw == "Raw" assert ValueFormat.signed_data == "SignedData"
true
true
f72d122ad8ca0a487720f9630a8a2086444e3a23
384
py
Python
1stRound/Easy/819 Most Common Word/RegexCounter1.py
ericchen12377/Leetcode-Algorithm-Python
eb58cd4f01d9b8006b7d1a725fc48910aad7f192
[ "MIT" ]
2
2020-04-24T18:36:52.000Z
2020-04-25T00:15:57.000Z
1stRound/Easy/819 Most Common Word/RegexCounter1.py
ericchen12377/Leetcode-Algorithm-Python
eb58cd4f01d9b8006b7d1a725fc48910aad7f192
[ "MIT" ]
null
null
null
1stRound/Easy/819 Most Common Word/RegexCounter1.py
ericchen12377/Leetcode-Algorithm-Python
eb58cd4f01d9b8006b7d1a725fc48910aad7f192
[ "MIT" ]
null
null
null
import collections import re class Solution(object): def mostCommonWord(self, paragraph, banned): """ :type paragraph: str :type banned: List[str] :rtype: str """ paragraph = re.findall(r"\w+", paragraph.lower()) count = collections.Counter(x for x in paragraph if x not in banned) return count.most_common(1)[0][0]
29.538462
76
0.606771
import collections import re class Solution(object): def mostCommonWord(self, paragraph, banned): paragraph = re.findall(r"\w+", paragraph.lower()) count = collections.Counter(x for x in paragraph if x not in banned) return count.most_common(1)[0][0]
true
true
f72d12744056fae45f212a2dfb4d1368b26b9baf
15,546
py
Python
test/tools.py
jni/asv
f1ec1c157d52c77a799853062dac3468fab3e2ab
[ "BSD-3-Clause" ]
null
null
null
test/tools.py
jni/asv
f1ec1c157d52c77a799853062dac3468fab3e2ab
[ "BSD-3-Clause" ]
3
2018-07-26T17:56:30.000Z
2018-07-27T20:23:27.000Z
test/tools.py
jni/asv
f1ec1c157d52c77a799853062dac3468fab3e2ab
[ "BSD-3-Clause" ]
3
2018-07-25T22:53:31.000Z
2018-09-16T06:14:43.000Z
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals, print_function """ This file contains utilities to generate test repositories. """ import datetime import io import os import threading import time import six import tempfile import textwrap import sys from os.path import abspath, join, dirname, relpath, isdir from contextlib import contextmanager from hashlib import sha256 from six.moves import SimpleHTTPServer import pytest try: import hglib except ImportError as exc: hglib = None from asv import util from asv import commands from asv import config from asv.commands.preview import create_httpd from asv.repo import get_repo from asv.results import Results # Two Python versions for testing PYTHON_VER1 = "{0[0]}.{0[1]}".format(sys.version_info) if sys.version_info < (3,): PYTHON_VER2 = "3.6" else: PYTHON_VER2 = "2.7" # Installable library versions to use in tests SIX_VERSION = "1.10" COLORAMA_VERSIONS = ["0.3.7", "0.3.9"] try: import selenium from selenium.common.exceptions import TimeoutException HAVE_WEBDRIVER = True except ImportError: HAVE_WEBDRIVER = False WAIT_TIME = 20.0 def run_asv(*argv): parser, subparsers = commands.make_argparser() args = parser.parse_args(argv) return args.func(args) def run_asv_with_conf(conf, *argv, **kwargs): assert isinstance(conf, config.Config) parser, subparsers = commands.make_argparser() args = parser.parse_args(argv) if sys.version_info[0] >= 3: cls = args.func.__self__ else: cls = args.func.im_self return cls.run_from_conf_args(conf, args, **kwargs) # These classes are defined here, rather than using asv/plugins/git.py # and asv/plugins/mercurial.py since here we need to perform write # operations to the repository, and the others should be read-only for # safety. class Git(object): def __init__(self, path): self.path = abspath(path) self._git = util.which('git') self._fake_date = datetime.datetime.now() def run_git(self, args, chdir=True, **kwargs): if chdir: cwd = self.path else: cwd = None kwargs['cwd'] = cwd return util.check_output( [self._git] + args, **kwargs) def init(self): self.run_git(['init']) self.run_git(['config', 'user.email', 'robot@asv']) self.run_git(['config', 'user.name', 'Robotic Swallow']) def commit(self, message, date=None): if date is None: self._fake_date += datetime.timedelta(seconds=1) date = self._fake_date self.run_git(['commit', '--date', date.isoformat(), '-m', message]) def tag(self, number): self.run_git(['tag', '-a', '-m', 'Tag {0}'.format(number), 'tag{0}'.format(number)]) def add(self, filename): self.run_git(['add', relpath(filename, self.path)]) def checkout(self, branch_name, start_commit=None): args = ["checkout"] if start_commit is not None: args.extend(["-b", branch_name, start_commit]) else: args.append(branch_name) self.run_git(args) def merge(self, branch_name, commit_message=None): self.run_git(["merge", "--no-ff", "--no-commit", "-X", "theirs", branch_name]) if commit_message is None: commit_message = "Merge {0}".format(branch_name) self.commit(commit_message) def get_hash(self, name): return self.run_git(['rev-parse', name]).strip() def get_branch_hashes(self, branch=None): if branch is None: branch = "master" return [x.strip() for x in self.run_git(['rev-list', branch]).splitlines() if x.strip()] def get_commit_message(self, commit_hash): return self.run_git(["log", "-n", "1", "--format=%s", commit_hash]).strip() _hg_config = """ [ui] username = Robotic Swallow <robot@asv> """ class Hg(object): encoding = 'utf-8' def __init__(self, path): self._fake_date = datetime.datetime.now() self.path = abspath(path) def init(self): hglib.init(self.path) with io.open(join(self.path, '.hg', 'hgrc'), 'w', encoding="utf-8") as fd: fd.write(_hg_config) self._repo = hglib.open(self.path.encode(sys.getfilesystemencoding()), encoding=self.encoding) def commit(self, message, date=None): if date is None: self._fake_date += datetime.timedelta(seconds=1) date = self._fake_date date = "{0} 0".format(util.datetime_to_timestamp(date)) self._repo.commit(message.encode(self.encoding), date=date.encode(self.encoding)) def tag(self, number): self._fake_date += datetime.timedelta(seconds=1) date = "{0} 0".format(util.datetime_to_timestamp(self._fake_date)) self._repo.tag( ['tag{0}'.format(number).encode(self.encoding)], message="Tag {0}".format(number).encode(self.encoding), date=date.encode(self.encoding)) def add(self, filename): self._repo.add([filename.encode(sys.getfilesystemencoding())]) def checkout(self, branch_name, start_commit=None): if start_commit is not None: self._repo.update(start_commit.encode(self.encoding)) self._repo.branch(branch_name.encode(self.encoding)) else: self._repo.update(branch_name.encode(self.encoding)) def merge(self, branch_name, commit_message=None): self._repo.merge(branch_name.encode(self.encoding), tool=b"internal:other") if commit_message is None: commit_message = "Merge {0}".format(branch_name) self.commit(commit_message) def get_hash(self, name): log = self._repo.log(name.encode(self.encoding), limit=1) if log: return log[0][1].decode(self.encoding) return None def get_branch_hashes(self, branch=None): if branch is None: branch = "default" log = self._repo.log('sort(ancestors({0}), -rev)'.format(branch).encode(self.encoding)) return [entry[1].decode(self.encoding) for entry in log] def get_commit_message(self, commit_hash): return self._repo.log(commit_hash.encode(self.encoding))[0].desc.decode(self.encoding) def copy_template(src, dst, dvcs, values): for root, dirs, files in os.walk(src): for dir in dirs: src_path = join(root, dir) dst_path = join(dst, relpath(src_path, src)) if not isdir(dst_path): os.makedirs(dst_path) for file in files: src_path = join(root, file) dst_path = join(dst, relpath(src_path, src)) try: with io.open(src_path, 'r', encoding='utf-8') as fd: content = fd.read() except UnicodeDecodeError: # File is some sort of binary file... just copy it # directly with no template substitution with io.open(src_path, 'rb') as fd: content = fd.read() with io.open(dst_path, 'wb') as fd: fd.write(content) else: content = content.format(**values) with io.open(dst_path, 'w', encoding='utf-8') as fd: fd.write(content) dvcs.add(dst_path) def generate_test_repo(tmpdir, values=[0], dvcs_type='git', extra_branches=(), subdir=''): """ Generate a test repository Parameters ---------- tmpdir Repository directory values : list List of values to substitute in the template dvcs_type : {'git', 'hg'} What dvcs to use extra_branches : list of (start_commit, branch_name, values) Additional branches to generate in the repository. For branch start commits, use relative references, e.g., the format 'master~10' or 'default~10' works both for Hg and Git. subdir A relative subdirectory inside the repository to copy the test project into. Returns ------- dvcs : Git or Hg """ if dvcs_type == 'git': dvcs_cls = Git elif dvcs_type == 'hg': dvcs_cls = Hg else: raise ValueError("Unknown dvcs type {0}".format(dvcs_type)) template_path = join(dirname(__file__), 'test_repo_template') if not os.path.isdir(tmpdir): os.makedirs(tmpdir) dvcs_path = tempfile.mkdtemp(prefix='test_repo', dir=tmpdir) dvcs = dvcs_cls(dvcs_path) dvcs.init() project_path = os.path.join(dvcs_path, subdir) if not os.path.exists(project_path): os.makedirs(project_path) for i, value in enumerate(values): mapping = { 'version': i, 'dummy_value': value } copy_template(template_path, project_path, dvcs, mapping) dvcs.commit("Revision {0}".format(i)) dvcs.tag(i) if extra_branches: for start_commit, branch_name, values in extra_branches: dvcs.checkout(branch_name, start_commit) for i, value in enumerate(values): mapping = { 'version': "{0}".format(i), 'dummy_value': value } copy_template(template_path, project_path, dvcs, mapping) dvcs.commit("Revision {0}.{1}".format(branch_name, i)) return dvcs def generate_repo_from_ops(tmpdir, dvcs_type, operations): if dvcs_type == 'git': dvcs_cls = Git elif dvcs_type == 'hg': dvcs_cls = Hg else: raise ValueError("Unknown dvcs type {0}".format(dvcs_type)) template_path = join(dirname(__file__), 'test_repo_template') if not os.path.isdir(tmpdir): os.makedirs(tmpdir) dvcs_path = tempfile.mkdtemp(prefix='test_repo', dir=tmpdir) dvcs = dvcs_cls(dvcs_path) dvcs.init() version = 0 for op in operations: if op[0] == "commit": copy_template(template_path, dvcs_path, dvcs, { "version": version, "dummy_value": op[1], }) version += 1 dvcs.commit("Revision {0}".format(version), *op[2:]) elif op[0] == "checkout": dvcs.checkout(*op[1:]) elif op[0] == "merge": dvcs.merge(*op[1:]) else: raise ValueError("Unknown dvcs operation {0}".format(op)) return dvcs def generate_result_dir(tmpdir, dvcs, values, branches=None): result_dir = join(tmpdir, "results") os.makedirs(result_dir) html_dir = join(tmpdir, "html") machine_dir = join(result_dir, "tarzan") os.makedirs(machine_dir) if branches is None: branches = [None] conf = config.Config.from_json({ 'results_dir': result_dir, 'html_dir': html_dir, 'repo': dvcs.path, 'project': 'asv', 'branches': branches or [None], }) repo = get_repo(conf) util.write_json(join(machine_dir, "machine.json"), { 'machine': 'tarzan', 'version': 1, }) timestamp = datetime.datetime.utcnow() benchmark_version = sha256(os.urandom(16)).hexdigest() params = None param_names = None for commit, value in values.items(): if isinstance(value, dict): params = value["params"] result = Results({"machine": "tarzan"}, {}, commit, repo.get_date_from_name(commit), "2.7", None) value = { 'result': [value], 'params': [], 'started_at': timestamp, 'ended_at': timestamp, 'stats': None, 'samples': None, 'number': None, } result.add_result("time_func", value, benchmark_version) result.save(result_dir) if params: param_names = ["param{}".format(k) for k in range(len(params))] util.write_json(join(result_dir, "benchmarks.json"), { "time_func": { "name": "time_func", "params": params or [], "param_names": param_names or [], "version": benchmark_version, } }, api_version=1) return conf @pytest.fixture(scope="session") def browser(request, pytestconfig): """ Fixture for Selenium WebDriver browser interface """ driver_str = pytestconfig.getoption('webdriver') if driver_str == "None": pytest.skip("No webdriver selected for tests (use --webdriver).") # Evaluate the options def FirefoxHeadless(): from selenium.webdriver.firefox.options import Options options = Options() options.add_argument("-headless") return selenium.webdriver.Firefox(firefox_options=options) def ChromeHeadless(): options = selenium.webdriver.ChromeOptions() options.add_argument('headless') return selenium.webdriver.Chrome(chrome_options=options) ns = {} six.exec_("import selenium.webdriver", ns) six.exec_("from selenium.webdriver import *", ns) ns['FirefoxHeadless'] = FirefoxHeadless ns['ChromeHeadless'] = ChromeHeadless create_driver = ns.get(driver_str, None) if create_driver is None: src = "def create_driver():\n" src += textwrap.indent(driver_str, " ") six.exec_(src, ns) create_driver = ns['create_driver'] # Create the browser browser = create_driver() # Set timeouts browser.set_page_load_timeout(WAIT_TIME) browser.set_script_timeout(WAIT_TIME) # Clean up on fixture finalization def fin(): browser.quit() request.addfinalizer(fin) # Set default time to wait for AJAX requests to complete browser.implicitly_wait(WAIT_TIME) return browser @contextmanager def preview(base_path): """ Context manager for ASV preview web server. Gives the base URL to use. Parameters ---------- base_path : str Path to serve files from """ class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler): def translate_path(self, path): # Don't serve from cwd, but from a different directory path = SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self, path) path = os.path.join(base_path, os.path.relpath(path, os.getcwd())) return util.long_path(path) httpd, base_url = create_httpd(Handler) def run(): try: httpd.serve_forever() except: import traceback traceback.print_exc() return thread = threading.Thread(target=run) thread.daemon = True thread.start() try: yield base_url finally: # Stop must be run in a separate thread, because # httpd.shutdown blocks until serve_forever returns. We don't # want to block here --- it appears in some environments # problems shutting down the server may arise. stopper = threading.Thread(target=httpd.shutdown) stopper.daemon = True stopper.start() stopper.join(5.0) def get_with_retry(browser, url): for j in range(2): try: return browser.get(url) except TimeoutException: time.sleep(2) return browser.get(url)
29.724665
95
0.607487
from __future__ import absolute_import, division, unicode_literals, print_function import datetime import io import os import threading import time import six import tempfile import textwrap import sys from os.path import abspath, join, dirname, relpath, isdir from contextlib import contextmanager from hashlib import sha256 from six.moves import SimpleHTTPServer import pytest try: import hglib except ImportError as exc: hglib = None from asv import util from asv import commands from asv import config from asv.commands.preview import create_httpd from asv.repo import get_repo from asv.results import Results PYTHON_VER1 = "{0[0]}.{0[1]}".format(sys.version_info) if sys.version_info < (3,): PYTHON_VER2 = "3.6" else: PYTHON_VER2 = "2.7" SIX_VERSION = "1.10" COLORAMA_VERSIONS = ["0.3.7", "0.3.9"] try: import selenium from selenium.common.exceptions import TimeoutException HAVE_WEBDRIVER = True except ImportError: HAVE_WEBDRIVER = False WAIT_TIME = 20.0 def run_asv(*argv): parser, subparsers = commands.make_argparser() args = parser.parse_args(argv) return args.func(args) def run_asv_with_conf(conf, *argv, **kwargs): assert isinstance(conf, config.Config) parser, subparsers = commands.make_argparser() args = parser.parse_args(argv) if sys.version_info[0] >= 3: cls = args.func.__self__ else: cls = args.func.im_self return cls.run_from_conf_args(conf, args, **kwargs) class Git(object): def __init__(self, path): self.path = abspath(path) self._git = util.which('git') self._fake_date = datetime.datetime.now() def run_git(self, args, chdir=True, **kwargs): if chdir: cwd = self.path else: cwd = None kwargs['cwd'] = cwd return util.check_output( [self._git] + args, **kwargs) def init(self): self.run_git(['init']) self.run_git(['config', 'user.email', 'robot@asv']) self.run_git(['config', 'user.name', 'Robotic Swallow']) def commit(self, message, date=None): if date is None: self._fake_date += datetime.timedelta(seconds=1) date = self._fake_date self.run_git(['commit', '--date', date.isoformat(), '-m', message]) def tag(self, number): self.run_git(['tag', '-a', '-m', 'Tag {0}'.format(number), 'tag{0}'.format(number)]) def add(self, filename): self.run_git(['add', relpath(filename, self.path)]) def checkout(self, branch_name, start_commit=None): args = ["checkout"] if start_commit is not None: args.extend(["-b", branch_name, start_commit]) else: args.append(branch_name) self.run_git(args) def merge(self, branch_name, commit_message=None): self.run_git(["merge", "--no-ff", "--no-commit", "-X", "theirs", branch_name]) if commit_message is None: commit_message = "Merge {0}".format(branch_name) self.commit(commit_message) def get_hash(self, name): return self.run_git(['rev-parse', name]).strip() def get_branch_hashes(self, branch=None): if branch is None: branch = "master" return [x.strip() for x in self.run_git(['rev-list', branch]).splitlines() if x.strip()] def get_commit_message(self, commit_hash): return self.run_git(["log", "-n", "1", "--format=%s", commit_hash]).strip() _hg_config = """ [ui] username = Robotic Swallow <robot@asv> """ class Hg(object): encoding = 'utf-8' def __init__(self, path): self._fake_date = datetime.datetime.now() self.path = abspath(path) def init(self): hglib.init(self.path) with io.open(join(self.path, '.hg', 'hgrc'), 'w', encoding="utf-8") as fd: fd.write(_hg_config) self._repo = hglib.open(self.path.encode(sys.getfilesystemencoding()), encoding=self.encoding) def commit(self, message, date=None): if date is None: self._fake_date += datetime.timedelta(seconds=1) date = self._fake_date date = "{0} 0".format(util.datetime_to_timestamp(date)) self._repo.commit(message.encode(self.encoding), date=date.encode(self.encoding)) def tag(self, number): self._fake_date += datetime.timedelta(seconds=1) date = "{0} 0".format(util.datetime_to_timestamp(self._fake_date)) self._repo.tag( ['tag{0}'.format(number).encode(self.encoding)], message="Tag {0}".format(number).encode(self.encoding), date=date.encode(self.encoding)) def add(self, filename): self._repo.add([filename.encode(sys.getfilesystemencoding())]) def checkout(self, branch_name, start_commit=None): if start_commit is not None: self._repo.update(start_commit.encode(self.encoding)) self._repo.branch(branch_name.encode(self.encoding)) else: self._repo.update(branch_name.encode(self.encoding)) def merge(self, branch_name, commit_message=None): self._repo.merge(branch_name.encode(self.encoding), tool=b"internal:other") if commit_message is None: commit_message = "Merge {0}".format(branch_name) self.commit(commit_message) def get_hash(self, name): log = self._repo.log(name.encode(self.encoding), limit=1) if log: return log[0][1].decode(self.encoding) return None def get_branch_hashes(self, branch=None): if branch is None: branch = "default" log = self._repo.log('sort(ancestors({0}), -rev)'.format(branch).encode(self.encoding)) return [entry[1].decode(self.encoding) for entry in log] def get_commit_message(self, commit_hash): return self._repo.log(commit_hash.encode(self.encoding))[0].desc.decode(self.encoding) def copy_template(src, dst, dvcs, values): for root, dirs, files in os.walk(src): for dir in dirs: src_path = join(root, dir) dst_path = join(dst, relpath(src_path, src)) if not isdir(dst_path): os.makedirs(dst_path) for file in files: src_path = join(root, file) dst_path = join(dst, relpath(src_path, src)) try: with io.open(src_path, 'r', encoding='utf-8') as fd: content = fd.read() except UnicodeDecodeError: with io.open(src_path, 'rb') as fd: content = fd.read() with io.open(dst_path, 'wb') as fd: fd.write(content) else: content = content.format(**values) with io.open(dst_path, 'w', encoding='utf-8') as fd: fd.write(content) dvcs.add(dst_path) def generate_test_repo(tmpdir, values=[0], dvcs_type='git', extra_branches=(), subdir=''): if dvcs_type == 'git': dvcs_cls = Git elif dvcs_type == 'hg': dvcs_cls = Hg else: raise ValueError("Unknown dvcs type {0}".format(dvcs_type)) template_path = join(dirname(__file__), 'test_repo_template') if not os.path.isdir(tmpdir): os.makedirs(tmpdir) dvcs_path = tempfile.mkdtemp(prefix='test_repo', dir=tmpdir) dvcs = dvcs_cls(dvcs_path) dvcs.init() project_path = os.path.join(dvcs_path, subdir) if not os.path.exists(project_path): os.makedirs(project_path) for i, value in enumerate(values): mapping = { 'version': i, 'dummy_value': value } copy_template(template_path, project_path, dvcs, mapping) dvcs.commit("Revision {0}".format(i)) dvcs.tag(i) if extra_branches: for start_commit, branch_name, values in extra_branches: dvcs.checkout(branch_name, start_commit) for i, value in enumerate(values): mapping = { 'version': "{0}".format(i), 'dummy_value': value } copy_template(template_path, project_path, dvcs, mapping) dvcs.commit("Revision {0}.{1}".format(branch_name, i)) return dvcs def generate_repo_from_ops(tmpdir, dvcs_type, operations): if dvcs_type == 'git': dvcs_cls = Git elif dvcs_type == 'hg': dvcs_cls = Hg else: raise ValueError("Unknown dvcs type {0}".format(dvcs_type)) template_path = join(dirname(__file__), 'test_repo_template') if not os.path.isdir(tmpdir): os.makedirs(tmpdir) dvcs_path = tempfile.mkdtemp(prefix='test_repo', dir=tmpdir) dvcs = dvcs_cls(dvcs_path) dvcs.init() version = 0 for op in operations: if op[0] == "commit": copy_template(template_path, dvcs_path, dvcs, { "version": version, "dummy_value": op[1], }) version += 1 dvcs.commit("Revision {0}".format(version), *op[2:]) elif op[0] == "checkout": dvcs.checkout(*op[1:]) elif op[0] == "merge": dvcs.merge(*op[1:]) else: raise ValueError("Unknown dvcs operation {0}".format(op)) return dvcs def generate_result_dir(tmpdir, dvcs, values, branches=None): result_dir = join(tmpdir, "results") os.makedirs(result_dir) html_dir = join(tmpdir, "html") machine_dir = join(result_dir, "tarzan") os.makedirs(machine_dir) if branches is None: branches = [None] conf = config.Config.from_json({ 'results_dir': result_dir, 'html_dir': html_dir, 'repo': dvcs.path, 'project': 'asv', 'branches': branches or [None], }) repo = get_repo(conf) util.write_json(join(machine_dir, "machine.json"), { 'machine': 'tarzan', 'version': 1, }) timestamp = datetime.datetime.utcnow() benchmark_version = sha256(os.urandom(16)).hexdigest() params = None param_names = None for commit, value in values.items(): if isinstance(value, dict): params = value["params"] result = Results({"machine": "tarzan"}, {}, commit, repo.get_date_from_name(commit), "2.7", None) value = { 'result': [value], 'params': [], 'started_at': timestamp, 'ended_at': timestamp, 'stats': None, 'samples': None, 'number': None, } result.add_result("time_func", value, benchmark_version) result.save(result_dir) if params: param_names = ["param{}".format(k) for k in range(len(params))] util.write_json(join(result_dir, "benchmarks.json"), { "time_func": { "name": "time_func", "params": params or [], "param_names": param_names or [], "version": benchmark_version, } }, api_version=1) return conf @pytest.fixture(scope="session") def browser(request, pytestconfig): driver_str = pytestconfig.getoption('webdriver') if driver_str == "None": pytest.skip("No webdriver selected for tests (use --webdriver).") def FirefoxHeadless(): from selenium.webdriver.firefox.options import Options options = Options() options.add_argument("-headless") return selenium.webdriver.Firefox(firefox_options=options) def ChromeHeadless(): options = selenium.webdriver.ChromeOptions() options.add_argument('headless') return selenium.webdriver.Chrome(chrome_options=options) ns = {} six.exec_("import selenium.webdriver", ns) six.exec_("from selenium.webdriver import *", ns) ns['FirefoxHeadless'] = FirefoxHeadless ns['ChromeHeadless'] = ChromeHeadless create_driver = ns.get(driver_str, None) if create_driver is None: src = "def create_driver():\n" src += textwrap.indent(driver_str, " ") six.exec_(src, ns) create_driver = ns['create_driver'] browser = create_driver() browser.set_page_load_timeout(WAIT_TIME) browser.set_script_timeout(WAIT_TIME) def fin(): browser.quit() request.addfinalizer(fin) browser.implicitly_wait(WAIT_TIME) return browser @contextmanager def preview(base_path): class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler): def translate_path(self, path): path = SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self, path) path = os.path.join(base_path, os.path.relpath(path, os.getcwd())) return util.long_path(path) httpd, base_url = create_httpd(Handler) def run(): try: httpd.serve_forever() except: import traceback traceback.print_exc() return thread = threading.Thread(target=run) thread.daemon = True thread.start() try: yield base_url finally: # Stop must be run in a separate thread, because # httpd.shutdown blocks until serve_forever returns. We don't stopper = threading.Thread(target=httpd.shutdown) stopper.daemon = True stopper.start() stopper.join(5.0) def get_with_retry(browser, url): for j in range(2): try: return browser.get(url) except TimeoutException: time.sleep(2) return browser.get(url)
true
true
f72d15f5ed33a0c85d9606f64c9acb94edfbe6d1
16,313
py
Python
synapse/storage/receipts.py
xsteadfastx/synapse
9a8ae6f1bf833b58416fae1add1972ac3e9d2d59
[ "Apache-2.0" ]
1
2017-02-03T18:58:29.000Z
2017-02-03T18:58:29.000Z
synapse/storage/receipts.py
xsteadfastx/synapse
9a8ae6f1bf833b58416fae1add1972ac3e9d2d59
[ "Apache-2.0" ]
null
null
null
synapse/storage/receipts.py
xsteadfastx/synapse
9a8ae6f1bf833b58416fae1add1972ac3e9d2d59
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # 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 ._base import SQLBaseStore from synapse.util.caches.descriptors import cachedInlineCallbacks, cachedList, cached from synapse.util.caches.stream_change_cache import StreamChangeCache from twisted.internet import defer import logging import ujson as json logger = logging.getLogger(__name__) class ReceiptsStore(SQLBaseStore): def __init__(self, hs): super(ReceiptsStore, self).__init__(hs) self._receipts_stream_cache = StreamChangeCache( "ReceiptsRoomChangeCache", self._receipts_id_gen.get_current_token() ) @cachedInlineCallbacks() def get_users_with_read_receipts_in_room(self, room_id): receipts = yield self.get_receipts_for_room(room_id, "m.read") defer.returnValue(set(r['user_id'] for r in receipts)) def _invalidate_get_users_with_receipts_in_room(self, room_id, receipt_type, user_id): if receipt_type != "m.read": return # Returns an ObservableDeferred res = self.get_users_with_read_receipts_in_room.cache.get((room_id,), None) if res and res.called and user_id in res.result: # We'd only be adding to the set, so no point invalidating if the # user is already there return self.get_users_with_read_receipts_in_room.invalidate((room_id,)) @cached(num_args=2) def get_receipts_for_room(self, room_id, receipt_type): return self._simple_select_list( table="receipts_linearized", keyvalues={ "room_id": room_id, "receipt_type": receipt_type, }, retcols=("user_id", "event_id"), desc="get_receipts_for_room", ) @cached(num_args=3) def get_last_receipt_event_id_for_user(self, user_id, room_id, receipt_type): return self._simple_select_one_onecol( table="receipts_linearized", keyvalues={ "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id }, retcol="event_id", desc="get_own_receipt_for_user", allow_none=True, ) @cachedInlineCallbacks(num_args=2) def get_receipts_for_user(self, user_id, receipt_type): rows = yield self._simple_select_list( table="receipts_linearized", keyvalues={ "user_id": user_id, "receipt_type": receipt_type, }, retcols=("room_id", "event_id"), desc="get_receipts_for_user", ) defer.returnValue({row["room_id"]: row["event_id"] for row in rows}) @defer.inlineCallbacks def get_receipts_for_user_with_orderings(self, user_id, receipt_type): def f(txn): sql = ( "SELECT rl.room_id, rl.event_id," " e.topological_ordering, e.stream_ordering" " FROM receipts_linearized AS rl" " INNER JOIN events AS e USING (room_id, event_id)" " WHERE rl.room_id = e.room_id" " AND rl.event_id = e.event_id" " AND user_id = ?" ) txn.execute(sql, (user_id,)) return txn.fetchall() rows = yield self.runInteraction( "get_receipts_for_user_with_orderings", f ) defer.returnValue({ row[0]: { "event_id": row[1], "topological_ordering": row[2], "stream_ordering": row[3], } for row in rows }) @defer.inlineCallbacks def get_linearized_receipts_for_rooms(self, room_ids, to_key, from_key=None): """Get receipts for multiple rooms for sending to clients. Args: room_ids (list): List of room_ids. to_key (int): Max stream id to fetch receipts upto. from_key (int): Min stream id to fetch receipts from. None fetches from the start. Returns: list: A list of receipts. """ room_ids = set(room_ids) if from_key: room_ids = yield self._receipts_stream_cache.get_entities_changed( room_ids, from_key ) results = yield self._get_linearized_receipts_for_rooms( room_ids, to_key, from_key=from_key ) defer.returnValue([ev for res in results.values() for ev in res]) @cachedInlineCallbacks(num_args=3, tree=True) def get_linearized_receipts_for_room(self, room_id, to_key, from_key=None): """Get receipts for a single room for sending to clients. Args: room_ids (str): The room id. to_key (int): Max stream id to fetch receipts upto. from_key (int): Min stream id to fetch receipts from. None fetches from the start. Returns: list: A list of receipts. """ def f(txn): if from_key: sql = ( "SELECT * FROM receipts_linearized WHERE" " room_id = ? AND stream_id > ? AND stream_id <= ?" ) txn.execute( sql, (room_id, from_key, to_key) ) else: sql = ( "SELECT * FROM receipts_linearized WHERE" " room_id = ? AND stream_id <= ?" ) txn.execute( sql, (room_id, to_key) ) rows = self.cursor_to_dict(txn) return rows rows = yield self.runInteraction( "get_linearized_receipts_for_room", f ) if not rows: defer.returnValue([]) content = {} for row in rows: content.setdefault( row["event_id"], {} ).setdefault( row["receipt_type"], {} )[row["user_id"]] = json.loads(row["data"]) defer.returnValue([{ "type": "m.receipt", "room_id": room_id, "content": content, }]) @cachedList(cached_method_name="get_linearized_receipts_for_room", list_name="room_ids", num_args=3, inlineCallbacks=True) def _get_linearized_receipts_for_rooms(self, room_ids, to_key, from_key=None): if not room_ids: defer.returnValue({}) def f(txn): if from_key: sql = ( "SELECT * FROM receipts_linearized WHERE" " room_id IN (%s) AND stream_id > ? AND stream_id <= ?" ) % ( ",".join(["?"] * len(room_ids)) ) args = list(room_ids) args.extend([from_key, to_key]) txn.execute(sql, args) else: sql = ( "SELECT * FROM receipts_linearized WHERE" " room_id IN (%s) AND stream_id <= ?" ) % ( ",".join(["?"] * len(room_ids)) ) args = list(room_ids) args.append(to_key) txn.execute(sql, args) return self.cursor_to_dict(txn) txn_results = yield self.runInteraction( "_get_linearized_receipts_for_rooms", f ) results = {} for row in txn_results: # We want a single event per room, since we want to batch the # receipts by room, event and type. room_event = results.setdefault(row["room_id"], { "type": "m.receipt", "room_id": row["room_id"], "content": {}, }) # The content is of the form: # {"$foo:bar": { "read": { "@user:host": <receipt> }, .. }, .. } event_entry = room_event["content"].setdefault(row["event_id"], {}) receipt_type = event_entry.setdefault(row["receipt_type"], {}) receipt_type[row["user_id"]] = json.loads(row["data"]) results = { room_id: [results[room_id]] if room_id in results else [] for room_id in room_ids } defer.returnValue(results) def get_max_receipt_stream_id(self): return self._receipts_id_gen.get_current_token() def insert_linearized_receipt_txn(self, txn, room_id, receipt_type, user_id, event_id, data, stream_id): txn.call_after( self.get_receipts_for_room.invalidate, (room_id, receipt_type) ) txn.call_after( self._invalidate_get_users_with_receipts_in_room, room_id, receipt_type, user_id, ) txn.call_after( self.get_receipts_for_user.invalidate, (user_id, receipt_type) ) # FIXME: This shouldn't invalidate the whole cache txn.call_after(self.get_linearized_receipts_for_room.invalidate_many, (room_id,)) txn.call_after( self._receipts_stream_cache.entity_has_changed, room_id, stream_id ) txn.call_after( self.get_last_receipt_event_id_for_user.invalidate, (user_id, room_id, receipt_type) ) res = self._simple_select_one_txn( txn, table="events", retcols=["topological_ordering", "stream_ordering"], keyvalues={"event_id": event_id}, allow_none=True ) topological_ordering = int(res["topological_ordering"]) if res else None stream_ordering = int(res["stream_ordering"]) if res else None # We don't want to clobber receipts for more recent events, so we # have to compare orderings of existing receipts sql = ( "SELECT topological_ordering, stream_ordering, event_id FROM events" " INNER JOIN receipts_linearized as r USING (event_id, room_id)" " WHERE r.room_id = ? AND r.receipt_type = ? AND r.user_id = ?" ) txn.execute(sql, (room_id, receipt_type, user_id)) results = txn.fetchall() if results and topological_ordering: for to, so, _ in results: if int(to) > topological_ordering: return False elif int(to) == topological_ordering and int(so) >= stream_ordering: return False self._simple_delete_txn( txn, table="receipts_linearized", keyvalues={ "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id, } ) self._simple_insert_txn( txn, table="receipts_linearized", values={ "stream_id": stream_id, "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id, "event_id": event_id, "data": json.dumps(data), } ) if receipt_type == "m.read" and topological_ordering: self._remove_old_push_actions_before_txn( txn, room_id=room_id, user_id=user_id, topological_ordering=topological_ordering, ) return True @defer.inlineCallbacks def insert_receipt(self, room_id, receipt_type, user_id, event_ids, data): """Insert a receipt, either from local client or remote server. Automatically does conversion between linearized and graph representations. """ if not event_ids: return if len(event_ids) == 1: linearized_event_id = event_ids[0] else: # we need to points in graph -> linearized form. # TODO: Make this better. def graph_to_linear(txn): query = ( "SELECT event_id WHERE room_id = ? AND stream_ordering IN (" " SELECT max(stream_ordering) WHERE event_id IN (%s)" ")" ) % (",".join(["?"] * len(event_ids))) txn.execute(query, [room_id] + event_ids) rows = txn.fetchall() if rows: return rows[0][0] else: raise RuntimeError("Unrecognized event_ids: %r" % (event_ids,)) linearized_event_id = yield self.runInteraction( "insert_receipt_conv", graph_to_linear ) stream_id_manager = self._receipts_id_gen.get_next() with stream_id_manager as stream_id: have_persisted = yield self.runInteraction( "insert_linearized_receipt", self.insert_linearized_receipt_txn, room_id, receipt_type, user_id, linearized_event_id, data, stream_id=stream_id, ) if not have_persisted: defer.returnValue(None) yield self.insert_graph_receipt( room_id, receipt_type, user_id, event_ids, data ) max_persisted_id = self._receipts_id_gen.get_current_token() defer.returnValue((stream_id, max_persisted_id)) def insert_graph_receipt(self, room_id, receipt_type, user_id, event_ids, data): return self.runInteraction( "insert_graph_receipt", self.insert_graph_receipt_txn, room_id, receipt_type, user_id, event_ids, data ) def insert_graph_receipt_txn(self, txn, room_id, receipt_type, user_id, event_ids, data): txn.call_after( self.get_receipts_for_room.invalidate, (room_id, receipt_type) ) txn.call_after( self._invalidate_get_users_with_receipts_in_room, room_id, receipt_type, user_id, ) txn.call_after( self.get_receipts_for_user.invalidate, (user_id, receipt_type) ) # FIXME: This shouldn't invalidate the whole cache txn.call_after(self.get_linearized_receipts_for_room.invalidate_many, (room_id,)) self._simple_delete_txn( txn, table="receipts_graph", keyvalues={ "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id, } ) self._simple_insert_txn( txn, table="receipts_graph", values={ "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id, "event_ids": json.dumps(event_ids), "data": json.dumps(data), } ) def get_all_updated_receipts(self, last_id, current_id, limit=None): if last_id == current_id: return defer.succeed([]) def get_all_updated_receipts_txn(txn): sql = ( "SELECT stream_id, room_id, receipt_type, user_id, event_id, data" " FROM receipts_linearized" " WHERE ? < stream_id AND stream_id <= ?" " ORDER BY stream_id ASC" ) args = [last_id, current_id] if limit is not None: sql += " LIMIT ?" args.append(limit) txn.execute(sql, args) return txn.fetchall() return self.runInteraction( "get_all_updated_receipts", get_all_updated_receipts_txn )
34.199161
89
0.554343
from ._base import SQLBaseStore from synapse.util.caches.descriptors import cachedInlineCallbacks, cachedList, cached from synapse.util.caches.stream_change_cache import StreamChangeCache from twisted.internet import defer import logging import ujson as json logger = logging.getLogger(__name__) class ReceiptsStore(SQLBaseStore): def __init__(self, hs): super(ReceiptsStore, self).__init__(hs) self._receipts_stream_cache = StreamChangeCache( "ReceiptsRoomChangeCache", self._receipts_id_gen.get_current_token() ) @cachedInlineCallbacks() def get_users_with_read_receipts_in_room(self, room_id): receipts = yield self.get_receipts_for_room(room_id, "m.read") defer.returnValue(set(r['user_id'] for r in receipts)) def _invalidate_get_users_with_receipts_in_room(self, room_id, receipt_type, user_id): if receipt_type != "m.read": return res = self.get_users_with_read_receipts_in_room.cache.get((room_id,), None) if res and res.called and user_id in res.result: # user is already there return self.get_users_with_read_receipts_in_room.invalidate((room_id,)) @cached(num_args=2) def get_receipts_for_room(self, room_id, receipt_type): return self._simple_select_list( table="receipts_linearized", keyvalues={ "room_id": room_id, "receipt_type": receipt_type, }, retcols=("user_id", "event_id"), desc="get_receipts_for_room", ) @cached(num_args=3) def get_last_receipt_event_id_for_user(self, user_id, room_id, receipt_type): return self._simple_select_one_onecol( table="receipts_linearized", keyvalues={ "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id }, retcol="event_id", desc="get_own_receipt_for_user", allow_none=True, ) @cachedInlineCallbacks(num_args=2) def get_receipts_for_user(self, user_id, receipt_type): rows = yield self._simple_select_list( table="receipts_linearized", keyvalues={ "user_id": user_id, "receipt_type": receipt_type, }, retcols=("room_id", "event_id"), desc="get_receipts_for_user", ) defer.returnValue({row["room_id"]: row["event_id"] for row in rows}) @defer.inlineCallbacks def get_receipts_for_user_with_orderings(self, user_id, receipt_type): def f(txn): sql = ( "SELECT rl.room_id, rl.event_id," " e.topological_ordering, e.stream_ordering" " FROM receipts_linearized AS rl" " INNER JOIN events AS e USING (room_id, event_id)" " WHERE rl.room_id = e.room_id" " AND rl.event_id = e.event_id" " AND user_id = ?" ) txn.execute(sql, (user_id,)) return txn.fetchall() rows = yield self.runInteraction( "get_receipts_for_user_with_orderings", f ) defer.returnValue({ row[0]: { "event_id": row[1], "topological_ordering": row[2], "stream_ordering": row[3], } for row in rows }) @defer.inlineCallbacks def get_linearized_receipts_for_rooms(self, room_ids, to_key, from_key=None): room_ids = set(room_ids) if from_key: room_ids = yield self._receipts_stream_cache.get_entities_changed( room_ids, from_key ) results = yield self._get_linearized_receipts_for_rooms( room_ids, to_key, from_key=from_key ) defer.returnValue([ev for res in results.values() for ev in res]) @cachedInlineCallbacks(num_args=3, tree=True) def get_linearized_receipts_for_room(self, room_id, to_key, from_key=None): def f(txn): if from_key: sql = ( "SELECT * FROM receipts_linearized WHERE" " room_id = ? AND stream_id > ? AND stream_id <= ?" ) txn.execute( sql, (room_id, from_key, to_key) ) else: sql = ( "SELECT * FROM receipts_linearized WHERE" " room_id = ? AND stream_id <= ?" ) txn.execute( sql, (room_id, to_key) ) rows = self.cursor_to_dict(txn) return rows rows = yield self.runInteraction( "get_linearized_receipts_for_room", f ) if not rows: defer.returnValue([]) content = {} for row in rows: content.setdefault( row["event_id"], {} ).setdefault( row["receipt_type"], {} )[row["user_id"]] = json.loads(row["data"]) defer.returnValue([{ "type": "m.receipt", "room_id": room_id, "content": content, }]) @cachedList(cached_method_name="get_linearized_receipts_for_room", list_name="room_ids", num_args=3, inlineCallbacks=True) def _get_linearized_receipts_for_rooms(self, room_ids, to_key, from_key=None): if not room_ids: defer.returnValue({}) def f(txn): if from_key: sql = ( "SELECT * FROM receipts_linearized WHERE" " room_id IN (%s) AND stream_id > ? AND stream_id <= ?" ) % ( ",".join(["?"] * len(room_ids)) ) args = list(room_ids) args.extend([from_key, to_key]) txn.execute(sql, args) else: sql = ( "SELECT * FROM receipts_linearized WHERE" " room_id IN (%s) AND stream_id <= ?" ) % ( ",".join(["?"] * len(room_ids)) ) args = list(room_ids) args.append(to_key) txn.execute(sql, args) return self.cursor_to_dict(txn) txn_results = yield self.runInteraction( "_get_linearized_receipts_for_rooms", f ) results = {} for row in txn_results: # We want a single event per room, since we want to batch the # receipts by room, event and type. room_event = results.setdefault(row["room_id"], { "type": "m.receipt", "room_id": row["room_id"], "content": {}, }) # The content is of the form: # {"$foo:bar": { "read": { "@user:host": <receipt> }, .. }, .. } event_entry = room_event["content"].setdefault(row["event_id"], {}) receipt_type = event_entry.setdefault(row["receipt_type"], {}) receipt_type[row["user_id"]] = json.loads(row["data"]) results = { room_id: [results[room_id]] if room_id in results else [] for room_id in room_ids } defer.returnValue(results) def get_max_receipt_stream_id(self): return self._receipts_id_gen.get_current_token() def insert_linearized_receipt_txn(self, txn, room_id, receipt_type, user_id, event_id, data, stream_id): txn.call_after( self.get_receipts_for_room.invalidate, (room_id, receipt_type) ) txn.call_after( self._invalidate_get_users_with_receipts_in_room, room_id, receipt_type, user_id, ) txn.call_after( self.get_receipts_for_user.invalidate, (user_id, receipt_type) ) # FIXME: This shouldn't invalidate the whole cache txn.call_after(self.get_linearized_receipts_for_room.invalidate_many, (room_id,)) txn.call_after( self._receipts_stream_cache.entity_has_changed, room_id, stream_id ) txn.call_after( self.get_last_receipt_event_id_for_user.invalidate, (user_id, room_id, receipt_type) ) res = self._simple_select_one_txn( txn, table="events", retcols=["topological_ordering", "stream_ordering"], keyvalues={"event_id": event_id}, allow_none=True ) topological_ordering = int(res["topological_ordering"]) if res else None stream_ordering = int(res["stream_ordering"]) if res else None # have to compare orderings of existing receipts sql = ( "SELECT topological_ordering, stream_ordering, event_id FROM events" " INNER JOIN receipts_linearized as r USING (event_id, room_id)" " WHERE r.room_id = ? AND r.receipt_type = ? AND r.user_id = ?" ) txn.execute(sql, (room_id, receipt_type, user_id)) results = txn.fetchall() if results and topological_ordering: for to, so, _ in results: if int(to) > topological_ordering: return False elif int(to) == topological_ordering and int(so) >= stream_ordering: return False self._simple_delete_txn( txn, table="receipts_linearized", keyvalues={ "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id, } ) self._simple_insert_txn( txn, table="receipts_linearized", values={ "stream_id": stream_id, "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id, "event_id": event_id, "data": json.dumps(data), } ) if receipt_type == "m.read" and topological_ordering: self._remove_old_push_actions_before_txn( txn, room_id=room_id, user_id=user_id, topological_ordering=topological_ordering, ) return True @defer.inlineCallbacks def insert_receipt(self, room_id, receipt_type, user_id, event_ids, data): if not event_ids: return if len(event_ids) == 1: linearized_event_id = event_ids[0] else: # we need to points in graph -> linearized form. # TODO: Make this better. def graph_to_linear(txn): query = ( "SELECT event_id WHERE room_id = ? AND stream_ordering IN (" " SELECT max(stream_ordering) WHERE event_id IN (%s)" ")" ) % (",".join(["?"] * len(event_ids))) txn.execute(query, [room_id] + event_ids) rows = txn.fetchall() if rows: return rows[0][0] else: raise RuntimeError("Unrecognized event_ids: %r" % (event_ids,)) linearized_event_id = yield self.runInteraction( "insert_receipt_conv", graph_to_linear ) stream_id_manager = self._receipts_id_gen.get_next() with stream_id_manager as stream_id: have_persisted = yield self.runInteraction( "insert_linearized_receipt", self.insert_linearized_receipt_txn, room_id, receipt_type, user_id, linearized_event_id, data, stream_id=stream_id, ) if not have_persisted: defer.returnValue(None) yield self.insert_graph_receipt( room_id, receipt_type, user_id, event_ids, data ) max_persisted_id = self._receipts_id_gen.get_current_token() defer.returnValue((stream_id, max_persisted_id)) def insert_graph_receipt(self, room_id, receipt_type, user_id, event_ids, data): return self.runInteraction( "insert_graph_receipt", self.insert_graph_receipt_txn, room_id, receipt_type, user_id, event_ids, data ) def insert_graph_receipt_txn(self, txn, room_id, receipt_type, user_id, event_ids, data): txn.call_after( self.get_receipts_for_room.invalidate, (room_id, receipt_type) ) txn.call_after( self._invalidate_get_users_with_receipts_in_room, room_id, receipt_type, user_id, ) txn.call_after( self.get_receipts_for_user.invalidate, (user_id, receipt_type) ) # FIXME: This shouldn't invalidate the whole cache txn.call_after(self.get_linearized_receipts_for_room.invalidate_many, (room_id,)) self._simple_delete_txn( txn, table="receipts_graph", keyvalues={ "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id, } ) self._simple_insert_txn( txn, table="receipts_graph", values={ "room_id": room_id, "receipt_type": receipt_type, "user_id": user_id, "event_ids": json.dumps(event_ids), "data": json.dumps(data), } ) def get_all_updated_receipts(self, last_id, current_id, limit=None): if last_id == current_id: return defer.succeed([]) def get_all_updated_receipts_txn(txn): sql = ( "SELECT stream_id, room_id, receipt_type, user_id, event_id, data" " FROM receipts_linearized" " WHERE ? < stream_id AND stream_id <= ?" " ORDER BY stream_id ASC" ) args = [last_id, current_id] if limit is not None: sql += " LIMIT ?" args.append(limit) txn.execute(sql, args) return txn.fetchall() return self.runInteraction( "get_all_updated_receipts", get_all_updated_receipts_txn )
true
true
f72d160fcdb7089f1134d2d7d9f76d09c9f85a8c
2,166
py
Python
services/getSearchResults.py
r0uxt1/falcon
852774e3628fcc08209f34a69bcae4e0d903d408
[ "Unlicense" ]
null
null
null
services/getSearchResults.py
r0uxt1/falcon
852774e3628fcc08209f34a69bcae4e0d903d408
[ "Unlicense" ]
null
null
null
services/getSearchResults.py
r0uxt1/falcon
852774e3628fcc08209f34a69bcae4e0d903d408
[ "Unlicense" ]
null
null
null
import pickle import collections import json import sys import argparse import pathlib import time ROOT_PATH = pathlib.Path(__file__).parents[1].as_posix() trie = pickle.load(open( ROOT_PATH + "/dumps/trie.p", "rb")) catMap = pickle.load(open(ROOT_PATH + "/dumps/catMap.p", "rb")) category = json.load(open(ROOT_PATH + "/dumps/category.json", "r")) def writeToJSONFile(path, fileName, data): filePathNameWithExt = './' + path + '/' + fileName + '.json' with open(filePathNameWithExt, 'w') as fp: json.dump(data, fp) def getSearchResults(searchTerm, display=None): """ part of search.py script, which implements functionality similar to grep -ir <term> """ start = time.time() path = './services' fileName = 'search_output' searchTerms = searchTerm.split() results = [] newResults = [] jsonData = {} jsonData['searchTearm'] = searchTerm for terms in searchTerms: terms = terms.lower() if trie.get(terms): for value in catMap[terms]: results.append(value) counts = collections.Counter(results) results = sorted(results, key=lambda x: -counts[x]) searchResults = [] [searchResults.append(x) for x in results if x not in searchResults] idx = 1 if display: for data in searchResults: #print (category[data]['description']) newResults.append(category[data]['description']) results.append(category[data]) idx = idx+1 if idx>int(display): print ("\n".join(newResults)) jsonData['numResults'] = display jsonData['results'] = newResults end = time.time() jsonData['timeTaken'] = end - start writeToJSONFile(path, fileName, jsonData) return results results = [] newResults = [] for data in searchResults: newResults.append(category[data]['description']) results.append(category[data]) print ("\n".join(newResults)) return results # if len(searchResults)==0: # print "No results found for search"
30.942857
72
0.607572
import pickle import collections import json import sys import argparse import pathlib import time ROOT_PATH = pathlib.Path(__file__).parents[1].as_posix() trie = pickle.load(open( ROOT_PATH + "/dumps/trie.p", "rb")) catMap = pickle.load(open(ROOT_PATH + "/dumps/catMap.p", "rb")) category = json.load(open(ROOT_PATH + "/dumps/category.json", "r")) def writeToJSONFile(path, fileName, data): filePathNameWithExt = './' + path + '/' + fileName + '.json' with open(filePathNameWithExt, 'w') as fp: json.dump(data, fp) def getSearchResults(searchTerm, display=None): start = time.time() path = './services' fileName = 'search_output' searchTerms = searchTerm.split() results = [] newResults = [] jsonData = {} jsonData['searchTearm'] = searchTerm for terms in searchTerms: terms = terms.lower() if trie.get(terms): for value in catMap[terms]: results.append(value) counts = collections.Counter(results) results = sorted(results, key=lambda x: -counts[x]) searchResults = [] [searchResults.append(x) for x in results if x not in searchResults] idx = 1 if display: for data in searchResults: newResults.append(category[data]['description']) results.append(category[data]) idx = idx+1 if idx>int(display): print ("\n".join(newResults)) jsonData['numResults'] = display jsonData['results'] = newResults end = time.time() jsonData['timeTaken'] = end - start writeToJSONFile(path, fileName, jsonData) return results results = [] newResults = [] for data in searchResults: newResults.append(category[data]['description']) results.append(category[data]) print ("\n".join(newResults)) return results
true
true
f72d16e50aee7d691584f49425e40834f26ba2c2
2,098
py
Python
__init__.py
CraftYun83/Survery
bdd80186f5d0e22407c5a22cdf3c80edd50276de
[ "MIT" ]
null
null
null
__init__.py
CraftYun83/Survery
bdd80186f5d0e22407c5a22cdf3c80edd50276de
[ "MIT" ]
null
null
null
__init__.py
CraftYun83/Survery
bdd80186f5d0e22407c5a22cdf3c80edd50276de
[ "MIT" ]
null
null
null
questions = [] Answers = [] ending = "Thank you for taking this quiz!" def help(): print("SubCommands:") print("-----------------------------------------") print("help - shows this help page") print("addQuestion - adds a question") print("deleteQuestion - removes a question") print("printQuestions - prints all existing questions") print("setFinishedText - sets the text users see what the survey finishes") print("start - starts the survey") print("answers - shows the answers") print("reset - resets all options") print("-----------------------------------------") print("Module created by CraftYun83") def addQuestion(addQuestion): questions.append(addQuestion) def printQuestions(): print(questions) def deleteQuestion(deleteQuestion): questions.remove(deleteQuestion) print("Deleted:" , deleteQuestion , "from questions!") def setFinishedText(text): ending = text def start(): count = 0 QuestionLength = len(questions) for i in range(QuestionLength): answer = input(questions[count]) Answers.append(answer) count = count + 1 print(ending) action = input() if action == "Answers": answers() if action == "printQuestions": printQuestions() if action == "reset": reset() if action == "start": start() if action == "help": help() def answers(): countAnswers = 0 AnswersLength = len(Answers) print("Answers:") for i in range(AnswersLength): number = countAnswers + 1 print(number , ":" , Answers[countAnswers]) countAnswers = countAnswers + 1 def reset(): questions = [] count = 0 answers = [] ending = "Thank you for taking this quiz!" print("All settings has been resetted")
36.172414
84
0.522402
questions = [] Answers = [] ending = "Thank you for taking this quiz!" def help(): print("SubCommands:") print("-----------------------------------------") print("help - shows this help page") print("addQuestion - adds a question") print("deleteQuestion - removes a question") print("printQuestions - prints all existing questions") print("setFinishedText - sets the text users see what the survey finishes") print("start - starts the survey") print("answers - shows the answers") print("reset - resets all options") print("-----------------------------------------") print("Module created by CraftYun83") def addQuestion(addQuestion): questions.append(addQuestion) def printQuestions(): print(questions) def deleteQuestion(deleteQuestion): questions.remove(deleteQuestion) print("Deleted:" , deleteQuestion , "from questions!") def setFinishedText(text): ending = text def start(): count = 0 QuestionLength = len(questions) for i in range(QuestionLength): answer = input(questions[count]) Answers.append(answer) count = count + 1 print(ending) action = input() if action == "Answers": answers() if action == "printQuestions": printQuestions() if action == "reset": reset() if action == "start": start() if action == "help": help() def answers(): countAnswers = 0 AnswersLength = len(Answers) print("Answers:") for i in range(AnswersLength): number = countAnswers + 1 print(number , ":" , Answers[countAnswers]) countAnswers = countAnswers + 1 def reset(): questions = [] count = 0 answers = [] ending = "Thank you for taking this quiz!" print("All settings has been resetted")
true
true
f72d187a0bb36150ddc8d414250d5ed8a96e26c9
48,395
py
Python
gilbert.py
Erebyel/Gilbert
b7206278cae8c4686de9b87f042fbda42b5fe324
[ "MIT" ]
null
null
null
gilbert.py
Erebyel/Gilbert
b7206278cae8c4686de9b87f042fbda42b5fe324
[ "MIT" ]
null
null
null
gilbert.py
Erebyel/Gilbert
b7206278cae8c4686de9b87f042fbda42b5fe324
[ "MIT" ]
null
null
null
##---------------------- Carga de bibliotecas from pandas import DataFrame import streamlit as st import numpy as np ##---------------------- Base de datos frase = DataFrame({'artículo': ['El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'La', 'La', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'El'], 'sujeto': ['acantilado', 'ácaro', 'acertijo', 'adivinanza', 'adorno', 'aeronave', 'afluente', 'aguacate', 'aguja', 'alba', 'alegría', 'alféizar', 'alondra', 'amada', 'amanecer', 'amante', 'amistad', 'amor', 'anciana', 'andén', 'ángel', 'anillo', 'ansiedad', 'aposento', 'árbol', 'arco', 'armadura', 'arpía', 'arquitecto', 'arrebol', 'arroyo', 'artefacto mágico', 'asteroide', 'astronauta', 'atún', 'aurora', 'ausencia', 'avena', 'aventura', 'avión', 'azafrán', 'azúcar', 'baile de disfraces', 'balcón', 'baldosa', 'ballena', 'balrog', 'balsa', 'banco', 'bandido', 'bar', 'barca', 'barco pirata', 'belfo', 'beso', 'besugo', 'biblioteca', 'bicicleta', 'bigote', 'bikini', 'billar', 'bisonte', 'bizcocho borracho', 'boca', 'bocadillo', 'bogavante', 'bohemia', 'bolo', 'bombero', 'bosque', 'bota', 'botella', 'botón', 'braga', 'brisa', 'bronceador', 'bruja', 'brújula', 'buitre', 'burdégano', 'caballero', 'caballito de mar', 'caballo', 'cabaña', 'cadena', 'café', 'caldero', 'camarote', 'camino', 'campo de batalla', 'campo de torneos', 'cancerbero', 'canoa', 'capitán', 'carta', 'casa solariega', 'cascada', 'castillo', 'catacumba', 'catarro', 'cementerio', 'centauro', 'cerradura', 'chimenea', 'chocolate', 'cicatriz', 'cíclope', 'cielo', 'ciénaga', 'cisne', 'ciudad', 'claridad', 'cobertizo', 'cocina', 'cocinera', 'cofre', 'colchón', 'colibrí', 'colina', 'colonia', 'cometa', 'comida', 'compasión', 'concha', 'concierto', 'constelación', 'copo de nieve', 'cordón', 'corona', 'corpúsculo', 'creatividad', 'crepúsculo', 'crucero', 'cuchara', 'cuchillo', 'cuervo', 'cueva', 'dado', 'dardo', 'dátil', 'delfín', 'demonio', 'depresión', 'desagüe', 'desenlace', 'desertor', 'desfiladero', 'desierto', 'destino', 'devaneo', 'día', 'dibujo', 'dinastía', 'diodo', 'dios', 'dique', 'dodo', 'dolor', 'dragón', 'dragón de komodo', 'dríada', 'droga', 'duende', 'duna', 'eclipse', 'edredón', 'ejército', 'elfo', 'elocuencia', 'enano', 'enemigo', 'epifanía', 'época', 'equidna', 'equilibrista', 'equitación', 'erizo de mar', 'escalera', 'escarabajo', 'escarcha', 'escasez', 'escoba', 'escorpión', 'escotilla', 'escritor', 'escudero', 'escudo', 'esfinge', 'esgrima', 'espacio', 'espacio exterior', 'espada', 'espaguetis', 'espejo', 'esperanza', 'esponja', 'esposa', 'establo', 'estación', 'estadio', 'estanque', 'estatua', 'estrella', 'estropajo', 'estuario', 'faisán', 'familia', 'farmacia', 'farol', 'felpudo', 'fénix', 'feudo', 'fiambre', 'fiebre', 'fiera', 'fiesta', 'fino ropaje', 'fiordo', 'flamenco', 'flauta', 'flirteo', 'flota', 'fluctuación', 'foca', 'foso', 'frambuesa', 'francotirador', 'fraternidad', 'fresa', 'fresco', 'frío', 'frontera', 'fruta', 'fruto seco', 'fuego', 'fuente', 'futuro', 'gabardina', 'galápago', 'galaxia', 'gallo', 'gasolina', 'gato', 'gaviota', 'geografía', 'gigante', 'ginebra', 'giro postal', 'globo', 'glotón', 'golondrina', 'gorgona', 'gorila', 'gorrión', 'granada', 'granizo', 'granja', 'grapadora', 'grasa', 'grosella', 'grulla', 'guardia', 'guardia', 'guateque', 'guepardo', 'guindilla', 'gula', 'gusano', 'haba', 'habitante', 'hacha', 'hada', 'hada madrina', 'halcón', 'hambre', 'hamburguesa', 'hechizo', 'hélice', 'helicóptero', 'heraldo', 'herboristería', 'heredero', 'herida', 'hermana', 'hermanastra', 'hermano', 'herramienta', 'hidra', 'hiena', 'hierro forjado', 'hígado', 'higiene', 'hipocampo', 'hipogrifo', 'hipopótamo', 'hobbit', 'hogar', 'hormiga', 'hormigonera', 'horno microondas', 'hortaliza', 'huelga', 'huérfano', 'hueso', 'humedad', 'huracán', 'hurón', 'idilio', 'iglesia', 'iguana', 'imán', 'impermeable', 'impresionismo', 'incandescencia', 'infraestructura', 'insecto', 'instituto', 'incendio', 'interespacio', 'internado', 'interruptor', 'intimidad', 'invernadero', 'invierno', 'inyección', 'iridiscencia', 'isla', 'jabón', 'jaguar', 'jamón', 'jardín', 'jarra', 'jaula', 'jazz', 'jengibre', 'jerbo', 'jilguero', 'jinete', 'joya', 'judo', 'jungla', 'justa', 'justicia', 'kiwi', 'ladrón', 'lagartija', 'lago', 'lanza', 'látigo', 'laurel', 'lava', 'lechuga', 'lechuza', 'lenteja', 'leñador', 'león', 'leopardo', 'leotardo', 'leprechaun', 'lesión', 'libélula', 'libro', 'licor', 'ligue', 'diferencia', 'limón', 'linaje', 'lince', 'litera', 'literatura', 'llave', 'lluvia', 'lobo', 'locomotora', 'lombriz de tierra', 'loro', 'lotería', 'lubina', 'lugar bajo el agua', 'lugar bajo tierra', 'luminiscencia', 'luna', 'luz', 'madrastra', 'magnetófono', 'mago', 'mamut', 'manantial', 'manifestación', 'manta', 'mantícora', 'manzana', 'mapa', 'mar', 'mar', 'maratón', 'marinero', 'marisco', 'marmota', 'mausoleo', 'mazapán', 'mazmorra', 'mazorca', 'meandro', 'medianoche', 'meiga', 'melancolía', 'mendigo', 'mermelada de tomate', 'mina', 'minotauro', 'mirlo', 'molécula', 'molinillo', 'monasterio', 'monstruo', 'montaña', 'montaña rusa', 'monte', 'mosca', 'muérgano', 'mujeriego', 'muñeca', 'murciégalo', 'muro', 'musa', 'música', 'nabo', 'naranja', 'nariz', 'narval', 'nata', 'natación', 'naufragio', 'nave', 'náyade', 'nécora', 'nectarina', 'nevera', 'nieve', 'ninfa', 'niñera', 'niño', 'níspero', 'noche', 'noria', 'nostalgia', 'novelista', 'noviazgo', 'nube', 'nudillo', 'nutria', 'nutrición', 'nylon', 'ñandú', 'ñu', 'oasis', 'obertura', 'obrero', 'oca', 'océano', 'odio', 'oficial', 'ogro', 'ojo', 'oleaje', 'olla de presión', 'olvido', 'ombligo', 'ondina', 'orate', 'orco', 'ordinario', 'orégano', 'oreja', 'orfanato', 'ornitorrinco', 'oro', 'orquesta', 'ósculo', 'oso hormiguero', 'ostra', 'otoño', 'oveja', 'pabellón', 'pájaro', 'palacio', 'pantano', 'pantera', 'parchís', 'pasión', 'pastel', 'patinaje', 'payaso', 'pegaso', 'peluca', 'perfume', 'perro', 'pescador', 'petirrojo', 'pez', 'pezuña', 'piedra', 'pintura', 'piña', 'pipa', 'pirata', 'pistacho', 'pistola', 'pitonisa', 'pizarra', 'planeta', 'plano', 'plástico', 'plata', 'playa', 'pluma', 'poción', 'político', 'polizón', 'posada', 'pozo', 'pradera', 'precipicio', 'prenda de amor', 'primavera', 'princesa', 'príncipe', 'promesa', 'pueblo', 'puente', 'puerta', 'puerto', 'pulga', 'quebrantahuesos', 'quimera', 'química', 'quiosco', 'radio', 'rana', 'rascacielos', 'rastrillo', 'rata', 'ratón', 'raya', 'realismo', 'receta', 'recogedor', 'rectángulo', 'recuerdo', 'refresco', 'regadera', 'regalo', 'regreso', 'reina', 'reino', 'relámpago', 'relieve', 'religión', 'reliquia', 'remo', 'remolacha', 'rémora', 'rencor', 'reno', 'reportaje', 'reproducción', 'resiliencia', 'retraso', 'retrato', 'reunión', 'rey', 'rinoceronte', 'río', 'rocío', 'rodilla', 'romanticismo', 'ropa', 'ruina', 'ruiseñor', 'sábana', 'sacaclavos', 'sacerdote', 'sacerdotisa', 'sal', 'salchichón', 'salida', 'salmuera', 'salón de baile', 'salón del trono', 'saltamontes', 'salud', 'sangre', 'sanguijuela', 'santuario', 'sapo', 'sartén', 'satélite', 'semáforo', 'sensualidad', 'sentimiento', 'sequía', 'serendipia', 'sereno', 'serpiente', 'serpiente marina', 'servilletero', 'sexo', 'sílfide', 'sinfonía', 'sirena', 'sistema solar', 'sol', 'soledad', 'sombrero', 'sonámbulo', 'suciedad', 'sueño', 'sujetador', 'taberna', 'tambor', 'tarántula', 'tarta de queso', 'taxi', 'tempestad', 'templo', 'tentación', 'tentempié', 'terciopelo', 'tesoro', 'tierra', 'tierra extranjera', 'tifón', 'timón', 'tiovivo', 'toalla', 'tobillo', 'tobogán', 'torre', 'tortilla', 'tortuga', 'trabajo duro', 'trampa', 'transatlántico', 'transeúnte', 'tranvía', 'trasgo', 'tren', 'trenza', 'trigo', 'tripulación', 'tritón', 'troll', 'trueno', 'tucán', 'tuerca', 'tulipán', 'tumba', 'ultramarinos', 'unicornio', 'uniforme', 'universidad', 'universo', 'uña', 'urraca', 'utensilio', 'uva', 'vaca', 'vagabundo', 'vagina', 'vagón', 'vainilla', 'vajilla', 'valle', 'vampiro', 'varano', 'vaso', 'velero', 'venado', 'vendaje', 'ventana', 'verdad', 'verdulería', 'vestuario', 'vía', 'viajero', 'víbora', 'vida', 'vidrio', 'viejo', 'viento', 'vinagrera', 'virtud', 'visita', 'vitalidad', 'vituperio', 'vodka', 'volcán', 'vuelo', 'whisky', 'wombat', 'wyvern', 'xilófono', 'yate', 'yegua', 'yogur', 'yunque', 'zanahoria', 'zapato', 'zarzamora', 'zarzuela', 'cebra', 'zorro', 'zueco'], 'adjetivo masculino': ['absurdo', 'ácido', 'admirable', 'adolescente', 'afectuoso', 'afortunado', 'alegre', 'altivo', 'amable', 'amargo', 'ambiguo', 'amistoso', 'andrajoso', 'angelical', 'anómalo', 'anónimo', 'ansioso', 'antiguo', 'apasionado', 'apático', 'argénteo', 'árido', 'arrejuntado', 'artesanal', 'áspero', 'astuto', 'atento', 'atómico', 'atractivo', 'atrevido', 'atroz', 'audaz', 'áurico', 'ausente', 'automático', 'bajo', 'bancario', 'barato', 'bárbaro', 'básico', 'basto', 'beato', 'belga', 'bélico', 'beligerante', 'bello', 'bíblico', 'bilingüe', 'biológico', 'blanco', 'blando', 'bonito', 'boreal', 'borracho', 'boscoso', 'breve', 'brillante', 'brusco', 'brutal', 'bueno', 'burgués', 'burlón', 'cálido', 'callejero', 'caprichoso', 'cariñoso', 'cascarrabias', 'casposo', 'cauto', 'célebre', 'celoso', 'cercano', 'cerúleo', 'ciego', 'cínico', 'clasista', 'cobarde', 'coherente', 'colosal', 'cómodo', 'compacto', 'compasivo', 'complejo', 'complicado', 'comprensivo', 'común', 'contradictorio', 'convencional', 'convincente', 'cordial', 'corpulento', 'cortante', 'cortesano', 'cósmico', 'creativo', 'criminal', 'crítico', 'crónico', 'cruel', 'cuántico', 'cuidadoso', 'culpable', 'curativo', 'curioso', 'curvo', 'débil', 'decidido', 'delgado', 'delicado', 'delicioso', 'delincuente', 'dependiente', 'deprimido', 'desagradable', 'desaliñado', 'desapasionado', 'desarmado', 'descomunal', 'desconfiado', 'descuidado', 'deseado', 'desfavorecido', 'deshonrado', 'desierto', 'despierto', 'dichoso', 'diferente', 'difícil', 'diminuto', 'dinámico', 'directo', 'discreto', 'disfrazado', 'disperso', 'distante', 'divertido', 'divino', 'dócil', 'doloroso', 'doméstico', 'dorado', 'dracónico', 'dramático', 'druídico', 'dulce', 'duro', 'ecológico', 'efímero', 'egoísta', 'electrónico', 'elegante', 'élfico', 'emocional', 'encantador', 'enérgico', 'enfadado', 'enfermo', 'engreído', 'enjuto', 'enterrado', 'entrometido', 'equilibrado', 'erótico', 'erróneo', 'esbelto', 'escandaloso', 'escéptico', 'espacial', 'espeso', 'espiritual', 'espontáneo', 'estéril', 'estimulante', 'estoico', 'estricto', 'eterno', 'ético', 'exagerado', 'excéntrico', 'excesivo', 'exclusivo', 'exigente', 'exitoso', 'exótico', 'explosivo', 'expresivo', 'exquisito', 'extraordinario', 'extrovertido', 'fácil', 'falto', 'familiar', 'famoso', 'fanático', 'fantástico', 'fascinante', 'fatal', 'fatuo', 'favorito', 'feliz', 'femenino', 'feo', 'fértil', 'fiable', 'ficticio', 'fiel', 'fijo', 'final', 'fino', 'firme', 'flaco', 'flexible', 'flojo', 'floral', 'fluvial', 'formal', 'frágil', 'franco', 'frecuente', 'fresco', 'frío', 'fuerte', 'fugaz', 'fúnebre', 'funesto', 'furioso', 'fútil', 'general', 'genérico', 'generoso', 'genético', 'genial', 'geográfico', 'geológico', 'geométrico', 'gigante', 'gitano', 'glacial', 'global', 'glorioso', 'gordo', 'gótico', 'gracioso', 'gráfico', 'grande', 'grandilocuente', 'grandioso', 'grato', 'gratuito', 'grave', 'griego', 'gris', 'grosero', 'grotesco', 'grueso', 'gruñón', 'guapo', 'hábil', 'habitual', 'hablador', 'hambriento', 'harto', 'henchido', 'herbáceo', 'heredado', 'herido', 'hermoso', 'heroico', 'heterogéneo', 'hidráulico', 'hipócrita', 'hipotético', 'histérico', 'histórico', 'holgazán', 'homogéneo', 'homosexual', 'hondo', 'horizontal', 'horrible', 'hostil', 'humanitario', 'humano', 'húmedo', 'humilde', 'huraño', 'imprudente', 'incandescente', 'incognoscible', 'inconmensurable', 'inconsciente', 'joven', 'judío', 'juguetón', 'juramentado', 'jurídico', 'justo', 'juvenil', 'kinestésico', 'laboral', 'lamentable', 'largo', 'latente', 'lateral', 'legal', 'legítimo', 'lejano', 'lento', 'lésbico', 'leve', 'levítico', 'liberal', 'libre', 'lícito', 'ligero', 'limpio', 'lindo', 'lingüístico', 'líquido', 'listo', 'litúrgico', 'llamativo', 'lleno', 'llorón', 'lluvioso', 'local', 'loco', 'lógico', 'lúcido', 'lujoso', 'luminiscente', 'luminoso', 'lunático', 'maduro', 'mágico', 'magnífico', 'maldito', 'maleducado', 'malhumorado', 'malicioso', 'maltratado', 'maravilloso', 'marciano', 'marginal', 'marino', 'masculino', 'material', 'maternal', 'medieval', 'melancólico', 'mensurable', 'menudo', 'meticuloso', 'mezquino', 'miedoso', 'minúsculo', 'miserable', 'misterioso', 'mítico', 'moderado', 'moderno', 'modesto', 'molesto', 'monumental', 'mordaz', 'mortal', 'móvil', 'mudo', 'musical', 'mutuo', 'naciente', 'nacional', 'nacionalista', 'narcisista', 'narrativo', 'natural', 'nazi', 'negativo', 'negro', 'nervioso', 'neutro', 'noble', 'nocivo', 'nocturno', 'nónuplo', 'normal', 'normativo', 'notable', 'notarial', 'notorio', 'novel', 'novelero', 'nuclear', 'nuevo', 'nulo', 'numérico', 'numeroso', 'nutritivo', 'objetivo', 'obligatorio', 'observable', 'obvio', 'occidental', 'oceánico', 'octavo', 'óctuplo', 'ocultación', 'oculto', 'odioso', 'ofensivo', 'oficial', 'ontológico', 'opaco', 'operativo', 'oportuno', 'óptico', 'oral', 'orbitado', 'ordinario', 'orgánico', 'organizativo', 'orgulloso', 'oriental', 'original', 'originario', 'ortográfico', 'oscuro', 'pálido', 'parturiento', 'pasional', 'pasivo', 'pasteloso', 'patético', 'pedregoso', 'peligroso', 'penetrante', 'penoso', 'pequeño', 'perenne', 'perezoso', 'perfecto', 'perpetuo', 'perseverante', 'perverso', 'pícaro', 'pintoresco', 'placentero', 'pobre', 'poderoso', 'poético', 'polémico', 'positivo', 'precoz', 'preponderante', 'prestigioso', 'pretencioso', 'previsible', 'prodigioso', 'profético', 'profundo', 'progresista', 'provocador', 'prudente', 'puntual', 'quieto', 'químico', 'quinto', 'quirúrgico', 'quisquilloso', 'racional', 'racista', 'radiante', 'radical', 'rápido', 'raro', 'razonable', 'reacio', 'realista', 'rebelde', 'receloso', 'reciente', 'recto', 'referente', 'relativo', 'reluciente', 'renovador', 'repentino', 'reservado', 'resistente', 'respetable', 'responsable', 'revolucionario', 'rico', 'ridículo', 'rígido', 'riguroso', 'rimbombante', 'robado', 'rocoso', 'románico', 'romano', 'romántico', 'roto', 'rotundo', 'rubio', 'ruidoso', 'rutinario', 'sabio', 'sagaz', 'sagrado', 'salado', 'salvaje', 'sangriento', 'sano', 'santificado', 'secreto', 'seguro', 'selenita', 'sencillo', 'sensato', 'sensible', 'sensorial', 'sentimental', 'sereno', 'serio', 'servicial', 'severo', 'sexual', 'silencioso', 'similar', 'simpático', 'simulado', 'sincero', 'siniestro', 'sintético', 'sobrenatural', 'sofista', 'sofisticado', 'soleado', 'solemne', 'solidario', 'solitario', 'sombrío', 'sonriente', 'sospechoso', 'suave', 'sucio', 'suculento', 'sudoroso', 'sueño', 'susceptible', 'sutil', 'tacaño', 'taciturno', 'tajante', 'talentoso', 'tardío', 'temeroso', 'temible', 'temporal', 'tenaz', 'tenso', 'teórico', 'terapéutico', 'térmico', 'terrestre', 'terrible', 'territorial', 'terrorista', 'tibio', 'tierno', 'tieso', 'tímido', 'típico', 'tonto', 'torpe', 'tóxico', 'trabajador', 'tradicional', 'trágico', 'traicionado', 'tranquilo', 'transitorio', 'transparente', 'travieso', 'tripulado', 'triste', 'trivial', 'turbio', 'ulterior', 'último', 'unánime', 'único', 'uniforme', 'unitario', 'universal', 'universitario', 'urbano', 'urgente', 'usual', 'útil', 'utilitario', 'utilizable', 'vacío', 'vagamundo', 'vago', 'valeroso', 'válido', 'valiente', 'valioso', 'vano', 'variable', 'variado', 'vasto', 'vegetal', 'vegetativo', 'veloz', 'envenenado', 'verbal', 'verde', 'verosímil', 'vertical', 'vespertino', 'veterano', 'viable', 'victorioso', 'viejo', 'vigente', 'violento', 'virgen', 'visible', 'vital', 'vitoreado', 'vivaz', 'viviente', 'voluntario', 'vulgar', 'yodado', 'zafio', 'zafíreo', 'zarrapastroso', 'zopenco', 'enquistado', 'conquistado', 'atormentado', 'radiactivo', 'machista', 'fulminante', 'plurilingüe', 'equivalente', 'equidistante', 'paralelo', 'ignorante', 'destrozado', 'acuartelado', 'evolucionado', 'añejo', 'dañado', 'anglicano', 'norteño', 'sureño', 'sustentado', 'español', 'calzado', 'embustero', 'amarillo', 'azul', 'rojo', 'rosa', 'arrinconado', 'oloroso', 'omnipresente', 'omnisciente', 'todopoderoso', 'acomplejado', 'castellanizado', 'debilitado', 'diferenciado', 'sepulcral', 'terraplanista', 'homeostático', 'onomatopéyico', 'gritón', 'sustancioso', 'lácteo', 'cósmico', 'bíblico', 'apestoso', 'despojado', 'rubicundo', 'encuestado', 'tórrido', 'mentiroso', 'estúpido', 'escrupuloso', 'contundente', 'cobrizo', 'escandaloso', 'lozano', 'pechugón', 'níveo', 'blanco', 'esculpido', 'negro', 'racista', 'robótico', 'inteligente', 'artificial', 'artificioso', 'adecuado', 'cómico', 'tramado', 'tramposo', 'lúcido'], 'adjetivo femenino': ['absurda', 'ácida', 'admirable', 'adolescente', 'afectuosa', 'afortunada', 'alegre', 'altiva', 'amable', 'amarga', 'ambigua', 'amistosa', 'andrajosa', 'angelical', 'anómala', 'anónima', 'ansiosa', 'antigua', 'apasionada', 'apática', 'argéntea', 'árida', 'arrejuntada', 'artesanal', 'áspera', 'astuta', 'atenta', 'atómica', 'atractiva', 'atrevida', 'atroz', 'audaz', 'áurica', 'ausente', 'automática', 'baja', 'bancaria', 'barata', 'bárbara', 'básica', 'basta', 'beata', 'belga', 'bélica', 'beligerante', 'bella', 'bíblica', 'bilingüe', 'biológica', 'blanca', 'blanda', 'bonita', 'boreal', 'borracha', 'boscosa', 'breve', 'brillante', 'brusca', 'brutal', 'buena', 'burguesa', 'burlona', 'cálida', 'callejera', 'caprichosa', 'cariñosa', 'cascarrabias', 'casposa', 'cauta', 'célebre', 'celosa', 'cercana', 'cerúlea', 'ciega', 'cínica', 'clasista', 'cobarde', 'coherente', 'colosal', 'cómoda', 'compacta', 'compasiva', 'compleja', 'complicada', 'comprensiva', 'común', 'contradictoria', 'convencional', 'convincente', 'cordial', 'corpulenta', 'cortante', 'cortesana', 'cósmica', 'creativa', 'criminal', 'crítica', 'crónica', 'cruel', 'cuántica', 'cuidadosa', 'culpable', 'curativa', 'curiosa', 'curva', 'débil', 'decidida', 'delgada', 'delicada', 'deliciosa', 'delincuente', 'dependiente', 'deprimida', 'desagradable', 'desaliñada', 'desapasionada', 'desarmada', 'descomunal', 'desconfiada', 'descuidada', 'deseada', 'desfavorecida', 'deshonrada', 'desierta', 'despierta', 'dichosa', 'diferente', 'difícil', 'diminuta', 'dinámica', 'directa', 'discreta', 'disfrazada', 'dispersa', 'distante', 'divertida', 'divina', 'dócil', 'dolorosa', 'doméstica', 'dorada', 'dracónica', 'dramática', 'druídica', 'dulce', 'dura', 'ecológica', 'efímera', 'egoísta', 'electrónica', 'elegante', 'élfica', 'emocional', 'encantadora', 'enérgica', 'enfadada', 'enferma', 'engreída', 'enjuta', 'enterrada', 'entrometida', 'equilibrada', 'erótica', 'errónea', 'esbelta', 'escandalosa', 'escéptica', 'espacial', 'espesa', 'espiritual', 'espontánea', 'estéril', 'estimulante', 'estoica', 'estricta', 'eterna', 'ética', 'exagerada', 'excéntrica', 'excesiva', 'exclusiva', 'exigente', 'exitosa', 'exótica', 'explosiva', 'expresiva', 'exquisita', 'extraordinaria', 'extrovertida', 'fácil', 'falta', 'familiar', 'famosa', 'fanática', 'fantástica', 'fascinante', 'fatal', 'fatua', 'favorita', 'feliz', 'femenina', 'fea', 'fértil', 'fiable', 'ficticia', 'fiel', 'fija', 'final', 'fina', 'firme', 'flaca', 'flexible', 'floja', 'floral', 'fluvial', 'formal', 'frágil', 'franca', 'frecuente', 'fresca', 'fría', 'fuerte', 'fugaz', 'fúnebre', 'funesta', 'furiosa', 'fútil', 'general', 'genérica', 'generosa', 'genética', 'genial', 'geográfica', 'geológica', 'geométrica', 'gigante', 'gitana', 'glacial', 'global', 'gloriosa', 'gorda', 'gótica', 'graciosa', 'gráfica', 'grande', 'grandilocuente', 'grandiosa', 'grata', 'gratuita', 'grave', 'griega', 'gris', 'grosera', 'grotesca', 'gruesa', 'gruñona', 'guapa', 'hábil', 'habitual', 'habladora', 'hambrienta', 'harta', 'henchida', 'herbácea', 'heredada', 'herida', 'hermosa', 'heroica', 'heterogénea', 'hidráulica', 'hipócrita', 'hipotética', 'histérica', 'histórica', 'holgazana', 'homogénea', 'homosexual', 'honda', 'horizontal', 'horrible', 'hostil', 'humanitaria', 'humana', 'húmeda', 'humilde', 'huraña', 'imprudente', 'incandescente', 'incognoscible', 'inconmensurable', 'inconsciente', 'joven', 'judía', 'juguetona', 'juramentada', 'jurídica', 'justa', 'juvenil', 'kinestésica', 'laboral', 'lamentable', 'larga', 'latente', 'lateral', 'legal', 'legítima', 'lejana', 'lenta', 'lésbica', 'leve', 'levítica', 'liberal', 'libre', 'lícita', 'ligera', 'limpia', 'linda', 'lingüística', 'líquida', 'lista', 'litúrgica', 'llamativa', 'llena', 'llorona', 'lluviosa', 'local', 'loca', 'lógica', 'lúcida', 'lujosa', 'luminiscente', 'luminosa', 'lunática', 'madura', 'mágica', 'magnífica', 'maldita', 'maleducada', 'malhumorada', 'maliciosa', 'maltratada', 'maravillosa', 'marciana', 'marginal', 'marina', 'masculina', 'material', 'maternal', 'medieval', 'melancólica', 'mensurable', 'menuda', 'meticulosa', 'mezquina', 'miedosa', 'minúscula', 'miserable', 'misteriosa', 'mítica', 'moderada', 'moderna', 'modesta', 'molesta', 'monumental', 'mordaz', 'mortal', 'móvil', 'muda', 'musical', 'mutua', 'naciente', 'nacional', 'nacionalista', 'narcisista', 'narrativa', 'natural', 'nazi', 'negativa', 'negra', 'nerviosa', 'neutra', 'noble', 'nociva', 'nocturna', 'nónupla', 'normal', 'normativa', 'notable', 'notarial', 'notoria', 'novel', 'novelera', 'nuclear', 'nueva', 'nula', 'numérica', 'numerosa', 'nutritiva', 'objetiva', 'obligatoria', 'observable', 'obvia', 'occidental', 'oceánica', 'octava', 'óctupla', 'ocultación', 'oculta', 'odiosa', 'ofensiva', 'oficial', 'ontológica', 'opaca', 'operativa', 'oportuna', 'óptica', 'oral', 'orbitada', 'ordinaria', 'orgánica', 'organizativa', 'orgullosa', 'oriental', 'original', 'originaria', 'ortográfica', 'oscura', 'pálida', 'parturienta', 'pasional', 'pasiva', 'pastelosa', 'patética', 'pedregosa', 'peligrosa', 'penetrante', 'penosa', 'pequeña', 'perenne', 'perezosa', 'perfecta', 'perpetua', 'perseverante', 'perversa', 'pícara', 'pintoresca', 'placentera', 'pobre', 'poderosa', 'poética', 'polémica', 'positiva', 'precoz', 'preponderante', 'prestigiosa', 'pretenciosa', 'previsible', 'prodigiosa', 'profética', 'profunda', 'progresista', 'provocadora', 'prudente', 'puntual', 'quieta', 'química', 'quinta', 'quirúrgica', 'quisquillosa', 'racional', 'racista', 'radiante', 'radical', 'rápida', 'rara', 'razonable', 'reacia', 'realista', 'rebelde', 'recelosa', 'reciente', 'recta', 'referente', 'relativa', 'reluciente', 'renovadora', 'repentina', 'reservada', 'resistente', 'respetable', 'responsable', 'revolucionaria', 'rica', 'ridícula', 'rígida', 'rigurosa', 'rimbombante', 'robada', 'rocosa', 'románica', 'romana', 'romántica', 'rota', 'rotunda', 'rubia', 'ruidosa', 'rutinaria', 'sabia', 'sagaz', 'sagrada', 'salada', 'salvaje', 'sangrienta', 'sana', 'santificada', 'secreta', 'segura', 'selenita', 'sencilla', 'sensata', 'sensible', 'sensorial', 'sentimental', 'serena', 'seria', 'servicial', 'severa', 'sexual', 'silenciosa', 'similar', 'simpática', 'simulada', 'sincera', 'siniestra', 'sintética', 'sobrenatural', 'sofista', 'sofisticada', 'soleada', 'solemne', 'solidaria', 'solitaria', 'sombría', 'sonriente', 'sospechosa', 'suave', 'sucia', 'suculenta', 'sudorosa', 'sueña', 'susceptible', 'sutil', 'tacaña', 'taciturna', 'tajante', 'talentosa', 'tardía', 'temerosa', 'temible', 'temporal', 'tenaz', 'tensa', 'teórica', 'terapéutica', 'térmica', 'terrestre', 'terrible', 'territorial', 'terrorista', 'tibia', 'tierna', 'tiesa', 'tímida', 'típica', 'tonta', 'torpe', 'tóxica', 'trabajador', 'tradicional', 'trágica', 'traicionada', 'tranquila', 'transitoria', 'transparente', 'traviesa', 'tripulada', 'triste', 'trivial', 'turbia', 'ulterior', 'última', 'unánime', 'única', 'uniforme', 'unitaria', 'universal', 'universitaria', 'urbana', 'urgente', 'usual', 'útil', 'utilitaria', 'utilizable', 'vacía', 'vagamunda', 'vaga', 'valerosa', 'válida', 'valiente', 'valiosa', 'vana', 'variable', 'variada', 'vasta', 'vegetal', 'vegetativa', 'veloz', 'envenenada', 'verbal', 'verde', 'verosímil', 'vertical', 'vespertina', 'veterana', 'viable', 'victoriosa', 'vieja', 'vigente', 'violenta', 'virgen', 'visible', 'vital', 'vitoreada', 'vivaz', 'viviente', 'voluntaria', 'vulgar', 'yodada', 'zafia', 'zafírea', 'zarrapastrosa', 'zopenca', 'enquistada', 'conquistada', 'atormentada', 'radiactiva', 'machista', 'fulminante', 'plurilingüe', 'equivalente', 'equidistante', 'paralela', 'ignorante', 'destrozada', 'acuartelada', 'evolucionada', 'añeja', 'dañada', 'anglicana', 'norteña', 'sureña', 'sustentada', 'española', 'calzada', 'embustera', 'amarilla', 'azul', 'roja', 'rosa', 'arrinconada', 'olorosa', 'omnipresente', 'omnisciente', 'todopoderosa', 'acomplejada', 'castellanizada', 'debilitado', 'diferenciada', 'sepulcral', 'terraplanista', 'homeostática', 'onomatopéyica', 'gritona', 'sustanciosa', 'láctea', 'cósmica', 'bíblica', 'apestosa', 'despojada', 'rubicunda', 'encuestada', 'tórrida', 'mentirosa', 'estúpida', 'escrupulosa', 'contundente', 'cobriza', 'escandalosa', 'lozana', 'pechugona', 'nívea', 'blanca', 'esculpida', 'negra', 'racista', 'robótica', 'inteligente', 'artificial', 'artificiosa', 'adecuada', 'cómica', 'tramada', 'tramposa', 'lúcida'], 'acciones': ['abofetea a alguien', 'aborrece algo', 'aborta', 'abrocha algo', 'acaba inquieto', 'acaricia a algo/alguien', 'acosa a alguien', 'adelgaza', 'adivina', 'adopta', 'afeita', 'agria', 'agujerea una superficie', 'ahoga a alguien', 'ahorra', 'aísla', 'ajusta', 'alinea', 'alumbra', 'ama', 'amarra', 'amenaza a alguien', 'amputa un miembro', 'amuebla un hogar', 'aniquila un enemigo', 'anticipa un evento', 'anuncia un evento', 'apesta', 'araña', 'arde', 'asedia', 'asesina a un amigo', 'asfixia a un enemigo', 'aterriza forzosamente', 'atormenta', 'atraviesa', 'aturde a alguien', 'auxilia a alguien', 'averigua una mentira', 'ayuna', 'babea', 'baila', 'balancea un objeto', 'balbucea con vergüenza', 'barajea', 'barre', 'batalla en una guerra', 'batea', 'bautiza algo', 'bebe', 'besa a alguien', 'blande un arma', 'blanquea algo', 'blanquea dinero', 'bloquea algo', 'boicotea una estrategia', 'bombardea un territorio', 'borda un tapiz', 'borra algo', 'brilla', 'brinca', 'brinda', 'bromea', 'brota', 'bucea', 'bulle', 'burla', 'busca', 'cabalga', 'cae', 'cambia', 'camufla', 'canta', 'captura', 'castra', 'celebra', 'cepilla', 'cercena', 'chilla', 'cobra vida', 'codicia', 'cojea', 'combate', 'come', 'compite', 'complica algo', 'concibe algo', 'condena a alguien', 'confronta', 'conquista', 'consagra', 'conserva', 'consigna', 'conspira', 'construye', 'contagia', 'copula con el enemigo', 'coquetea', 'corona', 'corre', 'corta', 'corteja a alguien', 'cosecha', 'cultiva', 'cumple una promesa', 'curte', 'custodia', 'danza', 'daña', 'deambula', 'debilita', 'decapita', 'declara', 'deforma', 'defrauda', 'deja pasar el tiempo', 'delata', 'demora', 'denuncia', 'derruye', 'desabrocha', 'desafía', 'desaparece', 'desayuna', 'descansa', 'descubre algo', 'desea', 'desembarca', 'desencanta a alguien', 'desentona', 'deshonra', 'desilusiona', 'desnuda a alguien', 'desobedece', 'desviste', 'devasta', 'dibuja', 'discute', 'disfruta', 'dispara', 'distorsiona', 'divorcia', 'duda', 'duerme', 'eclipsa', 'edifica', 'elige un blasón', 'elimina', 'emborracha', 'emigra', 'empalma', 'empeora', 'enamora', 'encadena', 'encanta', 'enciende', 'encuentra', 'endulza', 'enferma', 'engaña', 'engrasa', 'ensambla', 'entierra', 'entrevista', 'envejece', 'envenena', 'erradica', 'eructa', 'es derrotado', 'es tentado', 'es timado', 'es vapuleado', 'escoge', 'escupe', 'esmalta', 'esposa', 'está penando', 'estornuda', 'estrangula', 'estropea', 'excita', 'experimenta', 'extermina', 'extorsiona', 'extraña', 'fabrica', 'facilita', 'falla', 'falsea', 'fantasea', 'favorece a alguien', 'fermenta', 'festeja', 'fía', 'filma', 'filtra', 'finaliza', 'financia', 'fisgonea', 'flagela', 'flaquea', 'flirtea', 'florece', 'flota', 'fluctúa', 'forcejea', 'forja', 'forma', 'fracasa', 'fracciona', 'fractura', 'fragmenta', 'frecuenta', 'fríe', 'friega', 'fuerza', 'funciona', 'galantea', 'galopa', 'gana', 'garabatea', 'garantiza', 'gasta', 'genera', 'germina', 'gesticula', 'gime', 'gimotea', 'gira', 'glasea', 'glorifica', 'glosa', 'gobierna', 'golpea', 'gorjea', 'gorrea', 'gorronear', 'gotea', 'goza', 'graba', 'grada', 'gradúa', 'granula', 'grapa', 'gravita', 'grita', 'gruñe', 'guarda', 'guía', 'habilita', 'habita', 'habla', 'hace', 'hace amigos', 'hace enemigos', 'hace vibrar algo', 'hacina', 'halla una herramienta', 'halla una pista', 'hereda', 'hermana', 'hiberna', 'hidrata', 'hiela', 'hiere', 'hierra', 'hierve', 'hila', 'hilvana', 'hipa', 'hojear', 'honra', 'hornea', 'hospeda', 'huele', 'huelga', 'humea', 'humedece', 'humilla', 'hunde', 'huye', 'idolatra', 'ignora', 'ilumina', 'imagina', 'imitar', 'impide', 'impone', 'impregna', 'improvisa', 'impulsa una iniciativa', 'incapacita a alguien', 'incinera', 'incomoda', 'infiere algo', 'influye', 'infringe las normas', 'injuria a alguien', 'inocula un veneno', 'inspira', 'instaura algo novedoso', 'instruye al enemigo', 'insulta a alguien', 'intercambia información', 'interpreta', 'interroga a alguien', 'intimida a alguien', 'invade algo', 'investiga', 'invita', 'invoca algo/a alguien', 'jadea', 'jala', 'juega', 'junta algunas piezas', 'jura', 'juzga acertadamente', 'juzga erróneamente', 'lacera', 'lacra', 'ladra', 'lame una superficie', 'lanza algo', 'lastra', 'late', 'le afecta un cambio mágico', 'le gusta algo', 'legitima', 'levanta', 'libera algo', 'lidera un evento', 'lidia con algo inesperado', 'limita', 'limpia', 'lincha', 'lisia a alguien', 'lisonjea inapropiadamente', 'llama a alguien', 'llamea', 'llega', 'llena algo', 'lleva algo a algún sitio', 'llora', 'llueve', 'logra', 'luce algo', 'lucha', 'lustra algo', 'madura', 'malgasta', 'maltrata', 'manda', 'manipula', 'masculla', 'medita', 'medra', 'mendiga', 'merodea', 'mezcla', 'mide', 'miente', 'mima', 'mina', 'mira', 'moderniza', 'modifica', 'moja', 'muele', 'muerde algo/a alguien', 'muere', 'nace', 'nada', 'narra', 'naufraga', 'navega', 'necesita algo/a alguien', 'negocia', 'niega algo', 'nieva', 'nivela', 'nombra', 'nomina', 'nota', 'notifica', 'nubla', 'numera', 'nutre', 'obedece', 'obsequia', 'obtiene', 'obvia', 'ocasiona', 'oculta', 'ocupa', 'odia', 'ofende', 'oficia', 'ofrece', 'olvida', 'omite', 'ondea algo en alto', 'opera lejos', 'opina', 'oprime a alguien', 'opta por una opción', 'ordena', 'organiza', 'orienta', 'origina un conflicto', 'orilla una embarcación', 'ornamenta algo', 'orquesta', 'oscila', 'otorga', 'oxigena', 'oye', 'parodia', 'participa en una justa', 'pasea', 'patea', 'patrulla', 'pega algo/ a alguien', 'peina', 'perdona', 'peregrina', 'perjudica', 'permanece', 'persevera', 'persigue', 'pertenece', 'pierde algo/ a alguien', 'pilota', 'piratea', 'pisotea', 'plancha', 'planifica', 'predestina', 'predice', 'premia', 'priva', 'procrea', 'profana', 'progresa', 'prohíbe', 'promete', 'promueve', 'propulsa', 'protesta', 'provoca', 'puebla', 'quebranta', 'queda', 'queda hospitalizado', 'quiebra', 'quiere a alguien/algo', 'quita a alguien', 'raciona algo', 'rapta a alguien', 'rasura algo', 'razona', 'recauda', 'rechaza', 'recluta a alguien', 'recoge algo', 'recompensa a alguien', 'reconquista a alguien', 'reconstruye algo', 'recuerda algo', 'recupera algo', 'reduce algo', 'regresa', 'renuncia', 'replica algo', 'reprime a alguien', 'repudia a alguien', 'requisa algo', 'rescata', 'rescata a alguien', 'responde', 'resucita', 'resuelve algo', 'retiene ilegalmente a alguien', 'rige un pueblo', 'rima', 'roba', 'rompe un juramento', 'ruega', 'sabotea algo', 'sacrifica algo', 'salpica', 'salva a alguien', 'saquea algo', 'se aburre', 'se ahoga', 'se baña', 'se confunde de identidad', 'se equivoca', 'se fascina con algo', 'se habitúa a algo extraño', 'se habitúa a una nueva vida', 'se hace valer', 'se harta', 'se hiere', 'se infiltra', 'se irrita', 'se jubila', 'se junta con alguien', 'se justifica', 'se lamenta', 'se lastima', 'se le rompe el corazón', 'se libra', 'se magulla', 'se mancha', 'se maravilla', 'se marcha', 'se marchita', 'se marea', 'se mece', 'se molesta', 'se mosquea', 'se motiva', 'se muda', 'se obsesiona', 'se olvida', 'se opone a algo', 'se pierde', 'se posa', 'se queja', 'se quema', 'se recluye', 'se reconcilia', 'se retira', 'se reúne', 'se ríe a carcajadas', 'se rinde', 'se rompe', 'se separa', 'se tambalea', 'se traga algo', 'se tranquiliza', 'se trastorna', 'se turna con alguien', 'se voltea', 'secuestra a alguien', 'seduce a alguien', 'selecciona algo', 'sella un pacto', 'separa algo', 'sepulta algo', 'simplifica algo', 'sitia un lugar', 'soborna a alguien', 'sobrevive', 'socorre a alguien', 'soluciona', 'somete a alguien', 'sonríe', 'soporta algo', 'sorprende a alguien', 'sospecha de algo', 'subestima a otro', 'subestima al enemigo', 'suelda', 'suelta', 'sueña', 'sufre un flechazo inoportuno', 'sugiere una idea', 'sujeta algo', 'supervisa', 'suplanta', 'sustituye', 'sustrae', 'talla', 'tapia algo', 'tararea', 'tartamudea', 'templa un objeto', 'tiembla', 'tiende algo', 'tiñe algo', 'tira algo', 'tira de alguien', 'tolera', 'tontea con alguien', 'tornea un objeto', 'tortura a alguien', 'traduce', 'trafica', 'traiciona', 'trama', 'traspasa algo', 'traslada algo', 'traza', 'trepa', 'trilla algo', 'trincha algo', 'tripula una nave', 'tritura algo', 'tropieza', 'ubica un lugar', 'ubica un objeto', 'ultima algún detalle', 'ultraja', 'ulula', 'une', 'unifica', 'unta algo', 'usa algo', 'usurpa', 'utiliza a alguien', 'va a prisión', 'vadea un lugar', 'vaga por un lugar', 'valida alguna aptitud', 'valora algo', 'vaticina un evento', 've algo insólito', 'veda algo', 'vegeta', 'veja a alguien', 'vence a alguien', 'vende algo/a alguien', 'venera algo', 'venga a alguien querido', 'venga a un desconocido', 'ventila', 'verifica', 'viaja', 'vigila a alguien', 'vilipendia', 'viola', 'visita', 'vitorea', 'vive', 'vocea', 'vota a alguien equivocadamente', 'vuela', 'vuelca', 'vuelve al origen', 'yace', 'zanganea', 'zanja un asunto importante', 'zarandea', 'zigzaguea por un lugar', 'zumba', 'se constipa', 'se apuesta aglo irremplazable', 'confiesa una mezquindad', 'prospera a costa de otro', 'confía en la persona equivocada', 'se come algo tóxico', 'engorda demasiado', 'se camufla entre los habitantes', 'corre hacia un sueño', 'se mete en una caja', 'se despierta en otra época', 'viaja al centro de la tierra', 'se duerme en clase', 'cae sobre una tarta', 'soba un sujetador', 'espolborea veneno sobre alguien', 'canta una canción de cuna', 'apuesta con el enemigo', 'se enamora de su enemigo', 'busca un final feliz', 'comienza a hacerse preguntas', 'se hace derogar', 'se intoxica', 'irradia algo', 'se vuelve radiactivo', 'consigue un material extraño', 'es un embustero', 'mordisquea la comida ajena', 'contextualiza algo', 'aporta un significado al mundo', 'encuentra el significado del universo', 'se encuentra con un ente creador', 'agita unas maracas', 'consigue un don', 'aplana el universo', 'conquista el espacio', 'se enamora de un objeto', 'se desposa con un objeto', 'asesina accidentalmente a alguien', 'secunda una censura', 'se atraganta', 'descuida su aspecto', 'hiere a un amigo', 'hiere a un enemigo', 'cosifica a alguien', 'se siente atraido sexualmente', 'es sexualizado', 'pronuncia un discuros', 'extravía el objeto que lo iba a salvar', 'muere', 'muere de forma estúpida', 'fallece premeditadamente', 'se suicida para evitar a su enemigo', 'estudia', 'convence a un aristócrata', 'se depila', 'depila a alguien', 'escribe un diario', 'roba un objeto', 'se esconde con cobardía', 'se detiene en el camino', 'detiene a alguien', 'es detenido inoportunamente', 'casca nueces', 'rompe un objeto sagrado', 'es excomulgado', 'es cómplice de un asesinato', 'ayuda a su enemigo']}) retos = {'Retos': ['Yo no tengo muy claro que Ana tenga una ánfora, pero eso da igual, porque lo que sí sé es que tienes que hacer una anáfora', 'Alíviate o no te alivies, altérate o no te alteres, pero haz que tu texto sea aliterado', 'Qué paradójico sería que tu texto no tuviese una paradoja', 'Era como… la descripción que has hecho. Ex-ac-ta-men-te', 'Este reto es un alivio, te permite la elipsis de 1 palabra que te haya salido como obligatoria para tu texto. Elige sabiamente', 'Este reto es un alivio, te permite la elipsis de 2 palabras que te hayan salido como obligatorias para tu texto. Elige sabiamente', 'Este reto es un alivio, te permite la elipsis de 3 palabras que te hayan salido como obligatorias para tu texto. Elige sabiamente', 'Este reto es un alivio, te permite la elipsis de 4 palabras que te hayan salido como obligatorias para tu texto. Elige sabiamente', '¿Quién conoce el futuro? Bueno, pues tendrás que imaginártelo', 'Me da igual que tengas que incluir una lavadora, tu texto debe enmarcarse en la época clásica', 'Me importa poco que tu protagonista sea una impresora 3D, tus protagonistas están en la Edad Media', 'En una época donde existía la magia… tu texto estaría en su contexto correcto', 'Si no te ríes al leerlo, no molas porque no es comedia', 'Seguro que, gracias a tu emotiva oda, el protagonista de tu historia será recordado eternamente', 'Ni Ulises está a la altura de tu epopeya', 'Don Quijote estaría orgulloso de tu aporte al noble arte de las historias de caballería', '¿A quién no le gusta viajar? Nos vamos a visitar otro planeta en este viaje intergaláctico', '¿Has soñado con viajes en el tiempo? Quién no…', '¿Estás preparado? Te vas a embarcar en un camino del héroe', 'Los escritores a veces parece que no saben hacerlo, yo que sé… mira, tú usa frases simples porque no puedes usar yuxtaposiciones ni subordinadas ni coordinadas.', '¡Te has librado! Eres libre de restricciones', 'Perdona, pero no me equivoqué al decir que tenías que escribir una antanaclasis', 'Este aire suena como una sinestesia, ¿no os parece?', 'No es dislexia, es un sinécdoque, ¡que no te enteras!', '¡Te has librado! Eres libre de restricciones', '¡No corras tanto! No puedes escribir más de 50 palabras', '¡No corras tanto! No puedes escribir más de 100 palabras', '¡No corras tanto! No puedes escribir más de 150 palabras', 'Tic-Tac Solo tienes 10 minutos para escribir ¡Rápido!', 'Y dije… que tu texto sea un diálogo', '¿No es verdad, ángel de amor, que en verso se escribe mejor?', 'Tiene que parecer un ensayo, no serlo, porque de esto sé que no tienes ni idea', 'A ver, no te alarmes, pero debes hacer una metáfora con lo que tengas', '¿Cuántas líneas tiene ese papel? Bueno, pues como mucho, puedes llenar 20 líneas', '¿Cuántas líneas tiene ese papel? Bueno, pues como mucho, puedes llenar 30 líneas', '¿Cuántas líneas tiene ese papel? Bueno, pues como mucho, puedes llenar 40 líneas', 'La prosa ha muerto, escríbeme un poema', 'Esta es difícil. Tu protagonista es ahora el antagonista… debe ser una tragedia, porque triunfa frente al bien', 'Esto es como cuando tienes que hacer un símil…', 'Tu protagonista se convierte en un lema del diccionario, ahora tienes que definirlo sin nombrarlo en ningún momento', 'Me apetece escuchar esa canción, sí, ya sabes… la que acabas de escribir', 'Los mitos griegos molan mucho, haz que el tuyo pueda colar por uno.', 'Encuentras la hoja de una novela durante un paseo matutino, ¿qué tiene escrito? ¿Podrías trascribirlo para mi?', 'Sepa vuesa merced que vuestras palabras suenan tan cercanas para alguien de mi uso, gracias por escribir unas líneas en castellano antiguo', 'Edgar Allan Poe no existe, ¿quién va a decirnos ahora "nunca más"?', 'Ni el señor gray está a la altura de tu perversión, haz que se corra (la tinta, la tinta)', 'Esto es un tema serio, te lo ha pedido un catedrático para la clase que tiene mañana.', 'Con la venia de su señoría, esa ley que usted cita y describe todavía no la he encontrado en el Código Civil.', 'A Spielberg le ha encantado tu idea, pero lo que has escrito solo da para un corto.', 'Más te vale que tu historia tenga una moraleja']} ##---------------------- Funciones def idea(): '''Genera una frase aleatoria que podrás utilizar como la idea principal del relato. El programa no utiliza ninguna lógica ni coherencia para la selección de las columnas, por lo que puedes enfrentarte a ideas bastante incoherentes; lo que puede resultar en un ejercicio bastante estimulante para la imaginación''' aleatorios = np.random.randint(len(frase['artículo']), size=3) if frase['artículo'][aleatorios[0]] == 'El': return ' '.join([frase['artículo'][aleatorios[0]], frase['sujeto'][aleatorios[0]], frase['adjetivo masculino'][aleatorios[1]], frase['acciones'][aleatorios[2]]]) else: return ' '.join([frase['artículo'][aleatorios[0]], frase['sujeto'][aleatorios[0]], frase['adjetivo femenino'][aleatorios[1]], frase['acciones'][aleatorios[2]]]) def palabras(): '''Genera un listado de palabras aleatorio en base a adjetivos que debes utilizar en el desarrollo del texto; estas palabras pueden aparecer en todas sus variantes de género y número.''' palabras = [] for n in range(int(np.random.randint(1, high=11, size=1))): palabras.append(frase['adjetivo masculino'][int(np.random.randint(len(frase['artículo']), size=1))]) return set(palabras) def reto(): '''Lanza un reto aleatorio de los que existen dentro de la lista, para hacer más complicado (o facilitar a veces) la ejecución del relato.''' return retos['Retos'][int(np.random.randint(len(retos['Retos']), size=1))] def dice(): '''¡Devuelve la respuesta que ha generado Gilbert!''' return {'idea': idea(), 'palabras': palabras(), 'reto': reto()} def juego(nivel = ''): '''Elige el nivel de dificultad que tendrá la tarea de Gilbert: fácil, normal o difícil.''' while nivel not in ['fácil', 'normal', 'difícil']: nivel = input('Elige el nivel de dificultad: fácil, normal o difícil: ').lower() partida = dice() if nivel == 'fácil': return idea() elif nivel == 'normal': return idea(), ', '.join(palabras()) elif nivel == 'difícil': return idea(), ', '.join(palabras()), reto() else: return 'Parece que ha ocurrido algo inesperado.' ##---------------------- Objetos externos with open('reglas.md', "r") as texto: reglas = texto.read() with open('sobre_proyecto.md', "r") as texto: sobre_proyecto = texto.read() with open('desarrollo.md', "r") as texto: desarrollado = texto.read() ##---------------------- Aplicación Streamlit ##--- Textos st.title('Gilbert.dice') st.header('Generador de frases aleatorias') st.markdown('### Podrás utilizarlas para inspirarte, trabajar la imaginación y perder el miedo a la página en blanco.') ##--- Menú de la izquierda st.sidebar.title("Acepta el reto y pincha en comenzar") st.sidebar.write('Elige la dificultad y enfréntate a la página en blanco.') fichero = st.sidebar.selectbox("Selecciona la dificultad:",('fácil', 'normal', 'difícil')) #-- Botones comenzar = st.sidebar.button('Generar') saber_mas = st.sidebar.button('Reglas del juego') proyecto = st.sidebar.button('Detalles del proyecto') desarrollo = st.sidebar.button('Desarrollo de Gilbert') ##--- Rutina del programa if comenzar: gilbert = juego(fichero) if fichero == 'fácil': st.markdown('La idea para tu próximo relato es:') st.markdown('**' + gilbert + '**\n') elif fichero == 'normal': st.markdown('La idea para tu próximo relato es:') st.markdown('**' + gilbert[0] + '**\n') st.markdown('El texto debe incluir estas palabras:') st.markdown('**' + gilbert[1] + '**\n') else: st.markdown('La idea para tu próximo relato es:') st.markdown('**' + gilbert[0] + '**\n') st.markdown('El texto debe incluir estas palabras:') st.markdown('**' + gilbert[1] + '**\n') st.markdown('Además, debes tratar de cumplir con el siguiente reto:') st.markdown('**' + gilbert[2] + '**\n') if saber_mas: st.markdown(reglas) if proyecto: st.markdown(sobre_proyecto) if desarrollo: st.markdown(desarrollado) ##--- Pie del menú de la izquierda st.sidebar.markdown('Un proyecto personal de [**Erebyel** (María Reyes Rocío Pérez)](http://www.erebyel.es).')
439.954545
39,817
0.638351
it as st import numpy as np , 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'La', 'La', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'El', 'La', 'El', 'La', 'El', 'El', 'El', 'La', 'El', 'La', 'La', 'El', 'La', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'La', 'La', 'El', 'La', 'El', 'La', 'La', 'El', 'El', 'El', 'La', 'La', 'La', 'La', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'El', 'La', 'El', 'El', 'La', 'El', 'La', 'La', 'La', 'El', 'El'], 'sujeto': ['acantilado', 'ácaro', 'acertijo', 'adivinanza', 'adorno', 'aeronave', 'afluente', 'aguacate', 'aguja', 'alba', 'alegría', 'alféizar', 'alondra', 'amada', 'amanecer', 'amante', 'amistad', 'amor', 'anciana', 'andén', 'ángel', 'anillo', 'ansiedad', 'aposento', 'árbol', 'arco', 'armadura', 'arpía', 'arquitecto', 'arrebol', 'arroyo', 'artefacto mágico', 'asteroide', 'astronauta', 'atún', 'aurora', 'ausencia', 'avena', 'aventura', 'avión', 'azafrán', 'azúcar', 'baile de disfraces', 'balcón', 'baldosa', 'ballena', 'balrog', 'balsa', 'banco', 'bandido', 'bar', 'barca', 'barco pirata', 'belfo', 'beso', 'besugo', 'biblioteca', 'bicicleta', 'bigote', 'bikini', 'billar', 'bisonte', 'bizcocho borracho', 'boca', 'bocadillo', 'bogavante', 'bohemia', 'bolo', 'bombero', 'bosque', 'bota', 'botella', 'botón', 'braga', 'brisa', 'bronceador', 'bruja', 'brújula', 'buitre', 'burdégano', 'caballero', 'caballito de mar', 'caballo', 'cabaña', 'cadena', 'café', 'caldero', 'camarote', 'camino', 'campo de batalla', 'campo de torneos', 'cancerbero', 'canoa', 'capitán', 'carta', 'casa solariega', 'cascada', 'castillo', 'catacumba', 'catarro', 'cementerio', 'centauro', 'cerradura', 'chimenea', 'chocolate', 'cicatriz', 'cíclope', 'cielo', 'ciénaga', 'cisne', 'ciudad', 'claridad', 'cobertizo', 'cocina', 'cocinera', 'cofre', 'colchón', 'colibrí', 'colina', 'colonia', 'cometa', 'comida', 'compasión', 'concha', 'concierto', 'constelación', 'copo de nieve', 'cordón', 'corona', 'corpúsculo', 'creatividad', 'crepúsculo', 'crucero', 'cuchara', 'cuchillo', 'cuervo', 'cueva', 'dado', 'dardo', 'dátil', 'delfín', 'demonio', 'depresión', 'desagüe', 'desenlace', 'desertor', 'desfiladero', 'desierto', 'destino', 'devaneo', 'día', 'dibujo', 'dinastía', 'diodo', 'dios', 'dique', 'dodo', 'dolor', 'dragón', 'dragón de komodo', 'dríada', 'droga', 'duende', 'duna', 'eclipse', 'edredón', 'ejército', 'elfo', 'elocuencia', 'enano', 'enemigo', 'epifanía', 'época', 'equidna', 'equilibrista', 'equitación', 'erizo de mar', 'escalera', 'escarabajo', 'escarcha', 'escasez', 'escoba', 'escorpión', 'escotilla', 'escritor', 'escudero', 'escudo', 'esfinge', 'esgrima', 'espacio', 'espacio exterior', 'espada', 'espaguetis', 'espejo', 'esperanza', 'esponja', 'esposa', 'establo', 'estación', 'estadio', 'estanque', 'estatua', 'estrella', 'estropajo', 'estuario', 'faisán', 'familia', 'farmacia', 'farol', 'felpudo', 'fénix', 'feudo', 'fiambre', 'fiebre', 'fiera', 'fiesta', 'fino ropaje', 'fiordo', 'flamenco', 'flauta', 'flirteo', 'flota', 'fluctuación', 'foca', 'foso', 'frambuesa', 'francotirador', 'fraternidad', 'fresa', 'fresco', 'frío', 'frontera', 'fruta', 'fruto seco', 'fuego', 'fuente', 'futuro', 'gabardina', 'galápago', 'galaxia', 'gallo', 'gasolina', 'gato', 'gaviota', 'geografía', 'gigante', 'ginebra', 'giro postal', 'globo', 'glotón', 'golondrina', 'gorgona', 'gorila', 'gorrión', 'granada', 'granizo', 'granja', 'grapadora', 'grasa', 'grosella', 'grulla', 'guardia', 'guardia', 'guateque', 'guepardo', 'guindilla', 'gula', 'gusano', 'haba', 'habitante', 'hacha', 'hada', 'hada madrina', 'halcón', 'hambre', 'hamburguesa', 'hechizo', 'hélice', 'helicóptero', 'heraldo', 'herboristería', 'heredero', 'herida', 'hermana', 'hermanastra', 'hermano', 'herramienta', 'hidra', 'hiena', 'hierro forjado', 'hígado', 'higiene', 'hipocampo', 'hipogrifo', 'hipopótamo', 'hobbit', 'hogar', 'hormiga', 'hormigonera', 'horno microondas', 'hortaliza', 'huelga', 'huérfano', 'hueso', 'humedad', 'huracán', 'hurón', 'idilio', 'iglesia', 'iguana', 'imán', 'impermeable', 'impresionismo', 'incandescencia', 'infraestructura', 'insecto', 'instituto', 'incendio', 'interespacio', 'internado', 'interruptor', 'intimidad', 'invernadero', 'invierno', 'inyección', 'iridiscencia', 'isla', 'jabón', 'jaguar', 'jamón', 'jardín', 'jarra', 'jaula', 'jazz', 'jengibre', 'jerbo', 'jilguero', 'jinete', 'joya', 'judo', 'jungla', 'justa', 'justicia', 'kiwi', 'ladrón', 'lagartija', 'lago', 'lanza', 'látigo', 'laurel', 'lava', 'lechuga', 'lechuza', 'lenteja', 'leñador', 'león', 'leopardo', 'leotardo', 'leprechaun', 'lesión', 'libélula', 'libro', 'licor', 'ligue', 'diferencia', 'limón', 'linaje', 'lince', 'litera', 'literatura', 'llave', 'lluvia', 'lobo', 'locomotora', 'lombriz de tierra', 'loro', 'lotería', 'lubina', 'lugar bajo el agua', 'lugar bajo tierra', 'luminiscencia', 'luna', 'luz', 'madrastra', 'magnetófono', 'mago', 'mamut', 'manantial', 'manifestación', 'manta', 'mantícora', 'manzana', 'mapa', 'mar', 'mar', 'maratón', 'marinero', 'marisco', 'marmota', 'mausoleo', 'mazapán', 'mazmorra', 'mazorca', 'meandro', 'medianoche', 'meiga', 'melancolía', 'mendigo', 'mermelada de tomate', 'mina', 'minotauro', 'mirlo', 'molécula', 'molinillo', 'monasterio', 'monstruo', 'montaña', 'montaña rusa', 'monte', 'mosca', 'muérgano', 'mujeriego', 'muñeca', 'murciégalo', 'muro', 'musa', 'música', 'nabo', 'naranja', 'nariz', 'narval', 'nata', 'natación', 'naufragio', 'nave', 'náyade', 'nécora', 'nectarina', 'nevera', 'nieve', 'ninfa', 'niñera', 'niño', 'níspero', 'noche', 'noria', 'nostalgia', 'novelista', 'noviazgo', 'nube', 'nudillo', 'nutria', 'nutrición', 'nylon', 'ñandú', 'ñu', 'oasis', 'obertura', 'obrero', 'oca', 'océano', 'odio', 'oficial', 'ogro', 'ojo', 'oleaje', 'olla de presión', 'olvido', 'ombligo', 'ondina', 'orate', 'orco', 'ordinario', 'orégano', 'oreja', 'orfanato', 'ornitorrinco', 'oro', 'orquesta', 'ósculo', 'oso hormiguero', 'ostra', 'otoño', 'oveja', 'pabellón', 'pájaro', 'palacio', 'pantano', 'pantera', 'parchís', 'pasión', 'pastel', 'patinaje', 'payaso', 'pegaso', 'peluca', 'perfume', 'perro', 'pescador', 'petirrojo', 'pez', 'pezuña', 'piedra', 'pintura', 'piña', 'pipa', 'pirata', 'pistacho', 'pistola', 'pitonisa', 'pizarra', 'planeta', 'plano', 'plástico', 'plata', 'playa', 'pluma', 'poción', 'político', 'polizón', 'posada', 'pozo', 'pradera', 'precipicio', 'prenda de amor', 'primavera', 'princesa', 'príncipe', 'promesa', 'pueblo', 'puente', 'puerta', 'puerto', 'pulga', 'quebrantahuesos', 'quimera', 'química', 'quiosco', 'radio', 'rana', 'rascacielos', 'rastrillo', 'rata', 'ratón', 'raya', 'realismo', 'receta', 'recogedor', 'rectángulo', 'recuerdo', 'refresco', 'regadera', 'regalo', 'regreso', 'reina', 'reino', 'relámpago', 'relieve', 'religión', 'reliquia', 'remo', 'remolacha', 'rémora', 'rencor', 'reno', 'reportaje', 'reproducción', 'resiliencia', 'retraso', 'retrato', 'reunión', 'rey', 'rinoceronte', 'río', 'rocío', 'rodilla', 'romanticismo', 'ropa', 'ruina', 'ruiseñor', 'sábana', 'sacaclavos', 'sacerdote', 'sacerdotisa', 'sal', 'salchichón', 'salida', 'salmuera', 'salón de baile', 'salón del trono', 'saltamontes', 'salud', 'sangre', 'sanguijuela', 'santuario', 'sapo', 'sartén', 'satélite', 'semáforo', 'sensualidad', 'sentimiento', 'sequía', 'serendipia', 'sereno', 'serpiente', 'serpiente marina', 'servilletero', 'sexo', 'sílfide', 'sinfonía', 'sirena', 'sistema solar', 'sol', 'soledad', 'sombrero', 'sonámbulo', 'suciedad', 'sueño', 'sujetador', 'taberna', 'tambor', 'tarántula', 'tarta de queso', 'taxi', 'tempestad', 'templo', 'tentación', 'tentempié', 'terciopelo', 'tesoro', 'tierra', 'tierra extranjera', 'tifón', 'timón', 'tiovivo', 'toalla', 'tobillo', 'tobogán', 'torre', 'tortilla', 'tortuga', 'trabajo duro', 'trampa', 'transatlántico', 'transeúnte', 'tranvía', 'trasgo', 'tren', 'trenza', 'trigo', 'tripulación', 'tritón', 'troll', 'trueno', 'tucán', 'tuerca', 'tulipán', 'tumba', 'ultramarinos', 'unicornio', 'uniforme', 'universidad', 'universo', 'uña', 'urraca', 'utensilio', 'uva', 'vaca', 'vagabundo', 'vagina', 'vagón', 'vainilla', 'vajilla', 'valle', 'vampiro', 'varano', 'vaso', 'velero', 'venado', 'vendaje', 'ventana', 'verdad', 'verdulería', 'vestuario', 'vía', 'viajero', 'víbora', 'vida', 'vidrio', 'viejo', 'viento', 'vinagrera', 'virtud', 'visita', 'vitalidad', 'vituperio', 'vodka', 'volcán', 'vuelo', 'whisky', 'wombat', 'wyvern', 'xilófono', 'yate', 'yegua', 'yogur', 'yunque', 'zanahoria', 'zapato', 'zarzamora', 'zarzuela', 'cebra', 'zorro', 'zueco'], 'adjetivo masculino': ['absurdo', 'ácido', 'admirable', 'adolescente', 'afectuoso', 'afortunado', 'alegre', 'altivo', 'amable', 'amargo', 'ambiguo', 'amistoso', 'andrajoso', 'angelical', 'anómalo', 'anónimo', 'ansioso', 'antiguo', 'apasionado', 'apático', 'argénteo', 'árido', 'arrejuntado', 'artesanal', 'áspero', 'astuto', 'atento', 'atómico', 'atractivo', 'atrevido', 'atroz', 'audaz', 'áurico', 'ausente', 'automático', 'bajo', 'bancario', 'barato', 'bárbaro', 'básico', 'basto', 'beato', 'belga', 'bélico', 'beligerante', 'bello', 'bíblico', 'bilingüe', 'biológico', 'blanco', 'blando', 'bonito', 'boreal', 'borracho', 'boscoso', 'breve', 'brillante', 'brusco', 'brutal', 'bueno', 'burgués', 'burlón', 'cálido', 'callejero', 'caprichoso', 'cariñoso', 'cascarrabias', 'casposo', 'cauto', 'célebre', 'celoso', 'cercano', 'cerúleo', 'ciego', 'cínico', 'clasista', 'cobarde', 'coherente', 'colosal', 'cómodo', 'compacto', 'compasivo', 'complejo', 'complicado', 'comprensivo', 'común', 'contradictorio', 'convencional', 'convincente', 'cordial', 'corpulento', 'cortante', 'cortesano', 'cósmico', 'creativo', 'criminal', 'crítico', 'crónico', 'cruel', 'cuántico', 'cuidadoso', 'culpable', 'curativo', 'curioso', 'curvo', 'débil', 'decidido', 'delgado', 'delicado', 'delicioso', 'delincuente', 'dependiente', 'deprimido', 'desagradable', 'desaliñado', 'desapasionado', 'desarmado', 'descomunal', 'desconfiado', 'descuidado', 'deseado', 'desfavorecido', 'deshonrado', 'desierto', 'despierto', 'dichoso', 'diferente', 'difícil', 'diminuto', 'dinámico', 'directo', 'discreto', 'disfrazado', 'disperso', 'distante', 'divertido', 'divino', 'dócil', 'doloroso', 'doméstico', 'dorado', 'dracónico', 'dramático', 'druídico', 'dulce', 'duro', 'ecológico', 'efímero', 'egoísta', 'electrónico', 'elegante', 'élfico', 'emocional', 'encantador', 'enérgico', 'enfadado', 'enfermo', 'engreído', 'enjuto', 'enterrado', 'entrometido', 'equilibrado', 'erótico', 'erróneo', 'esbelto', 'escandaloso', 'escéptico', 'espacial', 'espeso', 'espiritual', 'espontáneo', 'estéril', 'estimulante', 'estoico', 'estricto', 'eterno', 'ético', 'exagerado', 'excéntrico', 'excesivo', 'exclusivo', 'exigente', 'exitoso', 'exótico', 'explosivo', 'expresivo', 'exquisito', 'extraordinario', 'extrovertido', 'fácil', 'falto', 'familiar', 'famoso', 'fanático', 'fantástico', 'fascinante', 'fatal', 'fatuo', 'favorito', 'feliz', 'femenino', 'feo', 'fértil', 'fiable', 'ficticio', 'fiel', 'fijo', 'final', 'fino', 'firme', 'flaco', 'flexible', 'flojo', 'floral', 'fluvial', 'formal', 'frágil', 'franco', 'frecuente', 'fresco', 'frío', 'fuerte', 'fugaz', 'fúnebre', 'funesto', 'furioso', 'fútil', 'general', 'genérico', 'generoso', 'genético', 'genial', 'geográfico', 'geológico', 'geométrico', 'gigante', 'gitano', 'glacial', 'global', 'glorioso', 'gordo', 'gótico', 'gracioso', 'gráfico', 'grande', 'grandilocuente', 'grandioso', 'grato', 'gratuito', 'grave', 'griego', 'gris', 'grosero', 'grotesco', 'grueso', 'gruñón', 'guapo', 'hábil', 'habitual', 'hablador', 'hambriento', 'harto', 'henchido', 'herbáceo', 'heredado', 'herido', 'hermoso', 'heroico', 'heterogéneo', 'hidráulico', 'hipócrita', 'hipotético', 'histérico', 'histórico', 'holgazán', 'homogéneo', 'homosexual', 'hondo', 'horizontal', 'horrible', 'hostil', 'humanitario', 'humano', 'húmedo', 'humilde', 'huraño', 'imprudente', 'incandescente', 'incognoscible', 'inconmensurable', 'inconsciente', 'joven', 'judío', 'juguetón', 'juramentado', 'jurídico', 'justo', 'juvenil', 'kinestésico', 'laboral', 'lamentable', 'largo', 'latente', 'lateral', 'legal', 'legítimo', 'lejano', 'lento', 'lésbico', 'leve', 'levítico', 'liberal', 'libre', 'lícito', 'ligero', 'limpio', 'lindo', 'lingüístico', 'líquido', 'listo', 'litúrgico', 'llamativo', 'lleno', 'llorón', 'lluvioso', 'local', 'loco', 'lógico', 'lúcido', 'lujoso', 'luminiscente', 'luminoso', 'lunático', 'maduro', 'mágico', 'magnífico', 'maldito', 'maleducado', 'malhumorado', 'malicioso', 'maltratado', 'maravilloso', 'marciano', 'marginal', 'marino', 'masculino', 'material', 'maternal', 'medieval', 'melancólico', 'mensurable', 'menudo', 'meticuloso', 'mezquino', 'miedoso', 'minúsculo', 'miserable', 'misterioso', 'mítico', 'moderado', 'moderno', 'modesto', 'molesto', 'monumental', 'mordaz', 'mortal', 'móvil', 'mudo', 'musical', 'mutuo', 'naciente', 'nacional', 'nacionalista', 'narcisista', 'narrativo', 'natural', 'nazi', 'negativo', 'negro', 'nervioso', 'neutro', 'noble', 'nocivo', 'nocturno', 'nónuplo', 'normal', 'normativo', 'notable', 'notarial', 'notorio', 'novel', 'novelero', 'nuclear', 'nuevo', 'nulo', 'numérico', 'numeroso', 'nutritivo', 'objetivo', 'obligatorio', 'observable', 'obvio', 'occidental', 'oceánico', 'octavo', 'óctuplo', 'ocultación', 'oculto', 'odioso', 'ofensivo', 'oficial', 'ontológico', 'opaco', 'operativo', 'oportuno', 'óptico', 'oral', 'orbitado', 'ordinario', 'orgánico', 'organizativo', 'orgulloso', 'oriental', 'original', 'originario', 'ortográfico', 'oscuro', 'pálido', 'parturiento', 'pasional', 'pasivo', 'pasteloso', 'patético', 'pedregoso', 'peligroso', 'penetrante', 'penoso', 'pequeño', 'perenne', 'perezoso', 'perfecto', 'perpetuo', 'perseverante', 'perverso', 'pícaro', 'pintoresco', 'placentero', 'pobre', 'poderoso', 'poético', 'polémico', 'positivo', 'precoz', 'preponderante', 'prestigioso', 'pretencioso', 'previsible', 'prodigioso', 'profético', 'profundo', 'progresista', 'provocador', 'prudente', 'puntual', 'quieto', 'químico', 'quinto', 'quirúrgico', 'quisquilloso', 'racional', 'racista', 'radiante', 'radical', 'rápido', 'raro', 'razonable', 'reacio', 'realista', 'rebelde', 'receloso', 'reciente', 'recto', 'referente', 'relativo', 'reluciente', 'renovador', 'repentino', 'reservado', 'resistente', 'respetable', 'responsable', 'revolucionario', 'rico', 'ridículo', 'rígido', 'riguroso', 'rimbombante', 'robado', 'rocoso', 'románico', 'romano', 'romántico', 'roto', 'rotundo', 'rubio', 'ruidoso', 'rutinario', 'sabio', 'sagaz', 'sagrado', 'salado', 'salvaje', 'sangriento', 'sano', 'santificado', 'secreto', 'seguro', 'selenita', 'sencillo', 'sensato', 'sensible', 'sensorial', 'sentimental', 'sereno', 'serio', 'servicial', 'severo', 'sexual', 'silencioso', 'similar', 'simpático', 'simulado', 'sincero', 'siniestro', 'sintético', 'sobrenatural', 'sofista', 'sofisticado', 'soleado', 'solemne', 'solidario', 'solitario', 'sombrío', 'sonriente', 'sospechoso', 'suave', 'sucio', 'suculento', 'sudoroso', 'sueño', 'susceptible', 'sutil', 'tacaño', 'taciturno', 'tajante', 'talentoso', 'tardío', 'temeroso', 'temible', 'temporal', 'tenaz', 'tenso', 'teórico', 'terapéutico', 'térmico', 'terrestre', 'terrible', 'territorial', 'terrorista', 'tibio', 'tierno', 'tieso', 'tímido', 'típico', 'tonto', 'torpe', 'tóxico', 'trabajador', 'tradicional', 'trágico', 'traicionado', 'tranquilo', 'transitorio', 'transparente', 'travieso', 'tripulado', 'triste', 'trivial', 'turbio', 'ulterior', 'último', 'unánime', 'único', 'uniforme', 'unitario', 'universal', 'universitario', 'urbano', 'urgente', 'usual', 'útil', 'utilitario', 'utilizable', 'vacío', 'vagamundo', 'vago', 'valeroso', 'válido', 'valiente', 'valioso', 'vano', 'variable', 'variado', 'vasto', 'vegetal', 'vegetativo', 'veloz', 'envenenado', 'verbal', 'verde', 'verosímil', 'vertical', 'vespertino', 'veterano', 'viable', 'victorioso', 'viejo', 'vigente', 'violento', 'virgen', 'visible', 'vital', 'vitoreado', 'vivaz', 'viviente', 'voluntario', 'vulgar', 'yodado', 'zafio', 'zafíreo', 'zarrapastroso', 'zopenco', 'enquistado', 'conquistado', 'atormentado', 'radiactivo', 'machista', 'fulminante', 'plurilingüe', 'equivalente', 'equidistante', 'paralelo', 'ignorante', 'destrozado', 'acuartelado', 'evolucionado', 'añejo', 'dañado', 'anglicano', 'norteño', 'sureño', 'sustentado', 'español', 'calzado', 'embustero', 'amarillo', 'azul', 'rojo', 'rosa', 'arrinconado', 'oloroso', 'omnipresente', 'omnisciente', 'todopoderoso', 'acomplejado', 'castellanizado', 'debilitado', 'diferenciado', 'sepulcral', 'terraplanista', 'homeostático', 'onomatopéyico', 'gritón', 'sustancioso', 'lácteo', 'cósmico', 'bíblico', 'apestoso', 'despojado', 'rubicundo', 'encuestado', 'tórrido', 'mentiroso', 'estúpido', 'escrupuloso', 'contundente', 'cobrizo', 'escandaloso', 'lozano', 'pechugón', 'níveo', 'blanco', 'esculpido', 'negro', 'racista', 'robótico', 'inteligente', 'artificial', 'artificioso', 'adecuado', 'cómico', 'tramado', 'tramposo', 'lúcido'], 'adjetivo femenino': ['absurda', 'ácida', 'admirable', 'adolescente', 'afectuosa', 'afortunada', 'alegre', 'altiva', 'amable', 'amarga', 'ambigua', 'amistosa', 'andrajosa', 'angelical', 'anómala', 'anónima', 'ansiosa', 'antigua', 'apasionada', 'apática', 'argéntea', 'árida', 'arrejuntada', 'artesanal', 'áspera', 'astuta', 'atenta', 'atómica', 'atractiva', 'atrevida', 'atroz', 'audaz', 'áurica', 'ausente', 'automática', 'baja', 'bancaria', 'barata', 'bárbara', 'básica', 'basta', 'beata', 'belga', 'bélica', 'beligerante', 'bella', 'bíblica', 'bilingüe', 'biológica', 'blanca', 'blanda', 'bonita', 'boreal', 'borracha', 'boscosa', 'breve', 'brillante', 'brusca', 'brutal', 'buena', 'burguesa', 'burlona', 'cálida', 'callejera', 'caprichosa', 'cariñosa', 'cascarrabias', 'casposa', 'cauta', 'célebre', 'celosa', 'cercana', 'cerúlea', 'ciega', 'cínica', 'clasista', 'cobarde', 'coherente', 'colosal', 'cómoda', 'compacta', 'compasiva', 'compleja', 'complicada', 'comprensiva', 'común', 'contradictoria', 'convencional', 'convincente', 'cordial', 'corpulenta', 'cortante', 'cortesana', 'cósmica', 'creativa', 'criminal', 'crítica', 'crónica', 'cruel', 'cuántica', 'cuidadosa', 'culpable', 'curativa', 'curiosa', 'curva', 'débil', 'decidida', 'delgada', 'delicada', 'deliciosa', 'delincuente', 'dependiente', 'deprimida', 'desagradable', 'desaliñada', 'desapasionada', 'desarmada', 'descomunal', 'desconfiada', 'descuidada', 'deseada', 'desfavorecida', 'deshonrada', 'desierta', 'despierta', 'dichosa', 'diferente', 'difícil', 'diminuta', 'dinámica', 'directa', 'discreta', 'disfrazada', 'dispersa', 'distante', 'divertida', 'divina', 'dócil', 'dolorosa', 'doméstica', 'dorada', 'dracónica', 'dramática', 'druídica', 'dulce', 'dura', 'ecológica', 'efímera', 'egoísta', 'electrónica', 'elegante', 'élfica', 'emocional', 'encantadora', 'enérgica', 'enfadada', 'enferma', 'engreída', 'enjuta', 'enterrada', 'entrometida', 'equilibrada', 'erótica', 'errónea', 'esbelta', 'escandalosa', 'escéptica', 'espacial', 'espesa', 'espiritual', 'espontánea', 'estéril', 'estimulante', 'estoica', 'estricta', 'eterna', 'ética', 'exagerada', 'excéntrica', 'excesiva', 'exclusiva', 'exigente', 'exitosa', 'exótica', 'explosiva', 'expresiva', 'exquisita', 'extraordinaria', 'extrovertida', 'fácil', 'falta', 'familiar', 'famosa', 'fanática', 'fantástica', 'fascinante', 'fatal', 'fatua', 'favorita', 'feliz', 'femenina', 'fea', 'fértil', 'fiable', 'ficticia', 'fiel', 'fija', 'final', 'fina', 'firme', 'flaca', 'flexible', 'floja', 'floral', 'fluvial', 'formal', 'frágil', 'franca', 'frecuente', 'fresca', 'fría', 'fuerte', 'fugaz', 'fúnebre', 'funesta', 'furiosa', 'fútil', 'general', 'genérica', 'generosa', 'genética', 'genial', 'geográfica', 'geológica', 'geométrica', 'gigante', 'gitana', 'glacial', 'global', 'gloriosa', 'gorda', 'gótica', 'graciosa', 'gráfica', 'grande', 'grandilocuente', 'grandiosa', 'grata', 'gratuita', 'grave', 'griega', 'gris', 'grosera', 'grotesca', 'gruesa', 'gruñona', 'guapa', 'hábil', 'habitual', 'habladora', 'hambrienta', 'harta', 'henchida', 'herbácea', 'heredada', 'herida', 'hermosa', 'heroica', 'heterogénea', 'hidráulica', 'hipócrita', 'hipotética', 'histérica', 'histórica', 'holgazana', 'homogénea', 'homosexual', 'honda', 'horizontal', 'horrible', 'hostil', 'humanitaria', 'humana', 'húmeda', 'humilde', 'huraña', 'imprudente', 'incandescente', 'incognoscible', 'inconmensurable', 'inconsciente', 'joven', 'judía', 'juguetona', 'juramentada', 'jurídica', 'justa', 'juvenil', 'kinestésica', 'laboral', 'lamentable', 'larga', 'latente', 'lateral', 'legal', 'legítima', 'lejana', 'lenta', 'lésbica', 'leve', 'levítica', 'liberal', 'libre', 'lícita', 'ligera', 'limpia', 'linda', 'lingüística', 'líquida', 'lista', 'litúrgica', 'llamativa', 'llena', 'llorona', 'lluviosa', 'local', 'loca', 'lógica', 'lúcida', 'lujosa', 'luminiscente', 'luminosa', 'lunática', 'madura', 'mágica', 'magnífica', 'maldita', 'maleducada', 'malhumorada', 'maliciosa', 'maltratada', 'maravillosa', 'marciana', 'marginal', 'marina', 'masculina', 'material', 'maternal', 'medieval', 'melancólica', 'mensurable', 'menuda', 'meticulosa', 'mezquina', 'miedosa', 'minúscula', 'miserable', 'misteriosa', 'mítica', 'moderada', 'moderna', 'modesta', 'molesta', 'monumental', 'mordaz', 'mortal', 'móvil', 'muda', 'musical', 'mutua', 'naciente', 'nacional', 'nacionalista', 'narcisista', 'narrativa', 'natural', 'nazi', 'negativa', 'negra', 'nerviosa', 'neutra', 'noble', 'nociva', 'nocturna', 'nónupla', 'normal', 'normativa', 'notable', 'notarial', 'notoria', 'novel', 'novelera', 'nuclear', 'nueva', 'nula', 'numérica', 'numerosa', 'nutritiva', 'objetiva', 'obligatoria', 'observable', 'obvia', 'occidental', 'oceánica', 'octava', 'óctupla', 'ocultación', 'oculta', 'odiosa', 'ofensiva', 'oficial', 'ontológica', 'opaca', 'operativa', 'oportuna', 'óptica', 'oral', 'orbitada', 'ordinaria', 'orgánica', 'organizativa', 'orgullosa', 'oriental', 'original', 'originaria', 'ortográfica', 'oscura', 'pálida', 'parturienta', 'pasional', 'pasiva', 'pastelosa', 'patética', 'pedregosa', 'peligrosa', 'penetrante', 'penosa', 'pequeña', 'perenne', 'perezosa', 'perfecta', 'perpetua', 'perseverante', 'perversa', 'pícara', 'pintoresca', 'placentera', 'pobre', 'poderosa', 'poética', 'polémica', 'positiva', 'precoz', 'preponderante', 'prestigiosa', 'pretenciosa', 'previsible', 'prodigiosa', 'profética', 'profunda', 'progresista', 'provocadora', 'prudente', 'puntual', 'quieta', 'química', 'quinta', 'quirúrgica', 'quisquillosa', 'racional', 'racista', 'radiante', 'radical', 'rápida', 'rara', 'razonable', 'reacia', 'realista', 'rebelde', 'recelosa', 'reciente', 'recta', 'referente', 'relativa', 'reluciente', 'renovadora', 'repentina', 'reservada', 'resistente', 'respetable', 'responsable', 'revolucionaria', 'rica', 'ridícula', 'rígida', 'rigurosa', 'rimbombante', 'robada', 'rocosa', 'románica', 'romana', 'romántica', 'rota', 'rotunda', 'rubia', 'ruidosa', 'rutinaria', 'sabia', 'sagaz', 'sagrada', 'salada', 'salvaje', 'sangrienta', 'sana', 'santificada', 'secreta', 'segura', 'selenita', 'sencilla', 'sensata', 'sensible', 'sensorial', 'sentimental', 'serena', 'seria', 'servicial', 'severa', 'sexual', 'silenciosa', 'similar', 'simpática', 'simulada', 'sincera', 'siniestra', 'sintética', 'sobrenatural', 'sofista', 'sofisticada', 'soleada', 'solemne', 'solidaria', 'solitaria', 'sombría', 'sonriente', 'sospechosa', 'suave', 'sucia', 'suculenta', 'sudorosa', 'sueña', 'susceptible', 'sutil', 'tacaña', 'taciturna', 'tajante', 'talentosa', 'tardía', 'temerosa', 'temible', 'temporal', 'tenaz', 'tensa', 'teórica', 'terapéutica', 'térmica', 'terrestre', 'terrible', 'territorial', 'terrorista', 'tibia', 'tierna', 'tiesa', 'tímida', 'típica', 'tonta', 'torpe', 'tóxica', 'trabajador', 'tradicional', 'trágica', 'traicionada', 'tranquila', 'transitoria', 'transparente', 'traviesa', 'tripulada', 'triste', 'trivial', 'turbia', 'ulterior', 'última', 'unánime', 'única', 'uniforme', 'unitaria', 'universal', 'universitaria', 'urbana', 'urgente', 'usual', 'útil', 'utilitaria', 'utilizable', 'vacía', 'vagamunda', 'vaga', 'valerosa', 'válida', 'valiente', 'valiosa', 'vana', 'variable', 'variada', 'vasta', 'vegetal', 'vegetativa', 'veloz', 'envenenada', 'verbal', 'verde', 'verosímil', 'vertical', 'vespertina', 'veterana', 'viable', 'victoriosa', 'vieja', 'vigente', 'violenta', 'virgen', 'visible', 'vital', 'vitoreada', 'vivaz', 'viviente', 'voluntaria', 'vulgar', 'yodada', 'zafia', 'zafírea', 'zarrapastrosa', 'zopenca', 'enquistada', 'conquistada', 'atormentada', 'radiactiva', 'machista', 'fulminante', 'plurilingüe', 'equivalente', 'equidistante', 'paralela', 'ignorante', 'destrozada', 'acuartelada', 'evolucionada', 'añeja', 'dañada', 'anglicana', 'norteña', 'sureña', 'sustentada', 'española', 'calzada', 'embustera', 'amarilla', 'azul', 'roja', 'rosa', 'arrinconada', 'olorosa', 'omnipresente', 'omnisciente', 'todopoderosa', 'acomplejada', 'castellanizada', 'debilitado', 'diferenciada', 'sepulcral', 'terraplanista', 'homeostática', 'onomatopéyica', 'gritona', 'sustanciosa', 'láctea', 'cósmica', 'bíblica', 'apestosa', 'despojada', 'rubicunda', 'encuestada', 'tórrida', 'mentirosa', 'estúpida', 'escrupulosa', 'contundente', 'cobriza', 'escandalosa', 'lozana', 'pechugona', 'nívea', 'blanca', 'esculpida', 'negra', 'racista', 'robótica', 'inteligente', 'artificial', 'artificiosa', 'adecuada', 'cómica', 'tramada', 'tramposa', 'lúcida'], 'acciones': ['abofetea a alguien', 'aborrece algo', 'aborta', 'abrocha algo', 'acaba inquieto', 'acaricia a algo/alguien', 'acosa a alguien', 'adelgaza', 'adivina', 'adopta', 'afeita', 'agria', 'agujerea una superficie', 'ahoga a alguien', 'ahorra', 'aísla', 'ajusta', 'alinea', 'alumbra', 'ama', 'amarra', 'amenaza a alguien', 'amputa un miembro', 'amuebla un hogar', 'aniquila un enemigo', 'anticipa un evento', 'anuncia un evento', 'apesta', 'araña', 'arde', 'asedia', 'asesina a un amigo', 'asfixia a un enemigo', 'aterriza forzosamente', 'atormenta', 'atraviesa', 'aturde a alguien', 'auxilia a alguien', 'averigua una mentira', 'ayuna', 'babea', 'baila', 'balancea un objeto', 'balbucea con vergüenza', 'barajea', 'barre', 'batalla en una guerra', 'batea', 'bautiza algo', 'bebe', 'besa a alguien', 'blande un arma', 'blanquea algo', 'blanquea dinero', 'bloquea algo', 'boicotea una estrategia', 'bombardea un territorio', 'borda un tapiz', 'borra algo', 'brilla', 'brinca', 'brinda', 'bromea', 'brota', 'bucea', 'bulle', 'burla', 'busca', 'cabalga', 'cae', 'cambia', 'camufla', 'canta', 'captura', 'castra', 'celebra', 'cepilla', 'cercena', 'chilla', 'cobra vida', 'codicia', 'cojea', 'combate', 'come', 'compite', 'complica algo', 'concibe algo', 'condena a alguien', 'confronta', 'conquista', 'consagra', 'conserva', 'consigna', 'conspira', 'construye', 'contagia', 'copula con el enemigo', 'coquetea', 'corona', 'corre', 'corta', 'corteja a alguien', 'cosecha', 'cultiva', 'cumple una promesa', 'curte', 'custodia', 'danza', 'daña', 'deambula', 'debilita', 'decapita', 'declara', 'deforma', 'defrauda', 'deja pasar el tiempo', 'delata', 'demora', 'denuncia', 'derruye', 'desabrocha', 'desafía', 'desaparece', 'desayuna', 'descansa', 'descubre algo', 'desea', 'desembarca', 'desencanta a alguien', 'desentona', 'deshonra', 'desilusiona', 'desnuda a alguien', 'desobedece', 'desviste', 'devasta', 'dibuja', 'discute', 'disfruta', 'dispara', 'distorsiona', 'divorcia', 'duda', 'duerme', 'eclipsa', 'edifica', 'elige un blasón', 'elimina', 'emborracha', 'emigra', 'empalma', 'empeora', 'enamora', 'encadena', 'encanta', 'enciende', 'encuentra', 'endulza', 'enferma', 'engaña', 'engrasa', 'ensambla', 'entierra', 'entrevista', 'envejece', 'envenena', 'erradica', 'eructa', 'es derrotado', 'es tentado', 'es timado', 'es vapuleado', 'escoge', 'escupe', 'esmalta', 'esposa', 'está penando', 'estornuda', 'estrangula', 'estropea', 'excita', 'experimenta', 'extermina', 'extorsiona', 'extraña', 'fabrica', 'facilita', 'falla', 'falsea', 'fantasea', 'favorece a alguien', 'fermenta', 'festeja', 'fía', 'filma', 'filtra', 'finaliza', 'financia', 'fisgonea', 'flagela', 'flaquea', 'flirtea', 'florece', 'flota', 'fluctúa', 'forcejea', 'forja', 'forma', 'fracasa', 'fracciona', 'fractura', 'fragmenta', 'frecuenta', 'fríe', 'friega', 'fuerza', 'funciona', 'galantea', 'galopa', 'gana', 'garabatea', 'garantiza', 'gasta', 'genera', 'germina', 'gesticula', 'gime', 'gimotea', 'gira', 'glasea', 'glorifica', 'glosa', 'gobierna', 'golpea', 'gorjea', 'gorrea', 'gorronear', 'gotea', 'goza', 'graba', 'grada', 'gradúa', 'granula', 'grapa', 'gravita', 'grita', 'gruñe', 'guarda', 'guía', 'habilita', 'habita', 'habla', 'hace', 'hace amigos', 'hace enemigos', 'hace vibrar algo', 'hacina', 'halla una herramienta', 'halla una pista', 'hereda', 'hermana', 'hiberna', 'hidrata', 'hiela', 'hiere', 'hierra', 'hierve', 'hila', 'hilvana', 'hipa', 'hojear', 'honra', 'hornea', 'hospeda', 'huele', 'huelga', 'humea', 'humedece', 'humilla', 'hunde', 'huye', 'idolatra', 'ignora', 'ilumina', 'imagina', 'imitar', 'impide', 'impone', 'impregna', 'improvisa', 'impulsa una iniciativa', 'incapacita a alguien', 'incinera', 'incomoda', 'infiere algo', 'influye', 'infringe las normas', 'injuria a alguien', 'inocula un veneno', 'inspira', 'instaura algo novedoso', 'instruye al enemigo', 'insulta a alguien', 'intercambia información', 'interpreta', 'interroga a alguien', 'intimida a alguien', 'invade algo', 'investiga', 'invita', 'invoca algo/a alguien', 'jadea', 'jala', 'juega', 'junta algunas piezas', 'jura', 'juzga acertadamente', 'juzga erróneamente', 'lacera', 'lacra', 'ladra', 'lame una superficie', 'lanza algo', 'lastra', 'late', 'le afecta un cambio mágico', 'le gusta algo', 'legitima', 'levanta', 'libera algo', 'lidera un evento', 'lidia con algo inesperado', 'limita', 'limpia', 'lincha', 'lisia a alguien', 'lisonjea inapropiadamente', 'llama a alguien', 'llamea', 'llega', 'llena algo', 'lleva algo a algún sitio', 'llora', 'llueve', 'logra', 'luce algo', 'lucha', 'lustra algo', 'madura', 'malgasta', 'maltrata', 'manda', 'manipula', 'masculla', 'medita', 'medra', 'mendiga', 'merodea', 'mezcla', 'mide', 'miente', 'mima', 'mina', 'mira', 'moderniza', 'modifica', 'moja', 'muele', 'muerde algo/a alguien', 'muere', 'nace', 'nada', 'narra', 'naufraga', 'navega', 'necesita algo/a alguien', 'negocia', 'niega algo', 'nieva', 'nivela', 'nombra', 'nomina', 'nota', 'notifica', 'nubla', 'numera', 'nutre', 'obedece', 'obsequia', 'obtiene', 'obvia', 'ocasiona', 'oculta', 'ocupa', 'odia', 'ofende', 'oficia', 'ofrece', 'olvida', 'omite', 'ondea algo en alto', 'opera lejos', 'opina', 'oprime a alguien', 'opta por una opción', 'ordena', 'organiza', 'orienta', 'origina un conflicto', 'orilla una embarcación', 'ornamenta algo', 'orquesta', 'oscila', 'otorga', 'oxigena', 'oye', 'parodia', 'participa en una justa', 'pasea', 'patea', 'patrulla', 'pega algo/ a alguien', 'peina', 'perdona', 'peregrina', 'perjudica', 'permanece', 'persevera', 'persigue', 'pertenece', 'pierde algo/ a alguien', 'pilota', 'piratea', 'pisotea', 'plancha', 'planifica', 'predestina', 'predice', 'premia', 'priva', 'procrea', 'profana', 'progresa', 'prohíbe', 'promete', 'promueve', 'propulsa', 'protesta', 'provoca', 'puebla', 'quebranta', 'queda', 'queda hospitalizado', 'quiebra', 'quiere a alguien/algo', 'quita a alguien', 'raciona algo', 'rapta a alguien', 'rasura algo', 'razona', 'recauda', 'rechaza', 'recluta a alguien', 'recoge algo', 'recompensa a alguien', 'reconquista a alguien', 'reconstruye algo', 'recuerda algo', 'recupera algo', 'reduce algo', 'regresa', 'renuncia', 'replica algo', 'reprime a alguien', 'repudia a alguien', 'requisa algo', 'rescata', 'rescata a alguien', 'responde', 'resucita', 'resuelve algo', 'retiene ilegalmente a alguien', 'rige un pueblo', 'rima', 'roba', 'rompe un juramento', 'ruega', 'sabotea algo', 'sacrifica algo', 'salpica', 'salva a alguien', 'saquea algo', 'se aburre', 'se ahoga', 'se baña', 'se confunde de identidad', 'se equivoca', 'se fascina con algo', 'se habitúa a algo extraño', 'se habitúa a una nueva vida', 'se hace valer', 'se harta', 'se hiere', 'se infiltra', 'se irrita', 'se jubila', 'se junta con alguien', 'se justifica', 'se lamenta', 'se lastima', 'se le rompe el corazón', 'se libra', 'se magulla', 'se mancha', 'se maravilla', 'se marcha', 'se marchita', 'se marea', 'se mece', 'se molesta', 'se mosquea', 'se motiva', 'se muda', 'se obsesiona', 'se olvida', 'se opone a algo', 'se pierde', 'se posa', 'se queja', 'se quema', 'se recluye', 'se reconcilia', 'se retira', 'se reúne', 'se ríe a carcajadas', 'se rinde', 'se rompe', 'se separa', 'se tambalea', 'se traga algo', 'se tranquiliza', 'se trastorna', 'se turna con alguien', 'se voltea', 'secuestra a alguien', 'seduce a alguien', 'selecciona algo', 'sella un pacto', 'separa algo', 'sepulta algo', 'simplifica algo', 'sitia un lugar', 'soborna a alguien', 'sobrevive', 'socorre a alguien', 'soluciona', 'somete a alguien', 'sonríe', 'soporta algo', 'sorprende a alguien', 'sospecha de algo', 'subestima a otro', 'subestima al enemigo', 'suelda', 'suelta', 'sueña', 'sufre un flechazo inoportuno', 'sugiere una idea', 'sujeta algo', 'supervisa', 'suplanta', 'sustituye', 'sustrae', 'talla', 'tapia algo', 'tararea', 'tartamudea', 'templa un objeto', 'tiembla', 'tiende algo', 'tiñe algo', 'tira algo', 'tira de alguien', 'tolera', 'tontea con alguien', 'tornea un objeto', 'tortura a alguien', 'traduce', 'trafica', 'traiciona', 'trama', 'traspasa algo', 'traslada algo', 'traza', 'trepa', 'trilla algo', 'trincha algo', 'tripula una nave', 'tritura algo', 'tropieza', 'ubica un lugar', 'ubica un objeto', 'ultima algún detalle', 'ultraja', 'ulula', 'une', 'unifica', 'unta algo', 'usa algo', 'usurpa', 'utiliza a alguien', 'va a prisión', 'vadea un lugar', 'vaga por un lugar', 'valida alguna aptitud', 'valora algo', 'vaticina un evento', 've algo insólito', 'veda algo', 'vegeta', 'veja a alguien', 'vence a alguien', 'vende algo/a alguien', 'venera algo', 'venga a alguien querido', 'venga a un desconocido', 'ventila', 'verifica', 'viaja', 'vigila a alguien', 'vilipendia', 'viola', 'visita', 'vitorea', 'vive', 'vocea', 'vota a alguien equivocadamente', 'vuela', 'vuelca', 'vuelve al origen', 'yace', 'zanganea', 'zanja un asunto importante', 'zarandea', 'zigzaguea por un lugar', 'zumba', 'se constipa', 'se apuesta aglo irremplazable', 'confiesa una mezquindad', 'prospera a costa de otro', 'confía en la persona equivocada', 'se come algo tóxico', 'engorda demasiado', 'se camufla entre los habitantes', 'corre hacia un sueño', 'se mete en una caja', 'se despierta en otra época', 'viaja al centro de la tierra', 'se duerme en clase', 'cae sobre una tarta', 'soba un sujetador', 'espolborea veneno sobre alguien', 'canta una canción de cuna', 'apuesta con el enemigo', 'se enamora de su enemigo', 'busca un final feliz', 'comienza a hacerse preguntas', 'se hace derogar', 'se intoxica', 'irradia algo', 'se vuelve radiactivo', 'consigue un material extraño', 'es un embustero', 'mordisquea la comida ajena', 'contextualiza algo', 'aporta un significado al mundo', 'encuentra el significado del universo', 'se encuentra con un ente creador', 'agita unas maracas', 'consigue un don', 'aplana el universo', 'conquista el espacio', 'se enamora de un objeto', 'se desposa con un objeto', 'asesina accidentalmente a alguien', 'secunda una censura', 'se atraganta', 'descuida su aspecto', 'hiere a un amigo', 'hiere a un enemigo', 'cosifica a alguien', 'se siente atraido sexualmente', 'es sexualizado', 'pronuncia un discuros', 'extravía el objeto que lo iba a salvar', 'muere', 'muere de forma estúpida', 'fallece premeditadamente', 'se suicida para evitar a su enemigo', 'estudia', 'convence a un aristócrata', 'se depila', 'depila a alguien', 'escribe un diario', 'roba un objeto', 'se esconde con cobardía', 'se detiene en el camino', 'detiene a alguien', 'es detenido inoportunamente', 'casca nueces', 'rompe un objeto sagrado', 'es excomulgado', 'es cómplice de un asesinato', 'ayuda a su enemigo']}) retos = {'Retos': ['Yo no tengo muy claro que Ana tenga una ánfora, pero eso da igual, porque lo que sí sé es que tienes que hacer una anáfora', 'Alíviate o no te alivies, altérate o no te alteres, pero haz que tu texto sea aliterado', 'Qué paradójico sería que tu texto no tuviese una paradoja', 'Era como… la descripción que has hecho. Ex-ac-ta-men-te', 'Este reto es un alivio, te permite la elipsis de 1 palabra que te haya salido como obligatoria para tu texto. Elige sabiamente', 'Este reto es un alivio, te permite la elipsis de 2 palabras que te hayan salido como obligatorias para tu texto. Elige sabiamente', 'Este reto es un alivio, te permite la elipsis de 3 palabras que te hayan salido como obligatorias para tu texto. Elige sabiamente', 'Este reto es un alivio, te permite la elipsis de 4 palabras que te hayan salido como obligatorias para tu texto. Elige sabiamente', '¿Quién conoce el futuro? Bueno, pues tendrás que imaginártelo', 'Me da igual que tengas que incluir una lavadora, tu texto debe enmarcarse en la época clásica', 'Me importa poco que tu protagonista sea una impresora 3D, tus protagonistas están en la Edad Media', 'En una época donde existía la magia… tu texto estaría en su contexto correcto', 'Si no te ríes al leerlo, no molas porque no es comedia', 'Seguro que, gracias a tu emotiva oda, el protagonista de tu historia será recordado eternamente', 'Ni Ulises está a la altura de tu epopeya', 'Don Quijote estaría orgulloso de tu aporte al noble arte de las historias de caballería', '¿A quién no le gusta viajar? Nos vamos a visitar otro planeta en este viaje intergaláctico', '¿Has soñado con viajes en el tiempo? Quién no…', '¿Estás preparado? Te vas a embarcar en un camino del héroe', 'Los escritores a veces parece que no saben hacerlo, yo que sé… mira, tú usa frases simples porque no puedes usar yuxtaposiciones ni subordinadas ni coordinadas.', '¡Te has librado! Eres libre de restricciones', 'Perdona, pero no me equivoqué al decir que tenías que escribir una antanaclasis', 'Este aire suena como una sinestesia, ¿no os parece?', 'No es dislexia, es un sinécdoque, ¡que no te enteras!', '¡Te has librado! Eres libre de restricciones', '¡No corras tanto! No puedes escribir más de 50 palabras', '¡No corras tanto! No puedes escribir más de 100 palabras', '¡No corras tanto! No puedes escribir más de 150 palabras', 'Tic-Tac Solo tienes 10 minutos para escribir ¡Rápido!', 'Y dije… que tu texto sea un diálogo', '¿No es verdad, ángel de amor, que en verso se escribe mejor?', 'Tiene que parecer un ensayo, no serlo, porque de esto sé que no tienes ni idea', 'A ver, no te alarmes, pero debes hacer una metáfora con lo que tengas', '¿Cuántas líneas tiene ese papel? Bueno, pues como mucho, puedes llenar 20 líneas', '¿Cuántas líneas tiene ese papel? Bueno, pues como mucho, puedes llenar 30 líneas', '¿Cuántas líneas tiene ese papel? Bueno, pues como mucho, puedes llenar 40 líneas', 'La prosa ha muerto, escríbeme un poema', 'Esta es difícil. Tu protagonista es ahora el antagonista… debe ser una tragedia, porque triunfa frente al bien', 'Esto es como cuando tienes que hacer un símil…', 'Tu protagonista se convierte en un lema del diccionario, ahora tienes que definirlo sin nombrarlo en ningún momento', 'Me apetece escuchar esa canción, sí, ya sabes… la que acabas de escribir', 'Los mitos griegos molan mucho, haz que el tuyo pueda colar por uno.', 'Encuentras la hoja de una novela durante un paseo matutino, ¿qué tiene escrito? ¿Podrías trascribirlo para mi?', 'Sepa vuesa merced que vuestras palabras suenan tan cercanas para alguien de mi uso, gracias por escribir unas líneas en castellano antiguo', 'Edgar Allan Poe no existe, ¿quién va a decirnos ahora "nunca más"?', 'Ni el señor gray está a la altura de tu perversión, haz que se corra (la tinta, la tinta)', 'Esto es un tema serio, te lo ha pedido un catedrático para la clase que tiene mañana.', 'Con la venia de su señoría, esa ley que usted cita y describe todavía no la he encontrado en el Código Civil.', 'A Spielberg le ha encantado tu idea, pero lo que has escrito solo da para un corto.', 'Más te vale que tu historia tenga una moraleja']} random.randint(len(frase['artículo']), size=3) if frase['artículo'][aleatorios[0]] == 'El': return ' '.join([frase['artículo'][aleatorios[0]], frase['sujeto'][aleatorios[0]], frase['adjetivo masculino'][aleatorios[1]], frase['acciones'][aleatorios[2]]]) else: return ' '.join([frase['artículo'][aleatorios[0]], frase['sujeto'][aleatorios[0]], frase['adjetivo femenino'][aleatorios[1]], frase['acciones'][aleatorios[2]]]) def palabras(): palabras = [] for n in range(int(np.random.randint(1, high=11, size=1))): palabras.append(frase['adjetivo masculino'][int(np.random.randint(len(frase['artículo']), size=1))]) return set(palabras) def reto(): return retos['Retos'][int(np.random.randint(len(retos['Retos']), size=1))] def dice(): return {'idea': idea(), 'palabras': palabras(), 'reto': reto()} def juego(nivel = ''): while nivel not in ['fácil', 'normal', 'difícil']: nivel = input('Elige el nivel de dificultad: fácil, normal o difícil: ').lower() partida = dice() if nivel == 'fácil': return idea() elif nivel == 'normal': return idea(), ', '.join(palabras()) elif nivel == 'difícil': return idea(), ', '.join(palabras()), reto() else: return 'Parece que ha ocurrido algo inesperado.' reglas = texto.read() with open('sobre_proyecto.md', "r") as texto: sobre_proyecto = texto.read() with open('desarrollo.md', "r") as texto: desarrollado = texto.read() es aleatorias') st.markdown('### Podrás utilizarlas para inspirarte, trabajar la imaginación y perder el miedo a la página en blanco.') el reto y pincha en comenzar") st.sidebar.write('Elige la dificultad y enfréntate a la página en blanco.') fichero = st.sidebar.selectbox("Selecciona la dificultad:",('fácil', 'normal', 'difícil')) comenzar = st.sidebar.button('Generar') saber_mas = st.sidebar.button('Reglas del juego') proyecto = st.sidebar.button('Detalles del proyecto') desarrollo = st.sidebar.button('Desarrollo de Gilbert') t = juego(fichero) if fichero == 'fácil': st.markdown('La idea para tu próximo relato es:') st.markdown('**' + gilbert + '**\n') elif fichero == 'normal': st.markdown('La idea para tu próximo relato es:') st.markdown('**' + gilbert[0] + '**\n') st.markdown('El texto debe incluir estas palabras:') st.markdown('**' + gilbert[1] + '**\n') else: st.markdown('La idea para tu próximo relato es:') st.markdown('**' + gilbert[0] + '**\n') st.markdown('El texto debe incluir estas palabras:') st.markdown('**' + gilbert[1] + '**\n') st.markdown('Además, debes tratar de cumplir con el siguiente reto:') st.markdown('**' + gilbert[2] + '**\n') if saber_mas: st.markdown(reglas) if proyecto: st.markdown(sobre_proyecto) if desarrollo: st.markdown(desarrollado) personal de [**Erebyel** (María Reyes Rocío Pérez)](http://www.erebyel.es).')
true
true
f72d191576e71f07bf2745d08e2318b97ae476f0
52,444
py
Python
mne/viz/misc.py
GanshengT/mne-python
49253e74308137e14187561a204d784ea28f12a7
[ "BSD-3-Clause" ]
null
null
null
mne/viz/misc.py
GanshengT/mne-python
49253e74308137e14187561a204d784ea28f12a7
[ "BSD-3-Clause" ]
null
null
null
mne/viz/misc.py
GanshengT/mne-python
49253e74308137e14187561a204d784ea28f12a7
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """Functions to make simple plots with M/EEG data.""" # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis Engemann <denis.engemann@gmail.com> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # Cathy Nangini <cnangini@gmail.com> # Mainak Jas <mainak@neuro.hut.fi> # # License: Simplified BSD import base64 import copy from glob import glob from io import BytesIO from itertools import cycle import os.path as op import warnings from distutils.version import LooseVersion from collections import defaultdict import numpy as np from ..defaults import DEFAULTS from ..fixes import _get_img_fdata from ..rank import compute_rank from ..surface import read_surface from ..io.constants import FIFF from ..io.proj import make_projector from ..io.pick import (_DATA_CH_TYPES_SPLIT, pick_types, pick_info, pick_channels) from ..source_space import (read_source_spaces, SourceSpaces, _check_mri, _ensure_src) from ..transforms import invert_transform, apply_trans, _frame_to_str from ..utils import (logger, verbose, warn, _check_option, get_subjects_dir, _mask_to_onsets_offsets, _pl, _on_missing, fill_doc) from ..io.pick import _picks_by_type from ..filter import estimate_ringing_samples from .utils import (tight_layout, _get_color_list, _prepare_trellis, plt_show, _figure_agg) def _index_info_cov(info, cov, exclude): if exclude == 'bads': exclude = info['bads'] info = pick_info(info, pick_channels(info['ch_names'], cov['names'], exclude)) del exclude picks_list = \ _picks_by_type(info, meg_combined=False, ref_meg=False, exclude=()) picks_by_type = dict(picks_list) ch_names = [n for n in cov.ch_names if n in info['ch_names']] ch_idx = [cov.ch_names.index(n) for n in ch_names] info_ch_names = info['ch_names'] idx_by_type = defaultdict(list) for ch_type, sel in picks_by_type.items(): idx_by_type[ch_type] = [ch_names.index(info_ch_names[c]) for c in sel if info_ch_names[c] in ch_names] idx_names = [(idx_by_type[key], '%s covariance' % DEFAULTS['titles'][key], DEFAULTS['units'][key], DEFAULTS['scalings'][key], key) for key in _DATA_CH_TYPES_SPLIT if len(idx_by_type[key]) > 0] C = cov.data[ch_idx][:, ch_idx] return info, C, ch_names, idx_names @verbose def plot_cov(cov, info, exclude=(), colorbar=True, proj=False, show_svd=True, show=True, verbose=None): """Plot Covariance data. Parameters ---------- cov : instance of Covariance The covariance matrix. %(info_not_none)s exclude : list of str | str List of channels to exclude. If empty do not exclude any channel. If 'bads', exclude info['bads']. colorbar : bool Show colorbar or not. proj : bool Apply projections or not. show_svd : bool Plot also singular values of the noise covariance for each sensor type. We show square roots ie. standard deviations. show : bool Show figure if True. %(verbose)s Returns ------- fig_cov : instance of matplotlib.figure.Figure The covariance plot. fig_svd : instance of matplotlib.figure.Figure | None The SVD spectra plot of the covariance. See Also -------- mne.compute_rank Notes ----- For each channel type, the rank is estimated using :func:`mne.compute_rank`. .. versionchanged:: 0.19 Approximate ranks for each channel type are shown with red dashed lines. """ import matplotlib.pyplot as plt from matplotlib.colors import Normalize from scipy import linalg from ..cov import Covariance info, C, ch_names, idx_names = _index_info_cov(info, cov, exclude) del cov, exclude projs = [] if proj: projs = copy.deepcopy(info['projs']) # Activate the projection items for p in projs: p['active'] = True P, ncomp, _ = make_projector(projs, ch_names) if ncomp > 0: logger.info(' Created an SSP operator (subspace dimension' ' = %d)' % ncomp) C = np.dot(P, np.dot(C, P.T)) else: logger.info(' The projection vectors do not apply to these ' 'channels.') fig_cov, axes = plt.subplots(1, len(idx_names), squeeze=False, figsize=(3.8 * len(idx_names), 3.7)) for k, (idx, name, _, _, _) in enumerate(idx_names): vlim = np.max(np.abs(C[idx][:, idx])) im = axes[0, k].imshow(C[idx][:, idx], interpolation="nearest", norm=Normalize(vmin=-vlim, vmax=vlim), cmap='RdBu_r') axes[0, k].set(title=name) if colorbar: from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(axes[0, k]) cax = divider.append_axes("right", size="5.5%", pad=0.05) plt.colorbar(im, cax=cax, format='%.0e') fig_cov.subplots_adjust(0.04, 0.0, 0.98, 0.94, 0.2, 0.26) tight_layout(fig=fig_cov) fig_svd = None if show_svd: fig_svd, axes = plt.subplots(1, len(idx_names), squeeze=False, figsize=(3.8 * len(idx_names), 3.7)) for k, (idx, name, unit, scaling, key) in enumerate(idx_names): this_C = C[idx][:, idx] s = linalg.svd(this_C, compute_uv=False) this_C = Covariance(this_C, [info['ch_names'][ii] for ii in idx], [], [], 0) this_info = pick_info(info, idx) this_info['projs'] = [] this_rank = compute_rank(this_C, info=this_info) # Protect against true zero singular values s[s <= 0] = 1e-10 * s[s > 0].min() s = np.sqrt(s) * scaling axes[0, k].plot(s, color='k', zorder=3) this_rank = this_rank[key] axes[0, k].axvline(this_rank - 1, ls='--', color='r', alpha=0.5, zorder=4, clip_on=False) axes[0, k].text(this_rank - 1, axes[0, k].get_ylim()[1], 'rank ≈ %d' % (this_rank,), ha='right', va='top', color='r', alpha=0.5, zorder=4) axes[0, k].set(ylabel=u'Noise σ (%s)' % unit, yscale='log', xlabel='Eigenvalue index', title=name, xlim=[0, len(s) - 1]) tight_layout(fig=fig_svd) plt_show(show) return fig_cov, fig_svd def plot_source_spectrogram(stcs, freq_bins, tmin=None, tmax=None, source_index=None, colorbar=False, show=True): """Plot source power in time-freqency grid. Parameters ---------- stcs : list of SourceEstimate Source power for consecutive time windows, one SourceEstimate object should be provided for each frequency bin. freq_bins : list of tuples of float Start and end points of frequency bins of interest. tmin : float Minimum time instant to show. tmax : float Maximum time instant to show. source_index : int | None Index of source for which the spectrogram will be plotted. If None, the source with the largest activation will be selected. colorbar : bool If true, a colorbar will be added to the plot. show : bool Show figure if True. Returns ------- fig : instance of Figure The figure. """ import matplotlib.pyplot as plt # Input checks if len(stcs) == 0: raise ValueError('cannot plot spectrogram if len(stcs) == 0') stc = stcs[0] if tmin is not None and tmin < stc.times[0]: raise ValueError('tmin cannot be smaller than the first time point ' 'provided in stcs') if tmax is not None and tmax > stc.times[-1] + stc.tstep: raise ValueError('tmax cannot be larger than the sum of the last time ' 'point and the time step, which are provided in stcs') # Preparing time-frequency cell boundaries for plotting if tmin is None: tmin = stc.times[0] if tmax is None: tmax = stc.times[-1] + stc.tstep time_bounds = np.arange(tmin, tmax + stc.tstep, stc.tstep) freq_bounds = sorted(set(np.ravel(freq_bins))) freq_ticks = copy.deepcopy(freq_bounds) # Reject time points that will not be plotted and gather results source_power = [] for stc in stcs: stc = stc.copy() # copy since crop modifies inplace stc.crop(tmin, tmax - stc.tstep) source_power.append(stc.data) source_power = np.array(source_power) # Finding the source with maximum source power if source_index is None: source_index = np.unravel_index(source_power.argmax(), source_power.shape)[1] # If there is a gap in the frequency bins record its locations so that it # can be covered with a gray horizontal bar gap_bounds = [] for i in range(len(freq_bins) - 1): lower_bound = freq_bins[i][1] upper_bound = freq_bins[i + 1][0] if lower_bound != upper_bound: freq_bounds.remove(lower_bound) gap_bounds.append((lower_bound, upper_bound)) # Preparing time-frequency grid for plotting time_grid, freq_grid = np.meshgrid(time_bounds, freq_bounds) # Plotting the results fig = plt.figure(figsize=(9, 6)) plt.pcolor(time_grid, freq_grid, source_power[:, source_index, :], cmap='Reds') ax = plt.gca() ax.set(title='Source power', xlabel='Time (s)', ylabel='Frequency (Hz)') time_tick_labels = [str(np.round(t, 2)) for t in time_bounds] n_skip = 1 + len(time_bounds) // 10 for i in range(len(time_bounds)): if i % n_skip != 0: time_tick_labels[i] = '' ax.set_xticks(time_bounds) ax.set_xticklabels(time_tick_labels) plt.xlim(time_bounds[0], time_bounds[-1]) plt.yscale('log') ax.set_yticks(freq_ticks) ax.set_yticklabels([np.round(freq, 2) for freq in freq_ticks]) plt.ylim(freq_bounds[0], freq_bounds[-1]) plt.grid(True, ls='-') if colorbar: plt.colorbar() tight_layout(fig=fig) # Covering frequency gaps with horizontal bars for lower_bound, upper_bound in gap_bounds: plt.barh(lower_bound, time_bounds[-1] - time_bounds[0], upper_bound - lower_bound, time_bounds[0], color='#666666') plt_show(show) return fig def _plot_mri_contours(mri_fname, surfaces, src, orientation='coronal', slices=None, show=True, show_indices=False, show_orientation=False, img_output=False, width=512): """Plot BEM contours on anatomical slices.""" import matplotlib.pyplot as plt from matplotlib import patheffects from .._freesurfer import _mri_orientation, _read_mri_info # For ease of plotting, we will do everything in voxel coordinates. _check_option('orientation', orientation, ('coronal', 'axial', 'sagittal')) # Load the T1 data _, vox_mri_t, _, _, _, nim = _read_mri_info( mri_fname, units='mm', return_img=True) mri_vox_t = invert_transform(vox_mri_t)['trans'] del vox_mri_t # plot axes (x, y, z) as data axes (x, y, z), (flip_x, flip_y, flip_z), order = _mri_orientation( nim, orientation) transpose = x < y data = _get_img_fdata(nim) shift_x = data.shape[x] if flip_x < 0 else 0 shift_y = data.shape[y] if flip_y < 0 else 0 n_slices = data.shape[z] if slices is None: slices = np.round(np.linspace(0, n_slices - 1, 14)).astype(int)[1:-1] slices = np.atleast_1d(slices).copy() slices[slices < 0] += n_slices # allow negative indexing if not np.array_equal(np.sort(slices), slices) or slices.ndim != 1 or \ slices.size < 1 or slices[0] < 0 or slices[-1] >= n_slices or \ slices.dtype.kind not in 'iu': raise ValueError('slices must be a sorted 1D array of int with unique ' 'elements, at least one element, and no elements ' 'greater than %d, got %s' % (n_slices - 1, slices)) if flip_z < 0: # Proceed in the opposite order to maintain left-to-right / orientation slices = slices[::-1] # create of list of surfaces surfs = list() for file_name, color in surfaces: surf = dict() surf['rr'], surf['tris'] = read_surface(file_name) # move surface to voxel coordinate system surf['rr'] = apply_trans(mri_vox_t, surf['rr']) surfs.append((surf, color)) sources = list() if src is not None: _ensure_src(src, extra=' or None') # Eventually we can relax this by allowing ``trans`` if need be if src[0]['coord_frame'] != FIFF.FIFFV_COORD_MRI: raise ValueError( 'Source space must be in MRI coordinates, got ' f'{_frame_to_str[src[0]["coord_frame"]]}') for src_ in src: points = src_['rr'][src_['inuse'].astype(bool)] sources.append(apply_trans(mri_vox_t, points * 1e3)) sources = np.concatenate(sources, axis=0) if img_output: n_col = n_axes = 1 dpi = 96 # 2x standard MRI resolution is probably good enough for the # traces w = width / dpi figsize = (w, w / data.shape[x] * data.shape[y]) fig = _figure_agg(figsize=figsize, dpi=dpi, facecolor='k') ax = fig.add_axes([0, 0, 1, 1], frame_on=False, facecolor='k') axs = [ax] * len(slices) plt.close(fig) else: n_col = 4 fig, axs, _, _ = _prepare_trellis(len(slices), n_col) fig.set_facecolor('k') dpi = fig.get_dpi() n_axes = len(axs) bounds = np.concatenate( [[-np.inf], slices[:-1] + np.diff(slices) / 2., [np.inf]]) # float slicer = [slice(None)] * 3 ori_labels = dict(R='LR', A='PA', S='IS') xlabels, ylabels = ori_labels[order[0]], ori_labels[order[1]] path_effects = [patheffects.withStroke(linewidth=4, foreground="k", alpha=0.75)] out = list() if img_output else fig for ai, (ax, sl, lower, upper) in enumerate(zip( axs, slices, bounds[:-1], bounds[1:])): # adjust the orientations for good view slicer[z] = sl dat = data[tuple(slicer)] dat = dat.T if transpose else dat dat = dat[::flip_y, ::flip_x] # First plot the anatomical data if img_output: ax.clear() ax.imshow(dat, cmap=plt.cm.gray, origin='lower') ax.set_autoscale_on(False) ax.axis('off') ax.set_aspect('equal') # XXX eventually could deal with zooms # and then plot the contours on top for surf, color in surfs: with warnings.catch_warnings(record=True): # ignore contour warn warnings.simplefilter('ignore') ax.tricontour(flip_x * surf['rr'][:, x] + shift_x, flip_y * surf['rr'][:, y] + shift_y, surf['tris'], surf['rr'][:, z], levels=[sl], colors=color, linewidths=1.0, zorder=1) if len(sources): in_slice = (sources[:, z] >= lower) & (sources[:, z] < upper) ax.scatter(flip_x * sources[in_slice, x] + shift_x, flip_y * sources[in_slice, y] + shift_y, marker='.', color='#FF00FF', s=1, zorder=2) if show_indices: ax.text(dat.shape[1] // 8 + 0.5, 0.5, str(sl), color='w', fontsize='x-small', va='bottom', ha='left') # label the axes kwargs = dict( color='#66CCEE', fontsize='medium', path_effects=path_effects, family='monospace', clip_on=False, zorder=5, weight='bold') if show_orientation: if ai % n_col == 0: # left ax.text(0, dat.shape[0] / 2., xlabels[0], va='center', ha='left', **kwargs) if ai % n_col == n_col - 1 or ai == n_axes - 1: # right ax.text(dat.shape[1] - 1, dat.shape[0] / 2., xlabels[1], va='center', ha='right', **kwargs) if ai >= n_axes - n_col: # bottom ax.text(dat.shape[1] / 2., 0, ylabels[0], ha='center', va='bottom', **kwargs) if ai < n_col or n_col == 1: # top ax.text(dat.shape[1] / 2., dat.shape[0] - 1, ylabels[1], ha='center', va='top', **kwargs) if img_output: output = BytesIO() fig.savefig(output, bbox_inches='tight', pad_inches=0, format='png', dpi=dpi) out.append(base64.b64encode(output.getvalue()).decode('ascii')) fig.subplots_adjust(left=0., bottom=0., right=1., top=1., wspace=0., hspace=0.) plt_show(show, fig=fig) return out, flip_z def plot_bem(subject=None, subjects_dir=None, orientation='coronal', slices=None, brain_surfaces=None, src=None, show=True, show_indices=True, mri='T1.mgz', show_orientation=True): """Plot BEM contours on anatomical slices. Parameters ---------- subject : str Subject name. subjects_dir : str | None Path to the SUBJECTS_DIR. If None, the path is obtained by using the environment variable SUBJECTS_DIR. orientation : str 'coronal' or 'axial' or 'sagittal'. slices : list of int Slice indices. brain_surfaces : None | str | list of str One or more brain surface to plot (optional). Entries should correspond to files in the subject's ``surf`` directory (e.g. ``"white"``). src : None | SourceSpaces | str SourceSpaces instance or path to a source space to plot individual sources as scatter-plot. Sources will be shown on exactly one slice (whichever slice is closest to each source in the given orientation plane). Path can be absolute or relative to the subject's ``bem`` folder. .. versionchanged:: 0.20 All sources are shown on the nearest slice rather than some being omitted. show : bool Show figure if True. show_indices : bool Show slice indices if True. .. versionadded:: 0.20 mri : str The name of the MRI to use. Can be a standard FreeSurfer MRI such as ``'T1.mgz'``, or a full path to a custom MRI file. .. versionadded:: 0.21 show_orientation : str Show the orientation (L/R, P/A, I/S) of the data slices. .. versionadded:: 0.21 Returns ------- fig : instance of matplotlib.figure.Figure The figure. See Also -------- mne.viz.plot_alignment Notes ----- Images are plotted in MRI voxel coordinates. If ``src`` is not None, for a given slice index, all source points are shown that are halfway between the previous slice and the given slice, and halfway between the given slice and the next slice. For large slice decimations, this can make some source points appear outside the BEM contour, which is shown for the given slice index. For example, in the case where the single midpoint slice is used ``slices=[128]``, all source points will be shown on top of the midpoint MRI slice with the BEM boundary drawn for that slice. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) mri_fname = _check_mri(mri, subject, subjects_dir) # Get the BEM surface filenames bem_path = op.join(subjects_dir, subject, 'bem') if not op.isdir(bem_path): raise IOError('Subject bem directory "%s" does not exist' % bem_path) surfaces = _get_bem_plotting_surfaces(bem_path) if brain_surfaces is not None: if isinstance(brain_surfaces, str): brain_surfaces = (brain_surfaces,) for surf_name in brain_surfaces: for hemi in ('lh', 'rh'): surf_fname = op.join(subjects_dir, subject, 'surf', hemi + '.' + surf_name) if op.exists(surf_fname): surfaces.append((surf_fname, '#00DD00')) else: raise IOError("Surface %s does not exist." % surf_fname) if isinstance(src, str): if not op.exists(src): src_ = op.join(subjects_dir, subject, 'bem', src) if op.exists(src_): src = src_ else: raise IOError("%s does not exist" % src) src = read_source_spaces(src) elif src is not None and not isinstance(src, SourceSpaces): raise TypeError("src needs to be None, str or SourceSpaces instance, " "not %s" % repr(src)) if len(surfaces) == 0: raise IOError('No surface files found. Surface files must end with ' 'inner_skull.surf, outer_skull.surf or outer_skin.surf') # Plot the contours return _plot_mri_contours(mri_fname, surfaces, src, orientation, slices, show, show_indices, show_orientation)[0] def _get_bem_plotting_surfaces(bem_path): surfaces = [] for surf_name, color in (('*inner_skull', '#FF0000'), ('*outer_skull', '#FFFF00'), ('*outer_skin', '#FFAA80')): surf_fname = glob(op.join(bem_path, surf_name + '.surf')) if len(surf_fname) > 0: surf_fname = surf_fname[0] logger.info("Using surface: %s" % surf_fname) surfaces.append((surf_fname, color)) return surfaces @verbose def plot_events(events, sfreq=None, first_samp=0, color=None, event_id=None, axes=None, equal_spacing=True, show=True, on_missing='raise', verbose=None): """Plot events to get a visual display of the paradigm. Parameters ---------- events : array, shape (n_events, 3) The events. sfreq : float | None The sample frequency. If None, data will be displayed in samples (not seconds). first_samp : int The index of the first sample. Recordings made on Neuromag systems number samples relative to the system start (not relative to the beginning of the recording). In such cases the ``raw.first_samp`` attribute can be passed here. Default is 0. color : dict | None Dictionary of event_id integers as keys and colors as values. If None, colors are automatically drawn from a default list (cycled through if number of events longer than list of default colors). Color can be any valid :doc:`matplotlib color <tutorials/colors/colors>`. event_id : dict | None Dictionary of event labels (e.g. 'aud_l') as keys and their associated event_id values. Labels are used to plot a legend. If None, no legend is drawn. axes : instance of Axes The subplot handle. equal_spacing : bool Use equal spacing between events in y-axis. show : bool Show figure if True. %(on_missing_events)s %(verbose)s Returns ------- fig : matplotlib.figure.Figure The figure object containing the plot. Notes ----- .. versionadded:: 0.9.0 """ if sfreq is None: sfreq = 1.0 xlabel = 'Samples' else: xlabel = 'Time (s)' events = np.asarray(events) if len(events) == 0: raise ValueError('No events in events array, cannot plot.') unique_events = np.unique(events[:, 2]) if event_id is not None: # get labels and unique event ids from event_id dict, # sorted by value event_id_rev = {v: k for k, v in event_id.items()} conditions, unique_events_id = zip(*sorted(event_id.items(), key=lambda x: x[1])) keep = np.ones(len(unique_events_id), bool) for ii, this_event in enumerate(unique_events_id): if this_event not in unique_events: msg = f'{this_event} from event_id is not present in events.' _on_missing(on_missing, msg) keep[ii] = False conditions = [cond for cond, k in zip(conditions, keep) if k] unique_events_id = [id_ for id_, k in zip(unique_events_id, keep) if k] if len(unique_events_id) == 0: raise RuntimeError('No usable event IDs found') for this_event in unique_events: if this_event not in unique_events_id: warn('event %s missing from event_id will be ignored' % this_event) else: unique_events_id = unique_events color = _handle_event_colors(color, unique_events, event_id) import matplotlib.pyplot as plt fig = None if axes is None: fig = plt.figure() ax = axes if axes else plt.gca() unique_events_id = np.array(unique_events_id) min_event = np.min(unique_events_id) max_event = np.max(unique_events_id) max_x = (events[np.in1d(events[:, 2], unique_events_id), 0].max() - first_samp) / sfreq handles, labels = list(), list() for idx, ev in enumerate(unique_events_id): ev_mask = events[:, 2] == ev count = ev_mask.sum() if count == 0: continue y = np.full(count, idx + 1 if equal_spacing else events[ev_mask, 2][0]) if event_id is not None: event_label = '%s (%s)' % (event_id_rev[ev], count) else: event_label = 'N=%d' % (count,) labels.append(event_label) kwargs = {} if ev in color: kwargs['color'] = color[ev] handles.append( ax.plot((events[ev_mask, 0] - first_samp) / sfreq, y, '.', clip_on=False, **kwargs)[0]) if equal_spacing: ax.set_ylim(0, unique_events_id.size + 1) ax.set_yticks(1 + np.arange(unique_events_id.size)) ax.set_yticklabels(unique_events_id) else: ax.set_ylim([min_event - 1, max_event + 1]) ax.set(xlabel=xlabel, ylabel='Event id', xlim=[0, max_x]) ax.grid(True) fig = fig if fig is not None else plt.gcf() # reverse order so that the highest numbers are at the top # (match plot order) handles, labels = handles[::-1], labels[::-1] box = ax.get_position() factor = 0.8 if event_id is not None else 0.9 ax.set_position([box.x0, box.y0, box.width * factor, box.height]) ax.legend(handles, labels, loc='center left', bbox_to_anchor=(1, 0.5), fontsize='small') fig.canvas.draw() plt_show(show) return fig def _get_presser(fig): """Get our press callback.""" import matplotlib callbacks = fig.canvas.callbacks.callbacks['button_press_event'] func = None for key, val in callbacks.items(): if LooseVersion(matplotlib.__version__) >= '3': func = val() else: func = val.func if func.__class__.__name__ == 'partial': break else: func = None assert func is not None return func def plot_dipole_amplitudes(dipoles, colors=None, show=True): """Plot the amplitude traces of a set of dipoles. Parameters ---------- dipoles : list of instance of Dipole The dipoles whose amplitudes should be shown. colors : list of color | None Color to plot with each dipole. If None default colors are used. show : bool Show figure if True. Returns ------- fig : matplotlib.figure.Figure The figure object containing the plot. Notes ----- .. versionadded:: 0.9.0 """ import matplotlib.pyplot as plt if colors is None: colors = cycle(_get_color_list()) fig, ax = plt.subplots(1, 1) xlim = [np.inf, -np.inf] for dip, color in zip(dipoles, colors): ax.plot(dip.times, dip.amplitude * 1e9, color=color, linewidth=1.5) xlim[0] = min(xlim[0], dip.times[0]) xlim[1] = max(xlim[1], dip.times[-1]) ax.set(xlim=xlim, xlabel='Time (s)', ylabel='Amplitude (nAm)') if show: fig.show(warn=False) return fig def adjust_axes(axes, remove_spines=('top', 'right'), grid=True): """Adjust some properties of axes. Parameters ---------- axes : list List of axes to process. remove_spines : list of str Which axis spines to remove. grid : bool Turn grid on (True) or off (False). """ axes = [axes] if not isinstance(axes, (list, tuple, np.ndarray)) else axes for ax in axes: if grid: ax.grid(zorder=0) for key in remove_spines: ax.spines[key].set_visible(False) def _filter_ticks(lims, fscale): """Create approximately spaced ticks between lims.""" if fscale == 'linear': return None, None # let matplotlib handle it lims = np.array(lims) ticks = list() if lims[1] > 20 * lims[0]: base = np.array([1, 2, 4]) else: base = np.arange(1, 11) for exp in range(int(np.floor(np.log10(lims[0]))), int(np.floor(np.log10(lims[1]))) + 1): ticks += (base * (10 ** exp)).tolist() ticks = np.array(ticks) ticks = ticks[(ticks >= lims[0]) & (ticks <= lims[1])] ticklabels = [('%g' if t < 1 else '%d') % t for t in ticks] return ticks, ticklabels def _get_flim(flim, fscale, freq, sfreq=None): """Get reasonable frequency limits.""" if flim is None: if freq is None: flim = [0.1 if fscale == 'log' else 0., sfreq / 2.] else: if fscale == 'linear': flim = [freq[0]] else: flim = [freq[0] if freq[0] > 0 else 0.1 * freq[1]] flim += [freq[-1]] if fscale == 'log': if flim[0] <= 0: raise ValueError('flim[0] must be positive, got %s' % flim[0]) elif flim[0] < 0: raise ValueError('flim[0] must be non-negative, got %s' % flim[0]) return flim def _check_fscale(fscale): """Check for valid fscale.""" if not isinstance(fscale, str) or fscale not in ('log', 'linear'): raise ValueError('fscale must be "log" or "linear", got %s' % (fscale,)) _DEFAULT_ALIM = (-80, 10) def plot_filter(h, sfreq, freq=None, gain=None, title=None, color='#1f77b4', flim=None, fscale='log', alim=_DEFAULT_ALIM, show=True, compensate=False, plot=('time', 'magnitude', 'delay'), axes=None): """Plot properties of a filter. Parameters ---------- h : dict or ndarray An IIR dict or 1D ndarray of coefficients (for FIR filter). sfreq : float Sample rate of the data (Hz). freq : array-like or None The ideal response frequencies to plot (must be in ascending order). If None (default), do not plot the ideal response. gain : array-like or None The ideal response gains to plot. If None (default), do not plot the ideal response. title : str | None The title to use. If None (default), determine the title based on the type of the system. color : color object The color to use (default '#1f77b4'). flim : tuple or None If not None, the x-axis frequency limits (Hz) to use. If None, freq will be used. If None (default) and freq is None, ``(0.1, sfreq / 2.)`` will be used. fscale : str Frequency scaling to use, can be "log" (default) or "linear". alim : tuple The y-axis amplitude limits (dB) to use (default: (-60, 10)). show : bool Show figure if True (default). compensate : bool If True, compensate for the filter delay (phase will not be shown). - For linear-phase FIR filters, this visualizes the filter coefficients assuming that the output will be shifted by ``N // 2``. - For IIR filters, this changes the filter coefficient display by filtering backward and forward, and the frequency response by squaring it. .. versionadded:: 0.18 plot : list | tuple | str A list of the requested plots from ``time``, ``magnitude`` and ``delay``. Default is to plot all three filter properties ('time', 'magnitude', 'delay'). .. versionadded:: 0.21.0 axes : instance of Axes | list | None The axes to plot to. If list, the list must be a list of Axes of the same length as the number of requested plot types. If instance of Axes, there must be only one filter property plotted. Defaults to ``None``. .. versionadded:: 0.21.0 Returns ------- fig : matplotlib.figure.Figure The figure containing the plots. See Also -------- mne.filter.create_filter plot_ideal_filter Notes ----- .. versionadded:: 0.14 """ from scipy.signal import ( freqz, group_delay, lfilter, filtfilt, sosfilt, sosfiltfilt) import matplotlib.pyplot as plt sfreq = float(sfreq) _check_option('fscale', fscale, ['log', 'linear']) if isinstance(plot, str): plot = [plot] for xi, x in enumerate(plot): _check_option('plot[%d]' % xi, x, ('magnitude', 'delay', 'time')) flim = _get_flim(flim, fscale, freq, sfreq) if fscale == 'log': omega = np.logspace(np.log10(flim[0]), np.log10(flim[1]), 1000) else: omega = np.linspace(flim[0], flim[1], 1000) xticks, xticklabels = _filter_ticks(flim, fscale) omega /= sfreq / (2 * np.pi) if isinstance(h, dict): # IIR h.ndim == 2: # second-order sections if 'sos' in h: H = np.ones(len(omega), np.complex128) gd = np.zeros(len(omega)) for section in h['sos']: this_H = freqz(section[:3], section[3:], omega)[1] H *= this_H if compensate: H *= this_H.conj() # time reversal is freq conj else: # Assume the forward-backward delay zeros out, which it # mostly should with warnings.catch_warnings(record=True): # singular GD warnings.simplefilter('ignore') gd += group_delay((section[:3], section[3:]), omega)[1] n = estimate_ringing_samples(h['sos']) delta = np.zeros(n) delta[0] = 1 if compensate: delta = np.pad(delta, [(n - 1, 0)], 'constant') func = sosfiltfilt gd += (len(delta) - 1) // 2 else: func = sosfilt h = func(h['sos'], delta) else: H = freqz(h['b'], h['a'], omega)[1] if compensate: H *= H.conj() with warnings.catch_warnings(record=True): # singular GD warnings.simplefilter('ignore') gd = group_delay((h['b'], h['a']), omega)[1] if compensate: gd += group_delay(h['b'].conj(), h['a'].conj(), omega)[1] n = estimate_ringing_samples((h['b'], h['a'])) delta = np.zeros(n) delta[0] = 1 if compensate: delta = np.pad(delta, [(n - 1, 0)], 'constant') func = filtfilt else: func = lfilter h = func(h['b'], h['a'], delta) if title is None: title = 'SOS (IIR) filter' if compensate: title += ' (forward-backward)' else: H = freqz(h, worN=omega)[1] with warnings.catch_warnings(record=True): # singular GD warnings.simplefilter('ignore') gd = group_delay((h, [1.]), omega)[1] title = 'FIR filter' if title is None else title if compensate: title += ' (delay-compensated)' fig = None if axes is None: fig, axes = plt.subplots(len(plot), 1) if isinstance(axes, plt.Axes): axes = [axes] elif isinstance(axes, np.ndarray): axes = list(axes) if fig is None: fig = axes[0].get_figure() if len(axes) != len(plot): raise ValueError('Length of axes (%d) must be the same as number of ' 'requested filter properties (%d)' % (len(axes), len(plot))) t = np.arange(len(h)) dlim = np.abs(t).max() / 2. dlim = [-dlim, dlim] if compensate: n_shift = (len(h) - 1) // 2 t -= n_shift assert t[0] == -t[-1] gd -= n_shift t = t / sfreq gd = gd / sfreq f = omega * sfreq / (2 * np.pi) sl = slice(0 if fscale == 'linear' else 1, None, None) mag = 10 * np.log10(np.maximum((H * H.conj()).real, 1e-20)) if 'time' in plot: ax_time_idx = np.where([p == 'time' for p in plot])[0][0] axes[ax_time_idx].plot(t, h, color=color) axes[ax_time_idx].set(xlim=t[[0, -1]], xlabel='Time (s)', ylabel='Amplitude', title=title) # Magnitude if 'magnitude' in plot: ax_mag_idx = np.where([p == 'magnitude' for p in plot])[0][0] axes[ax_mag_idx].plot(f[sl], mag[sl], color=color, linewidth=2, zorder=4) if freq is not None and gain is not None: plot_ideal_filter(freq, gain, axes[ax_mag_idx], fscale=fscale, show=False) axes[ax_mag_idx].set(ylabel='Magnitude (dB)', xlabel='', xscale=fscale) if xticks is not None: axes[ax_mag_idx].set(xticks=xticks) axes[ax_mag_idx].set(xticklabels=xticklabels) axes[ax_mag_idx].set(xlim=flim, ylim=alim, xlabel='Frequency (Hz)', ylabel='Amplitude (dB)') # Delay if 'delay' in plot: ax_delay_idx = np.where([p == 'delay' for p in plot])[0][0] axes[ax_delay_idx].plot(f[sl], gd[sl], color=color, linewidth=2, zorder=4) # shade nulled regions for start, stop in zip(*_mask_to_onsets_offsets(mag <= -39.9)): axes[ax_delay_idx].axvspan(f[start], f[stop - 1], facecolor='k', alpha=0.05, zorder=5) axes[ax_delay_idx].set(xlim=flim, ylabel='Group delay (s)', xlabel='Frequency (Hz)', xscale=fscale) if xticks is not None: axes[ax_delay_idx].set(xticks=xticks) axes[ax_delay_idx].set(xticklabels=xticklabels) axes[ax_delay_idx].set(xlim=flim, ylim=dlim, xlabel='Frequency (Hz)', ylabel='Delay (s)') adjust_axes(axes) tight_layout() plt_show(show) return fig def plot_ideal_filter(freq, gain, axes=None, title='', flim=None, fscale='log', alim=_DEFAULT_ALIM, color='r', alpha=0.5, linestyle='--', show=True): """Plot an ideal filter response. Parameters ---------- freq : array-like The ideal response frequencies to plot (must be in ascending order). gain : array-like or None The ideal response gains to plot. axes : instance of Axes | None The subplot handle. With None (default), axes are created. title : str The title to use, (default: ''). flim : tuple or None If not None, the x-axis frequency limits (Hz) to use. If None (default), freq used. fscale : str Frequency scaling to use, can be "log" (default) or "linear". alim : tuple If not None (default), the y-axis limits (dB) to use. color : color object The color to use (default: 'r'). alpha : float The alpha to use (default: 0.5). linestyle : str The line style to use (default: '--'). show : bool Show figure if True (default). Returns ------- fig : instance of matplotlib.figure.Figure The figure. See Also -------- plot_filter Notes ----- .. versionadded:: 0.14 Examples -------- Plot a simple ideal band-pass filter:: >>> from mne.viz import plot_ideal_filter >>> freq = [0, 1, 40, 50] >>> gain = [0, 1, 1, 0] >>> plot_ideal_filter(freq, gain, flim=(0.1, 100)) #doctest: +ELLIPSIS <...Figure...> """ import matplotlib.pyplot as plt my_freq, my_gain = list(), list() if freq[0] != 0: raise ValueError('freq should start with DC (zero) and end with ' 'Nyquist, but got %s for DC' % (freq[0],)) freq = np.array(freq) # deal with semilogx problems @ x=0 _check_option('fscale', fscale, ['log', 'linear']) if fscale == 'log': freq[0] = 0.1 * freq[1] if flim is None else min(flim[0], freq[1]) flim = _get_flim(flim, fscale, freq) transitions = list() for ii in range(len(freq)): if ii < len(freq) - 1 and gain[ii] != gain[ii + 1]: transitions += [[freq[ii], freq[ii + 1]]] my_freq += np.linspace(freq[ii], freq[ii + 1], 20, endpoint=False).tolist() my_gain += np.linspace(gain[ii], gain[ii + 1], 20, endpoint=False).tolist() else: my_freq.append(freq[ii]) my_gain.append(gain[ii]) my_gain = 10 * np.log10(np.maximum(my_gain, 10 ** (alim[0] / 10.))) if axes is None: axes = plt.subplots(1)[1] for transition in transitions: axes.axvspan(*transition, color=color, alpha=0.1) axes.plot(my_freq, my_gain, color=color, linestyle=linestyle, alpha=0.5, linewidth=4, zorder=3) xticks, xticklabels = _filter_ticks(flim, fscale) axes.set(ylim=alim, xlabel='Frequency (Hz)', ylabel='Amplitude (dB)', xscale=fscale) if xticks is not None: axes.set(xticks=xticks) axes.set(xticklabels=xticklabels) axes.set(xlim=flim) if title: axes.set(title=title) adjust_axes(axes) tight_layout() plt_show(show) return axes.figure def _handle_event_colors(color_dict, unique_events, event_id): """Create event-integer-to-color mapping, assigning defaults as needed.""" default_colors = dict(zip(sorted(unique_events), cycle(_get_color_list()))) # warn if not enough colors if color_dict is None: if len(unique_events) > len(_get_color_list()): warn('More events than default colors available. You should pass ' 'a list of unique colors.') else: custom_colors = dict() for key, color in color_dict.items(): if key in unique_events: # key was a valid event integer custom_colors[key] = color elif key in event_id: # key was an event label custom_colors[event_id[key]] = color else: # key not a valid event, warn and ignore warn('Event ID %s is in the color dict but is not ' 'present in events or event_id.' % str(key)) # warn if color_dict is missing any entries unassigned = sorted(set(unique_events) - set(custom_colors)) if len(unassigned): unassigned_str = ', '.join(str(e) for e in unassigned) warn('Color was not assigned for event%s %s. Default colors will ' 'be used.' % (_pl(unassigned), unassigned_str)) default_colors.update(custom_colors) return default_colors @fill_doc def plot_csd(csd, info=None, mode='csd', colorbar=True, cmap=None, n_cols=None, show=True): """Plot CSD matrices. A sub-plot is created for each frequency. If an info object is passed to the function, different channel types are plotted in different figures. Parameters ---------- csd : instance of CrossSpectralDensity The CSD matrix to plot. %(info)s Used to split the figure by channel-type, if provided. By default, the CSD matrix is plotted as a whole. mode : 'csd' | 'coh' Whether to plot the cross-spectral density ('csd', the default), or the coherence ('coh') between the channels. colorbar : bool Whether to show a colorbar. Defaults to ``True``. cmap : str | None The matplotlib colormap to use. Defaults to None, which means the colormap will default to matplotlib's default. n_cols : int | None CSD matrices are plotted in a grid. This parameter controls how many matrix to plot side by side before starting a new row. By default, a number will be chosen to make the grid as square as possible. show : bool Whether to show the figure. Defaults to ``True``. Returns ------- fig : list of Figure The figures created by this function. """ import matplotlib.pyplot as plt if mode not in ['csd', 'coh']: raise ValueError('"mode" should be either "csd" or "coh".') if info is not None: info_ch_names = info['ch_names'] sel_eeg = pick_types(info, meg=False, eeg=True, ref_meg=False, exclude=[]) sel_mag = pick_types(info, meg='mag', eeg=False, ref_meg=False, exclude=[]) sel_grad = pick_types(info, meg='grad', eeg=False, ref_meg=False, exclude=[]) idx_eeg = [csd.ch_names.index(info_ch_names[c]) for c in sel_eeg if info_ch_names[c] in csd.ch_names] idx_mag = [csd.ch_names.index(info_ch_names[c]) for c in sel_mag if info_ch_names[c] in csd.ch_names] idx_grad = [csd.ch_names.index(info_ch_names[c]) for c in sel_grad if info_ch_names[c] in csd.ch_names] indices = [idx_eeg, idx_mag, idx_grad] titles = ['EEG', 'Magnetometers', 'Gradiometers'] if mode == 'csd': # The units in which to plot the CSD units = dict(eeg='µV²', grad='fT²/cm²', mag='fT²') scalings = dict(eeg=1e12, grad=1e26, mag=1e30) else: indices = [np.arange(len(csd.ch_names))] if mode == 'csd': titles = ['Cross-spectral density'] # Units and scaling unknown units = dict() scalings = dict() elif mode == 'coh': titles = ['Coherence'] n_freqs = len(csd.frequencies) if n_cols is None: n_cols = int(np.ceil(np.sqrt(n_freqs))) n_rows = int(np.ceil(n_freqs / float(n_cols))) figs = [] for ind, title, ch_type in zip(indices, titles, ['eeg', 'mag', 'grad']): if len(ind) == 0: continue fig, axes = plt.subplots(n_rows, n_cols, squeeze=False, figsize=(2 * n_cols + 1, 2.2 * n_rows)) csd_mats = [] for i in range(len(csd.frequencies)): cm = csd.get_data(index=i)[ind][:, ind] if mode == 'csd': cm = np.abs(cm) * scalings.get(ch_type, 1) elif mode == 'coh': # Compute coherence from the CSD matrix psd = np.diag(cm).real cm = np.abs(cm) ** 2 / psd[np.newaxis, :] / psd[:, np.newaxis] csd_mats.append(cm) vmax = np.max(csd_mats) for i, (freq, mat) in enumerate(zip(csd.frequencies, csd_mats)): ax = axes[i // n_cols][i % n_cols] im = ax.imshow(mat, interpolation='nearest', cmap=cmap, vmin=0, vmax=vmax) ax.set_xticks([]) ax.set_yticks([]) if csd._is_sum: ax.set_title('%.1f-%.1f Hz.' % (np.min(freq), np.max(freq))) else: ax.set_title('%.1f Hz.' % freq) plt.suptitle(title) plt.subplots_adjust(top=0.8) if colorbar: cb = plt.colorbar(im, ax=[a for ax_ in axes for a in ax_]) if mode == 'csd': label = u'CSD' if ch_type in units: label += u' (%s)' % units[ch_type] cb.set_label(label) elif mode == 'coh': cb.set_label('Coherence') figs.append(fig) plt_show(show) return figs def plot_chpi_snr(snr_dict, axes=None): """Plot time-varying SNR estimates of the HPI coils. Parameters ---------- snr_dict : dict The dictionary returned by `~mne.chpi.compute_chpi_snr`. Must have keys ``times``, ``freqs``, ``TYPE_snr``, ``TYPE_power``, and ``TYPE_resid`` (where ``TYPE`` can be ``mag`` or ``grad`` or both). axes : None | list of matplotlib.axes.Axes Figure axes in which to draw the SNR, power, and residual plots. The number of axes should be 3× the number of MEG sensor types present in ``snr_dict``. If ``None`` (the default), a new `~matplotlib.figure.Figure` is created with the required number of axes. Returns ------- fig : instance of matplotlib.figure.Figure A figure with subplots for SNR, power, and residual variance, separately for magnetometers and/or gradiometers (depending on what is present in ``snr_dict``). Notes ----- If you supply a list of existing `~matplotlib.axes.Axes`, then the figure legend will not be drawn automatically. If you still want it, running ``fig.legend(loc='right', title='cHPI frequencies')`` will recreate it, though you may also need to manually adjust the margin to make room for it (e.g., using ``fig.subplots_adjust(right=0.8)``). .. versionadded:: 0.24 """ import matplotlib.pyplot as plt valid_keys = list(snr_dict)[2:] titles = dict(snr='SNR', power='cHPI power', resid='Residual variance') full_names = dict(mag='magnetometers', grad='gradiometers') axes_was_none = axes is None if axes_was_none: fig, axes = plt.subplots(len(valid_keys), 1, sharex=True) else: fig = axes[0].get_figure() if len(axes) != len(valid_keys): raise ValueError(f'axes must be a list of {len(valid_keys)} axes, got ' f'length {len(axes)} ({axes}).') fig.set_size_inches(10, 10) legend_labels_exist = False for key, ax in zip(valid_keys, axes): ch_type, kind = key.split('_') scaling = 1 if kind == 'snr' else DEFAULTS['scalings'][ch_type] plot_kwargs = dict(color='k') if kind == 'resid' else dict() lines = ax.plot(snr_dict['times'], snr_dict[key] * scaling ** 2, **plot_kwargs) # the freqs should be the same for all sensor types (and for SNR and # power subplots), so we only need to label the lines on one axes # (otherwise we get duplicate legend entries). if not legend_labels_exist: for line, freq in zip(lines, snr_dict['freqs']): line.set_label(f'{freq} Hz') legend_labels_exist = True unit = DEFAULTS['units'][ch_type] unit = f'({unit})' if '/' in unit else unit set_kwargs = dict(title=f'{titles[kind]}, {full_names[ch_type]}', ylabel='dB' if kind == 'snr' else f'{unit}²') if not axes_was_none: set_kwargs.update(xlabel='Time (s)') ax.set(**set_kwargs) if axes_was_none: ax.set(xlabel='Time (s)') fig.align_ylabels() fig.subplots_adjust(left=0.1, right=0.825, bottom=0.075, top=0.95, hspace=0.7) fig.legend(loc='right', title='cHPI frequencies') return fig
37.783862
79
0.574556
import base64 import copy from glob import glob from io import BytesIO from itertools import cycle import os.path as op import warnings from distutils.version import LooseVersion from collections import defaultdict import numpy as np from ..defaults import DEFAULTS from ..fixes import _get_img_fdata from ..rank import compute_rank from ..surface import read_surface from ..io.constants import FIFF from ..io.proj import make_projector from ..io.pick import (_DATA_CH_TYPES_SPLIT, pick_types, pick_info, pick_channels) from ..source_space import (read_source_spaces, SourceSpaces, _check_mri, _ensure_src) from ..transforms import invert_transform, apply_trans, _frame_to_str from ..utils import (logger, verbose, warn, _check_option, get_subjects_dir, _mask_to_onsets_offsets, _pl, _on_missing, fill_doc) from ..io.pick import _picks_by_type from ..filter import estimate_ringing_samples from .utils import (tight_layout, _get_color_list, _prepare_trellis, plt_show, _figure_agg) def _index_info_cov(info, cov, exclude): if exclude == 'bads': exclude = info['bads'] info = pick_info(info, pick_channels(info['ch_names'], cov['names'], exclude)) del exclude picks_list = \ _picks_by_type(info, meg_combined=False, ref_meg=False, exclude=()) picks_by_type = dict(picks_list) ch_names = [n for n in cov.ch_names if n in info['ch_names']] ch_idx = [cov.ch_names.index(n) for n in ch_names] info_ch_names = info['ch_names'] idx_by_type = defaultdict(list) for ch_type, sel in picks_by_type.items(): idx_by_type[ch_type] = [ch_names.index(info_ch_names[c]) for c in sel if info_ch_names[c] in ch_names] idx_names = [(idx_by_type[key], '%s covariance' % DEFAULTS['titles'][key], DEFAULTS['units'][key], DEFAULTS['scalings'][key], key) for key in _DATA_CH_TYPES_SPLIT if len(idx_by_type[key]) > 0] C = cov.data[ch_idx][:, ch_idx] return info, C, ch_names, idx_names @verbose def plot_cov(cov, info, exclude=(), colorbar=True, proj=False, show_svd=True, show=True, verbose=None): import matplotlib.pyplot as plt from matplotlib.colors import Normalize from scipy import linalg from ..cov import Covariance info, C, ch_names, idx_names = _index_info_cov(info, cov, exclude) del cov, exclude projs = [] if proj: projs = copy.deepcopy(info['projs']) for p in projs: p['active'] = True P, ncomp, _ = make_projector(projs, ch_names) if ncomp > 0: logger.info(' Created an SSP operator (subspace dimension' ' = %d)' % ncomp) C = np.dot(P, np.dot(C, P.T)) else: logger.info(' The projection vectors do not apply to these ' 'channels.') fig_cov, axes = plt.subplots(1, len(idx_names), squeeze=False, figsize=(3.8 * len(idx_names), 3.7)) for k, (idx, name, _, _, _) in enumerate(idx_names): vlim = np.max(np.abs(C[idx][:, idx])) im = axes[0, k].imshow(C[idx][:, idx], interpolation="nearest", norm=Normalize(vmin=-vlim, vmax=vlim), cmap='RdBu_r') axes[0, k].set(title=name) if colorbar: from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(axes[0, k]) cax = divider.append_axes("right", size="5.5%", pad=0.05) plt.colorbar(im, cax=cax, format='%.0e') fig_cov.subplots_adjust(0.04, 0.0, 0.98, 0.94, 0.2, 0.26) tight_layout(fig=fig_cov) fig_svd = None if show_svd: fig_svd, axes = plt.subplots(1, len(idx_names), squeeze=False, figsize=(3.8 * len(idx_names), 3.7)) for k, (idx, name, unit, scaling, key) in enumerate(idx_names): this_C = C[idx][:, idx] s = linalg.svd(this_C, compute_uv=False) this_C = Covariance(this_C, [info['ch_names'][ii] for ii in idx], [], [], 0) this_info = pick_info(info, idx) this_info['projs'] = [] this_rank = compute_rank(this_C, info=this_info) s[s <= 0] = 1e-10 * s[s > 0].min() s = np.sqrt(s) * scaling axes[0, k].plot(s, color='k', zorder=3) this_rank = this_rank[key] axes[0, k].axvline(this_rank - 1, ls='--', color='r', alpha=0.5, zorder=4, clip_on=False) axes[0, k].text(this_rank - 1, axes[0, k].get_ylim()[1], 'rank ≈ %d' % (this_rank,), ha='right', va='top', color='r', alpha=0.5, zorder=4) axes[0, k].set(ylabel=u'Noise σ (%s)' % unit, yscale='log', xlabel='Eigenvalue index', title=name, xlim=[0, len(s) - 1]) tight_layout(fig=fig_svd) plt_show(show) return fig_cov, fig_svd def plot_source_spectrogram(stcs, freq_bins, tmin=None, tmax=None, source_index=None, colorbar=False, show=True): import matplotlib.pyplot as plt if len(stcs) == 0: raise ValueError('cannot plot spectrogram if len(stcs) == 0') stc = stcs[0] if tmin is not None and tmin < stc.times[0]: raise ValueError('tmin cannot be smaller than the first time point ' 'provided in stcs') if tmax is not None and tmax > stc.times[-1] + stc.tstep: raise ValueError('tmax cannot be larger than the sum of the last time ' 'point and the time step, which are provided in stcs') if tmin is None: tmin = stc.times[0] if tmax is None: tmax = stc.times[-1] + stc.tstep time_bounds = np.arange(tmin, tmax + stc.tstep, stc.tstep) freq_bounds = sorted(set(np.ravel(freq_bins))) freq_ticks = copy.deepcopy(freq_bounds) source_power = [] for stc in stcs: stc = stc.copy() stc.crop(tmin, tmax - stc.tstep) source_power.append(stc.data) source_power = np.array(source_power) if source_index is None: source_index = np.unravel_index(source_power.argmax(), source_power.shape)[1] gap_bounds = [] for i in range(len(freq_bins) - 1): lower_bound = freq_bins[i][1] upper_bound = freq_bins[i + 1][0] if lower_bound != upper_bound: freq_bounds.remove(lower_bound) gap_bounds.append((lower_bound, upper_bound)) time_grid, freq_grid = np.meshgrid(time_bounds, freq_bounds) fig = plt.figure(figsize=(9, 6)) plt.pcolor(time_grid, freq_grid, source_power[:, source_index, :], cmap='Reds') ax = plt.gca() ax.set(title='Source power', xlabel='Time (s)', ylabel='Frequency (Hz)') time_tick_labels = [str(np.round(t, 2)) for t in time_bounds] n_skip = 1 + len(time_bounds) // 10 for i in range(len(time_bounds)): if i % n_skip != 0: time_tick_labels[i] = '' ax.set_xticks(time_bounds) ax.set_xticklabels(time_tick_labels) plt.xlim(time_bounds[0], time_bounds[-1]) plt.yscale('log') ax.set_yticks(freq_ticks) ax.set_yticklabels([np.round(freq, 2) for freq in freq_ticks]) plt.ylim(freq_bounds[0], freq_bounds[-1]) plt.grid(True, ls='-') if colorbar: plt.colorbar() tight_layout(fig=fig) for lower_bound, upper_bound in gap_bounds: plt.barh(lower_bound, time_bounds[-1] - time_bounds[0], upper_bound - lower_bound, time_bounds[0], color='#666666') plt_show(show) return fig def _plot_mri_contours(mri_fname, surfaces, src, orientation='coronal', slices=None, show=True, show_indices=False, show_orientation=False, img_output=False, width=512): import matplotlib.pyplot as plt from matplotlib import patheffects from .._freesurfer import _mri_orientation, _read_mri_info _check_option('orientation', orientation, ('coronal', 'axial', 'sagittal')) _, vox_mri_t, _, _, _, nim = _read_mri_info( mri_fname, units='mm', return_img=True) mri_vox_t = invert_transform(vox_mri_t)['trans'] del vox_mri_t (x, y, z), (flip_x, flip_y, flip_z), order = _mri_orientation( nim, orientation) transpose = x < y data = _get_img_fdata(nim) shift_x = data.shape[x] if flip_x < 0 else 0 shift_y = data.shape[y] if flip_y < 0 else 0 n_slices = data.shape[z] if slices is None: slices = np.round(np.linspace(0, n_slices - 1, 14)).astype(int)[1:-1] slices = np.atleast_1d(slices).copy() slices[slices < 0] += n_slices if not np.array_equal(np.sort(slices), slices) or slices.ndim != 1 or \ slices.size < 1 or slices[0] < 0 or slices[-1] >= n_slices or \ slices.dtype.kind not in 'iu': raise ValueError('slices must be a sorted 1D array of int with unique ' 'elements, at least one element, and no elements ' 'greater than %d, got %s' % (n_slices - 1, slices)) if flip_z < 0: slices = slices[::-1] surfs = list() for file_name, color in surfaces: surf = dict() surf['rr'], surf['tris'] = read_surface(file_name) surf['rr'] = apply_trans(mri_vox_t, surf['rr']) surfs.append((surf, color)) sources = list() if src is not None: _ensure_src(src, extra=' or None') if src[0]['coord_frame'] != FIFF.FIFFV_COORD_MRI: raise ValueError( 'Source space must be in MRI coordinates, got ' f'{_frame_to_str[src[0]["coord_frame"]]}') for src_ in src: points = src_['rr'][src_['inuse'].astype(bool)] sources.append(apply_trans(mri_vox_t, points * 1e3)) sources = np.concatenate(sources, axis=0) if img_output: n_col = n_axes = 1 dpi = 96 w = width / dpi figsize = (w, w / data.shape[x] * data.shape[y]) fig = _figure_agg(figsize=figsize, dpi=dpi, facecolor='k') ax = fig.add_axes([0, 0, 1, 1], frame_on=False, facecolor='k') axs = [ax] * len(slices) plt.close(fig) else: n_col = 4 fig, axs, _, _ = _prepare_trellis(len(slices), n_col) fig.set_facecolor('k') dpi = fig.get_dpi() n_axes = len(axs) bounds = np.concatenate( [[-np.inf], slices[:-1] + np.diff(slices) / 2., [np.inf]]) slicer = [slice(None)] * 3 ori_labels = dict(R='LR', A='PA', S='IS') xlabels, ylabels = ori_labels[order[0]], ori_labels[order[1]] path_effects = [patheffects.withStroke(linewidth=4, foreground="k", alpha=0.75)] out = list() if img_output else fig for ai, (ax, sl, lower, upper) in enumerate(zip( axs, slices, bounds[:-1], bounds[1:])): slicer[z] = sl dat = data[tuple(slicer)] dat = dat.T if transpose else dat dat = dat[::flip_y, ::flip_x] if img_output: ax.clear() ax.imshow(dat, cmap=plt.cm.gray, origin='lower') ax.set_autoscale_on(False) ax.axis('off') ax.set_aspect('equal') for surf, color in surfs: with warnings.catch_warnings(record=True): warnings.simplefilter('ignore') ax.tricontour(flip_x * surf['rr'][:, x] + shift_x, flip_y * surf['rr'][:, y] + shift_y, surf['tris'], surf['rr'][:, z], levels=[sl], colors=color, linewidths=1.0, zorder=1) if len(sources): in_slice = (sources[:, z] >= lower) & (sources[:, z] < upper) ax.scatter(flip_x * sources[in_slice, x] + shift_x, flip_y * sources[in_slice, y] + shift_y, marker='.', color='#FF00FF', s=1, zorder=2) if show_indices: ax.text(dat.shape[1] // 8 + 0.5, 0.5, str(sl), color='w', fontsize='x-small', va='bottom', ha='left') kwargs = dict( color='#66CCEE', fontsize='medium', path_effects=path_effects, family='monospace', clip_on=False, zorder=5, weight='bold') if show_orientation: if ai % n_col == 0: ax.text(0, dat.shape[0] / 2., xlabels[0], va='center', ha='left', **kwargs) if ai % n_col == n_col - 1 or ai == n_axes - 1: ax.text(dat.shape[1] - 1, dat.shape[0] / 2., xlabels[1], va='center', ha='right', **kwargs) if ai >= n_axes - n_col: ax.text(dat.shape[1] / 2., 0, ylabels[0], ha='center', va='bottom', **kwargs) if ai < n_col or n_col == 1: ax.text(dat.shape[1] / 2., dat.shape[0] - 1, ylabels[1], ha='center', va='top', **kwargs) if img_output: output = BytesIO() fig.savefig(output, bbox_inches='tight', pad_inches=0, format='png', dpi=dpi) out.append(base64.b64encode(output.getvalue()).decode('ascii')) fig.subplots_adjust(left=0., bottom=0., right=1., top=1., wspace=0., hspace=0.) plt_show(show, fig=fig) return out, flip_z def plot_bem(subject=None, subjects_dir=None, orientation='coronal', slices=None, brain_surfaces=None, src=None, show=True, show_indices=True, mri='T1.mgz', show_orientation=True): subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) mri_fname = _check_mri(mri, subject, subjects_dir) bem_path = op.join(subjects_dir, subject, 'bem') if not op.isdir(bem_path): raise IOError('Subject bem directory "%s" does not exist' % bem_path) surfaces = _get_bem_plotting_surfaces(bem_path) if brain_surfaces is not None: if isinstance(brain_surfaces, str): brain_surfaces = (brain_surfaces,) for surf_name in brain_surfaces: for hemi in ('lh', 'rh'): surf_fname = op.join(subjects_dir, subject, 'surf', hemi + '.' + surf_name) if op.exists(surf_fname): surfaces.append((surf_fname, '#00DD00')) else: raise IOError("Surface %s does not exist." % surf_fname) if isinstance(src, str): if not op.exists(src): src_ = op.join(subjects_dir, subject, 'bem', src) if op.exists(src_): src = src_ else: raise IOError("%s does not exist" % src) src = read_source_spaces(src) elif src is not None and not isinstance(src, SourceSpaces): raise TypeError("src needs to be None, str or SourceSpaces instance, " "not %s" % repr(src)) if len(surfaces) == 0: raise IOError('No surface files found. Surface files must end with ' 'inner_skull.surf, outer_skull.surf or outer_skin.surf') return _plot_mri_contours(mri_fname, surfaces, src, orientation, slices, show, show_indices, show_orientation)[0] def _get_bem_plotting_surfaces(bem_path): surfaces = [] for surf_name, color in (('*inner_skull', '#FF0000'), ('*outer_skull', '#FFFF00'), ('*outer_skin', '#FFAA80')): surf_fname = glob(op.join(bem_path, surf_name + '.surf')) if len(surf_fname) > 0: surf_fname = surf_fname[0] logger.info("Using surface: %s" % surf_fname) surfaces.append((surf_fname, color)) return surfaces @verbose def plot_events(events, sfreq=None, first_samp=0, color=None, event_id=None, axes=None, equal_spacing=True, show=True, on_missing='raise', verbose=None): if sfreq is None: sfreq = 1.0 xlabel = 'Samples' else: xlabel = 'Time (s)' events = np.asarray(events) if len(events) == 0: raise ValueError('No events in events array, cannot plot.') unique_events = np.unique(events[:, 2]) if event_id is not None: event_id_rev = {v: k for k, v in event_id.items()} conditions, unique_events_id = zip(*sorted(event_id.items(), key=lambda x: x[1])) keep = np.ones(len(unique_events_id), bool) for ii, this_event in enumerate(unique_events_id): if this_event not in unique_events: msg = f'{this_event} from event_id is not present in events.' _on_missing(on_missing, msg) keep[ii] = False conditions = [cond for cond, k in zip(conditions, keep) if k] unique_events_id = [id_ for id_, k in zip(unique_events_id, keep) if k] if len(unique_events_id) == 0: raise RuntimeError('No usable event IDs found') for this_event in unique_events: if this_event not in unique_events_id: warn('event %s missing from event_id will be ignored' % this_event) else: unique_events_id = unique_events color = _handle_event_colors(color, unique_events, event_id) import matplotlib.pyplot as plt fig = None if axes is None: fig = plt.figure() ax = axes if axes else plt.gca() unique_events_id = np.array(unique_events_id) min_event = np.min(unique_events_id) max_event = np.max(unique_events_id) max_x = (events[np.in1d(events[:, 2], unique_events_id), 0].max() - first_samp) / sfreq handles, labels = list(), list() for idx, ev in enumerate(unique_events_id): ev_mask = events[:, 2] == ev count = ev_mask.sum() if count == 0: continue y = np.full(count, idx + 1 if equal_spacing else events[ev_mask, 2][0]) if event_id is not None: event_label = '%s (%s)' % (event_id_rev[ev], count) else: event_label = 'N=%d' % (count,) labels.append(event_label) kwargs = {} if ev in color: kwargs['color'] = color[ev] handles.append( ax.plot((events[ev_mask, 0] - first_samp) / sfreq, y, '.', clip_on=False, **kwargs)[0]) if equal_spacing: ax.set_ylim(0, unique_events_id.size + 1) ax.set_yticks(1 + np.arange(unique_events_id.size)) ax.set_yticklabels(unique_events_id) else: ax.set_ylim([min_event - 1, max_event + 1]) ax.set(xlabel=xlabel, ylabel='Event id', xlim=[0, max_x]) ax.grid(True) fig = fig if fig is not None else plt.gcf() handles, labels = handles[::-1], labels[::-1] box = ax.get_position() factor = 0.8 if event_id is not None else 0.9 ax.set_position([box.x0, box.y0, box.width * factor, box.height]) ax.legend(handles, labels, loc='center left', bbox_to_anchor=(1, 0.5), fontsize='small') fig.canvas.draw() plt_show(show) return fig def _get_presser(fig): import matplotlib callbacks = fig.canvas.callbacks.callbacks['button_press_event'] func = None for key, val in callbacks.items(): if LooseVersion(matplotlib.__version__) >= '3': func = val() else: func = val.func if func.__class__.__name__ == 'partial': break else: func = None assert func is not None return func def plot_dipole_amplitudes(dipoles, colors=None, show=True): import matplotlib.pyplot as plt if colors is None: colors = cycle(_get_color_list()) fig, ax = plt.subplots(1, 1) xlim = [np.inf, -np.inf] for dip, color in zip(dipoles, colors): ax.plot(dip.times, dip.amplitude * 1e9, color=color, linewidth=1.5) xlim[0] = min(xlim[0], dip.times[0]) xlim[1] = max(xlim[1], dip.times[-1]) ax.set(xlim=xlim, xlabel='Time (s)', ylabel='Amplitude (nAm)') if show: fig.show(warn=False) return fig def adjust_axes(axes, remove_spines=('top', 'right'), grid=True): axes = [axes] if not isinstance(axes, (list, tuple, np.ndarray)) else axes for ax in axes: if grid: ax.grid(zorder=0) for key in remove_spines: ax.spines[key].set_visible(False) def _filter_ticks(lims, fscale): if fscale == 'linear': return None, None lims = np.array(lims) ticks = list() if lims[1] > 20 * lims[0]: base = np.array([1, 2, 4]) else: base = np.arange(1, 11) for exp in range(int(np.floor(np.log10(lims[0]))), int(np.floor(np.log10(lims[1]))) + 1): ticks += (base * (10 ** exp)).tolist() ticks = np.array(ticks) ticks = ticks[(ticks >= lims[0]) & (ticks <= lims[1])] ticklabels = [('%g' if t < 1 else '%d') % t for t in ticks] return ticks, ticklabels def _get_flim(flim, fscale, freq, sfreq=None): if flim is None: if freq is None: flim = [0.1 if fscale == 'log' else 0., sfreq / 2.] else: if fscale == 'linear': flim = [freq[0]] else: flim = [freq[0] if freq[0] > 0 else 0.1 * freq[1]] flim += [freq[-1]] if fscale == 'log': if flim[0] <= 0: raise ValueError('flim[0] must be positive, got %s' % flim[0]) elif flim[0] < 0: raise ValueError('flim[0] must be non-negative, got %s' % flim[0]) return flim def _check_fscale(fscale): if not isinstance(fscale, str) or fscale not in ('log', 'linear'): raise ValueError('fscale must be "log" or "linear", got %s' % (fscale,)) _DEFAULT_ALIM = (-80, 10) def plot_filter(h, sfreq, freq=None, gain=None, title=None, color='#1f77b4', flim=None, fscale='log', alim=_DEFAULT_ALIM, show=True, compensate=False, plot=('time', 'magnitude', 'delay'), axes=None): from scipy.signal import ( freqz, group_delay, lfilter, filtfilt, sosfilt, sosfiltfilt) import matplotlib.pyplot as plt sfreq = float(sfreq) _check_option('fscale', fscale, ['log', 'linear']) if isinstance(plot, str): plot = [plot] for xi, x in enumerate(plot): _check_option('plot[%d]' % xi, x, ('magnitude', 'delay', 'time')) flim = _get_flim(flim, fscale, freq, sfreq) if fscale == 'log': omega = np.logspace(np.log10(flim[0]), np.log10(flim[1]), 1000) else: omega = np.linspace(flim[0], flim[1], 1000) xticks, xticklabels = _filter_ticks(flim, fscale) omega /= sfreq / (2 * np.pi) if isinstance(h, dict): H = np.ones(len(omega), np.complex128) gd = np.zeros(len(omega)) for section in h['sos']: this_H = freqz(section[:3], section[3:], omega)[1] H *= this_H if compensate: H *= this_H.conj() else: with warnings.catch_warnings(record=True): warnings.simplefilter('ignore') gd += group_delay((section[:3], section[3:]), omega)[1] n = estimate_ringing_samples(h['sos']) delta = np.zeros(n) delta[0] = 1 if compensate: delta = np.pad(delta, [(n - 1, 0)], 'constant') func = sosfiltfilt gd += (len(delta) - 1) // 2 else: func = sosfilt h = func(h['sos'], delta) else: H = freqz(h['b'], h['a'], omega)[1] if compensate: H *= H.conj() with warnings.catch_warnings(record=True): warnings.simplefilter('ignore') gd = group_delay((h['b'], h['a']), omega)[1] if compensate: gd += group_delay(h['b'].conj(), h['a'].conj(), omega)[1] n = estimate_ringing_samples((h['b'], h['a'])) delta = np.zeros(n) delta[0] = 1 if compensate: delta = np.pad(delta, [(n - 1, 0)], 'constant') func = filtfilt else: func = lfilter h = func(h['b'], h['a'], delta) if title is None: title = 'SOS (IIR) filter' if compensate: title += ' (forward-backward)' else: H = freqz(h, worN=omega)[1] with warnings.catch_warnings(record=True): warnings.simplefilter('ignore') gd = group_delay((h, [1.]), omega)[1] title = 'FIR filter' if title is None else title if compensate: title += ' (delay-compensated)' fig = None if axes is None: fig, axes = plt.subplots(len(plot), 1) if isinstance(axes, plt.Axes): axes = [axes] elif isinstance(axes, np.ndarray): axes = list(axes) if fig is None: fig = axes[0].get_figure() if len(axes) != len(plot): raise ValueError('Length of axes (%d) must be the same as number of ' 'requested filter properties (%d)' % (len(axes), len(plot))) t = np.arange(len(h)) dlim = np.abs(t).max() / 2. dlim = [-dlim, dlim] if compensate: n_shift = (len(h) - 1) // 2 t -= n_shift assert t[0] == -t[-1] gd -= n_shift t = t / sfreq gd = gd / sfreq f = omega * sfreq / (2 * np.pi) sl = slice(0 if fscale == 'linear' else 1, None, None) mag = 10 * np.log10(np.maximum((H * H.conj()).real, 1e-20)) if 'time' in plot: ax_time_idx = np.where([p == 'time' for p in plot])[0][0] axes[ax_time_idx].plot(t, h, color=color) axes[ax_time_idx].set(xlim=t[[0, -1]], xlabel='Time (s)', ylabel='Amplitude', title=title) if 'magnitude' in plot: ax_mag_idx = np.where([p == 'magnitude' for p in plot])[0][0] axes[ax_mag_idx].plot(f[sl], mag[sl], color=color, linewidth=2, zorder=4) if freq is not None and gain is not None: plot_ideal_filter(freq, gain, axes[ax_mag_idx], fscale=fscale, show=False) axes[ax_mag_idx].set(ylabel='Magnitude (dB)', xlabel='', xscale=fscale) if xticks is not None: axes[ax_mag_idx].set(xticks=xticks) axes[ax_mag_idx].set(xticklabels=xticklabels) axes[ax_mag_idx].set(xlim=flim, ylim=alim, xlabel='Frequency (Hz)', ylabel='Amplitude (dB)') if 'delay' in plot: ax_delay_idx = np.where([p == 'delay' for p in plot])[0][0] axes[ax_delay_idx].plot(f[sl], gd[sl], color=color, linewidth=2, zorder=4) for start, stop in zip(*_mask_to_onsets_offsets(mag <= -39.9)): axes[ax_delay_idx].axvspan(f[start], f[stop - 1], facecolor='k', alpha=0.05, zorder=5) axes[ax_delay_idx].set(xlim=flim, ylabel='Group delay (s)', xlabel='Frequency (Hz)', xscale=fscale) if xticks is not None: axes[ax_delay_idx].set(xticks=xticks) axes[ax_delay_idx].set(xticklabels=xticklabels) axes[ax_delay_idx].set(xlim=flim, ylim=dlim, xlabel='Frequency (Hz)', ylabel='Delay (s)') adjust_axes(axes) tight_layout() plt_show(show) return fig def plot_ideal_filter(freq, gain, axes=None, title='', flim=None, fscale='log', alim=_DEFAULT_ALIM, color='r', alpha=0.5, linestyle='--', show=True): import matplotlib.pyplot as plt my_freq, my_gain = list(), list() if freq[0] != 0: raise ValueError('freq should start with DC (zero) and end with ' 'Nyquist, but got %s for DC' % (freq[0],)) freq = np.array(freq) _check_option('fscale', fscale, ['log', 'linear']) if fscale == 'log': freq[0] = 0.1 * freq[1] if flim is None else min(flim[0], freq[1]) flim = _get_flim(flim, fscale, freq) transitions = list() for ii in range(len(freq)): if ii < len(freq) - 1 and gain[ii] != gain[ii + 1]: transitions += [[freq[ii], freq[ii + 1]]] my_freq += np.linspace(freq[ii], freq[ii + 1], 20, endpoint=False).tolist() my_gain += np.linspace(gain[ii], gain[ii + 1], 20, endpoint=False).tolist() else: my_freq.append(freq[ii]) my_gain.append(gain[ii]) my_gain = 10 * np.log10(np.maximum(my_gain, 10 ** (alim[0] / 10.))) if axes is None: axes = plt.subplots(1)[1] for transition in transitions: axes.axvspan(*transition, color=color, alpha=0.1) axes.plot(my_freq, my_gain, color=color, linestyle=linestyle, alpha=0.5, linewidth=4, zorder=3) xticks, xticklabels = _filter_ticks(flim, fscale) axes.set(ylim=alim, xlabel='Frequency (Hz)', ylabel='Amplitude (dB)', xscale=fscale) if xticks is not None: axes.set(xticks=xticks) axes.set(xticklabels=xticklabels) axes.set(xlim=flim) if title: axes.set(title=title) adjust_axes(axes) tight_layout() plt_show(show) return axes.figure def _handle_event_colors(color_dict, unique_events, event_id): default_colors = dict(zip(sorted(unique_events), cycle(_get_color_list()))) if color_dict is None: if len(unique_events) > len(_get_color_list()): warn('More events than default colors available. You should pass ' 'a list of unique colors.') else: custom_colors = dict() for key, color in color_dict.items(): if key in unique_events: custom_colors[key] = color elif key in event_id: custom_colors[event_id[key]] = color else: warn('Event ID %s is in the color dict but is not ' 'present in events or event_id.' % str(key)) unassigned = sorted(set(unique_events) - set(custom_colors)) if len(unassigned): unassigned_str = ', '.join(str(e) for e in unassigned) warn('Color was not assigned for event%s %s. Default colors will ' 'be used.' % (_pl(unassigned), unassigned_str)) default_colors.update(custom_colors) return default_colors @fill_doc def plot_csd(csd, info=None, mode='csd', colorbar=True, cmap=None, n_cols=None, show=True): import matplotlib.pyplot as plt if mode not in ['csd', 'coh']: raise ValueError('"mode" should be either "csd" or "coh".') if info is not None: info_ch_names = info['ch_names'] sel_eeg = pick_types(info, meg=False, eeg=True, ref_meg=False, exclude=[]) sel_mag = pick_types(info, meg='mag', eeg=False, ref_meg=False, exclude=[]) sel_grad = pick_types(info, meg='grad', eeg=False, ref_meg=False, exclude=[]) idx_eeg = [csd.ch_names.index(info_ch_names[c]) for c in sel_eeg if info_ch_names[c] in csd.ch_names] idx_mag = [csd.ch_names.index(info_ch_names[c]) for c in sel_mag if info_ch_names[c] in csd.ch_names] idx_grad = [csd.ch_names.index(info_ch_names[c]) for c in sel_grad if info_ch_names[c] in csd.ch_names] indices = [idx_eeg, idx_mag, idx_grad] titles = ['EEG', 'Magnetometers', 'Gradiometers'] if mode == 'csd': units = dict(eeg='µV²', grad='fT²/cm²', mag='fT²') scalings = dict(eeg=1e12, grad=1e26, mag=1e30) else: indices = [np.arange(len(csd.ch_names))] if mode == 'csd': titles = ['Cross-spectral density'] units = dict() scalings = dict() elif mode == 'coh': titles = ['Coherence'] n_freqs = len(csd.frequencies) if n_cols is None: n_cols = int(np.ceil(np.sqrt(n_freqs))) n_rows = int(np.ceil(n_freqs / float(n_cols))) figs = [] for ind, title, ch_type in zip(indices, titles, ['eeg', 'mag', 'grad']): if len(ind) == 0: continue fig, axes = plt.subplots(n_rows, n_cols, squeeze=False, figsize=(2 * n_cols + 1, 2.2 * n_rows)) csd_mats = [] for i in range(len(csd.frequencies)): cm = csd.get_data(index=i)[ind][:, ind] if mode == 'csd': cm = np.abs(cm) * scalings.get(ch_type, 1) elif mode == 'coh': psd = np.diag(cm).real cm = np.abs(cm) ** 2 / psd[np.newaxis, :] / psd[:, np.newaxis] csd_mats.append(cm) vmax = np.max(csd_mats) for i, (freq, mat) in enumerate(zip(csd.frequencies, csd_mats)): ax = axes[i // n_cols][i % n_cols] im = ax.imshow(mat, interpolation='nearest', cmap=cmap, vmin=0, vmax=vmax) ax.set_xticks([]) ax.set_yticks([]) if csd._is_sum: ax.set_title('%.1f-%.1f Hz.' % (np.min(freq), np.max(freq))) else: ax.set_title('%.1f Hz.' % freq) plt.suptitle(title) plt.subplots_adjust(top=0.8) if colorbar: cb = plt.colorbar(im, ax=[a for ax_ in axes for a in ax_]) if mode == 'csd': label = u'CSD' if ch_type in units: label += u' (%s)' % units[ch_type] cb.set_label(label) elif mode == 'coh': cb.set_label('Coherence') figs.append(fig) plt_show(show) return figs def plot_chpi_snr(snr_dict, axes=None): import matplotlib.pyplot as plt valid_keys = list(snr_dict)[2:] titles = dict(snr='SNR', power='cHPI power', resid='Residual variance') full_names = dict(mag='magnetometers', grad='gradiometers') axes_was_none = axes is None if axes_was_none: fig, axes = plt.subplots(len(valid_keys), 1, sharex=True) else: fig = axes[0].get_figure() if len(axes) != len(valid_keys): raise ValueError(f'axes must be a list of {len(valid_keys)} axes, got ' f'length {len(axes)} ({axes}).') fig.set_size_inches(10, 10) legend_labels_exist = False for key, ax in zip(valid_keys, axes): ch_type, kind = key.split('_') scaling = 1 if kind == 'snr' else DEFAULTS['scalings'][ch_type] plot_kwargs = dict(color='k') if kind == 'resid' else dict() lines = ax.plot(snr_dict['times'], snr_dict[key] * scaling ** 2, **plot_kwargs) if not legend_labels_exist: for line, freq in zip(lines, snr_dict['freqs']): line.set_label(f'{freq} Hz') legend_labels_exist = True unit = DEFAULTS['units'][ch_type] unit = f'({unit})' if '/' in unit else unit set_kwargs = dict(title=f'{titles[kind]}, {full_names[ch_type]}', ylabel='dB' if kind == 'snr' else f'{unit}²') if not axes_was_none: set_kwargs.update(xlabel='Time (s)') ax.set(**set_kwargs) if axes_was_none: ax.set(xlabel='Time (s)') fig.align_ylabels() fig.subplots_adjust(left=0.1, right=0.825, bottom=0.075, top=0.95, hspace=0.7) fig.legend(loc='right', title='cHPI frequencies') return fig
true
true
f72d193485085f4417f86600a03b9ba6200ca275
3,529
py
Python
bindings/python/ensmallen/datasets/string/alteromonadaceaebacteriumbs31.py
AnacletoLAB/ensmallen_graph
b2c1b18fb1e5801712852bcc239f239e03076f09
[ "MIT" ]
5
2021-02-17T00:44:45.000Z
2021-08-09T16:41:47.000Z
bindings/python/ensmallen/datasets/string/alteromonadaceaebacteriumbs31.py
AnacletoLAB/ensmallen_graph
b2c1b18fb1e5801712852bcc239f239e03076f09
[ "MIT" ]
18
2021-01-07T16:47:39.000Z
2021-08-12T21:51:32.000Z
bindings/python/ensmallen/datasets/string/alteromonadaceaebacteriumbs31.py
AnacletoLAB/ensmallen
b2c1b18fb1e5801712852bcc239f239e03076f09
[ "MIT" ]
3
2021-01-14T02:20:59.000Z
2021-08-04T19:09:52.000Z
""" This file offers the methods to automatically retrieve the graph Alteromonadaceae bacterium Bs31. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ from typing import Dict from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph from ...ensmallen import Graph # pylint: disable=import-error def AlteromonadaceaeBacteriumBs31( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph: """Return new instance of the Alteromonadaceae bacterium Bs31 graph. The graph is automatically retrieved from the STRING repository. Parameters ------------------- directed: bool = False Wether to load the graph as directed or undirected. By default false. preprocess: bool = True Whether to preprocess the graph to be loaded in optimal time and memory. load_nodes: bool = True, Whether to load the nodes vocabulary or treat the nodes simply as a numeric range. verbose: int = 2, Wether to show loading bars during the retrieval and building of the graph. cache: bool = True Whether to use cache, i.e. download files only once and preprocess them only once. cache_path: str = "graphs" Where to store the downloaded graphs. version: str = "links.v11.5" The version of the graph to retrieve. The available versions are: - homology.v11.5 - physical.links.v11.5 - links.v11.5 additional_graph_kwargs: Dict Additional graph kwargs. Returns ----------------------- Instace of Alteromonadaceae bacterium Bs31 graph. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ return AutomaticallyRetrievedGraph( graph_name="AlteromonadaceaeBacteriumBs31", repository="string", version=version, directed=directed, preprocess=preprocess, load_nodes=load_nodes, verbose=verbose, cache=cache, cache_path=cache_path, additional_graph_kwargs=additional_graph_kwargs )()
33.609524
223
0.682063
from typing import Dict from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph from ...ensmallen import Graph def AlteromonadaceaeBacteriumBs31( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph: return AutomaticallyRetrievedGraph( graph_name="AlteromonadaceaeBacteriumBs31", repository="string", version=version, directed=directed, preprocess=preprocess, load_nodes=load_nodes, verbose=verbose, cache=cache, cache_path=cache_path, additional_graph_kwargs=additional_graph_kwargs )()
true
true
f72d19bd7e21d68363282be4231a798cef9d93e4
716
py
Python
venv/Lib/site-packages/marshmallow/__init__.py
kakinpe1u/Riki
2812ce3279aacbd759fcaa096bb2cf2658195b7b
[ "BSD-3-Clause" ]
null
null
null
venv/Lib/site-packages/marshmallow/__init__.py
kakinpe1u/Riki
2812ce3279aacbd759fcaa096bb2cf2658195b7b
[ "BSD-3-Clause" ]
1
2021-06-02T01:17:03.000Z
2021-06-02T01:17:03.000Z
venv/Lib/site-packages/marshmallow/__init__.py
kakinpe1u/Riki
2812ce3279aacbd759fcaa096bb2cf2658195b7b
[ "BSD-3-Clause" ]
null
null
null
from marshmallow.schema import Schema, SchemaOpts from . import fields from marshmallow.decorators import ( pre_dump, post_dump, pre_load, post_load, validates, validates_schema, ) from marshmallow.utils import EXCLUDE, INCLUDE, RAISE, pprint, missing from marshmallow.exceptions import ValidationError from distutils.version import LooseVersion __version__ = "3.1.0" __version_info__ = tuple(LooseVersion(__version__).version) __all__ = [ "EXCLUDE", "INCLUDE", "RAISE", "Schema", "SchemaOpts", "fields", "validates", "validates_schema", "pre_dump", "post_dump", "pre_load", "post_load", "pprint", "ValidationError", "missing", ]
20.457143
70
0.685754
from marshmallow.schema import Schema, SchemaOpts from . import fields from marshmallow.decorators import ( pre_dump, post_dump, pre_load, post_load, validates, validates_schema, ) from marshmallow.utils import EXCLUDE, INCLUDE, RAISE, pprint, missing from marshmallow.exceptions import ValidationError from distutils.version import LooseVersion __version__ = "3.1.0" __version_info__ = tuple(LooseVersion(__version__).version) __all__ = [ "EXCLUDE", "INCLUDE", "RAISE", "Schema", "SchemaOpts", "fields", "validates", "validates_schema", "pre_dump", "post_dump", "pre_load", "post_load", "pprint", "ValidationError", "missing", ]
true
true
f72d19fb07ebb13290b184d52af272ca902172d8
3,406
py
Python
python/generic/parallel-processes.py
lotharwissler/bioinformatics
83a53771222ecb0759e3b4bfa2018d2cd7647643
[ "MIT" ]
10
2016-01-13T00:39:30.000Z
2020-11-30T05:56:19.000Z
python/generic/parallel-processes.py
lotharwissler/bioinformatics
83a53771222ecb0759e3b4bfa2018d2cd7647643
[ "MIT" ]
1
2017-02-09T22:46:49.000Z
2017-02-09T22:46:49.000Z
python/generic/parallel-processes.py
lotharwissler/bioinformatics
83a53771222ecb0759e3b4bfa2018d2cd7647643
[ "MIT" ]
10
2015-10-09T00:29:16.000Z
2019-06-09T05:32:15.000Z
#!/usr/bin/python import sys, os import math, time import threading import getopt # comand line argument handling from low import * # ============================================================================= def show_help(): """ displays the program parameter list and usage information """ stdout( "usage: " + sys.argv[0] + " -f <path> -n " ) stdout( " " ) stdout( " option description" ) stdout( " -h help (this text here)" ) stdout( " -f file that contains all system calls, one per line" ) stdout( " -n number of processes to be run in parallel" ) stdout( " " ) sys.exit(1) # ============================================================================= def handle_arguments(): """ verifies the presence of all necessary arguments and returns the data dir """ if len ( sys.argv ) == 1: stderr( "no arguments provided." ) show_help() try: # check for the right arguments keys, values = getopt.getopt( sys.argv[1:], "hf:n:" ) except getopt.GetoptError: stderr( "invalid arguments provided." ) show_help() args = {} for key, value in keys: if key == '-f': args['file'] = value if key == '-n': args['ncpu'] = int(value) if not args.has_key('file'): stderr( "process file missing." ) show_help() if not file_exists( args.get('file') ): stderr( "process file does not exist." ) show_help() if not args.has_key('ncpu'): stderr( "number of CPUs to use is missing." ) show_help() return args # ============================================================================= def get_jobs( file ): jobs = [] fo = open( file ) for line in fo: if not line.startswith("#"): jobs.append(line.rstrip()) fo.close() return jobs # ============================================================================= class MyThread( threading.Thread ): def set_command(self, command): self.command = command def run(self): os.system(self.command) # ============================================================================= # ============================================================================= def main( args ): jobs = get_jobs( args.get('file') ) totaljobs = len(jobs) infomsg( "Collected %s jobs queued | will distribute them among %s CPUs" %(len(jobs), args.get('ncpu')) ) start_time = time.time() while threading.activeCount() > 1 or len(jobs) > 0: # check existing threads: still running? # fill up all remaining slots elapsed = time.time() - start_time while threading.activeCount() <= args.get('ncpu') and len(jobs) > 0: # start new thread cmd = jobs.pop(0) t = MyThread() t.set_command( cmd ) t.start() remain = elapsed / (totaljobs - len(jobs) + (threading.activeCount() -1)) * len(jobs) info( "\telapsed: %s\tremaining: %s\t[ jobs done: %s | remain: %s | active: %s ] " % (humanize_time(elapsed), humanize_time(remain), totaljobs - len(jobs) - (threading.activeCount() -1), len(jobs), threading.activeCount() -1) ) time.sleep(0.2) info( "\n" ) infomsg( "DONE." ) # ============================================================================= # === MAIN ==================================================================== # ============================================================================= args = handle_arguments( ) main( args )
31.831776
231
0.490018
import sys, os import math, time import threading import getopt from low import * def show_help(): stdout( "usage: " + sys.argv[0] + " -f <path> -n " ) stdout( " " ) stdout( " option description" ) stdout( " -h help (this text here)" ) stdout( " -f file that contains all system calls, one per line" ) stdout( " -n number of processes to be run in parallel" ) stdout( " " ) sys.exit(1) def handle_arguments(): if len ( sys.argv ) == 1: stderr( "no arguments provided." ) show_help() try: keys, values = getopt.getopt( sys.argv[1:], "hf:n:" ) except getopt.GetoptError: stderr( "invalid arguments provided." ) show_help() args = {} for key, value in keys: if key == '-f': args['file'] = value if key == '-n': args['ncpu'] = int(value) if not args.has_key('file'): stderr( "process file missing." ) show_help() if not file_exists( args.get('file') ): stderr( "process file does not exist." ) show_help() if not args.has_key('ncpu'): stderr( "number of CPUs to use is missing." ) show_help() return args def get_jobs( file ): jobs = [] fo = open( file ) for line in fo: if not line.startswith("#"): jobs.append(line.rstrip()) fo.close() return jobs class MyThread( threading.Thread ): def set_command(self, command): self.command = command def run(self): os.system(self.command) def main( args ): jobs = get_jobs( args.get('file') ) totaljobs = len(jobs) infomsg( "Collected %s jobs queued | will distribute them among %s CPUs" %(len(jobs), args.get('ncpu')) ) start_time = time.time() while threading.activeCount() > 1 or len(jobs) > 0: elapsed = time.time() - start_time while threading.activeCount() <= args.get('ncpu') and len(jobs) > 0: cmd = jobs.pop(0) t = MyThread() t.set_command( cmd ) t.start() remain = elapsed / (totaljobs - len(jobs) + (threading.activeCount() -1)) * len(jobs) info( "\telapsed: %s\tremaining: %s\t[ jobs done: %s | remain: %s | active: %s ] " % (humanize_time(elapsed), humanize_time(remain), totaljobs - len(jobs) - (threading.activeCount() -1), len(jobs), threading.activeCount() -1) ) time.sleep(0.2) info( "\n" ) infomsg( "DONE." ) args = handle_arguments( ) main( args )
true
true
f72d1b20c6a6249fbd56850720d0cd584b7fb599
2,809
py
Python
env/lib/python3.6/site-packages/torch/optim/asgd.py
bopopescu/smart_contracts7
40a487cb3843e86ab5e4cb50b1aafa2095f648cd
[ "Apache-2.0" ]
null
null
null
env/lib/python3.6/site-packages/torch/optim/asgd.py
bopopescu/smart_contracts7
40a487cb3843e86ab5e4cb50b1aafa2095f648cd
[ "Apache-2.0" ]
null
null
null
env/lib/python3.6/site-packages/torch/optim/asgd.py
bopopescu/smart_contracts7
40a487cb3843e86ab5e4cb50b1aafa2095f648cd
[ "Apache-2.0" ]
1
2020-07-24T17:53:25.000Z
2020-07-24T17:53:25.000Z
import math import torch from .optimizer import Optimizer class ASGD(Optimizer): """Implements Averaged Stochastic Gradient Descent. It has been proposed in `Acceleration of stochastic approximation by averaging`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-2) lambd (float, optional): decay term (default: 1e-4) alpha (float, optional): power for eta update (default: 0.75) t0 (float, optional): point at which to start averaging (default: 1e6) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) .. _Acceleration of stochastic approximation by averaging: http://dl.acm.org/citation.cfm?id=131098 """ def __init__(self, params, lr=1e-2, lambd=1e-4, alpha=0.75, t0=1e6, weight_decay=0): defaults = dict(lr=lr, lambd=lambd, alpha=alpha, t0=t0, weight_decay=weight_decay) super(ASGD, self).__init__(params, defaults) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('ASGD does not support sparse gradients') state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 state['eta'] = group['lr'] state['mu'] = 1 state['ax'] = torch.zeros_like(p.data) state['step'] += 1 if group['weight_decay'] != 0: grad = grad.add(group['weight_decay'], p.data) # decay term p.data.mul_(1 - group['lambd'] * state['eta']) # update parameter p.data.add_(-state['eta'], grad) # averaging if state['mu'] != 1: state['ax'].add_(p.data.sub(state['ax']).mul(state['mu'])) else: state['ax'].copy_(p.data) # update eta and mu state['eta'] = (group['lr'] / math.pow((1 + group['lambd'] * group['lr'] * state['step']), group['alpha'])) state['mu'] = 1 / max(1, state['step'] - group['t0']) return loss
35.1125
109
0.521538
import math import torch from .optimizer import Optimizer class ASGD(Optimizer): def __init__(self, params, lr=1e-2, lambd=1e-4, alpha=0.75, t0=1e6, weight_decay=0): defaults = dict(lr=lr, lambd=lambd, alpha=alpha, t0=t0, weight_decay=weight_decay) super(ASGD, self).__init__(params, defaults) def step(self, closure=None): loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('ASGD does not support sparse gradients') state = self.state[p] if len(state) == 0: state['step'] = 0 state['eta'] = group['lr'] state['mu'] = 1 state['ax'] = torch.zeros_like(p.data) state['step'] += 1 if group['weight_decay'] != 0: grad = grad.add(group['weight_decay'], p.data) p.data.mul_(1 - group['lambd'] * state['eta']) p.data.add_(-state['eta'], grad) if state['mu'] != 1: state['ax'].add_(p.data.sub(state['ax']).mul(state['mu'])) else: state['ax'].copy_(p.data) state['eta'] = (group['lr'] / math.pow((1 + group['lambd'] * group['lr'] * state['step']), group['alpha'])) state['mu'] = 1 / max(1, state['step'] - group['t0']) return loss
true
true
f72d1b37a5cef82cf5cf152d89c95f2474d1e422
14,941
py
Python
ixnetwork_restpy/testplatform/sessions/ixnetwork/quicktest/asymmetricthroughput_b9e3c6717e2faf761c693cccff9c71b8.py
rfrye-github/ixnetwork_restpy
23eeb24b21568a23d3f31bbd72814ff55eb1af44
[ "MIT" ]
null
null
null
ixnetwork_restpy/testplatform/sessions/ixnetwork/quicktest/asymmetricthroughput_b9e3c6717e2faf761c693cccff9c71b8.py
rfrye-github/ixnetwork_restpy
23eeb24b21568a23d3f31bbd72814ff55eb1af44
[ "MIT" ]
null
null
null
ixnetwork_restpy/testplatform/sessions/ixnetwork/quicktest/asymmetricthroughput_b9e3c6717e2faf761c693cccff9c71b8.py
rfrye-github/ixnetwork_restpy
23eeb24b21568a23d3f31bbd72814ff55eb1af44
[ "MIT" ]
null
null
null
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class AsymmetricThroughput(Base): """Signifies the asymmetric throughput. The AsymmetricThroughput class encapsulates a list of asymmetricThroughput resources that are managed by the user. A list of resources can be retrieved from the server using the AsymmetricThroughput.find() method. The list can be managed by using the AsymmetricThroughput.add() and AsymmetricThroughput.remove() methods. """ __slots__ = () _SDM_NAME = 'asymmetricThroughput' _SDM_ATT_MAP = { 'ForceApplyQTConfig': 'forceApplyQTConfig', 'InputParameters': 'inputParameters', 'Mode': 'mode', 'Name': 'name', } def __init__(self, parent): super(AsymmetricThroughput, self).__init__(parent) @property def LearnFrames(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.learnframes_aff5042528d11d6e314f527665dc38f2.LearnFrames): An instance of the LearnFrames class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.learnframes_aff5042528d11d6e314f527665dc38f2 import LearnFrames return LearnFrames(self)._select() @property def PassCriteria(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.passcriteria_a2cbb052e2ad975c0acd3e8a31c8d5ca.PassCriteria): An instance of the PassCriteria class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.passcriteria_a2cbb052e2ad975c0acd3e8a31c8d5ca import PassCriteria return PassCriteria(self)._select() @property def Results(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.results_23583c0cce1dabf7b75fe7d2ae18cfc4.Results): An instance of the Results class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.results_23583c0cce1dabf7b75fe7d2ae18cfc4 import Results return Results(self)._select() @property def TestConfig(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.testconfig_81bab7c0e318724192d10cc0cd42f862.TestConfig): An instance of the TestConfig class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.testconfig_81bab7c0e318724192d10cc0cd42f862 import TestConfig return TestConfig(self)._select() @property def TrafficSelection(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.trafficselection_206d3c7fd8956cf41e032f8402bda1d7.TrafficSelection): An instance of the TrafficSelection class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.trafficselection_206d3c7fd8956cf41e032f8402bda1d7 import TrafficSelection return TrafficSelection(self) @property def ForceApplyQTConfig(self): """ Returns ------- - bool: Apply QT config """ return self._get_attribute(self._SDM_ATT_MAP['ForceApplyQTConfig']) @ForceApplyQTConfig.setter def ForceApplyQTConfig(self, value): self._set_attribute(self._SDM_ATT_MAP['ForceApplyQTConfig'], value) @property def InputParameters(self): """ Returns ------- - str: Input Parameters """ return self._get_attribute(self._SDM_ATT_MAP['InputParameters']) @InputParameters.setter def InputParameters(self, value): self._set_attribute(self._SDM_ATT_MAP['InputParameters'], value) @property def Mode(self): """ Returns ------- - str(existingMode | newMode): Test mode """ return self._get_attribute(self._SDM_ATT_MAP['Mode']) @Mode.setter def Mode(self, value): self._set_attribute(self._SDM_ATT_MAP['Mode'], value) @property def Name(self): """ Returns ------- - str: Test name """ return self._get_attribute(self._SDM_ATT_MAP['Name']) @Name.setter def Name(self, value): self._set_attribute(self._SDM_ATT_MAP['Name'], value) def update(self, ForceApplyQTConfig=None, InputParameters=None, Mode=None, Name=None): """Updates asymmetricThroughput resource on the server. Args ---- - ForceApplyQTConfig (bool): Apply QT config - InputParameters (str): Input Parameters - Mode (str(existingMode | newMode)): Test mode - Name (str): Test name Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def add(self, ForceApplyQTConfig=None, InputParameters=None, Mode=None, Name=None): """Adds a new asymmetricThroughput resource on the server and adds it to the container. Args ---- - ForceApplyQTConfig (bool): Apply QT config - InputParameters (str): Input Parameters - Mode (str(existingMode | newMode)): Test mode - Name (str): Test name Returns ------- - self: This instance with all currently retrieved asymmetricThroughput resources using find and the newly added asymmetricThroughput resources available through an iterator or index Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._create(self._map_locals(self._SDM_ATT_MAP, locals())) def remove(self): """Deletes all the contained asymmetricThroughput resources in this instance from the server. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ self._delete() def find(self, ForceApplyQTConfig=None, InputParameters=None, Mode=None, Name=None): """Finds and retrieves asymmetricThroughput resources from the server. All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve asymmetricThroughput resources from the server. To retrieve an exact match ensure the parameter value starts with ^ and ends with $ By default the find method takes no parameters and will retrieve all asymmetricThroughput resources from the server. Args ---- - ForceApplyQTConfig (bool): Apply QT config - InputParameters (str): Input Parameters - Mode (str(existingMode | newMode)): Test mode - Name (str): Test name Returns ------- - self: This instance with matching asymmetricThroughput resources retrieved from the server available through an iterator or index Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._select(self._map_locals(self._SDM_ATT_MAP, locals())) def read(self, href): """Retrieves a single instance of asymmetricThroughput data from the server. Args ---- - href (str): An href to the instance to be retrieved Returns ------- - self: This instance with the asymmetricThroughput resources from the server available through an iterator or index Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ return self._read(href) def Apply(self): """Executes the apply operation on the server. Applies the specified Quick Test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('apply', payload=payload, response_object=None) def ApplyAsync(self): """Executes the applyAsync operation on the server. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('applyAsync', payload=payload, response_object=None) def ApplyAsyncResult(self): """Executes the applyAsyncResult operation on the server. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('applyAsyncResult', payload=payload, response_object=None) def ApplyITWizardConfiguration(self): """Executes the applyITWizardConfiguration operation on the server. Applies the specified Quick Test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('applyITWizardConfiguration', payload=payload, response_object=None) def GenerateReport(self): """Executes the generateReport operation on the server. Generate a PDF report for the last succesfull test run. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('generateReport', payload=payload, response_object=None) def Run(self, *args, **kwargs): """Executes the run operation on the server. Starts the specified Quick Test and waits for its execution to finish. The IxNetwork model allows for multiple method Signatures with the same name while python does not. run(InputParameters=string)list ------------------------------- - InputParameters (str): The input arguments of the test. - Returns list(str): This method is synchronous and returns the result of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('run', payload=payload, response_object=None) def Start(self, *args, **kwargs): """Executes the start operation on the server. Starts the specified Quick Test. The IxNetwork model allows for multiple method Signatures with the same name while python does not. start(InputParameters=string) ----------------------------- - InputParameters (str): The input arguments of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('start', payload=payload, response_object=None) def Stop(self): """Executes the stop operation on the server. Stops the currently running Quick Test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('stop', payload=payload, response_object=None) def WaitForTest(self): """Executes the waitForTest operation on the server. Waits for the execution of the specified Quick Test to be completed. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('waitForTest', payload=payload, response_object=None)
39.318421
191
0.647212
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class AsymmetricThroughput(Base): __slots__ = () _SDM_NAME = 'asymmetricThroughput' _SDM_ATT_MAP = { 'ForceApplyQTConfig': 'forceApplyQTConfig', 'InputParameters': 'inputParameters', 'Mode': 'mode', 'Name': 'name', } def __init__(self, parent): super(AsymmetricThroughput, self).__init__(parent) @property def LearnFrames(self): from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.learnframes_aff5042528d11d6e314f527665dc38f2 import LearnFrames return LearnFrames(self)._select() @property def PassCriteria(self): from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.passcriteria_a2cbb052e2ad975c0acd3e8a31c8d5ca import PassCriteria return PassCriteria(self)._select() @property def Results(self): from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.results_23583c0cce1dabf7b75fe7d2ae18cfc4 import Results return Results(self)._select() @property def TestConfig(self): from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.testconfig_81bab7c0e318724192d10cc0cd42f862 import TestConfig return TestConfig(self)._select() @property def TrafficSelection(self): from ixnetwork_restpy.testplatform.sessions.ixnetwork.quicktest.trafficselection_206d3c7fd8956cf41e032f8402bda1d7 import TrafficSelection return TrafficSelection(self) @property def ForceApplyQTConfig(self): return self._get_attribute(self._SDM_ATT_MAP['ForceApplyQTConfig']) @ForceApplyQTConfig.setter def ForceApplyQTConfig(self, value): self._set_attribute(self._SDM_ATT_MAP['ForceApplyQTConfig'], value) @property def InputParameters(self): return self._get_attribute(self._SDM_ATT_MAP['InputParameters']) @InputParameters.setter def InputParameters(self, value): self._set_attribute(self._SDM_ATT_MAP['InputParameters'], value) @property def Mode(self): return self._get_attribute(self._SDM_ATT_MAP['Mode']) @Mode.setter def Mode(self, value): self._set_attribute(self._SDM_ATT_MAP['Mode'], value) @property def Name(self): return self._get_attribute(self._SDM_ATT_MAP['Name']) @Name.setter def Name(self, value): self._set_attribute(self._SDM_ATT_MAP['Name'], value) def update(self, ForceApplyQTConfig=None, InputParameters=None, Mode=None, Name=None): return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def add(self, ForceApplyQTConfig=None, InputParameters=None, Mode=None, Name=None): return self._create(self._map_locals(self._SDM_ATT_MAP, locals())) def remove(self): self._delete() def find(self, ForceApplyQTConfig=None, InputParameters=None, Mode=None, Name=None): return self._select(self._map_locals(self._SDM_ATT_MAP, locals())) def read(self, href): return self._read(href) def Apply(self): payload = { "Arg1": self.href } return self._execute('apply', payload=payload, response_object=None) def ApplyAsync(self): payload = { "Arg1": self.href } return self._execute('applyAsync', payload=payload, response_object=None) def ApplyAsyncResult(self): payload = { "Arg1": self.href } return self._execute('applyAsyncResult', payload=payload, response_object=None) def ApplyITWizardConfiguration(self): payload = { "Arg1": self.href } return self._execute('applyITWizardConfiguration', payload=payload, response_object=None) def GenerateReport(self): payload = { "Arg1": self.href } return self._execute('generateReport', payload=payload, response_object=None) def Run(self, *args, **kwargs): payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('run', payload=payload, response_object=None) def Start(self, *args, **kwargs): payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('start', payload=payload, response_object=None) def Stop(self): payload = { "Arg1": self.href } return self._execute('stop', payload=payload, response_object=None) def WaitForTest(self): payload = { "Arg1": self.href } return self._execute('waitForTest', payload=payload, response_object=None)
true
true
f72d1dd9c1044400d4f9011000b5c29914781ea4
1,959
py
Python
activemq/setup.py
kzap/integrations-core
88c3a72dbf5223b496be1c549ca2857d8489c491
[ "BSD-3-Clause" ]
1
2021-01-28T01:45:37.000Z
2021-01-28T01:45:37.000Z
activemq/setup.py
kzap/integrations-core
88c3a72dbf5223b496be1c549ca2857d8489c491
[ "BSD-3-Clause" ]
3
2021-01-27T04:56:40.000Z
2021-02-26T06:29:22.000Z
activemq/setup.py
kzap/integrations-core
88c3a72dbf5223b496be1c549ca2857d8489c491
[ "BSD-3-Clause" ]
1
2021-04-07T16:58:27.000Z
2021-04-07T16:58:27.000Z
# (C) Datadog, Inc. 2018-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from codecs import open # To use a consistent encoding from os import path from setuptools import setup HERE = path.dirname(path.abspath(__file__)) # Get version info ABOUT = {} with open(path.join(HERE, 'datadog_checks', 'activemq', '__about__.py')) as f: exec(f.read(), ABOUT) # Get the long description from the README file with open(path.join(HERE, 'README.md'), encoding='utf-8') as f: long_description = f.read() def get_dependencies(): dep_file = path.join(HERE, 'requirements.in') if not path.isfile(dep_file): return [] with open(dep_file, encoding='utf-8') as f: return f.readlines() CHECKS_BASE_REQ = 'datadog-checks-base' setup( name='datadog-activemq', version=ABOUT['__version__'], description='The ActiveMQ check', long_description=long_description, long_description_content_type='text/markdown', keywords='datadog agent activemq check', # The project's main homepage. url='https://github.com/DataDog/integrations-core', # Author details author='Datadog', author_email='packages@datadoghq.com', # License license='BSD', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Topic :: System :: Monitoring', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], # The package we're going to ship packages=['datadog_checks.activemq'], # Run-time dependencies install_requires=[CHECKS_BASE_REQ], extras_require={'deps': get_dependencies()}, # Extra files to ship with the wheel package include_package_data=True, )
30.138462
78
0.678918
from codecs import open from os import path from setuptools import setup HERE = path.dirname(path.abspath(__file__)) ABOUT = {} with open(path.join(HERE, 'datadog_checks', 'activemq', '__about__.py')) as f: exec(f.read(), ABOUT) with open(path.join(HERE, 'README.md'), encoding='utf-8') as f: long_description = f.read() def get_dependencies(): dep_file = path.join(HERE, 'requirements.in') if not path.isfile(dep_file): return [] with open(dep_file, encoding='utf-8') as f: return f.readlines() CHECKS_BASE_REQ = 'datadog-checks-base' setup( name='datadog-activemq', version=ABOUT['__version__'], description='The ActiveMQ check', long_description=long_description, long_description_content_type='text/markdown', keywords='datadog agent activemq check', url='https://github.com/DataDog/integrations-core', # Author details author='Datadog', author_email='packages@datadoghq.com', # License license='BSD', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Topic :: System :: Monitoring', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], # The package we're going to ship packages=['datadog_checks.activemq'], install_requires=[CHECKS_BASE_REQ], extras_require={'deps': get_dependencies()}, include_package_data=True, )
true
true
f72d1df9ba0d4ece4941df1261e9df055c7d4e59
1,480
py
Python
pyblas/level1/cswap.py
timleslie/pyblas
9109f2cc24e674cf59a3b39f95c2d7b8116ae884
[ "BSD-3-Clause" ]
null
null
null
pyblas/level1/cswap.py
timleslie/pyblas
9109f2cc24e674cf59a3b39f95c2d7b8116ae884
[ "BSD-3-Clause" ]
1
2020-10-10T23:23:06.000Z
2020-10-10T23:23:06.000Z
pyblas/level1/cswap.py
timleslie/pyblas
9109f2cc24e674cf59a3b39f95c2d7b8116ae884
[ "BSD-3-Clause" ]
null
null
null
from ..util import slice_ def cswap(N, CX, INCX, CY, INCY): """Swaps the contents of a vector x with a vector y Parameters ---------- N : int Number of elements in input vector CX : numpy.ndarray A single precision complex array, dimension (1 + (`N` - 1)*abs(`INCX`)) INCX : int Storage spacing between elements of `CX` CY : numpy.ndarray A single precision complex array, dimension (1 + (`N` - 1)*abs(`INCY`)) INCY : int Storage spacing between elements of `CY` Returns ------- None See Also -------- sswap : Single-precision real swap two vectors dswap : Double-precision real swap two vectors zswap : Double-precision complex swap two vectors Notes ----- Online PyBLAS documentation: https://nbviewer.jupyter.org/github/timleslie/pyblas/blob/main/docs/cswap.ipynb Reference BLAS documentation: https://github.com/Reference-LAPACK/lapack/blob/v3.9.0/BLAS/SRC/cswap.f Examples -------- >>> x = np.array([1+2j, 2+3j, 3+4j], dtype=np.complex64) >>> y = np.array([6+7j, 7+8j, 8+9j], dtype=np.complex64) >>> N = len(x) >>> incx = 1 >>> cswap(N, x, incx, y, incy) >>> print(x) [6+7j, 7+8j, 8+9j] >>> print(y) [1+2j, 2+3j, 3+4j] """ if N <= 0: return x_slice = slice_(N, INCX) y_slice = slice_(N, INCY) X_TEMP = CX[x_slice].copy() CX[x_slice] = CY[y_slice] CY[x_slice] = X_TEMP
27.407407
112
0.584459
from ..util import slice_ def cswap(N, CX, INCX, CY, INCY): if N <= 0: return x_slice = slice_(N, INCX) y_slice = slice_(N, INCY) X_TEMP = CX[x_slice].copy() CX[x_slice] = CY[y_slice] CY[x_slice] = X_TEMP
true
true
f72d1e7058caff6214e3cbcab08ed3706f8ab834
996
py
Python
wwpdb/utils/tests_wf/WfDataObjectImportTests.py
epeisach/py-wwpdb_utils_wf
4069bcc6236c99f99a78f2e0dd681d7971df97f8
[ "Apache-2.0" ]
null
null
null
wwpdb/utils/tests_wf/WfDataObjectImportTests.py
epeisach/py-wwpdb_utils_wf
4069bcc6236c99f99a78f2e0dd681d7971df97f8
[ "Apache-2.0" ]
1
2021-07-06T16:38:16.000Z
2021-07-06T16:38:16.000Z
wwpdb/utils/tests_wf/WfDataObjectImportTests.py
epeisach/py-wwpdb_utils_wf
4069bcc6236c99f99a78f2e0dd681d7971df97f8
[ "Apache-2.0" ]
1
2021-05-25T15:42:51.000Z
2021-05-25T15:42:51.000Z
## # File: WfDataObjectImportTests.py # Date: 10-Oct-2018 E. Peisach # # Updates: ## """Test cases for wwpdb.utils.wf - simply import everything to ensure imports work""" __docformat__ = "restructuredtext en" __author__ = "Ezra Peisach" __email__ = "peisach@rcsb.rutgers.edu" __license__ = "Creative Commons Attribution 3.0 Unported" __version__ = "V0.01" import unittest if __package__ is None or __package__ == "": import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from commonsetup import HERE # pylint: disable=import-error,unused-import else: from .commonsetup import HERE # noqa: F401 from wwpdb.utils.wf.WfDataObject import WfDataObject class ImportTests(unittest.TestCase): def setUp(self): pass def testInstantiate(self): # vT = WfDbApi() dO = WfDataObject() # __repr__ should not crash if not fixed print(dO) if __name__ == "__main__": unittest.main()
23.714286
85
0.699799
__docformat__ = "restructuredtext en" __author__ = "Ezra Peisach" __email__ = "peisach@rcsb.rutgers.edu" __license__ = "Creative Commons Attribution 3.0 Unported" __version__ = "V0.01" import unittest if __package__ is None or __package__ == "": import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from commonsetup import HERE else: from .commonsetup import HERE from wwpdb.utils.wf.WfDataObject import WfDataObject class ImportTests(unittest.TestCase): def setUp(self): pass def testInstantiate(self): dO = WfDataObject() print(dO) if __name__ == "__main__": unittest.main()
true
true
f72d1ee40a4fb822de765b3f6b614cbf451598f5
2,569
py
Python
misc/ig/ig/yahoo.py
all3g/pieces
bc378fd22ddc700891fe7f34ab0d5b341141e434
[ "CNRI-Python" ]
34
2016-10-31T02:05:24.000Z
2018-11-08T14:33:13.000Z
misc/ig/ig/yahoo.py
join-us/python-programming
bc378fd22ddc700891fe7f34ab0d5b341141e434
[ "CNRI-Python" ]
2
2017-05-11T03:00:31.000Z
2017-11-01T23:37:37.000Z
misc/ig/ig/yahoo.py
join-us/python-programming
bc378fd22ddc700891fe7f34ab0d5b341141e434
[ "CNRI-Python" ]
21
2016-08-19T09:05:45.000Z
2018-11-08T14:33:16.000Z
#!/usr/bin/python # -*- coding: utf-8 -*- import requests import time import lxml.etree import randoms import re from searchengine import searchengine class yahoo(searchengine): """Search resources from yahoo searchengine, include titles/urls.""" def __init__(self): super(yahoo, self).__init__() def yahoo_dork_search(self, dork, page=0, random_sleep=True): """Search dorks from yahoo pages""" resources = [] indexs = range(page + 1) for index in indexs: req = requests.Session() url = 'https://search.yahoo.com/search' headers = {'User-Agent': 'Mozilla/5.0'} pz = 10 # items num in per page params = {'pz': pz, 'p': dork, 'b': pz * index + 1} resp = req.get(url, params=params, headers=headers) if resp.status_code != 200: # no available baidu pages return {dork: resources} html = lxml.etree.HTML(resp.text) ols = html.xpath('//div[@id="main"]/div/div[@id="web"]/' 'ol[contains(@class, "searchCenterMiddle")]') if not ols: return {dork: resources} # no available baidu pages for ol in ols: as_ = ol.xpath('//h3[@class="title"]/a') for a in as_: title = "".join([_ for _ in a.itertext()]) href = a.get('href') href = self.parse_yahoo_url(href) data = [title, href] resources.append(data) # Avoid yahoo.com banning spider ip, sleep during 1...n (not 1, n) if random_sleep and len(indexs) > 1 and index != indexs[-1]: rt = randoms.rand_item_from_iters([_ for _ in range(1, 8)]) print("sleeping {} s to avoid yahoo...".format(rt)) time.sleep(int(rt)) return {dork: resources} def parse_yahoo_url(self, url): """parse link from yahoo href""" if '/RU=' in url: # parse # regex = re.compile('/RU=([^\']+)/RK=0') regex = re.compile('.*/RU=([^\']+)/RK=') url = regex.findall(url)[0] url = requests.utils.unquote(url) return url def demo_yahoo(): """A demo test for yahoo class""" yh = yahoo() dork = 'site:google.com' data = yh.yahoo_dork_search(dork, page=1) for title, href in data[dork]: print(title) print(href) print('\n-----------\n') if __name__ == "__main__": demo_yahoo()
33.363636
78
0.525886
import requests import time import lxml.etree import randoms import re from searchengine import searchengine class yahoo(searchengine): def __init__(self): super(yahoo, self).__init__() def yahoo_dork_search(self, dork, page=0, random_sleep=True): resources = [] indexs = range(page + 1) for index in indexs: req = requests.Session() url = 'https://search.yahoo.com/search' headers = {'User-Agent': 'Mozilla/5.0'} pz = 10 params = {'pz': pz, 'p': dork, 'b': pz * index + 1} resp = req.get(url, params=params, headers=headers) if resp.status_code != 200: return {dork: resources} html = lxml.etree.HTML(resp.text) ols = html.xpath('//div[@id="main"]/div/div[@id="web"]/' 'ol[contains(@class, "searchCenterMiddle")]') if not ols: return {dork: resources} for ol in ols: as_ = ol.xpath('//h3[@class="title"]/a') for a in as_: title = "".join([_ for _ in a.itertext()]) href = a.get('href') href = self.parse_yahoo_url(href) data = [title, href] resources.append(data) if random_sleep and len(indexs) > 1 and index != indexs[-1]: rt = randoms.rand_item_from_iters([_ for _ in range(1, 8)]) print("sleeping {} s to avoid yahoo...".format(rt)) time.sleep(int(rt)) return {dork: resources} def parse_yahoo_url(self, url): if '/RU=' in url: regex = re.compile('.*/RU=([^\']+)/RK=') url = regex.findall(url)[0] url = requests.utils.unquote(url) return url def demo_yahoo(): yh = yahoo() dork = 'site:google.com' data = yh.yahoo_dork_search(dork, page=1) for title, href in data[dork]: print(title) print(href) print('\n-----------\n') if __name__ == "__main__": demo_yahoo()
true
true
f72d1f45574ed5c7672e07db524c2cc553117bc4
1,883
py
Python
api/allennlp_demo/ccg_supertagging/test_api.py
jakpra/allennlp-demo
d9fa5203d2e500499cbd55c244454bed7b68e1f8
[ "Apache-2.0" ]
null
null
null
api/allennlp_demo/ccg_supertagging/test_api.py
jakpra/allennlp-demo
d9fa5203d2e500499cbd55c244454bed7b68e1f8
[ "Apache-2.0" ]
null
null
null
api/allennlp_demo/ccg_supertagging/test_api.py
jakpra/allennlp-demo
d9fa5203d2e500499cbd55c244454bed7b68e1f8
[ "Apache-2.0" ]
null
null
null
from allennlp_demo.common.testing import ModelEndpointTestCase from allennlp_demo.ccg_supertagging.api import CCGSupertaggingModelEndpoint class TestCCGSupertaggingModelEndpoint(ModelEndpointTestCase): endpoint = CCGSupertaggingModelEndpoint() predict_input = { "sentence": "Did Uriah honestly think he could beat The Legend of Zelda in under three hours?" } attack_input = None predict_okay = None def test_predict(self): """ Test the /predict route. """ if self.predict_okay: return response = self.client.post("/predict", json=self.predict_input) # print('response', response) # print(response.is_json) # print(response.headers) # print(response.data) # print(response.__dict__) self.check_response_okay(response, cache_hit=False) responseData = response.get_json() # self.attack_input = { k: {'tags': inst['tags'], 'words': inst['words']} # for k, inst in responseData.items() } self.attack_input = { '0': {'tags': responseData['0']['tags'], 'words': responseData['0']['words']} } self.predict_okay = True def test_attack(self): if self.attack_input is None: # assert False, 'Need to run predict before running attacks.' self.test_predict() inputs = dict( inputs=self.attack_input, input_field_to_attack="tokens", grad_input_field="grad_input_1", ignore_tokens=None, target=None) response = self.client.post("/attack/input_reduction", json=inputs) # print(response) # print(response.is_json) # print(response.headers) # print(response.data) # print(response.__dict__) self.check_response_okay(response, cache_hit=False)
36.211538
109
0.627722
from allennlp_demo.common.testing import ModelEndpointTestCase from allennlp_demo.ccg_supertagging.api import CCGSupertaggingModelEndpoint class TestCCGSupertaggingModelEndpoint(ModelEndpointTestCase): endpoint = CCGSupertaggingModelEndpoint() predict_input = { "sentence": "Did Uriah honestly think he could beat The Legend of Zelda in under three hours?" } attack_input = None predict_okay = None def test_predict(self): if self.predict_okay: return response = self.client.post("/predict", json=self.predict_input) self.check_response_okay(response, cache_hit=False) responseData = response.get_json() self.attack_input = { '0': {'tags': responseData['0']['tags'], 'words': responseData['0']['words']} } self.predict_okay = True def test_attack(self): if self.attack_input is None: self.test_predict() inputs = dict( inputs=self.attack_input, input_field_to_attack="tokens", grad_input_field="grad_input_1", ignore_tokens=None, target=None) response = self.client.post("/attack/input_reduction", json=inputs) self.check_response_okay(response, cache_hit=False)
true
true
f72d203b944c8b07115f5722c5e0681ea802674a
53,500
py
Python
qa/rpc-tests/p2p-fullblocktest.py
Kimax89/wallet-official
e2e804daa66aa82dd85a4e8a0c3f6662d03429ca
[ "MIT" ]
24
2018-05-21T02:53:18.000Z
2021-12-31T07:03:51.000Z
qa/rpc-tests/p2p-fullblocktest.py
Kimax89/wallet-official
e2e804daa66aa82dd85a4e8a0c3f6662d03429ca
[ "MIT" ]
8
2018-05-28T20:48:26.000Z
2019-11-26T18:45:00.000Z
qa/rpc-tests/p2p-fullblocktest.py
Kimax89/wallet-official
e2e804daa66aa82dd85a4e8a0c3f6662d03429ca
[ "MIT" ]
16
2018-05-21T02:53:23.000Z
2020-10-07T16:21:57.000Z
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Copyright (c) 2017 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.comptool import TestManager, TestInstance, RejectResult from test_framework.blocktools import * import time from test_framework.key import CECKey from test_framework.script import * import struct from test_framework.cdefs import LEGACY_MAX_BLOCK_SIZE, MAX_BLOCK_SIGOPS_PER_MB class PreviousSpendableOutput(object): def __init__(self, tx=CTransaction(), n=-1): self.tx = tx self.n = n # the output we're spending ''' This reimplements tests from the bitcoinj/FullBlockTestGenerator used by the pull-tester. We use the testing framework in which we expect a particular answer from each test. ''' # Use this class for tests that require behavior other than normal "mininode" behavior. # For now, it is used to serialize a bloated varint (b64). class CBrokenBlock(CBlock): def __init__(self, header=None): super(CBrokenBlock, self).__init__(header) def initialize(self, base_block): self.vtx = copy.deepcopy(base_block.vtx) self.hashMerkleRoot = self.calc_merkle_root() def serialize(self): r = b"" r += super(CBlock, self).serialize() r += struct.pack("<BQ", 255, len(self.vtx)) for tx in self.vtx: r += tx.serialize() return r def normal_serialize(self): r = b"" r += super(CBrokenBlock, self).serialize() return r class FullBlockTest(ComparisonTestFramework): # Can either run this test as 1 node with expected answers, or two and compare them. # Change the "outcome" variable from each TestInstance object to only do # the comparison. def __init__(self): super().__init__() self.num_nodes = 1 self.block_heights = {} self.coinbase_key = CECKey() self.coinbase_key.set_secretbytes(b"horsebattery") self.coinbase_pubkey = self.coinbase_key.get_pubkey() self.tip = None self.blocks = {} def add_options(self, parser): super().add_options(parser) parser.add_option( "--runbarelyexpensive", dest="runbarelyexpensive", default=True) def run_test(self): self.test = TestManager(self, self.options.tmpdir) self.test.add_all_connections(self.nodes) # Start up network handling in another thread NetworkThread().start() self.test.run() def add_transactions_to_block(self, block, tx_list): [tx.rehash() for tx in tx_list] block.vtx.extend(tx_list) # this is a little handier to use than the version in blocktools.py def create_tx(self, spend_tx, n, value, script=CScript([OP_TRUE])): tx = create_transaction(spend_tx, n, b"", value, script) return tx # sign a transaction, using the key we know about # this signs input 0 in tx, which is assumed to be spending output n in # spend_tx def sign_tx(self, tx, spend_tx, n): scriptPubKey = bytearray(spend_tx.vout[n].scriptPubKey) if (scriptPubKey[0] == OP_TRUE): # an anyone-can-spend tx.vin[0].scriptSig = CScript() return sighash = SignatureHashForkId( spend_tx.vout[n].scriptPubKey, tx, 0, SIGHASH_ALL | SIGHASH_FORKID, spend_tx.vout[n].nValue) tx.vin[0].scriptSig = CScript( [self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL | SIGHASH_FORKID]))]) def create_and_sign_transaction(self, spend_tx, n, value, script=CScript([OP_TRUE])): tx = self.create_tx(spend_tx, n, value, script) self.sign_tx(tx, spend_tx, n) tx.rehash() return tx def next_block(self, number, spend=None, additional_coinbase_value=0, script=CScript([OP_TRUE]), solve=True): if self.tip == None: base_block_hash = self.genesis_hash block_time = int(time.time()) + 1 else: base_block_hash = self.tip.sha256 block_time = self.tip.nTime + 1 # First create the coinbase height = self.block_heights[base_block_hash] + 1 coinbase = create_coinbase(height, self.coinbase_pubkey) coinbase.vout[0].nValue += additional_coinbase_value coinbase.rehash() if spend == None: block = create_block(base_block_hash, coinbase, block_time) else: coinbase.vout[0].nValue += spend.tx.vout[ spend.n].nValue - 1 # all but one satoshi to fees coinbase.rehash() block = create_block(base_block_hash, coinbase, block_time) tx = create_transaction( spend.tx, spend.n, b"", 1, script) # spend 1 satoshi self.sign_tx(tx, spend.tx, spend.n) self.add_transactions_to_block(block, [tx]) block.hashMerkleRoot = block.calc_merkle_root() if solve: block.solve() self.tip = block self.block_heights[block.sha256] = height assert number not in self.blocks self.blocks[number] = block return block def get_tests(self): self.genesis_hash = int(self.nodes[0].getbestblockhash(), 16) self.block_heights[self.genesis_hash] = 0 spendable_outputs = [] # save the current tip so it can be spent by a later block def save_spendable_output(): spendable_outputs.append(self.tip) # get an output that we previously marked as spendable def get_spendable_output(): return PreviousSpendableOutput(spendable_outputs.pop(0).vtx[0], 0) # returns a test case that asserts that the current tip was accepted def accepted(): return TestInstance([[self.tip, True]]) # returns a test case that asserts that the current tip was rejected def rejected(reject=None): if reject is None: return TestInstance([[self.tip, False]]) else: return TestInstance([[self.tip, reject]]) # move the tip back to a previous block def tip(number): self.tip = self.blocks[number] # adds transactions to the block and updates state def update_block(block_number, new_transactions): block = self.blocks[block_number] self.add_transactions_to_block(block, new_transactions) old_sha256 = block.sha256 block.hashMerkleRoot = block.calc_merkle_root() block.solve() # Update the internal state just like in next_block self.tip = block if block.sha256 != old_sha256: self.block_heights[ block.sha256] = self.block_heights[old_sha256] del self.block_heights[old_sha256] self.blocks[block_number] = block return block # shorthand for functions block = self.next_block create_tx = self.create_tx create_and_sign_tx = self.create_and_sign_transaction # Create a new block block(0) save_spendable_output() yield accepted() # Now we need that block to mature so we can spend the coinbase. test = TestInstance(sync_every_block=False) for i in range(99): block(5000 + i) test.blocks_and_transactions.append([self.tip, True]) save_spendable_output() yield test # collect spendable outputs now to avoid cluttering the code later on out = [] for i in range(33): out.append(get_spendable_output()) # Start by building a couple of blocks on top (which output is spent is # in parentheses): # genesis -> b1 (0) -> b2 (1) block(1, spend=out[0]) save_spendable_output() yield accepted() block(2, spend=out[1]) yield accepted() save_spendable_output() # so fork like this: # # genesis -> b1 (0) -> b2 (1) # \-> b3 (1) # # Nothing should happen at this point. We saw b2 first so it takes # priority. tip(1) b3 = block(3, spend=out[1]) txout_b3 = PreviousSpendableOutput(b3.vtx[1], 0) yield rejected() # Now we add another block to make the alternative chain longer. # # genesis -> b1 (0) -> b2 (1) # \-> b3 (1) -> b4 (2) block(4, spend=out[2]) yield accepted() # ... and back to the first chain. # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b3 (1) -> b4 (2) tip(2) block(5, spend=out[2]) save_spendable_output() yield rejected() block(6, spend=out[3]) yield accepted() # Try to create a fork that double-spends # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b7 (2) -> b8 (4) # \-> b3 (1) -> b4 (2) tip(5) block(7, spend=out[2]) yield rejected() block(8, spend=out[4]) yield rejected() # Try to create a block that has too much fee # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b9 (4) # \-> b3 (1) -> b4 (2) tip(6) block(9, spend=out[4], additional_coinbase_value=1) yield rejected(RejectResult(16, b'bad-cb-amount')) # Create a fork that ends in a block with too much fee (the one that causes the reorg) # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b10 (3) -> b11 (4) # \-> b3 (1) -> b4 (2) tip(5) block(10, spend=out[3]) yield rejected() block(11, spend=out[4], additional_coinbase_value=1) yield rejected(RejectResult(16, b'bad-cb-amount')) # Try again, but with a valid fork first # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b14 (5) # (b12 added last) # \-> b3 (1) -> b4 (2) tip(5) b12 = block(12, spend=out[3]) save_spendable_output() b13 = block(13, spend=out[4]) # Deliver the block header for b12, and the block b13. # b13 should be accepted but the tip won't advance until b12 is # delivered. yield TestInstance([[CBlockHeader(b12), None], [b13, False]]) save_spendable_output() # b14 is invalid, but the node won't know that until it tries to connect # Tip still can't advance because b12 is missing block(14, spend=out[5], additional_coinbase_value=1) yield rejected() yield TestInstance([[b12, True, b13.sha256]]) # New tip should be b13. # Add a block with MAX_BLOCK_SIGOPS_PER_MB and one with one more sigop # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b16 (6) # \-> b3 (1) -> b4 (2) # Test that a block with a lot of checksigs is okay lots_of_checksigs = CScript( [OP_CHECKSIG] * (MAX_BLOCK_SIGOPS_PER_MB - 1)) tip(13) block(15, spend=out[5], script=lots_of_checksigs) yield accepted() save_spendable_output() # Test that a block with too many checksigs is rejected too_many_checksigs = CScript([OP_CHECKSIG] * (MAX_BLOCK_SIGOPS_PER_MB)) block(16, spend=out[6], script=too_many_checksigs) yield rejected(RejectResult(16, b'bad-blk-sigops')) # Attempt to spend a transaction created on a different fork # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b17 (b3.vtx[1]) # \-> b3 (1) -> b4 (2) tip(15) block(17, spend=txout_b3) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # Attempt to spend a transaction created on a different fork (on a fork this time) # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) # \-> b18 (b3.vtx[1]) -> b19 (6) # \-> b3 (1) -> b4 (2) tip(13) block(18, spend=txout_b3) yield rejected() block(19, spend=out[6]) yield rejected() # Attempt to spend a coinbase at depth too low # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b20 (7) # \-> b3 (1) -> b4 (2) tip(15) block(20, spend=out[7]) yield rejected(RejectResult(16, b'bad-txns-premature-spend-of-coinbase')) # Attempt to spend a coinbase at depth too low (on a fork this time) # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) # \-> b21 (6) -> b22 (5) # \-> b3 (1) -> b4 (2) tip(13) block(21, spend=out[6]) yield rejected() block(22, spend=out[5]) yield rejected() # Create a block on either side of LEGACY_MAX_BLOCK_SIZE and make sure its accepted/rejected # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) # \-> b24 (6) -> b25 (7) # \-> b3 (1) -> b4 (2) tip(15) b23 = block(23, spend=out[6]) tx = CTransaction() script_length = LEGACY_MAX_BLOCK_SIZE - len(b23.serialize()) - 69 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) tx.vin.append(CTxIn(COutPoint(b23.vtx[1].sha256, 0))) b23 = update_block(23, [tx]) # Make sure the math above worked out to produce a max-sized block assert_equal(len(b23.serialize()), LEGACY_MAX_BLOCK_SIZE) yield accepted() save_spendable_output() # Create blocks with a coinbase input script size out of range # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) # \-> ... (6) -> ... (7) # \-> b3 (1) -> b4 (2) tip(15) b26 = block(26, spend=out[6]) b26.vtx[0].vin[0].scriptSig = b'\x00' b26.vtx[0].rehash() # update_block causes the merkle root to get updated, even with no new # transactions, and updates the required state. b26 = update_block(26, []) yield rejected(RejectResult(16, b'bad-cb-length')) # Extend the b26 chain to make sure clashicd isn't accepting b26 b27 = block(27, spend=out[7]) yield rejected(RejectResult(0, b'bad-prevblk')) # Now try a too-large-coinbase script tip(15) b28 = block(28, spend=out[6]) b28.vtx[0].vin[0].scriptSig = b'\x00' * 101 b28.vtx[0].rehash() b28 = update_block(28, []) yield rejected(RejectResult(16, b'bad-cb-length')) # Extend the b28 chain to make sure clashicd isn't accepting b28 b29 = block(29, spend=out[7]) yield rejected(RejectResult(0, b'bad-prevblk')) # b30 has a max-sized coinbase scriptSig. tip(23) b30 = block(30) b30.vtx[0].vin[0].scriptSig = b'\x00' * 100 b30.vtx[0].rehash() b30 = update_block(30, []) yield accepted() save_spendable_output() # b31 - b35 - check sigops of OP_CHECKMULTISIG / OP_CHECKMULTISIGVERIFY / OP_CHECKSIGVERIFY # # genesis -> ... -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) # \-> b36 (11) # \-> b34 (10) # \-> b32 (9) # # MULTISIG: each op code counts as 20 sigops. To create the edge case, # pack another 19 sigops at the end. lots_of_multisigs = CScript([OP_CHECKMULTISIG] * ( (MAX_BLOCK_SIGOPS_PER_MB - 1) // 20) + [OP_CHECKSIG] * 19) b31 = block(31, spend=out[8], script=lots_of_multisigs) assert_equal(get_legacy_sigopcount_block(b31), MAX_BLOCK_SIGOPS_PER_MB) yield accepted() save_spendable_output() # this goes over the limit because the coinbase has one sigop too_many_multisigs = CScript( [OP_CHECKMULTISIG] * (MAX_BLOCK_SIGOPS_PER_MB // 20)) b32 = block(32, spend=out[9], script=too_many_multisigs) assert_equal(get_legacy_sigopcount_block( b32), MAX_BLOCK_SIGOPS_PER_MB + 1) yield rejected(RejectResult(16, b'bad-blk-sigops')) # CHECKMULTISIGVERIFY tip(31) lots_of_multisigs = CScript([OP_CHECKMULTISIGVERIFY] * ( (MAX_BLOCK_SIGOPS_PER_MB - 1) // 20) + [OP_CHECKSIG] * 19) block(33, spend=out[9], script=lots_of_multisigs) yield accepted() save_spendable_output() too_many_multisigs = CScript( [OP_CHECKMULTISIGVERIFY] * (MAX_BLOCK_SIGOPS_PER_MB // 20)) block(34, spend=out[10], script=too_many_multisigs) yield rejected(RejectResult(16, b'bad-blk-sigops')) # CHECKSIGVERIFY tip(33) lots_of_checksigs = CScript( [OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS_PER_MB - 1)) b35 = block(35, spend=out[10], script=lots_of_checksigs) yield accepted() save_spendable_output() too_many_checksigs = CScript( [OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS_PER_MB)) block(36, spend=out[11], script=too_many_checksigs) yield rejected(RejectResult(16, b'bad-blk-sigops')) # Check spending of a transaction in a block which failed to connect # # b6 (3) # b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) # \-> b37 (11) # \-> b38 (11/37) # # save 37's spendable output, but then double-spend out11 to invalidate # the block tip(35) b37 = block(37, spend=out[11]) txout_b37 = PreviousSpendableOutput(b37.vtx[1], 0) tx = create_and_sign_tx(out[11].tx, out[11].n, 0) b37 = update_block(37, [tx]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # attempt to spend b37's first non-coinbase tx, at which point b37 was # still considered valid tip(35) block(38, spend=txout_b37) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # Check P2SH SigOp counting # # # 13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b41 (12) # \-> b40 (12) # # b39 - create some P2SH outputs that will require 6 sigops to spend: # # redeem_script = COINBASE_PUBKEY, (OP_2DUP+OP_CHECKSIGVERIFY) * 5, OP_CHECKSIG # p2sh_script = OP_HASH160, ripemd160(sha256(script)), OP_EQUAL # tip(35) b39 = block(39) b39_outputs = 0 b39_sigops_per_output = 6 # Build the redeem script, hash it, use hash to create the p2sh script redeem_script = CScript([self.coinbase_pubkey] + [ OP_2DUP, OP_CHECKSIGVERIFY] * 5 + [OP_CHECKSIG]) redeem_script_hash = hash160(redeem_script) p2sh_script = CScript([OP_HASH160, redeem_script_hash, OP_EQUAL]) # Create a transaction that spends one satoshi to the p2sh_script, the rest to OP_TRUE # This must be signed because it is spending a coinbase spend = out[11] tx = create_tx(spend.tx, spend.n, 1, p2sh_script) tx.vout.append( CTxOut(spend.tx.vout[spend.n].nValue - 1, CScript([OP_TRUE]))) self.sign_tx(tx, spend.tx, spend.n) tx.rehash() b39 = update_block(39, [tx]) b39_outputs += 1 # Until block is full, add tx's with 1 satoshi to p2sh_script, the rest # to OP_TRUE tx_new = None tx_last = tx total_size = len(b39.serialize()) while(total_size < LEGACY_MAX_BLOCK_SIZE): tx_new = create_tx(tx_last, 1, 1, p2sh_script) tx_new.vout.append( CTxOut(tx_last.vout[1].nValue - 1, CScript([OP_TRUE]))) tx_new.rehash() total_size += len(tx_new.serialize()) if total_size >= LEGACY_MAX_BLOCK_SIZE: break b39.vtx.append(tx_new) # add tx to block tx_last = tx_new b39_outputs += 1 b39 = update_block(39, []) yield accepted() save_spendable_output() # Test sigops in P2SH redeem scripts # # b40 creates 3333 tx's spending the 6-sigop P2SH outputs from b39 for a total of 19998 sigops. # The first tx has one sigop and then at the end we add 2 more to put us just over the max. # # b41 does the same, less one, so it has the maximum sigops permitted. # tip(39) b40 = block(40, spend=out[12]) sigops = get_legacy_sigopcount_block(b40) numTxes = (MAX_BLOCK_SIGOPS_PER_MB - sigops) // b39_sigops_per_output assert_equal(numTxes <= b39_outputs, True) lastOutpoint = COutPoint(b40.vtx[1].sha256, 0) lastAmount = b40.vtx[1].vout[0].nValue new_txs = [] for i in range(1, numTxes + 1): tx = CTransaction() tx.vout.append(CTxOut(1, CScript([OP_TRUE]))) tx.vin.append(CTxIn(lastOutpoint, b'')) # second input is corresponding P2SH output from b39 tx.vin.append(CTxIn(COutPoint(b39.vtx[i].sha256, 0), b'')) # Note: must pass the redeem_script (not p2sh_script) to the # signature hash function sighash = SignatureHashForkId( redeem_script, tx, 1, SIGHASH_ALL | SIGHASH_FORKID, lastAmount) sig = self.coinbase_key.sign( sighash) + bytes(bytearray([SIGHASH_ALL | SIGHASH_FORKID])) scriptSig = CScript([sig, redeem_script]) tx.vin[1].scriptSig = scriptSig tx.rehash() new_txs.append(tx) lastOutpoint = COutPoint(tx.sha256, 0) lastAmount = tx.vout[0].nValue b40_sigops_to_fill = MAX_BLOCK_SIGOPS_PER_MB - \ (numTxes * b39_sigops_per_output + sigops) + 1 tx = CTransaction() tx.vin.append(CTxIn(lastOutpoint, b'')) tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b40_sigops_to_fill))) tx.rehash() new_txs.append(tx) update_block(40, new_txs) yield rejected(RejectResult(16, b'bad-blk-sigops')) # same as b40, but one less sigop tip(39) b41 = block(41, spend=None) update_block(41, b40.vtx[1:-1]) b41_sigops_to_fill = b40_sigops_to_fill - 1 tx = CTransaction() tx.vin.append(CTxIn(lastOutpoint, b'')) tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b41_sigops_to_fill))) tx.rehash() update_block(41, [tx]) yield accepted() # Fork off of b39 to create a constant base again # # b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) # \-> b41 (12) # tip(39) block(42, spend=out[12]) yield rejected() save_spendable_output() block(43, spend=out[13]) yield accepted() save_spendable_output() # Test a number of really invalid scenarios # # -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b44 (14) # \-> ??? (15) # The next few blocks are going to be created "by hand" since they'll do funky things, such as having # the first transaction be non-coinbase, etc. The purpose of b44 is to # make sure this works. height = self.block_heights[self.tip.sha256] + 1 coinbase = create_coinbase(height, self.coinbase_pubkey) b44 = CBlock() b44.nTime = self.tip.nTime + 1 b44.hashPrevBlock = self.tip.sha256 b44.nBits = 0x207fffff b44.vtx.append(coinbase) b44.hashMerkleRoot = b44.calc_merkle_root() b44.solve() self.tip = b44 self.block_heights[b44.sha256] = height self.blocks[44] = b44 yield accepted() # A block with a non-coinbase as the first tx non_coinbase = create_tx(out[15].tx, out[15].n, 1) b45 = CBlock() b45.nTime = self.tip.nTime + 1 b45.hashPrevBlock = self.tip.sha256 b45.nBits = 0x207fffff b45.vtx.append(non_coinbase) b45.hashMerkleRoot = b45.calc_merkle_root() b45.calc_sha256() b45.solve() self.block_heights[b45.sha256] = self.block_heights[ self.tip.sha256] + 1 self.tip = b45 self.blocks[45] = b45 yield rejected(RejectResult(16, b'bad-cb-missing')) # A block with no txns tip(44) b46 = CBlock() b46.nTime = b44.nTime + 1 b46.hashPrevBlock = b44.sha256 b46.nBits = 0x207fffff b46.vtx = [] b46.hashMerkleRoot = 0 b46.solve() self.block_heights[b46.sha256] = self.block_heights[b44.sha256] + 1 self.tip = b46 assert 46 not in self.blocks self.blocks[46] = b46 s = ser_uint256(b46.hashMerkleRoot) yield rejected(RejectResult(16, b'bad-cb-missing')) # A block with invalid work tip(44) b47 = block(47, solve=False) target = uint256_from_compact(b47.nBits) while b47.sha256 < target: # changed > to < b47.nNonce += 1 b47.rehash() yield rejected(RejectResult(16, b'high-hash')) # A block with timestamp > 2 hrs in the future tip(44) b48 = block(48, solve=False) b48.nTime = int(time.time()) + 60 * 60 * 3 b48.solve() yield rejected(RejectResult(16, b'time-too-new')) # A block with an invalid merkle hash tip(44) b49 = block(49) b49.hashMerkleRoot += 1 b49.solve() yield rejected(RejectResult(16, b'bad-txnmrklroot')) # A block with an incorrect POW limit tip(44) b50 = block(50) b50.nBits = b50.nBits - 1 b50.solve() yield rejected(RejectResult(16, b'bad-diffbits')) # A block with two coinbase txns tip(44) b51 = block(51) cb2 = create_coinbase(51, self.coinbase_pubkey) b51 = update_block(51, [cb2]) yield rejected(RejectResult(16, b'bad-tx-coinbase')) # A block w/ duplicate txns # Note: txns have to be in the right position in the merkle tree to # trigger this error tip(44) b52 = block(52, spend=out[15]) tx = create_tx(b52.vtx[1], 0, 1) b52 = update_block(52, [tx, tx]) yield rejected(RejectResult(16, b'bad-txns-duplicate')) # Test block timestamps # -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) # \-> b54 (15) # tip(43) block(53, spend=out[14]) yield rejected() # rejected since b44 is at same height save_spendable_output() # invalid timestamp (b35 is 5 blocks back, so its time is # MedianTimePast) b54 = block(54, spend=out[15]) b54.nTime = b35.nTime - 1 b54.solve() yield rejected(RejectResult(16, b'time-too-old')) # valid timestamp tip(53) b55 = block(55, spend=out[15]) b55.nTime = b35.nTime update_block(55, []) yield accepted() save_spendable_output() # Test CVE-2012-2459 # # -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57p2 (16) # \-> b57 (16) # \-> b56p2 (16) # \-> b56 (16) # # Merkle tree malleability (CVE-2012-2459): repeating sequences of transactions in a block without # affecting the merkle root of a block, while still invalidating it. # See: src/consensus/merkle.h # # b57 has three txns: coinbase, tx, tx1. The merkle root computation will duplicate tx. # Result: OK # # b56 copies b57 but duplicates tx1 and does not recalculate the block hash. So it has a valid merkle # root but duplicate transactions. # Result: Fails # # b57p2 has six transactions in its merkle tree: # - coinbase, tx, tx1, tx2, tx3, tx4 # Merkle root calculation will duplicate as necessary. # Result: OK. # # b56p2 copies b57p2 but adds both tx3 and tx4. The purpose of the test is to make sure the code catches # duplicate txns that are not next to one another with the "bad-txns-duplicate" error (which indicates # that the error was caught early, avoiding a DOS vulnerability.) # b57 - a good block with 2 txs, don't submit until end tip(55) b57 = block(57) tx = create_and_sign_tx(out[16].tx, out[16].n, 1) tx1 = create_tx(tx, 0, 1) b57 = update_block(57, [tx, tx1]) # b56 - copy b57, add a duplicate tx tip(55) b56 = copy.deepcopy(b57) self.blocks[56] = b56 assert_equal(len(b56.vtx), 3) b56 = update_block(56, [tx1]) assert_equal(b56.hash, b57.hash) yield rejected(RejectResult(16, b'bad-txns-duplicate')) # b57p2 - a good block with 6 tx'es, don't submit until end tip(55) b57p2 = block("57p2") tx = create_and_sign_tx(out[16].tx, out[16].n, 1) tx1 = create_tx(tx, 0, 1) tx2 = create_tx(tx1, 0, 1) tx3 = create_tx(tx2, 0, 1) tx4 = create_tx(tx3, 0, 1) b57p2 = update_block("57p2", [tx, tx1, tx2, tx3, tx4]) # b56p2 - copy b57p2, duplicate two non-consecutive tx's tip(55) b56p2 = copy.deepcopy(b57p2) self.blocks["b56p2"] = b56p2 assert_equal(b56p2.hash, b57p2.hash) assert_equal(len(b56p2.vtx), 6) b56p2 = update_block("b56p2", [tx3, tx4]) yield rejected(RejectResult(16, b'bad-txns-duplicate')) tip("57p2") yield accepted() tip(57) yield rejected() # rejected because 57p2 seen first save_spendable_output() # Test a few invalid tx types # # -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) # \-> ??? (17) # # tx with prevout.n out of range tip(57) b58 = block(58, spend=out[17]) tx = CTransaction() assert(len(out[17].tx.vout) < 42) tx.vin.append( CTxIn(COutPoint(out[17].tx.sha256, 42), CScript([OP_TRUE]), 0xffffffff)) tx.vout.append(CTxOut(0, b"")) tx.calc_sha256() b58 = update_block(58, [tx]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # tx with output value > input value out of range tip(57) b59 = block(59) tx = create_and_sign_tx(out[17].tx, out[17].n, 51 * COIN) b59 = update_block(59, [tx]) yield rejected(RejectResult(16, b'bad-txns-in-belowout')) # reset to good chain tip(57) b60 = block(60, spend=out[17]) yield accepted() save_spendable_output() # Test BIP30 # # -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) # \-> b61 (18) # # Blocks are not allowed to contain a transaction whose id matches that of an earlier, # not-fully-spent transaction in the same chain. To test, make identical coinbases; # the second one should be rejected. # tip(60) b61 = block(61, spend=out[18]) b61.vtx[0].vin[0].scriptSig = b60.vtx[ 0].vin[0].scriptSig # equalize the coinbases b61.vtx[0].rehash() b61 = update_block(61, []) assert_equal(b60.vtx[0].serialize(), b61.vtx[0].serialize()) yield rejected(RejectResult(16, b'bad-txns-BIP30')) # Test tx.isFinal is properly rejected (not an exhaustive tx.isFinal test, that should be in data-driven transaction tests) # # -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) # \-> b62 (18) # tip(60) b62 = block(62) tx = CTransaction() tx.nLockTime = 0xffffffff # this locktime is non-final assert(out[18].n < len(out[18].tx.vout)) tx.vin.append( CTxIn(COutPoint(out[18].tx.sha256, out[18].n))) # don't set nSequence tx.vout.append(CTxOut(0, CScript([OP_TRUE]))) assert(tx.vin[0].nSequence < 0xffffffff) tx.calc_sha256() b62 = update_block(62, [tx]) yield rejected(RejectResult(16, b'bad-txns-nonfinal')) # Test a non-final coinbase is also rejected # # -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) # \-> b63 (-) # tip(60) b63 = block(63) b63.vtx[0].nLockTime = 0xffffffff b63.vtx[0].vin[0].nSequence = 0xDEADBEEF b63.vtx[0].rehash() b63 = update_block(63, []) yield rejected(RejectResult(16, b'bad-txns-nonfinal')) # This checks that a block with a bloated VARINT between the block_header and the array of tx such that # the block is > LEGACY_MAX_BLOCK_SIZE with the bloated varint, but <= LEGACY_MAX_BLOCK_SIZE without the bloated varint, # does not cause a subsequent, identical block with canonical encoding to be rejected. The test does not # care whether the bloated block is accepted or rejected; it only cares that the second block is accepted. # # What matters is that the receiving node should not reject the bloated block, and then reject the canonical # block on the basis that it's the same as an already-rejected block (which would be a consensus failure.) # # -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) # \ # b64a (18) # b64a is a bloated block (non-canonical varint) # b64 is a good block (same as b64 but w/ canonical varint) # tip(60) regular_block = block("64a", spend=out[18]) # make it a "broken_block," with non-canonical serialization b64a = CBrokenBlock(regular_block) b64a.initialize(regular_block) self.blocks["64a"] = b64a self.tip = b64a tx = CTransaction() # use canonical serialization to calculate size script_length = LEGACY_MAX_BLOCK_SIZE - \ len(b64a.normal_serialize()) - 69 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) tx.vin.append(CTxIn(COutPoint(b64a.vtx[1].sha256, 0))) b64a = update_block("64a", [tx]) assert_equal(len(b64a.serialize()), LEGACY_MAX_BLOCK_SIZE + 8) yield TestInstance([[self.tip, None]]) # comptool workaround: to make sure b64 is delivered, manually erase # b64a from blockstore self.test.block_store.erase(b64a.sha256) tip(60) b64 = CBlock(b64a) b64.vtx = copy.deepcopy(b64a.vtx) assert_equal(b64.hash, b64a.hash) assert_equal(len(b64.serialize()), LEGACY_MAX_BLOCK_SIZE) self.blocks[64] = b64 update_block(64, []) yield accepted() save_spendable_output() # Spend an output created in the block itself # # -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) # tip(64) b65 = block(65) tx1 = create_and_sign_tx( out[19].tx, out[19].n, out[19].tx.vout[0].nValue) tx2 = create_and_sign_tx(tx1, 0, 0) update_block(65, [tx1, tx2]) yield accepted() save_spendable_output() # Attempt to spend an output created later in the same block # # -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) # \-> b66 (20) tip(65) b66 = block(66) tx1 = create_and_sign_tx( out[20].tx, out[20].n, out[20].tx.vout[0].nValue) tx2 = create_and_sign_tx(tx1, 0, 1) update_block(66, [tx2, tx1]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # Attempt to double-spend a transaction created in a block # # -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) # \-> b67 (20) # # tip(65) b67 = block(67) tx1 = create_and_sign_tx( out[20].tx, out[20].n, out[20].tx.vout[0].nValue) tx2 = create_and_sign_tx(tx1, 0, 1) tx3 = create_and_sign_tx(tx1, 0, 2) update_block(67, [tx1, tx2, tx3]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # More tests of block subsidy # # -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) # \-> b68 (20) # # b68 - coinbase with an extra 10 satoshis, # creates a tx that has 9 satoshis from out[20] go to fees # this fails because the coinbase is trying to claim 1 satoshi too much in fees # # b69 - coinbase with extra 10 satoshis, and a tx that gives a 10 satoshi fee # this succeeds # tip(65) b68 = block(68, additional_coinbase_value=10) tx = create_and_sign_tx( out[20].tx, out[20].n, out[20].tx.vout[0].nValue - 9) update_block(68, [tx]) yield rejected(RejectResult(16, b'bad-cb-amount')) tip(65) b69 = block(69, additional_coinbase_value=10) tx = create_and_sign_tx( out[20].tx, out[20].n, out[20].tx.vout[0].nValue - 10) update_block(69, [tx]) yield accepted() save_spendable_output() # Test spending the outpoint of a non-existent transaction # # -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) # \-> b70 (21) # tip(69) block(70, spend=out[21]) bogus_tx = CTransaction() bogus_tx.sha256 = uint256_from_str( b"23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c") tx = CTransaction() tx.vin.append(CTxIn(COutPoint(bogus_tx.sha256, 0), b"", 0xffffffff)) tx.vout.append(CTxOut(1, b"")) update_block(70, [tx]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # Test accepting an invalid block which has the same hash as a valid one (via merkle tree tricks) # # -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) # \-> b71 (21) # # b72 is a good block. # b71 is a copy of 72, but re-adds one of its transactions. However, it has the same hash as b71. # tip(69) b72 = block(72) tx1 = create_and_sign_tx(out[21].tx, out[21].n, 2) tx2 = create_and_sign_tx(tx1, 0, 1) b72 = update_block(72, [tx1, tx2]) # now tip is 72 b71 = copy.deepcopy(b72) b71.vtx.append(tx2) # add duplicate tx2 self.block_heights[b71.sha256] = self.block_heights[ b69.sha256] + 1 # b71 builds off b69 self.blocks[71] = b71 assert_equal(len(b71.vtx), 4) assert_equal(len(b72.vtx), 3) assert_equal(b72.sha256, b71.sha256) tip(71) yield rejected(RejectResult(16, b'bad-txns-duplicate')) tip(72) yield accepted() save_spendable_output() # Test some invalid scripts and MAX_BLOCK_SIGOPS_PER_MB # # -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) # \-> b** (22) # # b73 - tx with excessive sigops that are placed after an excessively large script element. # The purpose of the test is to make sure those sigops are counted. # # script is a bytearray of size 20,526 # # bytearray[0-19,998] : OP_CHECKSIG # bytearray[19,999] : OP_PUSHDATA4 # bytearray[20,000-20,003]: 521 (max_script_element_size+1, in little-endian format) # bytearray[20,004-20,525]: unread data (script_element) # bytearray[20,526] : OP_CHECKSIG (this puts us over the limit) # tip(72) b73 = block(73) size = MAX_BLOCK_SIGOPS_PER_MB - 1 + \ MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 + 1 a = bytearray([OP_CHECKSIG] * size) a[MAX_BLOCK_SIGOPS_PER_MB - 1] = int("4e", 16) # OP_PUSHDATA4 element_size = MAX_SCRIPT_ELEMENT_SIZE + 1 a[MAX_BLOCK_SIGOPS_PER_MB] = element_size % 256 a[MAX_BLOCK_SIGOPS_PER_MB + 1] = element_size // 256 a[MAX_BLOCK_SIGOPS_PER_MB + 2] = 0 a[MAX_BLOCK_SIGOPS_PER_MB + 3] = 0 tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a)) b73 = update_block(73, [tx]) assert_equal( get_legacy_sigopcount_block(b73), MAX_BLOCK_SIGOPS_PER_MB + 1) yield rejected(RejectResult(16, b'bad-blk-sigops')) # b74/75 - if we push an invalid script element, all prevous sigops are counted, # but sigops after the element are not counted. # # The invalid script element is that the push_data indicates that # there will be a large amount of data (0xffffff bytes), but we only # provide a much smaller number. These bytes are CHECKSIGS so they would # cause b75 to fail for excessive sigops, if those bytes were counted. # # b74 fails because we put MAX_BLOCK_SIGOPS_PER_MB+1 before the element # b75 succeeds because we put MAX_BLOCK_SIGOPS_PER_MB before the element # # tip(72) b74 = block(74) size = MAX_BLOCK_SIGOPS_PER_MB - 1 + \ MAX_SCRIPT_ELEMENT_SIZE + 42 # total = 20,561 a = bytearray([OP_CHECKSIG] * size) a[MAX_BLOCK_SIGOPS_PER_MB] = 0x4e a[MAX_BLOCK_SIGOPS_PER_MB + 1] = 0xfe a[MAX_BLOCK_SIGOPS_PER_MB + 2] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 3] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 4] = 0xff tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a)) b74 = update_block(74, [tx]) yield rejected(RejectResult(16, b'bad-blk-sigops')) tip(72) b75 = block(75) size = MAX_BLOCK_SIGOPS_PER_MB - 1 + MAX_SCRIPT_ELEMENT_SIZE + 42 a = bytearray([OP_CHECKSIG] * size) a[MAX_BLOCK_SIGOPS_PER_MB - 1] = 0x4e a[MAX_BLOCK_SIGOPS_PER_MB] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 1] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 2] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 3] = 0xff tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a)) b75 = update_block(75, [tx]) yield accepted() save_spendable_output() # Check that if we push an element filled with CHECKSIGs, they are not # counted tip(75) b76 = block(76) size = MAX_BLOCK_SIGOPS_PER_MB - 1 + MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 a = bytearray([OP_CHECKSIG] * size) a[MAX_BLOCK_SIGOPS_PER_MB - 1] = 0x4e # PUSHDATA4, but leave the following bytes as just checksigs tx = create_and_sign_tx(out[23].tx, 0, 1, CScript(a)) b76 = update_block(76, [tx]) yield accepted() save_spendable_output() # Test transaction resurrection # # -> b77 (24) -> b78 (25) -> b79 (26) # \-> b80 (25) -> b81 (26) -> b82 (27) # # b78 creates a tx, which is spent in b79. After b82, both should be in mempool # # The tx'es must be unsigned and pass the node's mempool policy. It is unsigned for the # rather obscure reason that the Python signature code does not distinguish between # Low-S and High-S values (whereas the bitcoin code has custom code which does so); # as a result of which, the odds are 50% that the python code will use the right # value and the transaction will be accepted into the mempool. Until we modify the # test framework to support low-S signing, we are out of luck. # # To get around this issue, we construct transactions which are not signed and which # spend to OP_TRUE. If the standard-ness rules change, this test would need to be # updated. (Perhaps to spend to a P2SH OP_TRUE script) # tip(76) block(77) tx77 = create_and_sign_tx(out[24].tx, out[24].n, 10 * COIN) update_block(77, [tx77]) yield accepted() save_spendable_output() block(78) tx78 = create_tx(tx77, 0, 9 * COIN) update_block(78, [tx78]) yield accepted() block(79) tx79 = create_tx(tx78, 0, 8 * COIN) update_block(79, [tx79]) yield accepted() # mempool should be empty assert_equal(len(self.nodes[0].getrawmempool()), 0) tip(77) block(80, spend=out[25]) yield rejected() save_spendable_output() block(81, spend=out[26]) yield rejected() # other chain is same length save_spendable_output() block(82, spend=out[27]) yield accepted() # now this chain is longer, triggers re-org save_spendable_output() # now check that tx78 and tx79 have been put back into the peer's # mempool mempool = self.nodes[0].getrawmempool() assert_equal(len(mempool), 2) assert(tx78.hash in mempool) assert(tx79.hash in mempool) # Test invalid opcodes in dead execution paths. # # -> b81 (26) -> b82 (27) -> b83 (28) # b83 = block(83) op_codes = [OP_IF, OP_INVALIDOPCODE, OP_ELSE, OP_TRUE, OP_ENDIF] script = CScript(op_codes) tx1 = create_and_sign_tx( out[28].tx, out[28].n, out[28].tx.vout[0].nValue, script) tx2 = create_and_sign_tx(tx1, 0, 0, CScript([OP_TRUE])) tx2.vin[0].scriptSig = CScript([OP_FALSE]) tx2.rehash() update_block(83, [tx1, tx2]) yield accepted() save_spendable_output() # Reorg on/off blocks that have OP_RETURN in them (and try to spend them) # # -> b81 (26) -> b82 (27) -> b83 (28) -> b84 (29) -> b87 (30) -> b88 (31) # \-> b85 (29) -> b86 (30) \-> b89a (32) # # b84 = block(84) tx1 = create_tx(out[29].tx, out[29].n, 0, CScript([OP_RETURN])) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.calc_sha256() self.sign_tx(tx1, out[29].tx, out[29].n) tx1.rehash() tx2 = create_tx(tx1, 1, 0, CScript([OP_RETURN])) tx2.vout.append(CTxOut(0, CScript([OP_RETURN]))) tx3 = create_tx(tx1, 2, 0, CScript([OP_RETURN])) tx3.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx4 = create_tx(tx1, 3, 0, CScript([OP_TRUE])) tx4.vout.append(CTxOut(0, CScript([OP_RETURN]))) tx5 = create_tx(tx1, 4, 0, CScript([OP_RETURN])) update_block(84, [tx1, tx2, tx3, tx4, tx5]) yield accepted() save_spendable_output() tip(83) block(85, spend=out[29]) yield rejected() block(86, spend=out[30]) yield accepted() tip(84) block(87, spend=out[30]) yield rejected() save_spendable_output() block(88, spend=out[31]) yield accepted() save_spendable_output() # trying to spend the OP_RETURN output is rejected block("89a", spend=out[32]) tx = create_tx(tx1, 0, 0, CScript([OP_TRUE])) update_block("89a", [tx]) yield rejected() # Test re-org of a week's worth of blocks (1088 blocks) # This test takes a minute or two and can be accomplished in memory # if self.options.runbarelyexpensive: tip(88) LARGE_REORG_SIZE = 1088 test1 = TestInstance(sync_every_block=False) spend = out[32] for i in range(89, LARGE_REORG_SIZE + 89): b = block(i, spend) tx = CTransaction() script_length = LEGACY_MAX_BLOCK_SIZE - len(b.serialize()) - 69 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) tx.vin.append(CTxIn(COutPoint(b.vtx[1].sha256, 0))) b = update_block(i, [tx]) assert_equal(len(b.serialize()), LEGACY_MAX_BLOCK_SIZE) test1.blocks_and_transactions.append([self.tip, True]) save_spendable_output() spend = get_spendable_output() yield test1 chain1_tip = i # now create alt chain of same length tip(88) test2 = TestInstance(sync_every_block=False) for i in range(89, LARGE_REORG_SIZE + 89): block("alt" + str(i)) test2.blocks_and_transactions.append([self.tip, False]) yield test2 # extend alt chain to trigger re-org block("alt" + str(chain1_tip + 1)) yield accepted() # ... and re-org back to the first chain tip(chain1_tip) block(chain1_tip + 1) yield rejected() block(chain1_tip + 2) yield accepted() chain1_tip += 2 if __name__ == '__main__': FullBlockTest().main()
40.622627
131
0.539813
from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.comptool import TestManager, TestInstance, RejectResult from test_framework.blocktools import * import time from test_framework.key import CECKey from test_framework.script import * import struct from test_framework.cdefs import LEGACY_MAX_BLOCK_SIZE, MAX_BLOCK_SIGOPS_PER_MB class PreviousSpendableOutput(object): def __init__(self, tx=CTransaction(), n=-1): self.tx = tx self.n = n # Use this class for tests that require behavior other than normal "mininode" behavior. # For now, it is used to serialize a bloated varint (b64). class CBrokenBlock(CBlock): def __init__(self, header=None): super(CBrokenBlock, self).__init__(header) def initialize(self, base_block): self.vtx = copy.deepcopy(base_block.vtx) self.hashMerkleRoot = self.calc_merkle_root() def serialize(self): r = b"" r += super(CBlock, self).serialize() r += struct.pack("<BQ", 255, len(self.vtx)) for tx in self.vtx: r += tx.serialize() return r def normal_serialize(self): r = b"" r += super(CBrokenBlock, self).serialize() return r class FullBlockTest(ComparisonTestFramework): # Can either run this test as 1 node with expected answers, or two and compare them. # Change the "outcome" variable from each TestInstance object to only do # the comparison. def __init__(self): super().__init__() self.num_nodes = 1 self.block_heights = {} self.coinbase_key = CECKey() self.coinbase_key.set_secretbytes(b"horsebattery") self.coinbase_pubkey = self.coinbase_key.get_pubkey() self.tip = None self.blocks = {} def add_options(self, parser): super().add_options(parser) parser.add_option( "--runbarelyexpensive", dest="runbarelyexpensive", default=True) def run_test(self): self.test = TestManager(self, self.options.tmpdir) self.test.add_all_connections(self.nodes) # Start up network handling in another thread NetworkThread().start() self.test.run() def add_transactions_to_block(self, block, tx_list): [tx.rehash() for tx in tx_list] block.vtx.extend(tx_list) # this is a little handier to use than the version in blocktools.py def create_tx(self, spend_tx, n, value, script=CScript([OP_TRUE])): tx = create_transaction(spend_tx, n, b"", value, script) return tx # sign a transaction, using the key we know about # this signs input 0 in tx, which is assumed to be spending output n in # spend_tx def sign_tx(self, tx, spend_tx, n): scriptPubKey = bytearray(spend_tx.vout[n].scriptPubKey) if (scriptPubKey[0] == OP_TRUE): # an anyone-can-spend tx.vin[0].scriptSig = CScript() return sighash = SignatureHashForkId( spend_tx.vout[n].scriptPubKey, tx, 0, SIGHASH_ALL | SIGHASH_FORKID, spend_tx.vout[n].nValue) tx.vin[0].scriptSig = CScript( [self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL | SIGHASH_FORKID]))]) def create_and_sign_transaction(self, spend_tx, n, value, script=CScript([OP_TRUE])): tx = self.create_tx(spend_tx, n, value, script) self.sign_tx(tx, spend_tx, n) tx.rehash() return tx def next_block(self, number, spend=None, additional_coinbase_value=0, script=CScript([OP_TRUE]), solve=True): if self.tip == None: base_block_hash = self.genesis_hash block_time = int(time.time()) + 1 else: base_block_hash = self.tip.sha256 block_time = self.tip.nTime + 1 # First create the coinbase height = self.block_heights[base_block_hash] + 1 coinbase = create_coinbase(height, self.coinbase_pubkey) coinbase.vout[0].nValue += additional_coinbase_value coinbase.rehash() if spend == None: block = create_block(base_block_hash, coinbase, block_time) else: coinbase.vout[0].nValue += spend.tx.vout[ spend.n].nValue - 1 # all but one satoshi to fees coinbase.rehash() block = create_block(base_block_hash, coinbase, block_time) tx = create_transaction( spend.tx, spend.n, b"", 1, script) # spend 1 satoshi self.sign_tx(tx, spend.tx, spend.n) self.add_transactions_to_block(block, [tx]) block.hashMerkleRoot = block.calc_merkle_root() if solve: block.solve() self.tip = block self.block_heights[block.sha256] = height assert number not in self.blocks self.blocks[number] = block return block def get_tests(self): self.genesis_hash = int(self.nodes[0].getbestblockhash(), 16) self.block_heights[self.genesis_hash] = 0 spendable_outputs = [] # save the current tip so it can be spent by a later block def save_spendable_output(): spendable_outputs.append(self.tip) # get an output that we previously marked as spendable def get_spendable_output(): return PreviousSpendableOutput(spendable_outputs.pop(0).vtx[0], 0) # returns a test case that asserts that the current tip was accepted def accepted(): return TestInstance([[self.tip, True]]) # returns a test case that asserts that the current tip was rejected def rejected(reject=None): if reject is None: return TestInstance([[self.tip, False]]) else: return TestInstance([[self.tip, reject]]) # move the tip back to a previous block def tip(number): self.tip = self.blocks[number] # adds transactions to the block and updates state def update_block(block_number, new_transactions): block = self.blocks[block_number] self.add_transactions_to_block(block, new_transactions) old_sha256 = block.sha256 block.hashMerkleRoot = block.calc_merkle_root() block.solve() # Update the internal state just like in next_block self.tip = block if block.sha256 != old_sha256: self.block_heights[ block.sha256] = self.block_heights[old_sha256] del self.block_heights[old_sha256] self.blocks[block_number] = block return block # shorthand for functions block = self.next_block create_tx = self.create_tx create_and_sign_tx = self.create_and_sign_transaction # Create a new block block(0) save_spendable_output() yield accepted() # Now we need that block to mature so we can spend the coinbase. test = TestInstance(sync_every_block=False) for i in range(99): block(5000 + i) test.blocks_and_transactions.append([self.tip, True]) save_spendable_output() yield test # collect spendable outputs now to avoid cluttering the code later on out = [] for i in range(33): out.append(get_spendable_output()) # Start by building a couple of blocks on top (which output is spent is # in parentheses): # genesis -> b1 (0) -> b2 (1) block(1, spend=out[0]) save_spendable_output() yield accepted() block(2, spend=out[1]) yield accepted() save_spendable_output() # so fork like this: # # genesis -> b1 (0) -> b2 (1) # \-> b3 (1) # # Nothing should happen at this point. We saw b2 first so it takes # priority. tip(1) b3 = block(3, spend=out[1]) txout_b3 = PreviousSpendableOutput(b3.vtx[1], 0) yield rejected() # Now we add another block to make the alternative chain longer. # # genesis -> b1 (0) -> b2 (1) # \-> b3 (1) -> b4 (2) block(4, spend=out[2]) yield accepted() # ... and back to the first chain. # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b3 (1) -> b4 (2) tip(2) block(5, spend=out[2]) save_spendable_output() yield rejected() block(6, spend=out[3]) yield accepted() # Try to create a fork that double-spends # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b7 (2) -> b8 (4) # \-> b3 (1) -> b4 (2) tip(5) block(7, spend=out[2]) yield rejected() block(8, spend=out[4]) yield rejected() # Try to create a block that has too much fee # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b9 (4) # \-> b3 (1) -> b4 (2) tip(6) block(9, spend=out[4], additional_coinbase_value=1) yield rejected(RejectResult(16, b'bad-cb-amount')) # Create a fork that ends in a block with too much fee (the one that causes the reorg) # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b10 (3) -> b11 (4) # \-> b3 (1) -> b4 (2) tip(5) block(10, spend=out[3]) yield rejected() block(11, spend=out[4], additional_coinbase_value=1) yield rejected(RejectResult(16, b'bad-cb-amount')) # Try again, but with a valid fork first # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b14 (5) # (b12 added last) # \-> b3 (1) -> b4 (2) tip(5) b12 = block(12, spend=out[3]) save_spendable_output() b13 = block(13, spend=out[4]) # Deliver the block header for b12, and the block b13. # b13 should be accepted but the tip won't advance until b12 is yield TestInstance([[CBlockHeader(b12), None], [b13, False]]) save_spendable_output() # Tip still can't advance because b12 is missing block(14, spend=out[5], additional_coinbase_value=1) yield rejected() yield TestInstance([[b12, True, b13.sha256]]) lots_of_checksigs = CScript( [OP_CHECKSIG] * (MAX_BLOCK_SIGOPS_PER_MB - 1)) tip(13) block(15, spend=out[5], script=lots_of_checksigs) yield accepted() save_spendable_output() too_many_checksigs = CScript([OP_CHECKSIG] * (MAX_BLOCK_SIGOPS_PER_MB)) block(16, spend=out[6], script=too_many_checksigs) yield rejected(RejectResult(16, b'bad-blk-sigops')) tip(15) block(17, spend=txout_b3) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) tip(13) block(18, spend=txout_b3) yield rejected() block(19, spend=out[6]) yield rejected() tip(15) block(20, spend=out[7]) yield rejected(RejectResult(16, b'bad-txns-premature-spend-of-coinbase')) tip(13) block(21, spend=out[6]) yield rejected() block(22, spend=out[5]) yield rejected() tip(15) b23 = block(23, spend=out[6]) tx = CTransaction() script_length = LEGACY_MAX_BLOCK_SIZE - len(b23.serialize()) - 69 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) tx.vin.append(CTxIn(COutPoint(b23.vtx[1].sha256, 0))) b23 = update_block(23, [tx]) assert_equal(len(b23.serialize()), LEGACY_MAX_BLOCK_SIZE) yield accepted() save_spendable_output() tip(15) b26 = block(26, spend=out[6]) b26.vtx[0].vin[0].scriptSig = b'\x00' b26.vtx[0].rehash() b26 = update_block(26, []) yield rejected(RejectResult(16, b'bad-cb-length')) b27 = block(27, spend=out[7]) yield rejected(RejectResult(0, b'bad-prevblk')) # Now try a too-large-coinbase script tip(15) b28 = block(28, spend=out[6]) b28.vtx[0].vin[0].scriptSig = b'\x00' * 101 b28.vtx[0].rehash() b28 = update_block(28, []) yield rejected(RejectResult(16, b'bad-cb-length')) # Extend the b28 chain to make sure clashicd isn't accepting b28 b29 = block(29, spend=out[7]) yield rejected(RejectResult(0, b'bad-prevblk')) tip(23) b30 = block(30) b30.vtx[0].vin[0].scriptSig = b'\x00' * 100 b30.vtx[0].rehash() b30 = update_block(30, []) yield accepted() save_spendable_output() lots_of_multisigs = CScript([OP_CHECKMULTISIG] * ( (MAX_BLOCK_SIGOPS_PER_MB - 1) // 20) + [OP_CHECKSIG] * 19) b31 = block(31, spend=out[8], script=lots_of_multisigs) assert_equal(get_legacy_sigopcount_block(b31), MAX_BLOCK_SIGOPS_PER_MB) yield accepted() save_spendable_output() too_many_multisigs = CScript( [OP_CHECKMULTISIG] * (MAX_BLOCK_SIGOPS_PER_MB // 20)) b32 = block(32, spend=out[9], script=too_many_multisigs) assert_equal(get_legacy_sigopcount_block( b32), MAX_BLOCK_SIGOPS_PER_MB + 1) yield rejected(RejectResult(16, b'bad-blk-sigops')) tip(31) lots_of_multisigs = CScript([OP_CHECKMULTISIGVERIFY] * ( (MAX_BLOCK_SIGOPS_PER_MB - 1) // 20) + [OP_CHECKSIG] * 19) block(33, spend=out[9], script=lots_of_multisigs) yield accepted() save_spendable_output() too_many_multisigs = CScript( [OP_CHECKMULTISIGVERIFY] * (MAX_BLOCK_SIGOPS_PER_MB // 20)) block(34, spend=out[10], script=too_many_multisigs) yield rejected(RejectResult(16, b'bad-blk-sigops')) tip(33) lots_of_checksigs = CScript( [OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS_PER_MB - 1)) b35 = block(35, spend=out[10], script=lots_of_checksigs) yield accepted() save_spendable_output() too_many_checksigs = CScript( [OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS_PER_MB)) block(36, spend=out[11], script=too_many_checksigs) yield rejected(RejectResult(16, b'bad-blk-sigops')) # the block tip(35) b37 = block(37, spend=out[11]) txout_b37 = PreviousSpendableOutput(b37.vtx[1], 0) tx = create_and_sign_tx(out[11].tx, out[11].n, 0) b37 = update_block(37, [tx]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # attempt to spend b37's first non-coinbase tx, at which point b37 was tip(35) block(38, spend=txout_b37) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) tip(35) b39 = block(39) b39_outputs = 0 b39_sigops_per_output = 6 redeem_script = CScript([self.coinbase_pubkey] + [ OP_2DUP, OP_CHECKSIGVERIFY] * 5 + [OP_CHECKSIG]) redeem_script_hash = hash160(redeem_script) p2sh_script = CScript([OP_HASH160, redeem_script_hash, OP_EQUAL]) spend = out[11] tx = create_tx(spend.tx, spend.n, 1, p2sh_script) tx.vout.append( CTxOut(spend.tx.vout[spend.n].nValue - 1, CScript([OP_TRUE]))) self.sign_tx(tx, spend.tx, spend.n) tx.rehash() b39 = update_block(39, [tx]) b39_outputs += 1 # to OP_TRUE tx_new = None tx_last = tx total_size = len(b39.serialize()) while(total_size < LEGACY_MAX_BLOCK_SIZE): tx_new = create_tx(tx_last, 1, 1, p2sh_script) tx_new.vout.append( CTxOut(tx_last.vout[1].nValue - 1, CScript([OP_TRUE]))) tx_new.rehash() total_size += len(tx_new.serialize()) if total_size >= LEGACY_MAX_BLOCK_SIZE: break b39.vtx.append(tx_new) # add tx to block tx_last = tx_new b39_outputs += 1 b39 = update_block(39, []) yield accepted() save_spendable_output() # Test sigops in P2SH redeem scripts # # b40 creates 3333 tx's spending the 6-sigop P2SH outputs from b39 for a total of 19998 sigops. tip(39) b40 = block(40, spend=out[12]) sigops = get_legacy_sigopcount_block(b40) numTxes = (MAX_BLOCK_SIGOPS_PER_MB - sigops) // b39_sigops_per_output assert_equal(numTxes <= b39_outputs, True) lastOutpoint = COutPoint(b40.vtx[1].sha256, 0) lastAmount = b40.vtx[1].vout[0].nValue new_txs = [] for i in range(1, numTxes + 1): tx = CTransaction() tx.vout.append(CTxOut(1, CScript([OP_TRUE]))) tx.vin.append(CTxIn(lastOutpoint, b'')) tx.vin.append(CTxIn(COutPoint(b39.vtx[i].sha256, 0), b'')) sighash = SignatureHashForkId( redeem_script, tx, 1, SIGHASH_ALL | SIGHASH_FORKID, lastAmount) sig = self.coinbase_key.sign( sighash) + bytes(bytearray([SIGHASH_ALL | SIGHASH_FORKID])) scriptSig = CScript([sig, redeem_script]) tx.vin[1].scriptSig = scriptSig tx.rehash() new_txs.append(tx) lastOutpoint = COutPoint(tx.sha256, 0) lastAmount = tx.vout[0].nValue b40_sigops_to_fill = MAX_BLOCK_SIGOPS_PER_MB - \ (numTxes * b39_sigops_per_output + sigops) + 1 tx = CTransaction() tx.vin.append(CTxIn(lastOutpoint, b'')) tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b40_sigops_to_fill))) tx.rehash() new_txs.append(tx) update_block(40, new_txs) yield rejected(RejectResult(16, b'bad-blk-sigops')) tip(39) b41 = block(41, spend=None) update_block(41, b40.vtx[1:-1]) b41_sigops_to_fill = b40_sigops_to_fill - 1 tx = CTransaction() tx.vin.append(CTxIn(lastOutpoint, b'')) tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b41_sigops_to_fill))) tx.rehash() update_block(41, [tx]) yield accepted() tip(39) block(42, spend=out[12]) yield rejected() save_spendable_output() block(43, spend=out[13]) yield accepted() save_spendable_output() # the first transaction be non-coinbase, etc. The purpose of b44 is to # make sure this works. height = self.block_heights[self.tip.sha256] + 1 coinbase = create_coinbase(height, self.coinbase_pubkey) b44 = CBlock() b44.nTime = self.tip.nTime + 1 b44.hashPrevBlock = self.tip.sha256 b44.nBits = 0x207fffff b44.vtx.append(coinbase) b44.hashMerkleRoot = b44.calc_merkle_root() b44.solve() self.tip = b44 self.block_heights[b44.sha256] = height self.blocks[44] = b44 yield accepted() # A block with a non-coinbase as the first tx non_coinbase = create_tx(out[15].tx, out[15].n, 1) b45 = CBlock() b45.nTime = self.tip.nTime + 1 b45.hashPrevBlock = self.tip.sha256 b45.nBits = 0x207fffff b45.vtx.append(non_coinbase) b45.hashMerkleRoot = b45.calc_merkle_root() b45.calc_sha256() b45.solve() self.block_heights[b45.sha256] = self.block_heights[ self.tip.sha256] + 1 self.tip = b45 self.blocks[45] = b45 yield rejected(RejectResult(16, b'bad-cb-missing')) # A block with no txns tip(44) b46 = CBlock() b46.nTime = b44.nTime + 1 b46.hashPrevBlock = b44.sha256 b46.nBits = 0x207fffff b46.vtx = [] b46.hashMerkleRoot = 0 b46.solve() self.block_heights[b46.sha256] = self.block_heights[b44.sha256] + 1 self.tip = b46 assert 46 not in self.blocks self.blocks[46] = b46 s = ser_uint256(b46.hashMerkleRoot) yield rejected(RejectResult(16, b'bad-cb-missing')) # A block with invalid work tip(44) b47 = block(47, solve=False) target = uint256_from_compact(b47.nBits) while b47.sha256 < target: # changed > to < b47.nNonce += 1 b47.rehash() yield rejected(RejectResult(16, b'high-hash')) # A block with timestamp > 2 hrs in the future tip(44) b48 = block(48, solve=False) b48.nTime = int(time.time()) + 60 * 60 * 3 b48.solve() yield rejected(RejectResult(16, b'time-too-new')) # A block with an invalid merkle hash tip(44) b49 = block(49) b49.hashMerkleRoot += 1 b49.solve() yield rejected(RejectResult(16, b'bad-txnmrklroot')) # A block with an incorrect POW limit tip(44) b50 = block(50) b50.nBits = b50.nBits - 1 b50.solve() yield rejected(RejectResult(16, b'bad-diffbits')) # A block with two coinbase txns tip(44) b51 = block(51) cb2 = create_coinbase(51, self.coinbase_pubkey) b51 = update_block(51, [cb2]) yield rejected(RejectResult(16, b'bad-tx-coinbase')) # A block w/ duplicate txns # Note: txns have to be in the right position in the merkle tree to # trigger this error tip(44) b52 = block(52, spend=out[15]) tx = create_tx(b52.vtx[1], 0, 1) b52 = update_block(52, [tx, tx]) yield rejected(RejectResult(16, b'bad-txns-duplicate')) # Test block timestamps # -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) # \-> b54 (15) # tip(43) block(53, spend=out[14]) yield rejected() # rejected since b44 is at same height save_spendable_output() # invalid timestamp (b35 is 5 blocks back, so its time is # MedianTimePast) b54 = block(54, spend=out[15]) b54.nTime = b35.nTime - 1 b54.solve() yield rejected(RejectResult(16, b'time-too-old')) # valid timestamp tip(53) b55 = block(55, spend=out[15]) b55.nTime = b35.nTime update_block(55, []) yield accepted() save_spendable_output() # Test CVE-2012-2459 # # -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57p2 (16) # \-> b57 (16) # \-> b56p2 (16) # \-> b56 (16) # # Merkle tree malleability (CVE-2012-2459): repeating sequences of transactions in a block without # affecting the merkle root of a block, while still invalidating it. # See: src/consensus/merkle.h # # b57 has three txns: coinbase, tx, tx1. The merkle root computation will duplicate tx. # Result: OK # # b56 copies b57 but duplicates tx1 and does not recalculate the block hash. So it has a valid merkle # root but duplicate transactions. # Result: Fails # # b57p2 has six transactions in its merkle tree: # - coinbase, tx, tx1, tx2, tx3, tx4 # Merkle root calculation will duplicate as necessary. # Result: OK. # # b56p2 copies b57p2 but adds both tx3 and tx4. The purpose of the test is to make sure the code catches # duplicate txns that are not next to one another with the "bad-txns-duplicate" error (which indicates # that the error was caught early, avoiding a DOS vulnerability.) # b57 - a good block with 2 txs, don't submit until end tip(55) b57 = block(57) tx = create_and_sign_tx(out[16].tx, out[16].n, 1) tx1 = create_tx(tx, 0, 1) b57 = update_block(57, [tx, tx1]) tip(55) b56 = copy.deepcopy(b57) self.blocks[56] = b56 assert_equal(len(b56.vtx), 3) b56 = update_block(56, [tx1]) assert_equal(b56.hash, b57.hash) yield rejected(RejectResult(16, b'bad-txns-duplicate')) tip(55) b57p2 = block("57p2") tx = create_and_sign_tx(out[16].tx, out[16].n, 1) tx1 = create_tx(tx, 0, 1) tx2 = create_tx(tx1, 0, 1) tx3 = create_tx(tx2, 0, 1) tx4 = create_tx(tx3, 0, 1) b57p2 = update_block("57p2", [tx, tx1, tx2, tx3, tx4]) tip(55) b56p2 = copy.deepcopy(b57p2) self.blocks["b56p2"] = b56p2 assert_equal(b56p2.hash, b57p2.hash) assert_equal(len(b56p2.vtx), 6) b56p2 = update_block("b56p2", [tx3, tx4]) yield rejected(RejectResult(16, b'bad-txns-duplicate')) tip("57p2") yield accepted() tip(57) yield rejected() # rejected because 57p2 seen first save_spendable_output() # Test a few invalid tx types # # -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) # \-> ??? (17) # # tx with prevout.n out of range tip(57) b58 = block(58, spend=out[17]) tx = CTransaction() assert(len(out[17].tx.vout) < 42) tx.vin.append( CTxIn(COutPoint(out[17].tx.sha256, 42), CScript([OP_TRUE]), 0xffffffff)) tx.vout.append(CTxOut(0, b"")) tx.calc_sha256() b58 = update_block(58, [tx]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # tx with output value > input value out of range tip(57) b59 = block(59) tx = create_and_sign_tx(out[17].tx, out[17].n, 51 * COIN) b59 = update_block(59, [tx]) yield rejected(RejectResult(16, b'bad-txns-in-belowout')) # reset to good chain tip(57) b60 = block(60, spend=out[17]) yield accepted() save_spendable_output() # Test BIP30 # # -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) # \-> b61 (18) # # Blocks are not allowed to contain a transaction whose id matches that of an earlier, # not-fully-spent transaction in the same chain. To test, make identical coinbases; # the second one should be rejected. # tip(60) b61 = block(61, spend=out[18]) b61.vtx[0].vin[0].scriptSig = b60.vtx[ 0].vin[0].scriptSig # equalize the coinbases b61.vtx[0].rehash() b61 = update_block(61, []) assert_equal(b60.vtx[0].serialize(), b61.vtx[0].serialize()) yield rejected(RejectResult(16, b'bad-txns-BIP30')) # Test tx.isFinal is properly rejected (not an exhaustive tx.isFinal test, that should be in data-driven transaction tests) # # -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) # \-> b62 (18) # tip(60) b62 = block(62) tx = CTransaction() tx.nLockTime = 0xffffffff # this locktime is non-final assert(out[18].n < len(out[18].tx.vout)) tx.vin.append( CTxIn(COutPoint(out[18].tx.sha256, out[18].n))) # don't set nSequence tx.vout.append(CTxOut(0, CScript([OP_TRUE]))) assert(tx.vin[0].nSequence < 0xffffffff) tx.calc_sha256() b62 = update_block(62, [tx]) yield rejected(RejectResult(16, b'bad-txns-nonfinal')) tip(60) b63 = block(63) b63.vtx[0].nLockTime = 0xffffffff b63.vtx[0].vin[0].nSequence = 0xDEADBEEF b63.vtx[0].rehash() b63 = update_block(63, []) yield rejected(RejectResult(16, b'bad-txns-nonfinal')) # # -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) # \ # b64a (18) # b64a is a bloated block (non-canonical varint) # b64 is a good block (same as b64 but w/ canonical varint) # tip(60) regular_block = block("64a", spend=out[18]) # make it a "broken_block," with non-canonical serialization b64a = CBrokenBlock(regular_block) b64a.initialize(regular_block) self.blocks["64a"] = b64a self.tip = b64a tx = CTransaction() # use canonical serialization to calculate size script_length = LEGACY_MAX_BLOCK_SIZE - \ len(b64a.normal_serialize()) - 69 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) tx.vin.append(CTxIn(COutPoint(b64a.vtx[1].sha256, 0))) b64a = update_block("64a", [tx]) assert_equal(len(b64a.serialize()), LEGACY_MAX_BLOCK_SIZE + 8) yield TestInstance([[self.tip, None]]) # comptool workaround: to make sure b64 is delivered, manually erase # b64a from blockstore self.test.block_store.erase(b64a.sha256) tip(60) b64 = CBlock(b64a) b64.vtx = copy.deepcopy(b64a.vtx) assert_equal(b64.hash, b64a.hash) assert_equal(len(b64.serialize()), LEGACY_MAX_BLOCK_SIZE) self.blocks[64] = b64 update_block(64, []) yield accepted() save_spendable_output() # Spend an output created in the block itself # # -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) # tip(64) b65 = block(65) tx1 = create_and_sign_tx( out[19].tx, out[19].n, out[19].tx.vout[0].nValue) tx2 = create_and_sign_tx(tx1, 0, 0) update_block(65, [tx1, tx2]) yield accepted() save_spendable_output() # Attempt to spend an output created later in the same block # # -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) # \-> b66 (20) tip(65) b66 = block(66) tx1 = create_and_sign_tx( out[20].tx, out[20].n, out[20].tx.vout[0].nValue) tx2 = create_and_sign_tx(tx1, 0, 1) update_block(66, [tx2, tx1]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # Attempt to double-spend a transaction created in a block # # -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) # \-> b67 (20) # # tip(65) b67 = block(67) tx1 = create_and_sign_tx( out[20].tx, out[20].n, out[20].tx.vout[0].nValue) tx2 = create_and_sign_tx(tx1, 0, 1) tx3 = create_and_sign_tx(tx1, 0, 2) update_block(67, [tx1, tx2, tx3]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # More tests of block subsidy # # -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) # \-> b68 (20) # # b68 - coinbase with an extra 10 satoshis, # creates a tx that has 9 satoshis from out[20] go to fees # this fails because the coinbase is trying to claim 1 satoshi too much in fees # # b69 - coinbase with extra 10 satoshis, and a tx that gives a 10 satoshi fee # this succeeds # tip(65) b68 = block(68, additional_coinbase_value=10) tx = create_and_sign_tx( out[20].tx, out[20].n, out[20].tx.vout[0].nValue - 9) update_block(68, [tx]) yield rejected(RejectResult(16, b'bad-cb-amount')) tip(65) b69 = block(69, additional_coinbase_value=10) tx = create_and_sign_tx( out[20].tx, out[20].n, out[20].tx.vout[0].nValue - 10) update_block(69, [tx]) yield accepted() save_spendable_output() # Test spending the outpoint of a non-existent transaction # # -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) # \-> b70 (21) # tip(69) block(70, spend=out[21]) bogus_tx = CTransaction() bogus_tx.sha256 = uint256_from_str( b"23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c") tx = CTransaction() tx.vin.append(CTxIn(COutPoint(bogus_tx.sha256, 0), b"", 0xffffffff)) tx.vout.append(CTxOut(1, b"")) update_block(70, [tx]) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # Test accepting an invalid block which has the same hash as a valid one (via merkle tree tricks) # # -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) # \-> b71 (21) # # b72 is a good block. # b71 is a copy of 72, but re-adds one of its transactions. However, it has the same hash as b71. # tip(69) b72 = block(72) tx1 = create_and_sign_tx(out[21].tx, out[21].n, 2) tx2 = create_and_sign_tx(tx1, 0, 1) b72 = update_block(72, [tx1, tx2]) # now tip is 72 b71 = copy.deepcopy(b72) b71.vtx.append(tx2) # add duplicate tx2 self.block_heights[b71.sha256] = self.block_heights[ b69.sha256] + 1 # b71 builds off b69 self.blocks[71] = b71 assert_equal(len(b71.vtx), 4) assert_equal(len(b72.vtx), 3) assert_equal(b72.sha256, b71.sha256) tip(71) yield rejected(RejectResult(16, b'bad-txns-duplicate')) tip(72) yield accepted() save_spendable_output() # Test some invalid scripts and MAX_BLOCK_SIGOPS_PER_MB # # -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) # \-> b** (22) # # b73 - tx with excessive sigops that are placed after an excessively large script element. # The purpose of the test is to make sure those sigops are counted. # # script is a bytearray of size 20,526 # # bytearray[0-19,998] : OP_CHECKSIG # bytearray[19,999] : OP_PUSHDATA4 # bytearray[20,000-20,003]: 521 (max_script_element_size+1, in little-endian format) # bytearray[20,004-20,525]: unread data (script_element) # bytearray[20,526] : OP_CHECKSIG (this puts us over the limit) # tip(72) b73 = block(73) size = MAX_BLOCK_SIGOPS_PER_MB - 1 + \ MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 + 1 a = bytearray([OP_CHECKSIG] * size) a[MAX_BLOCK_SIGOPS_PER_MB - 1] = int("4e", 16) # OP_PUSHDATA4 element_size = MAX_SCRIPT_ELEMENT_SIZE + 1 a[MAX_BLOCK_SIGOPS_PER_MB] = element_size % 256 a[MAX_BLOCK_SIGOPS_PER_MB + 1] = element_size // 256 a[MAX_BLOCK_SIGOPS_PER_MB + 2] = 0 a[MAX_BLOCK_SIGOPS_PER_MB + 3] = 0 tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a)) b73 = update_block(73, [tx]) assert_equal( get_legacy_sigopcount_block(b73), MAX_BLOCK_SIGOPS_PER_MB + 1) yield rejected(RejectResult(16, b'bad-blk-sigops')) # b74/75 - if we push an invalid script element, all prevous sigops are counted, # but sigops after the element are not counted. # # The invalid script element is that the push_data indicates that # there will be a large amount of data (0xffffff bytes), but we only # provide a much smaller number. These bytes are CHECKSIGS so they would # cause b75 to fail for excessive sigops, if those bytes were counted. # # b74 fails because we put MAX_BLOCK_SIGOPS_PER_MB+1 before the element # b75 succeeds because we put MAX_BLOCK_SIGOPS_PER_MB before the element # # tip(72) b74 = block(74) size = MAX_BLOCK_SIGOPS_PER_MB - 1 + \ MAX_SCRIPT_ELEMENT_SIZE + 42 # total = 20,561 a = bytearray([OP_CHECKSIG] * size) a[MAX_BLOCK_SIGOPS_PER_MB] = 0x4e a[MAX_BLOCK_SIGOPS_PER_MB + 1] = 0xfe a[MAX_BLOCK_SIGOPS_PER_MB + 2] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 3] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 4] = 0xff tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a)) b74 = update_block(74, [tx]) yield rejected(RejectResult(16, b'bad-blk-sigops')) tip(72) b75 = block(75) size = MAX_BLOCK_SIGOPS_PER_MB - 1 + MAX_SCRIPT_ELEMENT_SIZE + 42 a = bytearray([OP_CHECKSIG] * size) a[MAX_BLOCK_SIGOPS_PER_MB - 1] = 0x4e a[MAX_BLOCK_SIGOPS_PER_MB] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 1] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 2] = 0xff a[MAX_BLOCK_SIGOPS_PER_MB + 3] = 0xff tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a)) b75 = update_block(75, [tx]) yield accepted() save_spendable_output() # Check that if we push an element filled with CHECKSIGs, they are not # counted tip(75) b76 = block(76) size = MAX_BLOCK_SIGOPS_PER_MB - 1 + MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 a = bytearray([OP_CHECKSIG] * size) a[MAX_BLOCK_SIGOPS_PER_MB - 1] = 0x4e # PUSHDATA4, but leave the following bytes as just checksigs tx = create_and_sign_tx(out[23].tx, 0, 1, CScript(a)) b76 = update_block(76, [tx]) yield accepted() save_spendable_output() # Test transaction resurrection # # -> b77 (24) -> b78 (25) -> b79 (26) # \-> b80 (25) -> b81 (26) -> b82 (27) # # b78 creates a tx, which is spent in b79. After b82, both should be in mempool # # The tx'es must be unsigned and pass the node's mempool policy. It is unsigned for the # rather obscure reason that the Python signature code does not distinguish between # Low-S and High-S values (whereas the bitcoin code has custom code which does so); # as a result of which, the odds are 50% that the python code will use the right # value and the transaction will be accepted into the mempool. Until we modify the # test framework to support low-S signing, we are out of luck. # # To get around this issue, we construct transactions which are not signed and which # spend to OP_TRUE. If the standard-ness rules change, this test would need to be # updated. (Perhaps to spend to a P2SH OP_TRUE script) # tip(76) block(77) tx77 = create_and_sign_tx(out[24].tx, out[24].n, 10 * COIN) update_block(77, [tx77]) yield accepted() save_spendable_output() block(78) tx78 = create_tx(tx77, 0, 9 * COIN) update_block(78, [tx78]) yield accepted() block(79) tx79 = create_tx(tx78, 0, 8 * COIN) update_block(79, [tx79]) yield accepted() # mempool should be empty assert_equal(len(self.nodes[0].getrawmempool()), 0) tip(77) block(80, spend=out[25]) yield rejected() save_spendable_output() block(81, spend=out[26]) yield rejected() # other chain is same length save_spendable_output() block(82, spend=out[27]) yield accepted() # now this chain is longer, triggers re-org save_spendable_output() # now check that tx78 and tx79 have been put back into the peer's mempool = self.nodes[0].getrawmempool() assert_equal(len(mempool), 2) assert(tx78.hash in mempool) assert(tx79.hash in mempool) b83 = block(83) op_codes = [OP_IF, OP_INVALIDOPCODE, OP_ELSE, OP_TRUE, OP_ENDIF] script = CScript(op_codes) tx1 = create_and_sign_tx( out[28].tx, out[28].n, out[28].tx.vout[0].nValue, script) tx2 = create_and_sign_tx(tx1, 0, 0, CScript([OP_TRUE])) tx2.vin[0].scriptSig = CScript([OP_FALSE]) tx2.rehash() update_block(83, [tx1, tx2]) yield accepted() save_spendable_output() b84 = block(84) tx1 = create_tx(out[29].tx, out[29].n, 0, CScript([OP_RETURN])) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.calc_sha256() self.sign_tx(tx1, out[29].tx, out[29].n) tx1.rehash() tx2 = create_tx(tx1, 1, 0, CScript([OP_RETURN])) tx2.vout.append(CTxOut(0, CScript([OP_RETURN]))) tx3 = create_tx(tx1, 2, 0, CScript([OP_RETURN])) tx3.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx4 = create_tx(tx1, 3, 0, CScript([OP_TRUE])) tx4.vout.append(CTxOut(0, CScript([OP_RETURN]))) tx5 = create_tx(tx1, 4, 0, CScript([OP_RETURN])) update_block(84, [tx1, tx2, tx3, tx4, tx5]) yield accepted() save_spendable_output() tip(83) block(85, spend=out[29]) yield rejected() block(86, spend=out[30]) yield accepted() tip(84) block(87, spend=out[30]) yield rejected() save_spendable_output() block(88, spend=out[31]) yield accepted() save_spendable_output() block("89a", spend=out[32]) tx = create_tx(tx1, 0, 0, CScript([OP_TRUE])) update_block("89a", [tx]) yield rejected() # This test takes a minute or two and can be accomplished in memory # if self.options.runbarelyexpensive: tip(88) LARGE_REORG_SIZE = 1088 test1 = TestInstance(sync_every_block=False) spend = out[32] for i in range(89, LARGE_REORG_SIZE + 89): b = block(i, spend) tx = CTransaction() script_length = LEGACY_MAX_BLOCK_SIZE - len(b.serialize()) - 69 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) tx.vin.append(CTxIn(COutPoint(b.vtx[1].sha256, 0))) b = update_block(i, [tx]) assert_equal(len(b.serialize()), LEGACY_MAX_BLOCK_SIZE) test1.blocks_and_transactions.append([self.tip, True]) save_spendable_output() spend = get_spendable_output() yield test1 chain1_tip = i # now create alt chain of same length tip(88) test2 = TestInstance(sync_every_block=False) for i in range(89, LARGE_REORG_SIZE + 89): block("alt" + str(i)) test2.blocks_and_transactions.append([self.tip, False]) yield test2 # extend alt chain to trigger re-org block("alt" + str(chain1_tip + 1)) yield accepted() # ... and re-org back to the first chain tip(chain1_tip) block(chain1_tip + 1) yield rejected() block(chain1_tip + 2) yield accepted() chain1_tip += 2 if __name__ == '__main__': FullBlockTest().main()
true
true
f72d220cd721047c490c67e94323bd45ebdd24c5
6,988
py
Python
ca/1d-life.py
pghrogue/Sprint-Challenge-BC-Cellular-Automata
0165bfaf0032de63d244793c069efc7bdb734912
[ "MIT" ]
null
null
null
ca/1d-life.py
pghrogue/Sprint-Challenge-BC-Cellular-Automata
0165bfaf0032de63d244793c069efc7bdb734912
[ "MIT" ]
null
null
null
ca/1d-life.py
pghrogue/Sprint-Challenge-BC-Cellular-Automata
0165bfaf0032de63d244793c069efc7bdb734912
[ "MIT" ]
null
null
null
import pygame, random def get_new_value(old_gen, old_automata): # TBC - add code to generate the next row of cells, # then replace the return statement below to # return the updated automata # automata = get_new_value(generations-1, automata) # If each row = 50 cells (0-49) and generations start at 1 # 1: 0-49 # 2: 50-99 # 3: 100-149 automata = old_automata.copy() new_automata = [] for i in range(old_gen + 1): working_row = automata[0:SQ_NUM] # Add this row to the new list new_automata += working_row if i == old_gen: # Calculate new row & add to new list new_automata += get_new_row(working_row) # Delete the row del automata[0:SQ_NUM] # Add the remaining rows to the end new_automata += automata return new_automata def get_new_row(row): # Calculate the new row based on Wolfram's Rule 126 # ... ..# .#. .## #.. #.# ##. ### <- this pattern # . # # # # # # . <- produces this result new_row = [0] * SQ_NUM for i in range(len(row)): neighbors = [i - 1, i, i + 1] n = 0 for pos in neighbors: try: n += row[pos] except: n += 0 if n > 0 and n < 3: new_row[i] = 1 i += 1 return new_row # Define some colors and other constants BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (25, 25, 25) MARGIN = 3 SQ_LENGTH = 10 SQ_NUM = 49 # min squares per row/column is 15 WIN_SIZE = (SQ_NUM+1)*MARGIN + SQ_NUM*SQ_LENGTH BTN_SIZE = 30 pygame.init() # Set the width and height of the screen [width, height] size = (WIN_SIZE, WIN_SIZE + BTN_SIZE+ 20) screen = pygame.display.set_mode(size) automata = [0] * (SQ_NUM*SQ_NUM) generations = 0 time_step = 5 running = True # Assign middle of first row to 1 automata[SQ_NUM//2] = 1 # Add a title pygame.display.set_caption("Wolfram's Rule 126") # Declare some buttons font = pygame.font.Font('freesansbold.ttf', 16) inc_time_step_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(10,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) dec_time_step_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(20+3*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) stop_play_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(30+6*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) restart_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(40+9*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) generation_display = pygame.draw.rect(screen, GRAY, pygame.Rect(60+12*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # -------- Main Program Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEBUTTONDOWN: click_pos = pygame.mouse.get_pos() # use coordinates to check if a btn clicked if inc_time_step_button.collidepoint(click_pos) and time_step < 20: time_step += 1 if dec_time_step_button.collidepoint(click_pos) and time_step > 1: time_step -= 1 if stop_play_button.collidepoint(click_pos): running = not running if restart_button.collidepoint(click_pos): automata = [0] * (SQ_NUM*SQ_NUM) # Assign middle of first row to 1 automata[SQ_NUM//2] = 1 generations = 0 # --- Game logic should go here if running: if generations < SQ_NUM: generations += 1 automata = get_new_value(generations-1, automata) # --- Screen-clearing code goes here # Here, we clear the screen to gray. Don't put other drawing commands # above this, or they will be erased with this command. screen.fill(GRAY) # --- Drawing code should go here y = MARGIN i = 0 while y < WIN_SIZE: x = MARGIN while x < WIN_SIZE: if automata[i] == 0: pygame.draw.rect(screen, BLACK, pygame.Rect(x, y, SQ_LENGTH, SQ_LENGTH)) else: pygame.draw.rect(screen, WHITE, pygame.Rect(x, y, SQ_LENGTH, SQ_LENGTH)) i += 1 x += SQ_LENGTH + MARGIN y += SQ_LENGTH + MARGIN # Update generation count / redraw buttons inc_time_step_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(10,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) text = font.render('Go faster', True, (14, 28, 54) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (inc_time_step_button.center[0], inc_time_step_button.center[1]) screen.blit(text, textRect) dec_time_step_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(20+3*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) text = font.render('Go slower', True, (14, 28, 54) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (dec_time_step_button.center[0], dec_time_step_button.center[1]) screen.blit(text, textRect) stop_play_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(30+6*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) text = font.render('Stop / Play', True, (14, 28, 54) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (stop_play_button.center[0], stop_play_button.center[1]) screen.blit(text, textRect) restart_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(40+9*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) text = font.render('Restart', True, (14, 28, 54) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (restart_button.center[0], restart_button.center[1]) screen.blit(text, textRect) generation_display = pygame.draw.rect(screen, GRAY, pygame.Rect(60+12*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) gen_text = str(generations) + ' generations' text = font.render(gen_text, True, (175, 203, 255) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (generation_display.center[0], generation_display.center[1]) screen.blit(text, textRect) # --- Go ahead and update the screen with what we've drawn. pygame.display.flip() # --- Limit to `time_step` frames per second clock.tick(time_step) # Close the window and quit. pygame.quit()
35.472081
133
0.608042
import pygame, random def get_new_value(old_gen, old_automata): automata = old_automata.copy() new_automata = [] for i in range(old_gen + 1): working_row = automata[0:SQ_NUM] new_automata += working_row if i == old_gen: new_automata += get_new_row(working_row) del automata[0:SQ_NUM] new_automata += automata return new_automata def get_new_row(row): # ... ..# .#. .## #.. #.# ##. ### <- this pattern # . # # # # # # . <- produces this result new_row = [0] * SQ_NUM for i in range(len(row)): neighbors = [i - 1, i, i + 1] n = 0 for pos in neighbors: try: n += row[pos] except: n += 0 if n > 0 and n < 3: new_row[i] = 1 i += 1 return new_row # Define some colors and other constants BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (25, 25, 25) MARGIN = 3 SQ_LENGTH = 10 SQ_NUM = 49 # min squares per row/column is 15 WIN_SIZE = (SQ_NUM+1)*MARGIN + SQ_NUM*SQ_LENGTH BTN_SIZE = 30 pygame.init() # Set the width and height of the screen [width, height] size = (WIN_SIZE, WIN_SIZE + BTN_SIZE+ 20) screen = pygame.display.set_mode(size) automata = [0] * (SQ_NUM*SQ_NUM) generations = 0 time_step = 5 running = True # Assign middle of first row to 1 automata[SQ_NUM//2] = 1 # Add a title pygame.display.set_caption("Wolfram's Rule 126") font = pygame.font.Font('freesansbold.ttf', 16) inc_time_step_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(10,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) dec_time_step_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(20+3*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) stop_play_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(30+6*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) restart_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(40+9*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) generation_display = pygame.draw.rect(screen, GRAY, pygame.Rect(60+12*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) done = False clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEBUTTONDOWN: click_pos = pygame.mouse.get_pos() if inc_time_step_button.collidepoint(click_pos) and time_step < 20: time_step += 1 if dec_time_step_button.collidepoint(click_pos) and time_step > 1: time_step -= 1 if stop_play_button.collidepoint(click_pos): running = not running if restart_button.collidepoint(click_pos): automata = [0] * (SQ_NUM*SQ_NUM) automata[SQ_NUM//2] = 1 generations = 0 if running: if generations < SQ_NUM: generations += 1 automata = get_new_value(generations-1, automata) # above this, or they will be erased with this command. screen.fill(GRAY) # --- Drawing code should go here y = MARGIN i = 0 while y < WIN_SIZE: x = MARGIN while x < WIN_SIZE: if automata[i] == 0: pygame.draw.rect(screen, BLACK, pygame.Rect(x, y, SQ_LENGTH, SQ_LENGTH)) else: pygame.draw.rect(screen, WHITE, pygame.Rect(x, y, SQ_LENGTH, SQ_LENGTH)) i += 1 x += SQ_LENGTH + MARGIN y += SQ_LENGTH + MARGIN # Update generation count / redraw buttons inc_time_step_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(10,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) text = font.render('Go faster', True, (14, 28, 54) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (inc_time_step_button.center[0], inc_time_step_button.center[1]) screen.blit(text, textRect) dec_time_step_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(20+3*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) text = font.render('Go slower', True, (14, 28, 54) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (dec_time_step_button.center[0], dec_time_step_button.center[1]) screen.blit(text, textRect) stop_play_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(30+6*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) text = font.render('Stop / Play', True, (14, 28, 54) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (stop_play_button.center[0], stop_play_button.center[1]) screen.blit(text, textRect) restart_button = pygame.draw.rect(screen, (175, 203, 255), pygame.Rect(40+9*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) text = font.render('Restart', True, (14, 28, 54) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (restart_button.center[0], restart_button.center[1]) screen.blit(text, textRect) generation_display = pygame.draw.rect(screen, GRAY, pygame.Rect(60+12*BTN_SIZE,WIN_SIZE+10,3*BTN_SIZE, BTN_SIZE)) gen_text = str(generations) + ' generations' text = font.render(gen_text, True, (175, 203, 255) ) # set the center of the rectangular object. textRect = text.get_rect() textRect.center = (generation_display.center[0], generation_display.center[1]) screen.blit(text, textRect) # --- Go ahead and update the screen with what we've drawn. pygame.display.flip() clock.tick(time_step) pygame.quit()
true
true
f72d22c9e5b0c4a483dbc497494b6ab24aa21494
13,242
py
Python
pandas/tests/io/parser/test_python_parser_only.py
luftwurzel/pandas
8980af7ce9d98713b0f8792e38f0fe43088e8780
[ "BSD-3-Clause" ]
1
2022-03-29T01:38:03.000Z
2022-03-29T01:38:03.000Z
pandas/tests/io/parser/test_python_parser_only.py
luftwurzel/pandas
8980af7ce9d98713b0f8792e38f0fe43088e8780
[ "BSD-3-Clause" ]
1
2022-03-18T01:26:58.000Z
2022-03-18T01:26:58.000Z
pandas/tests/io/parser/test_python_parser_only.py
luftwurzel/pandas
8980af7ce9d98713b0f8792e38f0fe43088e8780
[ "BSD-3-Clause" ]
1
2022-03-22T11:50:25.000Z
2022-03-22T11:50:25.000Z
""" Tests that apply specifically to the Python parser. Unless specifically stated as a Python-specific issue, the goal is to eventually move as many of these tests out of this module as soon as the C parser can accept further arguments when parsing. """ from __future__ import annotations import csv from io import ( BytesIO, StringIO, ) import pytest from pandas.errors import ( ParserError, ParserWarning, ) from pandas import ( DataFrame, Index, MultiIndex, ) import pandas._testing as tm def test_default_separator(python_parser_only): # see gh-17333 # # csv.Sniffer in Python treats "o" as separator. data = "aob\n1o2\n3o4" parser = python_parser_only expected = DataFrame({"a": [1, 3], "b": [2, 4]}) result = parser.read_csv(StringIO(data), sep=None) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("skipfooter", ["foo", 1.5, True]) def test_invalid_skipfooter_non_int(python_parser_only, skipfooter): # see gh-15925 (comment) data = "a\n1\n2" parser = python_parser_only msg = "skipfooter must be an integer" with pytest.raises(ValueError, match=msg): parser.read_csv(StringIO(data), skipfooter=skipfooter) def test_invalid_skipfooter_negative(python_parser_only): # see gh-15925 (comment) data = "a\n1\n2" parser = python_parser_only msg = "skipfooter cannot be negative" with pytest.raises(ValueError, match=msg): parser.read_csv(StringIO(data), skipfooter=-1) @pytest.mark.parametrize("kwargs", [{"sep": None}, {"delimiter": "|"}]) def test_sniff_delimiter(python_parser_only, kwargs): data = """index|A|B|C foo|1|2|3 bar|4|5|6 baz|7|8|9 """ parser = python_parser_only result = parser.read_csv(StringIO(data), index_col=0, **kwargs) expected = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"], index=Index(["foo", "bar", "baz"], name="index"), ) tm.assert_frame_equal(result, expected) def test_sniff_delimiter_comment(python_parser_only): data = """# comment line index|A|B|C # comment line foo|1|2|3 # ignore | this bar|4|5|6 baz|7|8|9 """ parser = python_parser_only result = parser.read_csv(StringIO(data), index_col=0, sep=None, comment="#") expected = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"], index=Index(["foo", "bar", "baz"], name="index"), ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("encoding", [None, "utf-8"]) def test_sniff_delimiter_encoding(python_parser_only, encoding): parser = python_parser_only data = """ignore this ignore this too index|A|B|C foo|1|2|3 bar|4|5|6 baz|7|8|9 """ if encoding is not None: from io import TextIOWrapper data = data.encode(encoding) data = BytesIO(data) data = TextIOWrapper(data, encoding=encoding) else: data = StringIO(data) result = parser.read_csv(data, index_col=0, sep=None, skiprows=2, encoding=encoding) expected = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"], index=Index(["foo", "bar", "baz"], name="index"), ) tm.assert_frame_equal(result, expected) def test_single_line(python_parser_only): # see gh-6607: sniff separator parser = python_parser_only result = parser.read_csv(StringIO("1,2"), names=["a", "b"], header=None, sep=None) expected = DataFrame({"a": [1], "b": [2]}) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("kwargs", [{"skipfooter": 2}, {"nrows": 3}]) def test_skipfooter(python_parser_only, kwargs): # see gh-6607 data = """A,B,C 1,2,3 4,5,6 7,8,9 want to skip this also also skip this """ parser = python_parser_only result = parser.read_csv(StringIO(data), **kwargs) expected = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"]) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "compression,klass", [("gzip", "GzipFile"), ("bz2", "BZ2File")] ) def test_decompression_regex_sep(python_parser_only, csv1, compression, klass): # see gh-6607 parser = python_parser_only with open(csv1, "rb") as f: data = f.read() data = data.replace(b",", b"::") expected = parser.read_csv(csv1) module = pytest.importorskip(compression) klass = getattr(module, klass) with tm.ensure_clean() as path: with klass(path, mode="wb") as tmp: tmp.write(data) result = parser.read_csv(path, sep="::", compression=compression) tm.assert_frame_equal(result, expected) def test_read_csv_buglet_4x_multi_index(python_parser_only): # see gh-6607 data = """ A B C D E one two three four a b 10.0032 5 -0.5109 -2.3358 -0.4645 0.05076 0.3640 a q 20 4 0.4473 1.4152 0.2834 1.00661 0.1744 x q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838""" parser = python_parser_only expected = DataFrame( [ [-0.5109, -2.3358, -0.4645, 0.05076, 0.3640], [0.4473, 1.4152, 0.2834, 1.00661, 0.1744], [-0.6662, -0.5243, -0.3580, 0.89145, 2.5838], ], columns=["A", "B", "C", "D", "E"], index=MultiIndex.from_tuples( [("a", "b", 10.0032, 5), ("a", "q", 20, 4), ("x", "q", 30, 3)], names=["one", "two", "three", "four"], ), ) result = parser.read_csv(StringIO(data), sep=r"\s+") tm.assert_frame_equal(result, expected) def test_read_csv_buglet_4x_multi_index2(python_parser_only): # see gh-6893 data = " A B C\na b c\n1 3 7 0 3 6\n3 1 4 1 5 9" parser = python_parser_only expected = DataFrame.from_records( [(1, 3, 7, 0, 3, 6), (3, 1, 4, 1, 5, 9)], columns=list("abcABC"), index=list("abc"), ) result = parser.read_csv(StringIO(data), sep=r"\s+") tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("add_footer", [True, False]) def test_skipfooter_with_decimal(python_parser_only, add_footer): # see gh-6971 data = "1#2\n3#4" parser = python_parser_only expected = DataFrame({"a": [1.2, 3.4]}) if add_footer: # The stray footer line should not mess with the # casting of the first two lines if we skip it. kwargs = {"skipfooter": 1} data += "\nFooter" else: kwargs = {} result = parser.read_csv(StringIO(data), names=["a"], decimal="#", **kwargs) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "sep", ["::", "#####", "!!!", "123", "#1!c5", "%!c!d", "@@#4:2", "_!pd#_"] ) @pytest.mark.parametrize( "encoding", ["utf-16", "utf-16-be", "utf-16-le", "utf-32", "cp037"] ) def test_encoding_non_utf8_multichar_sep(python_parser_only, sep, encoding): # see gh-3404 expected = DataFrame({"a": [1], "b": [2]}) parser = python_parser_only data = "1" + sep + "2" encoded_data = data.encode(encoding) result = parser.read_csv( BytesIO(encoded_data), sep=sep, names=["a", "b"], encoding=encoding ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("quoting", [csv.QUOTE_MINIMAL, csv.QUOTE_NONE]) def test_multi_char_sep_quotes(python_parser_only, quoting): # see gh-13374 kwargs = {"sep": ",,"} parser = python_parser_only data = 'a,,b\n1,,a\n2,,"2,,b"' if quoting == csv.QUOTE_NONE: msg = "Expected 2 fields in line 3, saw 3" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), quoting=quoting, **kwargs) else: msg = "ignored when a multi-char delimiter is used" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), quoting=quoting, **kwargs) def test_none_delimiter(python_parser_only, capsys): # see gh-13374 and gh-17465 parser = python_parser_only data = "a,b,c\n0,1,2\n3,4,5,6\n7,8,9" expected = DataFrame({"a": [0, 7], "b": [1, 8], "c": [2, 9]}) # We expect the third line in the data to be # skipped because it is malformed, but we do # not expect any errors to occur. result = parser.read_csv(StringIO(data), header=0, sep=None, on_bad_lines="warn") tm.assert_frame_equal(result, expected) captured = capsys.readouterr() assert "Skipping line 3" in captured.err @pytest.mark.parametrize("data", ['a\n1\n"b"a', 'a,b,c\ncat,foo,bar\ndog,foo,"baz']) @pytest.mark.parametrize("skipfooter", [0, 1]) def test_skipfooter_bad_row(python_parser_only, data, skipfooter): # see gh-13879 and gh-15910 parser = python_parser_only if skipfooter: msg = "parsing errors in the skipped footer rows" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), skipfooter=skipfooter) else: msg = "unexpected end of data|expected after" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), skipfooter=skipfooter) def test_malformed_skipfooter(python_parser_only): parser = python_parser_only data = """ignore A,B,C 1,2,3 # comment 1,2,3,4,5 2,3,4 footer """ msg = "Expected 3 fields in line 4, saw 5" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), header=1, comment="#", skipfooter=1) def test_python_engine_file_no_next(python_parser_only): parser = python_parser_only class NoNextBuffer: def __init__(self, csv_data) -> None: self.data = csv_data def __iter__(self): return self.data.__iter__() def read(self): return self.data def readline(self): return self.data parser.read_csv(NoNextBuffer("a\n1")) @pytest.mark.parametrize("bad_line_func", [lambda x: ["2", "3"], lambda x: x[:2]]) def test_on_bad_lines_callable(python_parser_only, bad_line_func): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) result = parser.read_csv(bad_sio, on_bad_lines=bad_line_func) expected = DataFrame({"a": [1, 2, 3], "b": [2, 3, 4]}) tm.assert_frame_equal(result, expected) def test_on_bad_lines_callable_write_to_external_list(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) lst = [] def bad_line_func(bad_line: list[str]) -> list[str]: lst.append(bad_line) return ["2", "3"] result = parser.read_csv(bad_sio, on_bad_lines=bad_line_func) expected = DataFrame({"a": [1, 2, 3], "b": [2, 3, 4]}) tm.assert_frame_equal(result, expected) assert lst == [["2", "3", "4", "5", "6"]] @pytest.mark.parametrize("bad_line_func", [lambda x: ["foo", "bar"], lambda x: x[:2]]) @pytest.mark.parametrize("sep", [",", "111"]) def test_on_bad_lines_callable_iterator_true(python_parser_only, bad_line_func, sep): # GH 5686 # iterator=True has a separate code path than iterator=False parser = python_parser_only data = f""" 0{sep}1 hi{sep}there foo{sep}bar{sep}baz good{sep}bye """ bad_sio = StringIO(data) result_iter = parser.read_csv( bad_sio, on_bad_lines=bad_line_func, chunksize=1, iterator=True, sep=sep ) expecteds = [ {"0": "hi", "1": "there"}, {"0": "foo", "1": "bar"}, {"0": "good", "1": "bye"}, ] for i, (result, expected) in enumerate(zip(result_iter, expecteds)): expected = DataFrame(expected, index=range(i, i + 1)) tm.assert_frame_equal(result, expected) def test_on_bad_lines_callable_dont_swallow_errors(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) msg = "This function is buggy." def bad_line_func(bad_line): raise ValueError(msg) with pytest.raises(ValueError, match=msg): parser.read_csv(bad_sio, on_bad_lines=bad_line_func) def test_on_bad_lines_callable_not_expected_length(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) with tm.assert_produces_warning(ParserWarning, match="Length of header or names"): result = parser.read_csv(bad_sio, on_bad_lines=lambda x: x) expected = DataFrame({"a": [1, 2, 3], "b": [2, 3, 4]}) tm.assert_frame_equal(result, expected) def test_on_bad_lines_callable_returns_none(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) result = parser.read_csv(bad_sio, on_bad_lines=lambda x: None) expected = DataFrame({"a": [1, 3], "b": [2, 4]}) tm.assert_frame_equal(result, expected) def test_on_bad_lines_index_col_inferred(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2,3 4,5,6 """ bad_sio = StringIO(data) result = parser.read_csv(bad_sio, on_bad_lines=lambda x: ["99", "99"]) expected = DataFrame({"a": [2, 5], "b": [3, 6]}, index=[1, 4]) tm.assert_frame_equal(result, expected)
28.786957
88
0.633515
from __future__ import annotations import csv from io import ( BytesIO, StringIO, ) import pytest from pandas.errors import ( ParserError, ParserWarning, ) from pandas import ( DataFrame, Index, MultiIndex, ) import pandas._testing as tm def test_default_separator(python_parser_only): data = "aob\n1o2\n3o4" parser = python_parser_only expected = DataFrame({"a": [1, 3], "b": [2, 4]}) result = parser.read_csv(StringIO(data), sep=None) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("skipfooter", ["foo", 1.5, True]) def test_invalid_skipfooter_non_int(python_parser_only, skipfooter): data = "a\n1\n2" parser = python_parser_only msg = "skipfooter must be an integer" with pytest.raises(ValueError, match=msg): parser.read_csv(StringIO(data), skipfooter=skipfooter) def test_invalid_skipfooter_negative(python_parser_only): data = "a\n1\n2" parser = python_parser_only msg = "skipfooter cannot be negative" with pytest.raises(ValueError, match=msg): parser.read_csv(StringIO(data), skipfooter=-1) @pytest.mark.parametrize("kwargs", [{"sep": None}, {"delimiter": "|"}]) def test_sniff_delimiter(python_parser_only, kwargs): data = """index|A|B|C foo|1|2|3 bar|4|5|6 baz|7|8|9 """ parser = python_parser_only result = parser.read_csv(StringIO(data), index_col=0, **kwargs) expected = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"], index=Index(["foo", "bar", "baz"], name="index"), ) tm.assert_frame_equal(result, expected) def test_sniff_delimiter_comment(python_parser_only): data = """# comment line index|A|B|C # comment line foo|1|2|3 # ignore | this bar|4|5|6 baz|7|8|9 """ parser = python_parser_only result = parser.read_csv(StringIO(data), index_col=0, sep=None, comment="#") expected = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"], index=Index(["foo", "bar", "baz"], name="index"), ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("encoding", [None, "utf-8"]) def test_sniff_delimiter_encoding(python_parser_only, encoding): parser = python_parser_only data = """ignore this ignore this too index|A|B|C foo|1|2|3 bar|4|5|6 baz|7|8|9 """ if encoding is not None: from io import TextIOWrapper data = data.encode(encoding) data = BytesIO(data) data = TextIOWrapper(data, encoding=encoding) else: data = StringIO(data) result = parser.read_csv(data, index_col=0, sep=None, skiprows=2, encoding=encoding) expected = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"], index=Index(["foo", "bar", "baz"], name="index"), ) tm.assert_frame_equal(result, expected) def test_single_line(python_parser_only): parser = python_parser_only result = parser.read_csv(StringIO("1,2"), names=["a", "b"], header=None, sep=None) expected = DataFrame({"a": [1], "b": [2]}) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("kwargs", [{"skipfooter": 2}, {"nrows": 3}]) def test_skipfooter(python_parser_only, kwargs): data = """A,B,C 1,2,3 4,5,6 7,8,9 want to skip this also also skip this """ parser = python_parser_only result = parser.read_csv(StringIO(data), **kwargs) expected = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"]) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "compression,klass", [("gzip", "GzipFile"), ("bz2", "BZ2File")] ) def test_decompression_regex_sep(python_parser_only, csv1, compression, klass): parser = python_parser_only with open(csv1, "rb") as f: data = f.read() data = data.replace(b",", b"::") expected = parser.read_csv(csv1) module = pytest.importorskip(compression) klass = getattr(module, klass) with tm.ensure_clean() as path: with klass(path, mode="wb") as tmp: tmp.write(data) result = parser.read_csv(path, sep="::", compression=compression) tm.assert_frame_equal(result, expected) def test_read_csv_buglet_4x_multi_index(python_parser_only): data = """ A B C D E one two three four a b 10.0032 5 -0.5109 -2.3358 -0.4645 0.05076 0.3640 a q 20 4 0.4473 1.4152 0.2834 1.00661 0.1744 x q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838""" parser = python_parser_only expected = DataFrame( [ [-0.5109, -2.3358, -0.4645, 0.05076, 0.3640], [0.4473, 1.4152, 0.2834, 1.00661, 0.1744], [-0.6662, -0.5243, -0.3580, 0.89145, 2.5838], ], columns=["A", "B", "C", "D", "E"], index=MultiIndex.from_tuples( [("a", "b", 10.0032, 5), ("a", "q", 20, 4), ("x", "q", 30, 3)], names=["one", "two", "three", "four"], ), ) result = parser.read_csv(StringIO(data), sep=r"\s+") tm.assert_frame_equal(result, expected) def test_read_csv_buglet_4x_multi_index2(python_parser_only): data = " A B C\na b c\n1 3 7 0 3 6\n3 1 4 1 5 9" parser = python_parser_only expected = DataFrame.from_records( [(1, 3, 7, 0, 3, 6), (3, 1, 4, 1, 5, 9)], columns=list("abcABC"), index=list("abc"), ) result = parser.read_csv(StringIO(data), sep=r"\s+") tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("add_footer", [True, False]) def test_skipfooter_with_decimal(python_parser_only, add_footer): data = "1#2\n3#4" parser = python_parser_only expected = DataFrame({"a": [1.2, 3.4]}) if add_footer: kwargs = {"skipfooter": 1} data += "\nFooter" else: kwargs = {} result = parser.read_csv(StringIO(data), names=["a"], decimal="#", **kwargs) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "sep", ["::", "#####", "!!!", "123", "#1!c5", "%!c!d", "@@#4:2", "_!pd#_"] ) @pytest.mark.parametrize( "encoding", ["utf-16", "utf-16-be", "utf-16-le", "utf-32", "cp037"] ) def test_encoding_non_utf8_multichar_sep(python_parser_only, sep, encoding): expected = DataFrame({"a": [1], "b": [2]}) parser = python_parser_only data = "1" + sep + "2" encoded_data = data.encode(encoding) result = parser.read_csv( BytesIO(encoded_data), sep=sep, names=["a", "b"], encoding=encoding ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("quoting", [csv.QUOTE_MINIMAL, csv.QUOTE_NONE]) def test_multi_char_sep_quotes(python_parser_only, quoting): kwargs = {"sep": ",,"} parser = python_parser_only data = 'a,,b\n1,,a\n2,,"2,,b"' if quoting == csv.QUOTE_NONE: msg = "Expected 2 fields in line 3, saw 3" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), quoting=quoting, **kwargs) else: msg = "ignored when a multi-char delimiter is used" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), quoting=quoting, **kwargs) def test_none_delimiter(python_parser_only, capsys): parser = python_parser_only data = "a,b,c\n0,1,2\n3,4,5,6\n7,8,9" expected = DataFrame({"a": [0, 7], "b": [1, 8], "c": [2, 9]}) result = parser.read_csv(StringIO(data), header=0, sep=None, on_bad_lines="warn") tm.assert_frame_equal(result, expected) captured = capsys.readouterr() assert "Skipping line 3" in captured.err @pytest.mark.parametrize("data", ['a\n1\n"b"a', 'a,b,c\ncat,foo,bar\ndog,foo,"baz']) @pytest.mark.parametrize("skipfooter", [0, 1]) def test_skipfooter_bad_row(python_parser_only, data, skipfooter): # see gh-13879 and gh-15910 parser = python_parser_only if skipfooter: msg = "parsing errors in the skipped footer rows" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), skipfooter=skipfooter) else: msg = "unexpected end of data|expected after" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), skipfooter=skipfooter) def test_malformed_skipfooter(python_parser_only): parser = python_parser_only data = """ignore A,B,C 1,2,3 # comment 1,2,3,4,5 2,3,4 footer """ msg = "Expected 3 fields in line 4, saw 5" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), header=1, comment=" def test_python_engine_file_no_next(python_parser_only): parser = python_parser_only class NoNextBuffer: def __init__(self, csv_data) -> None: self.data = csv_data def __iter__(self): return self.data.__iter__() def read(self): return self.data def readline(self): return self.data parser.read_csv(NoNextBuffer("a\n1")) @pytest.mark.parametrize("bad_line_func", [lambda x: ["2", "3"], lambda x: x[:2]]) def test_on_bad_lines_callable(python_parser_only, bad_line_func): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) result = parser.read_csv(bad_sio, on_bad_lines=bad_line_func) expected = DataFrame({"a": [1, 2, 3], "b": [2, 3, 4]}) tm.assert_frame_equal(result, expected) def test_on_bad_lines_callable_write_to_external_list(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) lst = [] def bad_line_func(bad_line: list[str]) -> list[str]: lst.append(bad_line) return ["2", "3"] result = parser.read_csv(bad_sio, on_bad_lines=bad_line_func) expected = DataFrame({"a": [1, 2, 3], "b": [2, 3, 4]}) tm.assert_frame_equal(result, expected) assert lst == [["2", "3", "4", "5", "6"]] @pytest.mark.parametrize("bad_line_func", [lambda x: ["foo", "bar"], lambda x: x[:2]]) @pytest.mark.parametrize("sep", [",", "111"]) def test_on_bad_lines_callable_iterator_true(python_parser_only, bad_line_func, sep): # GH 5686 # iterator=True has a separate code path than iterator=False parser = python_parser_only data = f""" 0{sep}1 hi{sep}there foo{sep}bar{sep}baz good{sep}bye """ bad_sio = StringIO(data) result_iter = parser.read_csv( bad_sio, on_bad_lines=bad_line_func, chunksize=1, iterator=True, sep=sep ) expecteds = [ {"0": "hi", "1": "there"}, {"0": "foo", "1": "bar"}, {"0": "good", "1": "bye"}, ] for i, (result, expected) in enumerate(zip(result_iter, expecteds)): expected = DataFrame(expected, index=range(i, i + 1)) tm.assert_frame_equal(result, expected) def test_on_bad_lines_callable_dont_swallow_errors(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) msg = "This function is buggy." def bad_line_func(bad_line): raise ValueError(msg) with pytest.raises(ValueError, match=msg): parser.read_csv(bad_sio, on_bad_lines=bad_line_func) def test_on_bad_lines_callable_not_expected_length(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) with tm.assert_produces_warning(ParserWarning, match="Length of header or names"): result = parser.read_csv(bad_sio, on_bad_lines=lambda x: x) expected = DataFrame({"a": [1, 2, 3], "b": [2, 3, 4]}) tm.assert_frame_equal(result, expected) def test_on_bad_lines_callable_returns_none(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2 2,3,4,5,6 3,4 """ bad_sio = StringIO(data) result = parser.read_csv(bad_sio, on_bad_lines=lambda x: None) expected = DataFrame({"a": [1, 3], "b": [2, 4]}) tm.assert_frame_equal(result, expected) def test_on_bad_lines_index_col_inferred(python_parser_only): # GH 5686 parser = python_parser_only data = """a,b 1,2,3 4,5,6 """ bad_sio = StringIO(data) result = parser.read_csv(bad_sio, on_bad_lines=lambda x: ["99", "99"]) expected = DataFrame({"a": [2, 5], "b": [3, 6]}, index=[1, 4]) tm.assert_frame_equal(result, expected)
true
true
f72d26ac34029c16b97220fe6f4e82f84591a1ca
867
py
Python
zulip_bots/zulip_bots/bots/tyro/fb_login.py
tuhinspatra/tyro-zulip-bot
29c149af1b01955e50564e31cff03331fa723880
[ "MIT" ]
1
2020-05-25T11:52:31.000Z
2020-05-25T11:52:31.000Z
zulip_bots/zulip_bots/bots/tyro/fb_login.py
armag-pro/tyro-zulip-bot
29c149af1b01955e50564e31cff03331fa723880
[ "MIT" ]
6
2020-03-24T16:39:54.000Z
2021-04-30T20:46:43.000Z
zulip_bots/zulip_bots/bots/tyro/fb_login.py
tuhinspatra/tyro-zulip-bot
29c149af1b01955e50564e31cff03331fa723880
[ "MIT" ]
3
2019-01-26T21:40:16.000Z
2019-02-24T20:16:26.000Z
import requests from selenium import webdriver from selenium.webdriver.common.keys import Keys def fblogin(bot_handler,message): if len(message)>=2: e=message[0] p=message[1] driver = webdriver.Chrome('/home/jugtaram/Downloads/chromedriver/chromedriver') driver.get('http://www.google.com/xhtml') time.sleep(1) search_box = driver.find_element_by_name('q') search_box.send_keys('fb') search_box.submit() time.sleep(1) fblink=driver.find_element_by_link_text('facebook.com') type(fblink) time.sleep(1) fblink.click() time.sleep(1) form=driver.find_element_by_id('login_form') email=driver.find_element_by_name('email') password=driver.find_element_by_name('pass') email.send_keys(e) password.send_keys(p) time.sleep(1) form.submit() return "fb login successfully." else: return "login <mobile no.> <password> :)"
27.967742
83
0.739331
import requests from selenium import webdriver from selenium.webdriver.common.keys import Keys def fblogin(bot_handler,message): if len(message)>=2: e=message[0] p=message[1] driver = webdriver.Chrome('/home/jugtaram/Downloads/chromedriver/chromedriver') driver.get('http://www.google.com/xhtml') time.sleep(1) search_box = driver.find_element_by_name('q') search_box.send_keys('fb') search_box.submit() time.sleep(1) fblink=driver.find_element_by_link_text('facebook.com') type(fblink) time.sleep(1) fblink.click() time.sleep(1) form=driver.find_element_by_id('login_form') email=driver.find_element_by_name('email') password=driver.find_element_by_name('pass') email.send_keys(e) password.send_keys(p) time.sleep(1) form.submit() return "fb login successfully." else: return "login <mobile no.> <password> :)"
true
true
f72d27381ef9a8326bf0fa9c73f1a02d54aac435
51
py
Python
recognition/learning_error_exception.py
SubmergedTree/SmartMirror
c822469f0d4340a31873fe623290cf4bcd745b5f
[ "MIT" ]
null
null
null
recognition/learning_error_exception.py
SubmergedTree/SmartMirror
c822469f0d4340a31873fe623290cf4bcd745b5f
[ "MIT" ]
1
2021-10-12T22:04:20.000Z
2021-10-12T22:04:20.000Z
recognition/learning_error_exception.py
SubmergedTree/SmartMirror
c822469f0d4340a31873fe623290cf4bcd745b5f
[ "MIT" ]
null
null
null
class LearningErrorException(Exception): pass
12.75
40
0.784314
class LearningErrorException(Exception): pass
true
true
f72d2884a4c116033ae93117d3448f7e063ac329
323
py
Python
tests/PartitionerTest/test_geom.py
stu314159/tLBM
1256c5b12fc315d59e08d704c6cef72200e9f01c
[ "MIT" ]
null
null
null
tests/PartitionerTest/test_geom.py
stu314159/tLBM
1256c5b12fc315d59e08d704c6cef72200e9f01c
[ "MIT" ]
null
null
null
tests/PartitionerTest/test_geom.py
stu314159/tLBM
1256c5b12fc315d59e08d704c6cef72200e9f01c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import sys sys.path.insert(1,'../../python') import FluidChannel as fc import numpy as np aLx_p = 1.0; aLy_p = 1.0; aLz_p = 5.0; aNdivs = 11; emptyChan = fc.FluidChannel(Lx_p = aLx_p,Ly_p = aLy_p, Lz_p = aLz_p, N_divs = aNdivs); emptyChan.write_mat_file('test_geom');
17.944444
58
0.634675
import sys sys.path.insert(1,'../../python') import FluidChannel as fc import numpy as np aLx_p = 1.0; aLy_p = 1.0; aLz_p = 5.0; aNdivs = 11; emptyChan = fc.FluidChannel(Lx_p = aLx_p,Ly_p = aLy_p, Lz_p = aLz_p, N_divs = aNdivs); emptyChan.write_mat_file('test_geom');
true
true
f72d28af1ec1193a05b944fcc0ecd4e67dee8ef2
3,876
py
Python
lib/bx/align/tools/thread.py
mr-c/bx-python
0b2b766eee008d1f7a2814be4ddd2c5dc3787537
[ "MIT" ]
null
null
null
lib/bx/align/tools/thread.py
mr-c/bx-python
0b2b766eee008d1f7a2814be4ddd2c5dc3787537
[ "MIT" ]
null
null
null
lib/bx/align/tools/thread.py
mr-c/bx-python
0b2b766eee008d1f7a2814be4ddd2c5dc3787537
[ "MIT" ]
null
null
null
""" Tools for "threading" out specific species from alignments (removing other species and fixing alignment text). """ from copy import deepcopy def thread(mafs, species): """ Restrict an list of alignments to a given list of species by: 1) Removing components for any other species 2) Remove any columns containing all gaps Example: >>> import bx.align.maf >>> block1 = bx.align.maf.from_string( ''' ... a score=4964.0 ... s hg18.chr10 52686 44 + 135374737 GTGCTAACTTACTGCTCCACAGAAAACATCAATTCTGCTCATGC ... s rheMac2.chr20 58163346 43 - 88221753 ATATTATCTTAACATTAAAGA-AGAACAGTAATTCTGGTCATAA ... s panTro1.chrUn_random 208115356 44 - 240967748 GTGCTAACTGACTGCTCCAGAGAAAACATCAATTCTGTTCATGT ... s oryCun1.scaffold_175207 85970 22 + 212797 ----------------------AAAATATTAGTTATCACCATAT ... s bosTau2.chr23 23894492 43 + 41602928 AAACTACCTTAATGTCACAGG-AAACAATGTATgctgctgctgc ... ''' ) >>> block2 = bx.align.maf.from_string( ''' ... a score=9151.0 ... s hg18.chr10 52730 69 + 135374737 GCAGGTACAATTCATCAAGAAAG-GAATTACAACTTCAGAAATGTGTTCAAAATATATCCATACTT-TGAC ... s oryCun1.scaffold_175207 85992 71 + 212797 TCTAGTGCTCTCCAATAATATAATAGATTATAACTTCATATAATTATGTGAAATATAAGATTATTTATCAG ... s panTro1.chrUn_random 208115400 69 - 240967748 GCAGCTACTATTCATCAAGAAAG-GGATTACAACTTCAGAAATGTGTTCAAAGTGTATCCATACTT-TGAT ... s rheMac2.chr20 58163389 69 - 88221753 ACACATATTATTTCTTAACATGGAGGATTATATCTT-AAACATGTGTGCaaaatataaatatatat-tcaa ... ''' ) >>> mafs = [ block1, block2 ] >>> threaded = [ t for t in thread( mafs, [ "hg18", "panTro1" ] ) ] >>> len( threaded ) 2 >>> print(threaded[0]) a score=0.0 s hg18.chr10 52686 44 + 135374737 GTGCTAACTTACTGCTCCACAGAAAACATCAATTCTGCTCATGC s panTro1.chrUn_random 208115356 44 - 240967748 GTGCTAACTGACTGCTCCAGAGAAAACATCAATTCTGTTCATGT <BLANKLINE> >>> print(threaded[1]) a score=0.0 s hg18.chr10 52730 69 + 135374737 GCAGGTACAATTCATCAAGAAAGGAATTACAACTTCAGAAATGTGTTCAAAATATATCCATACTTTGAC s panTro1.chrUn_random 208115400 69 - 240967748 GCAGCTACTATTCATCAAGAAAGGGATTACAACTTCAGAAATGTGTTCAAAGTGTATCCATACTTTGAT <BLANKLINE> """ for m in mafs: new_maf = deepcopy(m) new_components = get_components_for_species(new_maf, species) if new_components: remove_all_gap_columns(new_components) new_maf.components = new_components new_maf.score = 0.0 new_maf.text_size = len(new_components[0].text) yield new_maf def get_components_for_species(alignment, species): """Return the component for each species in the list `species` or None""" # If the number of components in the alignment is less that the requested number # of species we can immediately fail if len(alignment.components) < len(species): return None # Otherwise, build an index of components by species, then lookup index = dict([(c.src.split('.')[0], c) for c in alignment.components]) try: return [index[s] for s in species] except Exception: return None def remove_all_gap_columns(components): """ Remove any columns containing only gaps from a set of alignment components, text of components is modified IN PLACE. TODO: Optimize this with Pyrex. """ seqs = [list(c.text) for c in components] i = 0 text_size = len(seqs[0]) while i < text_size: all_gap = True for seq in seqs: if seq[i] != '-': all_gap = False if all_gap: for seq in seqs: del seq[i] text_size -= 1 else: i += 1 for i in range(len(components)): components[i].text = ''.join(seqs[i])
36.914286
130
0.663829
from copy import deepcopy def thread(mafs, species): for m in mafs: new_maf = deepcopy(m) new_components = get_components_for_species(new_maf, species) if new_components: remove_all_gap_columns(new_components) new_maf.components = new_components new_maf.score = 0.0 new_maf.text_size = len(new_components[0].text) yield new_maf def get_components_for_species(alignment, species): if len(alignment.components) < len(species): return None index = dict([(c.src.split('.')[0], c) for c in alignment.components]) try: return [index[s] for s in species] except Exception: return None def remove_all_gap_columns(components): seqs = [list(c.text) for c in components] i = 0 text_size = len(seqs[0]) while i < text_size: all_gap = True for seq in seqs: if seq[i] != '-': all_gap = False if all_gap: for seq in seqs: del seq[i] text_size -= 1 else: i += 1 for i in range(len(components)): components[i].text = ''.join(seqs[i])
true
true
f72d28c7ae1172bb24daa73c1333bd9c22f501e4
662
py
Python
hospital/migrations/0014_auto_20180727_1635.py
mohitkyadav/calldoc
ebdcdcfac346e995c44cbf94a3c87c25ba594ee1
[ "MIT" ]
9
2019-05-19T14:00:03.000Z
2019-05-21T14:19:56.000Z
hospital/migrations/0014_auto_20180727_1635.py
mohitkyadav/calldoc
ebdcdcfac346e995c44cbf94a3c87c25ba594ee1
[ "MIT" ]
8
2019-05-20T12:29:08.000Z
2022-02-10T11:06:55.000Z
hospital/migrations/0014_auto_20180727_1635.py
mohitkyadav/calldoc
ebdcdcfac346e995c44cbf94a3c87c25ba594ee1
[ "MIT" ]
1
2019-05-20T07:04:20.000Z
2019-05-20T07:04:20.000Z
# Generated by Django 2.0.5 on 2018-07-27 11:05 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hospital', '0013_hospital_verified'), ] operations = [ migrations.AlterField( model_name='hospital', name='phone_number', field=models.CharField(blank=True, help_text='Please enter valid email, it will be used for verification.', max_length=17, validators=[django.core.validators.RegexValidator(message="Phone number must be entered in the format:\\ '+919999999999'.", regex='^\\+?1?\\d{9,15}$')]), ), ]
33.1
288
0.663142
import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hospital', '0013_hospital_verified'), ] operations = [ migrations.AlterField( model_name='hospital', name='phone_number', field=models.CharField(blank=True, help_text='Please enter valid email, it will be used for verification.', max_length=17, validators=[django.core.validators.RegexValidator(message="Phone number must be entered in the format:\\ '+919999999999'.", regex='^\\+?1?\\d{9,15}$')]), ), ]
true
true
f72d2969cb4da475bd90bb46276e9d83169e8b9f
3,113
py
Python
preprocessing/GTEx/filter_by_tissue.py
arnegebert/splicing
3e19ce83a9f6d98bc6c2d8b653660d22e453ca77
[ "MIT" ]
1
2021-05-13T15:30:39.000Z
2021-05-13T15:30:39.000Z
preprocessing/GTEx/filter_by_tissue.py
arnegebert/splicing
3e19ce83a9f6d98bc6c2d8b653660d22e453ca77
[ "MIT" ]
null
null
null
preprocessing/GTEx/filter_by_tissue.py
arnegebert/splicing
3e19ce83a9f6d98bc6c2d8b653660d22e453ca77
[ "MIT" ]
null
null
null
import csv import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument('--tissue', type=str, default='Brain - Cortex', metavar='tissue', help='type of tissue filtered for') parser.add_argument('--save-to', type=str, default='../../data/gtex_processed/brain_cortex_junction_reads_one_sample.csv', metavar='save_to', help='path to folder and file to save to') args = parser.parse_args() tissue = args.tissue # tissue = 'Heart - Left Ventricle'# args.tissue # tissue = 'Brain - Cerebellum' # Brain - Cortex == Brain - Frontal Cortex (BA9) # Brain - Cerebellum == Brain - Cerebellar Hemisphere allowed_tissues = ['Brain - Cortex', 'Brain - Cerebellum', 'Heart - Left Ventricle'] assert tissue in allowed_tissues path_annotation = '../../data/gtex_origin/GTEx_Analysis_v8_Annotations_SampleAttributesDS.txt' path_junction_reads = '../../data/gtex_origin/GTEx_Analysis_2017-06-05_v8_STARv2.5.3a_junctions.gct' save_to = args.save_to # save_to = '../../data/gtex_processed/brain_cortex_junction_reads_one_sample.csv' # path_srcs = '../../data/gtex_origin/GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_tpm.gct' # Brain - Cortex sample with id 164 corresonds to sample id 'GTEX-1F7RK-1826-SM-7RHI4' # that is, 1F7RK is the donor id def load_annotation_file(path_annotation): with open(path_annotation) as f: reader = csv.reader(f, delimiter="\t") # contains list with rows of samples d = list(reader) return d annotation_data = load_annotation_file(path_annotation) def find_sample_with_desired_donor_and_tissue_type(annotation_data, tissue, donor_name): for i, row in enumerate(annotation_data): curr_sample_id = row[0] if donor_name in curr_sample_id: # found sample from desired donor if tissue in row: # sample from donor of sought after tissue type return curr_sample_id # This donor has tissue samples from all the tissues we want to examine # Was selected in a previous processing step desired_donor = '1HCVE' target_sample_name = find_sample_with_desired_donor_and_tissue_type(annotation_data, tissue, desired_donor) sample_idxs = [] data = [] total_reads = 0 with open(path_junction_reads) as f: for i, line in enumerate(f): if i % 1000 == 0: # ~ 357500 junctions print(f'Reading line {i}') line = line.split('\t') if i < 2: continue elif i == 2: # line 2 contains all sample names desired_donor_idx = line.find(target_sample_name) elif i > 2: gene = line[1] dot_idx = gene.index('.') gene = gene[:dot_idx] junction = line[0] reads = int(line[desired_donor_idx]) total_reads += reads data.append((gene, junction, reads)) print(f'Selected tissue sample has {total_reads} total reads') with open(save_to, 'w') as f: print('Beginning to write junction reads') for (gene, junction, reads) in data: f.write(f'{junction},{reads},{gene}\n') print('Processing finished')
39.910256
107
0.686476
import csv import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument('--tissue', type=str, default='Brain - Cortex', metavar='tissue', help='type of tissue filtered for') parser.add_argument('--save-to', type=str, default='../../data/gtex_processed/brain_cortex_junction_reads_one_sample.csv', metavar='save_to', help='path to folder and file to save to') args = parser.parse_args() tissue = args.tissue issues = ['Brain - Cortex', 'Brain - Cerebellum', 'Heart - Left Ventricle'] assert tissue in allowed_tissues path_annotation = '../../data/gtex_origin/GTEx_Analysis_v8_Annotations_SampleAttributesDS.txt' path_junction_reads = '../../data/gtex_origin/GTEx_Analysis_2017-06-05_v8_STARv2.5.3a_junctions.gct' save_to = args.save_to def load_annotation_file(path_annotation): with open(path_annotation) as f: reader = csv.reader(f, delimiter="\t") d = list(reader) return d annotation_data = load_annotation_file(path_annotation) def find_sample_with_desired_donor_and_tissue_type(annotation_data, tissue, donor_name): for i, row in enumerate(annotation_data): curr_sample_id = row[0] if donor_name in curr_sample_id: if tissue in row: return curr_sample_id desired_donor = '1HCVE' target_sample_name = find_sample_with_desired_donor_and_tissue_type(annotation_data, tissue, desired_donor) sample_idxs = [] data = [] total_reads = 0 with open(path_junction_reads) as f: for i, line in enumerate(f): if i % 1000 == 0: print(f'Reading line {i}') line = line.split('\t') if i < 2: continue elif i == 2: desired_donor_idx = line.find(target_sample_name) elif i > 2: gene = line[1] dot_idx = gene.index('.') gene = gene[:dot_idx] junction = line[0] reads = int(line[desired_donor_idx]) total_reads += reads data.append((gene, junction, reads)) print(f'Selected tissue sample has {total_reads} total reads') with open(save_to, 'w') as f: print('Beginning to write junction reads') for (gene, junction, reads) in data: f.write(f'{junction},{reads},{gene}\n') print('Processing finished')
true
true
f72d29bb6e25f40a831066ee40a2b39e46a84b2d
14,911
py
Python
indicator_opt.py
jkterry1/parameter-sharing-paper
cb26ad195b580006f66fd8a60973408d5657b209
[ "MIT" ]
1
2022-01-28T00:01:44.000Z
2022-01-28T00:01:44.000Z
indicator_opt.py
jkterry1/parameter-sharing-paper
cb26ad195b580006f66fd8a60973408d5657b209
[ "MIT" ]
null
null
null
indicator_opt.py
jkterry1/parameter-sharing-paper
cb26ad195b580006f66fd8a60973408d5657b209
[ "MIT" ]
null
null
null
import sys import json import numpy as np import os import pickle as pkl import time from pprint import pprint from stable_baselines3 import PPO, DQN from stable_baselines3.common.utils import set_random_seed from pettingzoo.butterfly import cooperative_pong_v3, prospector_v4, knights_archers_zombies_v7 from pettingzoo.atari import entombed_cooperative_v2, pong_v2 from pettingzoo.atari.base_atari_env import BaseAtariEnv, base_env_wrapper_fn, parallel_wrapper_fn import gym import supersuit as ss from stable_baselines3.common.vec_env import VecMonitor, VecTransposeImage, VecNormalize from stable_baselines3.common.evaluation import evaluate_policy from stable_baselines3.common.callbacks import EvalCallback from stable_baselines3.common.preprocessing import is_image_space, is_image_space_channels_first import optuna from optuna.integration.skopt import SkoptSampler from optuna.pruners import BasePruner, MedianPruner, SuccessiveHalvingPruner from optuna.samplers import BaseSampler, RandomSampler, TPESampler from optuna.visualization import plot_optimization_history, plot_param_importances from utils.hyperparams_opt import sample_ppo_params, sample_dqn_params from utils.callbacks import SaveVecNormalizeCallback, TrialEvalCallback from indicator_util import AgentIndicatorWrapper, InvertColorIndicator, BinaryIndicator, GeometricPatternIndicator import argparse from stable_baselines3.common.utils import set_random_seed if __name__ == "__main__": # noqa: C901 parser = argparse.ArgumentParser() ''' Env List - Entombed Cooperative (Atari): DQN, PPO - Cooperative Pong (Butterfly): DQN, PPO - Prospector (Butterfly): PPO - KAZ (Butterfly): DQN, PPO - Pong (Atari): DQN, PPO ''' butterfly_envs = ["prospector-v4", "knights-archers-zombies-v7", "cooperative-pong-v3"] atari_envs = ["entombed-cooperative-v2", "pong-v2"] parser.add_argument("--algo", help="RL Algorithm", default="ppo", type=str, required=False, choices=["ppo", "dqn"]) parser.add_argument("--env", type=str, default="pong-v2", help="environment ID", choices=[ "prospector-v4", "knights-archers-zombies-v7", "cooperative-pong-v3", "entombed-cooperative-v2", "pong-v2" ]) parser.add_argument("-n", "--n-timesteps", help="Overwrite the number of timesteps", default=1e6, type=int) parser.add_argument("--n-trials", help="Number of trials for optimizing hyperparameters", type=int, default=10) parser.add_argument( "--optimization-log-path", help="Path to save the evaluation log and optimal policy for each hyperparameter tried during optimization. " "Disabled if no argument is passed.", type=str, ) parser.add_argument("--eval-episodes", help="Number of episodes to use for evaluation", default=5, type=int) parser.add_argument( "--sampler", help="Sampler to use when optimizing hyperparameters", type=str, default="tpe", choices=["random", "tpe", "skopt"], ) parser.add_argument( "--pruner", help="Pruner to use when optimizing hyperparameters", type=str, default="median", choices=["halving", "median", "none"], ) parser.add_argument("--n-startup-trials", help="Number of trials before using optuna sampler", type=int, default=10) parser.add_argument( "--n-evaluations", help="Training policies are evaluated every n-timesteps // n-evaluations steps when doing hyperparameter optimization", type=int, default=100, ) parser.add_argument("-f", "--log-folder", help="Log folder", type=str, default="logs") parser.add_argument( "--storage", help="Database storage path if distributed optimization should be used", type=str, default=None ) parser.add_argument("--study-name", help="Study name for distributed optimization", type=str, default=None) parser.add_argument("--verbose", help="Verbose mode (0: no output, 1: INFO)", default=1, type=int) args = parser.parse_args() seed = np.random.randint(2 ** 32 - 1, dtype="int64").item() set_random_seed(seed) print("=" * 10, args.env, "=" * 10) print(f"Seed: {seed}") # Hyperparameter optimization # Determine sampler and pruner if args.sampler == "random": sampler = RandomSampler(seed=seed) elif args.sampler == "tpe": sampler = TPESampler(n_startup_trials=args.n_startup_trials, seed=seed) elif args.sampler == "skopt": sampler = SkoptSampler(skopt_kwargs={"base_estimator": "GP", "acq_func": "gp_hedge"}) else: raise ValueError(f"Unknown sampler: {args.sampler}") if args.pruner == "halving": pruner = SuccessiveHalvingPruner(min_resource=1, reduction_factor=4, min_early_stopping_rate=0) elif args.pruner == "median": pruner = MedianPruner(n_startup_trials=args.n_startup_trials, n_warmup_steps=args.n_evaluations // 3) elif args.pruner == "none": # Do not prune pruner = MedianPruner(n_startup_trials=args.n_trials, n_warmup_steps=args.n_evaluations) else: raise ValueError(f"Unknown pruner: {args.pruner}") print(f"Sampler: {args.sampler} - Pruner: {args.pruner}") # Create study study = optuna.create_study( sampler=sampler, pruner=pruner, storage=args.storage, study_name=args.study_name, load_if_exists=True, direction="maximize", ) hyperparams_sampler = {'ppo': sample_ppo_params, 'dqn': sample_dqn_params} hyperparams_algo = {'ppo': PPO, 'dqn': DQN} muesli_obs_size = 96 muesli_frame_size = 4 # Objective function for hyperparameter search def objective(trial: optuna.Trial) -> float: #kwargs = self._hyperparams.copy() kwargs = { #'n_envs': 1, 'policy': 'CnnPolicy', #'n_timesteps': 1e6, } # Sample candidate hyperparameters sampled_hyperparams = hyperparams_sampler[args.algo](trial) kwargs.update(sampled_hyperparams) # Create training env if args.env == "prospector-v4": env = prospector_v4.parallel_env() agent_type = "prospector" elif args.env == "knights-archers-zombies-v7": env = knights_archers_zombies_v7.parallel_env() agent_type = "archer" elif args.env == "cooperative-pong-v3": env = cooperative_pong_v3.parallel_env() agent_type = "paddle_0" elif args.env == "entombed-cooperative-v2": env = entombed_cooperative_v2.parallel_env() agent_type = "first" elif args.env == "pong-v2": env = pong_v2.parallel_env() agent_type = "first" env = ss.color_reduction_v0(env) env = ss.pad_action_space_v0(env) env = ss.pad_observations_v0(env) env = ss.resize_v0(env, x_size=muesli_obs_size, y_size=muesli_obs_size, linear_interp=True) env = ss.frame_stack_v1(env, stack_size=muesli_frame_size) # Enable black death if args.env == 'knights-archers-zombies-v7': env = ss.black_death_v2(env) # Agent indicator wrapper agent_indicator_name = trial.suggest_categorical("agent_indicator", choices=["identity", "invert", "invert-replace", "binary", "geometric"]) if agent_indicator_name == "invert": agent_indicator = InvertColorIndicator(env, agent_type) agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator) elif agent_indicator_name == "invert-replace": agent_indicator = InvertColorIndicator(env, agent_type) agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator, False) elif agent_indicator_name == "binary": agent_indicator = BinaryIndicator(env, agent_type) agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator) elif agent_indicator_name == "geometric": agent_indicator = GeometricPatternIndicator(env, agent_type) agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator) if agent_indicator_name != "identity": env = ss.observation_lambda_v0(env, agent_indicator_wrapper.apply, agent_indicator_wrapper.apply_space) env = ss.pettingzoo_env_to_vec_env_v0(env) #env = ss.concat_vec_envs_v0(env, num_vec_envs=1, num_cpus=1, base_class='stable_baselines3') env = VecMonitor(env) def image_transpose(env): if is_image_space(env.observation_space) and not is_image_space_channels_first(env.observation_space): env = VecTransposeImage(env) return env env = image_transpose(env) model = hyperparams_algo[args.algo]( env=env, tensorboard_log=None, # We do not seed the trial seed=None, verbose=0, **kwargs, ) model.trial = trial # Create eval env if args.env == "prospector-v4": eval_env = prospector_v4.parallel_env() agent_type = "prospector" elif args.env == "knights-archers-zombies-v7": eval_env = knights_archers_zombies_v7.parallel_env() agent_type = "archer" elif args.env == "cooperative-pong-v3": eval_env = cooperative_pong_v3.parallel_env() agent_type = "paddle_0" elif args.env == "entombed-cooperative-v2": eval_env = entombed_cooperative_v2.parallel_env() agent_type = "first" elif args.env == "pong-v2": def pong_single_raw_env(**kwargs): return BaseAtariEnv(game="pong", num_players=1, env_name=os.path.basename(__file__)[:-3], **kwargs) pong_single_env = base_env_wrapper_fn(pong_single_raw_env) pong_parallel_env = parallel_wrapper_fn(pong_single_env) eval_env = pong_parallel_env() #eval_env = pong_v2.parallel_env() #eval_env = gym.make("Pong-v0", obs_type='image') agent_type = "first" eval_env = ss.color_reduction_v0(eval_env) eval_env = ss.pad_action_space_v0(eval_env) eval_env = ss.pad_observations_v0(eval_env) eval_env = ss.resize_v0(eval_env, x_size=muesli_obs_size, y_size=muesli_obs_size, linear_interp=True) eval_env = ss.frame_stack_v1(eval_env, stack_size=muesli_frame_size) # Enable black death if args.env == 'knights-archers-zombies-v7': eval_env = ss.black_death_v2(eval_env) # Agent indicator wrapper if agent_indicator_name == "invert": eval_agent_indicator = InvertColorIndicator(eval_env, agent_type) eval_agent_indicator_wrapper = AgentIndicatorWrapper(eval_agent_indicator) elif agent_indicator_name == "invert-replace": eval_agent_indicator = InvertColorIndicator(eval_env, agent_type) eval_agent_indicator_wrapper = AgentIndicatorWrapper(eval_agent_indicator, False) elif agent_indicator_name == "binary": eval_agent_indicator = BinaryIndicator(eval_env, agent_type) eval_agent_indicator_wrapper = AgentIndicatorWrapper(eval_agent_indicator) elif agent_indicator_name == "geometric": eval_agent_indicator = GeometricPatternIndicator(eval_env, agent_type) eval_agent_indicator_wrapper = AgentIndicatorWrapper(eval_agent_indicator) if agent_indicator_name != "identity": eval_env = ss.observation_lambda_v0(eval_env, eval_agent_indicator_wrapper.apply, eval_agent_indicator_wrapper.apply_space) eval_env = ss.pettingzoo_env_to_vec_env_v0(eval_env) #eval_env = ss.concat_vec_envs_v0(eval_env, num_vec_envs=1, num_cpus=1, base_class='stable_baselines3') eval_env = VecMonitor(eval_env) eval_env = image_transpose(eval_env) optuna_eval_freq = int(args.n_timesteps / args.n_evaluations) # Account for parallel envs optuna_eval_freq = max(optuna_eval_freq // model.get_env().num_envs, 1) # Use non-deterministic eval for Atari path = None if args.optimization_log_path is not None: path = os.path.join(args.optimization_log_path, f"trial_{str(trial.number)}") #callbacks = get_callback_list({"callback": self.specified_callbacks}) callbacks = [] deterministic_eval = args.env not in atari_envs eval_callback = TrialEvalCallback( eval_env, trial, best_model_save_path=path, log_path=path, n_eval_episodes=args.eval_episodes, eval_freq=optuna_eval_freq, deterministic=deterministic_eval, ) callbacks.append(eval_callback) try: model.learn(args.n_timesteps, callback=callbacks) # Free memory model.env.close() eval_env.close() except (AssertionError, ValueError) as e: # Sometimes, random hyperparams can generate NaN # Free memory model.env.close() eval_env.close() # Prune hyperparams that generate NaNs print(e) print("============") print("Sampled hyperparams:") pprint(sampled_hyperparams) raise optuna.exceptions.TrialPruned() is_pruned = eval_callback.is_pruned reward = eval_callback.last_mean_reward del model.env, eval_env del model if is_pruned: raise optuna.exceptions.TrialPruned() return reward pass try: study.optimize(objective, n_trials=args.n_trials, n_jobs=1) except KeyboardInterrupt: pass print("Number of finished trials: ", len(study.trials)) print("Best trial:") trial = study.best_trial print("Value: ", trial.value) print("Params: ") for key, value in trial.params.items(): print(f" {key}: {value}") report_name = ( f"report_{args.env}_{args.n_trials}-trials-{args.n_timesteps}" f"-{args.sampler}-{args.pruner}_{int(time.time())}" ) log_path = os.path.join(args.log_folder, args.algo, report_name) if args.verbose: print(f"Writing report to {log_path}") # Write report os.makedirs(os.path.dirname(log_path), exist_ok=True) study.trials_dataframe().to_csv(f"{log_path}.csv") # Save python object to inspect/re-use it later with open(f"{log_path}.pkl", "wb+") as f: pkl.dump(study, f) # Plot optimization result try: fig1 = plot_optimization_history(study) fig2 = plot_param_importances(study) fig1.show() fig2.show() except (ValueError, ImportError, RuntimeError): pass
40.852055
148
0.66622
import sys import json import numpy as np import os import pickle as pkl import time from pprint import pprint from stable_baselines3 import PPO, DQN from stable_baselines3.common.utils import set_random_seed from pettingzoo.butterfly import cooperative_pong_v3, prospector_v4, knights_archers_zombies_v7 from pettingzoo.atari import entombed_cooperative_v2, pong_v2 from pettingzoo.atari.base_atari_env import BaseAtariEnv, base_env_wrapper_fn, parallel_wrapper_fn import gym import supersuit as ss from stable_baselines3.common.vec_env import VecMonitor, VecTransposeImage, VecNormalize from stable_baselines3.common.evaluation import evaluate_policy from stable_baselines3.common.callbacks import EvalCallback from stable_baselines3.common.preprocessing import is_image_space, is_image_space_channels_first import optuna from optuna.integration.skopt import SkoptSampler from optuna.pruners import BasePruner, MedianPruner, SuccessiveHalvingPruner from optuna.samplers import BaseSampler, RandomSampler, TPESampler from optuna.visualization import plot_optimization_history, plot_param_importances from utils.hyperparams_opt import sample_ppo_params, sample_dqn_params from utils.callbacks import SaveVecNormalizeCallback, TrialEvalCallback from indicator_util import AgentIndicatorWrapper, InvertColorIndicator, BinaryIndicator, GeometricPatternIndicator import argparse from stable_baselines3.common.utils import set_random_seed if __name__ == "__main__": parser = argparse.ArgumentParser() butterfly_envs = ["prospector-v4", "knights-archers-zombies-v7", "cooperative-pong-v3"] atari_envs = ["entombed-cooperative-v2", "pong-v2"] parser.add_argument("--algo", help="RL Algorithm", default="ppo", type=str, required=False, choices=["ppo", "dqn"]) parser.add_argument("--env", type=str, default="pong-v2", help="environment ID", choices=[ "prospector-v4", "knights-archers-zombies-v7", "cooperative-pong-v3", "entombed-cooperative-v2", "pong-v2" ]) parser.add_argument("-n", "--n-timesteps", help="Overwrite the number of timesteps", default=1e6, type=int) parser.add_argument("--n-trials", help="Number of trials for optimizing hyperparameters", type=int, default=10) parser.add_argument( "--optimization-log-path", help="Path to save the evaluation log and optimal policy for each hyperparameter tried during optimization. " "Disabled if no argument is passed.", type=str, ) parser.add_argument("--eval-episodes", help="Number of episodes to use for evaluation", default=5, type=int) parser.add_argument( "--sampler", help="Sampler to use when optimizing hyperparameters", type=str, default="tpe", choices=["random", "tpe", "skopt"], ) parser.add_argument( "--pruner", help="Pruner to use when optimizing hyperparameters", type=str, default="median", choices=["halving", "median", "none"], ) parser.add_argument("--n-startup-trials", help="Number of trials before using optuna sampler", type=int, default=10) parser.add_argument( "--n-evaluations", help="Training policies are evaluated every n-timesteps // n-evaluations steps when doing hyperparameter optimization", type=int, default=100, ) parser.add_argument("-f", "--log-folder", help="Log folder", type=str, default="logs") parser.add_argument( "--storage", help="Database storage path if distributed optimization should be used", type=str, default=None ) parser.add_argument("--study-name", help="Study name for distributed optimization", type=str, default=None) parser.add_argument("--verbose", help="Verbose mode (0: no output, 1: INFO)", default=1, type=int) args = parser.parse_args() seed = np.random.randint(2 ** 32 - 1, dtype="int64").item() set_random_seed(seed) print("=" * 10, args.env, "=" * 10) print(f"Seed: {seed}") if args.sampler == "random": sampler = RandomSampler(seed=seed) elif args.sampler == "tpe": sampler = TPESampler(n_startup_trials=args.n_startup_trials, seed=seed) elif args.sampler == "skopt": sampler = SkoptSampler(skopt_kwargs={"base_estimator": "GP", "acq_func": "gp_hedge"}) else: raise ValueError(f"Unknown sampler: {args.sampler}") if args.pruner == "halving": pruner = SuccessiveHalvingPruner(min_resource=1, reduction_factor=4, min_early_stopping_rate=0) elif args.pruner == "median": pruner = MedianPruner(n_startup_trials=args.n_startup_trials, n_warmup_steps=args.n_evaluations // 3) elif args.pruner == "none": pruner = MedianPruner(n_startup_trials=args.n_trials, n_warmup_steps=args.n_evaluations) else: raise ValueError(f"Unknown pruner: {args.pruner}") print(f"Sampler: {args.sampler} - Pruner: {args.pruner}") study = optuna.create_study( sampler=sampler, pruner=pruner, storage=args.storage, study_name=args.study_name, load_if_exists=True, direction="maximize", ) hyperparams_sampler = {'ppo': sample_ppo_params, 'dqn': sample_dqn_params} hyperparams_algo = {'ppo': PPO, 'dqn': DQN} muesli_obs_size = 96 muesli_frame_size = 4 def objective(trial: optuna.Trial) -> float: kwargs = { 'policy': 'CnnPolicy', } sampled_hyperparams = hyperparams_sampler[args.algo](trial) kwargs.update(sampled_hyperparams) if args.env == "prospector-v4": env = prospector_v4.parallel_env() agent_type = "prospector" elif args.env == "knights-archers-zombies-v7": env = knights_archers_zombies_v7.parallel_env() agent_type = "archer" elif args.env == "cooperative-pong-v3": env = cooperative_pong_v3.parallel_env() agent_type = "paddle_0" elif args.env == "entombed-cooperative-v2": env = entombed_cooperative_v2.parallel_env() agent_type = "first" elif args.env == "pong-v2": env = pong_v2.parallel_env() agent_type = "first" env = ss.color_reduction_v0(env) env = ss.pad_action_space_v0(env) env = ss.pad_observations_v0(env) env = ss.resize_v0(env, x_size=muesli_obs_size, y_size=muesli_obs_size, linear_interp=True) env = ss.frame_stack_v1(env, stack_size=muesli_frame_size) if args.env == 'knights-archers-zombies-v7': env = ss.black_death_v2(env) agent_indicator_name = trial.suggest_categorical("agent_indicator", choices=["identity", "invert", "invert-replace", "binary", "geometric"]) if agent_indicator_name == "invert": agent_indicator = InvertColorIndicator(env, agent_type) agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator) elif agent_indicator_name == "invert-replace": agent_indicator = InvertColorIndicator(env, agent_type) agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator, False) elif agent_indicator_name == "binary": agent_indicator = BinaryIndicator(env, agent_type) agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator) elif agent_indicator_name == "geometric": agent_indicator = GeometricPatternIndicator(env, agent_type) agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator) if agent_indicator_name != "identity": env = ss.observation_lambda_v0(env, agent_indicator_wrapper.apply, agent_indicator_wrapper.apply_space) env = ss.pettingzoo_env_to_vec_env_v0(env) env = VecMonitor(env) def image_transpose(env): if is_image_space(env.observation_space) and not is_image_space_channels_first(env.observation_space): env = VecTransposeImage(env) return env env = image_transpose(env) model = hyperparams_algo[args.algo]( env=env, tensorboard_log=None, seed=None, verbose=0, **kwargs, ) model.trial = trial if args.env == "prospector-v4": eval_env = prospector_v4.parallel_env() agent_type = "prospector" elif args.env == "knights-archers-zombies-v7": eval_env = knights_archers_zombies_v7.parallel_env() agent_type = "archer" elif args.env == "cooperative-pong-v3": eval_env = cooperative_pong_v3.parallel_env() agent_type = "paddle_0" elif args.env == "entombed-cooperative-v2": eval_env = entombed_cooperative_v2.parallel_env() agent_type = "first" elif args.env == "pong-v2": def pong_single_raw_env(**kwargs): return BaseAtariEnv(game="pong", num_players=1, env_name=os.path.basename(__file__)[:-3], **kwargs) pong_single_env = base_env_wrapper_fn(pong_single_raw_env) pong_parallel_env = parallel_wrapper_fn(pong_single_env) eval_env = pong_parallel_env() agent_type = "first" eval_env = ss.color_reduction_v0(eval_env) eval_env = ss.pad_action_space_v0(eval_env) eval_env = ss.pad_observations_v0(eval_env) eval_env = ss.resize_v0(eval_env, x_size=muesli_obs_size, y_size=muesli_obs_size, linear_interp=True) eval_env = ss.frame_stack_v1(eval_env, stack_size=muesli_frame_size) if args.env == 'knights-archers-zombies-v7': eval_env = ss.black_death_v2(eval_env) if agent_indicator_name == "invert": eval_agent_indicator = InvertColorIndicator(eval_env, agent_type) eval_agent_indicator_wrapper = AgentIndicatorWrapper(eval_agent_indicator) elif agent_indicator_name == "invert-replace": eval_agent_indicator = InvertColorIndicator(eval_env, agent_type) eval_agent_indicator_wrapper = AgentIndicatorWrapper(eval_agent_indicator, False) elif agent_indicator_name == "binary": eval_agent_indicator = BinaryIndicator(eval_env, agent_type) eval_agent_indicator_wrapper = AgentIndicatorWrapper(eval_agent_indicator) elif agent_indicator_name == "geometric": eval_agent_indicator = GeometricPatternIndicator(eval_env, agent_type) eval_agent_indicator_wrapper = AgentIndicatorWrapper(eval_agent_indicator) if agent_indicator_name != "identity": eval_env = ss.observation_lambda_v0(eval_env, eval_agent_indicator_wrapper.apply, eval_agent_indicator_wrapper.apply_space) eval_env = ss.pettingzoo_env_to_vec_env_v0(eval_env) eval_env = VecMonitor(eval_env) eval_env = image_transpose(eval_env) optuna_eval_freq = int(args.n_timesteps / args.n_evaluations) optuna_eval_freq = max(optuna_eval_freq // model.get_env().num_envs, 1) path = None if args.optimization_log_path is not None: path = os.path.join(args.optimization_log_path, f"trial_{str(trial.number)}") callbacks = [] deterministic_eval = args.env not in atari_envs eval_callback = TrialEvalCallback( eval_env, trial, best_model_save_path=path, log_path=path, n_eval_episodes=args.eval_episodes, eval_freq=optuna_eval_freq, deterministic=deterministic_eval, ) callbacks.append(eval_callback) try: model.learn(args.n_timesteps, callback=callbacks) model.env.close() eval_env.close() except (AssertionError, ValueError) as e: model.env.close() eval_env.close() print(e) print("============") print("Sampled hyperparams:") pprint(sampled_hyperparams) raise optuna.exceptions.TrialPruned() is_pruned = eval_callback.is_pruned reward = eval_callback.last_mean_reward del model.env, eval_env del model if is_pruned: raise optuna.exceptions.TrialPruned() return reward pass try: study.optimize(objective, n_trials=args.n_trials, n_jobs=1) except KeyboardInterrupt: pass print("Number of finished trials: ", len(study.trials)) print("Best trial:") trial = study.best_trial print("Value: ", trial.value) print("Params: ") for key, value in trial.params.items(): print(f" {key}: {value}") report_name = ( f"report_{args.env}_{args.n_trials}-trials-{args.n_timesteps}" f"-{args.sampler}-{args.pruner}_{int(time.time())}" ) log_path = os.path.join(args.log_folder, args.algo, report_name) if args.verbose: print(f"Writing report to {log_path}") os.makedirs(os.path.dirname(log_path), exist_ok=True) study.trials_dataframe().to_csv(f"{log_path}.csv") with open(f"{log_path}.pkl", "wb+") as f: pkl.dump(study, f) try: fig1 = plot_optimization_history(study) fig2 = plot_param_importances(study) fig1.show() fig2.show() except (ValueError, ImportError, RuntimeError): pass
true
true
f72d29c30cce97f016e99c825381c00e3af87148
3,105
py
Python
enhancitizer/tasks/duplication.py
cherusker/enhancitizer
1f1516f0aeb61262f2de9767a5f4f17cb62bcb26
[ "MIT" ]
null
null
null
enhancitizer/tasks/duplication.py
cherusker/enhancitizer
1f1516f0aeb61262f2de9767a5f4f17cb62bcb26
[ "MIT" ]
null
null
null
enhancitizer/tasks/duplication.py
cherusker/enhancitizer
1f1516f0aeb61262f2de9767a5f4f17cb62bcb26
[ "MIT" ]
null
null
null
# ------------------------------------------------------------------------------ # # Author: # Armin Hasitzka (enhancitizer@hasitzka.com) # # Licensed under the MIT license. # See LICENSE in the project root for license information. # # ------------------------------------------------------------------------------ from utils.printer import Printer class TaskEliminateDuplicateReports(object): description = 'Eliminating duplicate reports ...' __tsan_data_race_max_stack_frames = 3 def __init__(self, bank): self.__bank = bank def setup(self, options): self.__printer = Printer(options) self.__duplicate_reports = [] self.__identifiers_funcs = { 'tsan': { 'data race': self.__tsan_data_race_identifiers, 'thread leak': self.__tsan_thread_leak_identifiers } } # TODO: split into separate lists for sanitizers and categories for better performance self.__known_identifiers = [] def process(self, report): if not self.__identifiers_funcs.get(report.sanitizer.name_short, {}).get(report.category_name): self.__printer.bailout('unable to analyse ' + str(report)) identifiers = self.__identifiers_funcs[report.sanitizer.name_short][report.category_name](report) if not identifiers: self.__printer.bailout('unable to extract identifiers from ' + str(report)) for identifier in identifiers: if identifier in self.__known_identifiers: self.__printer.task_info('removing ' + str(report)) self.__duplicate_reports.append(report) return self.__known_identifiers.extend(identifiers) def teardown(self): for report in self.__duplicate_reports: self.__bank.remove_report(report) def __tsan_data_race_identifiers(self, report): fragments = [] for stack in report.call_stacks: if 'tsan_data_race_type' in stack.special: fragment = [ stack.special.get('tsan_data_race_type'), stack.special.get('tsan_data_race_bytes') ] for i in range(min(len(stack.frames), self.__tsan_data_race_max_stack_frames)): fragment.extend([ stack.frames[i].src_file_rel_path, stack.frames[i].func_name, stack.frames[i].line_num, stack.frames[i].char_pos ]) fragments.append(':'.join(['?' if not f else str(f) for f in fragment])) if len(fragments) == 1: return fragments if len(fragments) == 2: # either way is fine! return [fragments[0] + ':' + fragments[1], fragments[1] + ':' + fragments[0]] def __tsan_thread_leak_identifiers(self, report): for stack in report.call_stacks: if stack.special.get('tsan_thread_leak_thread_name'): return [stack.special['tsan_thread_leak_thread_name']]
40.324675
105
0.579066
from utils.printer import Printer class TaskEliminateDuplicateReports(object): description = 'Eliminating duplicate reports ...' __tsan_data_race_max_stack_frames = 3 def __init__(self, bank): self.__bank = bank def setup(self, options): self.__printer = Printer(options) self.__duplicate_reports = [] self.__identifiers_funcs = { 'tsan': { 'data race': self.__tsan_data_race_identifiers, 'thread leak': self.__tsan_thread_leak_identifiers } } self.__known_identifiers = [] def process(self, report): if not self.__identifiers_funcs.get(report.sanitizer.name_short, {}).get(report.category_name): self.__printer.bailout('unable to analyse ' + str(report)) identifiers = self.__identifiers_funcs[report.sanitizer.name_short][report.category_name](report) if not identifiers: self.__printer.bailout('unable to extract identifiers from ' + str(report)) for identifier in identifiers: if identifier in self.__known_identifiers: self.__printer.task_info('removing ' + str(report)) self.__duplicate_reports.append(report) return self.__known_identifiers.extend(identifiers) def teardown(self): for report in self.__duplicate_reports: self.__bank.remove_report(report) def __tsan_data_race_identifiers(self, report): fragments = [] for stack in report.call_stacks: if 'tsan_data_race_type' in stack.special: fragment = [ stack.special.get('tsan_data_race_type'), stack.special.get('tsan_data_race_bytes') ] for i in range(min(len(stack.frames), self.__tsan_data_race_max_stack_frames)): fragment.extend([ stack.frames[i].src_file_rel_path, stack.frames[i].func_name, stack.frames[i].line_num, stack.frames[i].char_pos ]) fragments.append(':'.join(['?' if not f else str(f) for f in fragment])) if len(fragments) == 1: return fragments if len(fragments) == 2: return [fragments[0] + ':' + fragments[1], fragments[1] + ':' + fragments[0]] def __tsan_thread_leak_identifiers(self, report): for stack in report.call_stacks: if stack.special.get('tsan_thread_leak_thread_name'): return [stack.special['tsan_thread_leak_thread_name']]
true
true
f72d2a82d4064325d5026f24287d9cbfc1f2c3ae
15,055
py
Python
tensorflow_probability/python/distributions/beta.py
sanket-kamthe/probability
c22b6201155c2e58d08a4ad30641d1aff59fbe7c
[ "Apache-2.0" ]
null
null
null
tensorflow_probability/python/distributions/beta.py
sanket-kamthe/probability
c22b6201155c2e58d08a4ad30641d1aff59fbe7c
[ "Apache-2.0" ]
null
null
null
tensorflow_probability/python/distributions/beta.py
sanket-kamthe/probability
c22b6201155c2e58d08a4ad30641d1aff59fbe7c
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """The Beta distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports import numpy as np import tensorflow.compat.v2 as tf from tensorflow_probability.python.distributions import distribution from tensorflow_probability.python.distributions import kullback_leibler from tensorflow_probability.python.internal import assert_util from tensorflow_probability.python.internal import distribution_util from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import prefer_static from tensorflow_probability.python.internal import reparameterization from tensorflow_probability.python.internal import tensor_util from tensorflow_probability.python.util.seed_stream import SeedStream from tensorflow.python.util import deprecation # pylint: disable=g-direct-tensorflow-import __all__ = [ "Beta", ] _beta_sample_note = """Note: `x` must have dtype `self.dtype` and be in `[0, 1].` It must have a shape compatible with `self.batch_shape()`.""" class Beta(distribution.Distribution): """Beta distribution. The Beta distribution is defined over the `(0, 1)` interval using parameters `concentration1` (aka "alpha") and `concentration0` (aka "beta"). #### Mathematical Details The probability density function (pdf) is, ```none pdf(x; alpha, beta) = x**(alpha - 1) (1 - x)**(beta - 1) / Z Z = Gamma(alpha) Gamma(beta) / Gamma(alpha + beta) ``` where: * `concentration1 = alpha`, * `concentration0 = beta`, * `Z` is the normalization constant, and, * `Gamma` is the [gamma function]( https://en.wikipedia.org/wiki/Gamma_function). The concentration parameters represent mean total counts of a `1` or a `0`, i.e., ```none concentration1 = alpha = mean * total_concentration concentration0 = beta = (1. - mean) * total_concentration ``` where `mean` in `(0, 1)` and `total_concentration` is a positive real number representing a mean `total_count = concentration1 + concentration0`. Distribution parameters are automatically broadcast in all functions; see examples for details. Warning: The samples can be zero due to finite precision. This happens more often when some of the concentrations are very small. Make sure to round the samples to `np.finfo(dtype).tiny` before computing the density. Samples of this distribution are reparameterized (pathwise differentiable). The derivatives are computed using the approach described in the paper [Michael Figurnov, Shakir Mohamed, Andriy Mnih. Implicit Reparameterization Gradients, 2018](https://arxiv.org/abs/1805.08498) #### Examples ```python import tensorflow_probability as tfp tfd = tfp.distributions # Create a batch of three Beta distributions. alpha = [1, 2, 3] beta = [1, 2, 3] dist = tfd.Beta(alpha, beta) dist.sample([4, 5]) # Shape [4, 5, 3] # `x` has three batch entries, each with two samples. x = [[.1, .4, .5], [.2, .3, .5]] # Calculate the probability of each pair of samples under the corresponding # distribution in `dist`. dist.prob(x) # Shape [2, 3] ``` ```python # Create batch_shape=[2, 3] via parameter broadcast: alpha = [[1.], [2]] # Shape [2, 1] beta = [3., 4, 5] # Shape [3] dist = tfd.Beta(alpha, beta) # alpha broadcast as: [[1., 1, 1,], # [2, 2, 2]] # beta broadcast as: [[3., 4, 5], # [3, 4, 5]] # batch_Shape [2, 3] dist.sample([4, 5]) # Shape [4, 5, 2, 3] x = [.2, .3, .5] # x will be broadcast as [[.2, .3, .5], # [.2, .3, .5]], # thus matching batch_shape [2, 3]. dist.prob(x) # Shape [2, 3] ``` Compute the gradients of samples w.r.t. the parameters: ```python alpha = tf.constant(1.0) beta = tf.constant(2.0) dist = tfd.Beta(alpha, beta) samples = dist.sample(5) # Shape [5] loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function # Unbiased stochastic gradients of the loss function grads = tf.gradients(loss, [alpha, beta]) ``` """ def __init__(self, concentration1, concentration0, validate_args=False, allow_nan_stats=True, name="Beta"): """Initialize a batch of Beta distributions. Args: concentration1: Positive floating-point `Tensor` indicating mean number of successes; aka "alpha". Implies `self.dtype` and `self.batch_shape`, i.e., `concentration1.shape = [N1, N2, ..., Nm] = self.batch_shape`. concentration0: Positive floating-point `Tensor` indicating mean number of failures; aka "beta". Otherwise has same semantics as `concentration1`. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. """ parameters = dict(locals()) with tf.name_scope(name) as name: dtype = dtype_util.common_dtype([concentration1, concentration0], dtype_hint=tf.float32) self._concentration1 = tensor_util.convert_nonref_to_tensor( concentration1, dtype=dtype, name="concentration1") self._concentration0 = tensor_util.convert_nonref_to_tensor( concentration0, dtype=dtype, name="concentration0") super(Beta, self).__init__( dtype=dtype, validate_args=validate_args, allow_nan_stats=allow_nan_stats, reparameterization_type=reparameterization.FULLY_REPARAMETERIZED, parameters=parameters, name=name) @staticmethod def _param_shapes(sample_shape): s = tf.convert_to_tensor(sample_shape, dtype=tf.int32) return dict(concentration1=s, concentration0=s) @classmethod def _params_event_ndims(cls): return dict(concentration1=0, concentration0=0) @property def concentration1(self): """Concentration parameter associated with a `1` outcome.""" return self._concentration1 @property def concentration0(self): """Concentration parameter associated with a `0` outcome.""" return self._concentration0 @property @deprecation.deprecated( "2019-10-01", ("The `total_concentration` property is deprecated; instead use " "`dist.concentration1 + dist.concentration0`."), warn_once=True) def total_concentration(self): """Sum of concentration parameters.""" with self._name_and_control_scope("total_concentration"): return self.concentration1 + self.concentration0 def _batch_shape_tensor(self, concentration1=None, concentration0=None): return prefer_static.broadcast_shape( prefer_static.shape( self.concentration1 if concentration1 is None else concentration1), prefer_static.shape( self.concentration0 if concentration0 is None else concentration0)) def _batch_shape(self): return tf.broadcast_static_shape( self.concentration1.shape, self.concentration0.shape) def _event_shape_tensor(self): return tf.constant([], dtype=tf.int32) def _event_shape(self): return tf.TensorShape([]) def _sample_n(self, n, seed=None): seed = SeedStream(seed, "beta") concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) shape = self._batch_shape_tensor(concentration1, concentration0) expanded_concentration1 = tf.broadcast_to(concentration1, shape) expanded_concentration0 = tf.broadcast_to(concentration0, shape) gamma1_sample = tf.random.gamma( shape=[n], alpha=expanded_concentration1, dtype=self.dtype, seed=seed()) gamma2_sample = tf.random.gamma( shape=[n], alpha=expanded_concentration0, dtype=self.dtype, seed=seed()) beta_sample = gamma1_sample / (gamma1_sample + gamma2_sample) return beta_sample @distribution_util.AppendDocstring(_beta_sample_note) def _log_prob(self, x): concentration0 = tf.convert_to_tensor(self.concentration0) concentration1 = tf.convert_to_tensor(self.concentration1) return (self._log_unnormalized_prob(x, concentration1, concentration0) - self._log_normalization(concentration1, concentration0)) @distribution_util.AppendDocstring(_beta_sample_note) def _prob(self, x): return tf.exp(self._log_prob(x)) @distribution_util.AppendDocstring(_beta_sample_note) def _log_cdf(self, x): return tf.math.log(self._cdf(x)) @distribution_util.AppendDocstring(_beta_sample_note) def _cdf(self, x): with tf.control_dependencies(self._maybe_assert_valid_sample(x)): concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) shape = self._batch_shape_tensor(concentration1, concentration0) concentration1 = tf.broadcast_to(concentration1, shape) concentration0 = tf.broadcast_to(concentration0, shape) return tf.math.betainc(concentration1, concentration0, x) def _log_unnormalized_prob(self, x, concentration1, concentration0): with tf.control_dependencies(self._maybe_assert_valid_sample(x)): return (tf.math.xlogy(concentration1 - 1., x) + (concentration0 - 1.) * tf.math.log1p(-x)) def _log_normalization(self, concentration1, concentration0): return (tf.math.lgamma(concentration1) + tf.math.lgamma(concentration0) - tf.math.lgamma(concentration1 + concentration0)) def _entropy(self): concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) total_concentration = concentration1 + concentration0 return (self._log_normalization(concentration1, concentration0) - (concentration1 - 1.) * tf.math.digamma(concentration1) - (concentration0 - 1.) * tf.math.digamma(concentration0) + (total_concentration - 2.) * tf.math.digamma(total_concentration)) def _mean(self): concentration1 = tf.convert_to_tensor(self.concentration1) return concentration1 / (concentration1 + self.concentration0) def _variance(self): concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) total_concentration = concentration1 + concentration0 return (concentration1 * concentration0 / ((total_concentration)**2 * (total_concentration + 1.))) @distribution_util.AppendDocstring( """Note: The mode is undefined when `concentration1 <= 1` or `concentration0 <= 1`. If `self.allow_nan_stats` is `True`, `NaN` is used for undefined modes. If `self.allow_nan_stats` is `False` an exception is raised when one or more modes are undefined.""") def _mode(self): concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) mode = (concentration1 - 1.) / (concentration1 + concentration0 - 2.) with tf.control_dependencies([] if self.allow_nan_stats else [ # pylint: disable=g-long-ternary assert_util.assert_less( tf.ones([], dtype=self.dtype), concentration1, message="Mode undefined for concentration1 <= 1."), assert_util.assert_less( tf.ones([], dtype=self.dtype), concentration0, message="Mode undefined for concentration0 <= 1.") ]): return tf.where( (concentration1 > 1.) & (concentration0 > 1.), mode, dtype_util.as_numpy_dtype(self.dtype)(np.nan)) def _maybe_assert_valid_sample(self, x): """Checks the validity of a sample.""" if not self.validate_args: return [] return [ assert_util.assert_positive(x, message="Sample must be positive."), assert_util.assert_less( x, tf.ones([], x.dtype), message="Sample must be less than `1`.") ] def _parameter_control_dependencies(self, is_init): if not self.validate_args: return [] assertions = [] for concentration in [self.concentration0, self.concentration1]: if is_init != tensor_util.is_ref(concentration): assertions.append(assert_util.assert_positive( concentration, message="Concentration parameter must be positive.")) return assertions @kullback_leibler.RegisterKL(Beta, Beta) def _kl_beta_beta(d1, d2, name=None): """Calculate the batchwise KL divergence KL(d1 || d2) with d1 and d2 Beta. Args: d1: instance of a Beta distribution object. d2: instance of a Beta distribution object. name: (optional) Name to use for created operations. default is "kl_beta_beta". Returns: Batchwise KL(d1 || d2) """ with tf.name_scope(name or "kl_beta_beta"): d1_concentration1 = tf.convert_to_tensor(d1.concentration1) d1_concentration0 = tf.convert_to_tensor(d1.concentration0) d2_concentration1 = tf.convert_to_tensor(d2.concentration1) d2_concentration0 = tf.convert_to_tensor(d2.concentration0) d1_total_concentration = d1_concentration1 + d1_concentration0 d2_total_concentration = d2_concentration1 + d2_concentration0 d1_log_normalization = d1._log_normalization( # pylint: disable=protected-access d1_concentration1, d1_concentration0) d2_log_normalization = d2._log_normalization( # pylint: disable=protected-access d2_concentration1, d2_concentration0) return ((d2_log_normalization - d1_log_normalization) - (tf.math.digamma(d1_concentration1) * (d2_concentration1 - d1_concentration1)) - (tf.math.digamma(d1_concentration0) * (d2_concentration0 - d1_concentration0)) + (tf.math.digamma(d1_total_concentration) * (d2_total_concentration - d1_total_concentration)))
39.308094
100
0.69897
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v2 as tf from tensorflow_probability.python.distributions import distribution from tensorflow_probability.python.distributions import kullback_leibler from tensorflow_probability.python.internal import assert_util from tensorflow_probability.python.internal import distribution_util from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import prefer_static from tensorflow_probability.python.internal import reparameterization from tensorflow_probability.python.internal import tensor_util from tensorflow_probability.python.util.seed_stream import SeedStream from tensorflow.python.util import deprecation __all__ = [ "Beta", ] _beta_sample_note = """Note: `x` must have dtype `self.dtype` and be in `[0, 1].` It must have a shape compatible with `self.batch_shape()`.""" class Beta(distribution.Distribution): def __init__(self, concentration1, concentration0, validate_args=False, allow_nan_stats=True, name="Beta"): parameters = dict(locals()) with tf.name_scope(name) as name: dtype = dtype_util.common_dtype([concentration1, concentration0], dtype_hint=tf.float32) self._concentration1 = tensor_util.convert_nonref_to_tensor( concentration1, dtype=dtype, name="concentration1") self._concentration0 = tensor_util.convert_nonref_to_tensor( concentration0, dtype=dtype, name="concentration0") super(Beta, self).__init__( dtype=dtype, validate_args=validate_args, allow_nan_stats=allow_nan_stats, reparameterization_type=reparameterization.FULLY_REPARAMETERIZED, parameters=parameters, name=name) @staticmethod def _param_shapes(sample_shape): s = tf.convert_to_tensor(sample_shape, dtype=tf.int32) return dict(concentration1=s, concentration0=s) @classmethod def _params_event_ndims(cls): return dict(concentration1=0, concentration0=0) @property def concentration1(self): return self._concentration1 @property def concentration0(self): return self._concentration0 @property @deprecation.deprecated( "2019-10-01", ("The `total_concentration` property is deprecated; instead use " "`dist.concentration1 + dist.concentration0`."), warn_once=True) def total_concentration(self): with self._name_and_control_scope("total_concentration"): return self.concentration1 + self.concentration0 def _batch_shape_tensor(self, concentration1=None, concentration0=None): return prefer_static.broadcast_shape( prefer_static.shape( self.concentration1 if concentration1 is None else concentration1), prefer_static.shape( self.concentration0 if concentration0 is None else concentration0)) def _batch_shape(self): return tf.broadcast_static_shape( self.concentration1.shape, self.concentration0.shape) def _event_shape_tensor(self): return tf.constant([], dtype=tf.int32) def _event_shape(self): return tf.TensorShape([]) def _sample_n(self, n, seed=None): seed = SeedStream(seed, "beta") concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) shape = self._batch_shape_tensor(concentration1, concentration0) expanded_concentration1 = tf.broadcast_to(concentration1, shape) expanded_concentration0 = tf.broadcast_to(concentration0, shape) gamma1_sample = tf.random.gamma( shape=[n], alpha=expanded_concentration1, dtype=self.dtype, seed=seed()) gamma2_sample = tf.random.gamma( shape=[n], alpha=expanded_concentration0, dtype=self.dtype, seed=seed()) beta_sample = gamma1_sample / (gamma1_sample + gamma2_sample) return beta_sample @distribution_util.AppendDocstring(_beta_sample_note) def _log_prob(self, x): concentration0 = tf.convert_to_tensor(self.concentration0) concentration1 = tf.convert_to_tensor(self.concentration1) return (self._log_unnormalized_prob(x, concentration1, concentration0) - self._log_normalization(concentration1, concentration0)) @distribution_util.AppendDocstring(_beta_sample_note) def _prob(self, x): return tf.exp(self._log_prob(x)) @distribution_util.AppendDocstring(_beta_sample_note) def _log_cdf(self, x): return tf.math.log(self._cdf(x)) @distribution_util.AppendDocstring(_beta_sample_note) def _cdf(self, x): with tf.control_dependencies(self._maybe_assert_valid_sample(x)): concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) shape = self._batch_shape_tensor(concentration1, concentration0) concentration1 = tf.broadcast_to(concentration1, shape) concentration0 = tf.broadcast_to(concentration0, shape) return tf.math.betainc(concentration1, concentration0, x) def _log_unnormalized_prob(self, x, concentration1, concentration0): with tf.control_dependencies(self._maybe_assert_valid_sample(x)): return (tf.math.xlogy(concentration1 - 1., x) + (concentration0 - 1.) * tf.math.log1p(-x)) def _log_normalization(self, concentration1, concentration0): return (tf.math.lgamma(concentration1) + tf.math.lgamma(concentration0) - tf.math.lgamma(concentration1 + concentration0)) def _entropy(self): concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) total_concentration = concentration1 + concentration0 return (self._log_normalization(concentration1, concentration0) - (concentration1 - 1.) * tf.math.digamma(concentration1) - (concentration0 - 1.) * tf.math.digamma(concentration0) + (total_concentration - 2.) * tf.math.digamma(total_concentration)) def _mean(self): concentration1 = tf.convert_to_tensor(self.concentration1) return concentration1 / (concentration1 + self.concentration0) def _variance(self): concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) total_concentration = concentration1 + concentration0 return (concentration1 * concentration0 / ((total_concentration)**2 * (total_concentration + 1.))) @distribution_util.AppendDocstring( """Note: The mode is undefined when `concentration1 <= 1` or `concentration0 <= 1`. If `self.allow_nan_stats` is `True`, `NaN` is used for undefined modes. If `self.allow_nan_stats` is `False` an exception is raised when one or more modes are undefined.""") def _mode(self): concentration1 = tf.convert_to_tensor(self.concentration1) concentration0 = tf.convert_to_tensor(self.concentration0) mode = (concentration1 - 1.) / (concentration1 + concentration0 - 2.) with tf.control_dependencies([] if self.allow_nan_stats else [ assert_util.assert_less( tf.ones([], dtype=self.dtype), concentration1, message="Mode undefined for concentration1 <= 1."), assert_util.assert_less( tf.ones([], dtype=self.dtype), concentration0, message="Mode undefined for concentration0 <= 1.") ]): return tf.where( (concentration1 > 1.) & (concentration0 > 1.), mode, dtype_util.as_numpy_dtype(self.dtype)(np.nan)) def _maybe_assert_valid_sample(self, x): if not self.validate_args: return [] return [ assert_util.assert_positive(x, message="Sample must be positive."), assert_util.assert_less( x, tf.ones([], x.dtype), message="Sample must be less than `1`.") ] def _parameter_control_dependencies(self, is_init): if not self.validate_args: return [] assertions = [] for concentration in [self.concentration0, self.concentration1]: if is_init != tensor_util.is_ref(concentration): assertions.append(assert_util.assert_positive( concentration, message="Concentration parameter must be positive.")) return assertions @kullback_leibler.RegisterKL(Beta, Beta) def _kl_beta_beta(d1, d2, name=None): with tf.name_scope(name or "kl_beta_beta"): d1_concentration1 = tf.convert_to_tensor(d1.concentration1) d1_concentration0 = tf.convert_to_tensor(d1.concentration0) d2_concentration1 = tf.convert_to_tensor(d2.concentration1) d2_concentration0 = tf.convert_to_tensor(d2.concentration0) d1_total_concentration = d1_concentration1 + d1_concentration0 d2_total_concentration = d2_concentration1 + d2_concentration0 d1_log_normalization = d1._log_normalization( d1_concentration1, d1_concentration0) d2_log_normalization = d2._log_normalization( d2_concentration1, d2_concentration0) return ((d2_log_normalization - d1_log_normalization) - (tf.math.digamma(d1_concentration1) * (d2_concentration1 - d1_concentration1)) - (tf.math.digamma(d1_concentration0) * (d2_concentration0 - d1_concentration0)) + (tf.math.digamma(d1_total_concentration) * (d2_total_concentration - d1_total_concentration)))
true
true
f72d2c7e7a339b176c424997056def39dbb232ca
476
py
Python
data/scripts/templates/object/mobile/shared_dressed_binayre_ruffian_trandoshan_female_01.py
obi-two/GameServer
7d37024e2291a97d49522610cd8f1dbe5666afc2
[ "MIT" ]
20
2015-02-23T15:11:56.000Z
2022-03-18T20:56:48.000Z
data/scripts/templates/object/mobile/shared_dressed_binayre_ruffian_trandoshan_female_01.py
apathyboy/swganh
665128efe9154611dec4cb5efc61d246dd095984
[ "MIT" ]
null
null
null
data/scripts/templates/object/mobile/shared_dressed_binayre_ruffian_trandoshan_female_01.py
apathyboy/swganh
665128efe9154611dec4cb5efc61d246dd095984
[ "MIT" ]
20
2015-04-04T16:35:59.000Z
2022-03-24T14:54:37.000Z
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_binayre_ruffian_trandoshan_female_01.iff" result.attribute_template_id = 9 result.stfName("npc_name","trandoshan_base_female") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
28
90
0.747899
true
true
f72d2d7694c02f9baefa28ab714fa7d648759fe9
8,778
py
Python
groupbunk.py
shine-jayakumar/groupbunk-fb
ddf3d66cd902343e419dd2cf0c86f42850315f08
[ "MIT" ]
1
2022-02-11T05:31:48.000Z
2022-02-11T05:31:48.000Z
groupbunk.py
shine-jayakumar/groupbunk-fb
ddf3d66cd902343e419dd2cf0c86f42850315f08
[ "MIT" ]
null
null
null
groupbunk.py
shine-jayakumar/groupbunk-fb
ddf3d66cd902343e419dd2cf0c86f42850315f08
[ "MIT" ]
null
null
null
""" GroupBunk v.1.2 Leave your Facebook groups quietly Author: Shine Jayakumar Github: https://github.com/shine-jayakumar LICENSE: MIT """ from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import StaleElementReferenceException from webdriver_manager.chrome import ChromeDriverManager import argparse import logging import sys from datetime import datetime import time from groupfuncs import * import os # suppress webdriver manager logs os.environ['WDM_LOG_LEVEL'] = '0' IGNORE_DIV = ['your feed', 'discover', 'your notifications'] FB_GROUP_URL = 'https://www.facebook.com/groups/feed/' def display_intro(): ''' Displays intro of the script ''' intro = """ GroupBunk v.1.2 Leave your Facebook groups quietly Author: Shine Jayakumar Github: https://github.com/shine-jayakumar """ print(intro) def time_taken(start_time, logger): ''' Calculates the time difference from now and start time ''' end_time = time.time() logger.info(f"Total time taken: {round(end_time - start_time, 4)} seconds") def cleanup_and_quit(driver): ''' Quits driver and exits the script ''' if driver: driver.quit() sys.exit() start_time = time.time() # ==================================================== # Argument parsing # ==================================================== description = "Leave your Facebook groups quietly" usage = "groupbunk.py username password [-h] [-eg FILE] [-et TIMEOUT] [-sw WAIT] [-gr RETRYCOUNT] [-dg FILE]" examples=""" Examples: groupbunk.py bob101@email.com bobspassword101 groupbunk.py bob101@email.com bobspassword101 -eg keepgroups.txt groupbunk.py bob101@email.com bobspassword101 -et 60 --scrollwait 10 -gr 7 groupbunk.py bob101@email.com bobspassword101 --dumpgroups mygroup.txt --groupretry 5 """ parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=description, usage=usage, epilog=examples, prog='groupbunk') # required arguments parser.add_argument('username', type=str, help='Facebook username') parser.add_argument('password', type=str, help='Facebook password') # optional arguments parser.add_argument('-eg', '--exgroups', type=str, metavar='', help='file with group names to exclude (one group per line)') parser.add_argument('-et', '--eltimeout', type=int, metavar='', help='max timeout for elements to be loaded', default=30) parser.add_argument('-sw', '--scrollwait', type=int, metavar='', help='time to wait after each scroll', default=4) parser.add_argument('-gr', '--groupretry', type=int, metavar='', help='retry count while recapturing group names', default=5) parser.add_argument('-dg', '--dumpgroups', type=str, metavar='', help='do not leave groups; only dump group names to a file') parser.add_argument('-v', '--version', action='version', version='%(prog)s v.1.2') args = parser.parse_args() # ==================================================== # Setting up logger # ===================================================== logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s:%(name)s:%(lineno)d:%(levelname)s:%(message)s") file_handler = logging.FileHandler(f'groupbunk_{datetime.now().strftime("%d_%m_%Y__%H_%M_%S")}.log', 'w', 'utf-8') file_handler.setFormatter(formatter) stdout_formatter = logging.Formatter("[*] => %(message)s") stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(stdout_formatter) logger.addHandler(file_handler) logger.addHandler(stdout_handler) #======================================================= try: display_intro() logger.info("script started") # loading group names to be excluded if args.exgroups: logger.info("Loading group names to be excluded") excluded_group_names = get_excluded_group_names(args.exgroups) IGNORE_DIV.extend(excluded_group_names) options = Options() # supresses notifications options.add_argument("--disable-notifications") options.add_experimental_option('excludeSwitches', ['enable-logging']) options.add_argument("--log-level=3") logger.info("Downloading latest chrome webdriver") # UNCOMMENT TO SPECIFY DRIVER LOCATION # driver = webdriver.Chrome("D:/chromedriver/98/chromedriver.exe", options=options) driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) if not driver: raise Exception('Unable to download chrome webdriver for your version of Chrome browser') logger.info("Successfully downloaded chrome webdriver") wait = WebDriverWait(driver, args.eltimeout) logger.info(f"Opening FB GROUPS URL: {FB_GROUP_URL}") driver.get(FB_GROUP_URL) logger.info("Sending username") wait.until(EC.visibility_of_element_located((By.ID, 'email'))).send_keys(args.username) logger.info("Sending password") driver.find_element(By.ID, 'pass').send_keys(args.password) logger.info("Clicking on Log In") wait.until(EC.presence_of_element_located((By.ID, 'loginbutton'))).click() # get all the links inside divs representing group names group_links = get_group_link_elements(driver, wait) if not group_links: raise Exception("Unable to find links") no_of_currently_loaded_links = 0 logger.info(f"Initial link count: {len(group_links)-3}") logger.info("Scrolling down to capture all the links") # scroll until no new group links are loaded while len(group_links) > no_of_currently_loaded_links: no_of_currently_loaded_links = len(group_links) logger.info(f"Updated link count: {no_of_currently_loaded_links-3}") scroll_into_view(driver, group_links[no_of_currently_loaded_links-1]) time.sleep(args.scrollwait) # re-capturing group_links = get_group_link_elements(driver, wait) logger.info(f"Total number of links found: {len(group_links)-3}") # only show the group names and exit if args.dumpgroups: logger.info('Only dumping group names to file. Not leaving groups') logger.info(f"Dumping group names to: {args.dumpgroups}") dump_groups(group_links, args.dumpgroups) time_taken(start_time, logger) cleanup_and_quit(driver) # first 3 links are for Your feed, 'Discover, Your notifications i = 0 save_state = 0 no_of_retries = 0 failed_groups = [] total_groups = len(group_links) while i < total_groups: try: # need only the group name and not Last Active group_name = group_links[i].text.split('\n')[0] # if group name not in ignore list if group_name.lower() not in IGNORE_DIV: logger.info(f"Leaving group: {group_name}") link = group_links[i].get_attribute('href') logger.info(f"Opening group link: {link}") switch_tab(driver, open_new_tab(driver)) driver.get(link) if not leave_group(wait): logger.info('Unable to leave the group. You might not be a member of this group.') driver.close() switch_tab(driver, driver.window_handles[0]) else: if group_name.lower() not in ['your feed', 'discover', 'your notifications']: logger.info(f"Skipping group : {group_name}") i += 1 except StaleElementReferenceException: logger.error('Captured group elements gone stale. Recapturing...') if no_of_retries > args.groupretry: logger.error('Reached max number of retry attempts') break save_state = i group_links = get_group_link_elements(driver, wait) no_of_retries += 1 except Exception as ex: logger.error(f"Unable to leave group {group_name}. Error: {ex}") failed_groups.append(group_name) i += 1 total_no_of_groups = len(group_links)-3 total_no_failed_groups = len(failed_groups) logger.info(f"Total groups: {total_no_of_groups}") logger.info(f"No. of groups failed to leave: {total_no_failed_groups}") logger.info(f"Success percentage: {((total_no_of_groups - total_no_failed_groups)/total_no_of_groups) * 100} %") if failed_groups: failed_group_names = ", ".join(failed_groups) logger.info(f"Failed groups: \n{failed_group_names}") except Exception as ex: logger.error(f"Script ended with exception: {ex}") finally: time_taken(start_time, logger) cleanup_and_quit(driver)
35.97541
127
0.670084
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import StaleElementReferenceException from webdriver_manager.chrome import ChromeDriverManager import argparse import logging import sys from datetime import datetime import time from groupfuncs import * import os os.environ['WDM_LOG_LEVEL'] = '0' IGNORE_DIV = ['your feed', 'discover', 'your notifications'] FB_GROUP_URL = 'https://www.facebook.com/groups/feed/' def display_intro(): intro = """ GroupBunk v.1.2 Leave your Facebook groups quietly Author: Shine Jayakumar Github: https://github.com/shine-jayakumar """ print(intro) def time_taken(start_time, logger): end_time = time.time() logger.info(f"Total time taken: {round(end_time - start_time, 4)} seconds") def cleanup_and_quit(driver): if driver: driver.quit() sys.exit() start_time = time.time() description = "Leave your Facebook groups quietly" usage = "groupbunk.py username password [-h] [-eg FILE] [-et TIMEOUT] [-sw WAIT] [-gr RETRYCOUNT] [-dg FILE]" examples=""" Examples: groupbunk.py bob101@email.com bobspassword101 groupbunk.py bob101@email.com bobspassword101 -eg keepgroups.txt groupbunk.py bob101@email.com bobspassword101 -et 60 --scrollwait 10 -gr 7 groupbunk.py bob101@email.com bobspassword101 --dumpgroups mygroup.txt --groupretry 5 """ parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=description, usage=usage, epilog=examples, prog='groupbunk') parser.add_argument('username', type=str, help='Facebook username') parser.add_argument('password', type=str, help='Facebook password') parser.add_argument('-eg', '--exgroups', type=str, metavar='', help='file with group names to exclude (one group per line)') parser.add_argument('-et', '--eltimeout', type=int, metavar='', help='max timeout for elements to be loaded', default=30) parser.add_argument('-sw', '--scrollwait', type=int, metavar='', help='time to wait after each scroll', default=4) parser.add_argument('-gr', '--groupretry', type=int, metavar='', help='retry count while recapturing group names', default=5) parser.add_argument('-dg', '--dumpgroups', type=str, metavar='', help='do not leave groups; only dump group names to a file') parser.add_argument('-v', '--version', action='version', version='%(prog)s v.1.2') args = parser.parse_args() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s:%(name)s:%(lineno)d:%(levelname)s:%(message)s") file_handler = logging.FileHandler(f'groupbunk_{datetime.now().strftime("%d_%m_%Y__%H_%M_%S")}.log', 'w', 'utf-8') file_handler.setFormatter(formatter) stdout_formatter = logging.Formatter("[*] => %(message)s") stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(stdout_formatter) logger.addHandler(file_handler) logger.addHandler(stdout_handler) try: display_intro() logger.info("script started") if args.exgroups: logger.info("Loading group names to be excluded") excluded_group_names = get_excluded_group_names(args.exgroups) IGNORE_DIV.extend(excluded_group_names) options = Options() options.add_argument("--disable-notifications") options.add_experimental_option('excludeSwitches', ['enable-logging']) options.add_argument("--log-level=3") logger.info("Downloading latest chrome webdriver") driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) if not driver: raise Exception('Unable to download chrome webdriver for your version of Chrome browser') logger.info("Successfully downloaded chrome webdriver") wait = WebDriverWait(driver, args.eltimeout) logger.info(f"Opening FB GROUPS URL: {FB_GROUP_URL}") driver.get(FB_GROUP_URL) logger.info("Sending username") wait.until(EC.visibility_of_element_located((By.ID, 'email'))).send_keys(args.username) logger.info("Sending password") driver.find_element(By.ID, 'pass').send_keys(args.password) logger.info("Clicking on Log In") wait.until(EC.presence_of_element_located((By.ID, 'loginbutton'))).click() group_links = get_group_link_elements(driver, wait) if not group_links: raise Exception("Unable to find links") no_of_currently_loaded_links = 0 logger.info(f"Initial link count: {len(group_links)-3}") logger.info("Scrolling down to capture all the links") while len(group_links) > no_of_currently_loaded_links: no_of_currently_loaded_links = len(group_links) logger.info(f"Updated link count: {no_of_currently_loaded_links-3}") scroll_into_view(driver, group_links[no_of_currently_loaded_links-1]) time.sleep(args.scrollwait) group_links = get_group_link_elements(driver, wait) logger.info(f"Total number of links found: {len(group_links)-3}") if args.dumpgroups: logger.info('Only dumping group names to file. Not leaving groups') logger.info(f"Dumping group names to: {args.dumpgroups}") dump_groups(group_links, args.dumpgroups) time_taken(start_time, logger) cleanup_and_quit(driver) i = 0 save_state = 0 no_of_retries = 0 failed_groups = [] total_groups = len(group_links) while i < total_groups: try: # need only the group name and not Last Active group_name = group_links[i].text.split('\n')[0] # if group name not in ignore list if group_name.lower() not in IGNORE_DIV: logger.info(f"Leaving group: {group_name}") link = group_links[i].get_attribute('href') logger.info(f"Opening group link: {link}") switch_tab(driver, open_new_tab(driver)) driver.get(link) if not leave_group(wait): logger.info('Unable to leave the group. You might not be a member of this group.') driver.close() switch_tab(driver, driver.window_handles[0]) else: if group_name.lower() not in ['your feed', 'discover', 'your notifications']: logger.info(f"Skipping group : {group_name}") i += 1 except StaleElementReferenceException: logger.error('Captured group elements gone stale. Recapturing...') if no_of_retries > args.groupretry: logger.error('Reached max number of retry attempts') break save_state = i group_links = get_group_link_elements(driver, wait) no_of_retries += 1 except Exception as ex: logger.error(f"Unable to leave group {group_name}. Error: {ex}") failed_groups.append(group_name) i += 1 total_no_of_groups = len(group_links)-3 total_no_failed_groups = len(failed_groups) logger.info(f"Total groups: {total_no_of_groups}") logger.info(f"No. of groups failed to leave: {total_no_failed_groups}") logger.info(f"Success percentage: {((total_no_of_groups - total_no_failed_groups)/total_no_of_groups) * 100} %") if failed_groups: failed_group_names = ", ".join(failed_groups) logger.info(f"Failed groups: \n{failed_group_names}") except Exception as ex: logger.error(f"Script ended with exception: {ex}") finally: time_taken(start_time, logger) cleanup_and_quit(driver)
true
true
f72d2dffe680e5fa8e448bd4483a994fa75b8c69
631
py
Python
python/24_swap_nodes_in_pairs.py
dchapp/blind75
aaa409cf2db4ef6d0f86177f4217eceeb391caa8
[ "MIT" ]
null
null
null
python/24_swap_nodes_in_pairs.py
dchapp/blind75
aaa409cf2db4ef6d0f86177f4217eceeb391caa8
[ "MIT" ]
null
null
null
python/24_swap_nodes_in_pairs.py
dchapp/blind75
aaa409cf2db4ef6d0f86177f4217eceeb391caa8
[ "MIT" ]
null
null
null
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: return self.recursive(head) def recursive(self, head): if head is None or head.next is None: return head current = head successor = head.next subproblem = head.next.next # Make successor the new head successor.next = current current.next = self.recursive(subproblem) return successor
28.681818
72
0.600634
class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: return self.recursive(head) def recursive(self, head): if head is None or head.next is None: return head current = head successor = head.next subproblem = head.next.next successor.next = current current.next = self.recursive(subproblem) return successor
true
true
f72d2e556f8e1a61daf19ae049a8aca684ccd0aa
4,594
py
Python
axelrod/tests/strategies/test_human.py
danilobellini/Axelrod
2c9212553e06095c24adcb82a5979279cbdf45fb
[ "MIT" ]
null
null
null
axelrod/tests/strategies/test_human.py
danilobellini/Axelrod
2c9212553e06095c24adcb82a5979279cbdf45fb
[ "MIT" ]
null
null
null
axelrod/tests/strategies/test_human.py
danilobellini/Axelrod
2c9212553e06095c24adcb82a5979279cbdf45fb
[ "MIT" ]
null
null
null
from os import linesep from unittest import TestCase from unittest.mock import patch from axelrod import Action, Cooperator, Player from axelrod.strategies.human import ActionValidator, Human from prompt_toolkit.validation import ValidationError from .test_player import TestPlayer C, D = Action.C, Action.D class TestDocument(object): """ A class to mimic a prompt-toolkit document having just the text attribute. """ def __init__(self, text): self.text = text class TestActionValidator(TestCase): def test_validator(self): test_documents = [TestDocument(x) for x in ["C", "c", "D", "d"]] for test_document in test_documents: ActionValidator().validate(test_document) test_document = TestDocument("E") self.assertRaises(ValidationError, ActionValidator().validate, test_document) class TestHumanClass(TestPlayer): name = "Human: human, C, D" player = Human expected_classifier = { "memory_depth": float("inf"), "stochastic": True, "makes_use_of": set(["length", "game"]), "long_run_time": True, "inspects_source": True, "manipulates_source": False, "manipulates_state": False, } def test_init(self): human = Human(name="test human", c_symbol="X", d_symbol="Y") self.assertEqual(human.human_name, "test human") self.assertEqual(human.symbols, {C: "X", D: "Y"}) def test_history_toolbar(self): human = Human() expected_content = "" actual_content = human._history_toolbar(None)[0][1] self.assertEqual(actual_content, expected_content) human.history = [C] human.opponent_history = [C] expected_content = "History (human, opponent): [('C', 'C')]" actual_content = human._history_toolbar(None)[0][1] self.assertIn(actual_content, expected_content) def test_status_messages(self): human = Human() expected_messages = { "toolbar": None, "print": "{}Starting new match".format(linesep), } actual_messages = human._status_messages() self.assertEqual(actual_messages, expected_messages) human.history = [C] human.opponent_history = [C] expected_print_message = "{}Turn 1: human played C, opponent played C".format( linesep ) actual_messages = human._status_messages() self.assertEqual(actual_messages["print"], expected_print_message) self.assertIsNotNone(actual_messages["toolbar"]) def test_get_human_input_c(self): with patch("axelrod.human.prompt", return_value="c") as prompt_: actions = [(C, C)] * 5 self.versus_test(Cooperator(), expected_actions=actions) self.assertEqual( prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) ) def test_get_human_input_C(self): with patch("axelrod.human.prompt", return_value="C") as prompt_: actions = [(C, C)] * 5 self.versus_test(Cooperator(), expected_actions=actions) self.assertEqual( prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) ) def test_get_human_input_d(self): with patch("axelrod.human.prompt", return_value="d") as prompt_: actions = [(D, C)] * 5 self.versus_test(Cooperator(), expected_actions=actions) self.assertEqual( prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) ) def test_get_human_input_D(self): with patch("axelrod.human.prompt", return_value="D") as prompt_: actions = [(D, C)] * 5 self.versus_test(Cooperator(), expected_actions=actions) self.assertEqual( prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) ) def test_strategy(self): human = Human() expected_action = C actual_action = human.strategy(Player(), lambda: C) self.assertEqual(actual_action, expected_action) def test_reset_history_and_attributes(self): """Overwrite the reset method for this strategy.""" pass def test_repr(self): human = Human() self.assertEqual(human.__repr__(), "Human: human") human = Human(name="John Nash") self.assertEqual(human.__repr__(), "Human: John Nash") human = Human(name="John Nash", c_symbol="1", d_symbol="2") self.assertEqual(human.__repr__(), "Human: John Nash")
34.80303
86
0.622987
from os import linesep from unittest import TestCase from unittest.mock import patch from axelrod import Action, Cooperator, Player from axelrod.strategies.human import ActionValidator, Human from prompt_toolkit.validation import ValidationError from .test_player import TestPlayer C, D = Action.C, Action.D class TestDocument(object): def __init__(self, text): self.text = text class TestActionValidator(TestCase): def test_validator(self): test_documents = [TestDocument(x) for x in ["C", "c", "D", "d"]] for test_document in test_documents: ActionValidator().validate(test_document) test_document = TestDocument("E") self.assertRaises(ValidationError, ActionValidator().validate, test_document) class TestHumanClass(TestPlayer): name = "Human: human, C, D" player = Human expected_classifier = { "memory_depth": float("inf"), "stochastic": True, "makes_use_of": set(["length", "game"]), "long_run_time": True, "inspects_source": True, "manipulates_source": False, "manipulates_state": False, } def test_init(self): human = Human(name="test human", c_symbol="X", d_symbol="Y") self.assertEqual(human.human_name, "test human") self.assertEqual(human.symbols, {C: "X", D: "Y"}) def test_history_toolbar(self): human = Human() expected_content = "" actual_content = human._history_toolbar(None)[0][1] self.assertEqual(actual_content, expected_content) human.history = [C] human.opponent_history = [C] expected_content = "History (human, opponent): [('C', 'C')]" actual_content = human._history_toolbar(None)[0][1] self.assertIn(actual_content, expected_content) def test_status_messages(self): human = Human() expected_messages = { "toolbar": None, "print": "{}Starting new match".format(linesep), } actual_messages = human._status_messages() self.assertEqual(actual_messages, expected_messages) human.history = [C] human.opponent_history = [C] expected_print_message = "{}Turn 1: human played C, opponent played C".format( linesep ) actual_messages = human._status_messages() self.assertEqual(actual_messages["print"], expected_print_message) self.assertIsNotNone(actual_messages["toolbar"]) def test_get_human_input_c(self): with patch("axelrod.human.prompt", return_value="c") as prompt_: actions = [(C, C)] * 5 self.versus_test(Cooperator(), expected_actions=actions) self.assertEqual( prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) ) def test_get_human_input_C(self): with patch("axelrod.human.prompt", return_value="C") as prompt_: actions = [(C, C)] * 5 self.versus_test(Cooperator(), expected_actions=actions) self.assertEqual( prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) ) def test_get_human_input_d(self): with patch("axelrod.human.prompt", return_value="d") as prompt_: actions = [(D, C)] * 5 self.versus_test(Cooperator(), expected_actions=actions) self.assertEqual( prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) ) def test_get_human_input_D(self): with patch("axelrod.human.prompt", return_value="D") as prompt_: actions = [(D, C)] * 5 self.versus_test(Cooperator(), expected_actions=actions) self.assertEqual( prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) ) def test_strategy(self): human = Human() expected_action = C actual_action = human.strategy(Player(), lambda: C) self.assertEqual(actual_action, expected_action) def test_reset_history_and_attributes(self): pass def test_repr(self): human = Human() self.assertEqual(human.__repr__(), "Human: human") human = Human(name="John Nash") self.assertEqual(human.__repr__(), "Human: John Nash") human = Human(name="John Nash", c_symbol="1", d_symbol="2") self.assertEqual(human.__repr__(), "Human: John Nash")
true
true
f72d30c55d3dd51166d633ec61c36e24eaf973af
4,841
py
Python
stepper.py
mechkro/Linux_Repo
f71e71814a5496470b731bb32b3be67ab8085f7a
[ "MIT" ]
null
null
null
stepper.py
mechkro/Linux_Repo
f71e71814a5496470b731bb32b3be67ab8085f7a
[ "MIT" ]
null
null
null
stepper.py
mechkro/Linux_Repo
f71e71814a5496470b731bb32b3be67ab8085f7a
[ "MIT" ]
null
null
null
from time import sleep import RPi.GPIO as GPIO ######################################################################## #SOURCE - https://www.rototron.info/raspberry-pi-stepper-motor-tutorial/ ######################################################################## """ As always I recommend you start with a freshly wiped Pi using the latest version of Raspbian to ensure you have all the necessary software. The first Python example rotates a 48 SPR (steps per revolution) motor once clockwise and then back counter-clockwise using the RPi.GPIO library. The DIR and STEP pins are set as outputs. The DIR pin is set high for clockwise. Then a for loop counts up to 48. Each cycle toggles the STEP pin high for .0208 seconds and low for .0208 seconds. The DIR pin is set low for counter-clockwise and the for loop is repeated. """ DIR = 20 # Direction GPIO Pin STEP = 21 # Step GPIO Pin CW = 1 # Clockwise Rotation CCW = 0 # Counterclockwise Rotation SPR = 48 # Steps per Revolution (360 / 7.5) GPIO.setmode(GPIO.BCM) GPIO.setup(DIR, GPIO.OUT) GPIO.setup(STEP, GPIO.OUT) GPIO.output(DIR, CW) step_count = SPR delay = .0208 for x in range(step_count): GPIO.output(STEP, GPIO.HIGH) sleep(delay) GPIO.output(STEP, GPIO.LOW) sleep(delay) sleep(.5) GPIO.output(DIR, CCW) for x in range(step_count): GPIO.output(STEP, GPIO.HIGH) sleep(delay) GPIO.output(STEP, GPIO.LOW) sleep(delay) GPIO.cleanup() """ This code may result in motor vibration and jerky motion especially at low speeds. One way to counter these result is with microstepping. The following code snippet is added to the code above. The mode GPIO pins are set as outputs. A dict holds the appropriate values for each stepping format. GPIO.output sets the mode to 1/32. Note that step count is multiplied by 32 because each rotation now takes 32 times as many cycles which results in more fluid motion. The delay is divided by 32 to compensate for the extra steps. """ MODE = (14, 15, 18) # Microstep Resolution GPIO Pins GPIO.setup(MODE, GPIO.OUT) RESOLUTION = {'Full': (0, 0, 0), 'Half': (1, 0, 0), '1/4': (0, 1, 0), '1/8': (1, 1, 0), '1/16': (0, 0, 1), '1/32': (1, 0, 1)} GPIO.output(MODE, RESOLUTION['1/32']) step_count = SPR * 32 delay = .0208 / 32 """ Please be aware that there are some significant downsides to microstepping. There is often a substantial loss of torque which can lead to a loss of accuracy. See the resources section below for more information. For the next example, a switch will be added to change direction. One terminal of the switch goes to GPIO16. Another terminal goes to ground. Schematic with switch One issue with the last program is that it relies on the Python sleep method for timing which is not very reliable. For the next example, I’ll use the PiGPIO library which provides hardware based PWM timing. Before use, the PiGPIO daemon must be started using sudo pigpiod from a terminal. >>$ sudo pigpiod The first part of the following code is similar to the first example. The syntax is modified for the PiGPIO library. The set_PWM_dutycycle method is used to set the PWM dutycycle. This is the percentage of the pulse that is high and low. The value 128 sets it to 50%. Therefore, the on and off portions of the cycle are equal. The set_PWM_frequency method sets the number of pulses per second. The value 500 sets the frequency to 500 Hz. An infinite while loop checks the switch and toggles the direction appropriately. """ from time import sleep import pigpio DIR = 20 # Direction GPIO Pin STEP = 21 # Step GPIO Pin SWITCH = 16 # GPIO pin of switch # Connect to pigpiod daemon pi = pigpio.pi() # Set up pins as an output pi.set_mode(DIR, pigpio.OUTPUT) pi.set_mode(STEP, pigpio.OUTPUT) # Set up input switch pi.set_mode(SWITCH, pigpio.INPUT) pi.set_pull_up_down(SWITCH, pigpio.PUD_UP) MODE = (14, 15, 18) # Microstep Resolution GPIO Pins RESOLUTION = {'Full': (0, 0, 0), 'Half': (1, 0, 0), '1/4': (0, 1, 0), '1/8': (1, 1, 0), '1/16': (0, 0, 1), '1/32': (1, 0, 1)} for i in range(3): pi.write(MODE[i], RESOLUTION['Full'][i]) # Set duty cycle and frequency pi.set_PWM_dutycycle(STEP, 128) # PWM 1/2 On 1/2 Off pi.set_PWM_frequency(STEP, 500) # 500 pulses per second try: while True: pi.write(DIR, pi.read(SWITCH)) # Set direction sleep(.1) except KeyboardInterrupt: print ("\nCtrl-C pressed. Stopping PIGPIO and exiting...") finally: pi.set_PWM_dutycycle(STEP, 0) # PWM off pi.stop() """ One caveat when using the PiGPIO set_PWM_frequency method is it is limited to specific frequency values per sample rate as specified in the following table. """
32.059603
92
0.677959
from time import sleep import RPi.GPIO as GPIO
true
true
f72d310e84eaa324a5380b4aaf86a7da4b908cd0
682
py
Python
spacy/tests/lang/nb/test_tokenizer.py
cedar101/spaCy
66e22098a8bb77cbe527b1a4a3c69ec1cfb56f95
[ "MIT" ]
12
2019-03-20T20:43:47.000Z
2020-04-13T11:10:52.000Z
spacy/tests/lang/nb/test_tokenizer.py
cedar101/spaCy
66e22098a8bb77cbe527b1a4a3c69ec1cfb56f95
[ "MIT" ]
13
2018-06-05T11:54:40.000Z
2019-07-02T11:33:14.000Z
spacy/tests/lang/nb/test_tokenizer.py
cedar101/spaCy
66e22098a8bb77cbe527b1a4a3c69ec1cfb56f95
[ "MIT" ]
2
2020-02-15T18:33:35.000Z
2022-02-13T14:11:41.000Z
# coding: utf8 from __future__ import unicode_literals import pytest NB_TOKEN_EXCEPTION_TESTS = [ ( "Smørsausen brukes bl.a. til fisk", ["Smørsausen", "brukes", "bl.a.", "til", "fisk"], ), ( "Jeg kommer først kl. 13 pga. diverse forsinkelser", ["Jeg", "kommer", "først", "kl.", "13", "pga.", "diverse", "forsinkelser"], ), ] @pytest.mark.parametrize("text,expected_tokens", NB_TOKEN_EXCEPTION_TESTS) def test_nb_tokenizer_handles_exception_cases(nb_tokenizer, text, expected_tokens): tokens = nb_tokenizer(text) token_list = [token.text for token in tokens if not token.is_space] assert expected_tokens == token_list
28.416667
83
0.673021
from __future__ import unicode_literals import pytest NB_TOKEN_EXCEPTION_TESTS = [ ( "Smørsausen brukes bl.a. til fisk", ["Smørsausen", "brukes", "bl.a.", "til", "fisk"], ), ( "Jeg kommer først kl. 13 pga. diverse forsinkelser", ["Jeg", "kommer", "først", "kl.", "13", "pga.", "diverse", "forsinkelser"], ), ] @pytest.mark.parametrize("text,expected_tokens", NB_TOKEN_EXCEPTION_TESTS) def test_nb_tokenizer_handles_exception_cases(nb_tokenizer, text, expected_tokens): tokens = nb_tokenizer(text) token_list = [token.text for token in tokens if not token.is_space] assert expected_tokens == token_list
true
true
f72d313ae90abc9a33fbbe8f201a19f2c2f9ceb1
2,825
py
Python
irobot/openinterface/constants.py
bhargav-nunna/irobot
9251f71267fa8cf5e9620f70aa892ae1b7a182f9
[ "Unlicense" ]
13
2018-08-19T07:09:36.000Z
2021-08-10T22:52:31.000Z
irobot/openinterface/constants.py
bhargav-nunna/irobot
9251f71267fa8cf5e9620f70aa892ae1b7a182f9
[ "Unlicense" ]
null
null
null
irobot/openinterface/constants.py
bhargav-nunna/irobot
9251f71267fa8cf5e9620f70aa892ae1b7a182f9
[ "Unlicense" ]
4
2019-01-21T20:03:36.000Z
2021-01-26T23:59:00.000Z
__author__ = 'Matthew Witherwax (lemoneer)' class Constant(object): def __init__(self, **kwds): self.__dict__.update(kwds) BAUD_RATE = Constant(BAUD_300=0, BAUD_600=1, BAUD_1200=2, BAUD_2400=3, BAUD_4800=4, BAUD_9600=5, BAUD_14400=6, BAUD_19200=7, BAUD_28800=8, BAUD_38400=9, BAUD_57600=10, BAUD_115200=11, DEFAULT=11) DAYS = Constant(SUNDAY=0x01, MONDAY=0x02, TUESDAY=0x04, WEDNESDAY=0x08, THURSDAY=0x10, FRIDAY=0x20, SATURDAY=0x40) DRIVE = Constant(STRAIGHT=0x8000, STRAIGHT_ALT=0x7FFF, TURN_IN_PLACE_CW=0xFFFF, TURN_IN_PLACE_CCW=0x0001) MOTORS = Constant(SIDE_BRUSH=0x01, VACUUM=0x02, MAIN_BRUSH=0x04, SIDE_BRUSH_DIRECTION=0x08, MAIN_BRUSH_DIRECTION=0x10) LEDS = Constant(DEBRIS=0x01, SPOT=0x02, DOCK=0x04, CHECK_ROBOT=0x08) WEEKDAY_LEDS = Constant(SUNDAY=0x01, MONDAY=0x02, TUESDAY=0x04, WEDNESDAY=0x08, THURSDAY=0x10, FRIDAY=0x20, SATURDAY=0x40) SCHEDULING_LEDS = Constant(COLON=0x01, PM=0x02, AM=0x04, CLOCK=0x08, SCHEDULE=0x10) RAW_LED = Constant(A=0x01, B=0x02, C=0x04, D=0x08, E=0x10, F=0x20, G=0x40) BUTTONS = Constant(CLEAN=0x01, SPOT=0x02, DOCK=0x04, MINUTE=0x08, HOUR=0x10, DAY=0x20, SCHEDULE=0x40, CLOCK=0x80) ROBOT = Constant(TICK_PER_REV=508.8, WHEEL_DIAMETER=72, WHEEL_BASE=235, TICK_TO_DISTANCE=0.44456499814949904317867595046408) MODES = Constant(OFF=0, PASSIVE=1, SAFE=2, FULL=3) WHEEL_OVERCURRENT = Constant(SIDE_BRUSH=0x01, MAIN_BRUSH=0x02, RIGHT_WHEEL=0x04, LEFT_WHEEL=0x08) BUMPS_WHEEL_DROPS = Constant(BUMP_RIGHT=0x01, BUMP_LEFT=0x02, WHEEL_DROP_RIGHT=0x04, WHEEL_DROP_LEFT=0x08) CHARGE_SOURCE = Constant(INTERNAL=0x01, HOME_BASE=0x02) LIGHT_BUMPER = Constant(LEFT=0x01, FRONT_LEFT=0x02, CENTER_LEFT=0x04, CENTER_RIGHT=0x08, FRONT_RIGHT=0x10, RIGHT=0x20) STASIS = Constant(TOGGLING=0x01, DISABLED=0x02) POWER_SAVE_TIME = 300 # seconds RESPONSE_SIZES = {0: 26, 1: 10, 2: 6, 3: 10, 4: 14, 5: 12, 6: 52, # actual sensors 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 2, 20: 2, 21: 1, 22: 2, 23: 2, 24: 1, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2, 32: 3, 33: 3, 34: 1, 35: 1, 36: 1, 37: 1, 38: 1, 39: 2, 40: 2, 41: 2, 42: 2, 43: 2, 44: 2, 45: 1, 46: 2, 47: 2, 48: 2, 49: 2, 50: 2, 51: 2, 52: 1, 53: 1, 54: 2, 55: 2, 56: 2, 57: 2, 58: 1, # end actual sensors 100: 80, 101: 28, 106: 12, 107: 9}
65.697674
121
0.578761
__author__ = 'Matthew Witherwax (lemoneer)' class Constant(object): def __init__(self, **kwds): self.__dict__.update(kwds) BAUD_RATE = Constant(BAUD_300=0, BAUD_600=1, BAUD_1200=2, BAUD_2400=3, BAUD_4800=4, BAUD_9600=5, BAUD_14400=6, BAUD_19200=7, BAUD_28800=8, BAUD_38400=9, BAUD_57600=10, BAUD_115200=11, DEFAULT=11) DAYS = Constant(SUNDAY=0x01, MONDAY=0x02, TUESDAY=0x04, WEDNESDAY=0x08, THURSDAY=0x10, FRIDAY=0x20, SATURDAY=0x40) DRIVE = Constant(STRAIGHT=0x8000, STRAIGHT_ALT=0x7FFF, TURN_IN_PLACE_CW=0xFFFF, TURN_IN_PLACE_CCW=0x0001) MOTORS = Constant(SIDE_BRUSH=0x01, VACUUM=0x02, MAIN_BRUSH=0x04, SIDE_BRUSH_DIRECTION=0x08, MAIN_BRUSH_DIRECTION=0x10) LEDS = Constant(DEBRIS=0x01, SPOT=0x02, DOCK=0x04, CHECK_ROBOT=0x08) WEEKDAY_LEDS = Constant(SUNDAY=0x01, MONDAY=0x02, TUESDAY=0x04, WEDNESDAY=0x08, THURSDAY=0x10, FRIDAY=0x20, SATURDAY=0x40) SCHEDULING_LEDS = Constant(COLON=0x01, PM=0x02, AM=0x04, CLOCK=0x08, SCHEDULE=0x10) RAW_LED = Constant(A=0x01, B=0x02, C=0x04, D=0x08, E=0x10, F=0x20, G=0x40) BUTTONS = Constant(CLEAN=0x01, SPOT=0x02, DOCK=0x04, MINUTE=0x08, HOUR=0x10, DAY=0x20, SCHEDULE=0x40, CLOCK=0x80) ROBOT = Constant(TICK_PER_REV=508.8, WHEEL_DIAMETER=72, WHEEL_BASE=235, TICK_TO_DISTANCE=0.44456499814949904317867595046408) MODES = Constant(OFF=0, PASSIVE=1, SAFE=2, FULL=3) WHEEL_OVERCURRENT = Constant(SIDE_BRUSH=0x01, MAIN_BRUSH=0x02, RIGHT_WHEEL=0x04, LEFT_WHEEL=0x08) BUMPS_WHEEL_DROPS = Constant(BUMP_RIGHT=0x01, BUMP_LEFT=0x02, WHEEL_DROP_RIGHT=0x04, WHEEL_DROP_LEFT=0x08) CHARGE_SOURCE = Constant(INTERNAL=0x01, HOME_BASE=0x02) LIGHT_BUMPER = Constant(LEFT=0x01, FRONT_LEFT=0x02, CENTER_LEFT=0x04, CENTER_RIGHT=0x08, FRONT_RIGHT=0x10, RIGHT=0x20) STASIS = Constant(TOGGLING=0x01, DISABLED=0x02) POWER_SAVE_TIME = 300 RESPONSE_SIZES = {0: 26, 1: 10, 2: 6, 3: 10, 4: 14, 5: 12, 6: 52, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 2, 20: 2, 21: 1, 22: 2, 23: 2, 24: 1, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2, 32: 3, 33: 3, 34: 1, 35: 1, 36: 1, 37: 1, 38: 1, 39: 2, 40: 2, 41: 2, 42: 2, 43: 2, 44: 2, 45: 1, 46: 2, 47: 2, 48: 2, 49: 2, 50: 2, 51: 2, 52: 1, 53: 1, 54: 2, 55: 2, 56: 2, 57: 2, 58: 1, 100: 80, 101: 28, 106: 12, 107: 9}
true
true
f72d313fd14aa573c97358c7fd15134cb132ca43
79
py
Python
part1/settings.py
codingfever-anishmishra/Warrior-Game-developement-in-python
ff9bb627251f6b82a08f3bc7d84fb72068fea3db
[ "Apache-2.0" ]
null
null
null
part1/settings.py
codingfever-anishmishra/Warrior-Game-developement-in-python
ff9bb627251f6b82a08f3bc7d84fb72068fea3db
[ "Apache-2.0" ]
null
null
null
part1/settings.py
codingfever-anishmishra/Warrior-Game-developement-in-python
ff9bb627251f6b82a08f3bc7d84fb72068fea3db
[ "Apache-2.0" ]
null
null
null
WIDTH = 1024 HEIGHT = 768 #colours WHITE = (255,255,255) RED = (255,0,0)
9.875
21
0.594937
WIDTH = 1024 HEIGHT = 768 WHITE = (255,255,255) RED = (255,0,0)
true
true
f72d316388cae4d3fa92f9185ec7e2b07efe7778
24,267
py
Python
source/spktype21.py
whiskie14142/spktype21
7ed22365fe92cdb74c416d27634df96a45712953
[ "MIT" ]
1
2021-10-21T20:07:04.000Z
2021-10-21T20:07:04.000Z
source/spktype21.py
whiskie14142/spktype21
7ed22365fe92cdb74c416d27634df96a45712953
[ "MIT" ]
1
2020-05-20T05:54:34.000Z
2020-05-20T05:54:34.000Z
source/spktype21.py
whiskie14142/spktype21
7ed22365fe92cdb74c416d27634df96a45712953
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """A supporting module for jplephem to handle data type 21 (Version 0.1.0) This module computes position and velocity of a celestial small body, from a NASA SPICE SPK ephemeris kernel file of data type 21 (Extended Modified Difference Arrays). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/FORTRAN/req/spk.html You can get SPK files for many solar system small bodies from HORIZONS system of NASA/JPL. See https://ssd.jpl.nasa.gov/?horizons This module reads SPK files of data type 21, one of the types of binary SPK file. At the point of Oct. 2018, HORIZONS system provides files of type 21 for binary SPK files by default. You can get type 21 binary SPK file for celestial small bodies through TELNET interface by answering back 'Binary' for 'SPK file format'. Also you can get type 21 binary SPK file from: https://ssd.jpl.nasa.gov/x/spk.html Modules required: jplephem (version 2.6 or later) numpy Usage: from spktype21 import SPKType21 kernel = SPKType21.open('path') position, velocity = kernel.compute_type21(center, target, jd) where: path - path to the SPK file center - SPKID of central body (0 for SSB, 10 for Sun, etc.) target - SPKID of target body jd - time for computation (Julian date) Exceptions: RuntimeError will be raised when: invalid data_type of SPK file, or SPK file contains too large table in EMDA record(s) ValueError will be raised when: invalid parameter(s) of compute_type21 function Author: Shushi Uetsuki (whiskie14142) This module has been developed based on jplephem and FORTRAN source of the SPICE Toolkit of NASA/JPL/NAIF. jplephem : https://pypi.org/project/jplephem/ SPICE Toolkit : http://naif.jpl.nasa.gov/naif/toolkit.html """ from numpy import array, zeros, reshape from jplephem.daf import DAF from jplephem.names import target_names T0 = 2451545.0 S_PER_DAY = 86400.0 # Included from 'spk21.inc' on the FORTRAN source 'spke21.f' MAXTRM = 25 def jd(seconds): """Convert a number of seconds since J2000 to a Julian Date. """ return T0 + seconds / S_PER_DAY class SPKType21(object): """Class for SPK kernel to handle data type 21 (Extended Modified Difference Arrays) """ def __init__(self, daf): self.daf = daf self.segments = [Segment(self.daf, *t) for t in self.daf.summaries()] ssec = lambda s : s.start_second self.segments.sort(key=ssec) # initialize arrays for spke21 self.G = zeros(MAXTRM) self.REFPOS = zeros(3) self.REFVEL = zeros(3) self.KQ = array([0, 0, 0]) self.FC = zeros(MAXTRM) self.FC[0] = 1.0 self.WC = zeros(MAXTRM - 1) self.W = zeros(MAXTRM + 2) # initialize for compute_type21 self.mda_record_exist = False self.current_segment_exist = False @classmethod def open(cls, path): """Open the file at `path` and return an SPK instance. """ return cls(DAF(open(path, 'rb'))) def close(self): """Close this SPK file.""" self.daf.file.close() def __str__(self): daf = self.daf d = lambda b: b.decode('latin-1') lines = (str(segment) for segment in self.segments) return 'File type {0} and format {1} with {2} segments:\n{3}'.format( d(daf.locidw), d(daf.locfmt), len(self.segments), '\n'.join(lines)) def comments(self): return self.daf.comments() def compute_type21(self, center, target, jd1, jd2=0.0): """Compute position and velocity of target from SPK data (data type 21). Inputs: center - SPKID of the coordinate center (0 for Solar System Barycenter, 10 for Sun, etc) target - SPKID of the target jd1, jd2 - Julian date of epoch for computation. (jd1 + jd2) will be used for computation. If you want precise definition of epoch, jd1 should be an integer or a half integer, and jd2 should be a relatively small floating point number. Returns: Position (X, Y, Z) and velocity (XD, YD, ZD) of the target at epoch. Position and velocity are provided as Numpy arrays respectively. """ eval_sec = (jd1 - T0) eval_sec = (eval_sec + jd2) * S_PER_DAY if self.mda_record_exist: if eval_sec >= self.mda_lb and eval_sec < self.mda_ub: result = self.spke21(eval_sec, self.mda_record) return result[0:3], result[3:] self.mda_record, self.mda_lb, self.mda_ub = self.get_MDA_record(eval_sec, target, center) self.mda_record_exists = True result = self.spke21(eval_sec, self.mda_record) return result[0:3], result[3:] def get_MDA_record(self, eval_sec, target, center): """Return a EMDA record for defined epoch. Inputs: eval_sec - epoch for computation, seconds from J2000 target - body ID of the target center - body ID of coordinate center Returns: EMDA record - a Numpy array of DLSIZE floating point numbers Exception: ValueError will be raised when: eval_sed is outside of SPK data target and center are not in SPK data RuntimeError will be raised when: invalid data type of SPK data """ # chech last segment can be used if self.current_segment_exist: if eval_sec >= self.current_segment.start_second \ and eval_sec < self.current_segment.end_second \ and target == self.current_segment.target \ and center == self.current_segment.center: return self.current_segment.get_MDA_record(eval_sec) # select segments with matched 'target' and 'center' matched = [] for segment in self.segments: if segment.target == target and segment.center == center: matched.append(segment) if len(matched) == 0: raise ValueError('Invalid Target and/or Center') if eval_sec < matched[0].start_second or eval_sec >= matched[-1].end_second: raise ValueError('Invalid Time to evaluate') # selet a segment based on eval_sec found = False for segment in matched: if eval_sec < segment.end_second: found = True self.current_segment = segment break if not found: self.current_segment = matched[-1] self.current_segment_exist = True # get the MDA record from selected segment if self.current_segment.data_type != 21: raise RuntimeError('Invalid data. Data Type must be 21') return self.current_segment.get_MDA_record(eval_sec) # left this module only 2018/10/12 def spke21(self, ET, RECORD): """Compute position and velocity from a Modified Difference Array record Inputs: ET: Epoch time to evaluate position and velocity (seconds since J2000) RECORD: A record of Extended Modified Difference Array Returns: STATE STATE: A numpy array which contains position and velocity """ # This method was translated from FORTRAN source code ‘spke21.f’ of SPICE # Toolkit and modified by Shushi Uetsuki. # # SPICE Toolkit for FORTRAN : http://naif.jpl.nasa.gov/naif/toolkit_FORTRAN.html # SPK Required Reading : http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/spk.html # # Unfortunately, I found some discrepancies between FORTRAN source code # and actual data contained in SPK files. So, I tried to compose a # method that compute positions and velocities correctly by referencing # code of spktype01. # Following comments start with #C were copied from original FORTRAN code. #C$ Abstract #C #C Evaluate a single SPK data record from a segment of type 21 #C (Extended Difference Lines). #C #C$ Disclaimer #C #C THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE #C CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. #C GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE #C PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" #C TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY #C WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A #C PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC #C SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE #C SOFTWARE AND RELATED MATERIALS, HOWEVER USED. #C #C IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA #C BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT #C LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, #C INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, #C REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE #C REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. #C #C RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF #C THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY #C CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE #C ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. #C #C$ Required_Reading #C #C SPK #C TIME #C #C$ Keywords #C #C EPHEMERIS #C #C$ Declarations STATE = zeros(6) #C$ Brief_I/O #C #C Variable I/O Description #C -------- --- -------------------------------------------------- #C ET I Evaluation epoch. #C RECORD I Data record. #C STATE O State (position and velocity). #C MAXTRM P Maximum number of terms per difference table #C component. #C #C$ Detailed_Input #C #C ET is an epoch at which a state vector is to be #C computed. The epoch is represented as seconds past #C J2000 TDB. #C #C RECORD is a data record which, when evaluated at epoch ET, #C will give the state (position and velocity) of an #C ephemeris object, relative to its center of motion, #C in an inertial reference frame. #C #C The contents of RECORD are as follows: #C #C RECORD(1): The difference table size per #C Cartesian component. Call this #C size MAXDIM; then the difference #C line (MDA) size DLSIZE is #C #C ( 4 * MAXDIM ) + 11 #C #C RECORD(2) #C ... #C RECORD(1+DLSIZE): An extended difference line. #C The contents are: #C #C Dimension Description #C --------- ---------------------------------- #C 1 Reference epoch of difference line #C MAXDIM Stepsize function vector #C 1 Reference position vector, x #C 1 Reference velocity vector, x #C 1 Reference position vector, y #C 1 Reference velocity vector, y #C 1 Reference position vector, z #C 1 Reference velocity vector, z #C MAXDIM,3 Modified divided difference #C arrays (MDAs) #C 1 Maximum integration order plus 1 #C 3 Integration order array #C #C$ Detailed_Output #C #C STATE is the state resulting from evaluation of the input #C record at ET. Units are km and km/sec. #C #C$ Parameters #C #C MAXTRM is the maximum number of terms allowed in #C each component of the difference table #C contained in the input argument RECORD. #C See the INCLUDE file spk21.inc for the value #C of MAXTRM. #C #C$ Exceptions #C #C 1) If the maximum table size of the input record exceeds #C MAXTRM, the error SPICE(DIFFLINETOOLARGE) is signaled. #C #C$ Files #C #C None. #C #C$ Particulars #C #C The exact format and structure of type 21 (difference lines) #C segments are described in the SPK Required Reading file. #C #C SPKE21 is a modified version of SPKE01. The routine has been #C generalized to support variable size difference lines. #C #C$ Examples #C #C None. #C #C$ Restrictions #C #C Unknown. #C #C$ Literature_References #C #C NAIF Document 168.0, "S- and P- Kernel (SPK) Specification and #C User's Guide" #C #C$ Author_and_Institution #C #C N.J. Bachman (JPL) #C F.T. Krogh (JPL) #C W.L. Taber (JPL) #C I.M. Underwood (JPL) #C #C$ Version #C #C- SPICELIB Version 1.0.0, 03-FEB-2014 (NJB) (FTK) (WLT) (IMU) #C #C-& # #C$ Index_Entries #C #C evaluate type_21 spk segment #C #C-& #C #C The first element of the input record is the dimension #C of the difference table MAXDIM. #C # The FORTRAN source code indicates that RECORD[0] contains MAXDIM, but actual # data record does not contain it. MAXDIM is contained in each segment. MAXDIM = self.current_segment.MAXDIM if MAXDIM > MAXTRM: mes = ('SPKE21 \nThe input record has a maximum table dimension ' + 'of {0}, while the maximum supported by this routine is {1}. ' + 'It is possible that this problem is due to your software ' + 'beeing out of date.').format(MAXDIM, MAXTRM) raise RuntimeError(mes) return STATE #C #C Unpack the contents of the MDA array. #C #C Name Dimension Description #C ------ --------- ------------------------------- #C TL 1 Reference epoch of record #C G MAXDIM Stepsize function vector #C REFPOS 3 Reference position vector #C REFVEL 3 Reference velocity vector #C DT MAXDIM,NTE Modified divided difference arrays #C KQMAX1 1 Maximum integration order plus 1 #C KQ NTE Integration order array #C #C For our purposes, NTE is always 3. #C # The FORTRAN source code indicates that RECORD[1] contains TL, but on the # actual data RECORD[0] contains it, and all addresses for following data are # shifted forward by one. self.TL = RECORD[0] self.G = RECORD[1:MAXDIM + 1] #C #C Collect the reference position and velocity. #C self.REFPOS[0] = RECORD[MAXDIM + 1] self.REFVEL[0] = RECORD[MAXDIM + 2] self.REFPOS[1] = RECORD[MAXDIM + 3] self.REFVEL[1] = RECORD[MAXDIM + 4] self.REFPOS[2] = RECORD[MAXDIM + 5] self.REFVEL[2] = RECORD[MAXDIM + 6] #C #C Initializing the difference table is one aspect of this routine #C that's a bit different from SPKE01. Here the first dimension of #C the table in the input record can be smaller than MAXTRM. So, we #C must transfer separately the portions of the table corresponding #C to each component. #C self.DT = reshape(RECORD[MAXDIM + 7:MAXDIM * 4 + 7], (MAXDIM, 3), order='F') self.KQMAX1 = int(RECORD[4 * MAXDIM + 7]) self.KQ[0] = int(RECORD[4 * MAXDIM + 8]) self.KQ[1] = int(RECORD[4 * MAXDIM + 9]) self.KQ[2] = int(RECORD[4 * MAXDIM + 10]) #C #C Next we set up for the computation of the various differences #C self.DELTA = ET - self.TL self.TP = self.DELTA self.MQ2 = self.KQMAX1 - 2 self.KS = self.KQMAX1 - 1 #C #C This is clearly collecting some kind of coefficients. #C The problem is that we have no idea what they are... #C #C The G coefficients are supposed to be some kind of step size #C vector. #C #C TP starts out as the delta t between the request time and the #C difference line's reference epoch. We then change it from DELTA #C by the components of the stepsize vector G. #C for J in range(1, self.MQ2 + 1): #C #C Make sure we're not about to attempt division by zero. #C if self.G[J-1] == 0.0: mes = ('SPKE21\nA value of zero was found at index {0} ' + 'of the step size vector.').format(J) raise RuntimeError(mes) return STATE self.FC[J] = self.TP / self.G[J-1] self.WC[J-1] = self.DELTA / self.G[J-1] self.TP = self.DELTA + self.G[J-1] #C #C Collect KQMAX1 reciprocals. #C for J in range(1, self.KQMAX1 + 1): self.W[J-1] = 1.0 / float(J) #C #C Compute the W(K) terms needed for the position interpolation #C (Note, it is assumed throughout this routine that KS, which #C starts out as KQMAX1-1 (the ``maximum integration'') #C is at least 2. #C self.JX = 0 self.KS1 = self.KS - 1 while self.KS >= 2: self.JX = self.JX + 1 for J in range(1, self.JX + 1): self.W[J+self.KS-1] = self.FC[J] * self.W[J+self.KS1-1] - self.WC[J-1] * self.W[J+self.KS-1] self.KS = self.KS1 self.KS1 = self.KS1 - 1 #C #C Perform position interpolation: (Note that KS = 1 right now. #C We don't know much more than that.) #C for I in range(1, 3 + 1): self.KQQ = self.KQ[I-1] self.SUM = 0.0 for J in range(self.KQQ, 0, -1): self.SUM = self.SUM + self.DT[J-1, I-1] * self.W[J+self.KS-1] STATE[I-1] = self.REFPOS[I-1] + self.DELTA * (self.REFVEL[I-1] + self.DELTA * self.SUM) #C #C Again we need to compute the W(K) coefficients that are #C going to be used in the velocity interpolation. #C (Note, at this point, KS = 1, KS1 = 0.) #C for J in range(1, self.JX + 1): self.W[J+self.KS-1] = self.FC[J] * self.W[J+self.KS1-1] - self.WC[J-1] * self.W[J+self.KS-1] self.KS = self.KS - 1 #C #C Perform velocity interpolation: #C for I in range(1, 3 + 1): self.KQQ = self.KQ[I-1] self.SUM = 0.0 for J in range(self.KQQ, 0, -1): self.SUM = self.SUM + self.DT[J-1, I-1] * self.W[J+self.KS-1] STATE[I+3-1] = self.REFVEL[I-1] + self.DELTA * self.SUM return STATE class Segment(object): """A single segment of a SPK file. There are several items of information about each segment that are loaded from the underlying SPK file, and made available as object attributes: segment.source - official ephemeris name, like 'DE-0430LE-0430' segment.start_second - initial epoch, as seconds from J2000 segment.end_second - final epoch, as seconds from J2000 segment.start_jd - start_second, converted to a Julian Date segment.end_jd - end_second, converted to a Julian Date segment.center - integer center identifier segment.target - integer target identifier segment.frame - integer frame identifier segment.data_type - integer data type identifier segment.start_i - index where segment starts segment.end_i - index where segment ends """ def __init__(self, daf, source, descriptor): self.daf = daf self.source = source (self.start_second, self.end_second, self.target, self.center, self.frame, self.data_type, self.start_i, self.end_i) = descriptor self.start_jd = jd(self.start_second) self.end_jd = jd(self.end_second) # 'SPK Required Reading' indicates that the penultimate element of the segment # is the difference line size (DLSIZE), but actual data contains there a MAXDIM. self.MAXDIM = int(self.daf.map_array(self.end_i - 1, self.end_i - 1)) self.DLSIZE = 4 * self.MAXDIM + 11 def __str__(self): return self.describe(verbose=False) def describe(self, verbose=True): """Return a textual description of the segment. """ center = titlecase(target_names.get(self.center, 'Unknown center')) target = titlecase(target_names.get(self.target, 'Unknown target')) text = ('{0.start_jd:.2f}..{0.end_jd:.2f} {1} ({0.center})' ' -> {2} ({0.target})' ' data_type={0.data_type}'.format(self, center, target)) if verbose: text += ('\n frame={0.frame} data_type={0.data_type} source={1}' .format(self, self.source.decode('ascii'))) return text def get_MDA_record(self, time_sec): """Return a Modified Difference Array(MDA) record for the time to evaluate with its effective time boundaries (lower and upper). Inputs: time_sec - epoch for computation, seconds from J2000 Returns: mda_record, lower_boundary, upper_boundary mda_record: A Modified Difference Array record lower_boundary: lower boundary of the record, seconds since J2000 upper_boundary: upper boundary of the record, seconds since J2000 """ # Number of records in this segment entry_count = int(self.daf.map_array(self.end_i, self.end_i)) # Number of entries in epoch directory epoch_dir_count = entry_count // 100 # serch target epoch in epoch directory to narrow serching aria if epoch_dir_count >= 1: epoch_dir = self.daf.map_array(self.end_i - epoch_dir_count - 1, self.end_i - 2) found = False for i in range(1, epoch_dir_count + 1): if epoch_dir[i-1] > time_sec: found = True break if found: serch_last_index = i * 100 serch_start_index = (i - 1) * 100 + 1 else: serch_last_index = entry_count serch_start_index = epoch_dir_count * 100 + 1 else: serch_last_index = entry_count serch_start_index = 1 # epoch_table contains epochs for all records in this segment epoch_table = self.daf.map_array(self.start_i + (entry_count * self.DLSIZE), self.start_i + (entry_count * self.DLSIZE) + entry_count - 1) # serch target epoch in epoch_table found = False for i in range(serch_start_index, serch_last_index + 1): if epoch_table[i-1] > time_sec: found = True break if not found: i = serch_last_index record_index = i upper_boundary = epoch_table[i-1] if i != 1: lower_boundary = epoch_table[i-2] else: lower_boundary = self.start_second mda_record = self.daf.map_array(self.start_i + ((record_index - 1) * self.DLSIZE), self.start_i + (record_index * self.DLSIZE) - 1) # mda_record : one record of MDA # lower_boundary : lower boundary of epoch in this MDA record # upper_boundary : upper boundary of epoch in this MDA record return mda_record, lower_boundary, upper_boundary def titlecase(name): """Title-case target `name` if it looks safe to do so. """ return name if name.startswith(('1', 'C/', 'DSS-')) else name.title()
36.712557
108
0.588536
from numpy import array, zeros, reshape from jplephem.daf import DAF from jplephem.names import target_names T0 = 2451545.0 S_PER_DAY = 86400.0 MAXTRM = 25 def jd(seconds): return T0 + seconds / S_PER_DAY class SPKType21(object): def __init__(self, daf): self.daf = daf self.segments = [Segment(self.daf, *t) for t in self.daf.summaries()] ssec = lambda s : s.start_second self.segments.sort(key=ssec) self.G = zeros(MAXTRM) self.REFPOS = zeros(3) self.REFVEL = zeros(3) self.KQ = array([0, 0, 0]) self.FC = zeros(MAXTRM) self.FC[0] = 1.0 self.WC = zeros(MAXTRM - 1) self.W = zeros(MAXTRM + 2) self.mda_record_exist = False self.current_segment_exist = False @classmethod def open(cls, path): return cls(DAF(open(path, 'rb'))) def close(self): self.daf.file.close() def __str__(self): daf = self.daf d = lambda b: b.decode('latin-1') lines = (str(segment) for segment in self.segments) return 'File type {0} and format {1} with {2} segments:\n{3}'.format( d(daf.locidw), d(daf.locfmt), len(self.segments), '\n'.join(lines)) def comments(self): return self.daf.comments() def compute_type21(self, center, target, jd1, jd2=0.0): eval_sec = (jd1 - T0) eval_sec = (eval_sec + jd2) * S_PER_DAY if self.mda_record_exist: if eval_sec >= self.mda_lb and eval_sec < self.mda_ub: result = self.spke21(eval_sec, self.mda_record) return result[0:3], result[3:] self.mda_record, self.mda_lb, self.mda_ub = self.get_MDA_record(eval_sec, target, center) self.mda_record_exists = True result = self.spke21(eval_sec, self.mda_record) return result[0:3], result[3:] def get_MDA_record(self, eval_sec, target, center): if self.current_segment_exist: if eval_sec >= self.current_segment.start_second \ and eval_sec < self.current_segment.end_second \ and target == self.current_segment.target \ and center == self.current_segment.center: return self.current_segment.get_MDA_record(eval_sec) matched = [] for segment in self.segments: if segment.target == target and segment.center == center: matched.append(segment) if len(matched) == 0: raise ValueError('Invalid Target and/or Center') if eval_sec < matched[0].start_second or eval_sec >= matched[-1].end_second: raise ValueError('Invalid Time to evaluate') found = False for segment in matched: if eval_sec < segment.end_second: found = True self.current_segment = segment break if not found: self.current_segment = matched[-1] self.current_segment_exist = True if self.current_segment.data_type != 21: raise RuntimeError('Invalid data. Data Type must be 21') return self.current_segment.get_MDA_record(eval_sec) def spke21(self, ET, RECORD): STATE = zeros(6) #C User's Guide" #C #C$ Author_and_Institution #C #C N.J. Bachman (JPL) #C F.T. Krogh (JPL) #C W.L. Taber (JPL) #C I.M. Underwood (JPL) #C #C$ Version #C #C- SPICELIB Version 1.0.0, 03-FEB-2014 (NJB) (FTK) (WLT) (IMU) #C #C-& # #C$ Index_Entries #C #C evaluate type_21 spk segment #C #C-& #C #C The first element of the input record is the dimension #C of the difference table MAXDIM. #C # The FORTRAN source code indicates that RECORD[0] contains MAXDIM, but actual # data record does not contain it. MAXDIM is contained in each segment. MAXDIM = self.current_segment.MAXDIM if MAXDIM > MAXTRM: mes = ('SPKE21 \nThe input record has a maximum table dimension ' + 'of {0}, while the maximum supported by this routine is {1}. ' + 'It is possible that this problem is due to your software ' + 'beeing out of date.').format(MAXDIM, MAXTRM) raise RuntimeError(mes) return STATE #C #C Unpack the contents of the MDA array. #C #C Name Dimension Description #C ------ --------- ------------------------------- #C TL 1 Reference epoch of record #C G MAXDIM Stepsize function vector #C REFPOS 3 Reference position vector #C REFVEL 3 Reference velocity vector #C DT MAXDIM,NTE Modified divided difference arrays #C KQMAX1 1 Maximum integration order plus 1 #C KQ NTE Integration order array #C #C For our purposes, NTE is always 3. #C # The FORTRAN source code indicates that RECORD[1] contains TL, but on the # actual data RECORD[0] contains it, and all addresses for following data are # shifted forward by one. self.TL = RECORD[0] self.G = RECORD[1:MAXDIM + 1] #C #C Collect the reference position and velocity. #C self.REFPOS[0] = RECORD[MAXDIM + 1] self.REFVEL[0] = RECORD[MAXDIM + 2] self.REFPOS[1] = RECORD[MAXDIM + 3] self.REFVEL[1] = RECORD[MAXDIM + 4] self.REFPOS[2] = RECORD[MAXDIM + 5] self.REFVEL[2] = RECORD[MAXDIM + 6] #C #C Initializing the difference table is one aspect of this routine #C that's a bit different from SPKE01. Here the first dimension of self.DT = reshape(RECORD[MAXDIM + 7:MAXDIM * 4 + 7], (MAXDIM, 3), order='F') self.KQMAX1 = int(RECORD[4 * MAXDIM + 7]) self.KQ[0] = int(RECORD[4 * MAXDIM + 8]) self.KQ[1] = int(RECORD[4 * MAXDIM + 9]) self.KQ[2] = int(RECORD[4 * MAXDIM + 10]) self.DELTA = ET - self.TL self.TP = self.DELTA self.MQ2 = self.KQMAX1 - 2 self.KS = self.KQMAX1 - 1 #C by the components of the stepsize vector G. #C for J in range(1, self.MQ2 + 1): #C #C Make sure we're not about to attempt division by zero. if self.G[J-1] == 0.0: mes = ('SPKE21\nA value of zero was found at index {0} ' + 'of the step size vector.').format(J) raise RuntimeError(mes) return STATE self.FC[J] = self.TP / self.G[J-1] self.WC[J-1] = self.DELTA / self.G[J-1] self.TP = self.DELTA + self.G[J-1] for J in range(1, self.KQMAX1 + 1): self.W[J-1] = 1.0 / float(J) self.JX = 0 self.KS1 = self.KS - 1 while self.KS >= 2: self.JX = self.JX + 1 for J in range(1, self.JX + 1): self.W[J+self.KS-1] = self.FC[J] * self.W[J+self.KS1-1] - self.WC[J-1] * self.W[J+self.KS-1] self.KS = self.KS1 self.KS1 = self.KS1 - 1 #C for I in range(1, 3 + 1): self.KQQ = self.KQ[I-1] self.SUM = 0.0 for J in range(self.KQQ, 0, -1): self.SUM = self.SUM + self.DT[J-1, I-1] * self.W[J+self.KS-1] STATE[I-1] = self.REFPOS[I-1] + self.DELTA * (self.REFVEL[I-1] + self.DELTA * self.SUM) #C #C Again we need to compute the W(K) coefficients that are #C going to be used in the velocity interpolation. #C (Note, at this point, KS = 1, KS1 = 0.) #C for J in range(1, self.JX + 1): self.W[J+self.KS-1] = self.FC[J] * self.W[J+self.KS1-1] - self.WC[J-1] * self.W[J+self.KS-1] self.KS = self.KS - 1 #C #C Perform velocity interpolation: #C for I in range(1, 3 + 1): self.KQQ = self.KQ[I-1] self.SUM = 0.0 for J in range(self.KQQ, 0, -1): self.SUM = self.SUM + self.DT[J-1, I-1] * self.W[J+self.KS-1] STATE[I+3-1] = self.REFVEL[I-1] + self.DELTA * self.SUM return STATE class Segment(object): def __init__(self, daf, source, descriptor): self.daf = daf self.source = source (self.start_second, self.end_second, self.target, self.center, self.frame, self.data_type, self.start_i, self.end_i) = descriptor self.start_jd = jd(self.start_second) self.end_jd = jd(self.end_second) # 'SPK Required Reading' indicates that the penultimate element of the segment # is the difference line size (DLSIZE), but actual data contains there a MAXDIM. self.MAXDIM = int(self.daf.map_array(self.end_i - 1, self.end_i - 1)) self.DLSIZE = 4 * self.MAXDIM + 11 def __str__(self): return self.describe(verbose=False) def describe(self, verbose=True): center = titlecase(target_names.get(self.center, 'Unknown center')) target = titlecase(target_names.get(self.target, 'Unknown target')) text = ('{0.start_jd:.2f}..{0.end_jd:.2f} {1} ({0.center})' ' -> {2} ({0.target})' ' data_type={0.data_type}'.format(self, center, target)) if verbose: text += ('\n frame={0.frame} data_type={0.data_type} source={1}' .format(self, self.source.decode('ascii'))) return text def get_MDA_record(self, time_sec): # Number of records in this segment entry_count = int(self.daf.map_array(self.end_i, self.end_i)) # Number of entries in epoch directory epoch_dir_count = entry_count // 100 # serch target epoch in epoch directory to narrow serching aria if epoch_dir_count >= 1: epoch_dir = self.daf.map_array(self.end_i - epoch_dir_count - 1, self.end_i - 2) found = False for i in range(1, epoch_dir_count + 1): if epoch_dir[i-1] > time_sec: found = True break if found: serch_last_index = i * 100 serch_start_index = (i - 1) * 100 + 1 else: serch_last_index = entry_count serch_start_index = epoch_dir_count * 100 + 1 else: serch_last_index = entry_count serch_start_index = 1 # epoch_table contains epochs for all records in this segment epoch_table = self.daf.map_array(self.start_i + (entry_count * self.DLSIZE), self.start_i + (entry_count * self.DLSIZE) + entry_count - 1) # serch target epoch in epoch_table found = False for i in range(serch_start_index, serch_last_index + 1): if epoch_table[i-1] > time_sec: found = True break if not found: i = serch_last_index record_index = i upper_boundary = epoch_table[i-1] if i != 1: lower_boundary = epoch_table[i-2] else: lower_boundary = self.start_second mda_record = self.daf.map_array(self.start_i + ((record_index - 1) * self.DLSIZE), self.start_i + (record_index * self.DLSIZE) - 1) # mda_record : one record of MDA # lower_boundary : lower boundary of epoch in this MDA record # upper_boundary : upper boundary of epoch in this MDA record return mda_record, lower_boundary, upper_boundary def titlecase(name): return name if name.startswith(('1', 'C/', 'DSS-')) else name.title()
true
true
f72d3177ad5efc5cf08c928ba31c9ec1b2799491
119,007
py
Python
cinder/volume/drivers/ibm/ibm_storage/xiv_proxy.py
yachika-ralhan/cinder
9d4fd16bcd8eca930910798cc519cb5bc5846c59
[ "Apache-2.0" ]
1
2018-10-23T17:00:53.000Z
2018-10-23T17:00:53.000Z
cinder/volume/drivers/ibm/ibm_storage/xiv_proxy.py
vexata/cinder
7b84c0842b685de7ee012acec40fb4064edde5e9
[ "Apache-2.0" ]
null
null
null
cinder/volume/drivers/ibm/ibm_storage/xiv_proxy.py
vexata/cinder
7b84c0842b685de7ee012acec40fb4064edde5e9
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2016 IBM 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. # import datetime import re import six import socket from oslo_log import log as logging from oslo_utils import importutils pyxcli = importutils.try_import("pyxcli") if pyxcli: from pyxcli import client from pyxcli import errors from pyxcli.events import events from pyxcli.mirroring import mirrored_entities from pyxcli import transports from cinder import context from cinder.i18n import _ from cinder.objects import fields from cinder import volume as c_volume import cinder.volume.drivers.ibm.ibm_storage as storage from cinder.volume.drivers.ibm.ibm_storage import certificate from cinder.volume.drivers.ibm.ibm_storage import cryptish from cinder.volume.drivers.ibm.ibm_storage import proxy from cinder.volume.drivers.ibm.ibm_storage import strings from cinder.volume.drivers.ibm.ibm_storage import xiv_replication as repl from cinder.volume import group_types from cinder.volume import qos_specs from cinder.volume import utils from cinder.volume import volume_types OPENSTACK_PRODUCT_NAME = "OpenStack" PERF_CLASS_NAME_PREFIX = "cinder-qos" HOST_BAD_NAME = "HOST_BAD_NAME" VOLUME_IS_MAPPED = "VOLUME_IS_MAPPED" CONNECTIONS_PER_MODULE = 2 MIN_LUNID = 1 MAX_LUNID = 511 SYNC = 'sync' ASYNC = 'async' SYNC_TIMEOUT = 300 SYNCHED_STATES = ['synchronized', 'rpo ok'] PYXCLI_VERSION = '1.1.6' LOG = logging.getLogger(__name__) # performance class strings - used in exceptions PERF_CLASS_ERROR = _("Unable to create or get performance class: %(details)s") PERF_CLASS_ADD_ERROR = _("Unable to add volume to performance class: " "%(details)s") PERF_CLASS_VALUES_ERROR = _("A performance class with the same name but " "different values exists: %(details)s") # setup strings - used in exceptions SETUP_BASE_ERROR = _("Unable to connect to %(title)s: %(details)s") SETUP_INVALID_ADDRESS = _("Unable to connect to the storage system " "at '%(address)s', invalid address.") # create volume strings - used in exceptions CREATE_VOLUME_BASE_ERROR = _("Unable to create volume: %(details)s") # initialize connection strings - used in exceptions CONNECTIVITY_FC_NO_TARGETS = _("Unable to detect FC connection between the " "compute host and the storage, please ensure " "that zoning is set up correctly.") # terminate connection strings - used in logging TERMINATE_CONNECTION_BASE_ERROR = ("Unable to terminate the connection " "for volume '%(volume)s': %(error)s.") TERMINATE_CONNECTION_HOST_ERROR = ("Terminate connection for volume " "'%(volume)s': for volume '%(volume)s': " "%(host)s %(error)s.") # delete volume strings - used in logging DELETE_VOLUME_BASE_ERROR = ("Unable to delete volume '%(volume)s': " "%(error)s.") # manage volume strings - used in exceptions MANAGE_VOLUME_BASE_ERROR = _("Unable to manage the volume '%(volume)s': " "%(error)s.") INCOMPATIBLE_PYXCLI = _('Incompatible pyxcli found. Mininum: %(required)s ' 'Found: %(found)s') class XIVProxy(proxy.IBMStorageProxy): """Proxy between the Cinder Volume and Spectrum Accelerate Storage. Supports IBM XIV, Spectrum Accelerate, A9000, A9000R Version: 2.3.0 Required pyxcli version: 1.1.6 .. code:: text 2.0 - First open source driver version 2.1.0 - Support Consistency groups through Generic volume groups - Support XIV/A9000 Volume independent QoS - Support groups replication 2.3.0 - Support Report backend state """ def __init__(self, storage_info, logger, exception, driver=None, active_backend_id=None, host=None): """Initialize Proxy.""" if not active_backend_id: active_backend_id = strings.PRIMARY_BACKEND_ID proxy.IBMStorageProxy.__init__( self, storage_info, logger, exception, driver, active_backend_id) LOG.info("__init__: storage_info: %(keys)s", {'keys': self.storage_info}) if active_backend_id: LOG.info("__init__: active_backend_id: %(id)s", {'id': active_backend_id}) self.ibm_storage_cli = None self.meta['ibm_storage_portal'] = None self.meta['ibm_storage_iqn'] = None self.ibm_storage_remote_cli = None self.meta['ibm_storage_fc_targets'] = [] self.meta['storage_version'] = None self.system_id = None @proxy._trace_time def setup(self, context): msg = '' if pyxcli: if pyxcli.version < PYXCLI_VERSION: msg = (INCOMPATIBLE_PYXCLI % {'required': PYXCLI_VERSION, 'found': pyxcli.version }) else: msg = (SETUP_BASE_ERROR % {'title': strings.TITLE, 'details': "IBM Python XCLI Client (pyxcli) not found" }) if msg != '': LOG.error(msg) raise self._get_exception()(msg) """Connect ssl client.""" LOG.info("Setting up connection to %(title)s...\n" "Active backend_id: '%(id)s'.", {'title': strings.TITLE, 'id': self.active_backend_id}) self.ibm_storage_cli = self._init_xcli(self.active_backend_id) if self._get_connection_type() == storage.XIV_CONNECTION_TYPE_ISCSI: self.meta['ibm_storage_iqn'] = ( self._call_xiv_xcli("config_get"). as_dict('name')['iscsi_name'].value) portals = storage.get_online_iscsi_ports(self.ibm_storage_cli) if len(portals) == 0: msg = (SETUP_BASE_ERROR, {'title': strings.TITLE, 'details': "No iSCSI portals available on the Storage." }) raise self._get_exception()( _("%(prefix)s %(portals)s") % {'prefix': storage.XIV_LOG_PREFIX, 'portals': msg}) self.meta['ibm_storage_portal'] = "%s:3260" % portals[:1][0] remote_id = self._get_secondary_backend_id() if remote_id: self.ibm_storage_remote_cli = self._init_xcli(remote_id) self._event_service_start() self._get_pool() LOG.info("IBM Storage %(common_ver)s " "xiv_proxy %(proxy_ver)s. ", {'common_ver': self.full_version, 'proxy_ver': self.full_version}) self._update_system_id() if remote_id: self._update_active_schedule_objects() self._update_remote_schedule_objects() LOG.info("Connection to the IBM storage " "system established successfully.") @proxy._trace_time def _update_active_schedule_objects(self): """Set schedule objects on active backend. The value 00:20:00 is covered in XIV by a pre-defined object named min_interval. """ schedules = self._call_xiv_xcli("schedule_list").as_dict('name') for rate in repl.Replication.async_rates: if rate.schedule == '00:00:20': continue name = rate.schedule_name schedule = schedules.get(name, None) if schedule: LOG.debug('Exists on local backend %(sch)s', {'sch': name}) interval = schedule.get('interval', '') if interval != rate.schedule: msg = (_("Schedule %(sch)s exists with incorrect " "value %(int)s") % {'sch': name, 'int': interval}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) else: LOG.debug('create %(sch)s', {'sch': name}) try: self._call_xiv_xcli("schedule_create", schedule=name, type='interval', interval=rate.schedule) except errors.XCLIError: msg = (_("Setting up Async mirroring failed, " "schedule %(sch)s is not supported on system: " " %(id)s.") % {'sch': name, 'id': self.system_id}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) @proxy._trace_time def _update_remote_schedule_objects(self): """Set schedule objects on remote backend. The value 00:20:00 is covered in XIV by a pre-defined object named min_interval. """ schedules = self._call_remote_xiv_xcli("schedule_list").as_dict('name') for rate in repl.Replication.async_rates: if rate.schedule == '00:00:20': continue name = rate.schedule_name if schedules.get(name, None): LOG.debug('Exists on remote backend %(sch)s', {'sch': name}) interval = schedules.get(name, None)['interval'] if interval != rate.schedule: msg = (_("Schedule %(sch)s exists with incorrect " "value %(int)s") % {'sch': name, 'int': interval}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) else: try: self._call_remote_xiv_xcli("schedule_create", schedule=name, type='interval', interval=rate.schedule) except errors.XCLIError: msg = (_("Setting up Async mirroring failed, " "schedule %(sch)s is not supported on system: " " %(id)s.") % {'sch': name, 'id': self.system_id}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) def _get_extra_specs(self, type_id): """get extra specs to match the type_id type_id can derive from volume or from consistency_group """ if type_id is None: return {} return c_volume.volume_types.get_volume_type_extra_specs(type_id) def _update_system_id(self): if self.system_id: return local_ibm_storage_cli = self._init_xcli(strings.PRIMARY_BACKEND_ID) if not local_ibm_storage_cli: LOG.error('Failed to connect to main backend. ' 'Cannot retrieve main backend system_id') return system_id = local_ibm_storage_cli.cmd.config_get().as_dict( 'name')['system_id'].value LOG.debug('system_id: %(id)s', {'id': system_id}) self.system_id = system_id @proxy._trace_time def _get_qos_specs(self, type_id): """Gets the qos specs from cinder.""" ctxt = context.get_admin_context() volume_type = volume_types.get_volume_type(ctxt, type_id) if not volume_type: return None qos_specs_id = volume_type.get('qos_specs_id', None) if qos_specs_id: return qos_specs.get_qos_specs( ctxt, qos_specs_id).get('specs', None) return None @proxy._trace_time def _qos_create_kwargs_for_xcli(self, specs): args = {} for key in specs: if key == 'bw': args['max_bw_rate'] = specs[key] if key == 'iops': args['max_io_rate'] = specs[key] return args def _qos_remove_vol(self, volume): try: self._call_xiv_xcli("perf_class_remove_vol", vol=volume['name']) except errors.VolumeNotConnectedToPerfClassError as e: details = self._get_code_and_status_or_message(e) LOG.debug(details) return True except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg_data = (_("Unable to add volume to performance " "class: %(details)s") % {'details': details}) LOG.error(msg_data) raise self.meta['exception'].VolumeBackendAPIException( data=msg_data) return True def _qos_add_vol(self, volume, perf_class_name): try: self._call_xiv_xcli("perf_class_add_vol", vol=volume['name'], perf_class=perf_class_name) except errors.VolumeAlreadyInPerfClassError as e: details = self._get_code_and_status_or_message(e) LOG.debug(details) return True except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = PERF_CLASS_ADD_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) return True def _check_perf_class_on_backend(self, specs): """Checking if class exists on backend. if not - create it.""" perf_class_name = PERF_CLASS_NAME_PREFIX if specs is None or specs == {}: return '' for key, value in sorted(specs.items()): perf_class_name += '_' + key + '_' + value try: classes_list = self._call_xiv_xcli("perf_class_list", perf_class=perf_class_name ).as_list # list is not empty, check if class has the right values for perf_class in classes_list: if (not perf_class.get('max_iops', None) == specs.get('iops', '0') or not perf_class.get('max_bw', None) == specs.get('bw', '0')): raise self.meta['exception'].VolumeBackendAPIException( data=PERF_CLASS_VALUES_ERROR % {'details': perf_class_name}) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = PERF_CLASS_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) # class does not exist, create it if not classes_list: self._create_qos_class(perf_class_name, specs) return perf_class_name def _get_type_from_perf_class_name(self, perf_class_name): _type = re.findall('type_(independent|shared)', perf_class_name) return _type[0] if _type else None def _create_qos_class(self, perf_class_name, specs): """Create the qos class on the backend.""" try: # check if we have a shared (default) perf class # or an independent perf class _type = self._get_type_from_perf_class_name(perf_class_name) if _type: self._call_xiv_xcli("perf_class_create", perf_class=perf_class_name, type=_type) else: self._call_xiv_xcli("perf_class_create", perf_class=perf_class_name) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = PERF_CLASS_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) try: args = self._qos_create_kwargs_for_xcli(specs) self._call_xiv_xcli("perf_class_set_rate", perf_class=perf_class_name, **args) return perf_class_name except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) # attempt to clean up self._call_xiv_xcli("perf_class_delete", perf_class=perf_class_name) msg = PERF_CLASS_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) def _qos_specs_from_volume(self, volume): """Returns qos_specs of volume. checks if there is a type on the volume if so, checks if it has been associated with a qos class returns the name of that class """ type_id = volume.get('volume_type_id', None) if not type_id: return None return self._get_qos_specs(type_id) def _get_replication_info(self, specs): info, msg = repl.Replication.extract_replication_info_from_specs(specs) if not info: LOG.error(msg) raise self._get_exception()(message=msg) return info @proxy._trace_time def _create_volume(self, volume): """Internal implementation to create a volume.""" size = storage.gigabytes_to_blocks(float(volume['size'])) pool = self._get_backend_pool() try: self._call_xiv_xcli( "vol_create", vol=volume['name'], size_blocks=size, pool=pool) except errors.SystemOutOfSpaceError: msg = _("Unable to create volume: System is out of space.") LOG.error(msg) raise self._get_exception()(msg) except errors.PoolOutOfSpaceError: msg = (_("Unable to create volume: pool '%(pool)s' is " "out of space.") % {'pool': pool}) LOG.error(msg) raise self._get_exception()(msg) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = (CREATE_VOLUME_BASE_ERROR, {'details': details}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) @proxy._trace_time def create_volume(self, volume): """Creates a volume.""" # read replication information specs = self._get_extra_specs(volume.get('volume_type_id', None)) replication_info = self._get_replication_info(specs) self._create_volume(volume) return self.handle_created_vol_properties(replication_info, volume) def handle_created_vol_properties(self, replication_info, volume): volume_update = {} LOG.debug('checking replication_info %(rep)s', {'rep': replication_info}) volume_update['replication_status'] = 'disabled' cg = volume.group and utils.is_group_a_cg_snapshot_type(volume.group) if replication_info['enabled']: try: repl.VolumeReplication(self).create_replication( volume.name, replication_info) except Exception as e: details = self._get_code_and_status_or_message(e) msg = ('Failed create_replication for ' 'volume %(vol)s: %(err)s', {'vol': volume['name'], 'err': details}) LOG.error(msg) if cg: cg_name = self._cg_name_from_volume(volume) self._silent_delete_volume_from_cg(volume, cg_name) self._silent_delete_volume(volume=volume) raise volume_update['replication_status'] = 'enabled' if cg: if volume.group.is_replicated: # for replicated Consistency Group: # The Volume must be mirrored, and its mirroring settings must # be identical to those of the Consistency Group: # mirroring type (e.g., synchronous), # mirroring status, mirroring target(backend) group_specs = group_types.get_group_type_specs( volume.group.group_type_id) group_rep_info = self._get_replication_info(group_specs) msg = None if volume_update['replication_status'] != 'enabled': msg = ('Cannot add non-replicated volume into' ' replicated group') elif replication_info['mode'] != group_rep_info['mode']: msg = ('Volume replication type and Group replication type' ' should be the same') elif volume.host != volume.group.host: msg = 'Cannot add volume to Group on different host' elif volume.group['replication_status'] == 'enabled': # if group is mirrored and enabled, compare state. group_name = self._cg_name_from_group(volume.group) me = mirrored_entities.MirroredEntities( self.ibm_storage_cli) me_objs = me.get_mirror_resources_by_name_map() vol_obj = me_objs['volumes'][volume.name] vol_sync_state = vol_obj['sync_state'] cg_sync_state = me_objs['cgs'][group_name]['sync_state'] if (vol_sync_state != 'Synchronized' or cg_sync_state != 'Synchronized'): msg = ('Cannot add volume to Group. Both volume and ' 'group should have sync_state = Synchronized') if msg: LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) try: cg_name = self._cg_name_from_volume(volume) self._call_xiv_xcli( "cg_add_vol", vol=volume['name'], cg=cg_name) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) self._silent_delete_volume(volume=volume) msg = (CREATE_VOLUME_BASE_ERROR, {'details': details}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) perf_class_name = None specs = self._qos_specs_from_volume(volume) if specs: try: perf_class_name = self._check_perf_class_on_backend(specs) if perf_class_name: self._call_xiv_xcli("perf_class_add_vol", vol=volume['name'], perf_class=perf_class_name) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) if cg: cg_name = self._cg_name_from_volume(volume) self._silent_delete_volume_from_cg(volume, cg_name) self._silent_delete_volume(volume=volume) msg = PERF_CLASS_ADD_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) return volume_update @proxy._trace_time def enable_replication(self, context, group, volumes): """Enable cg replication""" # fetch replication info group_specs = group_types.get_group_type_specs(group.group_type_id) if not group_specs: msg = 'No group specs inside group type' LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) # Add this field to adjust it to generic replication (for volumes) replication_info = self._get_replication_info(group_specs) if utils.is_group_a_cg_snapshot_type(group): # take every vol out of cg - we can't mirror the cg otherwise. if volumes: self._update_consistencygroup(context, group, remove_volumes=volumes) for volume in volumes: enabled_status = fields.ReplicationStatus.ENABLED if volume['replication_status'] != enabled_status: repl.VolumeReplication(self).create_replication( volume.name, replication_info) # mirror entire group group_name = self._cg_name_from_group(group) try: self._create_consistencygroup_on_remote(context, group_name) except errors.CgNameExistsError: LOG.debug("CG name %(cg)s exists, no need to open it on " "secondary backend.", {'cg': group_name}) repl.GroupReplication(self).create_replication(group_name, replication_info) updated_volumes = [] if volumes: # add volumes back to cg self._update_consistencygroup(context, group, add_volumes=volumes) for volume in volumes: updated_volumes.append( {'id': volume['id'], 'replication_status': fields.ReplicationStatus.ENABLED}) return ({'replication_status': fields.ReplicationStatus.ENABLED}, updated_volumes) else: # For generic groups we replicate all the volumes updated_volumes = [] for volume in volumes: repl.VolumeReplication(self).create_replication( volume.name, replication_info) # update status for volume in volumes: updated_volumes.append( {'id': volume['id'], 'replication_status': fields.ReplicationStatus.ENABLED}) return ({'replication_status': fields.ReplicationStatus.ENABLED}, updated_volumes) @proxy._trace_time def disable_replication(self, context, group, volumes): """disables CG replication""" group_specs = group_types.get_group_type_specs(group.group_type_id) if not group_specs: msg = 'No group specs inside group type' LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) replication_info = self._get_replication_info(group_specs) updated_volumes = [] if utils.is_group_a_cg_snapshot_type(group): # one call deletes replication for cgs and volumes together. group_name = self._cg_name_from_group(group) repl.GroupReplication(self).delete_replication(group_name, replication_info) for volume in volumes: # xiv locks volumes after deletion of replication. # we need to unlock it for further use. try: self.ibm_storage_cli.cmd.vol_unlock(vol=volume.name) self.ibm_storage_remote_cli.cmd.vol_unlock( vol=volume.name) self.ibm_storage_remote_cli.cmd.cg_remove_vol( vol=volume.name) except errors.VolumeBadNameError: LOG.debug("Failed to delete vol %(vol)s - " "ignoring.", {'vol': volume.name}) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = ('Failed to unlock volumes %(details)s' % {'details': details}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) updated_volumes.append( {'id': volume.id, 'replication_status': fields.ReplicationStatus.DISABLED}) else: # For generic groups we replicate all the volumes updated_volumes = [] for volume in volumes: repl.VolumeReplication(self).delete_replication( volume.name, replication_info) # update status for volume in volumes: try: self.ibm_storage_cli.cmd.vol_unlock(vol=volume.name) self.ibm_storage_remote_cli.cmd.vol_unlock( vol=volume.name) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = (_('Failed to unlock volumes %(details)s'), {'details': details}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) updated_volumes.append( {'id': volume['id'], 'replication_status': fields.ReplicationStatus.DISABLED}) return ({'replication_status': fields.ReplicationStatus.DISABLED}, updated_volumes) def get_secondary_backend_id(self, secondary_backend_id): if secondary_backend_id is None: secondary_backend_id = self._get_target() if secondary_backend_id is None: msg = _("No targets defined. Can't perform failover.") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) return secondary_backend_id def check_for_splitbrain(self, volumes, pool_master, pool_slave): if volumes: # check for split brain situations # check for files that are available on both volumes # and are not in an active mirroring relation split_brain = self._potential_split_brain( self.ibm_storage_cli, self.ibm_storage_remote_cli, volumes, pool_master, pool_slave) if split_brain: # if such a situation exists stop and raise an exception! msg = (_("A potential split brain condition has been found " "with the following volumes: \n'%(volumes)s.'") % {'volumes': split_brain}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) def failover_replication(self, context, group, volumes, secondary_backend_id): """Failover a cg with all it's volumes. if secondery_id is default, cg needs to be failed back. """ volumes_updated = [] goal_status = '' pool_master = None group_updated = {'replication_status': group.replication_status} LOG.info("failover_replication: of cg %(cg)s " "from %(active)s to %(id)s", {'cg': group.get('name'), 'active': self.active_backend_id, 'id': secondary_backend_id}) if secondary_backend_id == strings.PRIMARY_BACKEND_ID: # default as active backend id if self._using_default_backend(): LOG.info("CG has been failed back. " "No need to fail back again.") return group_updated, volumes_updated # get the master pool, not using default id. pool_master = self._get_target_params( self.active_backend_id)['san_clustername'] pool_slave = self.storage_info[storage.FLAG_KEYS['storage_pool']] goal_status = 'enabled' vol_goal_status = 'available' else: if not self._using_default_backend(): LOG.info("cg already failed over.") return group_updated, volumes_updated # using same api as Cheesecake, we need # replciation_device entry. so we use get_targets. secondary_backend_id = self.get_secondary_backend_id( secondary_backend_id) pool_master = self.storage_info[storage.FLAG_KEYS['storage_pool']] pool_slave = self._get_target_params( secondary_backend_id)['san_clustername'] goal_status = fields.ReplicationStatus.FAILED_OVER vol_goal_status = fields.ReplicationStatus.FAILED_OVER # we should have secondary_backend_id by here. self.ibm_storage_remote_cli = self._init_xcli(secondary_backend_id) # check for split brain in mirrored volumes self.check_for_splitbrain(volumes, pool_master, pool_slave) group_specs = group_types.get_group_type_specs(group.group_type_id) if group_specs is None: msg = "No group specs found. Cannot failover." LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) failback = (secondary_backend_id == strings.PRIMARY_BACKEND_ID) result = False details = "" if utils.is_group_a_cg_snapshot_type(group): result, details = repl.GroupReplication(self).failover(group, failback) else: replicated_vols = [] for volume in volumes: result, details = repl.VolumeReplication(self).failover( volume, failback) if not result: break replicated_vols.append(volume) # switch the replicated ones back in case of error if not result: for volume in replicated_vols: result, details = repl.VolumeReplication(self).failover( volume, not failback) if result: status = goal_status group_updated['replication_status'] = status else: status = 'error' updates = {'status': vol_goal_status} if status == 'error': group_updated['replication_extended_status'] = details # if replication on cg was successful, then all of the volumes # have been successfully replicated as well. for volume in volumes: volumes_updated.append({ 'id': volume.id, 'updates': updates }) # replace between active and secondary xcli self._replace_xcli_to_remote_xcli() self.active_backend_id = secondary_backend_id return group_updated, volumes_updated def _replace_xcli_to_remote_xcli(self): temp_ibm_storage_cli = self.ibm_storage_cli self.ibm_storage_cli = self.ibm_storage_remote_cli self.ibm_storage_remote_cli = temp_ibm_storage_cli def _get_replication_target_params(self): LOG.debug('_get_replication_target_params.') if not self.targets: msg = _("No targets available for replication") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) no_of_targets = len(self.targets) if no_of_targets > 1: msg = _("Too many targets configured. Only one is supported") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) LOG.debug('_get_replication_target_params selecting target...') target = self._get_target() if not target: msg = _("No targets available for replication.") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) params = self._get_target_params(target) if not params: msg = (_("Missing target information for target '%(target)s'"), {'target': target}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) return target, params def _delete_volume(self, vol_name): """Deletes a volume on the Storage.""" LOG.debug("_delete_volume: %(volume)s", {'volume': vol_name}) try: self._call_xiv_xcli("vol_delete", vol=vol_name) except errors.VolumeBadNameError: # Don't throw error here, allow the cinder volume manager # to set the volume as deleted if it's not available # on the XIV box LOG.info("Volume '%(volume)s' not found on storage", {'volume': vol_name}) def _silent_delete_volume(self, volume): """Silently delete a volume. silently delete a volume in case of an immediate failure within a function that created it. """ try: self._delete_volume(vol_name=volume['name']) except errors.XCLIError as e: error = self._get_code_and_status_or_message(e) LOG.error(DELETE_VOLUME_BASE_ERROR, {'volume': volume['name'], 'error': error}) def _silent_delete_volume_from_cg(self, volume, cgname): """Silently delete a volume from CG. silently delete a volume in case of an immediate failure within a function that created it. """ try: self._call_xiv_xcli( "cg_remove_vol", vol=volume['name']) except errors.XCLIError as e: LOG.error("Failed removing volume %(vol)s from " "consistency group %(cg)s: %(err)s", {'vol': volume['name'], 'cg': cgname, 'err': self._get_code_and_status_or_message(e)}) self._silent_delete_volume(volume=volume) @proxy._trace_time def delete_volume(self, volume): """Deletes a volume on the Storage machine.""" LOG.debug("delete_volume: %(volume)s", {'volume': volume['name']}) # read replication information specs = self._get_extra_specs(volume.get('volume_type_id', None)) replication_info = self._get_replication_info(specs) if replication_info['enabled']: try: repl.VolumeReplication(self).delete_replication( volume.name, replication_info) except Exception as e: error = self._get_code_and_status_or_message(e) LOG.error(DELETE_VOLUME_BASE_ERROR, {'volume': volume['name'], 'error': error}) # continue even if failed # attempt to delete volume at target target = None try: target, params = self._get_replication_target_params() LOG.info('Target %(target)s: %(params)s', {'target': target, 'params': params}) except Exception as e: LOG.error("Unable to delete replicated volume " "'%(volume)s': %(error)s.", {'error': self._get_code_and_status_or_message(e), 'volume': volume['name']}) if target: try: self._call_remote_xiv_xcli( "vol_delete", vol=volume['name']) except errors.XCLIError as e: LOG.error( "Unable to delete replicated volume " "'%(volume)s': %(error)s.", {'error': self._get_code_and_status_or_message(e), 'volume': volume['name']}) try: self._delete_volume(volume['name']) except errors.XCLIError as e: LOG.error(DELETE_VOLUME_BASE_ERROR, {'volume': volume['name'], 'error': self._get_code_and_status_or_message(e)}) @proxy._trace_time def initialize_connection(self, volume, connector): """Initialize connection to instance. Maps the created volume to the nova volume node, and returns the iSCSI target to be used in the instance """ connection_type = self._get_connection_type() LOG.debug("initialize_connection: %(volume)s %(connector)s" " connection_type: %(connection_type)s", {'volume': volume['name'], 'connector': connector, 'connection_type': connection_type}) # This call does all the work.. fc_targets, host = self._get_host_and_fc_targets( volume, connector) lun_id = self._vol_map_and_get_lun_id( volume, connector, host) meta = { 'driver_volume_type': connection_type, 'data': { 'target_discovered': True, 'target_lun': lun_id, 'volume_id': volume['id'], }, } if connection_type == storage.XIV_CONNECTION_TYPE_ISCSI: meta['data']['target_portal'] = self.meta['ibm_storage_portal'] meta['data']['target_iqn'] = self.meta['ibm_storage_iqn'] meta['data']['provider_location'] = "%s,1 %s %s" % ( self.meta['ibm_storage_portal'], self.meta['ibm_storage_iqn'], lun_id) chap_type = self._get_chap_type() LOG.debug("initialize_connection: %(volume)s." " chap_type:%(chap_type)s", {'volume': volume['name'], 'chap_type': chap_type}) if chap_type == storage.CHAP_ENABLED: chap = self._create_chap(host) meta['data']['auth_method'] = 'CHAP' meta['data']['auth_username'] = chap[0] meta['data']['auth_password'] = chap[1] else: all_storage_wwpns = self._get_fc_targets(None) meta['data']['all_storage_wwpns'] = all_storage_wwpns modules = set() for wwpn in fc_targets: modules.add(wwpn[-2]) meta['data']['recommended_connections'] = ( len(modules) * CONNECTIONS_PER_MODULE) meta['data']['target_wwn'] = fc_targets if fc_targets == []: fc_targets = all_storage_wwpns meta['data']['initiator_target_map'] = ( self._build_initiator_target_map(fc_targets, connector)) LOG.debug(six.text_type(meta)) return meta @proxy._trace_time def terminate_connection(self, volume, connector): """Terminate connection. Unmaps volume. If this is the last connection from the host, undefines the host from the storage. """ LOG.debug("terminate_connection: %(volume)s %(connector)s", {'volume': volume['name'], 'connector': connector}) host = self._get_host(connector) if host is None: LOG.error(TERMINATE_CONNECTION_BASE_ERROR, {'volume': volume['name'], 'error': "Host not found."}) return fc_targets = {} if self._get_connection_type() == storage.XIV_CONNECTION_TYPE_FC: fc_targets = self._get_fc_targets(host) try: self._call_xiv_xcli( "unmap_vol", vol=volume['name'], host=host.get('name')) except errors.VolumeBadNameError: LOG.error(TERMINATE_CONNECTION_BASE_ERROR, {'volume': volume['name'], 'error': "Volume not found."}) except errors.XCLIError as err: details = self._get_code_and_status_or_message(err) LOG.error(TERMINATE_CONNECTION_BASE_ERROR, {'volume': volume['name'], 'error': details}) # check if there are still mapped volumes or we can # remove this host host_mappings = [] try: host_mappings = self._call_xiv_xcli( "mapping_list", host=host.get('name')).as_list if len(host_mappings) == 0: LOG.info("Terminate connection for volume '%(volume)s': " "%(host)s %(info)s.", {'volume': volume['name'], 'host': host.get('name'), 'info': "will be deleted"}) if not self._is_iscsi(): # The following meta data is provided so that zoning can # be cleared meta = { 'driver_volume_type': self._get_connection_type(), 'data': {'volume_id': volume['id'], }, } meta['data']['target_wwn'] = fc_targets meta['data']['initiator_target_map'] = ( self._build_initiator_target_map(fc_targets, connector)) self._call_xiv_xcli("host_delete", host=host.get('name')) if not self._is_iscsi(): return meta return None else: LOG.debug(("Host '%(host)s' has additional mapped " "volumes %(mappings)s"), {'host': host.get('name'), 'mappings': host_mappings}) except errors.HostBadNameError: LOG.error(TERMINATE_CONNECTION_HOST_ERROR, {'volume': volume['name'], 'host': host.get('name'), 'error': "Host not found."}) except errors.XCLIError as err: details = self._get_code_and_status_or_message(err) LOG.error(TERMINATE_CONNECTION_HOST_ERROR, {'volume': volume['name'], 'host': host.get('name'), 'error': details}) def _create_volume_from_snapshot(self, volume, snapshot_name, snapshot_size): """Create volume from snapshot internal implementation. used for regular snapshot and cgsnapshot """ LOG.debug("_create_volume_from_snapshot: %(volume)s from %(name)s", {'volume': volume['name'], 'name': snapshot_name}) # TODO(alonma): Refactor common validation volume_size = float(volume['size']) if volume_size < snapshot_size: error = (_("Volume size (%(vol_size)sGB) cannot be smaller than " "the snapshot size (%(snap_size)sGB)..") % {'vol_size': volume_size, 'snap_size': snapshot_size}) LOG.error(error) raise self._get_exception()(error) self.create_volume(volume) try: self._call_xiv_xcli( "vol_copy", vol_src=snapshot_name, vol_trg=volume['name']) except errors.XCLIError as e: error = (_("Fatal error in copying volume: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) self._silent_delete_volume(volume) raise self._get_exception()(error) # A side effect of vol_copy is the resizing of the destination volume # to the size of the source volume. If the size is different we need # to get it back to the desired size if snapshot_size == volume_size: return size = storage.gigabytes_to_blocks(volume_size) try: self._call_xiv_xcli( "vol_resize", vol=volume['name'], size_blocks=size) except errors.XCLIError as e: error = (_("Fatal error in resize volume: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) self._silent_delete_volume(volume) raise self._get_exception()(error) @proxy._trace_time def create_volume_from_snapshot(self, volume, snapshot): """create volume from snapshot.""" snapshot_size = float(snapshot['volume_size']) self._create_volume_from_snapshot(volume, snapshot.name, snapshot_size) @proxy._trace_time def create_snapshot(self, snapshot): """create snapshot.""" try: self._call_xiv_xcli( "snapshot_create", vol=snapshot['volume_name'], name=snapshot['name']) except errors.XCLIError as e: error = (_("Fatal error in snapshot_create: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) @proxy._trace_time def delete_snapshot(self, snapshot): """delete snapshot.""" try: self._call_xiv_xcli( "snapshot_delete", snapshot=snapshot['name']) except errors.XCLIError as e: error = (_("Fatal error in snapshot_delete: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) @proxy._trace_time def extend_volume(self, volume, new_size): """Resize volume.""" volume_size = float(volume['size']) wanted_size = float(new_size) if wanted_size == volume_size: return shrink = 'yes' if wanted_size < volume_size else 'no' size = storage.gigabytes_to_blocks(wanted_size) try: self._call_xiv_xcli( "vol_resize", vol=volume['name'], size_blocks=size, shrink_volume=shrink) except errors.XCLIError as e: error = (_("Fatal error in vol_resize: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) @proxy._trace_time def migrate_volume(self, context, volume, host): """Migrate volume to another backend. Optimize the migration if the destination is on the same server. If the specified host is another back-end on the same server, and the volume is not attached, we can do the migration locally without going through iSCSI. Storage-assisted migration... """ false_ret = (False, None) if 'location_info' not in host['capabilities']: return false_ret info = host['capabilities']['location_info'] try: dest, dest_host, dest_pool = info.split(':') except ValueError: return false_ret volume_host = volume.host.split('_')[1] if dest != strings.XIV_BACKEND_PREFIX or dest_host != volume_host: return false_ret if volume.attach_status == 'attached': LOG.info("Storage-assisted volume migration: Volume " "%(volume)s is attached", {'volume': volume.id}) try: self._call_xiv_xcli( "vol_move", vol=volume.name, pool=dest_pool) except errors.XCLIError as e: error = (_("Fatal error in vol_move: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) return (True, None) @proxy._trace_time def manage_volume(self, volume, reference): """Brings an existing backend storage object under Cinder management. reference value is passed straight from the get_volume_list helper function. it is up to the driver how this should be interpreted. It should be sufficient to identify a storage object that the driver should somehow associate with the newly-created cinder volume structure. There are two ways to do this: 1. Rename the backend storage object so that it matches the, volume['name'] which is how drivers traditionally map between a cinder volume and the associated backend storage object. 2. Place some metadata on the volume, or somewhere in the backend, that allows other driver requests (e.g. delete, clone, attach, detach...) to locate the backend storage object when required. If the reference doesn't make sense, or doesn't refer to an existing backend storage object, raise a ManageExistingInvalidReference exception. The volume may have a volume_type, and the driver can inspect that and compare against the properties of the referenced backend storage object. If they are incompatible, raise a ManageExistingVolumeTypeMismatch, specifying a reason for the failure. """ existing_volume = reference['source-name'] LOG.debug("manage_volume: %(volume)s", {'volume': existing_volume}) # check that volume exists try: volumes = self._call_xiv_xcli( "vol_list", vol=existing_volume).as_list except errors.XCLIError as e: error = (MANAGE_VOLUME_BASE_ERROR % {'volume': existing_volume, 'error': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) if len(volumes) != 1: error = (MANAGE_VOLUME_BASE_ERROR % {'volume': existing_volume, 'error': 'Volume does not exist'}) LOG.error(error) raise self._get_exception()(error) volume['size'] = float(volumes[0]['size']) # option 1: # rename volume to volume['name'] try: self._call_xiv_xcli( "vol_rename", vol=existing_volume, new_name=volume['name']) except errors.XCLIError as e: error = (MANAGE_VOLUME_BASE_ERROR % {'volume': existing_volume, 'error': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) # option 2: # return volume name as admin metadata # update the admin metadata DB # Need to do the ~same in create data. use the metadata instead of the # volume name return {} @proxy._trace_time def manage_volume_get_size(self, volume, reference): """Return size of volume to be managed by manage_volume. When calculating the size, round up to the next GB. """ existing_volume = reference['source-name'] # check that volume exists try: volumes = self._call_xiv_xcli( "vol_list", vol=existing_volume).as_list except errors.XCLIError as e: error = (_("Fatal error in vol_list: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) if len(volumes) != 1: error = (_("Volume %(volume)s is not available on storage") % {'volume': existing_volume}) LOG.error(error) raise self._get_exception()(error) return float(volumes[0]['size']) @proxy._trace_time def unmanage_volume(self, volume): """Removes the specified volume from Cinder management. Does not delete the underlying backend storage object. """ pass @proxy._trace_time def get_replication_status(self, context, volume): """Return replication status.""" pass def freeze_backend(self, context): """Notify the backend that it's frozen.""" # go over volumes in backend that are replicated and lock them pass def thaw_backend(self, context): """Notify the backend that it's unfrozen/thawed.""" # go over volumes in backend that are replicated and unlock them pass def _using_default_backend(self): return ((self.active_backend_id is None) or (self.active_backend_id == strings.PRIMARY_BACKEND_ID)) def _is_vol_split_brain(self, xcli_master, xcli_slave, vol): mirror_master = xcli_master.cmd.mirror_list(vol=vol).as_list mirror_slave = xcli_slave.cmd.mirror_list(vol=vol).as_list if (len(mirror_master) == 1 and len(mirror_slave) == 1 and mirror_master[0].current_role == 'Master' and mirror_slave[0].current_role == 'Slave' and mirror_master[0].sync_state.lower() in SYNCHED_STATES): return False else: return True def _potential_split_brain(self, xcli_master, xcli_slave, volumes, pool_master, pool_slave): potential_split_brain = [] if xcli_master is None or xcli_slave is None: return potential_split_brain try: vols_master = xcli_master.cmd.vol_list( pool=pool_master).as_dict('name') except Exception: msg = "Failed getting information from the active storage." LOG.debug(msg) return potential_split_brain try: vols_slave = xcli_slave.cmd.vol_list( pool=pool_slave).as_dict('name') except Exception: msg = "Failed getting information from the target storage." LOG.debug(msg) return potential_split_brain vols_requested = set(vol['name'] for vol in volumes) common_vols = set(vols_master).intersection( set(vols_slave)).intersection(set(vols_requested)) for name in common_vols: if self._is_vol_split_brain(xcli_master=xcli_master, xcli_slave=xcli_slave, vol=name): potential_split_brain.append(name) return potential_split_brain @proxy._trace_time def failover_host(self, context, volumes, secondary_id, groups=None): """Failover a full backend. Fails over the volume back and forth, if secondary_id is 'default', volumes will be failed back, otherwize failed over. Note that the resulting status depends on the direction: in case of failover it will be 'failed-over' and in case of failback it will be 'available' """ volume_update_list = [] LOG.info("failover_host: from %(active)s to %(id)s", {'active': self.active_backend_id, 'id': secondary_id}) # special cases to handle if secondary_id == strings.PRIMARY_BACKEND_ID: # case: already failed back if self._using_default_backend(): LOG.info("Host has been failed back. No need " "to fail back again.") return self.active_backend_id, volume_update_list, [] pool_slave = self.storage_info[storage.FLAG_KEYS['storage_pool']] pool_master = self._get_target_params( self.active_backend_id)['san_clustername'] goal_status = 'available' else: if not self._using_default_backend(): LOG.info("Already failed over. No need to failover again.") return self.active_backend_id, volume_update_list, [] # case: need to select a target secondary_id = self.get_secondary_backend_id(secondary_id) pool_master = self.storage_info[storage.FLAG_KEYS['storage_pool']] try: pool_slave = self._get_target_params( secondary_id)['san_clustername'] except Exception: msg = _("Invalid target information. Can't perform failover") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) pool_master = self.storage_info[storage.FLAG_KEYS['storage_pool']] goal_status = fields.ReplicationStatus.FAILED_OVER # connnect xcli to secondary storage according to backend_id by # calling _init_xcli with secondary_id self.ibm_storage_remote_cli = self._init_xcli(secondary_id) # get replication_info for all volumes at once if len(volumes): # check for split brain situations # check for files that are available on both volumes # and are not in an active mirroring relation self.check_for_splitbrain(volumes, pool_master, pool_slave) # loop over volumes and attempt failover for volume in volumes: LOG.debug("Attempting to failover '%(vol)s'", {'vol': volume['name']}) result, details = repl.VolumeReplication(self).failover( volume, failback=(secondary_id == strings.PRIMARY_BACKEND_ID)) if result: status = goal_status else: status = 'error' updates = {'status': status} if status == 'error': updates['replication_extended_status'] = details volume_update_list.append({ 'volume_id': volume['id'], 'updates': updates }) # set active xcli to secondary xcli self._replace_xcli_to_remote_xcli() # set active backend id to secondary id self.active_backend_id = secondary_id return secondary_id, volume_update_list, [] @proxy._trace_time def retype(self, ctxt, volume, new_type, diff, host): """Change volume type. Returns a boolean indicating whether the retype occurred. :param ctxt: Context :param volume: A dictionary describing the volume to migrate :param new_type: A dictionary describing the volume type to convert to :param diff: A dictionary with the difference between the two types :param host: A dictionary describing the host to migrate to, where host['host'] is its name, and host['capabilities'] is a dictionary of its reported capabilities """ LOG.debug("retype: volume = %(vol)s type = %(ntype)s", {'vol': volume.get('display_name'), 'ntype': new_type['name']}) if 'location_info' not in host['capabilities']: return False info = host['capabilities']['location_info'] try: (dest, dest_host, dest_pool) = info.split(':') except ValueError: return False volume_host = volume.get('host').split('_')[1] if (dest != strings.XIV_BACKEND_PREFIX or dest_host != volume_host): return False pool_name = self._get_backend_pool() # if pool is different. else - we're on the same pool and retype is ok. if (pool_name != dest_pool): # The input host and pool are already "linked" to the new_type, # otherwise the scheduler does not assign them as candidates for # the retype thus we just need to migrate the volume to the new # pool LOG.debug("retype: migrate volume %(vol)s to " "host=%(host)s, pool=%(pool)s", {'vol': volume.get('display_name'), 'host': dest_host, 'pool': dest_pool}) (mig_result, model) = self.migrate_volume( context=ctxt, volume=volume, host=host) if not mig_result: raise self.meta['exception'].VolumeBackendAPIException( data=PERF_CLASS_ADD_ERROR) # Migration occurred, retype has finished. # We need to check for type and QoS. # getting the old specs old_specs = self._qos_specs_from_volume(volume) new_specs = self._get_qos_specs(new_type.get('id', None)) if not new_specs: if old_specs: LOG.debug("qos: removing qos class for %(vol)s.", {'vol': volume.display_name}) self._qos_remove_vol(volume) return True perf_class_name_old = self._check_perf_class_on_backend(old_specs) perf_class_name_new = self._check_perf_class_on_backend(new_specs) if perf_class_name_new != perf_class_name_old: # add new qos to vol. (removed from old qos automatically) self._qos_add_vol(volume, perf_class_name_new) return True @proxy._trace_time def _check_storage_version_for_qos_support(self): if self.meta['storage_version'] is None: self.meta['storage_version'] = self._call_xiv_xcli( "version_get").as_single_element.system_version if int(self.meta['storage_version'][0:2]) >= 12: return 'True' return 'False' @proxy._trace_time def _update_stats(self): """fetch and update stats.""" LOG.debug("Entered XIVProxy::_update_stats:") self.meta['stat'] = {} connection_type = self._get_connection_type() backend_name = None if self.driver: backend_name = self.driver.configuration.safe_get( 'volume_backend_name') self.meta['stat']['reserved_percentage'] = ( self.driver.configuration.safe_get('reserved_percentage')) self.meta['stat']["volume_backend_name"] = ( backend_name or '%s_%s_%s_%s' % ( strings.XIV_BACKEND_PREFIX, self.storage_info[storage.FLAG_KEYS['address']], self.storage_info[storage.FLAG_KEYS['storage_pool']], connection_type)) self.meta['stat']["vendor_name"] = 'IBM' self.meta['stat']["driver_version"] = self.full_version self.meta['stat']["storage_protocol"] = connection_type self.meta['stat']['multiattach'] = False self.meta['stat']['group_replication_enabled'] = True self.meta['stat']['consistent_group_replication_enabled'] = True self.meta['stat']['QoS_support'] = ( self._check_storage_version_for_qos_support()) self.meta['stat']['location_info'] = ( ('%(destination)s:%(hostname)s:%(pool)s' % {'destination': strings.XIV_BACKEND_PREFIX, 'hostname': self.storage_info[storage.FLAG_KEYS['address']], 'pool': self.storage_info[storage.FLAG_KEYS['storage_pool']] })) self._retrieve_pool_stats(self.meta) if self.targets: self.meta['stat']['replication_enabled'] = True self.meta['stat']['replication_type'] = [SYNC, ASYNC] self.meta['stat']['rpo'] = repl.Replication.get_supported_rpo() self.meta['stat']['replication_count'] = len(self.targets) self.meta['stat']['replication_targets'] = [target for target in self.targets] self.meta['stat']['timestamp'] = datetime.datetime.utcnow() LOG.debug("Exiting XIVProxy::_update_stats: %(stat)s", {'stat': self.meta['stat']}) @proxy._trace_time def _get_pool(self): pool_name = self._get_backend_pool() pools = self._call_xiv_xcli( "pool_list", pool=pool_name).as_list if not pools: msg = (_( "Pool %(pool)s not available on storage") % {'pool': pool_name}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) return pools def _get_backend_pool(self): if self.active_backend_id == strings.PRIMARY_BACKEND_ID: return self.storage_info[storage.FLAG_KEYS['storage_pool']] else: return self._get_target_params( self.active_backend_id)['san_clustername'] def _retrieve_pool_stats(self, data): try: pools = self._get_pool() pool = pools[0] data['stat']['pool_name'] = pool.get('name') # handle different fields in pool_list between Gen3 and BR soft_size = pool.get('soft_size') if soft_size is None: soft_size = pool.get('size') hard_size = 0 else: hard_size = pool.hard_size data['stat']['total_capacity_gb'] = int(soft_size) data['stat']['free_capacity_gb'] = int( pool.get('empty_space_soft', pool.get('empty_space'))) # thin/thick provision data['stat']['thin_provisioning_support'] = ( 'True' if soft_size > hard_size else 'False') data['stat']['backend_state'] = 'up' except Exception as e: data['stat']['total_capacity_gb'] = 0 data['stat']['free_capacity_gb'] = 0 data['stat']['thin_provision'] = False data['stat']['backend_state'] = 'down' error = self._get_code_and_status_or_message(e) LOG.error(error) @proxy._trace_time def create_cloned_volume(self, volume, src_vref): """Create cloned volume.""" # read replication information specs = self._get_extra_specs(volume.get('volume_type_id', None)) replication_info = self._get_replication_info(specs) # TODO(alonma): Refactor to use more common code src_vref_size = float(src_vref['size']) volume_size = float(volume['size']) if volume_size < src_vref_size: error = (_("New volume size (%(vol_size)s GB) cannot be less" "than the source volume size (%(src_size)s GB)..") % {'vol_size': volume_size, 'src_size': src_vref_size}) LOG.error(error) raise self._get_exception()(error) self._create_volume(volume) try: self._call_xiv_xcli( "vol_copy", vol_src=src_vref['name'], vol_trg=volume['name']) except errors.XCLIError as e: error = (_("Failed to copy from '%(src)s' to '%(vol)s': " "%(details)s") % {'src': src_vref.get('name', ''), 'vol': volume.get('name', ''), 'details': self._get_code_and_status_or_message(e)}) LOG.error(error) self._silent_delete_volume(volume=volume) raise self._get_exception()(error) # A side effect of vol_copy is the resizing of the destination volume # to the size of the source volume. If the size is different we need # to get it back to the desired size if src_vref_size != volume_size: size = storage.gigabytes_to_blocks(volume_size) try: self._call_xiv_xcli( "vol_resize", vol=volume['name'], size_blocks=size) except errors.XCLIError as e: error = (_("Fatal error in vol_resize: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) self._silent_delete_volume(volume=volume) raise self._get_exception()(error) self.handle_created_vol_properties(replication_info, volume) @proxy._trace_time def volume_exists(self, volume): """Checks if a volume exists on xiv.""" return len(self._call_xiv_xcli( "vol_list", vol=volume['name']).as_list) > 0 def _cg_name_from_id(self, id): '''Get storage CG name from id. A utility method to translate from id to CG name on the storage ''' return "cg_%(id)s" % {'id': id} def _group_name_from_id(self, id): '''Get storage group name from id. A utility method to translate from id to Snapshot Group name on the storage ''' return "cgs_%(id)s" % {'id': id} def _cg_name_from_volume(self, volume): '''Get storage CG name from volume. A utility method to translate from openstack volume to CG name on the storage ''' LOG.debug("_cg_name_from_volume: %(vol)s", {'vol': volume['name']}) cg_id = volume.get('group_id', None) if cg_id: cg_name = self._cg_name_from_id(cg_id) LOG.debug("Volume %(vol)s is in CG %(cg)s", {'vol': volume['name'], 'cg': cg_name}) return cg_name else: LOG.debug("Volume %(vol)s not in CG", {'vol': volume['name']}) return None def _cg_name_from_group(self, group): '''Get storage CG name from group. A utility method to translate from openstack group to CG name on the storage ''' return self._cg_name_from_id(group['id']) def _cg_name_from_cgsnapshot(self, cgsnapshot): '''Get storage CG name from snapshot. A utility method to translate from openstack cgsnapshot to CG name on the storage ''' return self._cg_name_from_id(cgsnapshot['group_id']) def _group_name_from_cgsnapshot_id(self, cgsnapshot_id): '''Get storage Snaphost Group name from snapshot. A utility method to translate from openstack cgsnapshot to Snapshot Group name on the storage ''' return self._group_name_from_id(cgsnapshot_id) def _volume_name_from_cg_snapshot(self, cgs, vol): # Note: The string is limited by the storage to 63 characters return ('%(cgs)s.%(vol)s' % {'cgs': cgs, 'vol': vol})[0:62] @proxy._trace_time def create_group(self, context, group): """Creates a group.""" if utils.is_group_a_cg_snapshot_type(group): cgname = self._cg_name_from_group(group) return self._create_consistencygroup(context, cgname) # For generic group, create is executed by manager raise NotImplementedError() def _create_consistencygroup(self, context, cgname): """Creates a consistency group.""" LOG.info("Creating consistency group %(name)s.", {'name': cgname}) # call XCLI try: self._call_xiv_xcli( "cg_create", cg=cgname, pool=self.storage_info[ storage.FLAG_KEYS['storage_pool']]).as_list except errors.CgNameExistsError as e: error = (_("consistency group %s already exists on backend") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.CgLimitReachedError as e: error = _("Reached Maximum number of consistency groups") LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = (_("Fatal error in cg_create: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) model_update = {'status': fields.GroupStatus.AVAILABLE} return model_update def _create_consistencygroup_on_remote(self, context, cgname): """Creates a consistency group on secondary machine. Return group available even if it already exists (for replication) """ LOG.info("Creating consistency group %(name)s on secondary.", {'name': cgname}) # call remote XCLI try: self._call_remote_xiv_xcli( "cg_create", cg=cgname, pool=self.storage_info[ storage.FLAG_KEYS['storage_pool']]).as_list except errors.CgNameExistsError: model_update = {'status': fields.GroupStatus.AVAILABLE} except errors.CgLimitReachedError: error = _("Maximum number of consistency groups reached") LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = (_("Fatal error in cg_create on remote: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) model_update = {'status': fields.GroupStatus.AVAILABLE} return model_update def _silent_cleanup_consistencygroup_from_src(self, context, group, volumes, cgname): """Silent cleanup of volumes from CG. Silently cleanup volumes and created consistency-group from storage. This function is called after a failure already occurred and just logs errors, but does not raise exceptions """ for volume in volumes: self._silent_delete_volume_from_cg(volume=volume, cgname=cgname) try: self._delete_consistencygroup(context, group, []) except Exception as e: details = self._get_code_and_status_or_message(e) LOG.error('Failed to cleanup CG %(details)s', {'details': details}) @proxy._trace_time def create_group_from_src(self, context, group, volumes, group_snapshot, sorted_snapshots, source_group, sorted_source_vols): """Create volume group from volume group or volume group snapshot.""" if utils.is_group_a_cg_snapshot_type(group): return self._create_consistencygroup_from_src(context, group, volumes, group_snapshot, sorted_snapshots, source_group, sorted_source_vols) else: raise NotImplementedError() def _create_consistencygroup_from_src(self, context, group, volumes, cgsnapshot, snapshots, source_cg, sorted_source_vols): """Creates a consistency group from source. Source can be a cgsnapshot with the relevant list of snapshots, or another CG with its list of volumes. """ cgname = self._cg_name_from_group(group) LOG.info("Creating consistency group %(cg)s from src.", {'cg': cgname}) volumes_model_update = [] if cgsnapshot and snapshots: LOG.debug("Creating from cgsnapshot %(cg)s", {'cg': self._cg_name_from_group(cgsnapshot)}) try: self._create_consistencygroup(context, cgname) except Exception as e: LOG.error( "Creating CG from cgsnapshot failed: %(details)s", {'details': self._get_code_and_status_or_message(e)}) raise created_volumes = [] try: groupname = self._group_name_from_cgsnapshot_id( cgsnapshot['id']) for volume, source in zip(volumes, snapshots): vol_name = source.volume_name LOG.debug("Original volume: %(vol_name)s", {'vol_name': vol_name}) snapshot_name = self._volume_name_from_cg_snapshot( groupname, vol_name) LOG.debug("create volume (vol)s from snapshot %(snap)s", {'vol': vol_name, 'snap': snapshot_name}) snapshot_size = float(source['volume_size']) self._create_volume_from_snapshot( volume, snapshot_name, snapshot_size) created_volumes.append(volume) volumes_model_update.append( { 'id': volume['id'], 'status': 'available', 'size': snapshot_size, }) except Exception as e: details = self._get_code_and_status_or_message(e) msg = (CREATE_VOLUME_BASE_ERROR % {'details': details}) LOG.error(msg) # cleanup and then raise exception self._silent_cleanup_consistencygroup_from_src( context, group, created_volumes, cgname) raise self.meta['exception'].VolumeBackendAPIException( data=msg) elif source_cg and sorted_source_vols: LOG.debug("Creating from CG %(cg)s .", {'cg': self._cg_name_from_group(source_cg)}) LOG.debug("Creating from CG %(cg)s .", {'cg': source_cg['id']}) try: self._create_consistencygroup(context, group) except Exception as e: LOG.error("Creating CG from CG failed: %(details)s", {'details': self._get_code_and_status_or_message(e)}) raise created_volumes = [] try: for volume, source in zip(volumes, sorted_source_vols): self.create_cloned_volume(volume, source) created_volumes.append(volume) volumes_model_update.append( { 'id': volume['id'], 'status': 'available', 'size': source['size'], }) except Exception as e: details = self._get_code_and_status_or_message(e) msg = (CREATE_VOLUME_BASE_ERROR, {'details': details}) LOG.error(msg) # cleanup and then raise exception self._silent_cleanup_consistencygroup_from_src( context, group, created_volumes, cgname) raise self.meta['exception'].VolumeBackendAPIException( data=msg) else: error = 'create_consistencygroup_from_src called without a source' raise self._get_exception()(error) model_update = {'status': fields.GroupStatus.AVAILABLE} return model_update, volumes_model_update @proxy._trace_time def delete_group(self, context, group, volumes): """Deletes a group.""" rep_status = group.get('replication_status') enabled = fields.ReplicationStatus.ENABLED failed_over = fields.ReplicationStatus.FAILED_OVER if rep_status == enabled or rep_status == failed_over: msg = _("Disable group replication before deleting group.") LOG.error(msg) raise self._get_exception()(msg) if utils.is_group_a_cg_snapshot_type(group): return self._delete_consistencygroup(context, group, volumes) else: # For generic group delete the volumes only - executed by manager raise NotImplementedError() def _delete_consistencygroup(self, context, group, volumes): """Deletes a consistency group.""" cgname = self._cg_name_from_group(group) LOG.info("Deleting consistency group %(name)s.", {'name': cgname}) model_update = {} model_update['status'] = group.get('status', fields.GroupStatus.DELETING) # clean up volumes volumes_model_update = [] for volume in volumes: try: self._call_xiv_xcli( "cg_remove_vol", vol=volume['name']) except errors.XCLIError as e: LOG.error("Failed removing volume %(vol)s from " "consistency group %(cg)s: %(err)s", {'vol': volume['name'], 'cg': cgname, 'err': self._get_code_and_status_or_message(e)}) # continue in spite of error try: self._delete_volume(volume['name']) # size and volume_type_id are required in liberty code # they are maintained here for backwards compatability volumes_model_update.append( { 'id': volume['id'], 'status': 'deleted', }) except errors.XCLIError as e: LOG.error(DELETE_VOLUME_BASE_ERROR, {'volume': volume['name'], 'error': self._get_code_and_status_or_message(e)}) model_update['status'] = fields.GroupStatus.ERROR_DELETING # size and volume_type_id are required in liberty code # they are maintained here for backwards compatibility volumes_model_update.append( { 'id': volume['id'], 'status': 'error_deleting', }) # delete CG from cinder.volume.drivers.ibm.ibm_storage if model_update['status'] != fields.GroupStatus.ERROR_DELETING: try: self._call_xiv_xcli( "cg_delete", cg=cgname).as_list model_update['status'] = fields.GroupStatus.DELETED except (errors.CgDoesNotExistError, errors.CgBadNameError): LOG.warning("consistency group %(cgname)s does not " "exist on backend", {'cgname': cgname}) # if the object was already deleted on the backend, we can # continue and delete the openstack object model_update['status'] = fields.GroupStatus.DELETED except errors.CgHasMirrorError: error = (_("consistency group %s is being mirrored") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.CgNotEmptyError: error = (_("consistency group %s is not empty") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = (_("Fatal: %(code)s. CG: %(cgname)s") % {'code': self._get_code_and_status_or_message(e), 'cgname': cgname}) LOG.error(error) raise self._get_exception()(error) return model_update, volumes_model_update @proxy._trace_time def update_group(self, context, group, add_volumes=None, remove_volumes=None): """Updates a group.""" if utils.is_group_a_cg_snapshot_type(group): return self._update_consistencygroup(context, group, add_volumes, remove_volumes) else: # For generic group update executed by manager raise NotImplementedError() def _update_consistencygroup(self, context, group, add_volumes=None, remove_volumes=None): """Updates a consistency group.""" cgname = self._cg_name_from_group(group) LOG.info("Updating consistency group %(name)s.", {'name': cgname}) model_update = {'status': fields.GroupStatus.AVAILABLE} add_volumes_update = [] if add_volumes: for volume in add_volumes: try: self._call_xiv_xcli( "cg_add_vol", vol=volume['name'], cg=cgname) except errors.XCLIError as e: error = (_("Failed adding volume %(vol)s to " "consistency group %(cg)s: %(err)s") % {'vol': volume['name'], 'cg': cgname, 'err': self._get_code_and_status_or_message(e)}) LOG.error(error) self._cleanup_consistencygroup_update( context, group, add_volumes_update, None) raise self._get_exception()(error) add_volumes_update.append({'name': volume['name']}) remove_volumes_update = [] if remove_volumes: for volume in remove_volumes: try: self._call_xiv_xcli( "cg_remove_vol", vol=volume['name']) except (errors.VolumeNotInConsGroup, errors.VolumeBadNameError) as e: # ignore the error if the volume exists in storage but # not in cg, or the volume does not exist in the storage details = self._get_code_and_status_or_message(e) LOG.debug(details) except errors.XCLIError as e: error = (_("Failed removing volume %(vol)s from " "consistency group %(cg)s: %(err)s") % {'vol': volume['name'], 'cg': cgname, 'err': self._get_code_and_status_or_message(e)}) LOG.error(error) self._cleanup_consistencygroup_update( context, group, add_volumes_update, remove_volumes_update) raise self._get_exception()(error) remove_volumes_update.append({'name': volume['name']}) return model_update, None, None def _cleanup_consistencygroup_update(self, context, group, add_volumes, remove_volumes): if add_volumes: for volume in add_volumes: try: self._call_xiv_xcli( "cg_remove_vol", vol=volume['name']) except Exception: LOG.debug("cg_remove_vol(%s) failed", volume['name']) if remove_volumes: cgname = self._cg_name_from_group(group) for volume in remove_volumes: try: self._call_xiv_xcli( "cg_add_vol", vol=volume['name'], cg=cgname) except Exception: LOG.debug("cg_add_vol(%(name)s, %(cgname)s) failed", {'name': volume['name'], 'cgname': cgname}) @proxy._trace_time def create_group_snapshot(self, context, group_snapshot, snapshots): """Create volume group snapshot.""" if utils.is_group_a_cg_snapshot_type(group_snapshot): return self._create_cgsnapshot(context, group_snapshot, snapshots) else: # For generic group snapshot create executed by manager raise NotImplementedError() def _create_cgsnapshot(self, context, cgsnapshot, snapshots): """Creates a CG snapshot.""" model_update = {'status': fields.GroupSnapshotStatus.AVAILABLE} cgname = self._cg_name_from_cgsnapshot(cgsnapshot) groupname = self._group_name_from_cgsnapshot_id(cgsnapshot['id']) LOG.info("Creating snapshot %(group)s for CG %(cg)s.", {'group': groupname, 'cg': cgname}) # call XCLI try: self._call_xiv_xcli( "cg_snapshots_create", cg=cgname, snap_group=groupname).as_list except errors.CgDoesNotExistError as e: error = (_("Consistency group %s does not exist on backend") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.CgBadNameError as e: error = (_("Consistency group %s has an illegal name") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.SnapshotGroupDoesNotExistError as e: error = (_("Snapshot group %s has an illegal name") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.PoolSnapshotLimitReachedError as e: error = _("Reached maximum snapshots allocation size") LOG.error(error) raise self._get_exception()(error) except errors.CgEmptyError as e: error = (_("Consistency group %s is empty") % cgname) LOG.error(error) raise self._get_exception()(error) except (errors.MaxVolumesReachedError, errors.DomainMaxVolumesReachedError) as e: error = _("Reached Maximum number of volumes") LOG.error(error) raise self._get_exception()(error) except errors.SnapshotGroupIsReservedError as e: error = (_("Consistency group %s name is reserved") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.SnapshotGroupAlreadyExistsError as e: error = (_("Snapshot group %s already exists") % groupname) LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = (_("Fatal: CG %(cg)s, Group %(group)s. %(err)s") % {'cg': cgname, 'group': groupname, 'err': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) snapshots_model_update = [] for snapshot in snapshots: snapshots_model_update.append( { 'id': snapshot['id'], 'status': fields.SnapshotStatus.AVAILABLE, }) return model_update, snapshots_model_update @proxy._trace_time def delete_group_snapshot(self, context, group_snapshot, snapshots): """Delete volume group snapshot.""" if utils.is_group_a_cg_snapshot_type(group_snapshot): return self._delete_cgsnapshot(context, group_snapshot, snapshots) else: # For generic group snapshot delete is executed by manager raise NotImplementedError() def _delete_cgsnapshot(self, context, cgsnapshot, snapshots): """Deletes a CG snapshot.""" cgname = self._cg_name_from_cgsnapshot(cgsnapshot) groupname = self._group_name_from_cgsnapshot_id(cgsnapshot['id']) LOG.info("Deleting snapshot %(group)s for CG %(cg)s.", {'group': groupname, 'cg': cgname}) # call XCLI try: self._call_xiv_xcli( "snap_group_delete", snap_group=groupname).as_list except errors.CgDoesNotExistError: error = _("consistency group %s not found on backend") % cgname LOG.error(error) raise self._get_exception()(error) except errors.PoolSnapshotLimitReachedError: error = _("Reached Maximum size allocated for snapshots") LOG.error(error) raise self._get_exception()(error) except errors.CgEmptyError: error = _("Consistency group %s is empty") % cgname LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = _("Fatal: CG %(cg)s, Group %(group)s. %(err)s") % { 'cg': cgname, 'group': groupname, 'err': self._get_code_and_status_or_message(e) } LOG.error(error) raise self._get_exception()(error) model_update = {'status': fields.GroupSnapshotStatus.DELETED} snapshots_model_update = [] for snapshot in snapshots: snapshots_model_update.append( { 'id': snapshot['id'], 'status': fields.SnapshotStatus.DELETED, }) return model_update, snapshots_model_update def _generate_chap_secret(self, chap_name): """Returns chap secret generated according to chap_name chap secret must be between 12-16 chaqnracters """ name = chap_name chap_secret = "" while len(chap_secret) < 12: chap_secret = cryptish.encrypt(name)[:16] name = name + '_' LOG.debug("_generate_chap_secret: %(secret)s", {'secret': chap_secret}) return chap_secret @proxy._trace_time def _create_chap(self, host=None): """Get CHAP name and secret returns chap name and secret chap_name and chap_secret must be 12-16 characters long """ if host: if host['chap']: chap_name = host['chap'][0] LOG.debug("_create_chap: %(chap_name)s ", {'chap_name': chap_name}) else: chap_name = host['name'] else: LOG.info("_create_chap: host missing!!!") chap_name = "12345678901234" chap_secret = self._generate_chap_secret(chap_name) LOG.debug("_create_chap (new): %(chap_name)s ", {'chap_name': chap_name}) return (chap_name, chap_secret) @proxy._trace_time def _get_host(self, connector): """Returns a host looked up via initiator.""" try: host_bunch = self._get_bunch_from_host(connector) except Exception as e: details = self._get_code_and_status_or_message(e) msg = (_("%(prefix)s. Invalid connector: '%(details)s.'") % {'prefix': storage.XIV_LOG_PREFIX, 'details': details}) raise self._get_exception()(msg) host = [] chap = None all_hosts = self._call_xiv_xcli("host_list").as_list if self._get_connection_type() == storage.XIV_CONNECTION_TYPE_ISCSI: host = [host_obj for host_obj in all_hosts if host_bunch['initiator'] in host_obj.iscsi_ports.split(',')] else: if 'wwpns' in connector: if len(host_bunch['wwpns']) > 0: wwpn_set = set([wwpn.lower() for wwpn in host_bunch['wwpns']]) host = [host_obj for host_obj in all_hosts if len(wwpn_set.intersection(host_obj.get( 'fc_ports', '').lower().split(','))) > 0] else: # fake connector created by nova host = [host_obj for host_obj in all_hosts if host_obj.get('name', '') == connector['host']] if len(host) == 1: if self._is_iscsi() and host[0].iscsi_chap_name: chap = (host[0].iscsi_chap_name, self._generate_chap_secret(host[0].iscsi_chap_name)) LOG.debug("_get_host: chap_name %(chap_name)s ", {'chap_name': host[0].iscsi_chap_name}) return self._get_bunch_from_host( connector, host[0].id, host[0].name, chap) LOG.debug("_get_host: returns None") return None @proxy._trace_time def _call_host_define(self, host, chap_name=None, chap_secret=None, domain_name=None): """Call host_define using XCLI.""" LOG.debug("host_define with domain: %s)", domain_name) if domain_name: if chap_name: return self._call_xiv_xcli( "host_define", host=host, iscsi_chap_name=chap_name, iscsi_chap_secret=chap_secret, domain=domain_name ).as_list[0] else: return self._call_xiv_xcli( "host_define", host=host, domain=domain_name ).as_list[0] else: # No domain if chap_name: return self._call_xiv_xcli( "host_define", host=host, iscsi_chap_name=chap_name, iscsi_chap_secret=chap_secret ).as_list[0] else: return self._call_xiv_xcli( "host_define", host=host ).as_list[0] @proxy._trace_time def _define_host_according_to_chap(self, host, in_domain): """Check on chap state and define host accordingly.""" chap_name = None chap_secret = None if (self._get_connection_type() == storage.XIV_CONNECTION_TYPE_ISCSI and self._get_chap_type() == storage.CHAP_ENABLED): host_bunch = {'name': host, 'chap': None, } chap = self._create_chap(host=host_bunch) chap_name = chap[0] chap_secret = chap[1] LOG.debug("_define_host_according_to_chap: " "%(name)s : %(secret)s", {'name': chap_name, 'secret': chap_secret}) return self._call_host_define( host=host, chap_name=chap_name, chap_secret=chap_secret, domain_name=in_domain) def _define_ports(self, host_bunch): """Defines ports in XIV.""" fc_targets = [] LOG.debug(host_bunch.get('name')) if self._get_connection_type() == storage.XIV_CONNECTION_TYPE_ISCSI: self._define_iscsi(host_bunch) else: fc_targets = self._define_fc(host_bunch) fc_targets = list(set(fc_targets)) fc_targets.sort(key=self._sort_last_digit) return fc_targets def _get_pool_domain(self, connector): pool_name = self._get_backend_pool() LOG.debug("pool name from configuration: %s", pool_name) domain = None try: domain = self._call_xiv_xcli( "pool_list", pool=pool_name).as_list[0].get('domain') LOG.debug("Pool's domain: %s", domain) except AttributeError: pass return domain @proxy._trace_time def _define_host(self, connector): """Defines a host in XIV.""" domain = self._get_pool_domain(connector) host_bunch = self._get_bunch_from_host(connector) host = self._call_xiv_xcli( "host_list", host=host_bunch['name']).as_list connection_type = self._get_connection_type() if len(host) == 0: LOG.debug("Non existing host, defining") host = self._define_host_according_to_chap( host=host_bunch['name'], in_domain=domain) host_bunch = self._get_bunch_from_host(connector, host.get('id')) else: host_bunch = self._get_bunch_from_host(connector, host[0].get('id')) LOG.debug("Generating hostname for connector %(conn)s", {'conn': connector}) generated_hostname = storage.get_host_or_create_from_iqn( connector, connection=connection_type) generated_host = self._call_xiv_xcli( "host_list", host=generated_hostname).as_list if len(generated_host) == 0: host = self._define_host_according_to_chap( host=generated_hostname, in_domain=domain) else: host = generated_host[0] host_bunch = self._get_bunch_from_host( connector, host.get('id'), host_name=generated_hostname) LOG.debug("The host_bunch: %s", host_bunch) return host_bunch @proxy._trace_time def _define_fc(self, host_bunch): """Define FC Connectivity.""" fc_targets = [] if len(host_bunch.get('wwpns')) > 0: connected_wwpns = [] for wwpn in host_bunch.get('wwpns'): component_ids = list(set( [p.component_id for p in self._call_xiv_xcli( "fc_connectivity_list", wwpn=wwpn.replace(":", ""))])) wwpn_fc_target_lists = [] for component in component_ids: wwpn_fc_target_lists += [fc_p.wwpn for fc_p in self._call_xiv_xcli( "fc_port_list", fcport=component)] LOG.debug("got %(tgts)s fc targets for wwpn %(wwpn)s", {'tgts': wwpn_fc_target_lists, 'wwpn': wwpn}) if len(wwpn_fc_target_lists) > 0: connected_wwpns += [wwpn] fc_targets += wwpn_fc_target_lists LOG.debug("adding fc port %s", wwpn) self._call_xiv_xcli( "host_add_port", host=host_bunch.get('name'), fcaddress=wwpn) if len(connected_wwpns) == 0: LOG.error(CONNECTIVITY_FC_NO_TARGETS) all_target_ports = self._get_all_target_ports() fc_targets = list(set([target.get('wwpn') for target in all_target_ports])) else: msg = _("No Fibre Channel HBA's are defined on the host.") LOG.error(msg) raise self._get_exception()(msg) return fc_targets @proxy._trace_time def _define_iscsi(self, host_bunch): """Add iscsi ports.""" if host_bunch.get('initiator'): LOG.debug("adding iscsi") self._call_xiv_xcli( "host_add_port", host=host_bunch.get('name'), iscsi_name=host_bunch.get('initiator')) else: msg = _("No iSCSI initiator found!") LOG.error(msg) raise self._get_exception()(msg) @proxy._trace_time def _event_service_start(self): """Send an event when cinder service starts.""" LOG.debug("send event SERVICE_STARTED") service_start_evnt_prop = { "openstack_version": self.meta['openstack_version'], "pool_name": self._get_backend_pool()} ev_mgr = events.EventsManager(self.ibm_storage_cli, OPENSTACK_PRODUCT_NAME, self.full_version) ev_mgr.send_event('SERVICE_STARTED', service_start_evnt_prop) @proxy._trace_time def _event_volume_attached(self): """Send an event when volume is attached to host.""" LOG.debug("send event VOLUME_ATTACHED") compute_host_name = socket.getfqdn() vol_attach_evnt_prop = { "openstack_version": self.meta['openstack_version'], "pool_name": self._get_backend_pool(), "compute_hostname": compute_host_name} ev_mgr = events.EventsManager(self.ibm_storage_cli, OPENSTACK_PRODUCT_NAME, self.full_version) ev_mgr.send_event('VOLUME_ATTACHED', vol_attach_evnt_prop) @proxy._trace_time def _build_initiator_target_map(self, fc_targets, connector): """Build the target_wwns and the initiator target map.""" init_targ_map = {} wwpns = connector.get('wwpns', []) for initiator in wwpns: init_targ_map[initiator] = fc_targets LOG.debug("_build_initiator_target_map: %(init_targ_map)s", {'init_targ_map': init_targ_map}) return init_targ_map @proxy._trace_time def _get_host_and_fc_targets(self, volume, connector): """Returns the host and its FC targets.""" LOG.debug("_get_host_and_fc_targets %(volume)s", {'volume': volume['name']}) fc_targets = [] host = self._get_host(connector) if not host: host = self._define_host(connector) fc_targets = self._define_ports(host) elif self._get_connection_type() == storage.XIV_CONNECTION_TYPE_FC: fc_targets = self._get_fc_targets(host) if len(fc_targets) == 0: LOG.error(CONNECTIVITY_FC_NO_TARGETS) raise self._get_exception()(CONNECTIVITY_FC_NO_TARGETS) return (fc_targets, host) def _vol_map_and_get_lun_id(self, volume, connector, host): """Maps volume to instance. Maps a volume to the nova volume node as host, and return the created lun id """ vol_name = volume['name'] LOG.debug("_vol_map_and_get_lun_id %(volume)s", {'volume': vol_name}) try: mapped_vols = self._call_xiv_xcli( "vol_mapping_list", vol=vol_name).as_dict('host') if host['name'] in mapped_vols: LOG.info("Volume '%(volume)s' was already attached to " "the host '%(host)s'.", {'host': host['name'], 'volume': volume['name']}) return int(mapped_vols[host['name']].lun) except errors.VolumeBadNameError: LOG.error("Volume not found. '%s'", volume['name']) raise self.meta['exception'].VolumeNotFound(volume_id=volume['id']) used_luns = [int(mapped.get('lun')) for mapped in self._call_xiv_xcli( "mapping_list", host=host['name']).as_list] luns = six.moves.xrange(MIN_LUNID, MAX_LUNID) # pylint: disable=E1101 for lun_id in luns: if lun_id not in used_luns: self._call_xiv_xcli( "map_vol", lun=lun_id, host=host['name'], vol=vol_name) self._event_volume_attached() return lun_id msg = _("All free LUN IDs were already mapped.") LOG.error(msg) raise self._get_exception()(msg) @proxy._trace_time def _get_all_target_ports(self): all_target_ports = [] fc_port_list = self._call_xiv_xcli("fc_port_list") all_target_ports += ([t for t in fc_port_list if t.get('wwpn') != '0000000000000000' and t.get('role') == 'Target' and t.get('port_state') == 'Online']) return all_target_ports @proxy._trace_time def _get_fc_targets(self, host): """Get FC targets :host: A dictionary describing the host :returns: array of FC target WWPNs """ target_wwpns = [] all_target_ports = self._get_all_target_ports() if host: host_conect_list = self._call_xiv_xcli("host_connectivity_list", host=host.get('name')) for connection in host_conect_list: fc_port = connection.get('local_fc_port') target_wwpns += ( [target.get('wwpn') for target in all_target_ports if target.get('component_id') == fc_port]) if not target_wwpns: LOG.debug('No fc targets found accessible to host: %s. Return list' ' of all available FC targets', host) target_wwpns = ([target.get('wwpn') for target in all_target_ports]) fc_targets = list(set(target_wwpns)) fc_targets.sort(key=self._sort_last_digit) LOG.debug("fc_targets : %s", fc_targets) return fc_targets def _sort_last_digit(self, a): return a[-1:] @proxy._trace_time def _get_xcli(self, xcli, backend_id): """Wrapper around XCLI to ensure that connection is up.""" if self.meta['bypass_connection_check']: LOG.debug("_get_xcli(bypass mode)") else: if not xcli.is_connected(): xcli = self._init_xcli(backend_id) return xcli @proxy._trace_time def _call_xiv_xcli(self, method, *args, **kwargs): """Wrapper around XCLI to call active storage.""" self.ibm_storage_cli = self._get_xcli( self.ibm_storage_cli, self.active_backend_id) if self.ibm_storage_cli: LOG.info("_call_xiv_xcli #1: %s", method) else: LOG.debug("_call_xiv_xcli #2: %s", method) return getattr(self.ibm_storage_cli.cmd, method)(*args, **kwargs) @proxy._trace_time def _call_remote_xiv_xcli(self, method, *args, **kwargs): """Wrapper around XCLI to call remote storage.""" remote_id = self._get_secondary_backend_id() if not remote_id: raise self._get_exception()(_("No remote backend found.")) self.ibm_storage_remote_cli = self._get_xcli( self.ibm_storage_remote_cli, remote_id) LOG.debug("_call_remote_xiv_xcli: %s", method) return getattr(self.ibm_storage_remote_cli.cmd, method)( *args, **kwargs) def _verify_xiv_flags(self, address, user, password): """Verify that the XIV flags were passed.""" if not user or not password: raise self._get_exception()(_("No credentials found.")) if not address: raise self._get_exception()(_("No host found.")) def _get_connection_params(self, backend_id=strings.PRIMARY_BACKEND_ID): """Get connection parameters. returns a tuple containing address list, user, password, according to backend_id """ if not backend_id or backend_id == strings.PRIMARY_BACKEND_ID: if self._get_management_ips(): address = [e.strip(" ") for e in self.storage_info[ storage.FLAG_KEYS['management_ips']].split(",")] else: address = self.storage_info[storage.FLAG_KEYS['address']] user = self.storage_info[storage.FLAG_KEYS['user']] password = self.storage_info[storage.FLAG_KEYS['password']] else: params = self._get_target_params(backend_id) if not params: msg = (_("Missing target information for target '%(target)s'"), {'target': backend_id}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) if params.get('management_ips', None): address = [e.strip(" ") for e in params['management_ips'].split(",")] else: address = params['san_ip'] user = params['san_login'] password = params['san_password'] return (address, user, password) @proxy._trace_time def _init_xcli(self, backend_id=strings.PRIMARY_BACKEND_ID): """Initilize XCLI connection. returns an XCLIClient object """ try: address, user, password = self._get_connection_params(backend_id) except Exception as e: details = self._get_code_and_status_or_message(e) ex_details = (SETUP_BASE_ERROR, {'title': strings.TITLE, 'details': details}) LOG.error(ex_details) raise self.meta['exception'].InvalidParameterValue( (_("%(prefix)s %(ex_details)s") % {'prefix': storage.XIV_LOG_PREFIX, 'ex_details': ex_details})) self._verify_xiv_flags(address, user, password) try: clear_pass = cryptish.decrypt(password) except TypeError: ex_details = (SETUP_BASE_ERROR, {'title': strings.TITLE, 'details': "Invalid password."}) LOG.error(ex_details) raise self.meta['exception'].InvalidParameterValue( (_("%(prefix)s %(ex_details)s") % {'prefix': storage.XIV_LOG_PREFIX, 'ex_details': ex_details})) certs = certificate.CertificateCollector() path = certs.collect_certificate() try: LOG.debug('connect_multiendpoint_ssl with: %s', address) xcli = client.XCLIClient.connect_multiendpoint_ssl( user, clear_pass, address, ca_certs=path) except errors.CredentialsError: LOG.error(SETUP_BASE_ERROR, {'title': strings.TITLE, 'details': "Invalid credentials."}) raise self.meta['exception'].NotAuthorized() except (errors.ConnectionError, transports.ClosedTransportError): err_msg = (SETUP_INVALID_ADDRESS, {'address': address}) LOG.error(err_msg) raise self.meta['exception'].HostNotFound(host=err_msg) except Exception as er: err_msg = (SETUP_BASE_ERROR % {'title': strings.TITLE, 'details': er}) LOG.error(err_msg) raise self._get_exception()(err_msg) finally: certs.free_certificate() return xcli
42.38141
79
0.561345
import datetime import re import six import socket from oslo_log import log as logging from oslo_utils import importutils pyxcli = importutils.try_import("pyxcli") if pyxcli: from pyxcli import client from pyxcli import errors from pyxcli.events import events from pyxcli.mirroring import mirrored_entities from pyxcli import transports from cinder import context from cinder.i18n import _ from cinder.objects import fields from cinder import volume as c_volume import cinder.volume.drivers.ibm.ibm_storage as storage from cinder.volume.drivers.ibm.ibm_storage import certificate from cinder.volume.drivers.ibm.ibm_storage import cryptish from cinder.volume.drivers.ibm.ibm_storage import proxy from cinder.volume.drivers.ibm.ibm_storage import strings from cinder.volume.drivers.ibm.ibm_storage import xiv_replication as repl from cinder.volume import group_types from cinder.volume import qos_specs from cinder.volume import utils from cinder.volume import volume_types OPENSTACK_PRODUCT_NAME = "OpenStack" PERF_CLASS_NAME_PREFIX = "cinder-qos" HOST_BAD_NAME = "HOST_BAD_NAME" VOLUME_IS_MAPPED = "VOLUME_IS_MAPPED" CONNECTIONS_PER_MODULE = 2 MIN_LUNID = 1 MAX_LUNID = 511 SYNC = 'sync' ASYNC = 'async' SYNC_TIMEOUT = 300 SYNCHED_STATES = ['synchronized', 'rpo ok'] PYXCLI_VERSION = '1.1.6' LOG = logging.getLogger(__name__) PERF_CLASS_ERROR = _("Unable to create or get performance class: %(details)s") PERF_CLASS_ADD_ERROR = _("Unable to add volume to performance class: " "%(details)s") PERF_CLASS_VALUES_ERROR = _("A performance class with the same name but " "different values exists: %(details)s") SETUP_BASE_ERROR = _("Unable to connect to %(title)s: %(details)s") SETUP_INVALID_ADDRESS = _("Unable to connect to the storage system " "at '%(address)s', invalid address.") CREATE_VOLUME_BASE_ERROR = _("Unable to create volume: %(details)s") CONNECTIVITY_FC_NO_TARGETS = _("Unable to detect FC connection between the " "compute host and the storage, please ensure " "that zoning is set up correctly.") TERMINATE_CONNECTION_BASE_ERROR = ("Unable to terminate the connection " "for volume '%(volume)s': %(error)s.") TERMINATE_CONNECTION_HOST_ERROR = ("Terminate connection for volume " "'%(volume)s': for volume '%(volume)s': " "%(host)s %(error)s.") DELETE_VOLUME_BASE_ERROR = ("Unable to delete volume '%(volume)s': " "%(error)s.") MANAGE_VOLUME_BASE_ERROR = _("Unable to manage the volume '%(volume)s': " "%(error)s.") INCOMPATIBLE_PYXCLI = _('Incompatible pyxcli found. Mininum: %(required)s ' 'Found: %(found)s') class XIVProxy(proxy.IBMStorageProxy): def __init__(self, storage_info, logger, exception, driver=None, active_backend_id=None, host=None): if not active_backend_id: active_backend_id = strings.PRIMARY_BACKEND_ID proxy.IBMStorageProxy.__init__( self, storage_info, logger, exception, driver, active_backend_id) LOG.info("__init__: storage_info: %(keys)s", {'keys': self.storage_info}) if active_backend_id: LOG.info("__init__: active_backend_id: %(id)s", {'id': active_backend_id}) self.ibm_storage_cli = None self.meta['ibm_storage_portal'] = None self.meta['ibm_storage_iqn'] = None self.ibm_storage_remote_cli = None self.meta['ibm_storage_fc_targets'] = [] self.meta['storage_version'] = None self.system_id = None @proxy._trace_time def setup(self, context): msg = '' if pyxcli: if pyxcli.version < PYXCLI_VERSION: msg = (INCOMPATIBLE_PYXCLI % {'required': PYXCLI_VERSION, 'found': pyxcli.version }) else: msg = (SETUP_BASE_ERROR % {'title': strings.TITLE, 'details': "IBM Python XCLI Client (pyxcli) not found" }) if msg != '': LOG.error(msg) raise self._get_exception()(msg) LOG.info("Setting up connection to %(title)s...\n" "Active backend_id: '%(id)s'.", {'title': strings.TITLE, 'id': self.active_backend_id}) self.ibm_storage_cli = self._init_xcli(self.active_backend_id) if self._get_connection_type() == storage.XIV_CONNECTION_TYPE_ISCSI: self.meta['ibm_storage_iqn'] = ( self._call_xiv_xcli("config_get"). as_dict('name')['iscsi_name'].value) portals = storage.get_online_iscsi_ports(self.ibm_storage_cli) if len(portals) == 0: msg = (SETUP_BASE_ERROR, {'title': strings.TITLE, 'details': "No iSCSI portals available on the Storage." }) raise self._get_exception()( _("%(prefix)s %(portals)s") % {'prefix': storage.XIV_LOG_PREFIX, 'portals': msg}) self.meta['ibm_storage_portal'] = "%s:3260" % portals[:1][0] remote_id = self._get_secondary_backend_id() if remote_id: self.ibm_storage_remote_cli = self._init_xcli(remote_id) self._event_service_start() self._get_pool() LOG.info("IBM Storage %(common_ver)s " "xiv_proxy %(proxy_ver)s. ", {'common_ver': self.full_version, 'proxy_ver': self.full_version}) self._update_system_id() if remote_id: self._update_active_schedule_objects() self._update_remote_schedule_objects() LOG.info("Connection to the IBM storage " "system established successfully.") @proxy._trace_time def _update_active_schedule_objects(self): schedules = self._call_xiv_xcli("schedule_list").as_dict('name') for rate in repl.Replication.async_rates: if rate.schedule == '00:00:20': continue name = rate.schedule_name schedule = schedules.get(name, None) if schedule: LOG.debug('Exists on local backend %(sch)s', {'sch': name}) interval = schedule.get('interval', '') if interval != rate.schedule: msg = (_("Schedule %(sch)s exists with incorrect " "value %(int)s") % {'sch': name, 'int': interval}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) else: LOG.debug('create %(sch)s', {'sch': name}) try: self._call_xiv_xcli("schedule_create", schedule=name, type='interval', interval=rate.schedule) except errors.XCLIError: msg = (_("Setting up Async mirroring failed, " "schedule %(sch)s is not supported on system: " " %(id)s.") % {'sch': name, 'id': self.system_id}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) @proxy._trace_time def _update_remote_schedule_objects(self): schedules = self._call_remote_xiv_xcli("schedule_list").as_dict('name') for rate in repl.Replication.async_rates: if rate.schedule == '00:00:20': continue name = rate.schedule_name if schedules.get(name, None): LOG.debug('Exists on remote backend %(sch)s', {'sch': name}) interval = schedules.get(name, None)['interval'] if interval != rate.schedule: msg = (_("Schedule %(sch)s exists with incorrect " "value %(int)s") % {'sch': name, 'int': interval}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) else: try: self._call_remote_xiv_xcli("schedule_create", schedule=name, type='interval', interval=rate.schedule) except errors.XCLIError: msg = (_("Setting up Async mirroring failed, " "schedule %(sch)s is not supported on system: " " %(id)s.") % {'sch': name, 'id': self.system_id}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) def _get_extra_specs(self, type_id): if type_id is None: return {} return c_volume.volume_types.get_volume_type_extra_specs(type_id) def _update_system_id(self): if self.system_id: return local_ibm_storage_cli = self._init_xcli(strings.PRIMARY_BACKEND_ID) if not local_ibm_storage_cli: LOG.error('Failed to connect to main backend. ' 'Cannot retrieve main backend system_id') return system_id = local_ibm_storage_cli.cmd.config_get().as_dict( 'name')['system_id'].value LOG.debug('system_id: %(id)s', {'id': system_id}) self.system_id = system_id @proxy._trace_time def _get_qos_specs(self, type_id): ctxt = context.get_admin_context() volume_type = volume_types.get_volume_type(ctxt, type_id) if not volume_type: return None qos_specs_id = volume_type.get('qos_specs_id', None) if qos_specs_id: return qos_specs.get_qos_specs( ctxt, qos_specs_id).get('specs', None) return None @proxy._trace_time def _qos_create_kwargs_for_xcli(self, specs): args = {} for key in specs: if key == 'bw': args['max_bw_rate'] = specs[key] if key == 'iops': args['max_io_rate'] = specs[key] return args def _qos_remove_vol(self, volume): try: self._call_xiv_xcli("perf_class_remove_vol", vol=volume['name']) except errors.VolumeNotConnectedToPerfClassError as e: details = self._get_code_and_status_or_message(e) LOG.debug(details) return True except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg_data = (_("Unable to add volume to performance " "class: %(details)s") % {'details': details}) LOG.error(msg_data) raise self.meta['exception'].VolumeBackendAPIException( data=msg_data) return True def _qos_add_vol(self, volume, perf_class_name): try: self._call_xiv_xcli("perf_class_add_vol", vol=volume['name'], perf_class=perf_class_name) except errors.VolumeAlreadyInPerfClassError as e: details = self._get_code_and_status_or_message(e) LOG.debug(details) return True except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = PERF_CLASS_ADD_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) return True def _check_perf_class_on_backend(self, specs): perf_class_name = PERF_CLASS_NAME_PREFIX if specs is None or specs == {}: return '' for key, value in sorted(specs.items()): perf_class_name += '_' + key + '_' + value try: classes_list = self._call_xiv_xcli("perf_class_list", perf_class=perf_class_name ).as_list for perf_class in classes_list: if (not perf_class.get('max_iops', None) == specs.get('iops', '0') or not perf_class.get('max_bw', None) == specs.get('bw', '0')): raise self.meta['exception'].VolumeBackendAPIException( data=PERF_CLASS_VALUES_ERROR % {'details': perf_class_name}) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = PERF_CLASS_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) if not classes_list: self._create_qos_class(perf_class_name, specs) return perf_class_name def _get_type_from_perf_class_name(self, perf_class_name): _type = re.findall('type_(independent|shared)', perf_class_name) return _type[0] if _type else None def _create_qos_class(self, perf_class_name, specs): try: _type = self._get_type_from_perf_class_name(perf_class_name) if _type: self._call_xiv_xcli("perf_class_create", perf_class=perf_class_name, type=_type) else: self._call_xiv_xcli("perf_class_create", perf_class=perf_class_name) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = PERF_CLASS_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) try: args = self._qos_create_kwargs_for_xcli(specs) self._call_xiv_xcli("perf_class_set_rate", perf_class=perf_class_name, **args) return perf_class_name except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) self._call_xiv_xcli("perf_class_delete", perf_class=perf_class_name) msg = PERF_CLASS_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) def _qos_specs_from_volume(self, volume): type_id = volume.get('volume_type_id', None) if not type_id: return None return self._get_qos_specs(type_id) def _get_replication_info(self, specs): info, msg = repl.Replication.extract_replication_info_from_specs(specs) if not info: LOG.error(msg) raise self._get_exception()(message=msg) return info @proxy._trace_time def _create_volume(self, volume): size = storage.gigabytes_to_blocks(float(volume['size'])) pool = self._get_backend_pool() try: self._call_xiv_xcli( "vol_create", vol=volume['name'], size_blocks=size, pool=pool) except errors.SystemOutOfSpaceError: msg = _("Unable to create volume: System is out of space.") LOG.error(msg) raise self._get_exception()(msg) except errors.PoolOutOfSpaceError: msg = (_("Unable to create volume: pool '%(pool)s' is " "out of space.") % {'pool': pool}) LOG.error(msg) raise self._get_exception()(msg) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = (CREATE_VOLUME_BASE_ERROR, {'details': details}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) @proxy._trace_time def create_volume(self, volume): specs = self._get_extra_specs(volume.get('volume_type_id', None)) replication_info = self._get_replication_info(specs) self._create_volume(volume) return self.handle_created_vol_properties(replication_info, volume) def handle_created_vol_properties(self, replication_info, volume): volume_update = {} LOG.debug('checking replication_info %(rep)s', {'rep': replication_info}) volume_update['replication_status'] = 'disabled' cg = volume.group and utils.is_group_a_cg_snapshot_type(volume.group) if replication_info['enabled']: try: repl.VolumeReplication(self).create_replication( volume.name, replication_info) except Exception as e: details = self._get_code_and_status_or_message(e) msg = ('Failed create_replication for ' 'volume %(vol)s: %(err)s', {'vol': volume['name'], 'err': details}) LOG.error(msg) if cg: cg_name = self._cg_name_from_volume(volume) self._silent_delete_volume_from_cg(volume, cg_name) self._silent_delete_volume(volume=volume) raise volume_update['replication_status'] = 'enabled' if cg: if volume.group.is_replicated: group_specs = group_types.get_group_type_specs( volume.group.group_type_id) group_rep_info = self._get_replication_info(group_specs) msg = None if volume_update['replication_status'] != 'enabled': msg = ('Cannot add non-replicated volume into' ' replicated group') elif replication_info['mode'] != group_rep_info['mode']: msg = ('Volume replication type and Group replication type' ' should be the same') elif volume.host != volume.group.host: msg = 'Cannot add volume to Group on different host' elif volume.group['replication_status'] == 'enabled': group_name = self._cg_name_from_group(volume.group) me = mirrored_entities.MirroredEntities( self.ibm_storage_cli) me_objs = me.get_mirror_resources_by_name_map() vol_obj = me_objs['volumes'][volume.name] vol_sync_state = vol_obj['sync_state'] cg_sync_state = me_objs['cgs'][group_name]['sync_state'] if (vol_sync_state != 'Synchronized' or cg_sync_state != 'Synchronized'): msg = ('Cannot add volume to Group. Both volume and ' 'group should have sync_state = Synchronized') if msg: LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) try: cg_name = self._cg_name_from_volume(volume) self._call_xiv_xcli( "cg_add_vol", vol=volume['name'], cg=cg_name) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) self._silent_delete_volume(volume=volume) msg = (CREATE_VOLUME_BASE_ERROR, {'details': details}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) perf_class_name = None specs = self._qos_specs_from_volume(volume) if specs: try: perf_class_name = self._check_perf_class_on_backend(specs) if perf_class_name: self._call_xiv_xcli("perf_class_add_vol", vol=volume['name'], perf_class=perf_class_name) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) if cg: cg_name = self._cg_name_from_volume(volume) self._silent_delete_volume_from_cg(volume, cg_name) self._silent_delete_volume(volume=volume) msg = PERF_CLASS_ADD_ERROR % {'details': details} LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) return volume_update @proxy._trace_time def enable_replication(self, context, group, volumes): group_specs = group_types.get_group_type_specs(group.group_type_id) if not group_specs: msg = 'No group specs inside group type' LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) replication_info = self._get_replication_info(group_specs) if utils.is_group_a_cg_snapshot_type(group): if volumes: self._update_consistencygroup(context, group, remove_volumes=volumes) for volume in volumes: enabled_status = fields.ReplicationStatus.ENABLED if volume['replication_status'] != enabled_status: repl.VolumeReplication(self).create_replication( volume.name, replication_info) # mirror entire group group_name = self._cg_name_from_group(group) try: self._create_consistencygroup_on_remote(context, group_name) except errors.CgNameExistsError: LOG.debug("CG name %(cg)s exists, no need to open it on " "secondary backend.", {'cg': group_name}) repl.GroupReplication(self).create_replication(group_name, replication_info) updated_volumes = [] if volumes: # add volumes back to cg self._update_consistencygroup(context, group, add_volumes=volumes) for volume in volumes: updated_volumes.append( {'id': volume['id'], 'replication_status': fields.ReplicationStatus.ENABLED}) return ({'replication_status': fields.ReplicationStatus.ENABLED}, updated_volumes) else: # For generic groups we replicate all the volumes updated_volumes = [] for volume in volumes: repl.VolumeReplication(self).create_replication( volume.name, replication_info) # update status for volume in volumes: updated_volumes.append( {'id': volume['id'], 'replication_status': fields.ReplicationStatus.ENABLED}) return ({'replication_status': fields.ReplicationStatus.ENABLED}, updated_volumes) @proxy._trace_time def disable_replication(self, context, group, volumes): group_specs = group_types.get_group_type_specs(group.group_type_id) if not group_specs: msg = 'No group specs inside group type' LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) replication_info = self._get_replication_info(group_specs) updated_volumes = [] if utils.is_group_a_cg_snapshot_type(group): # one call deletes replication for cgs and volumes together. group_name = self._cg_name_from_group(group) repl.GroupReplication(self).delete_replication(group_name, replication_info) for volume in volumes: # xiv locks volumes after deletion of replication. # we need to unlock it for further use. try: self.ibm_storage_cli.cmd.vol_unlock(vol=volume.name) self.ibm_storage_remote_cli.cmd.vol_unlock( vol=volume.name) self.ibm_storage_remote_cli.cmd.cg_remove_vol( vol=volume.name) except errors.VolumeBadNameError: LOG.debug("Failed to delete vol %(vol)s - " "ignoring.", {'vol': volume.name}) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = ('Failed to unlock volumes %(details)s' % {'details': details}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) updated_volumes.append( {'id': volume.id, 'replication_status': fields.ReplicationStatus.DISABLED}) else: # For generic groups we replicate all the volumes updated_volumes = [] for volume in volumes: repl.VolumeReplication(self).delete_replication( volume.name, replication_info) # update status for volume in volumes: try: self.ibm_storage_cli.cmd.vol_unlock(vol=volume.name) self.ibm_storage_remote_cli.cmd.vol_unlock( vol=volume.name) except errors.XCLIError as e: details = self._get_code_and_status_or_message(e) msg = (_('Failed to unlock volumes %(details)s'), {'details': details}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) updated_volumes.append( {'id': volume['id'], 'replication_status': fields.ReplicationStatus.DISABLED}) return ({'replication_status': fields.ReplicationStatus.DISABLED}, updated_volumes) def get_secondary_backend_id(self, secondary_backend_id): if secondary_backend_id is None: secondary_backend_id = self._get_target() if secondary_backend_id is None: msg = _("No targets defined. Can't perform failover.") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) return secondary_backend_id def check_for_splitbrain(self, volumes, pool_master, pool_slave): if volumes: split_brain = self._potential_split_brain( self.ibm_storage_cli, self.ibm_storage_remote_cli, volumes, pool_master, pool_slave) if split_brain: msg = (_("A potential split brain condition has been found " "with the following volumes: \n'%(volumes)s.'") % {'volumes': split_brain}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) def failover_replication(self, context, group, volumes, secondary_backend_id): volumes_updated = [] goal_status = '' pool_master = None group_updated = {'replication_status': group.replication_status} LOG.info("failover_replication: of cg %(cg)s " "from %(active)s to %(id)s", {'cg': group.get('name'), 'active': self.active_backend_id, 'id': secondary_backend_id}) if secondary_backend_id == strings.PRIMARY_BACKEND_ID: if self._using_default_backend(): LOG.info("CG has been failed back. " "No need to fail back again.") return group_updated, volumes_updated pool_master = self._get_target_params( self.active_backend_id)['san_clustername'] pool_slave = self.storage_info[storage.FLAG_KEYS['storage_pool']] goal_status = 'enabled' vol_goal_status = 'available' else: if not self._using_default_backend(): LOG.info("cg already failed over.") return group_updated, volumes_updated secondary_backend_id = self.get_secondary_backend_id( secondary_backend_id) pool_master = self.storage_info[storage.FLAG_KEYS['storage_pool']] pool_slave = self._get_target_params( secondary_backend_id)['san_clustername'] goal_status = fields.ReplicationStatus.FAILED_OVER vol_goal_status = fields.ReplicationStatus.FAILED_OVER self.ibm_storage_remote_cli = self._init_xcli(secondary_backend_id) self.check_for_splitbrain(volumes, pool_master, pool_slave) group_specs = group_types.get_group_type_specs(group.group_type_id) if group_specs is None: msg = "No group specs found. Cannot failover." LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) failback = (secondary_backend_id == strings.PRIMARY_BACKEND_ID) result = False details = "" if utils.is_group_a_cg_snapshot_type(group): result, details = repl.GroupReplication(self).failover(group, failback) else: replicated_vols = [] for volume in volumes: result, details = repl.VolumeReplication(self).failover( volume, failback) if not result: break replicated_vols.append(volume) if not result: for volume in replicated_vols: result, details = repl.VolumeReplication(self).failover( volume, not failback) if result: status = goal_status group_updated['replication_status'] = status else: status = 'error' updates = {'status': vol_goal_status} if status == 'error': group_updated['replication_extended_status'] = details for volume in volumes: volumes_updated.append({ 'id': volume.id, 'updates': updates }) self._replace_xcli_to_remote_xcli() self.active_backend_id = secondary_backend_id return group_updated, volumes_updated def _replace_xcli_to_remote_xcli(self): temp_ibm_storage_cli = self.ibm_storage_cli self.ibm_storage_cli = self.ibm_storage_remote_cli self.ibm_storage_remote_cli = temp_ibm_storage_cli def _get_replication_target_params(self): LOG.debug('_get_replication_target_params.') if not self.targets: msg = _("No targets available for replication") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) no_of_targets = len(self.targets) if no_of_targets > 1: msg = _("Too many targets configured. Only one is supported") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) LOG.debug('_get_replication_target_params selecting target...') target = self._get_target() if not target: msg = _("No targets available for replication.") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) params = self._get_target_params(target) if not params: msg = (_("Missing target information for target '%(target)s'"), {'target': target}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) return target, params def _delete_volume(self, vol_name): LOG.debug("_delete_volume: %(volume)s", {'volume': vol_name}) try: self._call_xiv_xcli("vol_delete", vol=vol_name) except errors.VolumeBadNameError: # to set the volume as deleted if it's not available LOG.info("Volume '%(volume)s' not found on storage", {'volume': vol_name}) def _silent_delete_volume(self, volume): try: self._delete_volume(vol_name=volume['name']) except errors.XCLIError as e: error = self._get_code_and_status_or_message(e) LOG.error(DELETE_VOLUME_BASE_ERROR, {'volume': volume['name'], 'error': error}) def _silent_delete_volume_from_cg(self, volume, cgname): try: self._call_xiv_xcli( "cg_remove_vol", vol=volume['name']) except errors.XCLIError as e: LOG.error("Failed removing volume %(vol)s from " "consistency group %(cg)s: %(err)s", {'vol': volume['name'], 'cg': cgname, 'err': self._get_code_and_status_or_message(e)}) self._silent_delete_volume(volume=volume) @proxy._trace_time def delete_volume(self, volume): LOG.debug("delete_volume: %(volume)s", {'volume': volume['name']}) specs = self._get_extra_specs(volume.get('volume_type_id', None)) replication_info = self._get_replication_info(specs) if replication_info['enabled']: try: repl.VolumeReplication(self).delete_replication( volume.name, replication_info) except Exception as e: error = self._get_code_and_status_or_message(e) LOG.error(DELETE_VOLUME_BASE_ERROR, {'volume': volume['name'], 'error': error}) target = None try: target, params = self._get_replication_target_params() LOG.info('Target %(target)s: %(params)s', {'target': target, 'params': params}) except Exception as e: LOG.error("Unable to delete replicated volume " "'%(volume)s': %(error)s.", {'error': self._get_code_and_status_or_message(e), 'volume': volume['name']}) if target: try: self._call_remote_xiv_xcli( "vol_delete", vol=volume['name']) except errors.XCLIError as e: LOG.error( "Unable to delete replicated volume " "'%(volume)s': %(error)s.", {'error': self._get_code_and_status_or_message(e), 'volume': volume['name']}) try: self._delete_volume(volume['name']) except errors.XCLIError as e: LOG.error(DELETE_VOLUME_BASE_ERROR, {'volume': volume['name'], 'error': self._get_code_and_status_or_message(e)}) @proxy._trace_time def initialize_connection(self, volume, connector): connection_type = self._get_connection_type() LOG.debug("initialize_connection: %(volume)s %(connector)s" " connection_type: %(connection_type)s", {'volume': volume['name'], 'connector': connector, 'connection_type': connection_type}) fc_targets, host = self._get_host_and_fc_targets( volume, connector) lun_id = self._vol_map_and_get_lun_id( volume, connector, host) meta = { 'driver_volume_type': connection_type, 'data': { 'target_discovered': True, 'target_lun': lun_id, 'volume_id': volume['id'], }, } if connection_type == storage.XIV_CONNECTION_TYPE_ISCSI: meta['data']['target_portal'] = self.meta['ibm_storage_portal'] meta['data']['target_iqn'] = self.meta['ibm_storage_iqn'] meta['data']['provider_location'] = "%s,1 %s %s" % ( self.meta['ibm_storage_portal'], self.meta['ibm_storage_iqn'], lun_id) chap_type = self._get_chap_type() LOG.debug("initialize_connection: %(volume)s." " chap_type:%(chap_type)s", {'volume': volume['name'], 'chap_type': chap_type}) if chap_type == storage.CHAP_ENABLED: chap = self._create_chap(host) meta['data']['auth_method'] = 'CHAP' meta['data']['auth_username'] = chap[0] meta['data']['auth_password'] = chap[1] else: all_storage_wwpns = self._get_fc_targets(None) meta['data']['all_storage_wwpns'] = all_storage_wwpns modules = set() for wwpn in fc_targets: modules.add(wwpn[-2]) meta['data']['recommended_connections'] = ( len(modules) * CONNECTIONS_PER_MODULE) meta['data']['target_wwn'] = fc_targets if fc_targets == []: fc_targets = all_storage_wwpns meta['data']['initiator_target_map'] = ( self._build_initiator_target_map(fc_targets, connector)) LOG.debug(six.text_type(meta)) return meta @proxy._trace_time def terminate_connection(self, volume, connector): LOG.debug("terminate_connection: %(volume)s %(connector)s", {'volume': volume['name'], 'connector': connector}) host = self._get_host(connector) if host is None: LOG.error(TERMINATE_CONNECTION_BASE_ERROR, {'volume': volume['name'], 'error': "Host not found."}) return fc_targets = {} if self._get_connection_type() == storage.XIV_CONNECTION_TYPE_FC: fc_targets = self._get_fc_targets(host) try: self._call_xiv_xcli( "unmap_vol", vol=volume['name'], host=host.get('name')) except errors.VolumeBadNameError: LOG.error(TERMINATE_CONNECTION_BASE_ERROR, {'volume': volume['name'], 'error': "Volume not found."}) except errors.XCLIError as err: details = self._get_code_and_status_or_message(err) LOG.error(TERMINATE_CONNECTION_BASE_ERROR, {'volume': volume['name'], 'error': details}) host_mappings = [] try: host_mappings = self._call_xiv_xcli( "mapping_list", host=host.get('name')).as_list if len(host_mappings) == 0: LOG.info("Terminate connection for volume '%(volume)s': " "%(host)s %(info)s.", {'volume': volume['name'], 'host': host.get('name'), 'info': "will be deleted"}) if not self._is_iscsi(): meta = { 'driver_volume_type': self._get_connection_type(), 'data': {'volume_id': volume['id'], }, } meta['data']['target_wwn'] = fc_targets meta['data']['initiator_target_map'] = ( self._build_initiator_target_map(fc_targets, connector)) self._call_xiv_xcli("host_delete", host=host.get('name')) if not self._is_iscsi(): return meta return None else: LOG.debug(("Host '%(host)s' has additional mapped " "volumes %(mappings)s"), {'host': host.get('name'), 'mappings': host_mappings}) except errors.HostBadNameError: LOG.error(TERMINATE_CONNECTION_HOST_ERROR, {'volume': volume['name'], 'host': host.get('name'), 'error': "Host not found."}) except errors.XCLIError as err: details = self._get_code_and_status_or_message(err) LOG.error(TERMINATE_CONNECTION_HOST_ERROR, {'volume': volume['name'], 'host': host.get('name'), 'error': details}) def _create_volume_from_snapshot(self, volume, snapshot_name, snapshot_size): LOG.debug("_create_volume_from_snapshot: %(volume)s from %(name)s", {'volume': volume['name'], 'name': snapshot_name}) volume_size = float(volume['size']) if volume_size < snapshot_size: error = (_("Volume size (%(vol_size)sGB) cannot be smaller than " "the snapshot size (%(snap_size)sGB)..") % {'vol_size': volume_size, 'snap_size': snapshot_size}) LOG.error(error) raise self._get_exception()(error) self.create_volume(volume) try: self._call_xiv_xcli( "vol_copy", vol_src=snapshot_name, vol_trg=volume['name']) except errors.XCLIError as e: error = (_("Fatal error in copying volume: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) self._silent_delete_volume(volume) raise self._get_exception()(error) if snapshot_size == volume_size: return size = storage.gigabytes_to_blocks(volume_size) try: self._call_xiv_xcli( "vol_resize", vol=volume['name'], size_blocks=size) except errors.XCLIError as e: error = (_("Fatal error in resize volume: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) self._silent_delete_volume(volume) raise self._get_exception()(error) @proxy._trace_time def create_volume_from_snapshot(self, volume, snapshot): snapshot_size = float(snapshot['volume_size']) self._create_volume_from_snapshot(volume, snapshot.name, snapshot_size) @proxy._trace_time def create_snapshot(self, snapshot): try: self._call_xiv_xcli( "snapshot_create", vol=snapshot['volume_name'], name=snapshot['name']) except errors.XCLIError as e: error = (_("Fatal error in snapshot_create: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) @proxy._trace_time def delete_snapshot(self, snapshot): try: self._call_xiv_xcli( "snapshot_delete", snapshot=snapshot['name']) except errors.XCLIError as e: error = (_("Fatal error in snapshot_delete: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) @proxy._trace_time def extend_volume(self, volume, new_size): volume_size = float(volume['size']) wanted_size = float(new_size) if wanted_size == volume_size: return shrink = 'yes' if wanted_size < volume_size else 'no' size = storage.gigabytes_to_blocks(wanted_size) try: self._call_xiv_xcli( "vol_resize", vol=volume['name'], size_blocks=size, shrink_volume=shrink) except errors.XCLIError as e: error = (_("Fatal error in vol_resize: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) @proxy._trace_time def migrate_volume(self, context, volume, host): false_ret = (False, None) if 'location_info' not in host['capabilities']: return false_ret info = host['capabilities']['location_info'] try: dest, dest_host, dest_pool = info.split(':') except ValueError: return false_ret volume_host = volume.host.split('_')[1] if dest != strings.XIV_BACKEND_PREFIX or dest_host != volume_host: return false_ret if volume.attach_status == 'attached': LOG.info("Storage-assisted volume migration: Volume " "%(volume)s is attached", {'volume': volume.id}) try: self._call_xiv_xcli( "vol_move", vol=volume.name, pool=dest_pool) except errors.XCLIError as e: error = (_("Fatal error in vol_move: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) return (True, None) @proxy._trace_time def manage_volume(self, volume, reference): existing_volume = reference['source-name'] LOG.debug("manage_volume: %(volume)s", {'volume': existing_volume}) try: volumes = self._call_xiv_xcli( "vol_list", vol=existing_volume).as_list except errors.XCLIError as e: error = (MANAGE_VOLUME_BASE_ERROR % {'volume': existing_volume, 'error': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) if len(volumes) != 1: error = (MANAGE_VOLUME_BASE_ERROR % {'volume': existing_volume, 'error': 'Volume does not exist'}) LOG.error(error) raise self._get_exception()(error) volume['size'] = float(volumes[0]['size']) try: self._call_xiv_xcli( "vol_rename", vol=existing_volume, new_name=volume['name']) except errors.XCLIError as e: error = (MANAGE_VOLUME_BASE_ERROR % {'volume': existing_volume, 'error': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) return {} @proxy._trace_time def manage_volume_get_size(self, volume, reference): existing_volume = reference['source-name'] try: volumes = self._call_xiv_xcli( "vol_list", vol=existing_volume).as_list except errors.XCLIError as e: error = (_("Fatal error in vol_list: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) if len(volumes) != 1: error = (_("Volume %(volume)s is not available on storage") % {'volume': existing_volume}) LOG.error(error) raise self._get_exception()(error) return float(volumes[0]['size']) @proxy._trace_time def unmanage_volume(self, volume): pass @proxy._trace_time def get_replication_status(self, context, volume): pass def freeze_backend(self, context): pass def thaw_backend(self, context): pass def _using_default_backend(self): return ((self.active_backend_id is None) or (self.active_backend_id == strings.PRIMARY_BACKEND_ID)) def _is_vol_split_brain(self, xcli_master, xcli_slave, vol): mirror_master = xcli_master.cmd.mirror_list(vol=vol).as_list mirror_slave = xcli_slave.cmd.mirror_list(vol=vol).as_list if (len(mirror_master) == 1 and len(mirror_slave) == 1 and mirror_master[0].current_role == 'Master' and mirror_slave[0].current_role == 'Slave' and mirror_master[0].sync_state.lower() in SYNCHED_STATES): return False else: return True def _potential_split_brain(self, xcli_master, xcli_slave, volumes, pool_master, pool_slave): potential_split_brain = [] if xcli_master is None or xcli_slave is None: return potential_split_brain try: vols_master = xcli_master.cmd.vol_list( pool=pool_master).as_dict('name') except Exception: msg = "Failed getting information from the active storage." LOG.debug(msg) return potential_split_brain try: vols_slave = xcli_slave.cmd.vol_list( pool=pool_slave).as_dict('name') except Exception: msg = "Failed getting information from the target storage." LOG.debug(msg) return potential_split_brain vols_requested = set(vol['name'] for vol in volumes) common_vols = set(vols_master).intersection( set(vols_slave)).intersection(set(vols_requested)) for name in common_vols: if self._is_vol_split_brain(xcli_master=xcli_master, xcli_slave=xcli_slave, vol=name): potential_split_brain.append(name) return potential_split_brain @proxy._trace_time def failover_host(self, context, volumes, secondary_id, groups=None): volume_update_list = [] LOG.info("failover_host: from %(active)s to %(id)s", {'active': self.active_backend_id, 'id': secondary_id}) if secondary_id == strings.PRIMARY_BACKEND_ID: if self._using_default_backend(): LOG.info("Host has been failed back. No need " "to fail back again.") return self.active_backend_id, volume_update_list, [] pool_slave = self.storage_info[storage.FLAG_KEYS['storage_pool']] pool_master = self._get_target_params( self.active_backend_id)['san_clustername'] goal_status = 'available' else: if not self._using_default_backend(): LOG.info("Already failed over. No need to failover again.") return self.active_backend_id, volume_update_list, [] secondary_id = self.get_secondary_backend_id(secondary_id) pool_master = self.storage_info[storage.FLAG_KEYS['storage_pool']] try: pool_slave = self._get_target_params( secondary_id)['san_clustername'] except Exception: msg = _("Invalid target information. Can't perform failover") LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) pool_master = self.storage_info[storage.FLAG_KEYS['storage_pool']] goal_status = fields.ReplicationStatus.FAILED_OVER # connnect xcli to secondary storage according to backend_id by # calling _init_xcli with secondary_id self.ibm_storage_remote_cli = self._init_xcli(secondary_id) # get replication_info for all volumes at once if len(volumes): # check for split brain situations # check for files that are available on both volumes # and are not in an active mirroring relation self.check_for_splitbrain(volumes, pool_master, pool_slave) # loop over volumes and attempt failover for volume in volumes: LOG.debug("Attempting to failover '%(vol)s'", {'vol': volume['name']}) result, details = repl.VolumeReplication(self).failover( volume, failback=(secondary_id == strings.PRIMARY_BACKEND_ID)) if result: status = goal_status else: status = 'error' updates = {'status': status} if status == 'error': updates['replication_extended_status'] = details volume_update_list.append({ 'volume_id': volume['id'], 'updates': updates }) # set active xcli to secondary xcli self._replace_xcli_to_remote_xcli() # set active backend id to secondary id self.active_backend_id = secondary_id return secondary_id, volume_update_list, [] @proxy._trace_time def retype(self, ctxt, volume, new_type, diff, host): LOG.debug("retype: volume = %(vol)s type = %(ntype)s", {'vol': volume.get('display_name'), 'ntype': new_type['name']}) if 'location_info' not in host['capabilities']: return False info = host['capabilities']['location_info'] try: (dest, dest_host, dest_pool) = info.split(':') except ValueError: return False volume_host = volume.get('host').split('_')[1] if (dest != strings.XIV_BACKEND_PREFIX or dest_host != volume_host): return False pool_name = self._get_backend_pool() # if pool is different. else - we're on the same pool and retype is ok. if (pool_name != dest_pool): LOG.debug("retype: migrate volume %(vol)s to " "host=%(host)s, pool=%(pool)s", {'vol': volume.get('display_name'), 'host': dest_host, 'pool': dest_pool}) (mig_result, model) = self.migrate_volume( context=ctxt, volume=volume, host=host) if not mig_result: raise self.meta['exception'].VolumeBackendAPIException( data=PERF_CLASS_ADD_ERROR) old_specs = self._qos_specs_from_volume(volume) new_specs = self._get_qos_specs(new_type.get('id', None)) if not new_specs: if old_specs: LOG.debug("qos: removing qos class for %(vol)s.", {'vol': volume.display_name}) self._qos_remove_vol(volume) return True perf_class_name_old = self._check_perf_class_on_backend(old_specs) perf_class_name_new = self._check_perf_class_on_backend(new_specs) if perf_class_name_new != perf_class_name_old: self._qos_add_vol(volume, perf_class_name_new) return True @proxy._trace_time def _check_storage_version_for_qos_support(self): if self.meta['storage_version'] is None: self.meta['storage_version'] = self._call_xiv_xcli( "version_get").as_single_element.system_version if int(self.meta['storage_version'][0:2]) >= 12: return 'True' return 'False' @proxy._trace_time def _update_stats(self): LOG.debug("Entered XIVProxy::_update_stats:") self.meta['stat'] = {} connection_type = self._get_connection_type() backend_name = None if self.driver: backend_name = self.driver.configuration.safe_get( 'volume_backend_name') self.meta['stat']['reserved_percentage'] = ( self.driver.configuration.safe_get('reserved_percentage')) self.meta['stat']["volume_backend_name"] = ( backend_name or '%s_%s_%s_%s' % ( strings.XIV_BACKEND_PREFIX, self.storage_info[storage.FLAG_KEYS['address']], self.storage_info[storage.FLAG_KEYS['storage_pool']], connection_type)) self.meta['stat']["vendor_name"] = 'IBM' self.meta['stat']["driver_version"] = self.full_version self.meta['stat']["storage_protocol"] = connection_type self.meta['stat']['multiattach'] = False self.meta['stat']['group_replication_enabled'] = True self.meta['stat']['consistent_group_replication_enabled'] = True self.meta['stat']['QoS_support'] = ( self._check_storage_version_for_qos_support()) self.meta['stat']['location_info'] = ( ('%(destination)s:%(hostname)s:%(pool)s' % {'destination': strings.XIV_BACKEND_PREFIX, 'hostname': self.storage_info[storage.FLAG_KEYS['address']], 'pool': self.storage_info[storage.FLAG_KEYS['storage_pool']] })) self._retrieve_pool_stats(self.meta) if self.targets: self.meta['stat']['replication_enabled'] = True self.meta['stat']['replication_type'] = [SYNC, ASYNC] self.meta['stat']['rpo'] = repl.Replication.get_supported_rpo() self.meta['stat']['replication_count'] = len(self.targets) self.meta['stat']['replication_targets'] = [target for target in self.targets] self.meta['stat']['timestamp'] = datetime.datetime.utcnow() LOG.debug("Exiting XIVProxy::_update_stats: %(stat)s", {'stat': self.meta['stat']}) @proxy._trace_time def _get_pool(self): pool_name = self._get_backend_pool() pools = self._call_xiv_xcli( "pool_list", pool=pool_name).as_list if not pools: msg = (_( "Pool %(pool)s not available on storage") % {'pool': pool_name}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException(data=msg) return pools def _get_backend_pool(self): if self.active_backend_id == strings.PRIMARY_BACKEND_ID: return self.storage_info[storage.FLAG_KEYS['storage_pool']] else: return self._get_target_params( self.active_backend_id)['san_clustername'] def _retrieve_pool_stats(self, data): try: pools = self._get_pool() pool = pools[0] data['stat']['pool_name'] = pool.get('name') soft_size = pool.get('soft_size') if soft_size is None: soft_size = pool.get('size') hard_size = 0 else: hard_size = pool.hard_size data['stat']['total_capacity_gb'] = int(soft_size) data['stat']['free_capacity_gb'] = int( pool.get('empty_space_soft', pool.get('empty_space'))) data['stat']['thin_provisioning_support'] = ( 'True' if soft_size > hard_size else 'False') data['stat']['backend_state'] = 'up' except Exception as e: data['stat']['total_capacity_gb'] = 0 data['stat']['free_capacity_gb'] = 0 data['stat']['thin_provision'] = False data['stat']['backend_state'] = 'down' error = self._get_code_and_status_or_message(e) LOG.error(error) @proxy._trace_time def create_cloned_volume(self, volume, src_vref): specs = self._get_extra_specs(volume.get('volume_type_id', None)) replication_info = self._get_replication_info(specs) src_vref_size = float(src_vref['size']) volume_size = float(volume['size']) if volume_size < src_vref_size: error = (_("New volume size (%(vol_size)s GB) cannot be less" "than the source volume size (%(src_size)s GB)..") % {'vol_size': volume_size, 'src_size': src_vref_size}) LOG.error(error) raise self._get_exception()(error) self._create_volume(volume) try: self._call_xiv_xcli( "vol_copy", vol_src=src_vref['name'], vol_trg=volume['name']) except errors.XCLIError as e: error = (_("Failed to copy from '%(src)s' to '%(vol)s': " "%(details)s") % {'src': src_vref.get('name', ''), 'vol': volume.get('name', ''), 'details': self._get_code_and_status_or_message(e)}) LOG.error(error) self._silent_delete_volume(volume=volume) raise self._get_exception()(error) if src_vref_size != volume_size: size = storage.gigabytes_to_blocks(volume_size) try: self._call_xiv_xcli( "vol_resize", vol=volume['name'], size_blocks=size) except errors.XCLIError as e: error = (_("Fatal error in vol_resize: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) self._silent_delete_volume(volume=volume) raise self._get_exception()(error) self.handle_created_vol_properties(replication_info, volume) @proxy._trace_time def volume_exists(self, volume): return len(self._call_xiv_xcli( "vol_list", vol=volume['name']).as_list) > 0 def _cg_name_from_id(self, id): return "cg_%(id)s" % {'id': id} def _group_name_from_id(self, id): return "cgs_%(id)s" % {'id': id} def _cg_name_from_volume(self, volume): LOG.debug("_cg_name_from_volume: %(vol)s", {'vol': volume['name']}) cg_id = volume.get('group_id', None) if cg_id: cg_name = self._cg_name_from_id(cg_id) LOG.debug("Volume %(vol)s is in CG %(cg)s", {'vol': volume['name'], 'cg': cg_name}) return cg_name else: LOG.debug("Volume %(vol)s not in CG", {'vol': volume['name']}) return None def _cg_name_from_group(self, group): return self._cg_name_from_id(group['id']) def _cg_name_from_cgsnapshot(self, cgsnapshot): return self._cg_name_from_id(cgsnapshot['group_id']) def _group_name_from_cgsnapshot_id(self, cgsnapshot_id): return self._group_name_from_id(cgsnapshot_id) def _volume_name_from_cg_snapshot(self, cgs, vol): return ('%(cgs)s.%(vol)s' % {'cgs': cgs, 'vol': vol})[0:62] @proxy._trace_time def create_group(self, context, group): if utils.is_group_a_cg_snapshot_type(group): cgname = self._cg_name_from_group(group) return self._create_consistencygroup(context, cgname) raise NotImplementedError() def _create_consistencygroup(self, context, cgname): LOG.info("Creating consistency group %(name)s.", {'name': cgname}) try: self._call_xiv_xcli( "cg_create", cg=cgname, pool=self.storage_info[ storage.FLAG_KEYS['storage_pool']]).as_list except errors.CgNameExistsError as e: error = (_("consistency group %s already exists on backend") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.CgLimitReachedError as e: error = _("Reached Maximum number of consistency groups") LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = (_("Fatal error in cg_create: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) model_update = {'status': fields.GroupStatus.AVAILABLE} return model_update def _create_consistencygroup_on_remote(self, context, cgname): LOG.info("Creating consistency group %(name)s on secondary.", {'name': cgname}) try: self._call_remote_xiv_xcli( "cg_create", cg=cgname, pool=self.storage_info[ storage.FLAG_KEYS['storage_pool']]).as_list except errors.CgNameExistsError: model_update = {'status': fields.GroupStatus.AVAILABLE} except errors.CgLimitReachedError: error = _("Maximum number of consistency groups reached") LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = (_("Fatal error in cg_create on remote: %(details)s") % {'details': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) model_update = {'status': fields.GroupStatus.AVAILABLE} return model_update def _silent_cleanup_consistencygroup_from_src(self, context, group, volumes, cgname): for volume in volumes: self._silent_delete_volume_from_cg(volume=volume, cgname=cgname) try: self._delete_consistencygroup(context, group, []) except Exception as e: details = self._get_code_and_status_or_message(e) LOG.error('Failed to cleanup CG %(details)s', {'details': details}) @proxy._trace_time def create_group_from_src(self, context, group, volumes, group_snapshot, sorted_snapshots, source_group, sorted_source_vols): if utils.is_group_a_cg_snapshot_type(group): return self._create_consistencygroup_from_src(context, group, volumes, group_snapshot, sorted_snapshots, source_group, sorted_source_vols) else: raise NotImplementedError() def _create_consistencygroup_from_src(self, context, group, volumes, cgsnapshot, snapshots, source_cg, sorted_source_vols): cgname = self._cg_name_from_group(group) LOG.info("Creating consistency group %(cg)s from src.", {'cg': cgname}) volumes_model_update = [] if cgsnapshot and snapshots: LOG.debug("Creating from cgsnapshot %(cg)s", {'cg': self._cg_name_from_group(cgsnapshot)}) try: self._create_consistencygroup(context, cgname) except Exception as e: LOG.error( "Creating CG from cgsnapshot failed: %(details)s", {'details': self._get_code_and_status_or_message(e)}) raise created_volumes = [] try: groupname = self._group_name_from_cgsnapshot_id( cgsnapshot['id']) for volume, source in zip(volumes, snapshots): vol_name = source.volume_name LOG.debug("Original volume: %(vol_name)s", {'vol_name': vol_name}) snapshot_name = self._volume_name_from_cg_snapshot( groupname, vol_name) LOG.debug("create volume (vol)s from snapshot %(snap)s", {'vol': vol_name, 'snap': snapshot_name}) snapshot_size = float(source['volume_size']) self._create_volume_from_snapshot( volume, snapshot_name, snapshot_size) created_volumes.append(volume) volumes_model_update.append( { 'id': volume['id'], 'status': 'available', 'size': snapshot_size, }) except Exception as e: details = self._get_code_and_status_or_message(e) msg = (CREATE_VOLUME_BASE_ERROR % {'details': details}) LOG.error(msg) self._silent_cleanup_consistencygroup_from_src( context, group, created_volumes, cgname) raise self.meta['exception'].VolumeBackendAPIException( data=msg) elif source_cg and sorted_source_vols: LOG.debug("Creating from CG %(cg)s .", {'cg': self._cg_name_from_group(source_cg)}) LOG.debug("Creating from CG %(cg)s .", {'cg': source_cg['id']}) try: self._create_consistencygroup(context, group) except Exception as e: LOG.error("Creating CG from CG failed: %(details)s", {'details': self._get_code_and_status_or_message(e)}) raise created_volumes = [] try: for volume, source in zip(volumes, sorted_source_vols): self.create_cloned_volume(volume, source) created_volumes.append(volume) volumes_model_update.append( { 'id': volume['id'], 'status': 'available', 'size': source['size'], }) except Exception as e: details = self._get_code_and_status_or_message(e) msg = (CREATE_VOLUME_BASE_ERROR, {'details': details}) LOG.error(msg) self._silent_cleanup_consistencygroup_from_src( context, group, created_volumes, cgname) raise self.meta['exception'].VolumeBackendAPIException( data=msg) else: error = 'create_consistencygroup_from_src called without a source' raise self._get_exception()(error) model_update = {'status': fields.GroupStatus.AVAILABLE} return model_update, volumes_model_update @proxy._trace_time def delete_group(self, context, group, volumes): rep_status = group.get('replication_status') enabled = fields.ReplicationStatus.ENABLED failed_over = fields.ReplicationStatus.FAILED_OVER if rep_status == enabled or rep_status == failed_over: msg = _("Disable group replication before deleting group.") LOG.error(msg) raise self._get_exception()(msg) if utils.is_group_a_cg_snapshot_type(group): return self._delete_consistencygroup(context, group, volumes) else: raise NotImplementedError() def _delete_consistencygroup(self, context, group, volumes): cgname = self._cg_name_from_group(group) LOG.info("Deleting consistency group %(name)s.", {'name': cgname}) model_update = {} model_update['status'] = group.get('status', fields.GroupStatus.DELETING) volumes_model_update = [] for volume in volumes: try: self._call_xiv_xcli( "cg_remove_vol", vol=volume['name']) except errors.XCLIError as e: LOG.error("Failed removing volume %(vol)s from " "consistency group %(cg)s: %(err)s", {'vol': volume['name'], 'cg': cgname, 'err': self._get_code_and_status_or_message(e)}) try: self._delete_volume(volume['name']) volumes_model_update.append( { 'id': volume['id'], 'status': 'deleted', }) except errors.XCLIError as e: LOG.error(DELETE_VOLUME_BASE_ERROR, {'volume': volume['name'], 'error': self._get_code_and_status_or_message(e)}) model_update['status'] = fields.GroupStatus.ERROR_DELETING volumes_model_update.append( { 'id': volume['id'], 'status': 'error_deleting', }) if model_update['status'] != fields.GroupStatus.ERROR_DELETING: try: self._call_xiv_xcli( "cg_delete", cg=cgname).as_list model_update['status'] = fields.GroupStatus.DELETED except (errors.CgDoesNotExistError, errors.CgBadNameError): LOG.warning("consistency group %(cgname)s does not " "exist on backend", {'cgname': cgname}) model_update['status'] = fields.GroupStatus.DELETED except errors.CgHasMirrorError: error = (_("consistency group %s is being mirrored") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.CgNotEmptyError: error = (_("consistency group %s is not empty") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = (_("Fatal: %(code)s. CG: %(cgname)s") % {'code': self._get_code_and_status_or_message(e), 'cgname': cgname}) LOG.error(error) raise self._get_exception()(error) return model_update, volumes_model_update @proxy._trace_time def update_group(self, context, group, add_volumes=None, remove_volumes=None): if utils.is_group_a_cg_snapshot_type(group): return self._update_consistencygroup(context, group, add_volumes, remove_volumes) else: raise NotImplementedError() def _update_consistencygroup(self, context, group, add_volumes=None, remove_volumes=None): cgname = self._cg_name_from_group(group) LOG.info("Updating consistency group %(name)s.", {'name': cgname}) model_update = {'status': fields.GroupStatus.AVAILABLE} add_volumes_update = [] if add_volumes: for volume in add_volumes: try: self._call_xiv_xcli( "cg_add_vol", vol=volume['name'], cg=cgname) except errors.XCLIError as e: error = (_("Failed adding volume %(vol)s to " "consistency group %(cg)s: %(err)s") % {'vol': volume['name'], 'cg': cgname, 'err': self._get_code_and_status_or_message(e)}) LOG.error(error) self._cleanup_consistencygroup_update( context, group, add_volumes_update, None) raise self._get_exception()(error) add_volumes_update.append({'name': volume['name']}) remove_volumes_update = [] if remove_volumes: for volume in remove_volumes: try: self._call_xiv_xcli( "cg_remove_vol", vol=volume['name']) except (errors.VolumeNotInConsGroup, errors.VolumeBadNameError) as e: details = self._get_code_and_status_or_message(e) LOG.debug(details) except errors.XCLIError as e: error = (_("Failed removing volume %(vol)s from " "consistency group %(cg)s: %(err)s") % {'vol': volume['name'], 'cg': cgname, 'err': self._get_code_and_status_or_message(e)}) LOG.error(error) self._cleanup_consistencygroup_update( context, group, add_volumes_update, remove_volumes_update) raise self._get_exception()(error) remove_volumes_update.append({'name': volume['name']}) return model_update, None, None def _cleanup_consistencygroup_update(self, context, group, add_volumes, remove_volumes): if add_volumes: for volume in add_volumes: try: self._call_xiv_xcli( "cg_remove_vol", vol=volume['name']) except Exception: LOG.debug("cg_remove_vol(%s) failed", volume['name']) if remove_volumes: cgname = self._cg_name_from_group(group) for volume in remove_volumes: try: self._call_xiv_xcli( "cg_add_vol", vol=volume['name'], cg=cgname) except Exception: LOG.debug("cg_add_vol(%(name)s, %(cgname)s) failed", {'name': volume['name'], 'cgname': cgname}) @proxy._trace_time def create_group_snapshot(self, context, group_snapshot, snapshots): if utils.is_group_a_cg_snapshot_type(group_snapshot): return self._create_cgsnapshot(context, group_snapshot, snapshots) else: raise NotImplementedError() def _create_cgsnapshot(self, context, cgsnapshot, snapshots): model_update = {'status': fields.GroupSnapshotStatus.AVAILABLE} cgname = self._cg_name_from_cgsnapshot(cgsnapshot) groupname = self._group_name_from_cgsnapshot_id(cgsnapshot['id']) LOG.info("Creating snapshot %(group)s for CG %(cg)s.", {'group': groupname, 'cg': cgname}) try: self._call_xiv_xcli( "cg_snapshots_create", cg=cgname, snap_group=groupname).as_list except errors.CgDoesNotExistError as e: error = (_("Consistency group %s does not exist on backend") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.CgBadNameError as e: error = (_("Consistency group %s has an illegal name") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.SnapshotGroupDoesNotExistError as e: error = (_("Snapshot group %s has an illegal name") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.PoolSnapshotLimitReachedError as e: error = _("Reached maximum snapshots allocation size") LOG.error(error) raise self._get_exception()(error) except errors.CgEmptyError as e: error = (_("Consistency group %s is empty") % cgname) LOG.error(error) raise self._get_exception()(error) except (errors.MaxVolumesReachedError, errors.DomainMaxVolumesReachedError) as e: error = _("Reached Maximum number of volumes") LOG.error(error) raise self._get_exception()(error) except errors.SnapshotGroupIsReservedError as e: error = (_("Consistency group %s name is reserved") % cgname) LOG.error(error) raise self._get_exception()(error) except errors.SnapshotGroupAlreadyExistsError as e: error = (_("Snapshot group %s already exists") % groupname) LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = (_("Fatal: CG %(cg)s, Group %(group)s. %(err)s") % {'cg': cgname, 'group': groupname, 'err': self._get_code_and_status_or_message(e)}) LOG.error(error) raise self._get_exception()(error) snapshots_model_update = [] for snapshot in snapshots: snapshots_model_update.append( { 'id': snapshot['id'], 'status': fields.SnapshotStatus.AVAILABLE, }) return model_update, snapshots_model_update @proxy._trace_time def delete_group_snapshot(self, context, group_snapshot, snapshots): if utils.is_group_a_cg_snapshot_type(group_snapshot): return self._delete_cgsnapshot(context, group_snapshot, snapshots) else: raise NotImplementedError() def _delete_cgsnapshot(self, context, cgsnapshot, snapshots): cgname = self._cg_name_from_cgsnapshot(cgsnapshot) groupname = self._group_name_from_cgsnapshot_id(cgsnapshot['id']) LOG.info("Deleting snapshot %(group)s for CG %(cg)s.", {'group': groupname, 'cg': cgname}) try: self._call_xiv_xcli( "snap_group_delete", snap_group=groupname).as_list except errors.CgDoesNotExistError: error = _("consistency group %s not found on backend") % cgname LOG.error(error) raise self._get_exception()(error) except errors.PoolSnapshotLimitReachedError: error = _("Reached Maximum size allocated for snapshots") LOG.error(error) raise self._get_exception()(error) except errors.CgEmptyError: error = _("Consistency group %s is empty") % cgname LOG.error(error) raise self._get_exception()(error) except errors.XCLIError as e: error = _("Fatal: CG %(cg)s, Group %(group)s. %(err)s") % { 'cg': cgname, 'group': groupname, 'err': self._get_code_and_status_or_message(e) } LOG.error(error) raise self._get_exception()(error) model_update = {'status': fields.GroupSnapshotStatus.DELETED} snapshots_model_update = [] for snapshot in snapshots: snapshots_model_update.append( { 'id': snapshot['id'], 'status': fields.SnapshotStatus.DELETED, }) return model_update, snapshots_model_update def _generate_chap_secret(self, chap_name): name = chap_name chap_secret = "" while len(chap_secret) < 12: chap_secret = cryptish.encrypt(name)[:16] name = name + '_' LOG.debug("_generate_chap_secret: %(secret)s", {'secret': chap_secret}) return chap_secret @proxy._trace_time def _create_chap(self, host=None): if host: if host['chap']: chap_name = host['chap'][0] LOG.debug("_create_chap: %(chap_name)s ", {'chap_name': chap_name}) else: chap_name = host['name'] else: LOG.info("_create_chap: host missing!!!") chap_name = "12345678901234" chap_secret = self._generate_chap_secret(chap_name) LOG.debug("_create_chap (new): %(chap_name)s ", {'chap_name': chap_name}) return (chap_name, chap_secret) @proxy._trace_time def _get_host(self, connector): try: host_bunch = self._get_bunch_from_host(connector) except Exception as e: details = self._get_code_and_status_or_message(e) msg = (_("%(prefix)s. Invalid connector: '%(details)s.'") % {'prefix': storage.XIV_LOG_PREFIX, 'details': details}) raise self._get_exception()(msg) host = [] chap = None all_hosts = self._call_xiv_xcli("host_list").as_list if self._get_connection_type() == storage.XIV_CONNECTION_TYPE_ISCSI: host = [host_obj for host_obj in all_hosts if host_bunch['initiator'] in host_obj.iscsi_ports.split(',')] else: if 'wwpns' in connector: if len(host_bunch['wwpns']) > 0: wwpn_set = set([wwpn.lower() for wwpn in host_bunch['wwpns']]) host = [host_obj for host_obj in all_hosts if len(wwpn_set.intersection(host_obj.get( 'fc_ports', '').lower().split(','))) > 0] else: host = [host_obj for host_obj in all_hosts if host_obj.get('name', '') == connector['host']] if len(host) == 1: if self._is_iscsi() and host[0].iscsi_chap_name: chap = (host[0].iscsi_chap_name, self._generate_chap_secret(host[0].iscsi_chap_name)) LOG.debug("_get_host: chap_name %(chap_name)s ", {'chap_name': host[0].iscsi_chap_name}) return self._get_bunch_from_host( connector, host[0].id, host[0].name, chap) LOG.debug("_get_host: returns None") return None @proxy._trace_time def _call_host_define(self, host, chap_name=None, chap_secret=None, domain_name=None): LOG.debug("host_define with domain: %s)", domain_name) if domain_name: if chap_name: return self._call_xiv_xcli( "host_define", host=host, iscsi_chap_name=chap_name, iscsi_chap_secret=chap_secret, domain=domain_name ).as_list[0] else: return self._call_xiv_xcli( "host_define", host=host, domain=domain_name ).as_list[0] else: if chap_name: return self._call_xiv_xcli( "host_define", host=host, iscsi_chap_name=chap_name, iscsi_chap_secret=chap_secret ).as_list[0] else: return self._call_xiv_xcli( "host_define", host=host ).as_list[0] @proxy._trace_time def _define_host_according_to_chap(self, host, in_domain): chap_name = None chap_secret = None if (self._get_connection_type() == storage.XIV_CONNECTION_TYPE_ISCSI and self._get_chap_type() == storage.CHAP_ENABLED): host_bunch = {'name': host, 'chap': None, } chap = self._create_chap(host=host_bunch) chap_name = chap[0] chap_secret = chap[1] LOG.debug("_define_host_according_to_chap: " "%(name)s : %(secret)s", {'name': chap_name, 'secret': chap_secret}) return self._call_host_define( host=host, chap_name=chap_name, chap_secret=chap_secret, domain_name=in_domain) def _define_ports(self, host_bunch): fc_targets = [] LOG.debug(host_bunch.get('name')) if self._get_connection_type() == storage.XIV_CONNECTION_TYPE_ISCSI: self._define_iscsi(host_bunch) else: fc_targets = self._define_fc(host_bunch) fc_targets = list(set(fc_targets)) fc_targets.sort(key=self._sort_last_digit) return fc_targets def _get_pool_domain(self, connector): pool_name = self._get_backend_pool() LOG.debug("pool name from configuration: %s", pool_name) domain = None try: domain = self._call_xiv_xcli( "pool_list", pool=pool_name).as_list[0].get('domain') LOG.debug("Pool's domain: %s", domain) except AttributeError: pass return domain @proxy._trace_time def _define_host(self, connector): domain = self._get_pool_domain(connector) host_bunch = self._get_bunch_from_host(connector) host = self._call_xiv_xcli( "host_list", host=host_bunch['name']).as_list connection_type = self._get_connection_type() if len(host) == 0: LOG.debug("Non existing host, defining") host = self._define_host_according_to_chap( host=host_bunch['name'], in_domain=domain) host_bunch = self._get_bunch_from_host(connector, host.get('id')) else: host_bunch = self._get_bunch_from_host(connector, host[0].get('id')) LOG.debug("Generating hostname for connector %(conn)s", {'conn': connector}) generated_hostname = storage.get_host_or_create_from_iqn( connector, connection=connection_type) generated_host = self._call_xiv_xcli( "host_list", host=generated_hostname).as_list if len(generated_host) == 0: host = self._define_host_according_to_chap( host=generated_hostname, in_domain=domain) else: host = generated_host[0] host_bunch = self._get_bunch_from_host( connector, host.get('id'), host_name=generated_hostname) LOG.debug("The host_bunch: %s", host_bunch) return host_bunch @proxy._trace_time def _define_fc(self, host_bunch): fc_targets = [] if len(host_bunch.get('wwpns')) > 0: connected_wwpns = [] for wwpn in host_bunch.get('wwpns'): component_ids = list(set( [p.component_id for p in self._call_xiv_xcli( "fc_connectivity_list", wwpn=wwpn.replace(":", ""))])) wwpn_fc_target_lists = [] for component in component_ids: wwpn_fc_target_lists += [fc_p.wwpn for fc_p in self._call_xiv_xcli( "fc_port_list", fcport=component)] LOG.debug("got %(tgts)s fc targets for wwpn %(wwpn)s", {'tgts': wwpn_fc_target_lists, 'wwpn': wwpn}) if len(wwpn_fc_target_lists) > 0: connected_wwpns += [wwpn] fc_targets += wwpn_fc_target_lists LOG.debug("adding fc port %s", wwpn) self._call_xiv_xcli( "host_add_port", host=host_bunch.get('name'), fcaddress=wwpn) if len(connected_wwpns) == 0: LOG.error(CONNECTIVITY_FC_NO_TARGETS) all_target_ports = self._get_all_target_ports() fc_targets = list(set([target.get('wwpn') for target in all_target_ports])) else: msg = _("No Fibre Channel HBA's are defined on the host.") LOG.error(msg) raise self._get_exception()(msg) return fc_targets @proxy._trace_time def _define_iscsi(self, host_bunch): if host_bunch.get('initiator'): LOG.debug("adding iscsi") self._call_xiv_xcli( "host_add_port", host=host_bunch.get('name'), iscsi_name=host_bunch.get('initiator')) else: msg = _("No iSCSI initiator found!") LOG.error(msg) raise self._get_exception()(msg) @proxy._trace_time def _event_service_start(self): LOG.debug("send event SERVICE_STARTED") service_start_evnt_prop = { "openstack_version": self.meta['openstack_version'], "pool_name": self._get_backend_pool()} ev_mgr = events.EventsManager(self.ibm_storage_cli, OPENSTACK_PRODUCT_NAME, self.full_version) ev_mgr.send_event('SERVICE_STARTED', service_start_evnt_prop) @proxy._trace_time def _event_volume_attached(self): LOG.debug("send event VOLUME_ATTACHED") compute_host_name = socket.getfqdn() vol_attach_evnt_prop = { "openstack_version": self.meta['openstack_version'], "pool_name": self._get_backend_pool(), "compute_hostname": compute_host_name} ev_mgr = events.EventsManager(self.ibm_storage_cli, OPENSTACK_PRODUCT_NAME, self.full_version) ev_mgr.send_event('VOLUME_ATTACHED', vol_attach_evnt_prop) @proxy._trace_time def _build_initiator_target_map(self, fc_targets, connector): init_targ_map = {} wwpns = connector.get('wwpns', []) for initiator in wwpns: init_targ_map[initiator] = fc_targets LOG.debug("_build_initiator_target_map: %(init_targ_map)s", {'init_targ_map': init_targ_map}) return init_targ_map @proxy._trace_time def _get_host_and_fc_targets(self, volume, connector): LOG.debug("_get_host_and_fc_targets %(volume)s", {'volume': volume['name']}) fc_targets = [] host = self._get_host(connector) if not host: host = self._define_host(connector) fc_targets = self._define_ports(host) elif self._get_connection_type() == storage.XIV_CONNECTION_TYPE_FC: fc_targets = self._get_fc_targets(host) if len(fc_targets) == 0: LOG.error(CONNECTIVITY_FC_NO_TARGETS) raise self._get_exception()(CONNECTIVITY_FC_NO_TARGETS) return (fc_targets, host) def _vol_map_and_get_lun_id(self, volume, connector, host): vol_name = volume['name'] LOG.debug("_vol_map_and_get_lun_id %(volume)s", {'volume': vol_name}) try: mapped_vols = self._call_xiv_xcli( "vol_mapping_list", vol=vol_name).as_dict('host') if host['name'] in mapped_vols: LOG.info("Volume '%(volume)s' was already attached to " "the host '%(host)s'.", {'host': host['name'], 'volume': volume['name']}) return int(mapped_vols[host['name']].lun) except errors.VolumeBadNameError: LOG.error("Volume not found. '%s'", volume['name']) raise self.meta['exception'].VolumeNotFound(volume_id=volume['id']) used_luns = [int(mapped.get('lun')) for mapped in self._call_xiv_xcli( "mapping_list", host=host['name']).as_list] luns = six.moves.xrange(MIN_LUNID, MAX_LUNID) for lun_id in luns: if lun_id not in used_luns: self._call_xiv_xcli( "map_vol", lun=lun_id, host=host['name'], vol=vol_name) self._event_volume_attached() return lun_id msg = _("All free LUN IDs were already mapped.") LOG.error(msg) raise self._get_exception()(msg) @proxy._trace_time def _get_all_target_ports(self): all_target_ports = [] fc_port_list = self._call_xiv_xcli("fc_port_list") all_target_ports += ([t for t in fc_port_list if t.get('wwpn') != '0000000000000000' and t.get('role') == 'Target' and t.get('port_state') == 'Online']) return all_target_ports @proxy._trace_time def _get_fc_targets(self, host): target_wwpns = [] all_target_ports = self._get_all_target_ports() if host: host_conect_list = self._call_xiv_xcli("host_connectivity_list", host=host.get('name')) for connection in host_conect_list: fc_port = connection.get('local_fc_port') target_wwpns += ( [target.get('wwpn') for target in all_target_ports if target.get('component_id') == fc_port]) if not target_wwpns: LOG.debug('No fc targets found accessible to host: %s. Return list' ' of all available FC targets', host) target_wwpns = ([target.get('wwpn') for target in all_target_ports]) fc_targets = list(set(target_wwpns)) fc_targets.sort(key=self._sort_last_digit) LOG.debug("fc_targets : %s", fc_targets) return fc_targets def _sort_last_digit(self, a): return a[-1:] @proxy._trace_time def _get_xcli(self, xcli, backend_id): if self.meta['bypass_connection_check']: LOG.debug("_get_xcli(bypass mode)") else: if not xcli.is_connected(): xcli = self._init_xcli(backend_id) return xcli @proxy._trace_time def _call_xiv_xcli(self, method, *args, **kwargs): self.ibm_storage_cli = self._get_xcli( self.ibm_storage_cli, self.active_backend_id) if self.ibm_storage_cli: LOG.info("_call_xiv_xcli #1: %s", method) else: LOG.debug("_call_xiv_xcli #2: %s", method) return getattr(self.ibm_storage_cli.cmd, method)(*args, **kwargs) @proxy._trace_time def _call_remote_xiv_xcli(self, method, *args, **kwargs): remote_id = self._get_secondary_backend_id() if not remote_id: raise self._get_exception()(_("No remote backend found.")) self.ibm_storage_remote_cli = self._get_xcli( self.ibm_storage_remote_cli, remote_id) LOG.debug("_call_remote_xiv_xcli: %s", method) return getattr(self.ibm_storage_remote_cli.cmd, method)( *args, **kwargs) def _verify_xiv_flags(self, address, user, password): if not user or not password: raise self._get_exception()(_("No credentials found.")) if not address: raise self._get_exception()(_("No host found.")) def _get_connection_params(self, backend_id=strings.PRIMARY_BACKEND_ID): if not backend_id or backend_id == strings.PRIMARY_BACKEND_ID: if self._get_management_ips(): address = [e.strip(" ") for e in self.storage_info[ storage.FLAG_KEYS['management_ips']].split(",")] else: address = self.storage_info[storage.FLAG_KEYS['address']] user = self.storage_info[storage.FLAG_KEYS['user']] password = self.storage_info[storage.FLAG_KEYS['password']] else: params = self._get_target_params(backend_id) if not params: msg = (_("Missing target information for target '%(target)s'"), {'target': backend_id}) LOG.error(msg) raise self.meta['exception'].VolumeBackendAPIException( data=msg) if params.get('management_ips', None): address = [e.strip(" ") for e in params['management_ips'].split(",")] else: address = params['san_ip'] user = params['san_login'] password = params['san_password'] return (address, user, password) @proxy._trace_time def _init_xcli(self, backend_id=strings.PRIMARY_BACKEND_ID): try: address, user, password = self._get_connection_params(backend_id) except Exception as e: details = self._get_code_and_status_or_message(e) ex_details = (SETUP_BASE_ERROR, {'title': strings.TITLE, 'details': details}) LOG.error(ex_details) raise self.meta['exception'].InvalidParameterValue( (_("%(prefix)s %(ex_details)s") % {'prefix': storage.XIV_LOG_PREFIX, 'ex_details': ex_details})) self._verify_xiv_flags(address, user, password) try: clear_pass = cryptish.decrypt(password) except TypeError: ex_details = (SETUP_BASE_ERROR, {'title': strings.TITLE, 'details': "Invalid password."}) LOG.error(ex_details) raise self.meta['exception'].InvalidParameterValue( (_("%(prefix)s %(ex_details)s") % {'prefix': storage.XIV_LOG_PREFIX, 'ex_details': ex_details})) certs = certificate.CertificateCollector() path = certs.collect_certificate() try: LOG.debug('connect_multiendpoint_ssl with: %s', address) xcli = client.XCLIClient.connect_multiendpoint_ssl( user, clear_pass, address, ca_certs=path) except errors.CredentialsError: LOG.error(SETUP_BASE_ERROR, {'title': strings.TITLE, 'details': "Invalid credentials."}) raise self.meta['exception'].NotAuthorized() except (errors.ConnectionError, transports.ClosedTransportError): err_msg = (SETUP_INVALID_ADDRESS, {'address': address}) LOG.error(err_msg) raise self.meta['exception'].HostNotFound(host=err_msg) except Exception as er: err_msg = (SETUP_BASE_ERROR % {'title': strings.TITLE, 'details': er}) LOG.error(err_msg) raise self._get_exception()(err_msg) finally: certs.free_certificate() return xcli
true
true
f72d3224b042c8c5cc09ea30e0b80e5291a743e2
283
py
Python
source.py
kingsam91/Habari-zote
ab6e41bc37cfa86d319c1fd26e868c32e3712a26
[ "Unlicense" ]
null
null
null
source.py
kingsam91/Habari-zote
ab6e41bc37cfa86d319c1fd26e868c32e3712a26
[ "Unlicense" ]
null
null
null
source.py
kingsam91/Habari-zote
ab6e41bc37cfa86d319c1fd26e868c32e3712a26
[ "Unlicense" ]
null
null
null
class Source: """ Class that generates new instances of news api source results """ def __init__(self,id,name,category): ''' define properties for our objects ''' self.id = id self.name = name self.category = category
21.769231
65
0.568905
class Source: def __init__(self,id,name,category): self.id = id self.name = name self.category = category
true
true
f72d3258acf4addc09946484e264cdf03539e560
441
py
Python
Mundo_1/Ex012.py
alinenog/Mundo_Python-1-2-3
2cfda105eec436ae32394e01c011342515fceff5
[ "MIT" ]
null
null
null
Mundo_1/Ex012.py
alinenog/Mundo_Python-1-2-3
2cfda105eec436ae32394e01c011342515fceff5
[ "MIT" ]
null
null
null
Mundo_1/Ex012.py
alinenog/Mundo_Python-1-2-3
2cfda105eec436ae32394e01c011342515fceff5
[ "MIT" ]
null
null
null
# Exercício Python 12: # Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto. print('----------------------------') print(' LEITOR DE PREÇO ') print('----------------------------') print() vl = float(input('Digite o valor do produto? R$')) d = (vl * 5) /100 print('Preço do produto atual R$ {}'.format(vl)) print('|Preço do produto com 5% de desconto é R$ {:.2f}|'.format(vl-d))
40.090909
96
0.548753
print('----------------------------') print(' LEITOR DE PREÇO ') print('----------------------------') print() vl = float(input('Digite o valor do produto? R$')) d = (vl * 5) /100 print('Preço do produto atual R$ {}'.format(vl)) print('|Preço do produto com 5% de desconto é R$ {:.2f}|'.format(vl-d))
true
true
f72d32a6cc1842bfd53c17bfe61d760812d0fc52
3,981
py
Python
sina_spider/sina_spider/spiders/SinaSpider.py
lj28478416/Sina_News
13ef1d52ba5c81021cdf73370e12ec84777741e0
[ "Apache-2.0" ]
null
null
null
sina_spider/sina_spider/spiders/SinaSpider.py
lj28478416/Sina_News
13ef1d52ba5c81021cdf73370e12ec84777741e0
[ "Apache-2.0" ]
null
null
null
sina_spider/sina_spider/spiders/SinaSpider.py
lj28478416/Sina_News
13ef1d52ba5c81021cdf73370e12ec84777741e0
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import scrapy import os from ..items import SinaSpiderItem from ..settings import COOKIES import re class SinaspiderSpider(scrapy.Spider): name = 'SinaSpider' allowed_domains = ["sina.com",'sina.com.cn'] start_urls = ['http://www.sina.com.cn/'] def parse(self, response): first_lev_node_list = response.xpath("//div[@class='main-nav']/div")[0:5] for first_lev_node_ul in first_lev_node_list: first_lev_node_ul_list = first_lev_node_ul.xpath("./ul") for first_lev_node in first_lev_node_ul_list: first_lev_node_name = first_lev_node.xpath("./li/a/b/text()").extract_first() second_lev_node_list = first_lev_node.xpath("./li")[1:4] for second_lev_node in second_lev_node_list: item = SinaSpiderItem() # num += 1 second_lev_node_name = second_lev_node.xpath("./a/text()").extract_first() second_lev_node_url = second_lev_node.xpath("./a/@href").extract_first() if not os.path.exists(first_lev_node_name + "/" + second_lev_node_name): os.makedirs(first_lev_node_name + "/" + second_lev_node_name) item['path'] = first_lev_node_name + "/" + second_lev_node_name # print(num) # print(first_lev_node_name + "/" + second_lev_node_name) # print(item) # num_list.append(item) # print(num_list) # print(item['news_url']) yield scrapy.Request(second_lev_node_url, callback=self.parse_detil, meta={'item1': item}, cookies=COOKIES) # print("PARSE_URL----") def parse_detil(self, response): # print("PARSE_DETIAL", id(response)) item = response.meta["item1"] shtml_url_list = [] for news_url in response.xpath("//a/@href").extract(): if news_url.endswith('.shtml'): if news_url.startswith('http:'): news_url= news_url else: news_url = 'http:' + news_url shtml_url_list.append(news_url) for shtml_url in shtml_url_list: item['news_url'] = shtml_url yield scrapy.Request(shtml_url, callback=self.parse_news, meta={'item2': item}, cookies=COOKIES) # yield item def parse_news(self, response): # print("PARSE_NEWS", response.url) item = response.meta["item2"] if response.url.startswith('http://english.sina.com/'): news_name = response.xpath("//div[@id='artibodyTitle']/h1/text()").extract_first() if news_name: news_name =re.sub(r'<.*?>', '' , news_name) item['news_name'] = news_name news_detil = response.xpath("//div[@id='artibody']").extract()[0] if len(response.xpath("//div[@id='artibody']").extract()) else '' news_detil = re.sub(r'<.*?>', '', news_detil) item['news_detil'] = news_detil else: item['news_name'] = 'error' item['news_detil'] = '' else: news_name = response.xpath("//h1[@class='main-title']").extract_first() if news_name: news_name =re.sub(r'<.*?>', '' , news_name) item['news_name'] = news_name news_detil = response.xpath("//div[@id='artibody']").extract()[0] if len(response.xpath("//div[@id='artibody']").extract()) else '' news_detil = re.sub(r'<.*?>', '', news_detil) item['news_detil'] = news_detil else: item['news_name'] = 'error' item['news_detil']='' # print(news_detil) # item['news_detil'] = node_test.xpath("/string()").extract_first() yield item
47.963855
147
0.544587
import scrapy import os from ..items import SinaSpiderItem from ..settings import COOKIES import re class SinaspiderSpider(scrapy.Spider): name = 'SinaSpider' allowed_domains = ["sina.com",'sina.com.cn'] start_urls = ['http://www.sina.com.cn/'] def parse(self, response): first_lev_node_list = response.xpath("//div[@class='main-nav']/div")[0:5] for first_lev_node_ul in first_lev_node_list: first_lev_node_ul_list = first_lev_node_ul.xpath("./ul") for first_lev_node in first_lev_node_ul_list: first_lev_node_name = first_lev_node.xpath("./li/a/b/text()").extract_first() second_lev_node_list = first_lev_node.xpath("./li")[1:4] for second_lev_node in second_lev_node_list: item = SinaSpiderItem() second_lev_node_name = second_lev_node.xpath("./a/text()").extract_first() second_lev_node_url = second_lev_node.xpath("./a/@href").extract_first() if not os.path.exists(first_lev_node_name + "/" + second_lev_node_name): os.makedirs(first_lev_node_name + "/" + second_lev_node_name) item['path'] = first_lev_node_name + "/" + second_lev_node_name yield scrapy.Request(second_lev_node_url, callback=self.parse_detil, meta={'item1': item}, cookies=COOKIES) def parse_detil(self, response): item = response.meta["item1"] shtml_url_list = [] for news_url in response.xpath("//a/@href").extract(): if news_url.endswith('.shtml'): if news_url.startswith('http:'): news_url= news_url else: news_url = 'http:' + news_url shtml_url_list.append(news_url) for shtml_url in shtml_url_list: item['news_url'] = shtml_url yield scrapy.Request(shtml_url, callback=self.parse_news, meta={'item2': item}, cookies=COOKIES) def parse_news(self, response): item = response.meta["item2"] if response.url.startswith('http://english.sina.com/'): news_name = response.xpath("//div[@id='artibodyTitle']/h1/text()").extract_first() if news_name: news_name =re.sub(r'<.*?>', '' , news_name) item['news_name'] = news_name news_detil = response.xpath("//div[@id='artibody']").extract()[0] if len(response.xpath("//div[@id='artibody']").extract()) else '' news_detil = re.sub(r'<.*?>', '', news_detil) item['news_detil'] = news_detil else: item['news_name'] = 'error' item['news_detil'] = '' else: news_name = response.xpath("//h1[@class='main-title']").extract_first() if news_name: news_name =re.sub(r'<.*?>', '' , news_name) item['news_name'] = news_name news_detil = response.xpath("//div[@id='artibody']").extract()[0] if len(response.xpath("//div[@id='artibody']").extract()) else '' news_detil = re.sub(r'<.*?>', '', news_detil) item['news_detil'] = news_detil else: item['news_name'] = 'error' item['news_detil']='' yield item
true
true
f72d3365da66cf6a696526d674b481da1da66e77
22,009
py
Python
LibBookbuilder/chapter.py
Siyavula/bookbuilder
484f344a6b536d01ed51ea719f47c68aae654d5d
[ "MIT" ]
1
2015-07-18T16:24:36.000Z
2015-07-18T16:24:36.000Z
LibBookbuilder/chapter.py
Siyavula/bookbuilder
484f344a6b536d01ed51ea719f47c68aae654d5d
[ "MIT" ]
2
2016-02-04T18:26:39.000Z
2019-05-09T12:23:16.000Z
LibBookbuilder/chapter.py
Siyavula/bookbuilder
484f344a6b536d01ed51ea719f47c68aae654d5d
[ "MIT" ]
1
2016-01-31T22:26:27.000Z
2016-01-31T22:26:27.000Z
"""Class to handle chapter processing for books.""" from __future__ import print_function import os import logging import hashlib import subprocess import inspect import copy import lxml from lxml import etree try: from termcolor import colored except ImportError: logging.error("Please install termcolor:\n sudo pip install termcolor") from XmlValidator import XmlValidator from XmlValidator import XmlValidationError from . import htmlutils import imageutils from utils import mkdir_p, copy_if_newer, TOCBuilder, TocElement, add_unique_ids specpath = os.path.join(os.path.dirname(inspect.getfile(XmlValidator)), 'spec.xml') DEBUG = False def print_debug_msg(msg): """Print a debug message if DEBUG is True.""" if DEBUG: print(colored("DEBUG: {msg}".format(msg=msg), "yellow")) class chapter(object): """Class to represent a single chapter.""" def __init__(self, cnxmlplusfile, **kwargs): """Cnxmlplusfile is the path of the file.""" # set some default attributes. self.file = cnxmlplusfile self.chapter_number = None self.title = None self.hash = None self.has_changed = True self.valid = None self.conversion_success = {'tex': False, 'html': False, 'xhtml': False, 'mobile': False, 'html5': False} # set attributes from keyword arguments # This can be used to set precomputed values e.g. read from a cache for key, value in kwargs.items(): setattr(self, key, value) if not self.render_problems: # if this has not been instantiated yet create an empty # dict to keep track of image rendering success for every output # format. Make all True to force image generation on first go. self.render_problems = {'tex': True, 'html': True, 'xhtml': True, 'mobile': True, 'html5': True} # Parse the xml self.parse_cnxmlplus() def calculate_hash(self, content): """Calculate the md5 hash of the file content and returns it.""" m = hashlib.md5() m.update(content) return m.hexdigest() def parse_cnxmlplus(self): """Parse the xml file and save some information.""" with open(self.file, 'r') as f_in: content = f_in.read() if (self.hash is None) or (self.valid is False): self.hash = self.calculate_hash(content) # if the hash is None, it has not been passed from Book class and # hence didn't exist in the cache. Need to validate this file self.validate() else: # If self.hash has been set and it differs from current hash, then # re-validate current_hash = self.calculate_hash(content) if self.hash != current_hash: self.validate() self.hash = current_hash self.has_changed = True else: # file is valid, no validation required. self.valid = True self.hash = current_hash self.has_changed = False try: xml = etree.XML(content) except lxml.etree.XMLSyntaxError: logging.error( colored("{file} is not valid XML!".format( file=self.file), 'red')) return None # save the number try: self.chapter_number = int(self.file[0:self.file.index('-')]) except: self.chapter_number = 'N/A' logging.warn( "{file} doesn't follow naming convention \ CC-title-here.cnxmlplus".format(file=self.file)) # The title should be in in an element called <title> # inside a <section type="chapter"> and there should only be one in the # file. For now. chapters = xml.findall('.//section[@type="chapter"]') if len(chapters) > 1: logging.error( "{filename} contains more than 1 chapter!".format( filename=self.file)) elif len(chapters) < 1: logging.error( "{filename} contains no chapters!".format(filename=self.file)) else: self.title = chapters[0].find('.//title').text def info(self): """Return a formatted string with all the details of the chapter.""" info = '{ch}'.format(ch=self.chapter_number) info += ' ' * (4 - len(info)) if self.valid: info += colored('OK'.center(8), 'green') else: info += colored('Not OK'.center(8), 'red') info += ' ' * (24 - len(info)) info += '{file}'.format(file=self.file) return info def validate(self): """ Run the validator on this file. Set self.valid to True or False depending on the outcome. """ print("Validating {f}".format(f=self.file)) with open(self.file, 'r') as xmlfile: xml = xmlfile.read() # see if it is valid XML first try: etree.XML(xml) except etree.XMLSyntaxError: self.valid = False return # create an instance of the Validator xmlValidator = XmlValidator(open(specpath, 'rt').read()) try: xmlValidator.validate(xml) self.valid = True except XmlValidationError as err: print(err) self.valid = False def __xml_preprocess(self, xml): """ Prepare the xml for processing. This is an internal method for the chapter class that tweaks the cnxmlplus before it is converted to one of the output formats e.g. image links are changed to point one folder up so that the output files in the build folder points to where the current images are located. This method is called from the convert method. input: cnxmlplus is an etree object of the cnxmlplus file output: etree object with pr """ processed_xml = xml return processed_xml def __copy_tex_images(self, build_folder, output_path): """ Copy tex images. Find all images referenced in the cnxmlplus document and copy them to their correct relative places in the build/tex folder. """ success = True with open(self.file) as f_in: xml = etree.XML(f_in.read()) # if it is tex, we can copy the images referenced in the cnxmlplus # directly to the build/tex folder for image in xml.findall('.//image'): # find the src, it may be an attribute or a child element if 'src' in image.attrib: src = image.attrib['src'].strip() else: src = image.find('.//src').text.strip() # check for paths starting with / if src.startswith('/'): print(colored("ERROR! image paths may not start with /: ", "red") + src) success = False continue dest = os.path.join(build_folder, 'tex', src) if not os.path.exists(dest): try: mkdir_p(os.path.dirname(dest)) except OSError: msg = colored("WARNING! {dest} is not allowed!" .format(dest=dest), "magenta") success = False print(msg) success = copy_if_newer(src, dest) return success def __render_pstikz(self, output_path, parallel=True): """ Render the pstikz images. Use Bookbuilder/pstricks2png to render each pstricks and tikz image to png. Insert replace div.alternate tags with <img> tags Also, find pstricks and tikz in tex output and replace with includegraphics{}. """ rendered = imageutils.render_images(output_path, parallel=parallel) return rendered def __copy_html_images(self, build_folder, output_path): """ Copy html images. Find all images referenced in the converted html document and copy them to their correct relative places in the build/tex folder. """ success = True # copy images directly included in cnxmlplus to the output folder with open(output_path, 'r') as f_in: html = etree.HTML(f_in.read()) for img in html.findall('.//img'): src = img.attrib['src'] dest = os.path.join(os.path.dirname(output_path), src) if not os.path.exists(src) and (not os.path.exists(dest)): print_debug_msg(src + " doesn't exist") success = copy_if_newer(src, dest) return success def __tolatex(self): """Convert this chapter to latex.""" print_debug_msg("Entered __tolatex {f}".format(f=self.file)) myprocess = subprocess.Popen(["cnxmlplus2latex", self.file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) latex, err = myprocess.communicate() return latex def __tohtml(self): """Convert this chapter to html.""" print_debug_msg("Entered __tohtml {f}".format(f=self.file)) # tohtmlpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), # 'tohtml.py') myprocess = subprocess.Popen(["cnxmlplus2html", self.file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) html, err = myprocess.communicate() # html = htmlutils.add_mathjax(html) html = htmlutils.repair_equations(html) return html def __tohtml5(self): ''' Convert this chapter to latex ''' print_debug_msg("Entered __tohtml5 {f}".format(f=self.file)) # tohtmlpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), # 'tohtml.py') myprocess = subprocess.Popen(["cnxmlplus2html5", self.file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) html, err = myprocess.communicate() # html = htmlutils.add_mathjax(html) html = htmlutils.repair_equations(html) return html def __toxhtml(self): """Convert this chapter to xhtml.""" xhtml = self.__tohtml() # Convert this html to xhtml xhtml = htmlutils.xhtml_cleanup(xhtml) return xhtml def __tomobile(self): """Convert this chapter to mobile.""" html = self.__toxhtml() return html def convert(self, build_folder, output_format, parallel=True): """Convert the chapter to the specified output format. Write to the build folder: {build_folder}/{output_format}/self.file.{format} e.g. build/tex/chapter1.cnxmlplus.tex as needed. output_format: one of 'tex', 'html'. """ conversion_functions = {'tex': self.__tolatex, 'html': self.__tohtml, 'xhtml': self.__toxhtml, 'mobile': self.__tomobile, 'html5': self.__tohtml5} for outformat in output_format: # convert this chapter to the specified format # call the converted method output_path = os.path.join(build_folder, outformat, self.file + '.{f}'.format(f=outformat)) if outformat == 'mobile': output_path = output_path.replace(r'.mobile', '.html') if outformat == 'html5': output_path = output_path.replace(r'.html5', '.html') # only try this on valid cnxmlplus files if self.valid: # run the conversion only if the file has changed OR if it # doesn't exist (it may have been deleted manually) if any((self.has_changed, not os.path.exists(output_path), self.render_problems)): mkdir_p(os.path.dirname(output_path)) print("Converting {ch} to {form}".format(ch=self.file, form=outformat)) converted = conversion_functions[outformat]() with open(output_path, 'w') as f_out: # This is a bit of a hack, not quite sure why I need # this if outformat == 'html' or outformat == 'html5': f_out.write(converted.encode('utf-8')) else: f_out.write(converted) # file has not changed AND the file exists elif (not self.has_changed) and (os.path.exists(output_path)): print("{f} {space} done {form}" .format(f=self.file, space=' ' * (40 - len(self.file)), form=outformat)) # copy the images to the build folder even if the file has not # changed and is still valid, the image may have been copied in # by the user if outformat == 'tex': copy_success = self.__copy_tex_images(build_folder, output_path) rendered = self.__render_pstikz(output_path, parallel=parallel) elif outformat == 'html': # copy images included to the output folder copy_success = self.__copy_html_images(build_folder, output_path) # read the output html, find all pstricks and tikz # code blocks and render them as pngs and include them # in <img> tags in the html rendered = self.__render_pstikz(output_path, parallel=parallel) elif outformat == 'xhtml': # copy images from html folder copy_success = self.__copy_html_images(build_folder, output_path) rendered = self.__render_pstikz(output_path, parallel=parallel) elif outformat == 'mobile': # copy images from html folder copy_success = self.__copy_html_images(build_folder, output_path) rendered = self.__render_pstikz(output_path, parallel=parallel) elif outformat == 'html5': # copy images from html folder copy_success = self.__copy_html_images(build_folder, output_path) rendered = self.__render_pstikz(output_path, parallel=parallel) if not (rendered and copy_success): self.render_problems = True else: self.render_problems = False def split_into_sections(self, formats=None): """ Split this chapter into seperate files, each containing a section. The first one contains the h1 element for the chapter too """ if formats is None: formats = ['html', 'xhtml', 'mobile', 'html5'] for form in formats: if 'tex' in form: continue if form == 'xhtml': ext = '.xhtml' else: ext = '.html' chapterfilepath = os.path.join('build', form, self.file + ext) with open(chapterfilepath) as chapterfile: html = etree.HTML(chapterfile.read()) # add unique IDs to all the section titles. html = add_unique_ids(html) # make a copy of the html, want to use as template. html_template = copy.deepcopy(html) for bodychild in html_template.find('.//body'): bodychild.getparent().remove(bodychild) if form != 'html5': # build up a list of the sections sections = [] chapter = [c.getparent() for c in html.findall('.//div[@class="section"]/h1')][0] thissection = [] for child in chapter: if (child.tag != 'div'): thissection.append(child) else: if len(child) == 0: pass elif (child[0].tag == 'h2') or (child.attrib.get('class') == 'exercises'): thissection.append(child) sections.append(thissection) thissection = [] else: thissection.append(child) else: # build up a list of the sections sections = [] try: chapter = [c.getparent() for c in html.findall('.//section[@class="section"]/h1')][0] except IndexError: continue thissection = [] for child in chapter: if (child.tag != 'section'): thissection.append(child) else: if len(child) == 0: pass elif (child[0].tag == 'h2'): thissection.append(child) sections.append(thissection) thissection = [] else: thissection.append(child) #sections.append(thissection) # write each section to a separate file for num, section in enumerate(sections): template = copy.deepcopy(html_template) body = template.find('.//body') for child in section: body.append(child) secfilename = self.file.replace('.cnxmlplus', '-{:02d}.cnxmlplus'.format(num)) secfilepath = os.path.join('build', form, secfilename + ext) # add css to head css = '<link rel="stylesheet" type="text/css" href="css/stylesheet.css"></link>' css = etree.fromstring(css) template.find('.//head').append(css) with open(secfilepath, 'w') as outfile: outfile.write(etree.tostring(template)) # remove the original html os.remove(chapterfilepath) # create the ToC file. self.create_toc(os.path.dirname(chapterfilepath)) def create_toc(self, path): """ Create the table of contents. Read all the html files in path and use div.section>h1 and div.section>h2 to make table of contents. """ # get all the (x)html files file_list = [f for f in os.listdir(path) if f.endswith('html')] file_list.sort() toc = [] for htmlfile in file_list: with open(os.path.join(path, htmlfile)) as hf: html = etree.HTML(hf.read()) for element in html.iter(): if element.tag in ['h1', 'h2']: parent = element.getparent() if (parent.attrib.get('class') in ['section']) or (parent.tag == 'body'): # exercises are special #if parent.attrib.get('class') == 'exercises': ##ancestors = len([a for a in element.iterancestors() if a.tag == 'div']) + 1 #element.text = "Exercises" #element.tag = 'h{}'.format(ancestors) toc.append((htmlfile, copy.deepcopy(element))) tocelements = [TocElement(t[0], t[1]) for t in toc] assert(len(toc) == len(set(toc))) tocbuilder = TOCBuilder() for tocelement in tocelements: tocbuilder.add_entry(tocelement) toccontent = """\ <html> <head> <title>Table of contents</title> <link rel="stylesheet" type="text/css" href="css/stylesheet.css"> </head> <body> {} </body> </html> """.format(etree.tostring(tocbuilder.as_etree_element(), pretty_print=True)) # TODO, add ids to the section html pages. with open(os.path.join(path, 'tableofcontents.html'), 'w') as tocout: tocout.write(toccontent) def __str__(self): chapno = str(self.chapter_number).ljust(4) return "{number} {title}".format(number=chapno, title=self.title)
38.612281
105
0.509383
from __future__ import print_function import os import logging import hashlib import subprocess import inspect import copy import lxml from lxml import etree try: from termcolor import colored except ImportError: logging.error("Please install termcolor:\n sudo pip install termcolor") from XmlValidator import XmlValidator from XmlValidator import XmlValidationError from . import htmlutils import imageutils from utils import mkdir_p, copy_if_newer, TOCBuilder, TocElement, add_unique_ids specpath = os.path.join(os.path.dirname(inspect.getfile(XmlValidator)), 'spec.xml') DEBUG = False def print_debug_msg(msg): if DEBUG: print(colored("DEBUG: {msg}".format(msg=msg), "yellow")) class chapter(object): def __init__(self, cnxmlplusfile, **kwargs): self.file = cnxmlplusfile self.chapter_number = None self.title = None self.hash = None self.has_changed = True self.valid = None self.conversion_success = {'tex': False, 'html': False, 'xhtml': False, 'mobile': False, 'html5': False} for key, value in kwargs.items(): setattr(self, key, value) if not self.render_problems: self.render_problems = {'tex': True, 'html': True, 'xhtml': True, 'mobile': True, 'html5': True} self.parse_cnxmlplus() def calculate_hash(self, content): m = hashlib.md5() m.update(content) return m.hexdigest() def parse_cnxmlplus(self): with open(self.file, 'r') as f_in: content = f_in.read() if (self.hash is None) or (self.valid is False): self.hash = self.calculate_hash(content) self.validate() else: # If self.hash has been set and it differs from current hash, then # re-validate current_hash = self.calculate_hash(content) if self.hash != current_hash: self.validate() self.hash = current_hash self.has_changed = True else: # file is valid, no validation required. self.valid = True self.hash = current_hash self.has_changed = False try: xml = etree.XML(content) except lxml.etree.XMLSyntaxError: logging.error( colored("{file} is not valid XML!".format( file=self.file), 'red')) return None # save the number try: self.chapter_number = int(self.file[0:self.file.index('-')]) except: self.chapter_number = 'N/A' logging.warn( "{file} doesn't follow naming convention \ CC-title-here.cnxmlplus".format(file=self.file)) chapters = xml.findall('.//section[@type="chapter"]') if len(chapters) > 1: logging.error( "{filename} contains more than 1 chapter!".format( filename=self.file)) elif len(chapters) < 1: logging.error( "{filename} contains no chapters!".format(filename=self.file)) else: self.title = chapters[0].find('.//title').text def info(self): info = '{ch}'.format(ch=self.chapter_number) info += ' ' * (4 - len(info)) if self.valid: info += colored('OK'.center(8), 'green') else: info += colored('Not OK'.center(8), 'red') info += ' ' * (24 - len(info)) info += '{file}'.format(file=self.file) return info def validate(self): print("Validating {f}".format(f=self.file)) with open(self.file, 'r') as xmlfile: xml = xmlfile.read() try: etree.XML(xml) except etree.XMLSyntaxError: self.valid = False return xmlValidator = XmlValidator(open(specpath, 'rt').read()) try: xmlValidator.validate(xml) self.valid = True except XmlValidationError as err: print(err) self.valid = False def __xml_preprocess(self, xml): processed_xml = xml return processed_xml def __copy_tex_images(self, build_folder, output_path): success = True with open(self.file) as f_in: xml = etree.XML(f_in.read()) for image in xml.findall('.//image'): if 'src' in image.attrib: src = image.attrib['src'].strip() else: src = image.find('.//src').text.strip() if src.startswith('/'): print(colored("ERROR! image paths may not start with /: ", "red") + src) success = False continue dest = os.path.join(build_folder, 'tex', src) if not os.path.exists(dest): try: mkdir_p(os.path.dirname(dest)) except OSError: msg = colored("WARNING! {dest} is not allowed!" .format(dest=dest), "magenta") success = False print(msg) success = copy_if_newer(src, dest) return success def __render_pstikz(self, output_path, parallel=True): rendered = imageutils.render_images(output_path, parallel=parallel) return rendered def __copy_html_images(self, build_folder, output_path): success = True with open(output_path, 'r') as f_in: html = etree.HTML(f_in.read()) for img in html.findall('.//img'): src = img.attrib['src'] dest = os.path.join(os.path.dirname(output_path), src) if not os.path.exists(src) and (not os.path.exists(dest)): print_debug_msg(src + " doesn't exist") success = copy_if_newer(src, dest) return success def __tolatex(self): print_debug_msg("Entered __tolatex {f}".format(f=self.file)) myprocess = subprocess.Popen(["cnxmlplus2latex", self.file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) latex, err = myprocess.communicate() return latex def __tohtml(self): print_debug_msg("Entered __tohtml {f}".format(f=self.file)) # tohtmlpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), # 'tohtml.py') myprocess = subprocess.Popen(["cnxmlplus2html", self.file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) html, err = myprocess.communicate() # html = htmlutils.add_mathjax(html) html = htmlutils.repair_equations(html) return html def __tohtml5(self): print_debug_msg("Entered __tohtml5 {f}".format(f=self.file)) # tohtmlpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), # 'tohtml.py') myprocess = subprocess.Popen(["cnxmlplus2html5", self.file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) html, err = myprocess.communicate() # html = htmlutils.add_mathjax(html) html = htmlutils.repair_equations(html) return html def __toxhtml(self): xhtml = self.__tohtml() # Convert this html to xhtml xhtml = htmlutils.xhtml_cleanup(xhtml) return xhtml def __tomobile(self): html = self.__toxhtml() return html def convert(self, build_folder, output_format, parallel=True): conversion_functions = {'tex': self.__tolatex, 'html': self.__tohtml, 'xhtml': self.__toxhtml, 'mobile': self.__tomobile, 'html5': self.__tohtml5} for outformat in output_format: # convert this chapter to the specified format # call the converted method output_path = os.path.join(build_folder, outformat, self.file + '.{f}'.format(f=outformat)) if outformat == 'mobile': output_path = output_path.replace(r'.mobile', '.html') if outformat == 'html5': output_path = output_path.replace(r'.html5', '.html') # only try this on valid cnxmlplus files if self.valid: # run the conversion only if the file has changed OR if it # doesn't exist (it may have been deleted manually) if any((self.has_changed, not os.path.exists(output_path), self.render_problems)): mkdir_p(os.path.dirname(output_path)) print("Converting {ch} to {form}".format(ch=self.file, form=outformat)) converted = conversion_functions[outformat]() with open(output_path, 'w') as f_out: if outformat == 'html' or outformat == 'html5': f_out.write(converted.encode('utf-8')) else: f_out.write(converted) elif (not self.has_changed) and (os.path.exists(output_path)): print("{f} {space} done {form}" .format(f=self.file, space=' ' * (40 - len(self.file)), form=outformat)) if outformat == 'tex': copy_success = self.__copy_tex_images(build_folder, output_path) rendered = self.__render_pstikz(output_path, parallel=parallel) elif outformat == 'html': copy_success = self.__copy_html_images(build_folder, output_path) rendered = self.__render_pstikz(output_path, parallel=parallel) elif outformat == 'xhtml': copy_success = self.__copy_html_images(build_folder, output_path) rendered = self.__render_pstikz(output_path, parallel=parallel) elif outformat == 'mobile': copy_success = self.__copy_html_images(build_folder, output_path) rendered = self.__render_pstikz(output_path, parallel=parallel) elif outformat == 'html5': copy_success = self.__copy_html_images(build_folder, output_path) rendered = self.__render_pstikz(output_path, parallel=parallel) if not (rendered and copy_success): self.render_problems = True else: self.render_problems = False def split_into_sections(self, formats=None): if formats is None: formats = ['html', 'xhtml', 'mobile', 'html5'] for form in formats: if 'tex' in form: continue if form == 'xhtml': ext = '.xhtml' else: ext = '.html' chapterfilepath = os.path.join('build', form, self.file + ext) with open(chapterfilepath) as chapterfile: html = etree.HTML(chapterfile.read()) html = add_unique_ids(html) html_template = copy.deepcopy(html) for bodychild in html_template.find('.//body'): bodychild.getparent().remove(bodychild) if form != 'html5': sections = [] chapter = [c.getparent() for c in html.findall('.//div[@class="section"]/h1')][0] thissection = [] for child in chapter: if (child.tag != 'div'): thissection.append(child) else: if len(child) == 0: pass elif (child[0].tag == 'h2') or (child.attrib.get('class') == 'exercises'): thissection.append(child) sections.append(thissection) thissection = [] else: thissection.append(child) else: sections = [] try: chapter = [c.getparent() for c in html.findall('.//section[@class="section"]/h1')][0] except IndexError: continue thissection = [] for child in chapter: if (child.tag != 'section'): thissection.append(child) else: if len(child) == 0: pass elif (child[0].tag == 'h2'): thissection.append(child) sections.append(thissection) thissection = [] else: thissection.append(child) for num, section in enumerate(sections): template = copy.deepcopy(html_template) body = template.find('.//body') for child in section: body.append(child) secfilename = self.file.replace('.cnxmlplus', '-{:02d}.cnxmlplus'.format(num)) secfilepath = os.path.join('build', form, secfilename + ext) css = '<link rel="stylesheet" type="text/css" href="css/stylesheet.css"></link>' css = etree.fromstring(css) template.find('.//head').append(css) with open(secfilepath, 'w') as outfile: outfile.write(etree.tostring(template)) os.remove(chapterfilepath) self.create_toc(os.path.dirname(chapterfilepath)) def create_toc(self, path): file_list = [f for f in os.listdir(path) if f.endswith('html')] file_list.sort() toc = [] for htmlfile in file_list: with open(os.path.join(path, htmlfile)) as hf: html = etree.HTML(hf.read()) for element in html.iter(): if element.tag in ['h1', 'h2']: parent = element.getparent() if (parent.attrib.get('class') in ['section']) or (parent.tag == 'body'): toc.append((htmlfile, copy.deepcopy(element))) tocelements = [TocElement(t[0], t[1]) for t in toc] assert(len(toc) == len(set(toc))) tocbuilder = TOCBuilder() for tocelement in tocelements: tocbuilder.add_entry(tocelement) toccontent = """\ <html> <head> <title>Table of contents</title> <link rel="stylesheet" type="text/css" href="css/stylesheet.css"> </head> <body> {} </body> </html> """.format(etree.tostring(tocbuilder.as_etree_element(), pretty_print=True)) with open(os.path.join(path, 'tableofcontents.html'), 'w') as tocout: tocout.write(toccontent) def __str__(self): chapno = str(self.chapter_number).ljust(4) return "{number} {title}".format(number=chapno, title=self.title)
true
true
f72d33747d7c9c8e08cd2921f18bbde62bc85b8d
16,578
py
Python
azure-mgmt-network/azure/mgmt/network/operations/security_rules_operations.py
azuresdkci1x/azure-sdk-for-python-1722
e08fa6606543ce0f35b93133dbb78490f8e6bcc9
[ "MIT" ]
1
2018-11-09T06:16:34.000Z
2018-11-09T06:16:34.000Z
azure-mgmt-network/azure/mgmt/network/operations/security_rules_operations.py
azuresdkci1x/azure-sdk-for-python-1722
e08fa6606543ce0f35b93133dbb78490f8e6bcc9
[ "MIT" ]
null
null
null
azure-mgmt-network/azure/mgmt/network/operations/security_rules_operations.py
azuresdkci1x/azure-sdk-for-python-1722
e08fa6606543ce0f35b93133dbb78490f8e6bcc9
[ "MIT" ]
1
2018-11-09T06:17:41.000Z
2018-11-09T06:17:41.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrestazure.azure_operation import AzureOperationPoller import uuid from .. import models class SecurityRulesOperations(object): """SecurityRulesOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. :ivar api_version: Client API version. Constant value: "2016-09-01". """ def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2016-09-01" self.config = config def delete( self, resource_group_name, network_security_group_name, security_rule_name, custom_headers=None, raw=False, **operation_config): """Deletes the specified network security rule. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_security_group_name: The name of the network security group. :type network_security_group_name: str :param security_rule_name: The name of the security rule. :type security_rule_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns None :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'), 'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request def long_running_send(): request = self._client.delete(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [204, 202, 200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def get( self, resource_group_name, network_security_group_name, security_rule_name, custom_headers=None, raw=False, **operation_config): """Get the specified network security rule. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_security_group_name: The name of the network security group. :type network_security_group_name: str :param security_rule_name: The name of the security rule. :type security_rule_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`SecurityRule <azure.mgmt.network.models.SecurityRule>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'), 'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('SecurityRule', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update( self, resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers=None, raw=False, **operation_config): """Creates or updates a security rule in the specified network security group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_security_group_name: The name of the network security group. :type network_security_group_name: str :param security_rule_name: The name of the security rule. :type security_rule_name: str :param security_rule_parameters: Parameters supplied to the create or update network security rule operation. :type security_rule_parameters: :class:`SecurityRule <azure.mgmt.network.models.SecurityRule>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`SecurityRule <azure.mgmt.network.models.SecurityRule>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'), 'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(security_rule_parameters, 'SecurityRule') # Construct and send request def long_running_send(): request = self._client.put(url, query_parameters) return self._client.send( request, header_parameters, body_content, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('SecurityRule', response) if response.status_code == 201: deserialized = self._deserialize('SecurityRule', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def list( self, resource_group_name, network_security_group_name, custom_headers=None, raw=False, **operation_config): """Gets all security rules in a network security group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_security_group_name: The name of the network security group. :type network_security_group_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`SecurityRulePaged <azure.mgmt.network.models.SecurityRulePaged>` :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.SecurityRulePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.SecurityRulePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized
46.830508
192
0.670829
from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrestazure.azure_operation import AzureOperationPoller import uuid from .. import models class SecurityRulesOperations(object): def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2016-09-01" self.config = config def delete( self, resource_group_name, network_security_group_name, security_rule_name, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'), 'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') def long_running_send(): request = self._client.delete(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [204, 202, 200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def get( self, resource_group_name, network_security_group_name, security_rule_name, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'), 'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('SecurityRule', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update( self, resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'), 'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') body_content = self._serialize.body(security_rule_parameters, 'SecurityRule') def long_running_send(): request = self._client.put(url, query_parameters) return self._client.send( request, header_parameters, body_content, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('SecurityRule', response) if response.status_code == 201: deserialized = self._deserialize('SecurityRule', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def list( self, resource_group_name, network_security_group_name, custom_headers=None, raw=False, **operation_config): def internal_paging(next_link=None, raw=False): if not next_link: url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response deserialized = models.SecurityRulePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.SecurityRulePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized
true
true
f72d34add56f4240517a10872e4332cb3d2bd4f6
907
py
Python
start_sample.py
ina-foss/stream-index-massive-tweets
63e6919fa441a24d12f90f42d3045b45a356f6dd
[ "MIT" ]
4
2020-04-10T16:25:19.000Z
2021-06-26T16:06:57.000Z
start_sample.py
ina-foss/stream-index-massive-tweets
63e6919fa441a24d12f90f42d3045b45a356f6dd
[ "MIT" ]
null
null
null
start_sample.py
ina-foss/stream-index-massive-tweets
63e6919fa441a24d12f90f42d3045b45a356f6dd
[ "MIT" ]
1
2020-10-07T16:36:22.000Z
2020-10-07T16:36:22.000Z
import requests import logging import time logging.basicConfig(format='%(asctime)s - %(levelname)s : %(message)s', level=logging.INFO) def stream(): """ Send stream instructions to streamer servers in the form of HTTP POST requests. The streamer_0 is dedicated to the Twitter sample API, so we don't send any keywords or language to track """ while True: try: r = requests.post("http://streamer_0:5000/stream", json={}) break except requests.exceptions.ConnectionError: logging.error("Could not connect to server streamer_0, retrying") time.sleep(2) continue logging.info("'http://streamer_0:5000/stream', response = {}".format(r.status_code)) if r.status_code != 200: time.sleep(2) stream() if __name__ == "__main__": while True: stream() time.sleep(3600 * 24)
29.258065
109
0.631753
import requests import logging import time logging.basicConfig(format='%(asctime)s - %(levelname)s : %(message)s', level=logging.INFO) def stream(): while True: try: r = requests.post("http://streamer_0:5000/stream", json={}) break except requests.exceptions.ConnectionError: logging.error("Could not connect to server streamer_0, retrying") time.sleep(2) continue logging.info("'http://streamer_0:5000/stream', response = {}".format(r.status_code)) if r.status_code != 200: time.sleep(2) stream() if __name__ == "__main__": while True: stream() time.sleep(3600 * 24)
true
true
f72d35520a9df35cca1aca5514b7eef3d130635f
1,121
py
Python
tests/test_dipdup/models.py
spruceid/dipdup-py
adc904196cfd66563938feec0f0afcc5f3df03e3
[ "MIT" ]
null
null
null
tests/test_dipdup/models.py
spruceid/dipdup-py
adc904196cfd66563938feec0f0afcc5f3df03e3
[ "MIT" ]
null
null
null
tests/test_dipdup/models.py
spruceid/dipdup-py
adc904196cfd66563938feec0f0afcc5f3df03e3
[ "MIT" ]
null
null
null
# generated by datamodel-codegen: # filename: storage.json from __future__ import annotations from typing import Dict, List, Optional from pydantic import BaseModel, Extra class ResourceMap(BaseModel): class Config: extra = Extra.forbid id: str rate: str class ResourceCollectorStorage(BaseModel): class Config: extra = Extra.forbid administrator: str current_user: Optional[str] default_start_time: str generation_rate: str managers: List[str] metadata: Dict[str, str] nft_registry: str paused: bool resource_map: Dict[str, ResourceMap] resource_registry: str tezotop_collection: Dict[str, str] # 'resource_map': { # 'type': 'object', # 'propertyNames': {'type': 'string', '$comment': 'string'}, # 'additionalProperties': { # 'type': 'object', # 'properties': {'id': {'type': 'string', '$comment': 'nat'}, 'rate': {'type': 'string', '$comment': 'nat'}}, # 'required': ['id', 'rate'], # 'additionalProperties': False, # '$comment': 'pair', # }, # '$comment': 'map', # },
23.354167
117
0.613738
from __future__ import annotations from typing import Dict, List, Optional from pydantic import BaseModel, Extra class ResourceMap(BaseModel): class Config: extra = Extra.forbid id: str rate: str class ResourceCollectorStorage(BaseModel): class Config: extra = Extra.forbid administrator: str current_user: Optional[str] default_start_time: str generation_rate: str managers: List[str] metadata: Dict[str, str] nft_registry: str paused: bool resource_map: Dict[str, ResourceMap] resource_registry: str tezotop_collection: Dict[str, str]
true
true
f72d35e8cf56ef9f7fbf1705d18d66a60efa75a9
4,831
py
Python
test/functional/mempool_reorg.py
arock121/pocketnet.core
bc08bf9dc565c60d7e7d53e3cc615408b76f9bde
[ "ECL-2.0", "Apache-2.0" ]
72
2019-06-23T07:48:03.000Z
2022-03-31T03:47:04.000Z
test/functional/mempool_reorg.py
arock121/pocketnet.core
bc08bf9dc565c60d7e7d53e3cc615408b76f9bde
[ "ECL-2.0", "Apache-2.0" ]
153
2021-01-20T08:10:23.000Z
2022-03-31T23:30:50.000Z
test/functional/mempool_reorg.py
arock121/pocketnet.core
bc08bf9dc565c60d7e7d53e3cc615408b76f9bde
[ "ECL-2.0", "Apache-2.0" ]
20
2019-10-10T22:18:25.000Z
2022-02-12T01:08:29.000Z
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Pocketcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool re-org scenarios. Test re-org scenarios with a mempool that contains transactions that spend (directly or indirectly) coinbase transactions. """ from test_framework.blocktools import create_raw_transaction from test_framework.test_framework import PocketcoinTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error class MempoolCoinbaseTest(PocketcoinTestFramework): def set_test_params(self): self.num_nodes = 2 def skip_test_if_missing_module(self): self.skip_if_no_wallet() alert_filename = None # Set by setup_network def run_test(self): # Start with a 200 block chain assert_equal(self.nodes[0].getblockcount(), 200) # Mine four blocks. After this, nodes[0] blocks # 101, 102, and 103 are spend-able. new_blocks = self.nodes[1].generate(4) self.sync_all() node0_address = self.nodes[0].getnewaddress() node1_address = self.nodes[1].getnewaddress() # Three scenarios for re-orging coinbase spends in the memory pool: # 1. Direct coinbase spend : spend_101 # 2. Indirect (coinbase spend in chain, child in mempool) : spend_102 and spend_102_1 # 3. Indirect (coinbase and child both in chain) : spend_103 and spend_103_1 # Use invalidatblock to make all of the above coinbase spends invalid (immature coinbase), # and make sure the mempool code behaves correctly. b = [ self.nodes[0].getblockhash(n) for n in range(101, 105) ] coinbase_txids = [ self.nodes[0].getblock(h)['tx'][0] for h in b ] spend_101_raw = create_raw_transaction(self.nodes[0], coinbase_txids[1], node1_address, amount=49.99) spend_102_raw = create_raw_transaction(self.nodes[0], coinbase_txids[2], node0_address, amount=49.99) spend_103_raw = create_raw_transaction(self.nodes[0], coinbase_txids[3], node0_address, amount=49.99) # Create a transaction which is time-locked to two blocks in the future timelock_tx = self.nodes[0].createrawtransaction([{"txid": coinbase_txids[0], "vout": 0}], {node0_address: 49.99}) # Set the time lock timelock_tx = timelock_tx.replace("ffffffff", "11111191", 1) timelock_tx = timelock_tx[:-8] + hex(self.nodes[0].getblockcount() + 2)[2:] + "000000" timelock_tx = self.nodes[0].signrawtransactionwithwallet(timelock_tx)["hex"] # This will raise an exception because the timelock transaction is too immature to spend assert_raises_rpc_error(-26, "non-final", self.nodes[0].sendrawtransaction, timelock_tx) # Broadcast and mine spend_102 and 103: spend_102_id = self.nodes[0].sendrawtransaction(spend_102_raw) spend_103_id = self.nodes[0].sendrawtransaction(spend_103_raw) self.nodes[0].generate(1) # Time-locked transaction is still too immature to spend assert_raises_rpc_error(-26, 'non-final', self.nodes[0].sendrawtransaction, timelock_tx) # Create 102_1 and 103_1: spend_102_1_raw = create_raw_transaction(self.nodes[0], spend_102_id, node1_address, amount=49.98) spend_103_1_raw = create_raw_transaction(self.nodes[0], spend_103_id, node1_address, amount=49.98) # Broadcast and mine 103_1: spend_103_1_id = self.nodes[0].sendrawtransaction(spend_103_1_raw) last_block = self.nodes[0].generate(1) # Time-locked transaction can now be spent timelock_tx_id = self.nodes[0].sendrawtransaction(timelock_tx) # ... now put spend_101 and spend_102_1 in memory pools: spend_101_id = self.nodes[0].sendrawtransaction(spend_101_raw) spend_102_1_id = self.nodes[0].sendrawtransaction(spend_102_1_raw) self.sync_all() assert_equal(set(self.nodes[0].getrawmempool()), {spend_101_id, spend_102_1_id, timelock_tx_id}) for node in self.nodes: node.invalidateblock(last_block[0]) # Time-locked transaction is now too immature and has been removed from the mempool # spend_103_1 has been re-orged out of the chain and is back in the mempool assert_equal(set(self.nodes[0].getrawmempool()), {spend_101_id, spend_102_1_id, spend_103_1_id}) # Use invalidateblock to re-org back and make all those coinbase spends # immature/invalid: for node in self.nodes: node.invalidateblock(new_blocks[0]) self.sync_all() # mempool should be empty. assert_equal(set(self.nodes[0].getrawmempool()), set()) if __name__ == '__main__': MempoolCoinbaseTest().main()
47.831683
122
0.703788
from test_framework.blocktools import create_raw_transaction from test_framework.test_framework import PocketcoinTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error class MempoolCoinbaseTest(PocketcoinTestFramework): def set_test_params(self): self.num_nodes = 2 def skip_test_if_missing_module(self): self.skip_if_no_wallet() alert_filename = None def run_test(self): assert_equal(self.nodes[0].getblockcount(), 200) new_blocks = self.nodes[1].generate(4) self.sync_all() node0_address = self.nodes[0].getnewaddress() node1_address = self.nodes[1].getnewaddress() b = [ self.nodes[0].getblockhash(n) for n in range(101, 105) ] coinbase_txids = [ self.nodes[0].getblock(h)['tx'][0] for h in b ] spend_101_raw = create_raw_transaction(self.nodes[0], coinbase_txids[1], node1_address, amount=49.99) spend_102_raw = create_raw_transaction(self.nodes[0], coinbase_txids[2], node0_address, amount=49.99) spend_103_raw = create_raw_transaction(self.nodes[0], coinbase_txids[3], node0_address, amount=49.99) timelock_tx = self.nodes[0].createrawtransaction([{"txid": coinbase_txids[0], "vout": 0}], {node0_address: 49.99}) timelock_tx = timelock_tx.replace("ffffffff", "11111191", 1) timelock_tx = timelock_tx[:-8] + hex(self.nodes[0].getblockcount() + 2)[2:] + "000000" timelock_tx = self.nodes[0].signrawtransactionwithwallet(timelock_tx)["hex"] assert_raises_rpc_error(-26, "non-final", self.nodes[0].sendrawtransaction, timelock_tx) spend_102_id = self.nodes[0].sendrawtransaction(spend_102_raw) spend_103_id = self.nodes[0].sendrawtransaction(spend_103_raw) self.nodes[0].generate(1) assert_raises_rpc_error(-26, 'non-final', self.nodes[0].sendrawtransaction, timelock_tx) spend_102_1_raw = create_raw_transaction(self.nodes[0], spend_102_id, node1_address, amount=49.98) spend_103_1_raw = create_raw_transaction(self.nodes[0], spend_103_id, node1_address, amount=49.98) spend_103_1_id = self.nodes[0].sendrawtransaction(spend_103_1_raw) last_block = self.nodes[0].generate(1) timelock_tx_id = self.nodes[0].sendrawtransaction(timelock_tx) spend_101_id = self.nodes[0].sendrawtransaction(spend_101_raw) spend_102_1_id = self.nodes[0].sendrawtransaction(spend_102_1_raw) self.sync_all() assert_equal(set(self.nodes[0].getrawmempool()), {spend_101_id, spend_102_1_id, timelock_tx_id}) for node in self.nodes: node.invalidateblock(last_block[0]) assert_equal(set(self.nodes[0].getrawmempool()), {spend_101_id, spend_102_1_id, spend_103_1_id}) for node in self.nodes: node.invalidateblock(new_blocks[0]) self.sync_all() assert_equal(set(self.nodes[0].getrawmempool()), set()) if __name__ == '__main__': MempoolCoinbaseTest().main()
true
true
f72d363eb6000b6d71778b49bc3242e3155db73d
1,224
py
Python
main.py
kchandra423/JPEG-Reader
8298e715dfba338ca6d17e6d9769cdba82256466
[ "MIT" ]
null
null
null
main.py
kchandra423/JPEG-Reader
8298e715dfba338ca6d17e6d9769cdba82256466
[ "MIT" ]
null
null
null
main.py
kchandra423/JPEG-Reader
8298e715dfba338ca6d17e6d9769cdba82256466
[ "MIT" ]
null
null
null
import os from fractions import Fraction from PIL import Image from PIL.ExifTags import TAGS def get_exif(fn): ret = {} i = Image.open(fn) info = i._getexif() decoded_dict = {} for tag, value in info.items(): decoded = TAGS.get(tag, tag) decoded_dict[decoded] = value ret['ISO'] = decoded_dict['ISOSpeedRatings'] ret['Shutter Speed'] = Fraction((decoded_dict['ExposureTime'])) ret['Aperture'] = decoded_dict['MaxApertureValue'] ret['Exposure Value'] = decoded_dict['ExposureBiasValue'] return ret def get_file() -> str: files = [] print(os.listdir('images')) for file in os.listdir('images'): extension = os.path.splitext(file)[1] if extension == '.jpg' or extension == '.jpeg': files.append(file) for i in range(len(files)): print(str(i + 1) + ') ' + files[i]) chosen_file = -1 while chosen_file < 0 or chosen_file >= len(files): chosen_file = int(input('Which file would you like to look at?')) - 1 return files[chosen_file] def main(): info = get_exif('images/' + get_file()) for tag in info: print(tag + ' = ' + str(info[tag])) if __name__ == '__main__': main()
26.042553
77
0.609477
import os from fractions import Fraction from PIL import Image from PIL.ExifTags import TAGS def get_exif(fn): ret = {} i = Image.open(fn) info = i._getexif() decoded_dict = {} for tag, value in info.items(): decoded = TAGS.get(tag, tag) decoded_dict[decoded] = value ret['ISO'] = decoded_dict['ISOSpeedRatings'] ret['Shutter Speed'] = Fraction((decoded_dict['ExposureTime'])) ret['Aperture'] = decoded_dict['MaxApertureValue'] ret['Exposure Value'] = decoded_dict['ExposureBiasValue'] return ret def get_file() -> str: files = [] print(os.listdir('images')) for file in os.listdir('images'): extension = os.path.splitext(file)[1] if extension == '.jpg' or extension == '.jpeg': files.append(file) for i in range(len(files)): print(str(i + 1) + ') ' + files[i]) chosen_file = -1 while chosen_file < 0 or chosen_file >= len(files): chosen_file = int(input('Which file would you like to look at?')) - 1 return files[chosen_file] def main(): info = get_exif('images/' + get_file()) for tag in info: print(tag + ' = ' + str(info[tag])) if __name__ == '__main__': main()
true
true
f72d36baefbadb9b5e6e7da71a7053953f8e03d6
245
py
Python
benchmarks/DNNF-CIFAR-EQ/properties/global_targeted_diff_8_1.py
dlshriver/dnnv-benchmarks
84b5bf1e046226d269da1cdbd7a7690fd90d024b
[ "MIT" ]
1
2022-03-01T08:59:32.000Z
2022-03-01T08:59:32.000Z
benchmarks/DNNF-CIFAR-EQ/properties/global_targeted_diff_8_1.py
dlshriver/dnnv-benchmarks
84b5bf1e046226d269da1cdbd7a7690fd90d024b
[ "MIT" ]
null
null
null
benchmarks/DNNF-CIFAR-EQ/properties/global_targeted_diff_8_1.py
dlshriver/dnnv-benchmarks
84b5bf1e046226d269da1cdbd7a7690fd90d024b
[ "MIT" ]
null
null
null
from dnnv.properties import * import numpy as np N1 = Network("N1") N2 = Network("N2") class_1 = 8 class_2 = 1 Forall( x, Implies( (0 <= x <= 1), (np.argmax(N1(x)) != class_1) | (np.argmax(N2(x)) != class_2), ), )
14.411765
70
0.530612
from dnnv.properties import * import numpy as np N1 = Network("N1") N2 = Network("N2") class_1 = 8 class_2 = 1 Forall( x, Implies( (0 <= x <= 1), (np.argmax(N1(x)) != class_1) | (np.argmax(N2(x)) != class_2), ), )
true
true
f72d376d64716f4e1292cdae5c874f29c229dbed
1,022
py
Python
GeeksForGeeks/SumOfPairs/solution2.py
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
165
2020-10-03T08:01:11.000Z
2022-03-31T02:42:08.000Z
GeeksForGeeks/SumOfPairs/solution2.py
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
383
2020-10-03T07:39:11.000Z
2021-11-20T07:06:35.000Z
GeeksForGeeks/SumOfPairs/solution2.py
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
380
2020-10-03T08:05:04.000Z
2022-03-19T06:56:59.000Z
# Map Approach [O(n)] : # Idea is to create a hashmap to store freq of the elements, and lookup those elements while traversing the array to check if their sum is equal to the given sum or not # GeeksforGeeks Explanation: https://youtu.be/bvKMZXc0jQU def getPairsCount(arr, n, sum): m = [0] * 1000 # Store counts of all elements in map m for i in range(0, n): m[arr[i]] # Stores the frequency of the number in the array m[arr[i]] += 1 twice_count = 0 # Iterate through each element and increment the count (Every pair is counted twice) for i in range(0, n): twice_count += m[sum - arr[i]] # if (arr[i], arr[i]) pair satisfies the condition, then we need to ensure that the count is decreased by one such that the (arr[i], arr[i]) pair is not considered if (sum - arr[i] == arr[i]): twice_count -= 1 # return the half of twice_count return int(twice_count / 2) n = int(input()) arr = list(map(int,input().split())) sum = int(input()) print(getPairsCount(arr, n, sum))
31.9375
168
0.671233
def getPairsCount(arr, n, sum): m = [0] * 1000 for i in range(0, n): m[arr[i]] m[arr[i]] += 1 twice_count = 0 for i in range(0, n): twice_count += m[sum - arr[i]] if (sum - arr[i] == arr[i]): twice_count -= 1 return int(twice_count / 2) n = int(input()) arr = list(map(int,input().split())) sum = int(input()) print(getPairsCount(arr, n, sum))
true
true
f72d384225a2566b1d26d248db3515c9b6c34c12
746
py
Python
run.py
raeyoungii/KJ_Emergency
cb044b8b93f80df6e953bd9f298b7c73bac4a8ed
[ "MIT" ]
1
2020-12-30T15:59:23.000Z
2020-12-30T15:59:23.000Z
run.py
raeyoungii/KJ_Emergency
cb044b8b93f80df6e953bd9f298b7c73bac4a8ed
[ "MIT" ]
null
null
null
run.py
raeyoungii/KJ_Emergency
cb044b8b93f80df6e953bd9f298b7c73bac4a8ed
[ "MIT" ]
1
2020-12-19T06:55:45.000Z
2020-12-19T06:55:45.000Z
# -*- encoding: utf-8 -*- """ Copyright (c) 2019 - present AppSeed.us """ from flask_migrate import Migrate from os import environ from sys import exit from decouple import config from config import config_dict from app import create_app, db # WARNING: Don't run with debug turned on in production! DEBUG = config('DEBUG', default=True) # The configuration get_config_mode = 'Debug' if DEBUG else 'Production' try: # Load the configuration using the default values app_config = config_dict[get_config_mode.capitalize()] except KeyError: exit('Error: Invalid <config_mode>. Expected values [Debug, Production] ') app = create_app(app_config) Migrate(app, db) if __name__ == "__main__": app.run(host='0.0.0.0', port=10027)
22.606061
78
0.733244
from flask_migrate import Migrate from os import environ from sys import exit from decouple import config from config import config_dict from app import create_app, db DEBUG = config('DEBUG', default=True) # The configuration get_config_mode = 'Debug' if DEBUG else 'Production' try: # Load the configuration using the default values app_config = config_dict[get_config_mode.capitalize()] except KeyError: exit('Error: Invalid <config_mode>. Expected values [Debug, Production] ') app = create_app(app_config) Migrate(app, db) if __name__ == "__main__": app.run(host='0.0.0.0', port=10027)
true
true
f72d38578c529760cc3eebfa7307b5a6fa0eef3a
19,861
py
Python
parcels/kernel/basekernel.py
nvogtvincent/parcels
6f6dbadacaae54949ade9acd4e4a57dd8b5af398
[ "MIT" ]
null
null
null
parcels/kernel/basekernel.py
nvogtvincent/parcels
6f6dbadacaae54949ade9acd4e4a57dd8b5af398
[ "MIT" ]
null
null
null
parcels/kernel/basekernel.py
nvogtvincent/parcels
6f6dbadacaae54949ade9acd4e4a57dd8b5af398
[ "MIT" ]
null
null
null
import re import _ctypes import inspect import numpy.ctypeslib as npct from time import time as ostime from os import path from os import remove from sys import platform from sys import version_info from ast import FunctionDef from hashlib import md5 from parcels.tools.loggers import logger import numpy as np from numpy import ndarray try: from mpi4py import MPI except: MPI = None from parcels.tools.global_statics import get_cache_dir # === import just necessary field classes to perform setup checks === # from parcels.field import Field from parcels.field import VectorField from parcels.field import NestedField from parcels.field import SummedField from parcels.grid import GridCode from parcels.field import FieldOutOfBoundError from parcels.field import FieldOutOfBoundSurfaceError from parcels.field import TimeExtrapolationError from parcels.tools.statuscodes import StateCode, OperationCode, ErrorCode from parcels.application_kernels.advection import AdvectionRK4_3D from parcels.application_kernels.advection import AdvectionAnalytical __all__ = ['BaseKernel'] re_indent = re.compile(r"^(\s+)") class BaseKernel(object): """Base super class for base Kernel objects that encapsulates auto-generated code. :arg fieldset: FieldSet object providing the field information (possibly None) :arg ptype: PType object for the kernel particle :arg pyfunc: (aggregated) Kernel function :arg funcname: function name :param delete_cfiles: Boolean whether to delete the C-files after compilation in JIT mode (default is True) Note: A Kernel is either created from a compiled <function ...> object or the necessary information (funcname, funccode, funcvars) is provided. The py_ast argument may be derived from the code string, but for concatenation, the merged AST plus the new header definition is required. """ _pyfunc = None _fieldset = None _ptype = None funcname = None def __init__(self, fieldset, ptype, pyfunc=None, funcname=None, funccode=None, py_ast=None, funcvars=None, c_include="", delete_cfiles=True): self._fieldset = fieldset self.field_args = None self.const_args = None self._ptype = ptype self._lib = None self.delete_cfiles = delete_cfiles self._cleanup_files = None self._cleanup_lib = None self._c_include = c_include # Derive meta information from pyfunc, if not given self._pyfunc = None self.funcname = funcname or pyfunc.__name__ self.name = "%s%s" % (ptype.name, self.funcname) self.ccode = "" self.funcvars = funcvars self.funccode = funccode self.py_ast = py_ast self.dyn_srcs = [] self.static_srcs = [] self.src_file = None self.lib_file = None self.log_file = None # Generate the kernel function and add the outer loop if self._ptype.uses_jit: src_file_or_files, self.lib_file, self.log_file = self.get_kernel_compile_files() if type(src_file_or_files) in (list, dict, tuple, ndarray): self.dyn_srcs = src_file_or_files else: self.src_file = src_file_or_files def __del__(self): # Clean-up the in-memory dynamic linked libraries. # This is not really necessary, as these programs are not that large, but with the new random # naming scheme which is required on Windows OS'es to deal with updates to a Parcels' kernel. try: self.remove_lib() except: pass self._fieldset = None self.field_args = None self.const_args = None self.funcvars = None self.funccode = None @property def ptype(self): return self._ptype @property def pyfunc(self): return self._pyfunc @property def fieldset(self): return self._fieldset @property def c_include(self): return self._c_include @property def _cache_key(self): field_keys = "" if self.field_args is not None: field_keys = "-".join( ["%s:%s" % (name, field.units.__class__.__name__) for name, field in self.field_args.items()]) key = self.name + self.ptype._cache_key + field_keys + ('TIME:%f' % ostime()) return md5(key.encode('utf-8')).hexdigest() @staticmethod def fix_indentation(string): """Fix indentation to allow in-lined kernel definitions""" lines = string.split('\n') indent = re_indent.match(lines[0]) if indent: lines = [line.replace(indent.groups()[0], '', 1) for line in lines] return "\n".join(lines) def check_fieldsets_in_kernels(self, pyfunc): """ function checks the integrity of the fieldset with the kernels. This function is to be called from the derived class when setting up the 'pyfunc'. """ if self.fieldset is not None: if pyfunc is AdvectionRK4_3D: warning = False if isinstance(self._fieldset.W, Field) and self._fieldset.W.creation_log != 'from_nemo' and \ self._fieldset.W._scaling_factor is not None and self._fieldset.W._scaling_factor > 0: warning = True if type(self._fieldset.W) in [SummedField, NestedField]: for f in self._fieldset.W: if f.creation_log != 'from_nemo' and f._scaling_factor is not None and f._scaling_factor > 0: warning = True if warning: logger.warning_once('Note that in AdvectionRK4_3D, vertical velocity is assumed positive towards increasing z.\n' ' If z increases downward and w is positive upward you can re-orient it downwards by setting fieldset.W.set_scaling_factor(-1.)') elif pyfunc is AdvectionAnalytical: if self._ptype.uses_jit: raise NotImplementedError('Analytical Advection only works in Scipy mode') if self._fieldset.U.interp_method != 'cgrid_velocity': raise NotImplementedError('Analytical Advection only works with C-grids') if self._fieldset.U.grid.gtype not in [GridCode.CurvilinearZGrid, GridCode.RectilinearZGrid]: raise NotImplementedError('Analytical Advection only works with Z-grids in the vertical') def check_kernel_signature_on_version(self): """ returns numkernelargs """ numkernelargs = 0 if self._pyfunc is not None: if version_info[0] < 3: numkernelargs = len(inspect.getargspec(self._pyfunc).args) else: numkernelargs = len(inspect.getfullargspec(self._pyfunc).args) return numkernelargs def remove_lib(self): if self._lib is not None: BaseKernel.cleanup_unload_lib(self._lib) del self._lib self._lib = None all_files_array = [] if self.src_file is None: if self.dyn_srcs is not None: [all_files_array.append(fpath) for fpath in self.dyn_srcs] else: if self.src_file is not None: all_files_array.append(self.src_file) if self.log_file is not None: all_files_array.append(self.log_file) if self.lib_file is not None and all_files_array is not None and self.delete_cfiles is not None: BaseKernel.cleanup_remove_files(self.lib_file, all_files_array, self.delete_cfiles) # If file already exists, pull new names. This is necessary on a Windows machine, because # Python's ctype does not deal in any sort of manner well with dynamic linked libraries on this OS. if self._ptype.uses_jit: src_file_or_files, self.lib_file, self.log_file = self.get_kernel_compile_files() if type(src_file_or_files) in (list, dict, tuple, ndarray): self.dyn_srcs = src_file_or_files else: self.src_file = src_file_or_files def get_kernel_compile_files(self): """ Returns the correct src_file, lib_file, log_file for this kernel """ if MPI: mpi_comm = MPI.COMM_WORLD mpi_rank = mpi_comm.Get_rank() cache_name = self._cache_key # only required here because loading is done by Kernel class instead of Compiler class dyn_dir = get_cache_dir() if mpi_rank == 0 else None dyn_dir = mpi_comm.bcast(dyn_dir, root=0) basename = cache_name if mpi_rank == 0 else None basename = mpi_comm.bcast(basename, root=0) basename = basename + "_%d" % mpi_rank else: cache_name = self._cache_key # only required here because loading is done by Kernel class instead of Compiler class dyn_dir = get_cache_dir() basename = "%s_0" % cache_name lib_path = "lib" + basename src_file_or_files = None if type(basename) in (list, dict, tuple, ndarray): src_file_or_files = ["", ] * len(basename) for i, src_file in enumerate(basename): src_file_or_files[i] = "%s.c" % path.join(dyn_dir, src_file) else: src_file_or_files = "%s.c" % path.join(dyn_dir, basename) lib_file = "%s.%s" % (path.join(dyn_dir, lib_path), 'dll' if platform == 'win32' else 'so') log_file = "%s.log" % path.join(dyn_dir, basename) return src_file_or_files, lib_file, log_file def compile(self, compiler): """ Writes kernel code to file and compiles it.""" all_files_array = [] if self.src_file is None: if self.dyn_srcs is not None: for dyn_src in self.dyn_srcs: with open(dyn_src, 'w') as f: f.write(self.ccode) all_files_array.append(dyn_src) compiler.compile(self.dyn_srcs, self.lib_file, self.log_file) else: if self.src_file is not None: with open(self.src_file, 'w') as f: f.write(self.ccode) if self.src_file is not None: all_files_array.append(self.src_file) compiler.compile(self.src_file, self.lib_file, self.log_file) if len(all_files_array) > 0: logger.info("Compiled %s ==> %s" % (self.name, self.lib_file)) if self.log_file is not None: all_files_array.append(self.log_file) def load_lib(self): self._lib = npct.load_library(self.lib_file, '.') self._function = self._lib.particle_loop def merge(self, kernel, kclass): funcname = self.funcname + kernel.funcname func_ast = None if self.py_ast is not None: func_ast = FunctionDef(name=funcname, args=self.py_ast.args, body=self.py_ast.body + kernel.py_ast.body, decorator_list=[], lineno=1, col_offset=0) delete_cfiles = self.delete_cfiles and kernel.delete_cfiles return kclass(self.fieldset, self.ptype, pyfunc=None, funcname=funcname, funccode=self.funccode + kernel.funccode, py_ast=func_ast, funcvars=self.funcvars + kernel.funcvars, c_include=self._c_include + kernel.c_include, delete_cfiles=delete_cfiles) def __add__(self, kernel): if not isinstance(kernel, BaseKernel): kernel = BaseKernel(self.fieldset, self.ptype, pyfunc=kernel) return self.merge(kernel, BaseKernel) def __radd__(self, kernel): if not isinstance(kernel, BaseKernel): kernel = BaseKernel(self.fieldset, self.ptype, pyfunc=kernel) return kernel.merge(self, BaseKernel) @staticmethod def cleanup_remove_files(lib_file, all_files_array, delete_cfiles): if lib_file is not None: if path.isfile(lib_file): # and delete_cfiles [remove(s) for s in [lib_file, ] if path is not None and path.exists(s)] if delete_cfiles and len(all_files_array) > 0: [remove(s) for s in all_files_array if path is not None and path.exists(s)] @staticmethod def cleanup_unload_lib(lib): # Clean-up the in-memory dynamic linked libraries. # This is not really necessary, as these programs are not that large, but with the new random # naming scheme which is required on Windows OS'es to deal with updates to a Parcels' kernel. if lib is not None: try: _ctypes.FreeLibrary(lib._handle) if platform == 'win32' else _ctypes.dlclose(lib._handle) except: pass def remove_deleted(self, pset, output_file, endtime): """ Utility to remove all particles that signalled deletion. This version is generally applicable to all structures and collections """ indices = [i for i, p in enumerate(pset) if p.state == OperationCode.Delete] if len(indices) > 0 and output_file is not None: output_file.write(pset, endtime, deleted_only=indices) pset.remove_indices(indices) def load_fieldset_jit(self, pset): """ Updates the loaded fields of pset's fieldset according to the chunk information within their grids """ if pset.fieldset is not None: for g in pset.fieldset.gridset.grids: g.cstruct = None # This force to point newly the grids from Python to C # Make a copy of the transposed array to enforce # C-contiguous memory layout for JIT mode. for f in pset.fieldset.get_fields(): if type(f) in [VectorField, NestedField, SummedField]: continue if f.data.dtype != np.float32: raise RuntimeError('Field %s data needs to be float32 in JIT mode' % f.name) if f in self.field_args.values(): f.chunk_data() else: for block_id in range(len(f.data_chunks)): f.data_chunks[block_id] = None f.c_data_chunks[block_id] = None for g in pset.fieldset.gridset.grids: g.load_chunk = np.where(g.load_chunk == g.chunk_loading_requested, g.chunk_loaded_touched, g.load_chunk) if len(g.load_chunk) > g.chunk_not_loaded: # not the case if a field in not called in the kernel if not g.load_chunk.flags.c_contiguous: g.load_chunk = g.load_chunk.copy() if not g.depth.flags.c_contiguous: g.depth = g.depth.copy() if not g.lon.flags.c_contiguous: g.lon = g.lon.copy() if not g.lat.flags.c_contiguous: g.lat = g.lat.copy() def evaluate_particle(self, p, endtime, sign_dt, dt, analytical=False): """ Execute the kernel evaluation of for an individual particle. :arg p: object of (sub-)type (ScipyParticle, JITParticle) or (sub-)type of BaseParticleAccessor :arg fieldset: fieldset of the containing ParticleSet (e.g. pset.fieldset) :arg analytical: flag indicating the analytical advector or an iterative advection :arg endtime: endtime of this overall kernel evaluation step :arg dt: computational integration timestep """ variables = self._ptype.variables # back up variables in case of OperationCode.Repeat p_var_back = {} pdt_prekernels = .0 # Don't execute particles that aren't started yet sign_end_part = np.sign(endtime - p.time) # Compute min/max dt for first timestep. Only use endtime-p.time for one timestep reset_dt = False if abs(endtime - p.time) < abs(p.dt): dt_pos = abs(endtime - p.time) reset_dt = True else: dt_pos = abs(p.dt) reset_dt = False # ==== numerically stable; also making sure that continuously-recovered particles do end successfully, # as they fulfil the condition here on entering at the final calculation here. ==== # if ((sign_end_part != sign_dt) or np.isclose(dt_pos, 0)) and not np.isclose(dt, 0): if abs(p.time) >= abs(endtime): p.set_state(StateCode.Success) return p while p.state in [StateCode.Evaluate, OperationCode.Repeat] or np.isclose(dt, 0): for var in variables: p_var_back[var.name] = getattr(p, var.name) try: pdt_prekernels = sign_dt * dt_pos p.dt = pdt_prekernels state_prev = p.state res = self._pyfunc(p, self._fieldset, p.time) if res is None: res = StateCode.Success if res is StateCode.Success and p.state != state_prev: res = p.state if not analytical and res == StateCode.Success and not np.isclose(p.dt, pdt_prekernels): res = OperationCode.Repeat except FieldOutOfBoundError as fse_xy: res = ErrorCode.ErrorOutOfBounds p.exception = fse_xy except FieldOutOfBoundSurfaceError as fse_z: res = ErrorCode.ErrorThroughSurface p.exception = fse_z except TimeExtrapolationError as fse_t: res = ErrorCode.ErrorTimeExtrapolation p.exception = fse_t except Exception as e: res = ErrorCode.Error p.exception = e # Handle particle time and time loop if res in [StateCode.Success, OperationCode.Delete]: # Update time and repeat p.time += p.dt if reset_dt and p.dt == pdt_prekernels: p.dt = dt p.update_next_dt() if analytical: p.dt = np.inf if abs(endtime - p.time) < abs(p.dt): dt_pos = abs(endtime - p.time) reset_dt = True else: dt_pos = abs(p.dt) reset_dt = False sign_end_part = np.sign(endtime - p.time) if res != OperationCode.Delete and not np.isclose(dt_pos, 0) and (sign_end_part == sign_dt): res = StateCode.Evaluate if sign_end_part != sign_dt: dt_pos = 0 p.set_state(res) if np.isclose(dt, 0): break else: p.set_state(res) # Try again without time update for var in variables: if var.name not in ['dt', 'state']: setattr(p, var.name, p_var_back[var.name]) if abs(endtime - p.time) < abs(p.dt): dt_pos = abs(endtime - p.time) reset_dt = True else: dt_pos = abs(p.dt) reset_dt = False sign_end_part = np.sign(endtime - p.time) if sign_end_part != sign_dt: dt_pos = 0 break return p def execute_jit(self, pset, endtime, dt): pass def execute_python(self, pset, endtime, dt): pass def execute(self, pset, endtime, dt, recovery=None, output_file=None, execute_once=False): pass
42.803879
170
0.601682
import re import _ctypes import inspect import numpy.ctypeslib as npct from time import time as ostime from os import path from os import remove from sys import platform from sys import version_info from ast import FunctionDef from hashlib import md5 from parcels.tools.loggers import logger import numpy as np from numpy import ndarray try: from mpi4py import MPI except: MPI = None from parcels.tools.global_statics import get_cache_dir from parcels.field import Field from parcels.field import VectorField from parcels.field import NestedField from parcels.field import SummedField from parcels.grid import GridCode from parcels.field import FieldOutOfBoundError from parcels.field import FieldOutOfBoundSurfaceError from parcels.field import TimeExtrapolationError from parcels.tools.statuscodes import StateCode, OperationCode, ErrorCode from parcels.application_kernels.advection import AdvectionRK4_3D from parcels.application_kernels.advection import AdvectionAnalytical __all__ = ['BaseKernel'] re_indent = re.compile(r"^(\s+)") class BaseKernel(object): _pyfunc = None _fieldset = None _ptype = None funcname = None def __init__(self, fieldset, ptype, pyfunc=None, funcname=None, funccode=None, py_ast=None, funcvars=None, c_include="", delete_cfiles=True): self._fieldset = fieldset self.field_args = None self.const_args = None self._ptype = ptype self._lib = None self.delete_cfiles = delete_cfiles self._cleanup_files = None self._cleanup_lib = None self._c_include = c_include self._pyfunc = None self.funcname = funcname or pyfunc.__name__ self.name = "%s%s" % (ptype.name, self.funcname) self.ccode = "" self.funcvars = funcvars self.funccode = funccode self.py_ast = py_ast self.dyn_srcs = [] self.static_srcs = [] self.src_file = None self.lib_file = None self.log_file = None if self._ptype.uses_jit: src_file_or_files, self.lib_file, self.log_file = self.get_kernel_compile_files() if type(src_file_or_files) in (list, dict, tuple, ndarray): self.dyn_srcs = src_file_or_files else: self.src_file = src_file_or_files def __del__(self): try: self.remove_lib() except: pass self._fieldset = None self.field_args = None self.const_args = None self.funcvars = None self.funccode = None @property def ptype(self): return self._ptype @property def pyfunc(self): return self._pyfunc @property def fieldset(self): return self._fieldset @property def c_include(self): return self._c_include @property def _cache_key(self): field_keys = "" if self.field_args is not None: field_keys = "-".join( ["%s:%s" % (name, field.units.__class__.__name__) for name, field in self.field_args.items()]) key = self.name + self.ptype._cache_key + field_keys + ('TIME:%f' % ostime()) return md5(key.encode('utf-8')).hexdigest() @staticmethod def fix_indentation(string): lines = string.split('\n') indent = re_indent.match(lines[0]) if indent: lines = [line.replace(indent.groups()[0], '', 1) for line in lines] return "\n".join(lines) def check_fieldsets_in_kernels(self, pyfunc): if self.fieldset is not None: if pyfunc is AdvectionRK4_3D: warning = False if isinstance(self._fieldset.W, Field) and self._fieldset.W.creation_log != 'from_nemo' and \ self._fieldset.W._scaling_factor is not None and self._fieldset.W._scaling_factor > 0: warning = True if type(self._fieldset.W) in [SummedField, NestedField]: for f in self._fieldset.W: if f.creation_log != 'from_nemo' and f._scaling_factor is not None and f._scaling_factor > 0: warning = True if warning: logger.warning_once('Note that in AdvectionRK4_3D, vertical velocity is assumed positive towards increasing z.\n' ' If z increases downward and w is positive upward you can re-orient it downwards by setting fieldset.W.set_scaling_factor(-1.)') elif pyfunc is AdvectionAnalytical: if self._ptype.uses_jit: raise NotImplementedError('Analytical Advection only works in Scipy mode') if self._fieldset.U.interp_method != 'cgrid_velocity': raise NotImplementedError('Analytical Advection only works with C-grids') if self._fieldset.U.grid.gtype not in [GridCode.CurvilinearZGrid, GridCode.RectilinearZGrid]: raise NotImplementedError('Analytical Advection only works with Z-grids in the vertical') def check_kernel_signature_on_version(self): numkernelargs = 0 if self._pyfunc is not None: if version_info[0] < 3: numkernelargs = len(inspect.getargspec(self._pyfunc).args) else: numkernelargs = len(inspect.getfullargspec(self._pyfunc).args) return numkernelargs def remove_lib(self): if self._lib is not None: BaseKernel.cleanup_unload_lib(self._lib) del self._lib self._lib = None all_files_array = [] if self.src_file is None: if self.dyn_srcs is not None: [all_files_array.append(fpath) for fpath in self.dyn_srcs] else: if self.src_file is not None: all_files_array.append(self.src_file) if self.log_file is not None: all_files_array.append(self.log_file) if self.lib_file is not None and all_files_array is not None and self.delete_cfiles is not None: BaseKernel.cleanup_remove_files(self.lib_file, all_files_array, self.delete_cfiles) if self._ptype.uses_jit: src_file_or_files, self.lib_file, self.log_file = self.get_kernel_compile_files() if type(src_file_or_files) in (list, dict, tuple, ndarray): self.dyn_srcs = src_file_or_files else: self.src_file = src_file_or_files def get_kernel_compile_files(self): if MPI: mpi_comm = MPI.COMM_WORLD mpi_rank = mpi_comm.Get_rank() cache_name = self._cache_key # only required here because loading is done by Kernel class instead of Compiler class dyn_dir = get_cache_dir() if mpi_rank == 0 else None dyn_dir = mpi_comm.bcast(dyn_dir, root=0) basename = cache_name if mpi_rank == 0 else None basename = mpi_comm.bcast(basename, root=0) basename = basename + "_%d" % mpi_rank else: cache_name = self._cache_key # only required here because loading is done by Kernel class instead of Compiler class dyn_dir = get_cache_dir() basename = "%s_0" % cache_name lib_path = "lib" + basename src_file_or_files = None if type(basename) in (list, dict, tuple, ndarray): src_file_or_files = ["", ] * len(basename) for i, src_file in enumerate(basename): src_file_or_files[i] = "%s.c" % path.join(dyn_dir, src_file) else: src_file_or_files = "%s.c" % path.join(dyn_dir, basename) lib_file = "%s.%s" % (path.join(dyn_dir, lib_path), 'dll' if platform == 'win32' else 'so') log_file = "%s.log" % path.join(dyn_dir, basename) return src_file_or_files, lib_file, log_file def compile(self, compiler): all_files_array = [] if self.src_file is None: if self.dyn_srcs is not None: for dyn_src in self.dyn_srcs: with open(dyn_src, 'w') as f: f.write(self.ccode) all_files_array.append(dyn_src) compiler.compile(self.dyn_srcs, self.lib_file, self.log_file) else: if self.src_file is not None: with open(self.src_file, 'w') as f: f.write(self.ccode) if self.src_file is not None: all_files_array.append(self.src_file) compiler.compile(self.src_file, self.lib_file, self.log_file) if len(all_files_array) > 0: logger.info("Compiled %s ==> %s" % (self.name, self.lib_file)) if self.log_file is not None: all_files_array.append(self.log_file) def load_lib(self): self._lib = npct.load_library(self.lib_file, '.') self._function = self._lib.particle_loop def merge(self, kernel, kclass): funcname = self.funcname + kernel.funcname func_ast = None if self.py_ast is not None: func_ast = FunctionDef(name=funcname, args=self.py_ast.args, body=self.py_ast.body + kernel.py_ast.body, decorator_list=[], lineno=1, col_offset=0) delete_cfiles = self.delete_cfiles and kernel.delete_cfiles return kclass(self.fieldset, self.ptype, pyfunc=None, funcname=funcname, funccode=self.funccode + kernel.funccode, py_ast=func_ast, funcvars=self.funcvars + kernel.funcvars, c_include=self._c_include + kernel.c_include, delete_cfiles=delete_cfiles) def __add__(self, kernel): if not isinstance(kernel, BaseKernel): kernel = BaseKernel(self.fieldset, self.ptype, pyfunc=kernel) return self.merge(kernel, BaseKernel) def __radd__(self, kernel): if not isinstance(kernel, BaseKernel): kernel = BaseKernel(self.fieldset, self.ptype, pyfunc=kernel) return kernel.merge(self, BaseKernel) @staticmethod def cleanup_remove_files(lib_file, all_files_array, delete_cfiles): if lib_file is not None: if path.isfile(lib_file): # and delete_cfiles [remove(s) for s in [lib_file, ] if path is not None and path.exists(s)] if delete_cfiles and len(all_files_array) > 0: [remove(s) for s in all_files_array if path is not None and path.exists(s)] @staticmethod def cleanup_unload_lib(lib): # Clean-up the in-memory dynamic linked libraries. # This is not really necessary, as these programs are not that large, but with the new random # naming scheme which is required on Windows OS'es to deal with updates to a Parcels' kernel. if lib is not None: try: _ctypes.FreeLibrary(lib._handle) if platform == 'win32' else _ctypes.dlclose(lib._handle) except: pass def remove_deleted(self, pset, output_file, endtime): indices = [i for i, p in enumerate(pset) if p.state == OperationCode.Delete] if len(indices) > 0 and output_file is not None: output_file.write(pset, endtime, deleted_only=indices) pset.remove_indices(indices) def load_fieldset_jit(self, pset): if pset.fieldset is not None: for g in pset.fieldset.gridset.grids: g.cstruct = None # This force to point newly the grids from Python to C # Make a copy of the transposed array to enforce # C-contiguous memory layout for JIT mode. for f in pset.fieldset.get_fields(): if type(f) in [VectorField, NestedField, SummedField]: continue if f.data.dtype != np.float32: raise RuntimeError('Field %s data needs to be float32 in JIT mode' % f.name) if f in self.field_args.values(): f.chunk_data() else: for block_id in range(len(f.data_chunks)): f.data_chunks[block_id] = None f.c_data_chunks[block_id] = None for g in pset.fieldset.gridset.grids: g.load_chunk = np.where(g.load_chunk == g.chunk_loading_requested, g.chunk_loaded_touched, g.load_chunk) if len(g.load_chunk) > g.chunk_not_loaded: # not the case if a field in not called in the kernel if not g.load_chunk.flags.c_contiguous: g.load_chunk = g.load_chunk.copy() if not g.depth.flags.c_contiguous: g.depth = g.depth.copy() if not g.lon.flags.c_contiguous: g.lon = g.lon.copy() if not g.lat.flags.c_contiguous: g.lat = g.lat.copy() def evaluate_particle(self, p, endtime, sign_dt, dt, analytical=False): variables = self._ptype.variables # back up variables in case of OperationCode.Repeat p_var_back = {} pdt_prekernels = .0 # Don't execute particles that aren't started yet sign_end_part = np.sign(endtime - p.time) # Compute min/max dt for first timestep. Only use endtime-p.time for one timestep reset_dt = False if abs(endtime - p.time) < abs(p.dt): dt_pos = abs(endtime - p.time) reset_dt = True else: dt_pos = abs(p.dt) reset_dt = False # ==== numerically stable; also making sure that continuously-recovered particles do end successfully, # as they fulfil the condition here on entering at the final calculation here. ==== # if ((sign_end_part != sign_dt) or np.isclose(dt_pos, 0)) and not np.isclose(dt, 0): if abs(p.time) >= abs(endtime): p.set_state(StateCode.Success) return p while p.state in [StateCode.Evaluate, OperationCode.Repeat] or np.isclose(dt, 0): for var in variables: p_var_back[var.name] = getattr(p, var.name) try: pdt_prekernels = sign_dt * dt_pos p.dt = pdt_prekernels state_prev = p.state res = self._pyfunc(p, self._fieldset, p.time) if res is None: res = StateCode.Success if res is StateCode.Success and p.state != state_prev: res = p.state if not analytical and res == StateCode.Success and not np.isclose(p.dt, pdt_prekernels): res = OperationCode.Repeat except FieldOutOfBoundError as fse_xy: res = ErrorCode.ErrorOutOfBounds p.exception = fse_xy except FieldOutOfBoundSurfaceError as fse_z: res = ErrorCode.ErrorThroughSurface p.exception = fse_z except TimeExtrapolationError as fse_t: res = ErrorCode.ErrorTimeExtrapolation p.exception = fse_t except Exception as e: res = ErrorCode.Error p.exception = e # Handle particle time and time loop if res in [StateCode.Success, OperationCode.Delete]: # Update time and repeat p.time += p.dt if reset_dt and p.dt == pdt_prekernels: p.dt = dt p.update_next_dt() if analytical: p.dt = np.inf if abs(endtime - p.time) < abs(p.dt): dt_pos = abs(endtime - p.time) reset_dt = True else: dt_pos = abs(p.dt) reset_dt = False sign_end_part = np.sign(endtime - p.time) if res != OperationCode.Delete and not np.isclose(dt_pos, 0) and (sign_end_part == sign_dt): res = StateCode.Evaluate if sign_end_part != sign_dt: dt_pos = 0 p.set_state(res) if np.isclose(dt, 0): break else: p.set_state(res) # Try again without time update for var in variables: if var.name not in ['dt', 'state']: setattr(p, var.name, p_var_back[var.name]) if abs(endtime - p.time) < abs(p.dt): dt_pos = abs(endtime - p.time) reset_dt = True else: dt_pos = abs(p.dt) reset_dt = False sign_end_part = np.sign(endtime - p.time) if sign_end_part != sign_dt: dt_pos = 0 break return p def execute_jit(self, pset, endtime, dt): pass def execute_python(self, pset, endtime, dt): pass def execute(self, pset, endtime, dt, recovery=None, output_file=None, execute_once=False): pass
true
true
f72d390cbcef3353b659e18c1886e17ecd60788c
5,876
py
Python
MachikoroSimulator/MachikoroSimulator/Game/Game.py
djscheuf/Machikoro-Simulator
e479ef8d27b0396e2f182537926321689c160f7a
[ "MIT" ]
null
null
null
MachikoroSimulator/MachikoroSimulator/Game/Game.py
djscheuf/Machikoro-Simulator
e479ef8d27b0396e2f182537926321689c160f7a
[ "MIT" ]
null
null
null
MachikoroSimulator/MachikoroSimulator/Game/Game.py
djscheuf/Machikoro-Simulator
e479ef8d27b0396e2f182537926321689c160f7a
[ "MIT" ]
null
null
null
import random from ..CardEnum import * from copy import deepcopy class GameResult: def __init__(self,winner,turns): self.winner = winner self.turns = turns class Game: def __init__(self, players, engine, deck, logger): random.seed() self.winner = None self.total_turns = 0 self._logger = logger self._players = players self._playerCount = len(self._players) self._engine = engine self._initialDeck = deepcopy(deck) self._currentDeck = deck self._init_game() def _log(self, msg): self._logger.debug(msg) def _init_game(self): self._currentPlayer = 0 self._turn = 0 self.winner = None self.total_turns = 0 init_state = self._engine.initialstate() for player in self._players: player.initialstate(deepcopy(init_state)) def run(self): self._log("Starting a game.") game_finished = False while not game_finished: self._execute_turn() self._log("") game_finished = self._engine.winconditionmet(self._players) self.winner = self._engine.get_winner(self._players) self.total_turns = self._turn def _execute_turn(self): player = self._players[self._currentPlayer] self._log("\tTurn {0}, Player {1}".format(self._turn, player.name)) # Ask current player for roll. dicecnt = player.get_number_toroll() # roll rollnum = self._roll(dicecnt) self._log("\t\tPlayer rolls {0} dice, and gets a {1}".format(dicecnt, rollnum)) # use engine to determine earning. # - Steal first self._take_money_if_necessary(rollnum) # - Then Earn self._award_money_if_necessary(rollnum) state = player.get_currentstate() self._log("\t\tAfter money has changed hands, the player now has:{0}".format(state.Money)) # ask current player for purchase card = player.get_card_topurchase(self._currentDeck.get_availablecards()) # make purchase if card is not CardEnum.NoCard: if player.get_currentstate().Money >= CardCosts[card]: player.deduct_money(CardCosts[card]) self._currentDeck.request_card(card) player.award_card(card) self._log("\tThe player purchases {0}".format(card)) # increment current player (increment turn if back to first player) self._currentPlayer = self._get_next_player() if self._currentPlayer == 0: self._turn += 1 @staticmethod def _roll(dice): """Rolls the designated number of 6 sided dice. Returns sum of dice.""" result = 0 i = 0 while i < dice: result += random.randint(1, 6) i += 1 return result def _take_money_if_necessary(self, roll): """Iterates thru all other players to determine if money is owed by rolling player.""" currentPlayer = self._players[self._currentPlayer] nextIdx = self._get_next_player() canContinue= True self._log("") while canContinue: # - Determine Cards activated on other players nextPlayer = self._players[nextIdx] owed = self._engine.steals_money(nextPlayer.get_currentstate(), roll) self._log("\t\tPlayer {0} owes {1} {2} money.".format(currentPlayer.name, nextPlayer.name, owed)) # - Attempt to aware going around to next available = currentPlayer.deduct_money(owed) if available is None: self._log("\t\t\t But had no money left...") canContinue = False continue else: nextPlayer.award_money(available) if owed != available: self._log("\t\t\t But could only pay {0}...".format(available)) canContinue = False continue self._log("\t\t\t and paid in full.") nextIdx = self._get_next_player(nextIdx) if nextIdx == self._currentPlayer: canContinue = False def _get_next_player(self, cur_idx=None): idx = cur_idx if cur_idx is None: idx = self._currentPlayer return (idx + 1) % self._playerCount def _award_money_if_necessary(self, roll): """Iterates thru all players and awards money from bank as applicable.""" # Iterate thru other players first self._log("") next_idx = self._get_next_player(self._currentPlayer) while next_idx != self._currentPlayer: player = self._players[next_idx] earned = self._engine.earns_money(player.get_currentstate(), roll, False) # False because it is not the players turn self._log("\t\t{0} earned {1} for their blues.".format(player.name, earned)) player.award_money(earned) next_idx = self._get_next_player(next_idx) # Award money to current player player = self._players[self._currentPlayer] earned = self._engine.earns_money(player.get_currentstate(), roll, True) self._log("\t\t{0} earned {1} for their blues and greens.".format(player.name, earned)) player.award_money(earned) def reset(self): self._currentDeck = deepcopy(self._initialDeck) self._init_game() self._randomize_first_player() def _randomize_first_player(self): self._currentPlayer = random.randint(0, self._playerCount-1) def get_players(self): result = [] for player in self._players: result.append(player.name) return result def get_result(self): return GameResult(self.winner, self.total_turns)
33.770115
109
0.607897
import random from ..CardEnum import * from copy import deepcopy class GameResult: def __init__(self,winner,turns): self.winner = winner self.turns = turns class Game: def __init__(self, players, engine, deck, logger): random.seed() self.winner = None self.total_turns = 0 self._logger = logger self._players = players self._playerCount = len(self._players) self._engine = engine self._initialDeck = deepcopy(deck) self._currentDeck = deck self._init_game() def _log(self, msg): self._logger.debug(msg) def _init_game(self): self._currentPlayer = 0 self._turn = 0 self.winner = None self.total_turns = 0 init_state = self._engine.initialstate() for player in self._players: player.initialstate(deepcopy(init_state)) def run(self): self._log("Starting a game.") game_finished = False while not game_finished: self._execute_turn() self._log("") game_finished = self._engine.winconditionmet(self._players) self.winner = self._engine.get_winner(self._players) self.total_turns = self._turn def _execute_turn(self): player = self._players[self._currentPlayer] self._log("\tTurn {0}, Player {1}".format(self._turn, player.name)) dicecnt = player.get_number_toroll() rollnum = self._roll(dicecnt) self._log("\t\tPlayer rolls {0} dice, and gets a {1}".format(dicecnt, rollnum)) self._take_money_if_necessary(rollnum) self._award_money_if_necessary(rollnum) state = player.get_currentstate() self._log("\t\tAfter money has changed hands, the player now has:{0}".format(state.Money)) card = player.get_card_topurchase(self._currentDeck.get_availablecards()) if card is not CardEnum.NoCard: if player.get_currentstate().Money >= CardCosts[card]: player.deduct_money(CardCosts[card]) self._currentDeck.request_card(card) player.award_card(card) self._log("\tThe player purchases {0}".format(card)) self._currentPlayer = self._get_next_player() if self._currentPlayer == 0: self._turn += 1 @staticmethod def _roll(dice): result = 0 i = 0 while i < dice: result += random.randint(1, 6) i += 1 return result def _take_money_if_necessary(self, roll): currentPlayer = self._players[self._currentPlayer] nextIdx = self._get_next_player() canContinue= True self._log("") while canContinue: nextPlayer = self._players[nextIdx] owed = self._engine.steals_money(nextPlayer.get_currentstate(), roll) self._log("\t\tPlayer {0} owes {1} {2} money.".format(currentPlayer.name, nextPlayer.name, owed)) available = currentPlayer.deduct_money(owed) if available is None: self._log("\t\t\t But had no money left...") canContinue = False continue else: nextPlayer.award_money(available) if owed != available: self._log("\t\t\t But could only pay {0}...".format(available)) canContinue = False continue self._log("\t\t\t and paid in full.") nextIdx = self._get_next_player(nextIdx) if nextIdx == self._currentPlayer: canContinue = False def _get_next_player(self, cur_idx=None): idx = cur_idx if cur_idx is None: idx = self._currentPlayer return (idx + 1) % self._playerCount def _award_money_if_necessary(self, roll): self._log("") next_idx = self._get_next_player(self._currentPlayer) while next_idx != self._currentPlayer: player = self._players[next_idx] earned = self._engine.earns_money(player.get_currentstate(), roll, False) self._log("\t\t{0} earned {1} for their blues.".format(player.name, earned)) player.award_money(earned) next_idx = self._get_next_player(next_idx) player = self._players[self._currentPlayer] earned = self._engine.earns_money(player.get_currentstate(), roll, True) self._log("\t\t{0} earned {1} for their blues and greens.".format(player.name, earned)) player.award_money(earned) def reset(self): self._currentDeck = deepcopy(self._initialDeck) self._init_game() self._randomize_first_player() def _randomize_first_player(self): self._currentPlayer = random.randint(0, self._playerCount-1) def get_players(self): result = [] for player in self._players: result.append(player.name) return result def get_result(self): return GameResult(self.winner, self.total_turns)
true
true
f72d3911465af80a203ccedab020f7e0013fa7da
6,068
py
Python
mcdp/mcstring.py
HWServer/Mcdp
5877d371ffb6ff3ddc13312d65902707e378d026
[ "Apache-2.0" ]
null
null
null
mcdp/mcstring.py
HWServer/Mcdp
5877d371ffb6ff3ddc13312d65902707e378d026
[ "Apache-2.0" ]
null
null
null
mcdp/mcstring.py
HWServer/Mcdp
5877d371ffb6ff3ddc13312d65902707e378d026
[ "Apache-2.0" ]
null
null
null
from pydantic import validator, Field from typing import Dict, List, Any, Literal, Tuple, Union, Optional from .typings import McdpBaseModel from .config import check_mc_version, MinecraftVersionError class MCStringObj(McdpBaseModel): def json(self, **kw) -> str: data = self.dict(**kw) return self.__config__.json_dumps(data) class Score(MCStringObj): name: str objective: str value: Optional[str] = None class ClickEvent(MCStringObj): action: Literal["open_url", "run_command", "suggest_command", "change_page", "copy_to_clipboard"] value: str @check_mc_version('>=1.16') def _hover_event_checker( action: Literal["show_text", "show_item", "show_entity"], value: Optional[str], _contents: Optional[Union[str, list, dict]] ) -> Tuple: if not _contents: if value: return value, _contents else: raise ValueError("invalid string attrs 'hoverEvent'.") if action == 'show_text': if isinstance(_contents, dict): contents = MCString(**_contents) else: contents = _contents elif action == 'show_item': if not isinstance(_contents, dict): raise ValueError("invalid string attrs 'hoverEvent'.") contents = HoverItem(**_contents) elif action == 'show_entity': if not isinstance(_contents, dict): raise ValueError("invalid string attrs 'hoverEvent'.") contents = HoverEntity(**_contents) return value, contents @check_mc_version('<1.16') def _hover_event_checker( action: Literal["show_text", "show_item", "show_entity"], value: Optional[str], _contents: Optional[Union[str, list, dict]] ) -> Tuple: if _contents: raise MinecraftVersionError( "the attribute 'contents' only can be used in Minecraft 1.16+.") return value, None class HoverEvent(MCStringObj): action: Literal["show_text", "show_item", "show_entity"] value: Optional[str] = None contents: Optional[Union[str, list, "MCString", "HoverItem", "HoverEntity"]] = None def __init__( self, *, action: str, value: Optional[str] = None, contents: Optional[Union[str, list, dict]] = None ) -> None: value, contents = _hover_event_checker(action, value, contents) super().__init__(action=action, value=value, contents=contents) class HoverItem(MCStringObj): id: str count: Optional[int] = None tag: Optional[str] = None class HoverEntity(MCStringObj): name: Optional["MCString"] = None type: str id: Optional[str] = None _stand_color = ("black", "dark_blue", "dark_green", "dark_aqua", "dark_red", "dark_purple", "gold", "gray", "dark_gray", "blue", "green", "aqua", "red", "light_purple", "yellow", "white", "reset") @check_mc_version('>=1.16') def _check_color(color: str) -> None: if not color in _stand_color and color.startswith('#'): try: int(color[1:]) except (TypeError, ValueError): pass else: return elif color in _stand_color: return raise ValueError("invalid string attrs 'color'.") @check_mc_version('<1.16') def _check_color(color: str) -> None: if not color in _stand_color: raise ValueError("invalid string attrs 'color'.") class MCSS(MCStringObj): color: str = None bold: bool = None italic: bool = None underlined: bool = None strikethrough: bool = None obfuscated: bool = None font: str = None separator: Union[str, dict] = None insertion: str = None clickEvent: ClickEvent = None hoverEvent: HoverEvent = None @validator('color') def colorValidator(cls, val: str) -> str: _check_color(val) return val def __call__(self, text: Optional[str] = None, **kw): if text: kw["text"] = text return MCString(**self.dict(), **kw) class MCString(MCSS): text: str = None translate: str = None with_: list = Field(default=None, alias='with') score: Score = None selector: str = None keybind: str = None nbt: str = None block: str = None entity: str = None storage: str = None extra: list = None def __new__(cls, string: Any = None, **data) -> "MCString": if not string or isinstance(string, str): return MCSS.__new__(cls) elif hasattr(string, "__mcstr__"): return string.__mcstr__() else: raise TypeError(f"Invalid string {string}.") def __init__(self, string: Optional[Union[str, "MCString"]] = None, **data: Any) -> None: if string: if not isinstance(string, str): return data["text"] = string super().__init__(**data) def __mod__(self, _with: Union[str, "MCString", Tuple[Any]]) -> "MCString": self = self.copy() if not self.translate: self.translate = self.text del self.text if isinstance(_with, self.__class__): _with = (_with,) elif isinstance(_with, tuple): _with = tuple((self.__class__(x) for x in _with)) else: _with = (self.__class__(_with),) if self.with_: self.with_.extend(_with) else: self.with_ = list(_with) return self @classmethod def validate(cls, val): if isinstance(val, str) or hasattr(val, "__mcstr__"): return cls(val) elif isinstance(val, cls): return val else: raise TypeError("Invalid mcstring.") def dict( self, *, exclude_none: bool = True, **kwds ) -> Dict[str, Any]: data = super().dict(exclude_none=exclude_none, **kwds) if 'with_' in data: data['with'] = data.pop('with_') return data def __str__(self) -> str: return self.json()
28.223256
101
0.593276
from pydantic import validator, Field from typing import Dict, List, Any, Literal, Tuple, Union, Optional from .typings import McdpBaseModel from .config import check_mc_version, MinecraftVersionError class MCStringObj(McdpBaseModel): def json(self, **kw) -> str: data = self.dict(**kw) return self.__config__.json_dumps(data) class Score(MCStringObj): name: str objective: str value: Optional[str] = None class ClickEvent(MCStringObj): action: Literal["open_url", "run_command", "suggest_command", "change_page", "copy_to_clipboard"] value: str @check_mc_version('>=1.16') def _hover_event_checker( action: Literal["show_text", "show_item", "show_entity"], value: Optional[str], _contents: Optional[Union[str, list, dict]] ) -> Tuple: if not _contents: if value: return value, _contents else: raise ValueError("invalid string attrs 'hoverEvent'.") if action == 'show_text': if isinstance(_contents, dict): contents = MCString(**_contents) else: contents = _contents elif action == 'show_item': if not isinstance(_contents, dict): raise ValueError("invalid string attrs 'hoverEvent'.") contents = HoverItem(**_contents) elif action == 'show_entity': if not isinstance(_contents, dict): raise ValueError("invalid string attrs 'hoverEvent'.") contents = HoverEntity(**_contents) return value, contents @check_mc_version('<1.16') def _hover_event_checker( action: Literal["show_text", "show_item", "show_entity"], value: Optional[str], _contents: Optional[Union[str, list, dict]] ) -> Tuple: if _contents: raise MinecraftVersionError( "the attribute 'contents' only can be used in Minecraft 1.16+.") return value, None class HoverEvent(MCStringObj): action: Literal["show_text", "show_item", "show_entity"] value: Optional[str] = None contents: Optional[Union[str, list, "MCString", "HoverItem", "HoverEntity"]] = None def __init__( self, *, action: str, value: Optional[str] = None, contents: Optional[Union[str, list, dict]] = None ) -> None: value, contents = _hover_event_checker(action, value, contents) super().__init__(action=action, value=value, contents=contents) class HoverItem(MCStringObj): id: str count: Optional[int] = None tag: Optional[str] = None class HoverEntity(MCStringObj): name: Optional["MCString"] = None type: str id: Optional[str] = None _stand_color = ("black", "dark_blue", "dark_green", "dark_aqua", "dark_red", "dark_purple", "gold", "gray", "dark_gray", "blue", "green", "aqua", "red", "light_purple", "yellow", "white", "reset") @check_mc_version('>=1.16') def _check_color(color: str) -> None: if not color in _stand_color and color.startswith('#'): try: int(color[1:]) except (TypeError, ValueError): pass else: return elif color in _stand_color: return raise ValueError("invalid string attrs 'color'.") @check_mc_version('<1.16') def _check_color(color: str) -> None: if not color in _stand_color: raise ValueError("invalid string attrs 'color'.") class MCSS(MCStringObj): color: str = None bold: bool = None italic: bool = None underlined: bool = None strikethrough: bool = None obfuscated: bool = None font: str = None separator: Union[str, dict] = None insertion: str = None clickEvent: ClickEvent = None hoverEvent: HoverEvent = None @validator('color') def colorValidator(cls, val: str) -> str: _check_color(val) return val def __call__(self, text: Optional[str] = None, **kw): if text: kw["text"] = text return MCString(**self.dict(), **kw) class MCString(MCSS): text: str = None translate: str = None with_: list = Field(default=None, alias='with') score: Score = None selector: str = None keybind: str = None nbt: str = None block: str = None entity: str = None storage: str = None extra: list = None def __new__(cls, string: Any = None, **data) -> "MCString": if not string or isinstance(string, str): return MCSS.__new__(cls) elif hasattr(string, "__mcstr__"): return string.__mcstr__() else: raise TypeError(f"Invalid string {string}.") def __init__(self, string: Optional[Union[str, "MCString"]] = None, **data: Any) -> None: if string: if not isinstance(string, str): return data["text"] = string super().__init__(**data) def __mod__(self, _with: Union[str, "MCString", Tuple[Any]]) -> "MCString": self = self.copy() if not self.translate: self.translate = self.text del self.text if isinstance(_with, self.__class__): _with = (_with,) elif isinstance(_with, tuple): _with = tuple((self.__class__(x) for x in _with)) else: _with = (self.__class__(_with),) if self.with_: self.with_.extend(_with) else: self.with_ = list(_with) return self @classmethod def validate(cls, val): if isinstance(val, str) or hasattr(val, "__mcstr__"): return cls(val) elif isinstance(val, cls): return val else: raise TypeError("Invalid mcstring.") def dict( self, *, exclude_none: bool = True, **kwds ) -> Dict[str, Any]: data = super().dict(exclude_none=exclude_none, **kwds) if 'with_' in data: data['with'] = data.pop('with_') return data def __str__(self) -> str: return self.json()
true
true
f72d3a61f612d2a23374b9374aeaf98f51986974
680
py
Python
migrations/versions/bcb4dc0e73e2_lower_activites.py
betagouv/ecosante
cc7dd76bb65405ba44f432197de851dc7e22ed38
[ "MIT" ]
3
2021-09-24T14:07:51.000Z
2021-12-14T13:48:34.000Z
migrations/versions/bcb4dc0e73e2_lower_activites.py
betagouv/recosante-api
4560b2cf2ff4dc19597792fe15a3805f6259201d
[ "MIT" ]
187
2021-03-25T16:43:49.000Z
2022-03-23T14:40:31.000Z
migrations/versions/bcb4dc0e73e2_lower_activites.py
betagouv/recosante-api
4560b2cf2ff4dc19597792fe15a3805f6259201d
[ "MIT" ]
2
2020-04-08T11:56:17.000Z
2020-04-09T14:04:15.000Z
"""lower activites Revision ID: bcb4dc0e73e2 Revises: 25116bbd585c Create Date: 2020-10-06 11:34:47.860748 """ from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text # revision identifiers, used by Alembic. revision = 'bcb4dc0e73e2' down_revision = '25116bbd585c' branch_labels = None depends_on = None def upgrade(): #op.drop_column('inscription', 'frequence_old') #op.drop_column('inscription', 'diffusion_old') conn = op.get_bind() conn.execute( text( """ UPDATE inscription SET activites=(SELECT array(SELECT lower(unnest(activites)))); """ ) ) def downgrade(): pass
18.888889
93
0.667647
from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text revision = 'bcb4dc0e73e2' down_revision = '25116bbd585c' branch_labels = None depends_on = None def upgrade(): conn = op.get_bind() conn.execute( text( """ UPDATE inscription SET activites=(SELECT array(SELECT lower(unnest(activites)))); """ ) ) def downgrade(): pass
true
true
f72d3bd5c2745fd8a21e158ba4e738b50066729f
1,529
py
Python
Artsy.py
pde-bakk/Artsy
f7c7a9d019b16d193d0418ddd7728ad9026f21e9
[ "MIT" ]
1
2020-12-22T06:13:52.000Z
2020-12-22T06:13:52.000Z
Artsy.py
pde-bakk/Artsy
f7c7a9d019b16d193d0418ddd7728ad9026f21e9
[ "MIT" ]
null
null
null
Artsy.py
pde-bakk/Artsy
f7c7a9d019b16d193d0418ddd7728ad9026f21e9
[ "MIT" ]
null
null
null
#!/usr/bin/python3 # **************************************************************************** # # # # :::::::: # # Artsy.py :+: :+: # # +:+ # # By: peerdb <peerdb@student.codam.nl> +#+ # # +#+ # # Created: 2020/11/30 19:16:01 by peerdb #+# #+# # # Updated: 2020/11/30 19:52:56 by peerdb ######## odam.nl # # # # **************************************************************************** # import sys, time, random, os from PIL import Image from GenerateASCII import generate_ascii if len(sys.argv) >= 2: imageName = sys.argv[1] + ".gif" else: imageName = "thor.gif" try: if '../' in imageName: print('Please only supply images in the "imgs/" folder') raise FileNotFoundError im = Image.open("imgs/" + imageName) except FileNotFoundError: print(f'Problem opening {"imgs/" + imageName}.\nPlease check your path again.') exit(1) while True: for frame in range(im.n_frames): im.seek(frame) generate_ascii(im) time.sleep(4.0 / im.n_frames)
40.236842
83
0.335513
Name) except FileNotFoundError: print(f'Problem opening {"imgs/" + imageName}.\nPlease check your path again.') exit(1) while True: for frame in range(im.n_frames): im.seek(frame) generate_ascii(im) time.sleep(4.0 / im.n_frames)
true
true
f72d3cd8fc9fdc84dd4cdf801ecc7d6a16740ea9
5,233
py
Python
axelerate/networks/common_utils/callbacks.py
joaopdss/aXeleRate
791c8b29056ed11bd0ed306e620664577ec9724c
[ "MIT" ]
148
2020-03-18T01:36:20.000Z
2022-03-24T08:56:45.000Z
axelerate/networks/common_utils/callbacks.py
joaopdss/aXeleRate
791c8b29056ed11bd0ed306e620664577ec9724c
[ "MIT" ]
55
2020-03-29T14:36:44.000Z
2022-02-17T22:35:03.000Z
axelerate/networks/common_utils/callbacks.py
joaopdss/aXeleRate
791c8b29056ed11bd0ed306e620664577ec9724c
[ "MIT" ]
57
2020-04-01T14:22:53.000Z
2022-01-31T13:09:49.000Z
import numpy as np from tensorflow import keras from tensorflow.keras import backend as K def cosine_decay_with_warmup(global_step, learning_rate_base, total_steps, warmup_learning_rate=0.0, warmup_steps=0, hold_base_rate_steps=0): """Cosine decay schedule with warm up period. Cosine annealing learning rate as described in: Loshchilov and Hutter, SGDR: Stochastic Gradient Descent with Warm Restarts. ICLR 2017. https://arxiv.org/abs/1608.03983 In this schedule, the learning rate grows linearly from warmup_learning_rate to learning_rate_base for warmup_steps, then transitions to a cosine decay schedule. Arguments: global_step {int} -- global step. learning_rate_base {float} -- base learning rate. total_steps {int} -- total number of training steps. Keyword Arguments: warmup_learning_rate {float} -- initial learning rate for warm up. (default: {0.0}) warmup_steps {int} -- number of warmup steps. (default: {0}) hold_base_rate_steps {int} -- Optional number of steps to hold base learning rate before decaying. (default: {0}) Returns: a float representing learning rate. Raises: ValueError: if warmup_learning_rate is larger than learning_rate_base, or if warmup_steps is larger than total_steps. """ if total_steps < warmup_steps: raise ValueError('total_steps must be larger or equal to ' 'warmup_steps.') learning_rate = 0.5 * learning_rate_base * (1 + np.cos( np.pi * (global_step - warmup_steps - hold_base_rate_steps ) / float(total_steps - warmup_steps - hold_base_rate_steps))) if hold_base_rate_steps > 0: learning_rate = np.where(global_step > warmup_steps + hold_base_rate_steps, learning_rate, learning_rate_base) if warmup_steps > 0: if learning_rate_base < warmup_learning_rate: raise ValueError('learning_rate_base must be larger or equal to ' 'warmup_learning_rate.') slope = (learning_rate_base - warmup_learning_rate) / warmup_steps warmup_rate = slope * global_step + warmup_learning_rate learning_rate = np.where(global_step < warmup_steps, warmup_rate, learning_rate) return np.where(global_step > total_steps, 0.0, learning_rate) class WarmUpCosineDecayScheduler(keras.callbacks.Callback): """Cosine decay with warmup learning rate scheduler """ def __init__(self, learning_rate_base, total_steps, global_step_init=0, warmup_learning_rate=0.0, warmup_steps=0, hold_base_rate_steps=0, verbose=0): """Constructor for cosine decay with warmup learning rate scheduler. Arguments: learning_rate_base {float} -- base learning rate. total_steps {int} -- total number of training steps. Keyword Arguments: global_step_init {int} -- initial global step, e.g. from previous checkpoint. warmup_learning_rate {float} -- initial learning rate for warm up. (default: {0.0}) warmup_steps {int} -- number of warmup steps. (default: {0}) hold_base_rate_steps {int} -- Optional number of steps to hold base learning rate before decaying. (default: {0}) verbose {int} -- 0: quiet, 1: update messages. (default: {0}) """ super(WarmUpCosineDecayScheduler, self).__init__() self.learning_rate_base = learning_rate_base self.total_steps = total_steps self.global_step = global_step_init self.warmup_learning_rate = warmup_learning_rate self.warmup_steps = warmup_steps self.hold_base_rate_steps = hold_base_rate_steps self.verbose = verbose self.learning_rates = [] self.current_lr = 0.0 def on_epoch_end(self, epoch, logs={}): if self.verbose == 1: print('Epoch %05d: Learning rate is %s.\n' % (epoch, self.current_lr)) def on_batch_end(self, batch, logs=None): self.global_step = self.global_step + 1 lr = K.get_value(self.model.optimizer.lr) self.learning_rates.append(lr) def on_batch_begin(self, batch, logs=None): self.current_lr = cosine_decay_with_warmup(global_step=self.global_step, learning_rate_base=self.learning_rate_base, total_steps=self.total_steps, warmup_learning_rate=self.warmup_learning_rate, warmup_steps=self.warmup_steps, hold_base_rate_steps=self.hold_base_rate_steps) K.set_value(self.model.optimizer.lr, self.current_lr) if self.verbose ==2: print('\nBatch %05d: setting learning rate to %s.' % (self.global_step + 1, self.current_lr))
47.144144
105
0.620868
import numpy as np from tensorflow import keras from tensorflow.keras import backend as K def cosine_decay_with_warmup(global_step, learning_rate_base, total_steps, warmup_learning_rate=0.0, warmup_steps=0, hold_base_rate_steps=0): if total_steps < warmup_steps: raise ValueError('total_steps must be larger or equal to ' 'warmup_steps.') learning_rate = 0.5 * learning_rate_base * (1 + np.cos( np.pi * (global_step - warmup_steps - hold_base_rate_steps ) / float(total_steps - warmup_steps - hold_base_rate_steps))) if hold_base_rate_steps > 0: learning_rate = np.where(global_step > warmup_steps + hold_base_rate_steps, learning_rate, learning_rate_base) if warmup_steps > 0: if learning_rate_base < warmup_learning_rate: raise ValueError('learning_rate_base must be larger or equal to ' 'warmup_learning_rate.') slope = (learning_rate_base - warmup_learning_rate) / warmup_steps warmup_rate = slope * global_step + warmup_learning_rate learning_rate = np.where(global_step < warmup_steps, warmup_rate, learning_rate) return np.where(global_step > total_steps, 0.0, learning_rate) class WarmUpCosineDecayScheduler(keras.callbacks.Callback): def __init__(self, learning_rate_base, total_steps, global_step_init=0, warmup_learning_rate=0.0, warmup_steps=0, hold_base_rate_steps=0, verbose=0): super(WarmUpCosineDecayScheduler, self).__init__() self.learning_rate_base = learning_rate_base self.total_steps = total_steps self.global_step = global_step_init self.warmup_learning_rate = warmup_learning_rate self.warmup_steps = warmup_steps self.hold_base_rate_steps = hold_base_rate_steps self.verbose = verbose self.learning_rates = [] self.current_lr = 0.0 def on_epoch_end(self, epoch, logs={}): if self.verbose == 1: print('Epoch %05d: Learning rate is %s.\n' % (epoch, self.current_lr)) def on_batch_end(self, batch, logs=None): self.global_step = self.global_step + 1 lr = K.get_value(self.model.optimizer.lr) self.learning_rates.append(lr) def on_batch_begin(self, batch, logs=None): self.current_lr = cosine_decay_with_warmup(global_step=self.global_step, learning_rate_base=self.learning_rate_base, total_steps=self.total_steps, warmup_learning_rate=self.warmup_learning_rate, warmup_steps=self.warmup_steps, hold_base_rate_steps=self.hold_base_rate_steps) K.set_value(self.model.optimizer.lr, self.current_lr) if self.verbose ==2: print('\nBatch %05d: setting learning rate to %s.' % (self.global_step + 1, self.current_lr))
true
true
f72d3d948483dbe026cf497504af1a8d42844da7
14,549
py
Python
grr/core/grr_response_core/lib/rdfvalues/protodict.py
AjitNair2/grr
2a2ea891b3927775872904cdd402a18e7bb3d143
[ "Apache-2.0" ]
1
2019-08-17T14:02:44.000Z
2019-08-17T14:02:44.000Z
grr/core/grr_response_core/lib/rdfvalues/protodict.py
AjitNair2/grr
2a2ea891b3927775872904cdd402a18e7bb3d143
[ "Apache-2.0" ]
null
null
null
grr/core/grr_response_core/lib/rdfvalues/protodict.py
AjitNair2/grr
2a2ea891b3927775872904cdd402a18e7bb3d143
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python """A generic serializer for python dictionaries.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import collections from future.builtins import str from future.utils import iteritems from future.utils import itervalues from future.utils import python_2_unicode_compatible from past.builtins import long from typing import cast, List, Text, Union from grr_response_core.lib import rdfvalue from grr_response_core.lib import utils from grr_response_core.lib.rdfvalues import structs as rdf_structs from grr_response_proto import jobs_pb2 class EmbeddedRDFValue(rdf_structs.RDFProtoStruct): """An object that contains a serialized RDFValue.""" protobuf = jobs_pb2.EmbeddedRDFValue rdf_deps = [ rdfvalue.RDFDatetime, ] def __init__(self, initializer=None, payload=None, *args, **kwargs): if (not payload and isinstance(initializer, rdfvalue.RDFValue) and not isinstance(initializer, EmbeddedRDFValue)): # The initializer is an RDFValue object that we can use as payload. payload = initializer initializer = None super(EmbeddedRDFValue, self).__init__( initializer=initializer, *args, **kwargs) if payload is not None: self.payload = payload @property def payload(self): """Extracts and returns the serialized object.""" try: rdf_cls = self.classes.get(self.name) if rdf_cls: value = rdf_cls.FromSerializedBytes(self.data) value.age = self.embedded_age return value except TypeError: return None @payload.setter def payload(self, payload): self.name = payload.__class__.__name__ self.embedded_age = payload.age self.data = payload.SerializeToBytes() def __reduce__(self): return type(self), (None, self.payload) class DataBlob(rdf_structs.RDFProtoStruct): """Wrapper class for DataBlob protobuf.""" protobuf = jobs_pb2.DataBlob rdf_deps = [ "BlobArray", # TODO(user): dependency loop. "Dict", # TODO(user): dependency loop. EmbeddedRDFValue, ] def SetValue(self, value, raise_on_error=True): """Receives a value and fills it into a DataBlob. Args: value: value to set raise_on_error: if True, raise if we can't serialize. If False, set the key to an error string. Returns: self Raises: TypeError: if the value can't be serialized and raise_on_error is True """ type_mappings = [(Text, "string"), (bytes, "data"), (bool, "boolean"), (int, "integer"), (long, "integer"), (dict, "dict"), (float, "float")] if value is None: self.none = "None" elif isinstance(value, rdfvalue.RDFValue): self.rdf_value.data = value.SerializeToBytes() self.rdf_value.age = int(value.age) self.rdf_value.name = value.__class__.__name__ elif isinstance(value, (list, tuple)): self.list.content.Extend([ DataBlob().SetValue(v, raise_on_error=raise_on_error) for v in value ]) elif isinstance(value, set): self.set.content.Extend([ DataBlob().SetValue(v, raise_on_error=raise_on_error) for v in value ]) elif isinstance(value, dict): self.dict.FromDict(value, raise_on_error=raise_on_error) else: for type_mapping, member in type_mappings: if isinstance(value, type_mapping): setattr(self, member, value) return self message = "Unsupported type for ProtoDict: %s" % type(value) if raise_on_error: raise TypeError(message) setattr(self, "string", message) return self def GetValue(self, ignore_error=True): """Extracts and returns a single value from a DataBlob.""" if self.HasField("none"): return None field_names = [ "integer", "string", "data", "boolean", "list", "dict", "rdf_value", "float", "set" ] values = [getattr(self, x) for x in field_names if self.HasField(x)] if len(values) != 1: return None if self.HasField("boolean"): return bool(values[0]) # Unpack RDFValues. if self.HasField("rdf_value"): try: rdf_class = rdfvalue.RDFValue.classes[self.rdf_value.name] return rdf_class.FromSerializedBytes( self.rdf_value.data, age=self.rdf_value.age) except (ValueError, KeyError) as e: if ignore_error: return e raise elif self.HasField("list"): return [x.GetValue() for x in self.list.content] elif self.HasField("set"): return set([x.GetValue() for x in self.set.content]) else: return values[0] class KeyValue(rdf_structs.RDFProtoStruct): protobuf = jobs_pb2.KeyValue rdf_deps = [ DataBlob, ] @python_2_unicode_compatible class Dict(rdf_structs.RDFProtoStruct): """A high level interface for protobuf Dict objects. This effectively converts from a dict to a proto and back. The dict may contain strings (python unicode objects), int64, or binary blobs (python string objects) as keys and values. """ protobuf = jobs_pb2.Dict rdf_deps = [ KeyValue, ] _values = None def __init__(self, initializer=None, age=None, **kwarg): super(Dict, self).__init__(initializer=None, age=age) self.dat = None # type: Union[List[KeyValue], rdf_structs.RepeatedFieldHelper] # Support initializing from a mapping if isinstance(initializer, dict): self.FromDict(initializer) # Can be initialized from kwargs (like a dict). elif initializer is None: self.FromDict(kwarg) # Initialize from another Dict. elif isinstance(initializer, Dict): self.FromDict(initializer.ToDict()) self.age = initializer.age else: raise rdfvalue.InitializeError("Invalid initializer for ProtoDict.") def ToDict(self): result = {} for x in itervalues(self._values): key = x.k.GetValue() result[key] = x.v.GetValue() try: # Try to unpack nested AttributedDicts result[key] = result[key].ToDict() except AttributeError: pass return result def FromDict(self, dictionary, raise_on_error=True): # First clear and then set the dictionary. self._values = {} for key, value in iteritems(dictionary): self._values[key] = KeyValue( k=DataBlob().SetValue(key, raise_on_error=raise_on_error), v=DataBlob().SetValue(value, raise_on_error=raise_on_error)) self.dat = itervalues(self._values) return self def __getitem__(self, key): return self._values[key].v.GetValue() def __contains__(self, key): return key in self._values # TODO: This implementation is flawed. It returns a new instance # on each invocation, effectively preventing changes to mutable # datastructures, e.g. `dct["key"] = []; dct["key"].append(5)`. def GetItem(self, key, default=None): if key in self._values: return self._values[key].v.GetValue() return default def Items(self): for x in itervalues(self._values): yield x.k.GetValue(), x.v.GetValue() def Values(self): for x in itervalues(self._values): yield x.v.GetValue() def Keys(self): for x in itervalues(self._values): yield x.k.GetValue() get = utils.Proxy("GetItem") items = utils.Proxy("Items") keys = utils.Proxy("Keys") values = utils.Proxy("Values") def __delitem__(self, key): # TODO(user):pytype: assigning "dirty" here is a hack. The assumption # that self.dat is RepeatedFieldHelper may not hold. For some reason the # type checker doesn not respect the isinstance check below and explicit # cast is required. if not isinstance(self.dat, rdf_structs.RepeatedFieldHelper): raise TypeError("self.dat has an unexpected type %s" % self.dat.__class__) cast(rdf_structs.RepeatedFieldHelper, self.dat).dirty = True del self._values[key] def __len__(self): return len(self._values) def SetItem(self, key, value, raise_on_error=True): """Alternative to __setitem__ that can ignore errors. Sometimes we want to serialize a structure that contains some simple objects, and some that can't be serialized. This method gives the caller a way to specify that they don't care about values that can't be serialized. Args: key: dict key value: dict value raise_on_error: if True, raise if we can't serialize. If False, set the key to an error string. """ # TODO(user):pytype: assigning "dirty" here is a hack. The assumption # that self.dat is RepeatedFieldHelper may not hold. For some reason the # type checker doesn not respect the isinstance check below and explicit # cast is required. if not isinstance(self.dat, rdf_structs.RepeatedFieldHelper): raise TypeError("self.dat has an unexpected type %s" % self.dat.__class__) cast(rdf_structs.RepeatedFieldHelper, self.dat).dirty = True self._values[key] = KeyValue( k=DataBlob().SetValue(key, raise_on_error=raise_on_error), v=DataBlob().SetValue(value, raise_on_error=raise_on_error)) def __setitem__(self, key, value): # TODO(user):pytype: assigning "dirty" here is a hack. The assumption # that self.dat is RepeatedFieldHelper may not hold. For some reason the # type checker doesn not respect the isinstance check below and explicit # cast is required. if not isinstance(self.dat, rdf_structs.RepeatedFieldHelper): raise TypeError("self.dat has an unexpected type %s" % self.dat.__class__) cast(rdf_structs.RepeatedFieldHelper, self.dat).dirty = True self._values[key] = KeyValue( k=DataBlob().SetValue(key), v=DataBlob().SetValue(value)) def __iter__(self): for x in itervalues(self._values): yield x.k.GetValue() # Required, because in Python 3 overriding `__eq__` nullifies `__hash__`. __hash__ = rdf_structs.RDFProtoStruct.__hash__ def __eq__(self, other): if isinstance(other, dict): return self.ToDict() == other elif isinstance(other, Dict): return self.ToDict() == other.ToDict() else: return False def GetRawData(self): self.dat = itervalues(self._values) return super(Dict, self).GetRawData() def _CopyRawData(self): self.dat = itervalues(self._values) return super(Dict, self)._CopyRawData() def SetRawData(self, raw_data): super(Dict, self).SetRawData(raw_data) self._values = {} for d in self.dat: self._values[d.k.GetValue()] = d def SerializeToBytes(self): self.dat = itervalues(self._values) return super(Dict, self).SerializeToBytes() def ParseFromBytes(self, value): super(Dict, self).ParseFromBytes(value) self._values = {} for d in self.dat: self._values[d.k.GetValue()] = d def __str__(self): return str(self.ToDict()) class AttributedDict(Dict): """A Dict that supports attribute indexing.""" protobuf = jobs_pb2.AttributedDict rdf_deps = [ KeyValue, ] def __getattr__(self, item): # Pickle is checking for the presence of overrides for various builtins. # Without this check we swallow the error and return None, which confuses # pickle protocol version 2. if item.startswith("__"): raise AttributeError() return self.GetItem(item) def __setattr__(self, item, value): # Existing class or instance members are assigned to normally. if hasattr(self.__class__, item) or item in self.__dict__: object.__setattr__(self, item, value) else: self.SetItem(item, value) class BlobArray(rdf_structs.RDFProtoStruct): protobuf = jobs_pb2.BlobArray rdf_deps = [ DataBlob, ] class RDFValueArray(rdf_structs.RDFProtoStruct): """A type which serializes a list of RDFValue instances. TODO(user): This needs to be deprecated in favor of just defining a protobuf with a repeated field (This can be now done dynamically, which is the main reason we used this in the past). """ protobuf = jobs_pb2.BlobArray allow_custom_class_name = True rdf_deps = [ DataBlob, ] # Set this to an RDFValue class to ensure all members adhere to this type. rdf_type = None def __init__(self, initializer=None, age=None): super(RDFValueArray, self).__init__(age=age) if self.__class__ == initializer.__class__: self.content = initializer.Copy().content self.age = initializer.age # Initialize from a serialized protobuf. elif isinstance(initializer, str): self.ParseFromBytes(initializer) else: try: for item in initializer: self.Append(item) except TypeError: if initializer is not None: raise rdfvalue.InitializeError( "%s can not be initialized from %s" % (self.__class__.__name__, type(initializer))) def Append(self, value=None, **kwarg): """Add another member to the array. Args: value: The new data to append to the array. **kwarg: Create a new element from these keywords. Returns: The value which was added. This can be modified further by the caller and changes will be propagated here. Raises: ValueError: If the value to add is not allowed. """ if self.rdf_type is not None: if (isinstance(value, rdfvalue.RDFValue) and value.__class__ != self.rdf_type): raise ValueError("Can only accept %s" % self.rdf_type) try: # Try to coerce the value. value = self.rdf_type(value, **kwarg) # pylint: disable=not-callable except (TypeError, ValueError): raise ValueError("Unable to initialize %s from type %s" % (self.__class__.__name__, type(value))) self.content.Append(DataBlob().SetValue(value)) def Extend(self, values): for v in values: self.Append(v) def __getitem__(self, item): return self.content[item].GetValue() def __len__(self): return len(self.content) def __iter__(self): for blob in self.content: yield blob.GetValue() def __bool__(self): return bool(self.content) # TODO: Remove after support for Python 2 is dropped. __nonzero__ = __bool__ def Pop(self, index=0): return self.content.Pop(index).GetValue() # TODO(user):pytype: Mapping is likely using abc.ABCMeta that provides a # "register" method. Type checker doesn't see this, unfortunately. collections.Mapping.register(Dict) # pytype: disable=attribute-error
30.310417
83
0.679909
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import collections from future.builtins import str from future.utils import iteritems from future.utils import itervalues from future.utils import python_2_unicode_compatible from past.builtins import long from typing import cast, List, Text, Union from grr_response_core.lib import rdfvalue from grr_response_core.lib import utils from grr_response_core.lib.rdfvalues import structs as rdf_structs from grr_response_proto import jobs_pb2 class EmbeddedRDFValue(rdf_structs.RDFProtoStruct): protobuf = jobs_pb2.EmbeddedRDFValue rdf_deps = [ rdfvalue.RDFDatetime, ] def __init__(self, initializer=None, payload=None, *args, **kwargs): if (not payload and isinstance(initializer, rdfvalue.RDFValue) and not isinstance(initializer, EmbeddedRDFValue)): payload = initializer initializer = None super(EmbeddedRDFValue, self).__init__( initializer=initializer, *args, **kwargs) if payload is not None: self.payload = payload @property def payload(self): try: rdf_cls = self.classes.get(self.name) if rdf_cls: value = rdf_cls.FromSerializedBytes(self.data) value.age = self.embedded_age return value except TypeError: return None @payload.setter def payload(self, payload): self.name = payload.__class__.__name__ self.embedded_age = payload.age self.data = payload.SerializeToBytes() def __reduce__(self): return type(self), (None, self.payload) class DataBlob(rdf_structs.RDFProtoStruct): protobuf = jobs_pb2.DataBlob rdf_deps = [ "BlobArray", "Dict", EmbeddedRDFValue, ] def SetValue(self, value, raise_on_error=True): type_mappings = [(Text, "string"), (bytes, "data"), (bool, "boolean"), (int, "integer"), (long, "integer"), (dict, "dict"), (float, "float")] if value is None: self.none = "None" elif isinstance(value, rdfvalue.RDFValue): self.rdf_value.data = value.SerializeToBytes() self.rdf_value.age = int(value.age) self.rdf_value.name = value.__class__.__name__ elif isinstance(value, (list, tuple)): self.list.content.Extend([ DataBlob().SetValue(v, raise_on_error=raise_on_error) for v in value ]) elif isinstance(value, set): self.set.content.Extend([ DataBlob().SetValue(v, raise_on_error=raise_on_error) for v in value ]) elif isinstance(value, dict): self.dict.FromDict(value, raise_on_error=raise_on_error) else: for type_mapping, member in type_mappings: if isinstance(value, type_mapping): setattr(self, member, value) return self message = "Unsupported type for ProtoDict: %s" % type(value) if raise_on_error: raise TypeError(message) setattr(self, "string", message) return self def GetValue(self, ignore_error=True): if self.HasField("none"): return None field_names = [ "integer", "string", "data", "boolean", "list", "dict", "rdf_value", "float", "set" ] values = [getattr(self, x) for x in field_names if self.HasField(x)] if len(values) != 1: return None if self.HasField("boolean"): return bool(values[0]) if self.HasField("rdf_value"): try: rdf_class = rdfvalue.RDFValue.classes[self.rdf_value.name] return rdf_class.FromSerializedBytes( self.rdf_value.data, age=self.rdf_value.age) except (ValueError, KeyError) as e: if ignore_error: return e raise elif self.HasField("list"): return [x.GetValue() for x in self.list.content] elif self.HasField("set"): return set([x.GetValue() for x in self.set.content]) else: return values[0] class KeyValue(rdf_structs.RDFProtoStruct): protobuf = jobs_pb2.KeyValue rdf_deps = [ DataBlob, ] @python_2_unicode_compatible class Dict(rdf_structs.RDFProtoStruct): protobuf = jobs_pb2.Dict rdf_deps = [ KeyValue, ] _values = None def __init__(self, initializer=None, age=None, **kwarg): super(Dict, self).__init__(initializer=None, age=age) self.dat = None if isinstance(initializer, dict): self.FromDict(initializer) elif initializer is None: self.FromDict(kwarg) elif isinstance(initializer, Dict): self.FromDict(initializer.ToDict()) self.age = initializer.age else: raise rdfvalue.InitializeError("Invalid initializer for ProtoDict.") def ToDict(self): result = {} for x in itervalues(self._values): key = x.k.GetValue() result[key] = x.v.GetValue() try: result[key] = result[key].ToDict() except AttributeError: pass return result def FromDict(self, dictionary, raise_on_error=True): self._values = {} for key, value in iteritems(dictionary): self._values[key] = KeyValue( k=DataBlob().SetValue(key, raise_on_error=raise_on_error), v=DataBlob().SetValue(value, raise_on_error=raise_on_error)) self.dat = itervalues(self._values) return self def __getitem__(self, key): return self._values[key].v.GetValue() def __contains__(self, key): return key in self._values def GetItem(self, key, default=None): if key in self._values: return self._values[key].v.GetValue() return default def Items(self): for x in itervalues(self._values): yield x.k.GetValue(), x.v.GetValue() def Values(self): for x in itervalues(self._values): yield x.v.GetValue() def Keys(self): for x in itervalues(self._values): yield x.k.GetValue() get = utils.Proxy("GetItem") items = utils.Proxy("Items") keys = utils.Proxy("Keys") values = utils.Proxy("Values") def __delitem__(self, key): if not isinstance(self.dat, rdf_structs.RepeatedFieldHelper): raise TypeError("self.dat has an unexpected type %s" % self.dat.__class__) cast(rdf_structs.RepeatedFieldHelper, self.dat).dirty = True del self._values[key] def __len__(self): return len(self._values) def SetItem(self, key, value, raise_on_error=True): if not isinstance(self.dat, rdf_structs.RepeatedFieldHelper): raise TypeError("self.dat has an unexpected type %s" % self.dat.__class__) cast(rdf_structs.RepeatedFieldHelper, self.dat).dirty = True self._values[key] = KeyValue( k=DataBlob().SetValue(key, raise_on_error=raise_on_error), v=DataBlob().SetValue(value, raise_on_error=raise_on_error)) def __setitem__(self, key, value): if not isinstance(self.dat, rdf_structs.RepeatedFieldHelper): raise TypeError("self.dat has an unexpected type %s" % self.dat.__class__) cast(rdf_structs.RepeatedFieldHelper, self.dat).dirty = True self._values[key] = KeyValue( k=DataBlob().SetValue(key), v=DataBlob().SetValue(value)) def __iter__(self): for x in itervalues(self._values): yield x.k.GetValue() __hash__ = rdf_structs.RDFProtoStruct.__hash__ def __eq__(self, other): if isinstance(other, dict): return self.ToDict() == other elif isinstance(other, Dict): return self.ToDict() == other.ToDict() else: return False def GetRawData(self): self.dat = itervalues(self._values) return super(Dict, self).GetRawData() def _CopyRawData(self): self.dat = itervalues(self._values) return super(Dict, self)._CopyRawData() def SetRawData(self, raw_data): super(Dict, self).SetRawData(raw_data) self._values = {} for d in self.dat: self._values[d.k.GetValue()] = d def SerializeToBytes(self): self.dat = itervalues(self._values) return super(Dict, self).SerializeToBytes() def ParseFromBytes(self, value): super(Dict, self).ParseFromBytes(value) self._values = {} for d in self.dat: self._values[d.k.GetValue()] = d def __str__(self): return str(self.ToDict()) class AttributedDict(Dict): protobuf = jobs_pb2.AttributedDict rdf_deps = [ KeyValue, ] def __getattr__(self, item): if item.startswith("__"): raise AttributeError() return self.GetItem(item) def __setattr__(self, item, value): if hasattr(self.__class__, item) or item in self.__dict__: object.__setattr__(self, item, value) else: self.SetItem(item, value) class BlobArray(rdf_structs.RDFProtoStruct): protobuf = jobs_pb2.BlobArray rdf_deps = [ DataBlob, ] class RDFValueArray(rdf_structs.RDFProtoStruct): protobuf = jobs_pb2.BlobArray allow_custom_class_name = True rdf_deps = [ DataBlob, ] rdf_type = None def __init__(self, initializer=None, age=None): super(RDFValueArray, self).__init__(age=age) if self.__class__ == initializer.__class__: self.content = initializer.Copy().content self.age = initializer.age elif isinstance(initializer, str): self.ParseFromBytes(initializer) else: try: for item in initializer: self.Append(item) except TypeError: if initializer is not None: raise rdfvalue.InitializeError( "%s can not be initialized from %s" % (self.__class__.__name__, type(initializer))) def Append(self, value=None, **kwarg): if self.rdf_type is not None: if (isinstance(value, rdfvalue.RDFValue) and value.__class__ != self.rdf_type): raise ValueError("Can only accept %s" % self.rdf_type) try: value = self.rdf_type(value, **kwarg) except (TypeError, ValueError): raise ValueError("Unable to initialize %s from type %s" % (self.__class__.__name__, type(value))) self.content.Append(DataBlob().SetValue(value)) def Extend(self, values): for v in values: self.Append(v) def __getitem__(self, item): return self.content[item].GetValue() def __len__(self): return len(self.content) def __iter__(self): for blob in self.content: yield blob.GetValue() def __bool__(self): return bool(self.content) __nonzero__ = __bool__ def Pop(self, index=0): return self.content.Pop(index).GetValue() collections.Mapping.register(Dict) # pytype: disable=attribute-error
true
true
f72d3e3660c3afa145347ee9328b2093b79c0d7d
8,025
py
Python
Truth-and-Dare.py
sayantan-kuila/Truth-and-Dare_BOT
bf4306e4d526cb33af5ee7003ddc2c809aa7f8a5
[ "MIT" ]
null
null
null
Truth-and-Dare.py
sayantan-kuila/Truth-and-Dare_BOT
bf4306e4d526cb33af5ee7003ddc2c809aa7f8a5
[ "MIT" ]
null
null
null
Truth-and-Dare.py
sayantan-kuila/Truth-and-Dare_BOT
bf4306e4d526cb33af5ee7003ddc2c809aa7f8a5
[ "MIT" ]
null
null
null
from keep_alive import keep_alive import discord from discord.ext import commands,tasks from itertools import cycle import random intents = discord.Intents(messages = True , guilds = True , reactions = True , members = True , presences = True) client = commands.Bot(command_prefix = '.', intents = intents) @client.event async def on_ready(): change_status.start() print("I am turned on!!") status = cycle(['With Friends','With Parents','With Love','With Yourself']) @tasks.loop(seconds=5) async def change_status(): await client.change_presence(activity=discord.Game(f'{next(status)} | .help')) @client.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandNotFound): await ctx.send('Invalid Command Used. Type .help to know the commands') if isinstance(error, commands.MissingRequiredArgument): await ctx.send('Give proper values to the command an argument is missing') @client.command() async def clean(ctx, num = 1): await ctx.channel.purge(limit = num+1) truths = ["What’s the last lie you told?", "Whose chats/calls do you ignore the most in this room?" , "What’s your most bizarre nickname?" , "What’s been your most physically painful experience?" , "What’s the craziest thing you’ve done on public transportation?" , "If you met a genie, what would your three wishes be?/n You cannot say 'n' more wishes." , "What’s one thing you’d do if you knew there no consequences?" , "What’s the craziest thing you’ve done in front of a mirror?" , "What’s the meanest thing you’ve ever said about someone else?" , "Who are you most jealous of?" , "What's the type of cloth your partner to wears that turns you on?" , "Would you date your high school crush today?" , "Do you believe in any superstitions? If so, which ones and why?" , "What’s your most embarrassing habit?" , "Have you ever considered cheating on a partner? If yes then why?" , "If you were guaranteed to never get caught, who on Earth would you murder?" , "What’s the cheapest gift you’ve ever gotten for someone else?" , "Which of your family members annoys you the most and why?" , "What’s your biggest regret in life?" , "Have you ever regretted something you did to get a crush or partner’s attention?" , "What’s one not so common job you could never do?" , "If you switched genders for a day, what would you do?" , "When’s the last time you made someone else cry and how?" , "What’s the most embarrassing thing you’ve done in front of a crowd?" , "If you could become invisible, what’s the worst thing you’d do?" , "Have you ever farted and blamed it on someone else and to whom?" , "What’s something you would die if your mom found out about?" , "If you had one week to live and you had to marry someone in this room, who would it be?\nImagine everyone in your list is single." , "List one negative thing about anyone in the room." , "What’s the most sinful thing you’ve done in a house of worship?" , "Who would you call to help bury a body?" , "What’s the most embarrassing thing your parents have caught you doing?\nAhem ahem!" , "When’s the last time you peed your pants?" , "What’s your biggest insecurity?" , "If you could hire someone to do one thing for you, what would it be?" , "What’s the best lie/brag you’ve ever told anyone?" , "What’s the weirdest thing you’ve ever done in a bathroom? Ahem Ahem!" , "What’s the biggest secret you’ve kept from your parents?" , "If you were rescuing people from a burning building and you had to leave one person behind from this room, who would it be?\nCruel isn't it :p" , "When did you first started watching p*rn?" , "Why are you still addicted to something that you know is bad?" , "Have you ever hit on anyone's private part?What's their worst reaction" , "If you could get a bf from this room assuming everyone's single, who would it be?" , "Who do you think hits on you the most in this room?"] dares = ["Call your crush or any random person you never talk and start a random talk." , "Belly dance, twerk or do the moonwalk in front of everyone." , "Quote or enact your favourite Bollywood celebrity!" , "Try putting your entire fist in your mouth!" , "Call a person(opposite sex) and tell him that he/she is the most handsome/beatuiful person you have ever seen." , "Sing a romantic song." , "Share an old, embarrassing picture from your FB album on your timeline." , "Talk in a different accent for one hour." , "Apply soap on your face and don’t wash it for 10 minutes." , "Call up a restaurant and ask them the contact number of another restaurant." , "Post a random long status on Facebook/Instagram/Whatsapp Status." , "Remove your socks with your teeth." , "Do jumping jacks for one minute." , "Dial a random number and sing ‘Happy Birthday!’" , "Talk like a robot for the next 15 minutes of the game." , "Call up your friend and tell him/her how much you love his/her boyfriend/girlfriend." , "Tell your siblings that you just found out they are adopted." , "Fill your mouth with water and sing a song." , "Sing a song in a sexy voice." , "Try to turn someone on in the room." , "Kiss a stuffed toy/object passionately." , "Pick up a random book and read a chapter in the most seductive voice you can manage." , "Say atleast one honest thing about every player in the room." , "Do 20 push-ups." , "Eat 2-7 green chillies." , "Roast the person below you." , "Shave a small portion of your head with a trimmer." , "Do your best impression of someone in the room and keep going until someone correctly guesses who it is." , "Fake a pregnancy on social media." , "Take a selfie and upload it now, without any filters on your whatsapp status without hiding anymore person." , "Show us how you cry alone." , "Go to Facebook or Instagram profile of the girl and comment romantic line(s) on her pic." , "Sing like you are an opera singer." , "Call the last person you texted and shout on him/her." , "Make the first five emoji faces that you have used recently." , "Call an old friend of yours and tell him/her that they were your first crush." , "Make a call to your teacher. Ask, when will be the next class?" , "Predict the future of every person in this room. " , "Call/text someone randomly and say, You have a crush on them. (wait for their response)" , "Call/text someone randomly and say, You want to have a threesome with them. (wait for their response)" , "Confess something, that no one knows." , "Draw something on your forehead." , "Talk like Alexa or Siri." , "Call your partner and inform. “It’s over.”" , "Share your thoughts on relationships and marriage, like an expert." , "Go out and shout “I don't want to die.” Three times." , "Cry as if you just broke up with your loving partner. " , "Lick your shoe/slipper." , "Apply dettol to your face mask." , "How would you react if your partner says, let's have s*x." , "Act as if your parents caught you m@$turb@t!ng." , "Drink 1L of water right now." , "Dance but no one should record." , "Try doing a bottle flip but everytime you fail you scream." , "Shout song lyrics for next 10 seconds." , "Roast a person here." , "Draw something on your cheek with marker." , "Send a message in the chat about your sexual fantasies." , "Moan for next 30 seconds." , "Say O with your mouth closed." , "Start talking in babu shona totla language for the next 30minutes." , "Solve a question from any given assignment right now." , "Solve JEE Advance 2021 Physics first question?"] @client.command(aliases = ['t']) async def truth(ctx): await ctx.send(random.choice(truths)) @client.command(aliases = ['d']) async def dare(ctx): await ctx.send(random.choice(dares)) keep_alive() client.run('ODQyODY3NDewrsaDY1.YJ7jcg.wWLwkaBA_SsfhsosfaXROuQlU')
29.076087
147
0.701807
from keep_alive import keep_alive import discord from discord.ext import commands,tasks from itertools import cycle import random intents = discord.Intents(messages = True , guilds = True , reactions = True , members = True , presences = True) client = commands.Bot(command_prefix = '.', intents = intents) @client.event async def on_ready(): change_status.start() print("I am turned on!!") status = cycle(['With Friends','With Parents','With Love','With Yourself']) @tasks.loop(seconds=5) async def change_status(): await client.change_presence(activity=discord.Game(f'{next(status)} | .help')) @client.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandNotFound): await ctx.send('Invalid Command Used. Type .help to know the commands') if isinstance(error, commands.MissingRequiredArgument): await ctx.send('Give proper values to the command an argument is missing') @client.command() async def clean(ctx, num = 1): await ctx.channel.purge(limit = num+1) truths = ["What’s the last lie you told?", "Whose chats/calls do you ignore the most in this room?" , "What’s your most bizarre nickname?" , "What’s been your most physically painful experience?" , "What’s the craziest thing you’ve done on public transportation?" , "If you met a genie, what would your three wishes be?/n You cannot say 'n' more wishes." , "What’s one thing you’d do if you knew there no consequences?" , "What’s the craziest thing you’ve done in front of a mirror?" , "What’s the meanest thing you’ve ever said about someone else?" , "Who are you most jealous of?" , "What's the type of cloth your partner to wears that turns you on?" , "Would you date your high school crush today?" , "Do you believe in any superstitions? If so, which ones and why?" , "What’s your most embarrassing habit?" , "Have you ever considered cheating on a partner? If yes then why?" , "If you were guaranteed to never get caught, who on Earth would you murder?" , "What’s the cheapest gift you’ve ever gotten for someone else?" , "Which of your family members annoys you the most and why?" , "What’s your biggest regret in life?" , "Have you ever regretted something you did to get a crush or partner’s attention?" , "What’s one not so common job you could never do?" , "If you switched genders for a day, what would you do?" , "When’s the last time you made someone else cry and how?" , "What’s the most embarrassing thing you’ve done in front of a crowd?" , "If you could become invisible, what’s the worst thing you’d do?" , "Have you ever farted and blamed it on someone else and to whom?" , "What’s something you would die if your mom found out about?" , "If you had one week to live and you had to marry someone in this room, who would it be?\nImagine everyone in your list is single." , "List one negative thing about anyone in the room." , "What’s the most sinful thing you’ve done in a house of worship?" , "Who would you call to help bury a body?" , "What’s the most embarrassing thing your parents have caught you doing?\nAhem ahem!" , "When’s the last time you peed your pants?" , "What’s your biggest insecurity?" , "If you could hire someone to do one thing for you, what would it be?" , "What’s the best lie/brag you’ve ever told anyone?" , "What’s the weirdest thing you’ve ever done in a bathroom? Ahem Ahem!" , "What’s the biggest secret you’ve kept from your parents?" , "If you were rescuing people from a burning building and you had to leave one person behind from this room, who would it be?\nCruel isn't it :p" , "When did you first started watching p*rn?" , "Why are you still addicted to something that you know is bad?" , "Have you ever hit on anyone's private part?What's their worst reaction" , "If you could get a bf from this room assuming everyone's single, who would it be?" , "Who do you think hits on you the most in this room?"] dares = ["Call your crush or any random person you never talk and start a random talk." , "Belly dance, twerk or do the moonwalk in front of everyone." , "Quote or enact your favourite Bollywood celebrity!" , "Try putting your entire fist in your mouth!" , "Call a person(opposite sex) and tell him that he/she is the most handsome/beatuiful person you have ever seen." , "Sing a romantic song." , "Share an old, embarrassing picture from your FB album on your timeline." , "Talk in a different accent for one hour." , "Apply soap on your face and don’t wash it for 10 minutes." , "Call up a restaurant and ask them the contact number of another restaurant." , "Post a random long status on Facebook/Instagram/Whatsapp Status." , "Remove your socks with your teeth." , "Do jumping jacks for one minute." , "Dial a random number and sing ‘Happy Birthday!’" , "Talk like a robot for the next 15 minutes of the game." , "Call up your friend and tell him/her how much you love his/her boyfriend/girlfriend." , "Tell your siblings that you just found out they are adopted." , "Fill your mouth with water and sing a song." , "Sing a song in a sexy voice." , "Try to turn someone on in the room." , "Kiss a stuffed toy/object passionately." , "Pick up a random book and read a chapter in the most seductive voice you can manage." , "Say atleast one honest thing about every player in the room." , "Do 20 push-ups." , "Eat 2-7 green chillies." , "Roast the person below you." , "Shave a small portion of your head with a trimmer." , "Do your best impression of someone in the room and keep going until someone correctly guesses who it is." , "Fake a pregnancy on social media." , "Take a selfie and upload it now, without any filters on your whatsapp status without hiding anymore person." , "Show us how you cry alone." , "Go to Facebook or Instagram profile of the girl and comment romantic line(s) on her pic." , "Sing like you are an opera singer." , "Call the last person you texted and shout on him/her." , "Make the first five emoji faces that you have used recently." , "Call an old friend of yours and tell him/her that they were your first crush." , "Make a call to your teacher. Ask, when will be the next class?" , "Predict the future of every person in this room. " , "Call/text someone randomly and say, You have a crush on them. (wait for their response)" , "Call/text someone randomly and say, You want to have a threesome with them. (wait for their response)" , "Confess something, that no one knows." , "Draw something on your forehead." , "Talk like Alexa or Siri." , "Call your partner and inform. “It’s over.”" , "Share your thoughts on relationships and marriage, like an expert." , "Go out and shout “I don't want to die.” Three times." , "Cry as if you just broke up with your loving partner. " , "Lick your shoe/slipper." , "Apply dettol to your face mask." , "How would you react if your partner says, let's have s*x." , "Act as if your parents caught you m@$turb@t!ng." , "Drink 1L of water right now." , "Dance but no one should record." , "Try doing a bottle flip but everytime you fail you scream." , "Shout song lyrics for next 10 seconds." , "Roast a person here." , "Draw something on your cheek with marker." , "Send a message in the chat about your sexual fantasies." , "Moan for next 30 seconds." , "Say O with your mouth closed." , "Start talking in babu shona totla language for the next 30minutes." , "Solve a question from any given assignment right now." , "Solve JEE Advance 2021 Physics first question?"] @client.command(aliases = ['t']) async def truth(ctx): await ctx.send(random.choice(truths)) @client.command(aliases = ['d']) async def dare(ctx): await ctx.send(random.choice(dares)) keep_alive() client.run('ODQyODY3NDewrsaDY1.YJ7jcg.wWLwkaBA_SsfhsosfaXROuQlU')
true
true
f72d3e497e472525f055e00a6ef6329de6c33abd
3,605
py
Python
model-optimizer/unit_tests/extensions/front/div_test.py
monroid/openvino
8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6
[ "Apache-2.0" ]
2,406
2020-04-22T15:47:54.000Z
2022-03-31T10:27:37.000Z
model-optimizer/unit_tests/extensions/front/div_test.py
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
4,948
2020-04-22T15:12:39.000Z
2022-03-31T18:45:42.000Z
model-optimizer/unit_tests/extensions/front/div_test.py
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
991
2020-04-23T18:21:09.000Z
2022-03-31T18:40:57.000Z
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import unittest import numpy as np from extensions.front.div import Div from mo.utils.ir_engine.compare_graphs import compare_graphs from unit_tests.utils.graph import build_graph, result, regular_op_with_shaped_data, valued_const_with_data, connect, \ connect_data nodes = { **regular_op_with_shaped_data('placeholder_1', [1, 227, 227, 3], {'type': 'Parameter'}), **regular_op_with_shaped_data('placeholder_2', [1, 227, 227, 3], {'type': 'Parameter'}), **regular_op_with_shaped_data('div', None, {'op': 'Div', 'type': 'Divide', 'name': 'my_div'}), **regular_op_with_shaped_data('reciprocal', [1, 227, 227, 3], {'type': 'Power'}), **valued_const_with_data('minus_one', np.array(-1.)), **regular_op_with_shaped_data('mul', None, {'type': 'Multiply'}), **result(), } class TestDiv(unittest.TestCase): def test_div_test_1(self): # Test with two different inputs from two placeholders graph = build_graph(nodes, [ *connect('placeholder_1', '0:div'), *connect('placeholder_2', '1:div'), *connect('div', 'output'), ], nodes_with_edges_only=True) Div().find_and_replace_pattern(graph) graph_ref = build_graph(nodes, [ *connect('placeholder_1', '0:mul'), *connect('placeholder_2', '0:reciprocal'), *connect('minus_one', '1:reciprocal'), *connect('reciprocal', '1:mul'), *connect('mul', 'output'), ], nodes_with_edges_only=True) (flag, resp) = compare_graphs(graph, graph_ref, 'output', check_op_attrs=True) self.assertTrue(flag, resp) self.assertTrue(graph.node[graph.get_nodes_with_attributes(type='Multiply')[0]]['name'] == 'my_div') def test_div_test_2(self): # Test with two same inputs from one placeholder graph = build_graph(nodes, [ *connect('placeholder_1:0', '0:div'), *connect_data('placeholder_1:0', '1:div'), *connect('div', 'output'), ], nodes_with_edges_only=True) Div().find_and_replace_pattern(graph) graph_ref = build_graph(nodes, [ *connect('placeholder_1:0', '0:mul'), *connect_data('placeholder_1:0', '0:reciprocal'), *connect('minus_one', '1:reciprocal'), *connect('reciprocal', '1:mul'), *connect('mul', 'output'), ], nodes_with_edges_only=True) (flag, resp) = compare_graphs(graph, graph_ref, 'output', check_op_attrs=True) self.assertTrue(flag, resp) self.assertTrue(graph.node[graph.get_nodes_with_attributes(type='Multiply')[0]]['name'] == 'my_div') def test_div_with_integer(self): # Test where transformation should not be applied because the divisor is integer graph = build_graph({ **regular_op_with_shaped_data('parameter', [1, 227, 227, 3], {'type': 'Parameter', 'data_type': np.int32}), **valued_const_with_data('const', np.array([-1.], dtype=np.int32)), **regular_op_with_shaped_data('div', None, {'op': 'Div', 'type': 'Divide', 'name': 'my_div'}), **result()}, [ *connect('parameter:0', '0:div'), *connect_data('const:0', '1:div'), *connect('div', 'output'), ]) graph_ref = graph.copy() Div().find_and_replace_pattern(graph) (flag, resp) = compare_graphs(graph, graph_ref, 'output', check_op_attrs=True) self.assertTrue(flag, resp)
41.918605
119
0.615257
import unittest import numpy as np from extensions.front.div import Div from mo.utils.ir_engine.compare_graphs import compare_graphs from unit_tests.utils.graph import build_graph, result, regular_op_with_shaped_data, valued_const_with_data, connect, \ connect_data nodes = { **regular_op_with_shaped_data('placeholder_1', [1, 227, 227, 3], {'type': 'Parameter'}), **regular_op_with_shaped_data('placeholder_2', [1, 227, 227, 3], {'type': 'Parameter'}), **regular_op_with_shaped_data('div', None, {'op': 'Div', 'type': 'Divide', 'name': 'my_div'}), **regular_op_with_shaped_data('reciprocal', [1, 227, 227, 3], {'type': 'Power'}), **valued_const_with_data('minus_one', np.array(-1.)), **regular_op_with_shaped_data('mul', None, {'type': 'Multiply'}), **result(), } class TestDiv(unittest.TestCase): def test_div_test_1(self): graph = build_graph(nodes, [ *connect('placeholder_1', '0:div'), *connect('placeholder_2', '1:div'), *connect('div', 'output'), ], nodes_with_edges_only=True) Div().find_and_replace_pattern(graph) graph_ref = build_graph(nodes, [ *connect('placeholder_1', '0:mul'), *connect('placeholder_2', '0:reciprocal'), *connect('minus_one', '1:reciprocal'), *connect('reciprocal', '1:mul'), *connect('mul', 'output'), ], nodes_with_edges_only=True) (flag, resp) = compare_graphs(graph, graph_ref, 'output', check_op_attrs=True) self.assertTrue(flag, resp) self.assertTrue(graph.node[graph.get_nodes_with_attributes(type='Multiply')[0]]['name'] == 'my_div') def test_div_test_2(self): graph = build_graph(nodes, [ *connect('placeholder_1:0', '0:div'), *connect_data('placeholder_1:0', '1:div'), *connect('div', 'output'), ], nodes_with_edges_only=True) Div().find_and_replace_pattern(graph) graph_ref = build_graph(nodes, [ *connect('placeholder_1:0', '0:mul'), *connect_data('placeholder_1:0', '0:reciprocal'), *connect('minus_one', '1:reciprocal'), *connect('reciprocal', '1:mul'), *connect('mul', 'output'), ], nodes_with_edges_only=True) (flag, resp) = compare_graphs(graph, graph_ref, 'output', check_op_attrs=True) self.assertTrue(flag, resp) self.assertTrue(graph.node[graph.get_nodes_with_attributes(type='Multiply')[0]]['name'] == 'my_div') def test_div_with_integer(self): graph = build_graph({ **regular_op_with_shaped_data('parameter', [1, 227, 227, 3], {'type': 'Parameter', 'data_type': np.int32}), **valued_const_with_data('const', np.array([-1.], dtype=np.int32)), **regular_op_with_shaped_data('div', None, {'op': 'Div', 'type': 'Divide', 'name': 'my_div'}), **result()}, [ *connect('parameter:0', '0:div'), *connect_data('const:0', '1:div'), *connect('div', 'output'), ]) graph_ref = graph.copy() Div().find_and_replace_pattern(graph) (flag, resp) = compare_graphs(graph, graph_ref, 'output', check_op_attrs=True) self.assertTrue(flag, resp)
true
true
f72d3eb7ca0c3e84b7139eab0d79d7cc70f487df
1,158
py
Python
oss/ossimport/PUTCONFIGTOOSS.py
yibozhang/aliyunproduct
770205029c7bf3a0913c08a0e8bed2e0953579f1
[ "MIT" ]
null
null
null
oss/ossimport/PUTCONFIGTOOSS.py
yibozhang/aliyunproduct
770205029c7bf3a0913c08a0e8bed2e0953579f1
[ "MIT" ]
null
null
null
oss/ossimport/PUTCONFIGTOOSS.py
yibozhang/aliyunproduct
770205029c7bf3a0913c08a0e8bed2e0953579f1
[ "MIT" ]
1
2020-08-08T01:57:21.000Z
2020-08-08T01:57:21.000Z
#!/usr/bin/env python import oss2 class PUTCONFIGTOOSS(object): def __init__(self,DEST,STORESIZE): self.AK = '' self.SK = '' self.ENDPOINT = 'http://oss-cn-hangzhou.aliyuncs.com' self.BUCKET = 'ali-hangzhou' self.DEST = DEST self.STORESIZE = STORESIZE def INITIAL(self): try: AUTH = oss2.Auth(self.AK,self.SK) BUCKETS = oss2.Bucket(AUTH, self.ENDPOINT,self.BUCKET) SYSOBJS = '{0}/sys.properties'.format(self.DEST) if self.STORESIZE == "less-than-30": OBJECTS = '{0}/local_job.cfg'.format(self.DEST) else: OBJECTS = '{0}/{1}.cfg'.format(self.DEST,self.DEST) with open('/tmp/{0}.cfg'.format(self.DEST), 'rb') as FILEOBJ: OSSRESP = BUCKETS.put_object(OBJECTS, FILEOBJ) with open('/tmp/{0}.properties'.format(self.DEST), 'rb') as SYSOBJ: SYSRESP = BUCKETS.put_object(SYSOBJS, SYSOBJ) CFGDOWN = 'http://{0}.oss-cn-hangzhou.aliyuncs.com/{1}'.format(self.BUCKET,OBJECTS) SYSDOWN = 'http://{0}.oss-cn-hangzhou.aliyuncs.com/{1}'.format(self.BUCKET,SYSOBJS) return CFGDOWN,SYSDOWN except Exception: print(e) return e
28.243902
89
0.630397
import oss2 class PUTCONFIGTOOSS(object): def __init__(self,DEST,STORESIZE): self.AK = '' self.SK = '' self.ENDPOINT = 'http://oss-cn-hangzhou.aliyuncs.com' self.BUCKET = 'ali-hangzhou' self.DEST = DEST self.STORESIZE = STORESIZE def INITIAL(self): try: AUTH = oss2.Auth(self.AK,self.SK) BUCKETS = oss2.Bucket(AUTH, self.ENDPOINT,self.BUCKET) SYSOBJS = '{0}/sys.properties'.format(self.DEST) if self.STORESIZE == "less-than-30": OBJECTS = '{0}/local_job.cfg'.format(self.DEST) else: OBJECTS = '{0}/{1}.cfg'.format(self.DEST,self.DEST) with open('/tmp/{0}.cfg'.format(self.DEST), 'rb') as FILEOBJ: OSSRESP = BUCKETS.put_object(OBJECTS, FILEOBJ) with open('/tmp/{0}.properties'.format(self.DEST), 'rb') as SYSOBJ: SYSRESP = BUCKETS.put_object(SYSOBJS, SYSOBJ) CFGDOWN = 'http://{0}.oss-cn-hangzhou.aliyuncs.com/{1}'.format(self.BUCKET,OBJECTS) SYSDOWN = 'http://{0}.oss-cn-hangzhou.aliyuncs.com/{1}'.format(self.BUCKET,SYSOBJS) return CFGDOWN,SYSDOWN except Exception: print(e) return e
true
true
f72d3ee94c4789ef5592f0a51b0087799e26cbd9
859
py
Python
src/djangoreactredux/djrenv/lib/python3.5/site-packages/setoptconf/source/yamlfile.py
m2jobe/c_x
ba914449a9a85d82703895fc884733ca20454034
[ "MIT" ]
4
2016-08-11T20:00:07.000Z
2020-08-09T01:33:22.000Z
src/djangoreactredux/djrenv/lib/python3.5/site-packages/setoptconf/source/yamlfile.py
m2jobe/c_x
ba914449a9a85d82703895fc884733ca20454034
[ "MIT" ]
7
2020-02-12T03:06:52.000Z
2021-06-10T19:33:14.000Z
src/djangoreactredux/djrenv/lib/python3.5/site-packages/setoptconf/source/yamlfile.py
m2jobe/c_x
ba914449a9a85d82703895fc884733ca20454034
[ "MIT" ]
2
2015-01-27T10:42:03.000Z
2021-09-09T07:17:52.000Z
import codecs import yaml from .filebased import FileBasedSource __all__ = ( 'YamlFileSource', ) class YamlFileSource(FileBasedSource): def __init__(self, *args, **kwargs): self.encoding = kwargs.pop('encoding', 'utf-8') super(YamlFileSource, self).__init__(*args, **kwargs) def get_settings_from_file(self, file_path, settings, manager=None): content = codecs.open(file_path, 'r', self.encoding).read().strip() if not content: return None content = yaml.safe_load(content) if not content: return None if not isinstance(content, dict): raise TypeError('YAML files must contain only mappings') for setting in settings: if setting.name in content: setting.value = content[setting.name] return settings
24.542857
75
0.633295
import codecs import yaml from .filebased import FileBasedSource __all__ = ( 'YamlFileSource', ) class YamlFileSource(FileBasedSource): def __init__(self, *args, **kwargs): self.encoding = kwargs.pop('encoding', 'utf-8') super(YamlFileSource, self).__init__(*args, **kwargs) def get_settings_from_file(self, file_path, settings, manager=None): content = codecs.open(file_path, 'r', self.encoding).read().strip() if not content: return None content = yaml.safe_load(content) if not content: return None if not isinstance(content, dict): raise TypeError('YAML files must contain only mappings') for setting in settings: if setting.name in content: setting.value = content[setting.name] return settings
true
true
f72d408bda5345b17a849e6391721b7debb832c5
7,477
py
Python
sme_financing/main/apis/funding_project_api.py
BuildForSDG/team-214-backend
f1aff9c27d7b7588b4bbb2bc68956b35051d4506
[ "MIT" ]
1
2020-05-20T16:32:33.000Z
2020-05-20T16:32:33.000Z
sme_financing/main/apis/funding_project_api.py
BuildForSDG/team-214-backend
f1aff9c27d7b7588b4bbb2bc68956b35051d4506
[ "MIT" ]
23
2020-05-19T07:12:53.000Z
2020-06-21T03:57:54.000Z
sme_financing/main/apis/funding_project_api.py
BuildForSDG/team-214-backend
f1aff9c27d7b7588b4bbb2bc68956b35051d4506
[ "MIT" ]
1
2020-05-18T14:18:12.000Z
2020-05-18T14:18:12.000Z
from flask import request from flask_restx import Resource, reqparse from flask_restx._http import HTTPStatus from werkzeug.datastructures import FileStorage from ..service import funding_detail_service as fd_service from ..service import funding_project_service as fp_service from .dto import FundingDetailDTO, FundingProjectDTO api = FundingProjectDTO.funding_project_api _funding_project = FundingProjectDTO.funding_project _funding_detail = FundingDetailDTO.funding_detail _funding_detail_parser = reqparse.RequestParser() _funding_detail_parser.add_argument( "title", required=True, type=str, help="Funding detail title", location="form" ) _funding_detail_parser.add_argument( "description", required=True, type=str, help="Funding detail description", location="form", ) _funding_detail_parser.add_argument( "document_name", type=str, help="Document name", location="form" ) _funding_detail_parser.add_argument("file", type=FileStorage, location="files") @api.route("/") class FundingProjectList(Resource): @api.doc("list of funding projects") @api.marshal_list_with(_funding_project, envelope="data") def get(self): """List all funding projects.""" return fp_service.get_all_funding_projects() @api.doc("Create a new funding project") @api.expect(_funding_project, validate=True) @api.response(HTTPStatus.NOT_FOUND, "Investor not found") @api.response(HTTPStatus.NOT_FOUND, "Funding application not found") @api.response(201, "Funding project successfully registered") def post(self): """Create a new funding project.""" data = request.json return fp_service.create_funding_project(data=data) @api.route("/<funding_project_number>") @api.param("funding_project_number", "Funding project number to process") class FundingProjectByID(Resource): @api.doc("Get a single funding project") @api.marshal_with(_funding_project) def get(self, funding_project_number): """Retrieve a funding project by number.""" funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) else: return funding_project @api.doc("Delete an funding project") @api.response(HTTPStatus.BAD_REQUEST, "Can't delete the funding project") def delete(self, funding_project_number): """Delete an funding project.""" funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) else: return fp_service.delete_funding_project(funding_project) @api.doc("Update a Funding project") @api.expect(_funding_project, validate=True) @api.response(HTTPStatus.CREATED, "Funding project successfully updated") @api.response(HTTPStatus.BAD_REQUEST, "Can't update the Funding project") def patch(self, funding_project_number): """Update a Funding project.""" funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) else: data = request.json return fp_service.update_funding_project(data, funding_project) @api.route("/<funding_project_number>/funding_details") @api.param("funding_project_number", "Funding project number to process") @api.response(HTTPStatus.NOT_FOUND, "Funding detail not found") class FundingProjectDetail(Resource): @api.doc("list of funding details of a funding project") @api.marshal_list_with(_funding_detail, envelope="data") def get(self, funding_project_number): """ List all funding details of a funding project. """ return fp_service.get_project_funding_details(funding_project_number) @api.doc("Add funding detail") @api.expect(_funding_detail_parser, validate=True) @api.response(HTTPStatus.NOT_FOUND, "Funding project not found") @api.response(201, "Funding detail successfully added") def post(self, funding_project_number): """Add a funding detail.""" funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) else: data = _funding_detail_parser.parse_args() if not data["title"] or not data["description"]: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Empty inputs", ) else: return fd_service.create_funding_detail(data, funding_project) @api.route("/<funding_project_number>/funding_details/<funding_detail_id>") @api.param("funding_project_number", "Funding project number to process") @api.param("funding_detail_id", "Funding detail ID to process") @api.response(HTTPStatus.NOT_FOUND, "Funding detail not found") class FundingProjectDetailByID(Resource): @api.doc("Remove funding detail") @api.response(HTTPStatus.NOT_FOUND, "Funding project not found") @api.response(201, "Funding detail successfully added") def delete(self, funding_project_number, funding_detail_id): """Remove funding detail.""" funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) funding_detail = fd_service.get_funding_detail_by_id(funding_detail_id) if not funding_detail: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding detail not found" ) return fp_service.remove_funding_detail(funding_project, funding_detail) # @api.route("/<funding_project_number>/project_milestones") # @api.param("funding_project_number", "Funding project number to process") # @api.response(HTTPStatus.NOT_FOUND, "Funding detail not found") # class FundingProjectMilestones(Resource): # @api.doc("list of project milestones of a funding project") # @api.marshal_list_with(_funding_milestone, envelope="data") # def get(self, funding_project_number): # """ # List all project milestones of a funding project. # """ # return fp_service.get_project_project_milestones(funding_project_number) # @api.route("/<funding_project_number>/fund_disbursements") # @api.param("funding_project_number", "Funding project number to process") # @api.response(HTTPStatus.NOT_FOUND, "Fund disbursements not found") # class FundingProjectFundDisbursement(Resource): # @api.doc("list of fund disbursements of a funding project") # @api.marshal_list_with(_fund_disbursement, envelope="data") # def get(self, funding_project_number): # """ # List all fund disbursements of a funding project. # """ # return fp_service.get_project_fund_disbursements(funding_project_number)
40.857923
82
0.700816
from flask import request from flask_restx import Resource, reqparse from flask_restx._http import HTTPStatus from werkzeug.datastructures import FileStorage from ..service import funding_detail_service as fd_service from ..service import funding_project_service as fp_service from .dto import FundingDetailDTO, FundingProjectDTO api = FundingProjectDTO.funding_project_api _funding_project = FundingProjectDTO.funding_project _funding_detail = FundingDetailDTO.funding_detail _funding_detail_parser = reqparse.RequestParser() _funding_detail_parser.add_argument( "title", required=True, type=str, help="Funding detail title", location="form" ) _funding_detail_parser.add_argument( "description", required=True, type=str, help="Funding detail description", location="form", ) _funding_detail_parser.add_argument( "document_name", type=str, help="Document name", location="form" ) _funding_detail_parser.add_argument("file", type=FileStorage, location="files") @api.route("/") class FundingProjectList(Resource): @api.doc("list of funding projects") @api.marshal_list_with(_funding_project, envelope="data") def get(self): return fp_service.get_all_funding_projects() @api.doc("Create a new funding project") @api.expect(_funding_project, validate=True) @api.response(HTTPStatus.NOT_FOUND, "Investor not found") @api.response(HTTPStatus.NOT_FOUND, "Funding application not found") @api.response(201, "Funding project successfully registered") def post(self): data = request.json return fp_service.create_funding_project(data=data) @api.route("/<funding_project_number>") @api.param("funding_project_number", "Funding project number to process") class FundingProjectByID(Resource): @api.doc("Get a single funding project") @api.marshal_with(_funding_project) def get(self, funding_project_number): funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) else: return funding_project @api.doc("Delete an funding project") @api.response(HTTPStatus.BAD_REQUEST, "Can't delete the funding project") def delete(self, funding_project_number): funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) else: return fp_service.delete_funding_project(funding_project) @api.doc("Update a Funding project") @api.expect(_funding_project, validate=True) @api.response(HTTPStatus.CREATED, "Funding project successfully updated") @api.response(HTTPStatus.BAD_REQUEST, "Can't update the Funding project") def patch(self, funding_project_number): funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) else: data = request.json return fp_service.update_funding_project(data, funding_project) @api.route("/<funding_project_number>/funding_details") @api.param("funding_project_number", "Funding project number to process") @api.response(HTTPStatus.NOT_FOUND, "Funding detail not found") class FundingProjectDetail(Resource): @api.doc("list of funding details of a funding project") @api.marshal_list_with(_funding_detail, envelope="data") def get(self, funding_project_number): return fp_service.get_project_funding_details(funding_project_number) @api.doc("Add funding detail") @api.expect(_funding_detail_parser, validate=True) @api.response(HTTPStatus.NOT_FOUND, "Funding project not found") @api.response(201, "Funding detail successfully added") def post(self, funding_project_number): funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) else: data = _funding_detail_parser.parse_args() if not data["title"] or not data["description"]: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Empty inputs", ) else: return fd_service.create_funding_detail(data, funding_project) @api.route("/<funding_project_number>/funding_details/<funding_detail_id>") @api.param("funding_project_number", "Funding project number to process") @api.param("funding_detail_id", "Funding detail ID to process") @api.response(HTTPStatus.NOT_FOUND, "Funding detail not found") class FundingProjectDetailByID(Resource): @api.doc("Remove funding detail") @api.response(HTTPStatus.NOT_FOUND, "Funding project not found") @api.response(201, "Funding detail successfully added") def delete(self, funding_project_number, funding_detail_id): funding_project = fp_service.get_funding_project_by_number( funding_project_number ) if not funding_project: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding project not found" ) funding_detail = fd_service.get_funding_detail_by_id(funding_detail_id) if not funding_detail: self.api.abort( code=HTTPStatus.NOT_FOUND, message="Funding detail not found" ) return fp_service.remove_funding_detail(funding_project, funding_detail) # List all project milestones of a funding project. # """ # List all fund disbursements of a funding project. # """
true
true
f72d41922e895ee0d677b880780e2a005c5d83b5
1,847
py
Python
aardvark/conf/nova_conf.py
ttsiouts/aardvark
cbf29f332df86814dd581152faf863c0d29ae41c
[ "Apache-2.0" ]
null
null
null
aardvark/conf/nova_conf.py
ttsiouts/aardvark
cbf29f332df86814dd581152faf863c0d29ae41c
[ "Apache-2.0" ]
null
null
null
aardvark/conf/nova_conf.py
ttsiouts/aardvark
cbf29f332df86814dd581152faf863c0d29ae41c
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2018 European Organization for Nuclear Research. # 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 keystoneauth1 import loading as ks_loading from oslo_config import cfg SERVICE_TYPE = 'compute' compute_group = cfg.OptGroup( 'compute', title='Compute Service Options', help="Configuration options for connecting to the Nova API service" ) compute_opts = [ cfg.StrOpt("client_version", default="2.61", help=""" Selects where the API microversion requested by the novaclient. """ ), ] def register_opts(conf): conf.register_group(compute_group) conf.register_opts(compute_opts, group=compute_group) group = getattr(compute_group, 'name', compute_group) ks_loading.register_session_conf_options(conf, group) ks_loading.register_auth_conf_options(conf, group) adapter_opts = get_ksa_adapter_opts(SERVICE_TYPE) conf.register_opts(adapter_opts, group=group) def get_ksa_adapter_opts(default_service_type, deprecated_opts=None): opts = ks_loading.get_adapter_conf_options( include_deprecated=False, deprecated_opts=deprecated_opts) cfg.set_defaults(opts, valid_interfaces=['internal', 'public'], service_type=default_service_type) return opts
29.31746
78
0.728749
from keystoneauth1 import loading as ks_loading from oslo_config import cfg SERVICE_TYPE = 'compute' compute_group = cfg.OptGroup( 'compute', title='Compute Service Options', help="Configuration options for connecting to the Nova API service" ) compute_opts = [ cfg.StrOpt("client_version", default="2.61", help=""" Selects where the API microversion requested by the novaclient. """ ), ] def register_opts(conf): conf.register_group(compute_group) conf.register_opts(compute_opts, group=compute_group) group = getattr(compute_group, 'name', compute_group) ks_loading.register_session_conf_options(conf, group) ks_loading.register_auth_conf_options(conf, group) adapter_opts = get_ksa_adapter_opts(SERVICE_TYPE) conf.register_opts(adapter_opts, group=group) def get_ksa_adapter_opts(default_service_type, deprecated_opts=None): opts = ks_loading.get_adapter_conf_options( include_deprecated=False, deprecated_opts=deprecated_opts) cfg.set_defaults(opts, valid_interfaces=['internal', 'public'], service_type=default_service_type) return opts
true
true
f72d41a3123aa80a954c0db94bd894fab5e71a21
285
py
Python
exercicios-projetos-python/verificador-numero.py
lucaspalmanew/exercicios-projetos-python
fae75ee8f038811d5d869ba16d412ca726d848dc
[ "MIT" ]
null
null
null
exercicios-projetos-python/verificador-numero.py
lucaspalmanew/exercicios-projetos-python
fae75ee8f038811d5d869ba16d412ca726d848dc
[ "MIT" ]
null
null
null
exercicios-projetos-python/verificador-numero.py
lucaspalmanew/exercicios-projetos-python
fae75ee8f038811d5d869ba16d412ca726d848dc
[ "MIT" ]
null
null
null
n1 = int(input('Digite um número: ')) n2 = int(input('Digite outro número: ')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print(' A soma é {},\n o produto é {},\n a divisão é {:.3f}'.format(s, m, d)) print(' A divisão inteira é {}\n a potencia é {}'.format(di, e))
28.5
77
0.561404
n1 = int(input('Digite um número: ')) n2 = int(input('Digite outro número: ')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print(' A soma é {},\n o produto é {},\n a divisão é {:.3f}'.format(s, m, d)) print(' A divisão inteira é {}\n a potencia é {}'.format(di, e))
true
true
f72d4226675eac016336d700e165472ce8673a76
1,393
py
Python
speedcord/exceptions.py
MM-coder/speedcord
9b216a950f9766646bc54ce1cf85a7f11499c076
[ "MIT" ]
null
null
null
speedcord/exceptions.py
MM-coder/speedcord
9b216a950f9766646bc54ce1cf85a7f11499c076
[ "MIT" ]
null
null
null
speedcord/exceptions.py
MM-coder/speedcord
9b216a950f9766646bc54ce1cf85a7f11499c076
[ "MIT" ]
null
null
null
""" Created by Epic at 9/1/20 """ class HTTPException(Exception): def __init__(self, request, data): self.request = request self.data = data super().__init__(data) class Forbidden(HTTPException): pass class NotFound(HTTPException): def __init__(self, request): self.request = request Exception.__init__(self, "The selected resource was not found") class Unauthorized(HTTPException): def __init__(self, request): self.request = request Exception.__init__(self, "You are not authorized to view this resource") class LoginException(Exception): pass class InvalidToken(LoginException): def __init__(self): super().__init__("Invalid token provided.") class ShardingNotSupported(LoginException): def __init__(self): super().__init__("SpeedCord does not support sharding at this time.") class ConnectionsExceeded(LoginException): def __init__(self): super().__init__("You have exceeded your gateway connection limits") class GatewayException(Exception): pass class GatewayClosed(GatewayException): def __init__(self): super().__init__("You can't do this as the gateway is closed.") class GatewayUnavailable(GatewayException): def __init__(self): super().__init__("Can't reach the discord gateway. Have you tried checking your internet?")
23.216667
99
0.700646
class HTTPException(Exception): def __init__(self, request, data): self.request = request self.data = data super().__init__(data) class Forbidden(HTTPException): pass class NotFound(HTTPException): def __init__(self, request): self.request = request Exception.__init__(self, "The selected resource was not found") class Unauthorized(HTTPException): def __init__(self, request): self.request = request Exception.__init__(self, "You are not authorized to view this resource") class LoginException(Exception): pass class InvalidToken(LoginException): def __init__(self): super().__init__("Invalid token provided.") class ShardingNotSupported(LoginException): def __init__(self): super().__init__("SpeedCord does not support sharding at this time.") class ConnectionsExceeded(LoginException): def __init__(self): super().__init__("You have exceeded your gateway connection limits") class GatewayException(Exception): pass class GatewayClosed(GatewayException): def __init__(self): super().__init__("You can't do this as the gateway is closed.") class GatewayUnavailable(GatewayException): def __init__(self): super().__init__("Can't reach the discord gateway. Have you tried checking your internet?")
true
true
f72d422cd4575a6baaf77c2ff39a10a79d61fedc
2,219
py
Python
ServerComponent/Analysers/SubjectRelevance.py
CDU55/FakeNews
707bd48dd78851081d98ad21bbdadfc2720bd644
[ "MIT" ]
null
null
null
ServerComponent/Analysers/SubjectRelevance.py
CDU55/FakeNews
707bd48dd78851081d98ad21bbdadfc2720bd644
[ "MIT" ]
37
2020-10-20T08:30:53.000Z
2020-12-22T13:15:45.000Z
ServerComponent/Analysers/SubjectRelevance.py
CDU55/FakeNews
707bd48dd78851081d98ad21bbdadfc2720bd644
[ "MIT" ]
1
2020-10-19T14:55:23.000Z
2020-10-19T14:55:23.000Z
import os import time from dask import dataframe as dd import jellyfish from TextExtraction.APIs.TextAPI import getListOfSentences csv_path = os.path.join(os.path.dirname(__file__), "india-news-headlines.csv") headlines = dd.read_csv(csv_path).headline_text def get_mean(sentances_scores): return sum(sentances_scores.values()) / len(sentances_scores.values()) def calculate_maximum_similarity(social_media_post_text, timeout=5): start = time.time() max_sim = 0 for current_headline in headlines: current_sim = jellyfish.jaro_distance(social_media_post_text, current_headline) if current_sim > max_sim: max_sim = current_sim current_time = time.time() - start if current_time > timeout: return max_sim * 100 return max_sim * 100 def calculate_maximum_similarity_mean(social_media_post_text, timeout=5): start = time.time() sentences = getListOfSentences(social_media_post_text) distance_each_sentence = {} for sentence in sentences: distance_each_sentence[sentence] = 0 for current_headline in headlines: for sentence in sentences: current_sim = jellyfish.jaro_distance(sentence, current_headline) if current_sim > distance_each_sentence[sentence]: distance_each_sentence[sentence] = current_sim current_time = time.time() - start if current_time > timeout: return get_mean(distance_each_sentence) * 100 return get_mean(distance_each_sentence) * 100 #start = time.time() #print(calculate_maximum_similarity("Another HISTORIC breakthrough today! Our two GREAT friends Israel and the Kingdom " # "of Morocco have agreed to full diplomatic relations – a massive breakthrough for " # "peace in the Middle East!")) #print(time.time() - start) #start = time.time() #dist = calculate_maximum_similarity_mean( # "Another HISTORIC breakthrough today! Our two GREAT friends Israel and the Kingdom " # "of Morocco have agreed to full diplomatic relations – a massive breakthrough for " # "peace in the Middle East!") #print(dist) #print(time.time() - start)
37.610169
120
0.706625
import os import time from dask import dataframe as dd import jellyfish from TextExtraction.APIs.TextAPI import getListOfSentences csv_path = os.path.join(os.path.dirname(__file__), "india-news-headlines.csv") headlines = dd.read_csv(csv_path).headline_text def get_mean(sentances_scores): return sum(sentances_scores.values()) / len(sentances_scores.values()) def calculate_maximum_similarity(social_media_post_text, timeout=5): start = time.time() max_sim = 0 for current_headline in headlines: current_sim = jellyfish.jaro_distance(social_media_post_text, current_headline) if current_sim > max_sim: max_sim = current_sim current_time = time.time() - start if current_time > timeout: return max_sim * 100 return max_sim * 100 def calculate_maximum_similarity_mean(social_media_post_text, timeout=5): start = time.time() sentences = getListOfSentences(social_media_post_text) distance_each_sentence = {} for sentence in sentences: distance_each_sentence[sentence] = 0 for current_headline in headlines: for sentence in sentences: current_sim = jellyfish.jaro_distance(sentence, current_headline) if current_sim > distance_each_sentence[sentence]: distance_each_sentence[sentence] = current_sim current_time = time.time() - start if current_time > timeout: return get_mean(distance_each_sentence) * 100 return get_mean(distance_each_sentence) * 100
true
true
f72d425cc6b91707415be9dbb32383c596d493c2
646
py
Python
Code/GUI/config.py
boydj9/CRDB-Project
4c5612ea50d299bb0fd76947ce18f925c6d03cae
[ "MIT" ]
null
null
null
Code/GUI/config.py
boydj9/CRDB-Project
4c5612ea50d299bb0fd76947ce18f925c6d03cae
[ "MIT" ]
null
null
null
Code/GUI/config.py
boydj9/CRDB-Project
4c5612ea50d299bb0fd76947ce18f925c6d03cae
[ "MIT" ]
null
null
null
#!/usr/bin/python """ CSC 315 Spring 2020 John DeGood This code is from: https://www.postgresqltutorial.com/postgresql-python/ """ from ConfigParser import ConfigParser def config(filename='database.ini', section='postgresql'): # create a parser parser = ConfigParser() # read config file parser.read(filename) # get section, default to postgresql db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return db
20.83871
90
0.654799
from ConfigParser import ConfigParser def config(filename='database.ini', section='postgresql'): parser = ConfigParser() parser.read(filename) db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return db
true
true
f72d4281dc07073a8e5737e6290b89c1dbc6f12d
769
py
Python
viadot/tasks/__init__.py
PanczykowskiK/viadot
44e269790b3debb02318ff4c4f07638b3a37d800
[ "MIT" ]
null
null
null
viadot/tasks/__init__.py
PanczykowskiK/viadot
44e269790b3debb02318ff4c4f07638b3a37d800
[ "MIT" ]
null
null
null
viadot/tasks/__init__.py
PanczykowskiK/viadot
44e269790b3debb02318ff4c4f07638b3a37d800
[ "MIT" ]
null
null
null
from .azure_blob_storage import BlobFromCSV from .azure_data_lake import ( AzureDataLakeCopy, AzureDataLakeDownload, AzureDataLakeList, AzureDataLakeToDF, AzureDataLakeUpload, ) from .azure_key_vault import ( AzureKeyVaultSecret, CreateAzureKeyVaultSecret, DeleteAzureKeyVaultSecret, ) from .azure_sql import ( AzureSQLBulkInsert, AzureSQLCreateTable, AzureSQLDBQuery, CreateTableFromBlob, ) from .bcp import BCPTask from .github import DownloadGitHubFile from .great_expectations import RunGreatExpectationsValidation from .sqlite import SQLiteInsert, SQLiteSQLtoDF, SQLiteQuery from .supermetrics import SupermetricsToCSV, SupermetricsToDF from .cloud_for_customers import CloudForCustomersToCSV, CloudForCustomersToDF
29.576923
78
0.819246
from .azure_blob_storage import BlobFromCSV from .azure_data_lake import ( AzureDataLakeCopy, AzureDataLakeDownload, AzureDataLakeList, AzureDataLakeToDF, AzureDataLakeUpload, ) from .azure_key_vault import ( AzureKeyVaultSecret, CreateAzureKeyVaultSecret, DeleteAzureKeyVaultSecret, ) from .azure_sql import ( AzureSQLBulkInsert, AzureSQLCreateTable, AzureSQLDBQuery, CreateTableFromBlob, ) from .bcp import BCPTask from .github import DownloadGitHubFile from .great_expectations import RunGreatExpectationsValidation from .sqlite import SQLiteInsert, SQLiteSQLtoDF, SQLiteQuery from .supermetrics import SupermetricsToCSV, SupermetricsToDF from .cloud_for_customers import CloudForCustomersToCSV, CloudForCustomersToDF
true
true
f72d4377f739886a09d9defd618c46e865d276c5
9,276
py
Python
example.py
genesiscloud/py-genesiscloud
8fb1dd1884768d8245a1903a6a8042c650788309
[ "MIT" ]
6
2020-06-16T15:38:11.000Z
2021-04-20T20:39:19.000Z
example.py
genesiscloud/py-genesiscloud
8fb1dd1884768d8245a1903a6a8042c650788309
[ "MIT" ]
3
2020-06-16T15:38:07.000Z
2021-04-21T09:50:12.000Z
example.py
genesiscloud/py-genesiscloud
8fb1dd1884768d8245a1903a6a8042c650788309
[ "MIT" ]
1
2020-06-20T05:05:04.000Z
2020-06-20T05:05:04.000Z
# MIT License # # Copyright (c) 2020 Genesis Cloud Ltd. <opensource@genesiscloud.com> # # 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. # # Authors: # Oz Tiram <otiram@genesiscloud.com> """ An example script to show how to start a Genesis Cloud GPU instance with custom user data to install the NVIDIA GPU driver. Grab your API key from the UI and save it in a safe place. on the shell before running this script $ export GENESISCLOUD_API_KEY=secretkey """ import os import textwrap import time import subprocess as sp from genesiscloud.client import Client, INSTANCE_TYPES def simple_startup_script(): """see the documentation of cloud init""" return textwrap.dedent(""" #cloud-config hostname: mytestubuntu runcmd: - [ "apt", "install", "-y", "vim" ] """) def get_startup_script(): return """#!/bin/bash set -eux IS_INSTALLED=false NVIDIA_SHORT_VERSION=430 manual_fetch_install() { __nvidia_full_version="430_430.50-0ubuntu2" for i in $(seq 1 5) do echo "Connecting to http://archive.ubuntu.com site for $i time" if curl -s --head --request GET http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-"${NVIDIA_SHORT_VERSION}" | grep "HTTP/1.1" > /dev/null ; then echo "Connected to http://archive.ubuntu.com. Start downloading and installing the NVIDIA driver..." __tempdir="$(mktemp -d)" apt-get install -y --no-install-recommends "linux-headers-$(uname -r)" dkms wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/nvidia-kernel-common-${__nvidia_full_version}_amd64.deb wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/nvidia-kernel-source-${__nvidia_full_version}_amd64.deb wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/nvidia-dkms-${__nvidia_full_version}_amd64.deb dpkg -i "${__tempdir}"/nvidia-kernel-common-${__nvidia_full_version}_amd64.deb "${__tempdir}"/nvidia-kernel-source-${__nvidia_full_version}_amd64.deb "${__tempdir}"/nvidia-dkms-${__nvidia_full_version}_amd64.deb wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/nvidia-utils-${__nvidia_full_version}_amd64.deb wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/libnvidia-compute-${__nvidia_full_version}_amd64.deb dpkg -i "${__tempdir}"/nvidia-utils-${__nvidia_full_version}_amd64.deb "${__tempdir}"/libnvidia-compute-${__nvidia_full_version}_amd64.deb IS_INSTALLED=true rm -r "${__tempdir}" break fi sleep 2 done } apt_fetch_install() { add-apt-repository -s -u -y restricted # Ubuntu has only a single version in the repository marked as "latest" of # this series. for _ in $(seq 1 5) do if apt-get install -y --no-install-recommends nvidia-utils-${NVIDIA_SHORT_VERSION} libnvidia-compute-${NVIDIA_SHORT_VERSION} \ nvidia-kernel-common-${NVIDIA_SHORT_VERSION} \ nvidia-kernel-source-${NVIDIA_SHORT_VERSION} \ nvidia-dkms-${NVIDIA_SHORT_VERSION} \ "linux-headers-$(uname -r)" dkms; then IS_INSTALLED=true break fi sleep 2 done } main() { apt-get update if grep xenial /etc/os-release; then manual_fetch_install else apt_fetch_install fi # remove the module if it is inserted, blacklist it rmmod nouveau || echo "nouveau kernel module not loaded ..." echo "blacklist nouveau" > /etc/modprobe.d/nouveau.conf # log insertion of the nvidia module # this should always succeed on customer instances if modprobe -vi nvidia; then nvidia-smi modinfo nvidia gpu_found=true else gpu_found=false fi if [ "${IS_INSTALLED}" = true ]; then echo "NVIDIA driver has been successfully installed." else echo "NVIDIA driver has NOT been installed." fi if [ "${gpu_found}" ]; then echo "NVIDIA GPU device is found and ready" else echo "WARNING: NVIDIA GPU device is not found or is failed" fi } main """ def create_instance(): client = Client(os.getenv("GENESISCLOUD_API_KEY")) # before we continue to create objects, we check that we can communicate # with the API, if the connect method does not succeed it will throw an # error and the script will terminate if client.connect(): pass # To create an instance you will need an SSH public key. # Upload it via the Web UI, you can now find it with. # replace this to match your key SSHKEYNAME = 'YourKeyName' # genesiscloud.client.Resource.find methods returns generators - that is, # they are lazy per-default. sshkey_gen = client.SSHKeys.find({"name": SSHKEYNAME}) sshkey = list(sshkey_gen)[0] # You need to tell the client which OS should be used for your instance # One can use a snapshot or a base-os to create a new instance ubuntu_18 = [image for image in client.Images.find({"name": 'Ubuntu 18.04'})][0] # choose the most simple instance type # to see the instance properties, use # list(INSTANCE_TYPES.items())[0] # # ('vcpu-4_memory-12g_disk-80g_nvidia1080ti-1', # {'vCPUs': 4, 'RAM': 12, 'Disk': 80, 'GPU': 1}) instace_type = list(INSTANCE_TYPES.keys())[0] # To create an instace use Instances.create # You must pass a ssh key to SSH into the machine. Currently, only one # SSH key is supported. If you need more use the command # `ssh-import-id-gh oz123` # it can fetch public key from github.com/oz123.keys # *Obviously* __replace__ my user name with YOURS or anyone you TRUST. # You should put this in the user_data script. You can add this in the # text block that the function `get_startup_script` returns. # NOTE: # you can also create an instance with SSH password enabled, but you should # prefer SSH key authentication. If you choose to use password, you should # not pass ssh_keys my_instance = client.Instances.create( name="demo", hostname="demo", ssh_keys=[sshkey.id], # comment this to enable password image=ubuntu_18.id, type=instace_type, metadata={"startup_script": simple_startup_script()}, #password="yourSekretPassword#12!" ) # my_instance is a dictionary containing information about the instance # that was just created. print(my_instance) while my_instance['status'] != 'active': time.sleep(1) my_instance = client.Instances.get(my_instance.id) print(f"{my_instance['status']}\r", end="") print("") # yay! the instance is active # let's ssh to the public IP of the instance public_ip = my_instance.public_ip print(f"The ssh address of the Instance is: {public_ip}") # wait for ssh to become available, this returns exit code other # than 0 as long the ssh connection isn't available while sp.run( ("ssh -l ubuntu -o StrictHostKeyChecking=accept-new " "-o ConnectTimeout=50 " f"{public_ip} hostname"), shell=True).returncode: time.sleep(1) print("Congratulations! You genesiscloud instance has been created!") print("You can ssh to it with:") print(f"ssh -l ubuntu {public_ip}") print("Some interesting commands to try at first:") print("cloud-init stats # if this is still running, NVIDIA driver is still" " installing") print("use the following to see cloud-init output in real time:") print("sudo tail -f /var/log/cloud-init-output.log") return my_instance def destroy(instance_id): # finally destory this instance, when you no longer need it client = Client(os.getenv("GENESISCLOUD_API_KEY")) client.Instances.delete(id=instance_id) if __name__ == "__main__": instance = create_instance() instance_id = instance['id'] # destroy(instance_id)
38.65
221
0.691785
import os import textwrap import time import subprocess as sp from genesiscloud.client import Client, INSTANCE_TYPES def simple_startup_script(): return textwrap.dedent(""" #cloud-config hostname: mytestubuntu runcmd: - [ "apt", "install", "-y", "vim" ] """) def get_startup_script(): return """#!/bin/bash set -eux IS_INSTALLED=false NVIDIA_SHORT_VERSION=430 manual_fetch_install() { __nvidia_full_version="430_430.50-0ubuntu2" for i in $(seq 1 5) do echo "Connecting to http://archive.ubuntu.com site for $i time" if curl -s --head --request GET http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-"${NVIDIA_SHORT_VERSION}" | grep "HTTP/1.1" > /dev/null ; then echo "Connected to http://archive.ubuntu.com. Start downloading and installing the NVIDIA driver..." __tempdir="$(mktemp -d)" apt-get install -y --no-install-recommends "linux-headers-$(uname -r)" dkms wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/nvidia-kernel-common-${__nvidia_full_version}_amd64.deb wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/nvidia-kernel-source-${__nvidia_full_version}_amd64.deb wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/nvidia-dkms-${__nvidia_full_version}_amd64.deb dpkg -i "${__tempdir}"/nvidia-kernel-common-${__nvidia_full_version}_amd64.deb "${__tempdir}"/nvidia-kernel-source-${__nvidia_full_version}_amd64.deb "${__tempdir}"/nvidia-dkms-${__nvidia_full_version}_amd64.deb wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/nvidia-utils-${__nvidia_full_version}_amd64.deb wget -P "${__tempdir}" http://archive.ubuntu.com/ubuntu/pool/restricted/n/nvidia-graphics-drivers-${NVIDIA_SHORT_VERSION}/libnvidia-compute-${__nvidia_full_version}_amd64.deb dpkg -i "${__tempdir}"/nvidia-utils-${__nvidia_full_version}_amd64.deb "${__tempdir}"/libnvidia-compute-${__nvidia_full_version}_amd64.deb IS_INSTALLED=true rm -r "${__tempdir}" break fi sleep 2 done } apt_fetch_install() { add-apt-repository -s -u -y restricted # Ubuntu has only a single version in the repository marked as "latest" of # this series. for _ in $(seq 1 5) do if apt-get install -y --no-install-recommends nvidia-utils-${NVIDIA_SHORT_VERSION} libnvidia-compute-${NVIDIA_SHORT_VERSION} \ nvidia-kernel-common-${NVIDIA_SHORT_VERSION} \ nvidia-kernel-source-${NVIDIA_SHORT_VERSION} \ nvidia-dkms-${NVIDIA_SHORT_VERSION} \ "linux-headers-$(uname -r)" dkms; then IS_INSTALLED=true break fi sleep 2 done } main() { apt-get update if grep xenial /etc/os-release; then manual_fetch_install else apt_fetch_install fi # remove the module if it is inserted, blacklist it rmmod nouveau || echo "nouveau kernel module not loaded ..." echo "blacklist nouveau" > /etc/modprobe.d/nouveau.conf # log insertion of the nvidia module # this should always succeed on customer instances if modprobe -vi nvidia; then nvidia-smi modinfo nvidia gpu_found=true else gpu_found=false fi if [ "${IS_INSTALLED}" = true ]; then echo "NVIDIA driver has been successfully installed." else echo "NVIDIA driver has NOT been installed." fi if [ "${gpu_found}" ]; then echo "NVIDIA GPU device is found and ready" else echo "WARNING: NVIDIA GPU device is not found or is failed" fi } main """ def create_instance(): client = Client(os.getenv("GENESISCLOUD_API_KEY")) if client.connect(): pass SSHKEYNAME = 'YourKeyName' sshkey_gen = client.SSHKeys.find({"name": SSHKEYNAME}) sshkey = list(sshkey_gen)[0] ubuntu_18 = [image for image in client.Images.find({"name": 'Ubuntu 18.04'})][0] instace_type = list(INSTANCE_TYPES.keys())[0] my_instance = client.Instances.create( name="demo", hostname="demo", ssh_keys=[sshkey.id], image=ubuntu_18.id, type=instace_type, metadata={"startup_script": simple_startup_script()}, ) print(my_instance) while my_instance['status'] != 'active': time.sleep(1) my_instance = client.Instances.get(my_instance.id) print(f"{my_instance['status']}\r", end="") print("") public_ip = my_instance.public_ip print(f"The ssh address of the Instance is: {public_ip}") # wait for ssh to become available, this returns exit code other # than 0 as long the ssh connection isn't available while sp.run( ("ssh -l ubuntu -o StrictHostKeyChecking=accept-new " "-o ConnectTimeout=50 " f"{public_ip} hostname"), shell=True).returncode: time.sleep(1) print("Congratulations! You genesiscloud instance has been created!") print("You can ssh to it with:") print(f"ssh -l ubuntu {public_ip}") print("Some interesting commands to try at first:") print("cloud-init stats # if this is still running, NVIDIA driver is still" " installing") print("use the following to see cloud-init output in real time:") print("sudo tail -f /var/log/cloud-init-output.log") return my_instance def destroy(instance_id): client = Client(os.getenv("GENESISCLOUD_API_KEY")) client.Instances.delete(id=instance_id) if __name__ == "__main__": instance = create_instance() instance_id = instance['id']
true
true
f72d43e040d4b3be6767b65283613caed41078b8
32,888
py
Python
sysinv/sysinv/sysinv/sysinv/api/controllers/v1/service_parameter.py
riddopic/config
59f027fc42e2b34d9609c5fd6ec956b46a480235
[ "Apache-2.0" ]
null
null
null
sysinv/sysinv/sysinv/sysinv/api/controllers/v1/service_parameter.py
riddopic/config
59f027fc42e2b34d9609c5fd6ec956b46a480235
[ "Apache-2.0" ]
null
null
null
sysinv/sysinv/sysinv/sysinv/api/controllers/v1/service_parameter.py
riddopic/config
59f027fc42e2b34d9609c5fd6ec956b46a480235
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2015-2018 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # # vim: tabstop=4 shiftwidth=4 softtabstop=4 # coding=utf-8 # import copy import pecan from pecan import rest import six import wsme from wsme import types as wtypes import wsmeext.pecan as wsme_pecan from fm_api import constants as fm_constants from fm_api import fm_api from oslo_log import log from oslo_utils import excutils from sysinv._i18n import _ from sysinv.api.controllers.v1 import base from sysinv.api.controllers.v1 import collection from sysinv.api.controllers.v1 import link from sysinv.api.controllers.v1 import types from sysinv.api.controllers.v1 import utils from sysinv.api.controllers.v1.query import Query from sysinv import objects from sysinv.common import constants from sysinv.common import service_parameter from sysinv.common import exception from sysinv.common import utils as cutils from sysinv.openstack.common.rpc import common as rpc_common LOG = log.getLogger(__name__) class ServiceParameterPatchType(types.JsonPatchType): @staticmethod def mandatory_attrs(): return ['/uuid'] class ServiceParameter(base.APIBase): """API representation of a Service Parameter instance. This class enforces type checking and value constraints, and converts between the internal object model and the API representation of a service parameter. """ id = int "Unique ID for this entry" uuid = types.uuid "Unique UUID for this entry" service = wtypes.text "Name of a service." section = wtypes.text "Name of a section." name = wtypes.text "Name of a parameter" value = wtypes.text "Value of a parameter" personality = wtypes.text "The host personality to which the parameter is restricted." resource = wtypes.text "The puppet resource" links = [link.Link] "A list containing a self link and associated links" def __init__(self, **kwargs): self.fields = list(objects.service_parameter.fields.keys()) for k in self.fields: if not hasattr(self, k): continue setattr(self, k, kwargs.get(k, wtypes.Unset)) @classmethod def convert_with_links(cls, rpc_service_parameter, expand=True): parm = ServiceParameter(**rpc_service_parameter.as_dict()) if not expand: parm.unset_fields_except(['uuid', 'service', 'section', 'name', 'value', 'personality', 'resource']) parm.links = [link.Link.make_link('self', pecan.request.host_url, 'parameters', parm.uuid), link.Link.make_link('bookmark', pecan.request.host_url, 'parameters', parm.uuid, bookmark=True) ] return parm class ServiceParameterCollection(collection.Collection): """API representation of a collection of service parameters.""" parameters = [ServiceParameter] "A list containing Service Parameter objects" def __init__(self, **kwargs): self._type = 'parameters' @classmethod def convert_with_links(cls, rpc_service_parameter, limit, url=None, expand=False, **kwargs): collection = ServiceParameterCollection() collection.parameters = [ServiceParameter.convert_with_links(p, expand) for p in rpc_service_parameter] collection.next = collection.get_next(limit, url=url, **kwargs) return collection LOCK_NAME = 'ServiceParameterController' class ServiceParameterController(rest.RestController): """REST controller for ServiceParameter.""" _custom_actions = { 'apply': ['POST'], } def __init__(self, parent=None, **kwargs): self._parent = parent def _get_service_parameter_collection(self, marker=None, limit=None, sort_key=None, sort_dir=None, expand=False, resource_url=None, q=None): limit = utils.validate_limit(limit) sort_dir = utils.validate_sort_dir(sort_dir) kwargs = {} if q is not None: for i in q: if i.op == 'eq': kwargs[i.field] = i.value marker_obj = None if marker: marker_obj = objects.service_parameter.get_by_uuid( pecan.request.context, marker) if q is None: parms = pecan.request.dbapi.service_parameter_get_list( limit=limit, marker=marker_obj, sort_key=sort_key, sort_dir=sort_dir) else: kwargs['limit'] = limit kwargs['sort_key'] = sort_key kwargs['sort_dir'] = sort_dir parms = pecan.request.dbapi.service_parameter_get_all(**kwargs) # Before we can return the service parameter collection, # we need to ensure that the list does not contain any # "protected" service parameters which may need to be # obfuscated. for idx, svc_param in enumerate(parms): service = svc_param['service'] section = svc_param['section'] name = svc_param['name'] if service in service_parameter.SERVICE_PARAMETER_SCHEMA \ and section in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] if service_parameter.SERVICE_PARAM_PROTECTED in schema: # atleast one parameter is to be protected if name in schema[service_parameter.SERVICE_PARAM_PROTECTED]: parms[idx]['value'] = service_parameter.SERVICE_VALUE_PROTECTION_MASK return ServiceParameterCollection.convert_with_links( parms, limit, url=resource_url, expand=expand, sort_key=sort_key, sort_dir=sort_dir) def _get_updates(self, patch): """Retrieve the updated attributes from the patch request.""" updates = {} for p in patch: attribute = p['path'] if p['path'][0] != '/' else p['path'][1:] updates[attribute] = p['value'] return updates @wsme_pecan.wsexpose(ServiceParameterCollection, [Query], types.uuid, wtypes.text, wtypes.text, wtypes.text, wtypes.text) def get_all(self, q=None, marker=None, limit=None, sort_key='id', sort_dir='asc'): """Retrieve a list of service parameters.""" if q is None: q = [] sort_key = ['section', 'name'] return self._get_service_parameter_collection(marker, limit, sort_key, sort_dir, q=q) @wsme_pecan.wsexpose(ServiceParameter, types.uuid) def get_one(self, uuid): """Retrieve information about the given parameter.""" rpc_parameter = objects.service_parameter.get_by_uuid( pecan.request.context, uuid) # Before we can return the service parameter, we need # to ensure that it is not a "protected" parameter # which may need to be obfuscated. service = rpc_parameter['service'] section = rpc_parameter['section'] name = rpc_parameter['name'] if service in service_parameter.SERVICE_PARAMETER_SCHEMA \ and section in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] if service_parameter.SERVICE_PARAM_PROTECTED in schema: # parameter is to be protected if name in schema[service_parameter.SERVICE_PARAM_PROTECTED]: rpc_parameter['value'] = service_parameter.SERVICE_VALUE_PROTECTION_MASK return ServiceParameter.convert_with_links(rpc_parameter) @staticmethod def _check_read_only_parameter(svc_param): """Check the read-only attribute of service parameter""" service = svc_param['service'] section = svc_param['section'] name = svc_param['name'] schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] readonly_parameters = schema.get(service_parameter.SERVICE_PARAM_READONLY, []) if name in readonly_parameters: msg = _("The parameter '%s' is readonly." % name) raise wsme.exc.ClientSideError(msg) @staticmethod def _check_parameter_syntax(svc_param): """Check the attributes of service parameter""" service = svc_param['service'] section = svc_param['section'] name = svc_param['name'] value = svc_param['value'] if service == constants.SERVICE_TYPE_PTP: msg = _("%s service is deprecated" % service) raise wsme.exc.ClientSideError(msg) schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] parameters = (schema.get(service_parameter.SERVICE_PARAM_MANDATORY, []) + schema.get(service_parameter.SERVICE_PARAM_OPTIONAL, [])) has_wildcard = (constants.SERVICE_PARAM_NAME_WILDCARD in parameters) if name not in parameters and not has_wildcard: msg = _("The parameter name %s is invalid for " "service %s section %s" % (name, service, section)) raise wsme.exc.ClientSideError(msg) if not value: msg = _("The service parameter value is mandatory") raise wsme.exc.ClientSideError(msg) if len(value) > service_parameter.SERVICE_PARAMETER_MAX_LENGTH: msg = _("The service parameter value is restricted to at most %d " "characters." % service_parameter.SERVICE_PARAMETER_MAX_LENGTH) raise wsme.exc.ClientSideError(msg) validators = schema.get(service_parameter.SERVICE_PARAM_VALIDATOR, {}) validator = validators.get(name) if callable(validator): validator(name, value) @staticmethod def _check_custom_parameter_syntax(svc_param): """Check the attributes of custom service parameter""" service = svc_param['service'] section = svc_param['section'] name = svc_param['name'] value = svc_param['value'] personality = svc_param['personality'] resource = svc_param['resource'] if service == constants.SERVICE_TYPE_PTP: msg = _("%s service is deprecated" % service) raise wsme.exc.ClientSideError(msg) if personality is not None and personality not in constants.PERSONALITIES: msg = _("%s is not a supported personality type" % personality) raise wsme.exc.ClientSideError(msg) if len(resource) > service_parameter.SERVICE_PARAMETER_MAX_LENGTH: msg = _("The custom resource option is restricted to at most %d " "characters." % service_parameter.SERVICE_PARAMETER_MAX_LENGTH) raise wsme.exc.ClientSideError(msg) if service in service_parameter.SERVICE_PARAMETER_SCHEMA \ and section in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] parameters = (schema.get(service_parameter.SERVICE_PARAM_MANDATORY, []) + schema.get(service_parameter.SERVICE_PARAM_OPTIONAL, [])) if name in parameters: msg = _("The parameter name %s is reserved for " "service %s section %s, and cannot be customized" % (name, service, section)) raise wsme.exc.ClientSideError(msg) if value is not None and len(value) > service_parameter.SERVICE_PARAMETER_MAX_LENGTH: msg = _("The service parameter value is restricted to at most %d " "characters." % service_parameter.SERVICE_PARAMETER_MAX_LENGTH) raise wsme.exc.ClientSideError(msg) mapped_resource = service_parameter.map_resource(resource) if mapped_resource is not None: msg = _("The specified resource is reserved for " "service=%s section=%s name=%s and cannot " "be customized." % (mapped_resource.get('service'), mapped_resource.get('section'), mapped_resource.get('name'))) raise wsme.exc.ClientSideError(msg) def post_custom_resource(self, body, personality, resource): """Create new custom Service Parameter.""" if resource is None: raise wsme.exc.ClientSideError(_("Unspecified resource")) service = body.get('service') if not service: raise wsme.exc.ClientSideError("Unspecified service name") section = body.get('section') if not section: raise wsme.exc.ClientSideError(_("Unspecified section name.")) new_records = [] parameters = body.get('parameters') if not parameters: raise wsme.exc.ClientSideError(_("Unspecified parameters.")) if len(parameters) > 1: msg = _("Cannot specify multiple parameters with custom resource.") raise wsme.exc.ClientSideError(msg) for name, value in parameters.items(): new_record = { 'service': service, 'section': section, 'name': name, 'value': value, 'personality': personality, 'resource': resource, } self._check_custom_parameter_syntax(new_record) existing = False try: pecan.request.dbapi.service_parameter_get_one( service, section, name, personality, resource) existing = True except exception.NotFound: pass except exception.MultipleResults: # We'll check/handle this in the "finally" block existing = True finally: if existing: msg = _("Service parameter add failed: " "Parameter already exists: " "service=%s section=%s name=%s " "personality=%s resource=%s" % (service, section, name, personality, resource)) raise wsme.exc.ClientSideError(msg) new_records.append(new_record) svc_params = [] for n in new_records: try: new_parm = pecan.request.dbapi.service_parameter_create(n) except exception.NotFound: msg = _("Service parameter add failed: " "service %s section %s name %s value %s" " personality %s resource %s" % (service, section, n.name, n.value, personality, resource)) raise wsme.exc.ClientSideError(msg) svc_params.append(new_parm) try: pecan.request.rpcapi.update_service_config( pecan.request.context, service, section=section) except rpc_common.RemoteError as e: # rollback create service parameters for p in svc_params: try: pecan.request.dbapi.service_parameter_destroy_uuid(p.uuid) LOG.warn(_("Rollback service parameter create: " "destroy uuid {}".format(p.uuid))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e) return ServiceParameterCollection.convert_with_links( svc_params, limit=None, url=None, expand=False, sort_key='id', sort_dir='asc') @cutils.synchronized(LOCK_NAME) @wsme_pecan.wsexpose(ServiceParameterCollection, body=types.apidict) def post(self, body): """Create new Service Parameter.""" resource = body.get('resource') personality = body.get('personality') if personality is not None or resource is not None: return self.post_custom_resource(body, personality, resource) service = self._get_service(body) section = body.get('section') if not section: raise wsme.exc.ClientSideError(_("Unspecified section name.")) elif section not in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: msg = _("Invalid service section %s." % section) raise wsme.exc.ClientSideError(msg) new_records = [] parameters = body.get('parameters') if not parameters: raise wsme.exc.ClientSideError(_("Unspecified parameters.")) for name, value in parameters.items(): new_record = { 'service': service, 'section': section, 'name': name, 'value': value, } self._check_parameter_syntax(new_record) existing = False try: pecan.request.dbapi.service_parameter_get_one( service, section, name) existing = True except exception.NotFound: pass except exception.MultipleResults: # We'll check/handle this in the "finally" block existing = True finally: if existing: msg = _("Service parameter add failed: " "Parameter already exists: " "service=%s section=%s name=%s" % (service, section, name)) raise wsme.exc.ClientSideError(msg) new_records.append(new_record) svc_params = [] for n in new_records: try: new_parm = pecan.request.dbapi.service_parameter_create(n) except exception.NotFound: msg = _("Service parameter add failed: " "service %s section %s name %s value %s" % (service, section, n.name, n.value)) raise wsme.exc.ClientSideError(msg) svc_params.append(new_parm) try: pecan.request.rpcapi.update_service_config( pecan.request.context, service, section=section) except rpc_common.RemoteError as e: # rollback create service parameters for p in svc_params: try: pecan.request.dbapi.service_parameter_destroy_uuid(p.uuid) LOG.warn(_("Rollback service parameter create: " "destroy uuid {}".format(p.uuid))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e) return ServiceParameterCollection.convert_with_links( svc_params, limit=None, url=None, expand=False, sort_key='id', sort_dir='asc') def patch_custom_resource(self, uuid, patch, personality, resource): """Updates attributes of Service Parameter.""" parameter = objects.service_parameter.get_by_uuid( pecan.request.context, uuid) parameter = parameter.as_dict() old_parameter = copy.deepcopy(parameter) updates = self._get_updates(patch) parameter.update(updates) self._check_custom_parameter_syntax(parameter) updated_parameter = pecan.request.dbapi.service_parameter_update( uuid, updates) try: pecan.request.rpcapi.update_service_config( pecan.request.context, parameter['service'], section=parameter['section']) except rpc_common.RemoteError as e: # rollback service parameter update try: pecan.request.dbapi.service_parameter_update(uuid, old_parameter) LOG.warn(_("Rollback service parameter update: " "uuid={}, old_values={}".format(uuid, old_parameter))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) return ServiceParameter.convert_with_links(updated_parameter) @cutils.synchronized(LOCK_NAME) @wsme.validate(types.uuid, [ServiceParameterPatchType]) @wsme_pecan.wsexpose(ServiceParameter, types.uuid, body=[ServiceParameterPatchType]) def patch(self, uuid, patch): """Updates attributes of Service Parameter.""" parameter = objects.service_parameter.get_by_uuid( pecan.request.context, uuid) if parameter.personality is not None or parameter.resource is not None: return self.patch_custom_resource(uuid, patch, parameter.personality, parameter.resource) parameter = parameter.as_dict() old_parameter = copy.deepcopy(parameter) updates = self._get_updates(patch) parameter.update(updates) self._check_parameter_syntax(parameter) self._check_read_only_parameter(parameter) updated_parameter = pecan.request.dbapi.service_parameter_update( uuid, updates) try: pecan.request.rpcapi.update_service_config( pecan.request.context, parameter['service'], section=parameter['section']) except rpc_common.RemoteError as e: # rollback service parameter update try: pecan.request.dbapi.service_parameter_update(uuid, old_parameter) LOG.warn(_("Rollback service parameter update: " "uuid={}, old_values={}".format(uuid, old_parameter))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) # Before we can return the service parameter, we need # to ensure that this updated parameter is not "protected" # which may need to be obfuscated. service = updated_parameter['service'] section = updated_parameter['section'] name = updated_parameter['name'] if service in service_parameter.SERVICE_PARAMETER_SCHEMA \ and section in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] if service_parameter.SERVICE_PARAM_PROTECTED in schema: # parameter is to be protected if name in schema[service_parameter.SERVICE_PARAM_PROTECTED]: updated_parameter['value'] = service_parameter.SERVICE_VALUE_PROTECTION_MASK return ServiceParameter.convert_with_links(updated_parameter) @cutils.synchronized(LOCK_NAME) @wsme_pecan.wsexpose(None, types.uuid, status_code=204) def delete(self, uuid): """Delete a Service Parameter instance.""" parameter = objects.service_parameter.get_by_uuid(pecan.request.context, uuid) if parameter.section == \ constants.SERVICE_PARAM_SECTION_PLATFORM_MAINTENANCE: msg = _("Platform Maintenance Parameter '%s' is required." % parameter.name) raise wsme.exc.ClientSideError(msg) pecan.request.dbapi.service_parameter_destroy_uuid(uuid) try: pecan.request.rpcapi.update_service_config( pecan.request.context, parameter.service, section=parameter.section) except rpc_common.RemoteError as e: # rollback destroy service parameter try: parameter = parameter.as_dict() pecan.request.dbapi.service_parameter_create(parameter) LOG.warn(_("Rollback service parameter destroy: " "create parameter with values={}".format(parameter))) # rollback parameter has a different uuid except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) @staticmethod def _service_parameter_apply_semantic_check_mtce(): """Semantic checks for the Platform Maintenance Service Type """ hbs_failure_threshold = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_PLATFORM, section=constants.SERVICE_PARAM_SECTION_PLATFORM_MAINTENANCE, name=constants.SERVICE_PARAM_PLAT_MTCE_HBS_FAILURE_THRESHOLD) hbs_degrade_threshold = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_PLATFORM, section=constants.SERVICE_PARAM_SECTION_PLATFORM_MAINTENANCE, name=constants.SERVICE_PARAM_PLAT_MTCE_HBS_DEGRADE_THRESHOLD) if int(hbs_degrade_threshold.value) >= int(hbs_failure_threshold.value): msg = _("Unable to apply service parameters. " "Service parameter '%s' should be greater than '%s' " % ( constants.SERVICE_PARAM_PLAT_MTCE_HBS_FAILURE_THRESHOLD, constants.SERVICE_PARAM_PLAT_MTCE_HBS_DEGRADE_THRESHOLD )) raise wsme.exc.ClientSideError(msg) @staticmethod def _service_parameter_apply_semantic_check_http(): """Semantic checks for the HTTP Service Type """ # check if a patching operation in progress fm = fm_api.FaultAPIs() alarms = fm.get_faults_by_id(fm_constants. FM_ALARM_ID_PATCH_IN_PROGRESS) if alarms is not None: msg = _("Unable to apply %s service parameters. " "A patching operation is in progress." % constants.SERVICE_TYPE_HTTP) raise wsme.exc.ClientSideError(msg) # check if a device image update operation is in progress alarms = fm.get_faults_by_id(fm_constants. FM_ALARM_ID_DEVICE_IMAGE_UPDATE_IN_PROGRESS) if alarms is not None: msg = _("Unable to apply %s service parameters. " "A device image update operation is in progress. " "Please try again later when the operation is complete." % constants.SERVICE_TYPE_HTTP) raise wsme.exc.ClientSideError(msg) # check if all hosts are unlocked/enabled hosts = pecan.request.dbapi.ihost_get_list() for host in hosts: if (host['administrative'] == constants.ADMIN_UNLOCKED and host['operational'] == constants.OPERATIONAL_ENABLED): continue else: # the host name might be None for a newly discovered host if not host['hostname']: host_id = host['uuid'] else: host_id = host['hostname'] raise wsme.exc.ClientSideError( _("Host %s must be unlocked and enabled." % host_id)) @staticmethod def _service_parameter_apply_semantic_check_kubernetes(): """Semantic checks for the Platform Kubernetes Service Type """ try: oidc_issuer_url = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_KUBERNETES, section=constants.SERVICE_PARAM_SECTION_KUBERNETES_APISERVER, name=constants.SERVICE_PARAM_NAME_OIDC_ISSUER_URL) except exception.NotFound: oidc_issuer_url = None try: oidc_client_id = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_KUBERNETES, section=constants.SERVICE_PARAM_SECTION_KUBERNETES_APISERVER, name=constants.SERVICE_PARAM_NAME_OIDC_CLIENT_ID) except exception.NotFound: oidc_client_id = None try: oidc_username_claim = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_KUBERNETES, section=constants.SERVICE_PARAM_SECTION_KUBERNETES_APISERVER, name=constants.SERVICE_PARAM_NAME_OIDC_USERNAME_CLAIM) except exception.NotFound: oidc_username_claim = None try: oidc_groups_claim = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_KUBERNETES, section=constants.SERVICE_PARAM_SECTION_KUBERNETES_APISERVER, name=constants.SERVICE_PARAM_NAME_OIDC_GROUPS_CLAIM) except exception.NotFound: oidc_groups_claim = None if not ((not oidc_issuer_url and not oidc_client_id and not oidc_username_claim and not oidc_groups_claim) or (oidc_issuer_url and oidc_client_id and oidc_username_claim and not oidc_groups_claim) or (oidc_issuer_url and oidc_client_id and oidc_username_claim and oidc_groups_claim)): msg = _("Unable to apply service parameters. Please choose one of " "the valid Kubernetes OIDC parameter setups: (None) or " "(oidc_issuer_url, oidc_client_id, oidc_username_claim) or " "(the previous 3 plus oidc_groups_claim)") raise wsme.exc.ClientSideError(msg) def _service_parameter_apply_semantic_check(self, service): """Semantic checks for the service-parameter-apply command """ # Check if all the mandatory parameters have been configured for section, schema in service_parameter.SERVICE_PARAMETER_SCHEMA[service].items(): mandatory = schema.get(service_parameter.SERVICE_PARAM_MANDATORY, []) for name in mandatory: try: pecan.request.dbapi.service_parameter_get_one( service=service, section=section, name=name) except exception.NotFound: msg = _("Unable to apply service parameters. " "Missing service parameter '%s' for service '%s' " "in section '%s'." % (name, service, section)) raise wsme.exc.ClientSideError(msg) # Apply service specific semantic checks if service == constants.SERVICE_TYPE_PLATFORM: self._service_parameter_apply_semantic_check_mtce() elif service == constants.SERVICE_TYPE_HTTP: self._service_parameter_apply_semantic_check_http() elif service == constants.SERVICE_TYPE_KUBERNETES: self._service_parameter_apply_semantic_check_kubernetes() elif service == constants.SERVICE_TYPE_PTP: msg = _("%s service is deprecated" % service) raise wsme.exc.ClientSideError(msg) def _get_service(self, body): service = body.get('service') or "" if not service: raise wsme.exc.ClientSideError("Unspecified service name") if body['service'] not in service_parameter.SERVICE_PARAMETER_SCHEMA: msg = _("Invalid service name %s." % body['service']) raise wsme.exc.ClientSideError(msg) return service @cutils.synchronized(LOCK_NAME) @wsme_pecan.wsexpose('json', body=six.text_type) def apply(self, body): """ Apply the service parameters.""" service = self._get_service(body) self._service_parameter_apply_semantic_check(service) try: pecan.request.rpcapi.update_service_config( pecan.request.context, service, do_apply=True) except rpc_common.RemoteError as e: raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e)
41.736041
97
0.608429
import copy import pecan from pecan import rest import six import wsme from wsme import types as wtypes import wsmeext.pecan as wsme_pecan from fm_api import constants as fm_constants from fm_api import fm_api from oslo_log import log from oslo_utils import excutils from sysinv._i18n import _ from sysinv.api.controllers.v1 import base from sysinv.api.controllers.v1 import collection from sysinv.api.controllers.v1 import link from sysinv.api.controllers.v1 import types from sysinv.api.controllers.v1 import utils from sysinv.api.controllers.v1.query import Query from sysinv import objects from sysinv.common import constants from sysinv.common import service_parameter from sysinv.common import exception from sysinv.common import utils as cutils from sysinv.openstack.common.rpc import common as rpc_common LOG = log.getLogger(__name__) class ServiceParameterPatchType(types.JsonPatchType): @staticmethod def mandatory_attrs(): return ['/uuid'] class ServiceParameter(base.APIBase): id = int uuid = types.uuid service = wtypes.text section = wtypes.text name = wtypes.text value = wtypes.text personality = wtypes.text resource = wtypes.text links = [link.Link] def __init__(self, **kwargs): self.fields = list(objects.service_parameter.fields.keys()) for k in self.fields: if not hasattr(self, k): continue setattr(self, k, kwargs.get(k, wtypes.Unset)) @classmethod def convert_with_links(cls, rpc_service_parameter, expand=True): parm = ServiceParameter(**rpc_service_parameter.as_dict()) if not expand: parm.unset_fields_except(['uuid', 'service', 'section', 'name', 'value', 'personality', 'resource']) parm.links = [link.Link.make_link('self', pecan.request.host_url, 'parameters', parm.uuid), link.Link.make_link('bookmark', pecan.request.host_url, 'parameters', parm.uuid, bookmark=True) ] return parm class ServiceParameterCollection(collection.Collection): parameters = [ServiceParameter] def __init__(self, **kwargs): self._type = 'parameters' @classmethod def convert_with_links(cls, rpc_service_parameter, limit, url=None, expand=False, **kwargs): collection = ServiceParameterCollection() collection.parameters = [ServiceParameter.convert_with_links(p, expand) for p in rpc_service_parameter] collection.next = collection.get_next(limit, url=url, **kwargs) return collection LOCK_NAME = 'ServiceParameterController' class ServiceParameterController(rest.RestController): _custom_actions = { 'apply': ['POST'], } def __init__(self, parent=None, **kwargs): self._parent = parent def _get_service_parameter_collection(self, marker=None, limit=None, sort_key=None, sort_dir=None, expand=False, resource_url=None, q=None): limit = utils.validate_limit(limit) sort_dir = utils.validate_sort_dir(sort_dir) kwargs = {} if q is not None: for i in q: if i.op == 'eq': kwargs[i.field] = i.value marker_obj = None if marker: marker_obj = objects.service_parameter.get_by_uuid( pecan.request.context, marker) if q is None: parms = pecan.request.dbapi.service_parameter_get_list( limit=limit, marker=marker_obj, sort_key=sort_key, sort_dir=sort_dir) else: kwargs['limit'] = limit kwargs['sort_key'] = sort_key kwargs['sort_dir'] = sort_dir parms = pecan.request.dbapi.service_parameter_get_all(**kwargs) for idx, svc_param in enumerate(parms): service = svc_param['service'] section = svc_param['section'] name = svc_param['name'] if service in service_parameter.SERVICE_PARAMETER_SCHEMA \ and section in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] if service_parameter.SERVICE_PARAM_PROTECTED in schema: if name in schema[service_parameter.SERVICE_PARAM_PROTECTED]: parms[idx]['value'] = service_parameter.SERVICE_VALUE_PROTECTION_MASK return ServiceParameterCollection.convert_with_links( parms, limit, url=resource_url, expand=expand, sort_key=sort_key, sort_dir=sort_dir) def _get_updates(self, patch): updates = {} for p in patch: attribute = p['path'] if p['path'][0] != '/' else p['path'][1:] updates[attribute] = p['value'] return updates @wsme_pecan.wsexpose(ServiceParameterCollection, [Query], types.uuid, wtypes.text, wtypes.text, wtypes.text, wtypes.text) def get_all(self, q=None, marker=None, limit=None, sort_key='id', sort_dir='asc'): if q is None: q = [] sort_key = ['section', 'name'] return self._get_service_parameter_collection(marker, limit, sort_key, sort_dir, q=q) @wsme_pecan.wsexpose(ServiceParameter, types.uuid) def get_one(self, uuid): rpc_parameter = objects.service_parameter.get_by_uuid( pecan.request.context, uuid) service = rpc_parameter['service'] section = rpc_parameter['section'] name = rpc_parameter['name'] if service in service_parameter.SERVICE_PARAMETER_SCHEMA \ and section in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] if service_parameter.SERVICE_PARAM_PROTECTED in schema: if name in schema[service_parameter.SERVICE_PARAM_PROTECTED]: rpc_parameter['value'] = service_parameter.SERVICE_VALUE_PROTECTION_MASK return ServiceParameter.convert_with_links(rpc_parameter) @staticmethod def _check_read_only_parameter(svc_param): service = svc_param['service'] section = svc_param['section'] name = svc_param['name'] schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] readonly_parameters = schema.get(service_parameter.SERVICE_PARAM_READONLY, []) if name in readonly_parameters: msg = _("The parameter '%s' is readonly." % name) raise wsme.exc.ClientSideError(msg) @staticmethod def _check_parameter_syntax(svc_param): service = svc_param['service'] section = svc_param['section'] name = svc_param['name'] value = svc_param['value'] if service == constants.SERVICE_TYPE_PTP: msg = _("%s service is deprecated" % service) raise wsme.exc.ClientSideError(msg) schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] parameters = (schema.get(service_parameter.SERVICE_PARAM_MANDATORY, []) + schema.get(service_parameter.SERVICE_PARAM_OPTIONAL, [])) has_wildcard = (constants.SERVICE_PARAM_NAME_WILDCARD in parameters) if name not in parameters and not has_wildcard: msg = _("The parameter name %s is invalid for " "service %s section %s" % (name, service, section)) raise wsme.exc.ClientSideError(msg) if not value: msg = _("The service parameter value is mandatory") raise wsme.exc.ClientSideError(msg) if len(value) > service_parameter.SERVICE_PARAMETER_MAX_LENGTH: msg = _("The service parameter value is restricted to at most %d " "characters." % service_parameter.SERVICE_PARAMETER_MAX_LENGTH) raise wsme.exc.ClientSideError(msg) validators = schema.get(service_parameter.SERVICE_PARAM_VALIDATOR, {}) validator = validators.get(name) if callable(validator): validator(name, value) @staticmethod def _check_custom_parameter_syntax(svc_param): service = svc_param['service'] section = svc_param['section'] name = svc_param['name'] value = svc_param['value'] personality = svc_param['personality'] resource = svc_param['resource'] if service == constants.SERVICE_TYPE_PTP: msg = _("%s service is deprecated" % service) raise wsme.exc.ClientSideError(msg) if personality is not None and personality not in constants.PERSONALITIES: msg = _("%s is not a supported personality type" % personality) raise wsme.exc.ClientSideError(msg) if len(resource) > service_parameter.SERVICE_PARAMETER_MAX_LENGTH: msg = _("The custom resource option is restricted to at most %d " "characters." % service_parameter.SERVICE_PARAMETER_MAX_LENGTH) raise wsme.exc.ClientSideError(msg) if service in service_parameter.SERVICE_PARAMETER_SCHEMA \ and section in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] parameters = (schema.get(service_parameter.SERVICE_PARAM_MANDATORY, []) + schema.get(service_parameter.SERVICE_PARAM_OPTIONAL, [])) if name in parameters: msg = _("The parameter name %s is reserved for " "service %s section %s, and cannot be customized" % (name, service, section)) raise wsme.exc.ClientSideError(msg) if value is not None and len(value) > service_parameter.SERVICE_PARAMETER_MAX_LENGTH: msg = _("The service parameter value is restricted to at most %d " "characters." % service_parameter.SERVICE_PARAMETER_MAX_LENGTH) raise wsme.exc.ClientSideError(msg) mapped_resource = service_parameter.map_resource(resource) if mapped_resource is not None: msg = _("The specified resource is reserved for " "service=%s section=%s name=%s and cannot " "be customized." % (mapped_resource.get('service'), mapped_resource.get('section'), mapped_resource.get('name'))) raise wsme.exc.ClientSideError(msg) def post_custom_resource(self, body, personality, resource): if resource is None: raise wsme.exc.ClientSideError(_("Unspecified resource")) service = body.get('service') if not service: raise wsme.exc.ClientSideError("Unspecified service name") section = body.get('section') if not section: raise wsme.exc.ClientSideError(_("Unspecified section name.")) new_records = [] parameters = body.get('parameters') if not parameters: raise wsme.exc.ClientSideError(_("Unspecified parameters.")) if len(parameters) > 1: msg = _("Cannot specify multiple parameters with custom resource.") raise wsme.exc.ClientSideError(msg) for name, value in parameters.items(): new_record = { 'service': service, 'section': section, 'name': name, 'value': value, 'personality': personality, 'resource': resource, } self._check_custom_parameter_syntax(new_record) existing = False try: pecan.request.dbapi.service_parameter_get_one( service, section, name, personality, resource) existing = True except exception.NotFound: pass except exception.MultipleResults: existing = True finally: if existing: msg = _("Service parameter add failed: " "Parameter already exists: " "service=%s section=%s name=%s " "personality=%s resource=%s" % (service, section, name, personality, resource)) raise wsme.exc.ClientSideError(msg) new_records.append(new_record) svc_params = [] for n in new_records: try: new_parm = pecan.request.dbapi.service_parameter_create(n) except exception.NotFound: msg = _("Service parameter add failed: " "service %s section %s name %s value %s" " personality %s resource %s" % (service, section, n.name, n.value, personality, resource)) raise wsme.exc.ClientSideError(msg) svc_params.append(new_parm) try: pecan.request.rpcapi.update_service_config( pecan.request.context, service, section=section) except rpc_common.RemoteError as e: # rollback create service parameters for p in svc_params: try: pecan.request.dbapi.service_parameter_destroy_uuid(p.uuid) LOG.warn(_("Rollback service parameter create: " "destroy uuid {}".format(p.uuid))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e) return ServiceParameterCollection.convert_with_links( svc_params, limit=None, url=None, expand=False, sort_key='id', sort_dir='asc') @cutils.synchronized(LOCK_NAME) @wsme_pecan.wsexpose(ServiceParameterCollection, body=types.apidict) def post(self, body): resource = body.get('resource') personality = body.get('personality') if personality is not None or resource is not None: return self.post_custom_resource(body, personality, resource) service = self._get_service(body) section = body.get('section') if not section: raise wsme.exc.ClientSideError(_("Unspecified section name.")) elif section not in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: msg = _("Invalid service section %s." % section) raise wsme.exc.ClientSideError(msg) new_records = [] parameters = body.get('parameters') if not parameters: raise wsme.exc.ClientSideError(_("Unspecified parameters.")) for name, value in parameters.items(): new_record = { 'service': service, 'section': section, 'name': name, 'value': value, } self._check_parameter_syntax(new_record) existing = False try: pecan.request.dbapi.service_parameter_get_one( service, section, name) existing = True except exception.NotFound: pass except exception.MultipleResults: # We'll check/handle this in the "finally" block existing = True finally: if existing: msg = _("Service parameter add failed: " "Parameter already exists: " "service=%s section=%s name=%s" % (service, section, name)) raise wsme.exc.ClientSideError(msg) new_records.append(new_record) svc_params = [] for n in new_records: try: new_parm = pecan.request.dbapi.service_parameter_create(n) except exception.NotFound: msg = _("Service parameter add failed: " "service %s section %s name %s value %s" % (service, section, n.name, n.value)) raise wsme.exc.ClientSideError(msg) svc_params.append(new_parm) try: pecan.request.rpcapi.update_service_config( pecan.request.context, service, section=section) except rpc_common.RemoteError as e: for p in svc_params: try: pecan.request.dbapi.service_parameter_destroy_uuid(p.uuid) LOG.warn(_("Rollback service parameter create: " "destroy uuid {}".format(p.uuid))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e) return ServiceParameterCollection.convert_with_links( svc_params, limit=None, url=None, expand=False, sort_key='id', sort_dir='asc') def patch_custom_resource(self, uuid, patch, personality, resource): parameter = objects.service_parameter.get_by_uuid( pecan.request.context, uuid) parameter = parameter.as_dict() old_parameter = copy.deepcopy(parameter) updates = self._get_updates(patch) parameter.update(updates) self._check_custom_parameter_syntax(parameter) updated_parameter = pecan.request.dbapi.service_parameter_update( uuid, updates) try: pecan.request.rpcapi.update_service_config( pecan.request.context, parameter['service'], section=parameter['section']) except rpc_common.RemoteError as e: try: pecan.request.dbapi.service_parameter_update(uuid, old_parameter) LOG.warn(_("Rollback service parameter update: " "uuid={}, old_values={}".format(uuid, old_parameter))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) return ServiceParameter.convert_with_links(updated_parameter) @cutils.synchronized(LOCK_NAME) @wsme.validate(types.uuid, [ServiceParameterPatchType]) @wsme_pecan.wsexpose(ServiceParameter, types.uuid, body=[ServiceParameterPatchType]) def patch(self, uuid, patch): parameter = objects.service_parameter.get_by_uuid( pecan.request.context, uuid) if parameter.personality is not None or parameter.resource is not None: return self.patch_custom_resource(uuid, patch, parameter.personality, parameter.resource) parameter = parameter.as_dict() old_parameter = copy.deepcopy(parameter) updates = self._get_updates(patch) parameter.update(updates) self._check_parameter_syntax(parameter) self._check_read_only_parameter(parameter) updated_parameter = pecan.request.dbapi.service_parameter_update( uuid, updates) try: pecan.request.rpcapi.update_service_config( pecan.request.context, parameter['service'], section=parameter['section']) except rpc_common.RemoteError as e: try: pecan.request.dbapi.service_parameter_update(uuid, old_parameter) LOG.warn(_("Rollback service parameter update: " "uuid={}, old_values={}".format(uuid, old_parameter))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) service = updated_parameter['service'] section = updated_parameter['section'] name = updated_parameter['name'] if service in service_parameter.SERVICE_PARAMETER_SCHEMA \ and section in service_parameter.SERVICE_PARAMETER_SCHEMA[service]: schema = service_parameter.SERVICE_PARAMETER_SCHEMA[service][section] if service_parameter.SERVICE_PARAM_PROTECTED in schema: if name in schema[service_parameter.SERVICE_PARAM_PROTECTED]: updated_parameter['value'] = service_parameter.SERVICE_VALUE_PROTECTION_MASK return ServiceParameter.convert_with_links(updated_parameter) @cutils.synchronized(LOCK_NAME) @wsme_pecan.wsexpose(None, types.uuid, status_code=204) def delete(self, uuid): parameter = objects.service_parameter.get_by_uuid(pecan.request.context, uuid) if parameter.section == \ constants.SERVICE_PARAM_SECTION_PLATFORM_MAINTENANCE: msg = _("Platform Maintenance Parameter '%s' is required." % parameter.name) raise wsme.exc.ClientSideError(msg) pecan.request.dbapi.service_parameter_destroy_uuid(uuid) try: pecan.request.rpcapi.update_service_config( pecan.request.context, parameter.service, section=parameter.section) except rpc_common.RemoteError as e: try: parameter = parameter.as_dict() pecan.request.dbapi.service_parameter_create(parameter) LOG.warn(_("Rollback service parameter destroy: " "create parameter with values={}".format(parameter))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) @staticmethod def _service_parameter_apply_semantic_check_mtce(): hbs_failure_threshold = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_PLATFORM, section=constants.SERVICE_PARAM_SECTION_PLATFORM_MAINTENANCE, name=constants.SERVICE_PARAM_PLAT_MTCE_HBS_FAILURE_THRESHOLD) hbs_degrade_threshold = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_PLATFORM, section=constants.SERVICE_PARAM_SECTION_PLATFORM_MAINTENANCE, name=constants.SERVICE_PARAM_PLAT_MTCE_HBS_DEGRADE_THRESHOLD) if int(hbs_degrade_threshold.value) >= int(hbs_failure_threshold.value): msg = _("Unable to apply service parameters. " "Service parameter '%s' should be greater than '%s' " % ( constants.SERVICE_PARAM_PLAT_MTCE_HBS_FAILURE_THRESHOLD, constants.SERVICE_PARAM_PLAT_MTCE_HBS_DEGRADE_THRESHOLD )) raise wsme.exc.ClientSideError(msg) @staticmethod def _service_parameter_apply_semantic_check_http(): fm = fm_api.FaultAPIs() alarms = fm.get_faults_by_id(fm_constants. FM_ALARM_ID_PATCH_IN_PROGRESS) if alarms is not None: msg = _("Unable to apply %s service parameters. " "A patching operation is in progress." % constants.SERVICE_TYPE_HTTP) raise wsme.exc.ClientSideError(msg) alarms = fm.get_faults_by_id(fm_constants. FM_ALARM_ID_DEVICE_IMAGE_UPDATE_IN_PROGRESS) if alarms is not None: msg = _("Unable to apply %s service parameters. " "A device image update operation is in progress. " "Please try again later when the operation is complete." % constants.SERVICE_TYPE_HTTP) raise wsme.exc.ClientSideError(msg) hosts = pecan.request.dbapi.ihost_get_list() for host in hosts: if (host['administrative'] == constants.ADMIN_UNLOCKED and host['operational'] == constants.OPERATIONAL_ENABLED): continue else: if not host['hostname']: host_id = host['uuid'] else: host_id = host['hostname'] raise wsme.exc.ClientSideError( _("Host %s must be unlocked and enabled." % host_id)) @staticmethod def _service_parameter_apply_semantic_check_kubernetes(): try: oidc_issuer_url = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_KUBERNETES, section=constants.SERVICE_PARAM_SECTION_KUBERNETES_APISERVER, name=constants.SERVICE_PARAM_NAME_OIDC_ISSUER_URL) except exception.NotFound: oidc_issuer_url = None try: oidc_client_id = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_KUBERNETES, section=constants.SERVICE_PARAM_SECTION_KUBERNETES_APISERVER, name=constants.SERVICE_PARAM_NAME_OIDC_CLIENT_ID) except exception.NotFound: oidc_client_id = None try: oidc_username_claim = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_KUBERNETES, section=constants.SERVICE_PARAM_SECTION_KUBERNETES_APISERVER, name=constants.SERVICE_PARAM_NAME_OIDC_USERNAME_CLAIM) except exception.NotFound: oidc_username_claim = None try: oidc_groups_claim = pecan.request.dbapi.service_parameter_get_one( service=constants.SERVICE_TYPE_KUBERNETES, section=constants.SERVICE_PARAM_SECTION_KUBERNETES_APISERVER, name=constants.SERVICE_PARAM_NAME_OIDC_GROUPS_CLAIM) except exception.NotFound: oidc_groups_claim = None if not ((not oidc_issuer_url and not oidc_client_id and not oidc_username_claim and not oidc_groups_claim) or (oidc_issuer_url and oidc_client_id and oidc_username_claim and not oidc_groups_claim) or (oidc_issuer_url and oidc_client_id and oidc_username_claim and oidc_groups_claim)): msg = _("Unable to apply service parameters. Please choose one of " "the valid Kubernetes OIDC parameter setups: (None) or " "(oidc_issuer_url, oidc_client_id, oidc_username_claim) or " "(the previous 3 plus oidc_groups_claim)") raise wsme.exc.ClientSideError(msg) def _service_parameter_apply_semantic_check(self, service): for section, schema in service_parameter.SERVICE_PARAMETER_SCHEMA[service].items(): mandatory = schema.get(service_parameter.SERVICE_PARAM_MANDATORY, []) for name in mandatory: try: pecan.request.dbapi.service_parameter_get_one( service=service, section=section, name=name) except exception.NotFound: msg = _("Unable to apply service parameters. " "Missing service parameter '%s' for service '%s' " "in section '%s'." % (name, service, section)) raise wsme.exc.ClientSideError(msg) if service == constants.SERVICE_TYPE_PLATFORM: self._service_parameter_apply_semantic_check_mtce() elif service == constants.SERVICE_TYPE_HTTP: self._service_parameter_apply_semantic_check_http() elif service == constants.SERVICE_TYPE_KUBERNETES: self._service_parameter_apply_semantic_check_kubernetes() elif service == constants.SERVICE_TYPE_PTP: msg = _("%s service is deprecated" % service) raise wsme.exc.ClientSideError(msg) def _get_service(self, body): service = body.get('service') or "" if not service: raise wsme.exc.ClientSideError("Unspecified service name") if body['service'] not in service_parameter.SERVICE_PARAMETER_SCHEMA: msg = _("Invalid service name %s." % body['service']) raise wsme.exc.ClientSideError(msg) return service @cutils.synchronized(LOCK_NAME) @wsme_pecan.wsexpose('json', body=six.text_type) def apply(self, body): service = self._get_service(body) self._service_parameter_apply_semantic_check(service) try: pecan.request.rpcapi.update_service_config( pecan.request.context, service, do_apply=True) except rpc_common.RemoteError as e: raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e)
true
true
f72d454abe47a21d4da45346d8bde4ef78bc13d9
5,237
py
Python
src/Python/sirf/contrib/kcl/Prior.py
SyneRBI/SIRF-Contribs
130223d9bc11991eadcd11f9b715aea34c4842fd
[ "Apache-2.0" ]
1
2019-04-18T08:54:12.000Z
2019-04-18T08:54:12.000Z
src/Python/sirf/contrib/kcl/Prior.py
CCPPETMR/SIRF-Contribs
3298c1519b3c7d7f0794306061c08dccf339199b
[ "Apache-2.0" ]
5
2018-12-18T10:13:02.000Z
2018-12-19T16:49:07.000Z
src/Python/sirf/contrib/kcl/Prior.py
SyneRBI/SIRF-Contribs
130223d9bc11991eadcd11f9b715aea34c4842fd
[ "Apache-2.0" ]
1
2019-09-26T11:48:39.000Z
2019-09-26T11:48:39.000Z
import numpy as np class Prior(object): def __init__(self,imageSize, sWindowSize=3, imageCropFactor=[0]): self.imageSize = imageSize if len(imageSize)==3 else imageSize.append(1) self.imageCropFactor = imageCropFactor if np.mod(sWindowSize,2): self.sWindowSize = sWindowSize else: raise ValueError("search window size must be odd") self.is3D = 1 if imageSize[2]>1 else 0 self.nS = sWindowSize**3 if self.is3D else sWindowSize**2 _,self.imageSizeCrop= self.imCrop() self.SearchWindow, self.Wd = self.__neighborhood(self.sWindowSize) def __neighborhood(self,w): n = self.imageSizeCrop[0] m = self.imageSizeCrop[1] h = self.imageSizeCrop[2] wlen = 2*np.floor(w/2) widx = xidx = yidx = np.arange(-wlen/2,wlen/2+1) if h==1: zidx = [0] nN = w*w else: zidx = widx nN = w*w*w Y,X,Z = np.meshgrid(np.arange(0,m), np.arange(0,n), np.arange(0,h)) N = np.zeros([n*m*h, nN],dtype='int32') D = np.zeros([n*m*h, nN],dtype='float') l = 0 for x in xidx: Xnew = self.__setBoundary(X + x, n) for y in yidx: Ynew = self.__setBoundary(Y + y, m) for z in zidx: Znew = self.__setBoundary(Z + z, h) N[:,l] = (Xnew + (Ynew)*n + (Znew)*n*m).reshape(-1,1).flatten('F') D[:,l] = np.sqrt(x**2+y**2+z**2) l += 1 D = 1/D D[np.isinf(D)]= 0 D = D/np.sum(D,axis=1).reshape(-1,1) return N, D def __setBoundary(self,X,n): idx = X<0 X[idx] = X[idx]+n idx = X>n-1 X[idx] = X[idx]-n return X.flatten('F') def imCrop(self,img=None): if np.any(self.imageCropFactor): if len(self.imageCropFactor)==1: self.imageCropFactor = self.imageCropFactor*3 I = 0 if self.imageCropFactor[0]: self.imageCropFactor[0] = np.max([2.5, self.imageCropFactor[0]]) I = np.floor(self.imageSize[0]/self.imageCropFactor[0]).astype('int') J = 0 if self.imageCropFactor[1]: self.imageCropFactor[1] = np.max([2.5, self.imageCropFactor[1]]) J = np.floor(self.imageSize[1]/self.imageCropFactor[1]).astype('int') K = 0 if self.imageCropFactor[2] and self.is3D: self.imageCropFactor[2] = np.max([2.5, self.imageCropFactor[2]]) K = np.floor(self.imageSize[2]/self.imageCropFactor[2]).astype('int') imageSizeCrop = [np.arange(I,self.imageSize[0]-I).shape[0], np.arange(J,self.imageSize[1]-J).shape[0], np.arange(K,self.imageSize[2]-K).shape[0]] if img is not None: if self.is3D: img = img[I:self.imageSize[0]-I, J:self.imageSize[1]-J, K:self.imageSize[2]-K] else: img = img[I:self.imageSize[0]-I, J:self.imageSize[1]-J] else: imageSizeCrop = self.imageSize return img,imageSizeCrop def imCropUndo(self,img): if np.any(self.imageCropFactor): tmp = img img = np.zeros(self.imageSize,tmp.dtype) I = (self.imageSize[0] - self.imageSizeCrop[0])//2 J = (self.imageSize[1] - self.imageSizeCrop[1])//2 K = (self.imageSize[2] - self.imageSizeCrop[2])//2 if self.is3D: img[I:self.imageSize[0]-I, J:self.imageSize[1]-J, K:self.imageSize[2]-K] = tmp else: img[I:self.imageSize[0]-I, J:self.imageSize[1]-J] = tmp return img def Grad(self,img): img,_ = self.imCrop(img) img = img.flatten('F') imgGrad = img[self.SearchWindow] - img.reshape(-1,1) imgGrad[np.isnan(imgGrad)] = 0 return imgGrad def GradT(self,imgGrad): dP = -2*np.sum(self.Wd*imgGrad,axis=1) dP = dP.reshape(self.imageSizeCrop,order='F') dP = self.imCropUndo(dP) dP[np.isnan(dP)] = 0 return dP def Div(self,img): img,_ = self.imCrop(img) img = img.flatten('F') imgDiv = img[self.SearchWindow] + img.reshape(-1,1) imgDiv[np.isnan(imgDiv)] = 0 return imgDiv def gaussianWeights(self,img,sigma): return 1/np.sqrt(2*np.pi*sigma**2)*np.exp(-0.5*self.Grad(img)**2/sigma**2) def BowshserWeights(self,img,b): if b>self.nS: raise ValueError("Number of most similar voxels must be smaller than number of voxels per neighbourhood") imgGradAbs = np.abs(self.Grad(img)) Wb = 0*imgGradAbs for i in range(imgGradAbs.shape[0]): idx = np.argsort(imgGradAbs[i,:]) Wb[i,idx[0:b]]=1 return Wb
37.141844
118
0.504105
import numpy as np class Prior(object): def __init__(self,imageSize, sWindowSize=3, imageCropFactor=[0]): self.imageSize = imageSize if len(imageSize)==3 else imageSize.append(1) self.imageCropFactor = imageCropFactor if np.mod(sWindowSize,2): self.sWindowSize = sWindowSize else: raise ValueError("search window size must be odd") self.is3D = 1 if imageSize[2]>1 else 0 self.nS = sWindowSize**3 if self.is3D else sWindowSize**2 _,self.imageSizeCrop= self.imCrop() self.SearchWindow, self.Wd = self.__neighborhood(self.sWindowSize) def __neighborhood(self,w): n = self.imageSizeCrop[0] m = self.imageSizeCrop[1] h = self.imageSizeCrop[2] wlen = 2*np.floor(w/2) widx = xidx = yidx = np.arange(-wlen/2,wlen/2+1) if h==1: zidx = [0] nN = w*w else: zidx = widx nN = w*w*w Y,X,Z = np.meshgrid(np.arange(0,m), np.arange(0,n), np.arange(0,h)) N = np.zeros([n*m*h, nN],dtype='int32') D = np.zeros([n*m*h, nN],dtype='float') l = 0 for x in xidx: Xnew = self.__setBoundary(X + x, n) for y in yidx: Ynew = self.__setBoundary(Y + y, m) for z in zidx: Znew = self.__setBoundary(Z + z, h) N[:,l] = (Xnew + (Ynew)*n + (Znew)*n*m).reshape(-1,1).flatten('F') D[:,l] = np.sqrt(x**2+y**2+z**2) l += 1 D = 1/D D[np.isinf(D)]= 0 D = D/np.sum(D,axis=1).reshape(-1,1) return N, D def __setBoundary(self,X,n): idx = X<0 X[idx] = X[idx]+n idx = X>n-1 X[idx] = X[idx]-n return X.flatten('F') def imCrop(self,img=None): if np.any(self.imageCropFactor): if len(self.imageCropFactor)==1: self.imageCropFactor = self.imageCropFactor*3 I = 0 if self.imageCropFactor[0]: self.imageCropFactor[0] = np.max([2.5, self.imageCropFactor[0]]) I = np.floor(self.imageSize[0]/self.imageCropFactor[0]).astype('int') J = 0 if self.imageCropFactor[1]: self.imageCropFactor[1] = np.max([2.5, self.imageCropFactor[1]]) J = np.floor(self.imageSize[1]/self.imageCropFactor[1]).astype('int') K = 0 if self.imageCropFactor[2] and self.is3D: self.imageCropFactor[2] = np.max([2.5, self.imageCropFactor[2]]) K = np.floor(self.imageSize[2]/self.imageCropFactor[2]).astype('int') imageSizeCrop = [np.arange(I,self.imageSize[0]-I).shape[0], np.arange(J,self.imageSize[1]-J).shape[0], np.arange(K,self.imageSize[2]-K).shape[0]] if img is not None: if self.is3D: img = img[I:self.imageSize[0]-I, J:self.imageSize[1]-J, K:self.imageSize[2]-K] else: img = img[I:self.imageSize[0]-I, J:self.imageSize[1]-J] else: imageSizeCrop = self.imageSize return img,imageSizeCrop def imCropUndo(self,img): if np.any(self.imageCropFactor): tmp = img img = np.zeros(self.imageSize,tmp.dtype) I = (self.imageSize[0] - self.imageSizeCrop[0])//2 J = (self.imageSize[1] - self.imageSizeCrop[1])//2 K = (self.imageSize[2] - self.imageSizeCrop[2])//2 if self.is3D: img[I:self.imageSize[0]-I, J:self.imageSize[1]-J, K:self.imageSize[2]-K] = tmp else: img[I:self.imageSize[0]-I, J:self.imageSize[1]-J] = tmp return img def Grad(self,img): img,_ = self.imCrop(img) img = img.flatten('F') imgGrad = img[self.SearchWindow] - img.reshape(-1,1) imgGrad[np.isnan(imgGrad)] = 0 return imgGrad def GradT(self,imgGrad): dP = -2*np.sum(self.Wd*imgGrad,axis=1) dP = dP.reshape(self.imageSizeCrop,order='F') dP = self.imCropUndo(dP) dP[np.isnan(dP)] = 0 return dP def Div(self,img): img,_ = self.imCrop(img) img = img.flatten('F') imgDiv = img[self.SearchWindow] + img.reshape(-1,1) imgDiv[np.isnan(imgDiv)] = 0 return imgDiv def gaussianWeights(self,img,sigma): return 1/np.sqrt(2*np.pi*sigma**2)*np.exp(-0.5*self.Grad(img)**2/sigma**2) def BowshserWeights(self,img,b): if b>self.nS: raise ValueError("Number of most similar voxels must be smaller than number of voxels per neighbourhood") imgGradAbs = np.abs(self.Grad(img)) Wb = 0*imgGradAbs for i in range(imgGradAbs.shape[0]): idx = np.argsort(imgGradAbs[i,:]) Wb[i,idx[0:b]]=1 return Wb
true
true
f72d459899b797331f8484c4f146860d8d0ebd33
108
py
Python
server/__init__.py
enotnadoske/JointPython
e335fbf8eba41cf3a29601d0578ff37964b3b8d4
[ "Apache-2.0" ]
null
null
null
server/__init__.py
enotnadoske/JointPython
e335fbf8eba41cf3a29601d0578ff37964b3b8d4
[ "Apache-2.0" ]
27
2020-04-07T22:59:39.000Z
2022-02-23T09:03:13.000Z
server/__init__.py
enotnadoske/JointPython
e335fbf8eba41cf3a29601d0578ff37964b3b8d4
[ "Apache-2.0" ]
4
2020-03-17T10:53:07.000Z
2020-04-26T11:29:50.000Z
"""A package for http server""" # pylint: skip-file __all__ = [ 'demo_server', 'http_server', ]
15.428571
31
0.592593
__all__ = [ 'demo_server', 'http_server', ]
true
true
f72d467797d7f4e6a5ea93e34366cacd30a1c9eb
702
py
Python
var/spack/repos/builtin/packages/glproto/package.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2,360
2017-11-06T08:47:01.000Z
2022-03-31T14:45:33.000Z
var/spack/repos/builtin/packages/glproto/package.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
13,838
2017-11-04T07:49:45.000Z
2022-03-31T23:38:39.000Z
var/spack/repos/builtin/packages/glproto/package.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1,793
2017-11-04T07:45:50.000Z
2022-03-30T14:31:53.000Z
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Glproto(AutotoolsPackage, XorgPackage): """OpenGL Extension to the X Window System. This extension defines a protocol for the client to send 3D rendering commands to the X server.""" homepage = "https://www.x.org/wiki/" xorg_mirror_path = "proto/glproto-1.4.17.tar.gz" version('1.4.17', sha256='9d8130fec2b98bd032db7730fa092dd9dec39f3de34f4bb03ceb43b9903dbc96') depends_on('pkgconfig', type='build') depends_on('util-macros', type='build')
31.909091
96
0.737892
from spack import * class Glproto(AutotoolsPackage, XorgPackage): homepage = "https://www.x.org/wiki/" xorg_mirror_path = "proto/glproto-1.4.17.tar.gz" version('1.4.17', sha256='9d8130fec2b98bd032db7730fa092dd9dec39f3de34f4bb03ceb43b9903dbc96') depends_on('pkgconfig', type='build') depends_on('util-macros', type='build')
true
true
f72d47de2913cc5694788e68cb664a1c6f4860a0
4,356
py
Python
codestosort/NaturalLanguage/module/bestmodel.py
jimmy-academia/Deeper-Learnings
ac363efe5450dd2751c0c1bea0ee7af457f7ac24
[ "MIT" ]
2
2019-09-30T04:57:11.000Z
2020-04-06T04:27:46.000Z
codestosort/NaturalLanguage/module/bestmodel.py
jimmy-academia/Deeper-Learnings
ac363efe5450dd2751c0c1bea0ee7af457f7ac24
[ "MIT" ]
null
null
null
codestosort/NaturalLanguage/module/bestmodel.py
jimmy-academia/Deeper-Learnings
ac363efe5450dd2751c0c1bea0ee7af457f7ac24
[ "MIT" ]
null
null
null
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class BestNet(torch.nn.Module): def __init__(self, embedding_dim): super(BestNet, self).__init__() self.embedding_dim = embedding_dim self.hidden_dim = 256 self.embedding_dropout=0.6 self.desc_rnn_size = 100 self.rnn = nn.GRU( input_size=self.embedding_dim, hidden_size=self.hidden_dim, num_layers=1, batch_first=True, bidirectional=True ) self.rnn_desc = nn.GRU( input_size=self.embedding_dim, hidden_size=self.desc_rnn_size, num_layers=1, batch_first=True, bidirectional=True ) self.emb_drop = nn.Dropout(self.embedding_dropout) self.M = nn.Parameter(torch.FloatTensor(2*self.hidden_dim, 2*self.hidden_dim)) self.b = nn.Parameter(torch.FloatTensor([0])) self.Wc = nn.Parameter(torch.FloatTensor(2*self.hidden_dim, self.embedding_dim)) self.We = nn.Parameter(torch.FloatTensor(self.embedding_dim, self.embedding_dim)) self.attn = nn.Linear(2*self.hidden_dim, 2*self.hidden_dim) self.init_params_() self.tech_w = 0.0 def init_params_(self): #Initializing parameters nn.init.xavier_normal_(self.M) # Set forget gate bias to 2 size = self.rnn.bias_hh_l0.size(0) self.rnn.bias_hh_l0.data[size//4:size//2] = 2 size = self.rnn.bias_ih_l0.size(0) self.rnn.bias_ih_l0.data[size//4:size//2] = 2 size = self.rnn_desc.bias_hh_l0.size(0) self.rnn_desc.bias_hh_l0.data[size//4:size//2] = 2 size = self.rnn_desc.bias_ih_l0.size(0) self.rnn_desc.bias_ih_l0.data[size//4:size//2] = 2 # def forward(self, context, options): # logits = [] # for i, option in enumerate(options.transpose(1, 0)): # gits = [] # for context in context.transpose(1,0): # git = self.forward_one_option(context, option) # gits.append(logit) # logit = torch.stack(gits).mean(0) # logits = torch.stack(logits, 1) # return logits.squeeze() # def forward(self, context, options): # logits = [] # for i, option in enumerate(options.transpose(1, 0)): # logit = self.forward_one_option(context, option) # logits.append(logit) # logits = torch.stack(logits, 1) # return logits.squeeze() def forward(self, context, options): logits = [] for i, option in enumerate(options.transpose(1, 0)): logit_ = [] for utter in context.transpose(1,0): logit = self.forward_one_option(utter, option) # 10,1,1 logit_.append(logit) logits.append(torch.stack(logit_,1).mean(1)) logits = torch.stack(logits, 1) return logits.squeeze() def forward_one_option(self, context, option): context, c_h, option, o_h = self.forward_crosspath(context, option) context_attn = self.forward_attn(context, o_h) option_attn = self.forward_attn(option, c_h) final = self.forward_fc(context_attn, option_attn) return final def forward_crosspath(self, context, option): context, c_h = self.rnn(self.emb_drop(context)) c_h = torch.cat([i for i in c_h], dim=-1) option, o_h = self.rnn(self.emb_drop(option)) o_h = torch.cat([i for i in o_h], dim=-1) return context, c_h.squeeze(), option, o_h.squeeze() def forward_attn(self, output, hidden): max_len = output.size(1) b_size = output.size(0) hidden = hidden.squeeze(0).unsqueeze(2) attn = self.attn(output.contiguous().view(b_size*max_len, -1)) attn = attn.view(b_size, max_len, -1) attn_energies = (attn.bmm(hidden).transpose(1,2)) alpha = F.softmax(attn_energies.squeeze(1), dim=-1) alpha = alpha.unsqueeze(1) weighted_attn = alpha.bmm(output) return weighted_attn.squeeze() def forward_fc(self, context, option): out = torch.mm(context, self.M).unsqueeze(1) out = torch.bmm(out, option.unsqueeze(2)) out = out + self.b return out def save(self, filepath): torch.save(self.state_dict(), filepath)
36.3
89
0.61685
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class BestNet(torch.nn.Module): def __init__(self, embedding_dim): super(BestNet, self).__init__() self.embedding_dim = embedding_dim self.hidden_dim = 256 self.embedding_dropout=0.6 self.desc_rnn_size = 100 self.rnn = nn.GRU( input_size=self.embedding_dim, hidden_size=self.hidden_dim, num_layers=1, batch_first=True, bidirectional=True ) self.rnn_desc = nn.GRU( input_size=self.embedding_dim, hidden_size=self.desc_rnn_size, num_layers=1, batch_first=True, bidirectional=True ) self.emb_drop = nn.Dropout(self.embedding_dropout) self.M = nn.Parameter(torch.FloatTensor(2*self.hidden_dim, 2*self.hidden_dim)) self.b = nn.Parameter(torch.FloatTensor([0])) self.Wc = nn.Parameter(torch.FloatTensor(2*self.hidden_dim, self.embedding_dim)) self.We = nn.Parameter(torch.FloatTensor(self.embedding_dim, self.embedding_dim)) self.attn = nn.Linear(2*self.hidden_dim, 2*self.hidden_dim) self.init_params_() self.tech_w = 0.0 def init_params_(self): nn.init.xavier_normal_(self.M) size = self.rnn.bias_hh_l0.size(0) self.rnn.bias_hh_l0.data[size//4:size//2] = 2 size = self.rnn.bias_ih_l0.size(0) self.rnn.bias_ih_l0.data[size//4:size//2] = 2 size = self.rnn_desc.bias_hh_l0.size(0) self.rnn_desc.bias_hh_l0.data[size//4:size//2] = 2 size = self.rnn_desc.bias_ih_l0.size(0) self.rnn_desc.bias_ih_l0.data[size//4:size//2] = 2 def forward(self, context, options): logits = [] for i, option in enumerate(options.transpose(1, 0)): logit_ = [] for utter in context.transpose(1,0): logit = self.forward_one_option(utter, option) logit_.append(logit) logits.append(torch.stack(logit_,1).mean(1)) logits = torch.stack(logits, 1) return logits.squeeze() def forward_one_option(self, context, option): context, c_h, option, o_h = self.forward_crosspath(context, option) context_attn = self.forward_attn(context, o_h) option_attn = self.forward_attn(option, c_h) final = self.forward_fc(context_attn, option_attn) return final def forward_crosspath(self, context, option): context, c_h = self.rnn(self.emb_drop(context)) c_h = torch.cat([i for i in c_h], dim=-1) option, o_h = self.rnn(self.emb_drop(option)) o_h = torch.cat([i for i in o_h], dim=-1) return context, c_h.squeeze(), option, o_h.squeeze() def forward_attn(self, output, hidden): max_len = output.size(1) b_size = output.size(0) hidden = hidden.squeeze(0).unsqueeze(2) attn = self.attn(output.contiguous().view(b_size*max_len, -1)) attn = attn.view(b_size, max_len, -1) attn_energies = (attn.bmm(hidden).transpose(1,2)) alpha = F.softmax(attn_energies.squeeze(1), dim=-1) alpha = alpha.unsqueeze(1) weighted_attn = alpha.bmm(output) return weighted_attn.squeeze() def forward_fc(self, context, option): out = torch.mm(context, self.M).unsqueeze(1) out = torch.bmm(out, option.unsqueeze(2)) out = out + self.b return out def save(self, filepath): torch.save(self.state_dict(), filepath)
true
true
f72d4958dd28a6e9ba69d6907852444ec2ed532f
6,624
py
Python
indico/modules/events/papers/models/call_for_papers.py
tobiashuste/indico
c1e6ec0c8c84745988e38c9b1768142a6feb9e0e
[ "MIT" ]
null
null
null
indico/modules/events/papers/models/call_for_papers.py
tobiashuste/indico
c1e6ec0c8c84745988e38c9b1768142a6feb9e0e
[ "MIT" ]
null
null
null
indico/modules/events/papers/models/call_for_papers.py
tobiashuste/indico
c1e6ec0c8c84745988e38c9b1768142a6feb9e0e
[ "MIT" ]
null
null
null
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from indico.modules.events.papers.models.competences import PaperCompetence from indico.modules.events.papers.models.reviews import PaperReviewType from indico.modules.events.papers.settings import PaperReviewingRole, paper_reviewing_settings from indico.modules.events.settings import EventSettingProperty from indico.util.caching import memoize_request from indico.util.date_time import now_utc from indico.util.string import MarkdownText, return_ascii class CallForPapers(object): """Proxy class to facilitate access to the call for papers settings""" def __init__(self, event): self.event = event @return_ascii def __repr__(self): return '<CallForPapers({}, start_dt={}, end_dt={})>'.format(self.event.id, self.start_dt, self.end_dt) start_dt = EventSettingProperty(paper_reviewing_settings, 'start_dt') end_dt = EventSettingProperty(paper_reviewing_settings, 'end_dt') content_reviewing_enabled = EventSettingProperty(paper_reviewing_settings, 'content_reviewing_enabled') layout_reviewing_enabled = EventSettingProperty(paper_reviewing_settings, 'layout_reviewing_enabled') judge_deadline = EventSettingProperty(paper_reviewing_settings, 'judge_deadline') layout_reviewer_deadline = EventSettingProperty(paper_reviewing_settings, 'layout_reviewer_deadline') content_reviewer_deadline = EventSettingProperty(paper_reviewing_settings, 'content_reviewer_deadline') @property def has_started(self): return self.start_dt is not None and self.start_dt <= now_utc() @property def has_ended(self): return self.end_dt is not None and self.end_dt <= now_utc() @property def is_open(self): return self.has_started and not self.has_ended def schedule(self, start_dt, end_dt): paper_reviewing_settings.set_multi(self.event, { 'start_dt': start_dt, 'end_dt': end_dt }) def open(self): if self.has_ended: paper_reviewing_settings.set(self.event, 'end_dt', None) else: paper_reviewing_settings.set(self.event, 'start_dt', now_utc(False)) def close(self): paper_reviewing_settings.set(self.event, 'end_dt', now_utc(False)) def set_reviewing_state(self, reviewing_type, enable): if reviewing_type == PaperReviewType.content: self.content_reviewing_enabled = enable elif reviewing_type == PaperReviewType.layout: self.layout_reviewing_enabled = enable else: raise ValueError('Invalid reviewing type: {}'.format(reviewing_type)) def get_reviewing_state(self, reviewing_type): if reviewing_type == PaperReviewType.content: return self.content_reviewing_enabled elif reviewing_type == PaperReviewType.layout: return self.layout_reviewing_enabled else: raise ValueError('Invalid reviewing type: {}'.format(reviewing_type)) @property def managers(self): return {p.principal for p in self.event.acl_entries if p.has_management_permission('paper_manager', explicit=True)} @property def judges(self): return {p.principal for p in self.event.acl_entries if p.has_management_permission('paper_judge', explicit=True)} @property def content_reviewers(self): return {p.principal for p in self.event.acl_entries if p.has_management_permission('paper_content_reviewer', explicit=True)} @property def layout_reviewers(self): return {p.principal for p in self.event.acl_entries if p.has_management_permission('paper_layout_reviewer', explicit=True)} @property def content_review_questions(self): return [q for q in self.event.paper_review_questions if q.type == PaperReviewType.content] @property def layout_review_questions(self): return [q for q in self.event.paper_review_questions if q.type == PaperReviewType.layout] @property def assignees(self): users = set(self.judges) if self.content_reviewing_enabled: users |= self.content_reviewers if self.layout_reviewing_enabled: users |= self.layout_reviewers return users @property @memoize_request def user_competences(self): user_ids = {user.id for user in self.event.cfp.assignees} user_competences = (PaperCompetence.query.with_parent(self.event) .filter(PaperCompetence.user_id.in_(user_ids)) .all()) return {competences.user_id: competences for competences in user_competences} @property def announcement(self): return MarkdownText(paper_reviewing_settings.get(self.event, 'announcement')) def get_questions_for_review_type(self, review_type): return (self.content_review_questions if review_type == PaperReviewType.content else self.layout_review_questions) @property def rating_range(self): return tuple(paper_reviewing_settings.get(self.event, key) for key in ('scale_lower', 'scale_upper')) def is_staff(self, user): return self.is_manager(user) or self.is_judge(user) or self.is_reviewer(user) def is_manager(self, user): return self.event.can_manage(user, permission='paper_manager') def is_judge(self, user): return self.event.can_manage(user, permission='paper_judge', explicit_permission=True) def is_reviewer(self, user, role=None): if role: enabled = { PaperReviewingRole.content_reviewer: self.content_reviewing_enabled, PaperReviewingRole.layout_reviewer: self.layout_reviewing_enabled, } return enabled[role] and self.event.can_manage(user, permission=role.acl_permission, explicit_permission=True) else: return (self.is_reviewer(user, PaperReviewingRole.content_reviewer) or self.is_reviewer(user, PaperReviewingRole.layout_reviewer)) def can_access_reviewing_area(self, user): return self.is_staff(user) def can_access_judging_area(self, user): return self.is_manager(user) or self.is_judge(user)
39.664671
110
0.696256
from __future__ import unicode_literals from indico.modules.events.papers.models.competences import PaperCompetence from indico.modules.events.papers.models.reviews import PaperReviewType from indico.modules.events.papers.settings import PaperReviewingRole, paper_reviewing_settings from indico.modules.events.settings import EventSettingProperty from indico.util.caching import memoize_request from indico.util.date_time import now_utc from indico.util.string import MarkdownText, return_ascii class CallForPapers(object): def __init__(self, event): self.event = event @return_ascii def __repr__(self): return '<CallForPapers({}, start_dt={}, end_dt={})>'.format(self.event.id, self.start_dt, self.end_dt) start_dt = EventSettingProperty(paper_reviewing_settings, 'start_dt') end_dt = EventSettingProperty(paper_reviewing_settings, 'end_dt') content_reviewing_enabled = EventSettingProperty(paper_reviewing_settings, 'content_reviewing_enabled') layout_reviewing_enabled = EventSettingProperty(paper_reviewing_settings, 'layout_reviewing_enabled') judge_deadline = EventSettingProperty(paper_reviewing_settings, 'judge_deadline') layout_reviewer_deadline = EventSettingProperty(paper_reviewing_settings, 'layout_reviewer_deadline') content_reviewer_deadline = EventSettingProperty(paper_reviewing_settings, 'content_reviewer_deadline') @property def has_started(self): return self.start_dt is not None and self.start_dt <= now_utc() @property def has_ended(self): return self.end_dt is not None and self.end_dt <= now_utc() @property def is_open(self): return self.has_started and not self.has_ended def schedule(self, start_dt, end_dt): paper_reviewing_settings.set_multi(self.event, { 'start_dt': start_dt, 'end_dt': end_dt }) def open(self): if self.has_ended: paper_reviewing_settings.set(self.event, 'end_dt', None) else: paper_reviewing_settings.set(self.event, 'start_dt', now_utc(False)) def close(self): paper_reviewing_settings.set(self.event, 'end_dt', now_utc(False)) def set_reviewing_state(self, reviewing_type, enable): if reviewing_type == PaperReviewType.content: self.content_reviewing_enabled = enable elif reviewing_type == PaperReviewType.layout: self.layout_reviewing_enabled = enable else: raise ValueError('Invalid reviewing type: {}'.format(reviewing_type)) def get_reviewing_state(self, reviewing_type): if reviewing_type == PaperReviewType.content: return self.content_reviewing_enabled elif reviewing_type == PaperReviewType.layout: return self.layout_reviewing_enabled else: raise ValueError('Invalid reviewing type: {}'.format(reviewing_type)) @property def managers(self): return {p.principal for p in self.event.acl_entries if p.has_management_permission('paper_manager', explicit=True)} @property def judges(self): return {p.principal for p in self.event.acl_entries if p.has_management_permission('paper_judge', explicit=True)} @property def content_reviewers(self): return {p.principal for p in self.event.acl_entries if p.has_management_permission('paper_content_reviewer', explicit=True)} @property def layout_reviewers(self): return {p.principal for p in self.event.acl_entries if p.has_management_permission('paper_layout_reviewer', explicit=True)} @property def content_review_questions(self): return [q for q in self.event.paper_review_questions if q.type == PaperReviewType.content] @property def layout_review_questions(self): return [q for q in self.event.paper_review_questions if q.type == PaperReviewType.layout] @property def assignees(self): users = set(self.judges) if self.content_reviewing_enabled: users |= self.content_reviewers if self.layout_reviewing_enabled: users |= self.layout_reviewers return users @property @memoize_request def user_competences(self): user_ids = {user.id for user in self.event.cfp.assignees} user_competences = (PaperCompetence.query.with_parent(self.event) .filter(PaperCompetence.user_id.in_(user_ids)) .all()) return {competences.user_id: competences for competences in user_competences} @property def announcement(self): return MarkdownText(paper_reviewing_settings.get(self.event, 'announcement')) def get_questions_for_review_type(self, review_type): return (self.content_review_questions if review_type == PaperReviewType.content else self.layout_review_questions) @property def rating_range(self): return tuple(paper_reviewing_settings.get(self.event, key) for key in ('scale_lower', 'scale_upper')) def is_staff(self, user): return self.is_manager(user) or self.is_judge(user) or self.is_reviewer(user) def is_manager(self, user): return self.event.can_manage(user, permission='paper_manager') def is_judge(self, user): return self.event.can_manage(user, permission='paper_judge', explicit_permission=True) def is_reviewer(self, user, role=None): if role: enabled = { PaperReviewingRole.content_reviewer: self.content_reviewing_enabled, PaperReviewingRole.layout_reviewer: self.layout_reviewing_enabled, } return enabled[role] and self.event.can_manage(user, permission=role.acl_permission, explicit_permission=True) else: return (self.is_reviewer(user, PaperReviewingRole.content_reviewer) or self.is_reviewer(user, PaperReviewingRole.layout_reviewer)) def can_access_reviewing_area(self, user): return self.is_staff(user) def can_access_judging_area(self, user): return self.is_manager(user) or self.is_judge(user)
true
true
f72d4a199674fe45edb35fd243b59bbb77a4e1f8
2,592
py
Python
examples/ppo/agent.py
jaehlee/flax
e01e2bcb012211d48e4c75e78297b8e15d742a37
[ "Apache-2.0" ]
2,249
2020-03-08T12:13:08.000Z
2022-03-31T10:25:13.000Z
examples/ppo/agent.py
jaehlee/flax
e01e2bcb012211d48e4c75e78297b8e15d742a37
[ "Apache-2.0" ]
1,338
2020-03-06T16:56:34.000Z
2022-03-31T13:46:49.000Z
examples/ppo/agent.py
jaehlee/flax
e01e2bcb012211d48e4c75e78297b8e15d742a37
[ "Apache-2.0" ]
343
2020-03-06T16:35:39.000Z
2022-03-27T17:31:45.000Z
# Copyright 2021 The Flax Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Agent utilities, incl. choosing the move and running in separate process.""" import functools import multiprocessing import collections from typing import Any, Callable import numpy as np import jax import flax import env_utils @functools.partial(jax.jit, static_argnums=0) def policy_action( apply_fn: Callable[..., Any], params: flax.core.frozen_dict.FrozenDict, state: np.ndarray): """Forward pass of the network. Args: params: the parameters of the actor-critic model module: the actor-critic model state: the input for the forward pass Returns: out: a tuple (log_probabilities, values) """ out = apply_fn({'params': params}, state) return out ExpTuple = collections.namedtuple( 'ExpTuple', ['state', 'action', 'reward', 'value', 'log_prob', 'done']) class RemoteSimulator: """Wrap functionality for an agent emulating Atari in a separate process. An object of this class is created for every agent. """ def __init__(self, game: str): """Start the remote process and create Pipe() to communicate with it.""" parent_conn, child_conn = multiprocessing.Pipe() self.proc = multiprocessing.Process( target=rcv_action_send_exp, args=(child_conn, game)) self.proc.daemon = True self.conn = parent_conn self.proc.start() def rcv_action_send_exp(conn, game: str): """Run the remote agents. Receive action from the main learner, perform one step of simulation and send back collected experience. """ env = env_utils.create_env(game, clip_rewards=True) while True: obs = env.reset() done = False # Observations fetched from Atari env need additional batch dimension. state = obs[None, ...] while not done: conn.send(state) action = conn.recv() obs, reward, done, _ = env.step(action) next_state = obs[None, ...] if not done else None experience = (state, action, reward, done) conn.send(experience) if done: break state = next_state
29.123596
79
0.707948
import functools import multiprocessing import collections from typing import Any, Callable import numpy as np import jax import flax import env_utils @functools.partial(jax.jit, static_argnums=0) def policy_action( apply_fn: Callable[..., Any], params: flax.core.frozen_dict.FrozenDict, state: np.ndarray): out = apply_fn({'params': params}, state) return out ExpTuple = collections.namedtuple( 'ExpTuple', ['state', 'action', 'reward', 'value', 'log_prob', 'done']) class RemoteSimulator: def __init__(self, game: str): parent_conn, child_conn = multiprocessing.Pipe() self.proc = multiprocessing.Process( target=rcv_action_send_exp, args=(child_conn, game)) self.proc.daemon = True self.conn = parent_conn self.proc.start() def rcv_action_send_exp(conn, game: str): env = env_utils.create_env(game, clip_rewards=True) while True: obs = env.reset() done = False state = obs[None, ...] while not done: conn.send(state) action = conn.recv() obs, reward, done, _ = env.step(action) next_state = obs[None, ...] if not done else None experience = (state, action, reward, done) conn.send(experience) if done: break state = next_state
true
true
f72d4ac16b95c592bb8e27f024b8fa3fe860340e
542
py
Python
slot_machine/output_literals.py
gorbulus/Slot_Machine
9bb3a93d4a3948b92a77c13a6a4ce5026b214ee4
[ "MIT" ]
null
null
null
slot_machine/output_literals.py
gorbulus/Slot_Machine
9bb3a93d4a3948b92a77c13a6a4ce5026b214ee4
[ "MIT" ]
null
null
null
slot_machine/output_literals.py
gorbulus/Slot_Machine
9bb3a93d4a3948b92a77c13a6a4ce5026b214ee4
[ "MIT" ]
null
null
null
# output_literals.py # William Ponton # 2.10.19 # Import modules import slot_machine.data_structures # Constants WELCOME = "\tWelcome to the Slot Machine!" RULES = "\tMatch 2 of any kind to win $5\n\tMatch 3 of any fruit to win $10\n\tMatch 3 BELLS to win $50!\n" ENGAGE = "Do you want to play? (y or n): " LEVER = "\t OK, pulling the lever!" DRAW = "\t{} | {} | {}" DRAW_MAX = 5 EARNED = "You earned ${}" PLAY_SUMMARY = "In {} play(s), you have earned ${:.1f}.\n" EXIT_MESSAGE = "Thanks for playing~!" DIV_LINE = ("=" * 40) NEW_LINE = "\n"
28.526316
107
0.651292
import slot_machine.data_structures WELCOME = "\tWelcome to the Slot Machine!" RULES = "\tMatch 2 of any kind to win $5\n\tMatch 3 of any fruit to win $10\n\tMatch 3 BELLS to win $50!\n" ENGAGE = "Do you want to play? (y or n): " LEVER = "\t OK, pulling the lever!" DRAW = "\t{} | {} | {}" DRAW_MAX = 5 EARNED = "You earned ${}" PLAY_SUMMARY = "In {} play(s), you have earned ${:.1f}.\n" EXIT_MESSAGE = "Thanks for playing~!" DIV_LINE = ("=" * 40) NEW_LINE = "\n"
true
true
f72d4b6995f7533f7aca12a0af1e7b0c0dacd90c
2,458
py
Python
handling-program-flow/code.py
krishnakammari/greyatom-python-for-data-science
8beab2a5f70304916d2d018c2283bf953db0b503
[ "MIT" ]
null
null
null
handling-program-flow/code.py
krishnakammari/greyatom-python-for-data-science
8beab2a5f70304916d2d018c2283bf953db0b503
[ "MIT" ]
null
null
null
handling-program-flow/code.py
krishnakammari/greyatom-python-for-data-science
8beab2a5f70304916d2d018c2283bf953db0b503
[ "MIT" ]
null
null
null
# -------------- ##File path for the file file_path #Code starts here def read_file(path): file1=open(path,"r") sentence=file1.readline() return sentence sample_message=read_file(file_path) # -------------- #Code starts here def read_file(path): fp=open(path,"r") return fp.readline() def fuse_msg(message_a,message_b): quotient=int(int(message_b)/int(message_a)) return quotient message_1=read_file(file_path_1) message_2=read_file(file_path_2) print(message_1) print(message_2) secret_msg_1=str(fuse_msg(message_1,message_2)) # -------------- #Code starts here file_path_3 def read_file(path): fp=open(path,"r") return fp.readline() message_3=read_file(file_path_3) print(message_3) def substitute_msg(message_c): if message_c=="Red": sub="Army General" return sub elif message_c=="Green": sub="Data Scientist" return sub elif message_c=="Blue": sub="Marine Biologist" return sub secret_msg_2=str(substitute_msg(message_3)) # -------------- # File path for message 4 and message 5 file_path_4 file_path_5 #Code starts here def read_file(path): fp=open(path,"r") return fp.readline() def compare_msg(message_d,message_e): a_list=message_d.split() b_list=message_e.split() c_list=list(i for i in a_list if i not in b_list) final_msg=" ".join(c_list) return final_msg message_4=read_file(file_path_4) message_5=read_file(file_path_5) print(message_4) print(message_5) secret_msg_3=compare_msg(str(message_4),str(message_5)) # -------------- #Code starts here def read_file(path): fp=open(path,"r") return fp.readline() even_word=lambda x: len(x)%2==0 def extract_msg(message_f): a_list=message_f.split() b_list=list(filter(even_word,a_list)) final_msg=" ".join(b_list) return final_msg message_6=read_file(file_path_6) print(message_6) secret_msg_4=extract_msg(message_6) # -------------- #Secret message parts in the correct order message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] final_path= user_data_dir + '/secret_message.txt' #Code starts here secret_msg=" ".join(message_parts) def write_file(secret_msg,path): fp=open(path,"a+") fp.write(secret_msg) fp.close() write_file(secret_msg,final_path) print(secret_msg)
19.054264
71
0.663141
d_file(path): file1=open(path,"r") sentence=file1.readline() return sentence sample_message=read_file(file_path) def read_file(path): fp=open(path,"r") return fp.readline() def fuse_msg(message_a,message_b): quotient=int(int(message_b)/int(message_a)) return quotient message_1=read_file(file_path_1) message_2=read_file(file_path_2) print(message_1) print(message_2) secret_msg_1=str(fuse_msg(message_1,message_2)) file_path_3 def read_file(path): fp=open(path,"r") return fp.readline() message_3=read_file(file_path_3) print(message_3) def substitute_msg(message_c): if message_c=="Red": sub="Army General" return sub elif message_c=="Green": sub="Data Scientist" return sub elif message_c=="Blue": sub="Marine Biologist" return sub secret_msg_2=str(substitute_msg(message_3)) file_path_4 file_path_5 def read_file(path): fp=open(path,"r") return fp.readline() def compare_msg(message_d,message_e): a_list=message_d.split() b_list=message_e.split() c_list=list(i for i in a_list if i not in b_list) final_msg=" ".join(c_list) return final_msg message_4=read_file(file_path_4) message_5=read_file(file_path_5) print(message_4) print(message_5) secret_msg_3=compare_msg(str(message_4),str(message_5)) def read_file(path): fp=open(path,"r") return fp.readline() even_word=lambda x: len(x)%2==0 def extract_msg(message_f): a_list=message_f.split() b_list=list(filter(even_word,a_list)) final_msg=" ".join(b_list) return final_msg message_6=read_file(file_path_6) print(message_6) secret_msg_4=extract_msg(message_6) message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] final_path= user_data_dir + '/secret_message.txt' secret_msg=" ".join(message_parts) def write_file(secret_msg,path): fp=open(path,"a+") fp.write(secret_msg) fp.close() write_file(secret_msg,final_path) print(secret_msg)
true
true
f72d4bb42b3c82dbcde9ccb416274b8896683766
16,657
py
Python
plotly_study/validators/table/__init__.py
lucasiscovici/plotly_py
42ab769febb45fbbe0a3c677dc4306a4f59cea36
[ "MIT" ]
null
null
null
plotly_study/validators/table/__init__.py
lucasiscovici/plotly_py
42ab769febb45fbbe0a3c677dc4306a4f59cea36
[ "MIT" ]
null
null
null
plotly_study/validators/table/__init__.py
lucasiscovici/plotly_py
42ab769febb45fbbe0a3c677dc4306a4f59cea36
[ "MIT" ]
null
null
null
import _plotly_utils.basevalidators class VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="visible", parent_name="table", **kwargs): super(VisibleValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "info"), values=kwargs.pop("values", [True, False, "legendonly"]), **kwargs ) import _plotly_utils.basevalidators class UirevisionValidator(_plotly_utils.basevalidators.AnyValidator): def __init__(self, plotly_name="uirevision", parent_name="table", **kwargs): super(UirevisionValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class UidValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="uid", parent_name="table", **kwargs): super(UidValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class StreamValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="stream", parent_name="table", **kwargs): super(StreamValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Stream"), data_docs=kwargs.pop( "data_docs", """ maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details. """, ), **kwargs ) import _plotly_utils.basevalidators class NameValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="name", parent_name="table", **kwargs): super(NameValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class MetasrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="metasrc", parent_name="table", **kwargs): super(MetasrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class MetaValidator(_plotly_utils.basevalidators.AnyValidator): def __init__(self, plotly_name="meta", parent_name="table", **kwargs): super(MetaValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class IdssrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="idssrc", parent_name="table", **kwargs): super(IdssrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class IdsValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="ids", parent_name="table", **kwargs): super(IdsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "data"), **kwargs ) import _plotly_utils.basevalidators class HoverlabelValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="hoverlabel", parent_name="table", **kwargs): super(HoverlabelValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Hoverlabel"), data_docs=kwargs.pop( "data_docs", """ align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on plot.ly for align . bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on plot.ly for bgcolor . bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on plot.ly for bordercolor . font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on plot.ly for namelength . """, ), **kwargs ) import _plotly_utils.basevalidators class HoverinfosrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="hoverinfosrc", parent_name="table", **kwargs): super(HoverinfosrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class HoverinfoValidator(_plotly_utils.basevalidators.FlaglistValidator): def __init__(self, plotly_name="hoverinfo", parent_name="table", **kwargs): super(HoverinfoValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), extras=kwargs.pop("extras", ["all", "none", "skip"]), flags=kwargs.pop("flags", ["x", "y", "z", "text", "name"]), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class HeaderValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="header", parent_name="table", **kwargs): super(HeaderValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Header"), data_docs=kwargs.pop( "data_docs", """ align Sets the horizontal alignment of the `text` within the box. Has an effect only if `text` spans more two or more lines (i.e. `text` contains one or more <br> HTML tags) or if an explicit width is set to override the text width. alignsrc Sets the source reference on plot.ly for align . fill plotly_study.graph_objects.table.header.Fill instance or dict with compatible properties font plotly_study.graph_objects.table.header.Font instance or dict with compatible properties format Sets the cell value formatting rule using d3 formatting mini-language which is similar to those of Python. See https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format formatsrc Sets the source reference on plot.ly for format . height The height of cells. line plotly_study.graph_objects.table.header.Line instance or dict with compatible properties prefix Prefix for cell values. prefixsrc Sets the source reference on plot.ly for prefix . suffix Suffix for cell values. suffixsrc Sets the source reference on plot.ly for suffix . values Header cell values. `values[m][n]` represents the value of the `n`th point in column `m`, therefore the `values[m]` vector length for all columns must be the same (longer vectors will be truncated). Each value must be a finite number or a string. valuessrc Sets the source reference on plot.ly for values . """, ), **kwargs ) import _plotly_utils.basevalidators class DomainValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="domain", parent_name="table", **kwargs): super(DomainValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Domain"), data_docs=kwargs.pop( "data_docs", """ column If there is a layout grid, use the domain for this column in the grid for this table trace . row If there is a layout grid, use the domain for this row in the grid for this table trace . x Sets the horizontal domain of this table trace (in plot fraction). y Sets the vertical domain of this table trace (in plot fraction). """, ), **kwargs ) import _plotly_utils.basevalidators class CustomdatasrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="customdatasrc", parent_name="table", **kwargs): super(CustomdatasrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="customdata", parent_name="table", **kwargs): super(CustomdataValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "data"), **kwargs ) import _plotly_utils.basevalidators class ColumnwidthsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="columnwidthsrc", parent_name="table", **kwargs): super(ColumnwidthsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class ColumnwidthValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="columnwidth", parent_name="table", **kwargs): super(ColumnwidthValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "style"), **kwargs ) import _plotly_utils.basevalidators class ColumnordersrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="columnordersrc", parent_name="table", **kwargs): super(ColumnordersrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class ColumnorderValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="columnorder", parent_name="table", **kwargs): super(ColumnorderValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "data"), **kwargs ) import _plotly_utils.basevalidators class CellsValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="cells", parent_name="table", **kwargs): super(CellsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Cells"), data_docs=kwargs.pop( "data_docs", """ align Sets the horizontal alignment of the `text` within the box. Has an effect only if `text` spans more two or more lines (i.e. `text` contains one or more <br> HTML tags) or if an explicit width is set to override the text width. alignsrc Sets the source reference on plot.ly for align . fill plotly_study.graph_objects.table.cells.Fill instance or dict with compatible properties font plotly_study.graph_objects.table.cells.Font instance or dict with compatible properties format Sets the cell value formatting rule using d3 formatting mini-language which is similar to those of Python. See https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format formatsrc Sets the source reference on plot.ly for format . height The height of cells. line plotly_study.graph_objects.table.cells.Line instance or dict with compatible properties prefix Prefix for cell values. prefixsrc Sets the source reference on plot.ly for prefix . suffix Suffix for cell values. suffixsrc Sets the source reference on plot.ly for suffix . values Cell values. `values[m][n]` represents the value of the `n`th point in column `m`, therefore the `values[m]` vector length for all columns must be the same (longer vectors will be truncated). Each value must be a finite number or a string. valuessrc Sets the source reference on plot.ly for values . """, ), **kwargs )
35.067368
84
0.58642
import _plotly_utils.basevalidators class VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="visible", parent_name="table", **kwargs): super(VisibleValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "info"), values=kwargs.pop("values", [True, False, "legendonly"]), **kwargs ) import _plotly_utils.basevalidators class UirevisionValidator(_plotly_utils.basevalidators.AnyValidator): def __init__(self, plotly_name="uirevision", parent_name="table", **kwargs): super(UirevisionValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class UidValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="uid", parent_name="table", **kwargs): super(UidValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class StreamValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="stream", parent_name="table", **kwargs): super(StreamValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Stream"), data_docs=kwargs.pop( "data_docs", """ maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details. """, ), **kwargs ) import _plotly_utils.basevalidators class NameValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="name", parent_name="table", **kwargs): super(NameValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class MetasrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="metasrc", parent_name="table", **kwargs): super(MetasrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class MetaValidator(_plotly_utils.basevalidators.AnyValidator): def __init__(self, plotly_name="meta", parent_name="table", **kwargs): super(MetaValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class IdssrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="idssrc", parent_name="table", **kwargs): super(IdssrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class IdsValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="ids", parent_name="table", **kwargs): super(IdsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "data"), **kwargs ) import _plotly_utils.basevalidators class HoverlabelValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="hoverlabel", parent_name="table", **kwargs): super(HoverlabelValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Hoverlabel"), data_docs=kwargs.pop( "data_docs", """ align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on plot.ly for align . bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on plot.ly for bgcolor . bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on plot.ly for bordercolor . font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on plot.ly for namelength . """, ), **kwargs ) import _plotly_utils.basevalidators class HoverinfosrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="hoverinfosrc", parent_name="table", **kwargs): super(HoverinfosrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class HoverinfoValidator(_plotly_utils.basevalidators.FlaglistValidator): def __init__(self, plotly_name="hoverinfo", parent_name="table", **kwargs): super(HoverinfoValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), extras=kwargs.pop("extras", ["all", "none", "skip"]), flags=kwargs.pop("flags", ["x", "y", "z", "text", "name"]), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class HeaderValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="header", parent_name="table", **kwargs): super(HeaderValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Header"), data_docs=kwargs.pop( "data_docs", """ align Sets the horizontal alignment of the `text` within the box. Has an effect only if `text` spans more two or more lines (i.e. `text` contains one or more <br> HTML tags) or if an explicit width is set to override the text width. alignsrc Sets the source reference on plot.ly for align . fill plotly_study.graph_objects.table.header.Fill instance or dict with compatible properties font plotly_study.graph_objects.table.header.Font instance or dict with compatible properties format Sets the cell value formatting rule using d3 formatting mini-language which is similar to those of Python. See https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format formatsrc Sets the source reference on plot.ly for format . height The height of cells. line plotly_study.graph_objects.table.header.Line instance or dict with compatible properties prefix Prefix for cell values. prefixsrc Sets the source reference on plot.ly for prefix . suffix Suffix for cell values. suffixsrc Sets the source reference on plot.ly for suffix . values Header cell values. `values[m][n]` represents the value of the `n`th point in column `m`, therefore the `values[m]` vector length for all columns must be the same (longer vectors will be truncated). Each value must be a finite number or a string. valuessrc Sets the source reference on plot.ly for values . """, ), **kwargs ) import _plotly_utils.basevalidators class DomainValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="domain", parent_name="table", **kwargs): super(DomainValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Domain"), data_docs=kwargs.pop( "data_docs", """ column If there is a layout grid, use the domain for this column in the grid for this table trace . row If there is a layout grid, use the domain for this row in the grid for this table trace . x Sets the horizontal domain of this table trace (in plot fraction). y Sets the vertical domain of this table trace (in plot fraction). """, ), **kwargs ) import _plotly_utils.basevalidators class CustomdatasrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="customdatasrc", parent_name="table", **kwargs): super(CustomdatasrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="customdata", parent_name="table", **kwargs): super(CustomdataValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "data"), **kwargs ) import _plotly_utils.basevalidators class ColumnwidthsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="columnwidthsrc", parent_name="table", **kwargs): super(ColumnwidthsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class ColumnwidthValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="columnwidth", parent_name="table", **kwargs): super(ColumnwidthValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "style"), **kwargs ) import _plotly_utils.basevalidators class ColumnordersrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="columnordersrc", parent_name="table", **kwargs): super(ColumnordersrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class ColumnorderValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="columnorder", parent_name="table", **kwargs): super(ColumnorderValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "data"), **kwargs ) import _plotly_utils.basevalidators class CellsValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="cells", parent_name="table", **kwargs): super(CellsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Cells"), data_docs=kwargs.pop( "data_docs", """ align Sets the horizontal alignment of the `text` within the box. Has an effect only if `text` spans more two or more lines (i.e. `text` contains one or more <br> HTML tags) or if an explicit width is set to override the text width. alignsrc Sets the source reference on plot.ly for align . fill plotly_study.graph_objects.table.cells.Fill instance or dict with compatible properties font plotly_study.graph_objects.table.cells.Font instance or dict with compatible properties format Sets the cell value formatting rule using d3 formatting mini-language which is similar to those of Python. See https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format formatsrc Sets the source reference on plot.ly for format . height The height of cells. line plotly_study.graph_objects.table.cells.Line instance or dict with compatible properties prefix Prefix for cell values. prefixsrc Sets the source reference on plot.ly for prefix . suffix Suffix for cell values. suffixsrc Sets the source reference on plot.ly for suffix . values Cell values. `values[m][n]` represents the value of the `n`th point in column `m`, therefore the `values[m]` vector length for all columns must be the same (longer vectors will be truncated). Each value must be a finite number or a string. valuessrc Sets the source reference on plot.ly for values . """, ), **kwargs )
true
true
f72d4ca040a06d403beb425e327eeba6d1205c6a
26,527
py
Python
py/legacypipe/unwise.py
ameisner/legacypipe
5ffe6fb2458618b68653580badc4a94e1ecb4f04
[ "BSD-3-Clause" ]
null
null
null
py/legacypipe/unwise.py
ameisner/legacypipe
5ffe6fb2458618b68653580badc4a94e1ecb4f04
[ "BSD-3-Clause" ]
null
null
null
py/legacypipe/unwise.py
ameisner/legacypipe
5ffe6fb2458618b68653580badc4a94e1ecb4f04
[ "BSD-3-Clause" ]
null
null
null
import os import numpy as np import fitsio from astrometry.util.fits import fits_table from astrometry.util.ttime import Time from wise.unwise import get_unwise_tractor_image import logging logger = logging.getLogger('legacypipe.unwise') def info(*args): from legacypipe.utils import log_info log_info(logger, args) def debug(*args): from legacypipe.utils import log_debug log_debug(logger, args) ''' This function was imported whole from the tractor repo: wise/forcedphot.py because I figured we were doing enough LegacySurvey-specific stuff in it that it was time to just import it and edit it rather than build elaborate options. ''' def unwise_forcedphot(cat, tiles, band=1, roiradecbox=None, use_ceres=True, ceres_block=8, save_fits=False, get_models=False, ps=None, psf_broadening=None, pixelized_psf=False, get_masks=None, move_crpix=False, modelsky_dir=None): ''' Given a list of tractor sources *cat* and a list of unWISE tiles *tiles* (a fits_table with RA,Dec,coadd_id) runs forced photometry, returning a FITS table the same length as *cat*. *get_masks*: the WCS to resample mask bits into. ''' from tractor import PointSource, Tractor, ExpGalaxy, DevGalaxy from tractor.sersic import SersicGalaxy if not pixelized_psf and psf_broadening is None: # PSF broadening in post-reactivation data, by band. # Newer version from Aaron's email to decam-chatter, 2018-06-14. broadening = { 1: 1.0405, 2: 1.0346, 3: None, 4: None } psf_broadening = broadening[band] if False: from astrometry.util.plotutils import PlotSequence ps = PlotSequence('wise-forced-w%i' % band) plots = (ps is not None) if plots: import pylab as plt wantims = (plots or save_fits or get_models) wanyband = 'w' if get_models: models = [] wband = 'w%i' % band Nsrcs = len(cat) phot = fits_table() # Filled in based on unique tile overlap phot.wise_coadd_id = np.array([' '] * Nsrcs, dtype='U8') phot.wise_x = np.zeros(Nsrcs, np.float32) phot.wise_y = np.zeros(Nsrcs, np.float32) phot.set('psfdepth_%s' % wband, np.zeros(Nsrcs, np.float32)) nexp = np.zeros(Nsrcs, np.int16) mjd = np.zeros(Nsrcs, np.float64) central_flux = np.zeros(Nsrcs, np.float32) ra = np.array([src.getPosition().ra for src in cat]) dec = np.array([src.getPosition().dec for src in cat]) fskeys = ['prochi2', 'profracflux'] fitstats = {} if get_masks: mh,mw = get_masks.shape maskmap = np.zeros((mh,mw), np.uint32) tims = [] for tile in tiles: info('Reading WISE tile', tile.coadd_id, 'band', band) tim = get_unwise_tractor_image(tile.unwise_dir, tile.coadd_id, band, bandname=wanyband, roiradecbox=roiradecbox) if tim is None: debug('Actually, no overlap with WISE coadd tile', tile.coadd_id) continue if plots: sig1 = tim.sig1 plt.clf() plt.imshow(tim.getImage(), interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=10 * sig1) plt.colorbar() tag = '%s W%i' % (tile.coadd_id, band) plt.title('%s: tim data' % tag) ps.savefig() plt.clf() plt.hist((tim.getImage() * tim.inverr)[tim.inverr > 0].ravel(), range=(-5,10), bins=100) plt.xlabel('Per-pixel intensity (Sigma)') plt.title(tag) ps.savefig() if move_crpix and band in [1, 2]: realwcs = tim.wcs.wcs x,y = realwcs.crpix tile_crpix = tile.get('crpix_w%i' % band) dx = tile_crpix[0] - 1024.5 dy = tile_crpix[1] - 1024.5 realwcs.set_crpix(x+dx, y+dy) debug('unWISE', tile.coadd_id, 'band', band, 'CRPIX', x,y, 'shift by', dx,dy, 'to', realwcs.crpix) if modelsky_dir and band in [1, 2]: fn = os.path.join(modelsky_dir, '%s.%i.mod.fits' % (tile.coadd_id, band)) if not os.path.exists(fn): raise RuntimeError('WARNING: does not exist:', fn) x0,x1,y0,y1 = tim.roi bg = fitsio.FITS(fn)[2][y0:y1, x0:x1] assert(bg.shape == tim.shape) if plots: plt.clf() plt.subplot(1,2,1) plt.imshow(tim.getImage(), interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=5 * sig1) plt.subplot(1,2,2) plt.imshow(bg, interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=5 * sig1) tag = '%s W%i' % (tile.coadd_id, band) plt.suptitle(tag) ps.savefig() plt.clf() ha = dict(range=(-5,10), bins=100, histtype='step') plt.hist((tim.getImage() * tim.inverr)[tim.inverr > 0].ravel(), color='b', label='Original', **ha) plt.hist(((tim.getImage()-bg) * tim.inverr)[tim.inverr > 0].ravel(), color='g', label='Minus Background', **ha) plt.axvline(0, color='k', alpha=0.5) plt.xlabel('Per-pixel intensity (Sigma)') plt.legend() plt.title(tag + ': background') ps.savefig() # Actually subtract the background! tim.data -= bg # Floor the per-pixel variances, # and add Poisson contribution from sources if band in [1,2]: # in Vega nanomaggies per pixel floor_sigma = {1: 0.5, 2: 2.0} poissons = {1: 0.15, 2: 0.3} with np.errstate(divide='ignore'): new_ie = 1. / np.sqrt( (1./tim.inverr)**2 + floor_sigma[band]**2 + poissons[band]**2 * np.maximum(0., tim.data)) new_ie[tim.inverr == 0] = 0. if plots: plt.clf() plt.plot((1. / tim.inverr[tim.inverr>0]).ravel(), (1./new_ie[tim.inverr>0]).ravel(), 'b.') plt.title('unWISE per-pixel error: %s band %i' % (tile.coadd_id, band)) plt.xlabel('original') plt.ylabel('floored') ps.savefig() assert(np.all(np.isfinite(new_ie))) assert(np.all(new_ie >= 0.)) tim.inverr = new_ie # Expand a 3-pixel radius around weight=0 (saturated) pixels # from Eddie via crowdsource # https://github.com/schlafly/crowdsource/blob/7069da3e7d9d3124be1cbbe1d21ffeb63fc36dcc/python/wise_proc.py#L74 ## FIXME -- W3/W4 ?? satlimit = 85000 msat = ((tim.data > satlimit) | ((tim.nims == 0) & (tim.nuims > 1))) from scipy.ndimage.morphology import binary_dilation xx, yy = np.mgrid[-3:3+1, -3:3+1] dilate = xx**2+yy**2 <= 3**2 msat = binary_dilation(msat, dilate) nbefore = np.sum(tim.inverr == 0) tim.inverr[msat] = 0 nafter = np.sum(tim.inverr == 0) debug('Masking an additional', (nafter-nbefore), 'near-saturated pixels in unWISE', tile.coadd_id, 'band', band) # Read mask file? if get_masks: from astrometry.util.resample import resample_with_wcs, OverlapError # unwise_dir can be a colon-separated list of paths tilemask = None for d in tile.unwise_dir.split(':'): fn = os.path.join(d, tile.coadd_id[:3], tile.coadd_id, 'unwise-%s-msk.fits.gz' % tile.coadd_id) if os.path.exists(fn): debug('Reading unWISE mask file', fn) x0,x1,y0,y1 = tim.roi tilemask = fitsio.FITS(fn)[0][y0:y1,x0:x1] break if tilemask is None: info('unWISE mask file for tile', tile.coadd_id, 'does not exist') else: try: tanwcs = tim.wcs.wcs assert(tanwcs.shape == tilemask.shape) Yo,Xo,Yi,Xi,_ = resample_with_wcs(get_masks, tanwcs, intType=np.int16) # Only deal with mask pixels that are set. I, = np.nonzero(tilemask[Yi,Xi] > 0) # Trim to unique area for this tile rr,dd = get_masks.pixelxy2radec(Xo[I]+1, Yo[I]+1) good = radec_in_unique_area(rr, dd, tile.ra1, tile.ra2, tile.dec1, tile.dec2) I = I[good] maskmap[Yo[I],Xo[I]] = tilemask[Yi[I], Xi[I]] except OverlapError: # Shouldn't happen by this point print('Warning: no overlap between WISE tile', tile.coadd_id, 'and brick') if plots: plt.clf() plt.imshow(tilemask, interpolation='nearest', origin='lower') plt.title('Tile %s: mask' % tile.coadd_id) ps.savefig() plt.clf() plt.imshow(maskmap, interpolation='nearest', origin='lower') plt.title('Tile %s: accumulated maskmap' % tile.coadd_id) ps.savefig() # The tiles have some overlap, so zero out pixels outside the # tile's unique area. th,tw = tim.shape xx,yy = np.meshgrid(np.arange(tw), np.arange(th)) rr,dd = tim.wcs.wcs.pixelxy2radec(xx+1, yy+1) unique = radec_in_unique_area(rr, dd, tile.ra1, tile.ra2, tile.dec1, tile.dec2) debug('Tile', tile.coadd_id, '- total of', np.sum(unique), 'unique pixels out of', len(unique.flat), 'total pixels') if get_models: # Save the inverr before blanking out non-unique pixels, for making coadds with no gaps! # (actually, slightly more subtly, expand unique area by 1 pixel) from scipy.ndimage.morphology import binary_dilation du = binary_dilation(unique) tim.coadd_inverr = tim.inverr * du tim.inverr[unique == False] = 0. del xx,yy,rr,dd,unique if plots: sig1 = tim.sig1 plt.clf() plt.imshow(tim.getImage() * (tim.inverr > 0), interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=10 * sig1) plt.colorbar() tag = '%s W%i' % (tile.coadd_id, band) plt.title('%s: tim data (unique)' % tag) ps.savefig() if pixelized_psf: from unwise_psf import unwise_psf if (band == 1) or (band == 2): # we only have updated PSFs for W1 and W2 psfimg = unwise_psf.get_unwise_psf(band, tile.coadd_id, modelname='neo6_unwisecat') else: psfimg = unwise_psf.get_unwise_psf(band, tile.coadd_id) if band == 4: # oversample (the unwise_psf models are at native W4 5.5"/pix, # while the unWISE coadds are made at 2.75"/pix. ph,pw = psfimg.shape subpsf = np.zeros((ph*2-1, pw*2-1), np.float32) from astrometry.util.util import lanczos3_interpolate xx,yy = np.meshgrid(np.arange(0., pw-0.51, 0.5, dtype=np.float32), np.arange(0., ph-0.51, 0.5, dtype=np.float32)) xx = xx.ravel() yy = yy.ravel() ix = xx.astype(np.int32) iy = yy.astype(np.int32) dx = (xx - ix).astype(np.float32) dy = (yy - iy).astype(np.float32) psfimg = psfimg.astype(np.float32) rtn = lanczos3_interpolate(ix, iy, dx, dy, [subpsf.flat], [psfimg]) if plots: plt.clf() plt.imshow(psfimg, interpolation='nearest', origin='lower') plt.title('Original PSF model') ps.savefig() plt.clf() plt.imshow(subpsf, interpolation='nearest', origin='lower') plt.title('Subsampled PSF model') ps.savefig() psfimg = subpsf del xx, yy, ix, iy, dx, dy from tractor.psf import PixelizedPSF psfimg /= psfimg.sum() fluxrescales = {1: 1.04, 2: 1.005, 3: 1.0, 4: 1.0} psfimg *= fluxrescales[band] tim.psf = PixelizedPSF(psfimg) if psf_broadening is not None and not pixelized_psf: # psf_broadening is a factor by which the PSF FWHMs # should be scaled; the PSF is a little wider # post-reactivation. psf = tim.getPsf() from tractor import GaussianMixturePSF if isinstance(psf, GaussianMixturePSF): debug('Broadening PSF: from', psf) p0 = psf.getParams() pnames = psf.getParamNames() p1 = [p * psf_broadening**2 if 'var' in name else p for (p, name) in zip(p0, pnames)] psf.setParams(p1) debug('Broadened PSF:', psf) else: print('WARNING: cannot apply psf_broadening to WISE PSF of type', type(psf)) wcs = tim.wcs.wcs _,fx,fy = wcs.radec2pixelxy(ra, dec) x = np.round(fx - 1.).astype(int) y = np.round(fy - 1.).astype(int) good = (x >= 0) * (x < tw) * (y >= 0) * (y < th) # Which sources are in this brick's unique area? usrc = radec_in_unique_area(ra, dec, tile.ra1, tile.ra2, tile.dec1, tile.dec2) I, = np.nonzero(good * usrc) nexp[I] = tim.nuims[y[I], x[I]] if hasattr(tim, 'mjdmin') and hasattr(tim, 'mjdmax'): mjd[I] = (tim.mjdmin + tim.mjdmax) / 2. phot.wise_coadd_id[I] = tile.coadd_id phot.wise_x[I] = fx[I] - 1. phot.wise_y[I] = fy[I] - 1. central_flux[I] = tim.getImage()[y[I], x[I]] del x,y,good,usrc # PSF norm for depth psf = tim.getPsf() h,w = tim.shape patch = psf.getPointSourcePatch(h//2, w//2).patch psfnorm = np.sqrt(np.sum(patch**2)) # To handle zero-depth, we return 1/nanomaggies^2 units rather than mags. # In the small empty patches of the sky (eg W4 in 0922p702), we get sig1 = NaN if np.isfinite(tim.sig1): phot.get('psfdepth_%s' % wband)[I] = 1. / (tim.sig1 / psfnorm)**2 tim.tile = tile tims.append(tim) if plots: plt.clf() mn,mx = 0.1, 20000 plt.hist(np.log10(np.clip(central_flux, mn, mx)), bins=100, range=(np.log10(mn), np.log10(mx))) logt = np.arange(0, 5) plt.xticks(logt, ['%i' % i for i in 10.**logt]) plt.title('Central fluxes (W%i)' % band) plt.axvline(np.log10(20000), color='k') plt.axvline(np.log10(1000), color='k') ps.savefig() # Eddie's non-secret recipe: #- central pixel <= 1000: 19x19 pix box size #- central pixel in 1000 - 20000: 59x59 box size #- central pixel > 20000 or saturated: 149x149 box size #- object near "bright star": 299x299 box size nbig = nmedium = nsmall = 0 for src,cflux in zip(cat, central_flux): if cflux > 20000: R = 100 nbig += 1 elif cflux > 1000: R = 30 nmedium += 1 else: R = 15 nsmall += 1 if isinstance(src, PointSource): src.fixedRadius = R else: ### FIXME -- sizes for galaxies..... can we set PSF size separately? galrad = 0 # RexGalaxy is a subclass of ExpGalaxy if isinstance(src, (ExpGalaxy, DevGalaxy, SersicGalaxy)): galrad = src.shape.re pixscale = 2.75 src.halfsize = int(np.hypot(R, galrad * 5 / pixscale)) debug('Set WISE source sizes:', nbig, 'big', nmedium, 'medium', nsmall, 'small') tractor = Tractor(tims, cat) if use_ceres: from tractor.ceres_optimizer import CeresOptimizer tractor.optimizer = CeresOptimizer(BW=ceres_block, BH=ceres_block) tractor.freezeParamsRecursive('*') tractor.thawPathsTo(wanyband) t0 = Time() R = tractor.optimize_forced_photometry( fitstats=True, variance=True, shared_params=False, wantims=wantims) info('unWISE forced photometry took', Time() - t0) if use_ceres: term = R.ceres_status['termination'] # Running out of memory can cause failure to converge and term # status = 2. Fail completely in this case. if term != 0: info('Ceres termination status:', term) raise RuntimeError('Ceres terminated with status %i' % term) if wantims: ims1 = R.ims1 # can happen if empty source list (we still want to generate coadds) if ims1 is None: ims1 = R.ims0 flux_invvars = R.IV if R.fitstats is not None: for k in fskeys: x = getattr(R.fitstats, k) fitstats[k] = np.array(x).astype(np.float32) if save_fits: for i,tim in enumerate(tims): tile = tim.tile (dat, mod, _, chi, _) = ims1[i] wcshdr = fitsio.FITSHDR() tim.wcs.wcs.add_to_header(wcshdr) tag = 'fit-%s-w%i' % (tile.coadd_id, band) fitsio.write('%s-data.fits' % tag, dat, clobber=True, header=wcshdr) fitsio.write('%s-mod.fits' % tag, mod, clobber=True, header=wcshdr) fitsio.write('%s-chi.fits' % tag, chi, clobber=True, header=wcshdr) if plots: # Create models for just the brightest sources bright_cat = [src for src in cat if src.getBrightness().getBand(wanyband) > 1000] debug('Bright soures:', len(bright_cat)) btr = Tractor(tims, bright_cat) for tim in tims: mod = btr.getModelImage(tim) tile = tim.tile tag = '%s W%i' % (tile.coadd_id, band) sig1 = tim.sig1 plt.clf() plt.imshow(mod, interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=25 * sig1) plt.colorbar() plt.title('%s: bright-star models' % tag) ps.savefig() if get_models: for i,tim in enumerate(tims): tile = tim.tile (dat, mod, _, _, _) = ims1[i] models.append((tile.coadd_id, band, tim.wcs.wcs, dat, mod, tim.coadd_inverr)) if plots: for i,tim in enumerate(tims): tile = tim.tile tag = '%s W%i' % (tile.coadd_id, band) (dat, mod, _, chi, _) = ims1[i] sig1 = tim.sig1 plt.clf() plt.imshow(dat, interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=25 * sig1) plt.colorbar() plt.title('%s: data' % tag) ps.savefig() plt.clf() plt.imshow(mod, interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=25 * sig1) plt.colorbar() plt.title('%s: model' % tag) ps.savefig() plt.clf() plt.imshow(chi, interpolation='nearest', origin='lower', cmap='gray', vmin=-5, vmax=+5) plt.colorbar() plt.title('%s: chi' % tag) ps.savefig() nm = np.array([src.getBrightness().getBand(wanyband) for src in cat]) nm_ivar = flux_invvars # Sources out of bounds, eg, never change from their initial # fluxes. Zero them out instead. nm[nm_ivar == 0] = 0. phot.set('flux_%s' % wband, nm.astype(np.float32)) phot.set('flux_ivar_%s' % wband, nm_ivar.astype(np.float32)) for k in fskeys: phot.set(k + '_' + wband, fitstats.get(k, np.zeros(len(phot), np.float32))) phot.set('nobs_%s' % wband, nexp) phot.set('mjd_%s' % wband, mjd) rtn = wphotduck() rtn.phot = phot rtn.models = None rtn.maskmap = None if get_models: rtn.models = models if get_masks: rtn.maskmap = maskmap return rtn class wphotduck(object): pass def radec_in_unique_area(rr, dd, ra1, ra2, dec1, dec2): '''Are the given points within the given RA,Dec rectangle? Returns a boolean array.''' unique = (dd >= dec1) * (dd < dec2) if ra1 < ra2: # normal RA unique *= (rr >= ra1) * (rr < ra2) else: # RA wrap-around unique[rr > 180] *= (rr[rr > 180] >= ra1) unique[rr < 180] *= (rr[rr < 180] < ra2) return unique def unwise_phot(X): ''' This is the entry-point from runbrick.py, called via mp.map() ''' (key, (wcat, tiles, band, roiradec, wise_ceres, pixelized_psf, get_mods, get_masks, ps, move_crpix, modelsky_dir)) = X kwargs = dict(roiradecbox=roiradec, band=band, pixelized_psf=pixelized_psf, get_masks=get_masks, ps=ps, move_crpix=move_crpix, modelsky_dir=modelsky_dir) if get_mods: kwargs.update(get_models=get_mods) if wise_ceres and len(wcat) == 0: wise_ceres = False # DEBUG #kwargs.update(save_fits=True) W = None try: W = unwise_forcedphot(wcat, tiles, use_ceres=wise_ceres, **kwargs) except: import traceback print('unwise_forcedphot failed:') traceback.print_exc() if wise_ceres: print('Trying without Ceres...') try: W = unwise_forcedphot(wcat, tiles, use_ceres=False, **kwargs) except: print('unwise_forcedphot failed (2):') traceback.print_exc() return key,W def collapse_unwise_bitmask(bitmask, band): ''' Converts WISE mask bits (in the unWISE data products) into the more compact codes reported in the tractor files as WISEMASK_W[12], and the "maskbits" WISE extensions. output bits : # 2^0 = bright star core and wings # 2^1 = PSF-based diffraction spike # 2^2 = optical ghost # 2^3 = first latent # 2^4 = second latent # 2^5 = AllWISE-like circular halo # 2^6 = bright star saturation # 2^7 = geometric diffraction spike ''' assert((band == 1) or (band == 2)) from collections import OrderedDict bits_w1 = OrderedDict([('core_wings', 2**0 + 2**1), ('psf_spike', 2**27), ('ghost', 2**25 + 2**26), ('first_latent', 2**13 + 2**14), ('second_latent', 2**17 + 2**18), ('circular_halo', 2**23), ('saturation', 2**4), ('geom_spike', 2**29)]) bits_w2 = OrderedDict([('core_wings', 2**2 + 2**3), ('psf_spike', 2**28), ('ghost', 2**11 + 2**12), ('first_latent', 2**15 + 2**16), ('second_latent', 2**19 + 2**20), ('circular_halo', 2**24), ('saturation', 2**5), ('geom_spike', 2**30)]) bits = (bits_w1 if (band == 1) else bits_w2) # hack to handle both scalar and array inputs result = 0*bitmask for i, feat in enumerate(bits.keys()): result += ((2**i)*(np.bitwise_and(bitmask, bits[feat]) != 0)).astype(np.uint8) return result.astype('uint8') ### # This is taken directly from tractor/wise.py, replacing only the filename. ### def unwise_tiles_touching_wcs(wcs, polygons=True): ''' Returns a FITS table (with RA,Dec,coadd_id) of unWISE tiles ''' from astrometry.util.miscutils import polygons_intersect from astrometry.util.starutil_numpy import degrees_between from pkg_resources import resource_filename atlasfn = resource_filename('legacypipe', 'data/wise-tiles.fits') T = fits_table(atlasfn) trad = wcs.radius() wrad = np.sqrt(2.) / 2. * 2048 * 2.75 / 3600. rad = trad + wrad r, d = wcs.radec_center() I, = np.nonzero(np.abs(T.dec - d) < rad) I = I[degrees_between(T.ra[I], T.dec[I], r, d) < rad] if not polygons: return T[I] # now check actual polygon intersection tw, th = wcs.imagew, wcs.imageh targetpoly = [(0.5, 0.5), (tw + 0.5, 0.5), (tw + 0.5, th + 0.5), (0.5, th + 0.5)] cd = wcs.get_cd() tdet = cd[0] * cd[3] - cd[1] * cd[2] if tdet > 0: targetpoly = list(reversed(targetpoly)) targetpoly = np.array(targetpoly) keep = [] for i in I: wwcs = unwise_tile_wcs(T.ra[i], T.dec[i]) cd = wwcs.get_cd() wdet = cd[0] * cd[3] - cd[1] * cd[2] H, W = wwcs.shape poly = [] for x, y in [(0.5, 0.5), (W + 0.5, 0.5), (W + 0.5, H + 0.5), (0.5, H + 0.5)]: rr,dd = wwcs.pixelxy2radec(x, y) _,xx,yy = wcs.radec2pixelxy(rr, dd) poly.append((xx, yy)) if wdet > 0: poly = list(reversed(poly)) poly = np.array(poly) if polygons_intersect(targetpoly, poly): keep.append(i) I = np.array(keep) return T[I] ### Also direct from tractor/wise.py def unwise_tile_wcs(ra, dec, W=2048, H=2048, pixscale=2.75): from astrometry.util.util import Tan ''' Returns a Tan WCS object at the given RA,Dec center, axis aligned, with the given pixel W,H and pixel scale in arcsec/pixel. ''' cowcs = Tan(ra, dec, (W + 1) / 2., (H + 1) / 2., -pixscale / 3600., 0., 0., pixscale / 3600., W, H) return cowcs
39.183161
123
0.529121
import os import numpy as np import fitsio from astrometry.util.fits import fits_table from astrometry.util.ttime import Time from wise.unwise import get_unwise_tractor_image import logging logger = logging.getLogger('legacypipe.unwise') def info(*args): from legacypipe.utils import log_info log_info(logger, args) def debug(*args): from legacypipe.utils import log_debug log_debug(logger, args) def unwise_forcedphot(cat, tiles, band=1, roiradecbox=None, use_ceres=True, ceres_block=8, save_fits=False, get_models=False, ps=None, psf_broadening=None, pixelized_psf=False, get_masks=None, move_crpix=False, modelsky_dir=None): from tractor import PointSource, Tractor, ExpGalaxy, DevGalaxy from tractor.sersic import SersicGalaxy if not pixelized_psf and psf_broadening is None: broadening = { 1: 1.0405, 2: 1.0346, 3: None, 4: None } psf_broadening = broadening[band] if False: from astrometry.util.plotutils import PlotSequence ps = PlotSequence('wise-forced-w%i' % band) plots = (ps is not None) if plots: import pylab as plt wantims = (plots or save_fits or get_models) wanyband = 'w' if get_models: models = [] wband = 'w%i' % band Nsrcs = len(cat) phot = fits_table() # Filled in based on unique tile overlap phot.wise_coadd_id = np.array([' '] * Nsrcs, dtype='U8') phot.wise_x = np.zeros(Nsrcs, np.float32) phot.wise_y = np.zeros(Nsrcs, np.float32) phot.set('psfdepth_%s' % wband, np.zeros(Nsrcs, np.float32)) nexp = np.zeros(Nsrcs, np.int16) mjd = np.zeros(Nsrcs, np.float64) central_flux = np.zeros(Nsrcs, np.float32) ra = np.array([src.getPosition().ra for src in cat]) dec = np.array([src.getPosition().dec for src in cat]) fskeys = ['prochi2', 'profracflux'] fitstats = {} if get_masks: mh,mw = get_masks.shape maskmap = np.zeros((mh,mw), np.uint32) tims = [] for tile in tiles: info('Reading WISE tile', tile.coadd_id, 'band', band) tim = get_unwise_tractor_image(tile.unwise_dir, tile.coadd_id, band, bandname=wanyband, roiradecbox=roiradecbox) if tim is None: debug('Actually, no overlap with WISE coadd tile', tile.coadd_id) continue if plots: sig1 = tim.sig1 plt.clf() plt.imshow(tim.getImage(), interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=10 * sig1) plt.colorbar() tag = '%s W%i' % (tile.coadd_id, band) plt.title('%s: tim data' % tag) ps.savefig() plt.clf() plt.hist((tim.getImage() * tim.inverr)[tim.inverr > 0].ravel(), range=(-5,10), bins=100) plt.xlabel('Per-pixel intensity (Sigma)') plt.title(tag) ps.savefig() if move_crpix and band in [1, 2]: realwcs = tim.wcs.wcs x,y = realwcs.crpix tile_crpix = tile.get('crpix_w%i' % band) dx = tile_crpix[0] - 1024.5 dy = tile_crpix[1] - 1024.5 realwcs.set_crpix(x+dx, y+dy) debug('unWISE', tile.coadd_id, 'band', band, 'CRPIX', x,y, 'shift by', dx,dy, 'to', realwcs.crpix) if modelsky_dir and band in [1, 2]: fn = os.path.join(modelsky_dir, '%s.%i.mod.fits' % (tile.coadd_id, band)) if not os.path.exists(fn): raise RuntimeError('WARNING: does not exist:', fn) x0,x1,y0,y1 = tim.roi bg = fitsio.FITS(fn)[2][y0:y1, x0:x1] assert(bg.shape == tim.shape) if plots: plt.clf() plt.subplot(1,2,1) plt.imshow(tim.getImage(), interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=5 * sig1) plt.subplot(1,2,2) plt.imshow(bg, interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=5 * sig1) tag = '%s W%i' % (tile.coadd_id, band) plt.suptitle(tag) ps.savefig() plt.clf() ha = dict(range=(-5,10), bins=100, histtype='step') plt.hist((tim.getImage() * tim.inverr)[tim.inverr > 0].ravel(), color='b', label='Original', **ha) plt.hist(((tim.getImage()-bg) * tim.inverr)[tim.inverr > 0].ravel(), color='g', label='Minus Background', **ha) plt.axvline(0, color='k', alpha=0.5) plt.xlabel('Per-pixel intensity (Sigma)') plt.legend() plt.title(tag + ': background') ps.savefig() # Actually subtract the background! tim.data -= bg # Floor the per-pixel variances, # and add Poisson contribution from sources if band in [1,2]: # in Vega nanomaggies per pixel floor_sigma = {1: 0.5, 2: 2.0} poissons = {1: 0.15, 2: 0.3} with np.errstate(divide='ignore'): new_ie = 1. / np.sqrt( (1./tim.inverr)**2 + floor_sigma[band]**2 + poissons[band]**2 * np.maximum(0., tim.data)) new_ie[tim.inverr == 0] = 0. if plots: plt.clf() plt.plot((1. / tim.inverr[tim.inverr>0]).ravel(), (1./new_ie[tim.inverr>0]).ravel(), 'b.') plt.title('unWISE per-pixel error: %s band %i' % (tile.coadd_id, band)) plt.xlabel('original') plt.ylabel('floored') ps.savefig() assert(np.all(np.isfinite(new_ie))) assert(np.all(new_ie >= 0.)) tim.inverr = new_ie # Expand a 3-pixel radius around weight=0 (saturated) pixels # from Eddie via crowdsource # https://github.com/schlafly/crowdsource/blob/7069da3e7d9d3124be1cbbe1d21ffeb63fc36dcc/python/wise_proc.py#L74 ## FIXME -- W3/W4 ?? satlimit = 85000 msat = ((tim.data > satlimit) | ((tim.nims == 0) & (tim.nuims > 1))) from scipy.ndimage.morphology import binary_dilation xx, yy = np.mgrid[-3:3+1, -3:3+1] dilate = xx**2+yy**2 <= 3**2 msat = binary_dilation(msat, dilate) nbefore = np.sum(tim.inverr == 0) tim.inverr[msat] = 0 nafter = np.sum(tim.inverr == 0) debug('Masking an additional', (nafter-nbefore), 'near-saturated pixels in unWISE', tile.coadd_id, 'band', band) # Read mask file? if get_masks: from astrometry.util.resample import resample_with_wcs, OverlapError # unwise_dir can be a colon-separated list of paths tilemask = None for d in tile.unwise_dir.split(':'): fn = os.path.join(d, tile.coadd_id[:3], tile.coadd_id, 'unwise-%s-msk.fits.gz' % tile.coadd_id) if os.path.exists(fn): debug('Reading unWISE mask file', fn) x0,x1,y0,y1 = tim.roi tilemask = fitsio.FITS(fn)[0][y0:y1,x0:x1] break if tilemask is None: info('unWISE mask file for tile', tile.coadd_id, 'does not exist') else: try: tanwcs = tim.wcs.wcs assert(tanwcs.shape == tilemask.shape) Yo,Xo,Yi,Xi,_ = resample_with_wcs(get_masks, tanwcs, intType=np.int16) # Only deal with mask pixels that are set. I, = np.nonzero(tilemask[Yi,Xi] > 0) # Trim to unique area for this tile rr,dd = get_masks.pixelxy2radec(Xo[I]+1, Yo[I]+1) good = radec_in_unique_area(rr, dd, tile.ra1, tile.ra2, tile.dec1, tile.dec2) I = I[good] maskmap[Yo[I],Xo[I]] = tilemask[Yi[I], Xi[I]] except OverlapError: # Shouldn't happen by this point print('Warning: no overlap between WISE tile', tile.coadd_id, 'and brick') if plots: plt.clf() plt.imshow(tilemask, interpolation='nearest', origin='lower') plt.title('Tile %s: mask' % tile.coadd_id) ps.savefig() plt.clf() plt.imshow(maskmap, interpolation='nearest', origin='lower') plt.title('Tile %s: accumulated maskmap' % tile.coadd_id) ps.savefig() th,tw = tim.shape xx,yy = np.meshgrid(np.arange(tw), np.arange(th)) rr,dd = tim.wcs.wcs.pixelxy2radec(xx+1, yy+1) unique = radec_in_unique_area(rr, dd, tile.ra1, tile.ra2, tile.dec1, tile.dec2) debug('Tile', tile.coadd_id, '- total of', np.sum(unique), 'unique pixels out of', len(unique.flat), 'total pixels') if get_models: # Save the inverr before blanking out non-unique pixels, for making coadds with no gaps! # (actually, slightly more subtly, expand unique area by 1 pixel) from scipy.ndimage.morphology import binary_dilation du = binary_dilation(unique) tim.coadd_inverr = tim.inverr * du tim.inverr[unique == False] = 0. del xx,yy,rr,dd,unique if plots: sig1 = tim.sig1 plt.clf() plt.imshow(tim.getImage() * (tim.inverr > 0), interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=10 * sig1) plt.colorbar() tag = '%s W%i' % (tile.coadd_id, band) plt.title('%s: tim data (unique)' % tag) ps.savefig() if pixelized_psf: from unwise_psf import unwise_psf if (band == 1) or (band == 2): # we only have updated PSFs for W1 and W2 psfimg = unwise_psf.get_unwise_psf(band, tile.coadd_id, modelname='neo6_unwisecat') else: psfimg = unwise_psf.get_unwise_psf(band, tile.coadd_id) if band == 4: # oversample (the unwise_psf models are at native W4 5.5"/pix, # while the unWISE coadds are made at 2.75"/pix. ph,pw = psfimg.shape subpsf = np.zeros((ph*2-1, pw*2-1), np.float32) from astrometry.util.util import lanczos3_interpolate xx,yy = np.meshgrid(np.arange(0., pw-0.51, 0.5, dtype=np.float32), np.arange(0., ph-0.51, 0.5, dtype=np.float32)) xx = xx.ravel() yy = yy.ravel() ix = xx.astype(np.int32) iy = yy.astype(np.int32) dx = (xx - ix).astype(np.float32) dy = (yy - iy).astype(np.float32) psfimg = psfimg.astype(np.float32) rtn = lanczos3_interpolate(ix, iy, dx, dy, [subpsf.flat], [psfimg]) if plots: plt.clf() plt.imshow(psfimg, interpolation='nearest', origin='lower') plt.title('Original PSF model') ps.savefig() plt.clf() plt.imshow(subpsf, interpolation='nearest', origin='lower') plt.title('Subsampled PSF model') ps.savefig() psfimg = subpsf del xx, yy, ix, iy, dx, dy from tractor.psf import PixelizedPSF psfimg /= psfimg.sum() fluxrescales = {1: 1.04, 2: 1.005, 3: 1.0, 4: 1.0} psfimg *= fluxrescales[band] tim.psf = PixelizedPSF(psfimg) if psf_broadening is not None and not pixelized_psf: # psf_broadening is a factor by which the PSF FWHMs # should be scaled; the PSF is a little wider # post-reactivation. psf = tim.getPsf() from tractor import GaussianMixturePSF if isinstance(psf, GaussianMixturePSF): debug('Broadening PSF: from', psf) p0 = psf.getParams() pnames = psf.getParamNames() p1 = [p * psf_broadening**2 if 'var' in name else p for (p, name) in zip(p0, pnames)] psf.setParams(p1) debug('Broadened PSF:', psf) else: print('WARNING: cannot apply psf_broadening to WISE PSF of type', type(psf)) wcs = tim.wcs.wcs _,fx,fy = wcs.radec2pixelxy(ra, dec) x = np.round(fx - 1.).astype(int) y = np.round(fy - 1.).astype(int) good = (x >= 0) * (x < tw) * (y >= 0) * (y < th) # Which sources are in this brick's unique area? usrc = radec_in_unique_area(ra, dec, tile.ra1, tile.ra2, tile.dec1, tile.dec2) I, = np.nonzero(good * usrc) nexp[I] = tim.nuims[y[I], x[I]] if hasattr(tim, 'mjdmin') and hasattr(tim, 'mjdmax'): mjd[I] = (tim.mjdmin + tim.mjdmax) / 2. phot.wise_coadd_id[I] = tile.coadd_id phot.wise_x[I] = fx[I] - 1. phot.wise_y[I] = fy[I] - 1. central_flux[I] = tim.getImage()[y[I], x[I]] del x,y,good,usrc psf = tim.getPsf() h,w = tim.shape patch = psf.getPointSourcePatch(h//2, w//2).patch psfnorm = np.sqrt(np.sum(patch**2)) if np.isfinite(tim.sig1): phot.get('psfdepth_%s' % wband)[I] = 1. / (tim.sig1 / psfnorm)**2 tim.tile = tile tims.append(tim) if plots: plt.clf() mn,mx = 0.1, 20000 plt.hist(np.log10(np.clip(central_flux, mn, mx)), bins=100, range=(np.log10(mn), np.log10(mx))) logt = np.arange(0, 5) plt.xticks(logt, ['%i' % i for i in 10.**logt]) plt.title('Central fluxes (W%i)' % band) plt.axvline(np.log10(20000), color='k') plt.axvline(np.log10(1000), color='k') ps.savefig() #- central pixel <= 1000: 19x19 pix box size #- central pixel in 1000 - 20000: 59x59 box size #- central pixel > 20000 or saturated: 149x149 box size #- object near "bright star": 299x299 box size nbig = nmedium = nsmall = 0 for src,cflux in zip(cat, central_flux): if cflux > 20000: R = 100 nbig += 1 elif cflux > 1000: R = 30 nmedium += 1 else: R = 15 nsmall += 1 if isinstance(src, PointSource): src.fixedRadius = R else: ### FIXME -- sizes for galaxies..... can we set PSF size separately? galrad = 0 # RexGalaxy is a subclass of ExpGalaxy if isinstance(src, (ExpGalaxy, DevGalaxy, SersicGalaxy)): galrad = src.shape.re pixscale = 2.75 src.halfsize = int(np.hypot(R, galrad * 5 / pixscale)) debug('Set WISE source sizes:', nbig, 'big', nmedium, 'medium', nsmall, 'small') tractor = Tractor(tims, cat) if use_ceres: from tractor.ceres_optimizer import CeresOptimizer tractor.optimizer = CeresOptimizer(BW=ceres_block, BH=ceres_block) tractor.freezeParamsRecursive('*') tractor.thawPathsTo(wanyband) t0 = Time() R = tractor.optimize_forced_photometry( fitstats=True, variance=True, shared_params=False, wantims=wantims) info('unWISE forced photometry took', Time() - t0) if use_ceres: term = R.ceres_status['termination'] # Running out of memory can cause failure to converge and term # status = 2. Fail completely in this case. if term != 0: info('Ceres termination status:', term) raise RuntimeError('Ceres terminated with status %i' % term) if wantims: ims1 = R.ims1 # can happen if empty source list (we still want to generate coadds) if ims1 is None: ims1 = R.ims0 flux_invvars = R.IV if R.fitstats is not None: for k in fskeys: x = getattr(R.fitstats, k) fitstats[k] = np.array(x).astype(np.float32) if save_fits: for i,tim in enumerate(tims): tile = tim.tile (dat, mod, _, chi, _) = ims1[i] wcshdr = fitsio.FITSHDR() tim.wcs.wcs.add_to_header(wcshdr) tag = 'fit-%s-w%i' % (tile.coadd_id, band) fitsio.write('%s-data.fits' % tag, dat, clobber=True, header=wcshdr) fitsio.write('%s-mod.fits' % tag, mod, clobber=True, header=wcshdr) fitsio.write('%s-chi.fits' % tag, chi, clobber=True, header=wcshdr) if plots: # Create models for just the brightest sources bright_cat = [src for src in cat if src.getBrightness().getBand(wanyband) > 1000] debug('Bright soures:', len(bright_cat)) btr = Tractor(tims, bright_cat) for tim in tims: mod = btr.getModelImage(tim) tile = tim.tile tag = '%s W%i' % (tile.coadd_id, band) sig1 = tim.sig1 plt.clf() plt.imshow(mod, interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=25 * sig1) plt.colorbar() plt.title('%s: bright-star models' % tag) ps.savefig() if get_models: for i,tim in enumerate(tims): tile = tim.tile (dat, mod, _, _, _) = ims1[i] models.append((tile.coadd_id, band, tim.wcs.wcs, dat, mod, tim.coadd_inverr)) if plots: for i,tim in enumerate(tims): tile = tim.tile tag = '%s W%i' % (tile.coadd_id, band) (dat, mod, _, chi, _) = ims1[i] sig1 = tim.sig1 plt.clf() plt.imshow(dat, interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=25 * sig1) plt.colorbar() plt.title('%s: data' % tag) ps.savefig() plt.clf() plt.imshow(mod, interpolation='nearest', origin='lower', cmap='gray', vmin=-3 * sig1, vmax=25 * sig1) plt.colorbar() plt.title('%s: model' % tag) ps.savefig() plt.clf() plt.imshow(chi, interpolation='nearest', origin='lower', cmap='gray', vmin=-5, vmax=+5) plt.colorbar() plt.title('%s: chi' % tag) ps.savefig() nm = np.array([src.getBrightness().getBand(wanyband) for src in cat]) nm_ivar = flux_invvars # Sources out of bounds, eg, never change from their initial # fluxes. Zero them out instead. nm[nm_ivar == 0] = 0. phot.set('flux_%s' % wband, nm.astype(np.float32)) phot.set('flux_ivar_%s' % wband, nm_ivar.astype(np.float32)) for k in fskeys: phot.set(k + '_' + wband, fitstats.get(k, np.zeros(len(phot), np.float32))) phot.set('nobs_%s' % wband, nexp) phot.set('mjd_%s' % wband, mjd) rtn = wphotduck() rtn.phot = phot rtn.models = None rtn.maskmap = None if get_models: rtn.models = models if get_masks: rtn.maskmap = maskmap return rtn class wphotduck(object): pass def radec_in_unique_area(rr, dd, ra1, ra2, dec1, dec2): unique = (dd >= dec1) * (dd < dec2) if ra1 < ra2: # normal RA unique *= (rr >= ra1) * (rr < ra2) else: # RA wrap-around unique[rr > 180] *= (rr[rr > 180] >= ra1) unique[rr < 180] *= (rr[rr < 180] < ra2) return unique def unwise_phot(X): (key, (wcat, tiles, band, roiradec, wise_ceres, pixelized_psf, get_mods, get_masks, ps, move_crpix, modelsky_dir)) = X kwargs = dict(roiradecbox=roiradec, band=band, pixelized_psf=pixelized_psf, get_masks=get_masks, ps=ps, move_crpix=move_crpix, modelsky_dir=modelsky_dir) if get_mods: kwargs.update(get_models=get_mods) if wise_ceres and len(wcat) == 0: wise_ceres = False # DEBUG #kwargs.update(save_fits=True) W = None try: W = unwise_forcedphot(wcat, tiles, use_ceres=wise_ceres, **kwargs) except: import traceback print('unwise_forcedphot failed:') traceback.print_exc() if wise_ceres: print('Trying without Ceres...') try: W = unwise_forcedphot(wcat, tiles, use_ceres=False, **kwargs) except: print('unwise_forcedphot failed (2):') traceback.print_exc() return key,W def collapse_unwise_bitmask(bitmask, band): assert((band == 1) or (band == 2)) from collections import OrderedDict bits_w1 = OrderedDict([('core_wings', 2**0 + 2**1), ('psf_spike', 2**27), ('ghost', 2**25 + 2**26), ('first_latent', 2**13 + 2**14), ('second_latent', 2**17 + 2**18), ('circular_halo', 2**23), ('saturation', 2**4), ('geom_spike', 2**29)]) bits_w2 = OrderedDict([('core_wings', 2**2 + 2**3), ('psf_spike', 2**28), ('ghost', 2**11 + 2**12), ('first_latent', 2**15 + 2**16), ('second_latent', 2**19 + 2**20), ('circular_halo', 2**24), ('saturation', 2**5), ('geom_spike', 2**30)]) bits = (bits_w1 if (band == 1) else bits_w2) # hack to handle both scalar and array inputs result = 0*bitmask for i, feat in enumerate(bits.keys()): result += ((2**i)*(np.bitwise_and(bitmask, bits[feat]) != 0)).astype(np.uint8) return result.astype('uint8') ### # This is taken directly from tractor/wise.py, replacing only the filename. ### def unwise_tiles_touching_wcs(wcs, polygons=True): from astrometry.util.miscutils import polygons_intersect from astrometry.util.starutil_numpy import degrees_between from pkg_resources import resource_filename atlasfn = resource_filename('legacypipe', 'data/wise-tiles.fits') T = fits_table(atlasfn) trad = wcs.radius() wrad = np.sqrt(2.) / 2. * 2048 * 2.75 / 3600. rad = trad + wrad r, d = wcs.radec_center() I, = np.nonzero(np.abs(T.dec - d) < rad) I = I[degrees_between(T.ra[I], T.dec[I], r, d) < rad] if not polygons: return T[I] # now check actual polygon intersection tw, th = wcs.imagew, wcs.imageh targetpoly = [(0.5, 0.5), (tw + 0.5, 0.5), (tw + 0.5, th + 0.5), (0.5, th + 0.5)] cd = wcs.get_cd() tdet = cd[0] * cd[3] - cd[1] * cd[2] if tdet > 0: targetpoly = list(reversed(targetpoly)) targetpoly = np.array(targetpoly) keep = [] for i in I: wwcs = unwise_tile_wcs(T.ra[i], T.dec[i]) cd = wwcs.get_cd() wdet = cd[0] * cd[3] - cd[1] * cd[2] H, W = wwcs.shape poly = [] for x, y in [(0.5, 0.5), (W + 0.5, 0.5), (W + 0.5, H + 0.5), (0.5, H + 0.5)]: rr,dd = wwcs.pixelxy2radec(x, y) _,xx,yy = wcs.radec2pixelxy(rr, dd) poly.append((xx, yy)) if wdet > 0: poly = list(reversed(poly)) poly = np.array(poly) if polygons_intersect(targetpoly, poly): keep.append(i) I = np.array(keep) return T[I] ### Also direct from tractor/wise.py def unwise_tile_wcs(ra, dec, W=2048, H=2048, pixscale=2.75): from astrometry.util.util import Tan cowcs = Tan(ra, dec, (W + 1) / 2., (H + 1) / 2., -pixscale / 3600., 0., 0., pixscale / 3600., W, H) return cowcs
true
true