max_stars_repo_path
stringlengths
3
269
max_stars_repo_name
stringlengths
4
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.05M
score
float64
0.23
5.13
int_score
int64
0
5
seagrass/hooks/__init__.py
kernelmethod/Seagrass
0
4700
<filename>seagrass/hooks/__init__.py # flake8: noqa: F401 from .context_manager_hook import ContextManagerHook from .counter_hook import CounterHook from .file_open_hook import FileOpenHook from .logging_hook import LoggingHook from .profiler_hook import ProfilerHook from .runtime_audit_hook import RuntimeAuditHook from .stack_trace_hook import StackTraceHook from .timer_hook import TimerHook from .tracing_hook import TracingHook __all__ = [ "CounterHook", "FileOpenHook", "LoggingHook", "ProfilerHook", "StackTraceHook", "RuntimeAuditHook", "TimerHook", "TracingHook", ]
1.203125
1
tests/test_internal.py
aschleg/hypy
40
4701
<reponame>aschleg/hypy<filename>tests/test_internal.py import pytest import numpy as np import pandas as pd from hypothetical._lib import _build_des_mat def test_array(): d = np.array([[1., 1.11, 2.569, 3.58, 0.76], [1., 1.19, 2.928, 3.75, 0.821], [1., 1.09, 2.865, 3.93, 0.928], [1., 1.25, 3.844, 3.94, 1.009], [1., 1.11, 3.027, 3.6, 0.766], [1., 1.08, 2.336, 3.51, 0.726], [1., 1.11, 3.211, 3.98, 1.209], [1., 1.16, 3.037, 3.62, 0.75], [2., 1.05, 2.074, 4.09, 1.036], [2., 1.17, 2.885, 4.06, 1.094], [2., 1.11, 3.378, 4.87, 1.635], [2., 1.25, 3.906, 4.98, 1.517], [2., 1.17, 2.782, 4.38, 1.197], [2., 1.15, 3.018, 4.65, 1.244], [2., 1.17, 3.383, 4.69, 1.495], [2., 1.19, 3.447, 4.4, 1.026], [3., 1.07, 2.505, 3.76, 0.912], [3., 0.99, 2.315, 4.44, 1.398], [3., 1.06, 2.667, 4.38, 1.197], [3., 1.02, 2.39, 4.67, 1.613], [3., 1.15, 3.021, 4.48, 1.476], [3., 1.2, 3.085, 4.78, 1.571], [3., 1.2, 3.308, 4.57, 1.506], [3., 1.17, 3.231, 4.56, 1.458], [4., 1.22, 2.838, 3.89, 0.944], [4., 1.03, 2.351, 4.05, 1.241], [4., 1.14, 3.001, 4.05, 1.023], [4., 1.01, 2.439, 3.92, 1.067], [4., 0.99, 2.199, 3.27, 0.693], [4., 1.11, 3.318, 3.95, 1.085], [4., 1.2, 3.601, 4.27, 1.242], [4., 1.08, 3.291, 3.85, 1.017], [5., 0.91, 1.532, 4.04, 1.084], [5., 1.15, 2.552, 4.16, 1.151], [5., 1.14, 3.083, 4.79, 1.381], [5., 1.05, 2.33, 4.42, 1.242], [5., 0.99, 2.079, 3.47, 0.673], [5., 1.22, 3.366, 4.41, 1.137], [5., 1.05, 2.416, 4.64, 1.455], [5., 1.13, 3.1, 4.57, 1.325], [6., 1.11, 2.813, 3.76, 0.8], [6., 0.75, 0.84, 3.14, 0.606], [6., 1.05, 2.199, 3.75, 0.79], [6., 1.02, 2.132, 3.99, 0.853], [6., 1.05, 1.949, 3.34, 0.61], [6., 1.07, 2.251, 3.21, 0.562], [6., 1.13, 3.064, 3.63, 0.707], [6., 1.11, 2.469, 3.95, 0.952]]) return d def test_build_design_matrix(): dat = test_array() dat_df = pd.DataFrame(dat) des_mat = _build_des_mat(dat[:, 1], dat[:, 2], dat[:, 3], dat[:, 4], group=dat[:, 0]) des_mat_df = _build_des_mat(dat_df[1], dat_df[2], dat_df[3], dat_df[4], group=dat_df[0]) des_mat_no_group = _build_des_mat(dat[:, 1], dat[:, 2], dat[:, 3], dat[:, 4]) des_mat_group_df = _build_des_mat(dat[:, 1], dat[:, 2], dat[:, 3], dat[:, 4], group=pd.DataFrame(dat[:, 0])) des_mat_group_df = _build_des_mat(dat[:, 1], dat[:, 2], dat[:, 3], dat[:, 4], group=pd.DataFrame(dat[:, 0])) assert isinstance(des_mat, np.ndarray) assert des_mat.shape == dat.shape assert isinstance(des_mat_df, np.ndarray) assert des_mat_df.shape == dat.shape assert isinstance(des_mat_no_group, np.ndarray) assert des_mat_no_group.shape[1] == 2 assert isinstance(des_mat, np.ndarray) assert des_mat_group_df.shape == dat.shape def test_build_matrix(): arr1 = [4, 4, 5, 5, 3, 2, 5] arr2 = [2, 3, 3, 3, 3, 3, 3]
2.15625
2
download.py
JamesWang007/Open3D-PointNet
120
4702
<reponame>JamesWang007/Open3D-PointNet<gh_stars>100-1000 #!/usr/bin/env python3 # Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de # Barcelona (UAB). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """Download big files from Google Drive.""" import shutil import sys import requests import os import time import urllib.request import zipfile def reporthook(count, block_size, total_size): global start_time if count == 0: start_time = time.time() return duration = time.time() - start_time progress_size = int(count * block_size) speed = int(progress_size / (1024 * duration)) percent = int(count * block_size * 100 / total_size) if percent % 5 == 0: sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" % (percent, progress_size / (1024 * 1024), speed, duration)) sys.stdout.flush() def sizeof_fmt(num, suffix='B'): # https://stackoverflow.com/a/1094933/5308925 for unit in ['','K','M','G','T','P','E','Z']: if abs(num) < 1000.0: return "%3.2f%s%s" % (num, unit, suffix) num /= 1000.0 return "%.2f%s%s" % (num, 'Yi', suffix) def print_status(destination, progress): message = "Downloading %s... %s" % (destination, sizeof_fmt(progress)) empty_space = shutil.get_terminal_size((80, 20)).columns - len(message) sys.stdout.write('\r' + message + empty_space * ' ') sys.stdout.flush() def download_file_from_google_drive(id, destination): # https://stackoverflow.com/a/39225039/5308925 def save_response_content(response, destination): chunk_size = 32768 written_size = 0 with open(destination, "wb") as f: for chunk in response.iter_content(chunk_size): if chunk: # filter out keep-alive new chunks f.write(chunk) written_size += chunk_size print_status(destination, written_size) print('Done.') def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None url = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(url, params={'id': id}, stream=True) token = get_confirm_token(response) if token: params = {'id': id, 'confirm': token} response = session.get(url, params=params, stream=True) save_response_content(response, destination) def download_contents(): # download model model_path = './cls_model.pth' if os.path.isfile(model_path): print('Model file already downloaded in', model_path) else: download_file_from_google_drive('1WWf5B5fmik5_P1dwxltJ-atRkYeCcCC5', './cls_model.pth') # download dataset dataset_path = './shapenetcore_partanno_segmentation_benchmark_v0.zip' if os.path.isfile(dataset_path): print('Dataset file already downloaded in', dataset_path) else: dataset_url = 'https://shapenet.cs.stanford.edu/ericyi/shapenetcore_partanno_segmentation_benchmark_v0.zip' urllib.request.urlretrieve(dataset_url, os.path.basename(dataset_url), reporthook) # unzip dataset zip_ref = zipfile.ZipFile(os.path.basename(dataset_url), 'r') zip_ref.extractall('.') zip_ref.close() print('Now unzipping...Wait for 2 minutes ish...!') return 0 if __name__ == '__main__': download_contents()
2.234375
2
ls12/demo5.py
cklwblove/python-100-days-source-code
0
4703
<gh_stars>0 # -*- coding: utf-8 -*- """ 将耗时间的任务放到线程中以获得更好的用户体验。 """ import time import tkinter import tkinter.messagebox def download(): # 模拟下载任务需要花费10秒时间 time.sleep(10) tkinter.messagebox.showinfo('提示', '下载完成') def show_about(): tkinter.messagebox.showinfo('关于', '作者:罗浩') def main(): top = tkinter.Tk() top.title('单线程') top.geometry('200x150') top.wm_attributes('-topmost', True) panel = tkinter.Frame(top) button1 = tkinter.Button(panel, text='下载', command=download) button1.pack(side='left') button2 = tkinter.Button(panel, text='关于', command=show_about) button2.pack(side='right') panel.pack(side='bottom') tkinter.mainloop() if __name__ == '__main__': main()
3.4375
3
hangupsbot/sinks/gitlab/simplepush.py
mygreentour/hangoutsbot
0
4704
""" GitLab webhook receiver - see http://doc.gitlab.com/ee/web_hooks/web_hooks.html """ import asyncio import json import logging from sinks.base_bot_request_handler import AsyncRequestHandler logger = logging.getLogger(__name__) try: import dateutil.parser except ImportError: logger.error("missing module python_dateutil: pip3 install python_dateutil") raise class webhookReceiver(AsyncRequestHandler): """Receive REST API posts from GitLab""" _bot = None @asyncio.coroutine def process_request(self, path, dummy_query_string, content): """Process a received POST to a given converstation""" path = path.split("/") conv_or_user_id = path[1] if conv_or_user_id is None: logger.error("conversation or user id must be provided as part of path") return try: payload = json.loads(content) except json.JSONDecodeError as err: logger.exception("invalid payload @%d:%d: %s", err.lineno, err.colno, err) logger.error("GitLab message: %s", json.dumps(payload)) refs = payload.get("ref", '').split("/") user = payload.get("user_name") if not user: user = payload["user"]["name"] message = ["GitLab update for [{}]({}) by __{}__".format( payload["project"]["name"], payload["project"]["web_url"], user)] if payload["object_kind"] == "push": message.append("Pushed {} commit(s) on {} branch:".format( payload["total_commits_count"], "/".join(refs[2:]))) for commit in payload["commits"]: message.append("{} -- {} at [{:%c}]({})".format( commit["message"], commit["author"]["name"], dateutil.parser.parse(commit["timestamp"]), commit["url"])) elif payload["object_kind"] == "tag_push": message.append("Pushed tag {}]".format("/".join(refs[2:]))) elif payload["object_kind"] == "issue": issue = payload["object_attributes"] message.append("Update {} issue {} at {:%c}\n[{}]({})".format( issue["state"], issue["id"], dateutil.parser.parse(issue["updated_at"]), issue["title"], issue["url"])) elif payload["object_kind"] == "note": note = payload["object_attributes"] message.append("{} note on {}: [{}]({})".format( note["notable_type"], note["id"], note["note"], note["url"])) elif payload["object_kind"] == "merge_request": request = payload["object_attributes"] message.append("Merge request {}: from [{}:{}]({}) to [{}:{}]({})".format( request["id"], request["source"]["name"], request["source_branch"], request["source"]["web_url"], request["target"]["name"], request["target_branch"], request["target"]["web_url"])) else: message.append("{}: unknown gitlab webhook object kind".format(payload["object_kind"])) logger.warning("%s: unknown gitlab webhook object kind", payload["object_kind"]) if message: yield from self.send_data(conv_or_user_id, "\n".join(message))
2.453125
2
evsim/assessor.py
cbchoi/nppsim
3
4705
<reponame>cbchoi/nppsim<gh_stars>1-10 from evsim.system_simulator import SystemSimulator from evsim.behavior_model_executor import BehaviorModelExecutor from evsim.system_message import SysMessage from evsim.definition import * import os import subprocess as sp class Assessor(BehaviorModelExecutor): def __init__(self, instance_time, destruct_time, name, engine_name): BehaviorModelExecutor.__init__(self, instance_time, destruct_time, name, engine_name) # Open CSV self.init_state("IDLE") self.insert_state("IDLE", Infinite) self.insert_state("MOVE", 1) self.insert_input_port("assess") self.insert_output_port("done") def ext_trans(self,port, msg): data = msg.retrieve() #print("Assessor") #print(str(datetime.datetime.now()) + " " + str(data[0])) #temp = "[%f] %s" % (SystemSimulator().get_engine(self.engine_name).get_global_time(), str(data[0])) #print(temp) def output(self): #temp = "[%f] %s" % (SystemSimulator().get_engine(self.engine_name).get_global_time(), "Human Receiver Object: Move") #print(temp) return None def int_trans(self): self._cur_state = "MOVE"
2.328125
2
tei_entity_enricher/interface/postprocessing/gnd_connector.py
NEISSproject/TEIEntityEnricher
0
4706
import os from typing import Union, List from tei_entity_enricher.interface.postprocessing.io import FileReader, FileWriter from tei_entity_enricher.util.helper import local_save_path, makedir_if_necessary from tei_entity_enricher.util.exceptions import FileNotFound class GndConnector: def __init__( self, gnd_id: Union[str, List[str], None] = None, apiindex: int = 0, check_connectivity: bool = True, show_printmessages: bool = True, ) -> None: """establishes connection to api, from which norm data for entities of Deutsche Nationalbibliothek´s database is retrieved, loaded data can be passed to an instance of Cache class for further processing or FileWriter class to save it gnd_id: gnd id number(s) apiindex: index of selected api in list defined in self.apilist check_connectivity: execute connectivity check in __init__() or not (see connectivitycheck_loop()) show_printmessages: show class internal printmessages on runtime or not apilist_filepath: path to apilist config file apilist: list of dicts as configuration data set, delivers a mapping to be able to normalize data from different apis, defines api`s url and aliases for filtering purposes (see get_gnd_data()) connection_established: data from an api has already been received or not remaining_apis_to_check: list of apiindex values, which have not been checked yet in connectivitycheck_loop()""" print("initializing GndConnector..") if show_printmessages else None self.show_printmessages: bool = show_printmessages self.gnd_id: Union[str, List[str], None] = gnd_id self.apiindex: int = apiindex self.apilist_filepath: str = os.path.join(local_save_path, "config", "postprocessing", "gnd_apilist.json") try: self.apilist: Union[dict, None] = FileReader( filepath=self.apilist_filepath, origin="local", internal_call=True, show_printmessages=False ).loadfile_json() except FileNotFound: print( "GndConnector: could not find gnd_apilist.json in config dir. creating file with default settings..." ) if self.show_printmessages else None self.apilist: List[dict] = [ { "name": "culturegraph", "baseUrl": "https://hub.culturegraph.org/entityfacts/{}", "baseAliases": { "type": [ "@type", "str", "categorial", { "person": "person", "organisation": "organisation", "place": "place", }, ], "name": ["preferredName", "str", "nominal"], "furtherNames": ["variantName", ["str"], "nominal"], "sameAs": ["sameAs", [{"@id": "str"}], "nominal"], "pseudonyms": [ "pseudonym", [{"preferredName": "str"}], "nominal", ], }, "personAliases": {}, "placeAliases": {}, "organizationAliases": {}, }, { "name": "lobid", "baseUrl": "http://lobid.org/gnd/{}", "baseAliases": { "type": [ "type", ["str"], "categorial", { "person": "Person", "organisation": "CorporateBody", "place": "PlaceOrGeographicName", }, ], "name": ["preferredName", "str", "nominal"], "furtherNames": ["variantName", ["str"], "nominal"], "sameAs": ["sameAs", [{"id": "str"}], "nominal"], "pseudonyms": [ "variantNameEntityForThePerson", [{"forename": ["str"], "surname": ["str"]}], "nominal", ], }, "personAliases": {}, "placeAliases": {}, "organizationAliases": {}, }, ] self.apiindex: int = 0 try: makedir_if_necessary(os.path.dirname(self.apilist_filepath)) FileWriter(data=self.apilist, filepath=self.apilist_filepath).writefile_json() except: print( f"GndConnector __init__(): could not create default gnd_apilist.json in config folder." ) if self.show_printmessages == True else None self.check_connectivity: bool = check_connectivity self.connection_established: bool = False self.remaining_apis_to_check: list = [i for i, _ in enumerate(self.apilist)] if self.check_connectivity == True: self.connectivitycheck_loop() else: print( "GndConnector: initialization has been done without connectivity check." ) if self.show_printmessages else None def connectivitycheck_single(self, index_to_test: int, gnd_id_to_test: str = "118540238") -> bool: """auxiliary method of connectivitycheck_loop(), checks a single api`s (from self.apilist) response status code and checks if response data type is json, preset gnd_id_to_test value refers to Goethe""" try: result: dict = FileReader( filepath=self.apilist[index_to_test]["baseUrl"].format(gnd_id_to_test), origin="web", internal_call=True, show_printmessages=self.show_printmessages, ).loadfile_json() except: return False if type(result) == dict: return True return False def connectivitycheck_loop(self) -> int: """recursive connectivity check, checking every single api in self.apilist (ascending) and setting self.apiindex to the value of those api, which is first to pass the check successfully. returns 0 or -1 for unittest purposes""" if self.check_connectivity == False: self.check_connectivity == True if len(self.remaining_apis_to_check) > 0: if self.connectivitycheck_single(self.remaining_apis_to_check[0]) == True: print( f"GndConnector: connectivity check passed, connection to {self.apilist[self.remaining_apis_to_check[0]]['name']} api established." ) if self.show_printmessages else None self.apiindex = self.remaining_apis_to_check[0] self.remaining_apis_to_check = [i for i, _ in enumerate(self.apilist)] self.connection_established = True return 0 else: print( f"GndConnector connectivity check: {self.apilist[self.remaining_apis_to_check[0]]['name']} api is currently not responding as expected. checking for alternatives..." ) if self.show_printmessages else None self.remaining_apis_to_check.remove(self.remaining_apis_to_check[0]) self.connectivitycheck_loop() else: print( "GndConnector connectivity check error: none of the listed apis is responding as expected." ) if self.show_printmessages else None return -1 def print_complete_url(self, index: int = 0) -> int: """print baseUrl string of the currently selected api defined in self.apilist, formatted with a gnd id number of self.gnd_id (list or str) selected by index value. returns 0 or -1 for unittest purposes""" if self.apiindex not in [i for i, _ in enumerate(self.apilist)]: print( "GndConnector print_complete_url() error: apiindex is not defined correctly. using default api..." ) if self.show_printmessages else None self.apiindex = 0 if self.gnd_id is not None: if type(self.gnd_id) == str: print( f"GndConnector complete URL: {self.apilist[self.apiindex]['baseUrl'].format(self.gnd_id)}" ) if self.show_printmessages else None elif type(self.gnd_id) == list: print( f"GndConnector complete URL of gnd id number {index + 1} in passed gnd id list: {self.apilist[self.apiindex]['baseUrl'].format(self.gnd_id[index])}" ) if self.show_printmessages else None return 0 else: print( "GndConnector print_complete_url() internal error: no gnd id number has been passed to connector object yet." ) if self.show_printmessages else None return -1 def return_complete_url(self, index: int = 0) -> Union[str, None]: """return baseUrl string of the currently selected api defined in self.apilist, formatted with a gnd id number of self.gnd_id (list or str) selected by index value""" if self.apiindex not in [i for i, _ in enumerate(self.apilist)]: print( "GndConnector return_complete_url() error: apiindex is not defined correctly. using default api..." ) if self.show_printmessages else None self.apiindex = 0 if self.gnd_id is not None: if type(self.gnd_id) == str: return self.apilist[self.apiindex]["baseUrl"].format(self.gnd_id) elif type(self.gnd_id) == list: return self.apilist[self.apiindex]["baseUrl"].format(self.gnd_id[index]) else: print( "GndConnector return_complete_url() internal error: no gnd id number has been passed to connector object yet." ) if self.show_printmessages else None return None def get_gnd_data(self, data_selection: Union[str, List[str], None] = None) -> Union[dict, None]: """method to receive data from api with the possibility to filter results, a dict is created, having gnd id numbers as keys and filtered or unfiltered response json data as values data_selection: if delivered, a normalized output is generated by renaming keys and re-sorting data from different keys from the raw data into new keys (purpose: json data delivered by different apis comes in different key-value-structures; normalization of this data is achieved with the help of key-value mapping information stored in self.apilist) can be "base" (all baseAliases data is provided: "type", "name", "furtherNames", "sameAs", "pseudonyms") can be a list of one or more baseAliases (i.e. ["type", "name"]) (not yet implemented: can be a "person", "place", "organization" or a custom string refering to a user-defined set of keys, for which the mapping is provided in self.apilist) """ if self.check_connectivity == False: print( f"GndConnector note: connections to apis have not been checked yet. to do so manually execute connectivitycheck_loop() method of the current connector object. continuing attempt to receive gnd data from {self.apilist[self.apiindex]['name']} api..." ) if self.show_printmessages else None elif self.connection_established == False: print( "GndConnector connectivity error: after connectivity check no connection could has been established to any of the available apis. gnd data queries can not be executed at the moment." ) if self.show_printmessages else None return None result = {} if type(self.gnd_id) == str: _temp_data = {} try: filereader = FileReader( filepath=self.return_complete_url(), origin="web", internal_call=True, show_printmessages=False ) _temp_data = filereader.loadfile_json() except: print( "GndConnector connectivity error in get_gnd_data() method: could not load resource from api as expected." ) if self.show_printmessages else None return None self.connection_established = True if _temp_data != None and _temp_data != False: result[self.gnd_id] = _temp_data print( f"GndConnector get_gnd_data() status: data for gnd id {self.gnd_id} received." ) if self.show_printmessages else None else: print( f"GndConnector get_gnd_data() status: for gnd id {self.gnd_id} no data could be delivered by api" ) if self.show_printmessages else None return None elif type(self.gnd_id) == list: for index, gnd in enumerate(self.gnd_id): _temp_data = {} try: filereader = FileReader( filepath=self.return_complete_url(index), origin="web", internal_call=True, show_printmessages=True, ) _temp_data = filereader.loadfile_json() except: print( f"GndConnector get_gnd_data() status: for gnd id {index + 1} ({gnd}) of {len(self.gnd_id)} no data could be delivered by api" ) if self.show_printmessages else None result[gnd] = _temp_data print( f"GndConnector get_gnd_data() status: gnd id {index + 1} ({gnd}) of {len(self.gnd_id)} processed" ) if self.show_printmessages else None self.connection_established = True # filtering: build new dict with selected values, which should be returned (base mode = all base aliases from apilist definition. list mode = select specific aliases from base set) # defining sub method for filtering def filter_received_data(gnd_id: str, mode: Union[str, List[str]]) -> dict: """sub method, which extracts the key-value pairs from the raw data received from api for one gnd id number and renames the keys and/or values. alias definitions in self.apilist are used for this filtering process: the keys of 'baseAliases' dict define the new key names, their value list denotates (in order of the list) 1. the original key name, 2. the original value type (python-wise: i.e. 'str' or '[str]'), 3. the original value type (logic-wise: 'categorial' or 'nominal'), 4. a categorization dict, if the original value type logic-wise is 'categorial': it delivers mapping information to assign a category (defined keys of this mapping dict) based on specific values (defined in the values of this mapping dict) found in raw data, example 1: using culturegraph api the value of the base category 'type' is assigned to 'person', if the raw data json object has a key '@type' with the value 'person' of type str, example 2: using lobid api the value of the base category 'type' is assigned to 'person', if the raw data json object has a key 'type' with a list as a value, which has itself a value 'Person' of type str in it, mode parameter accepts str 'base' (all base aliases will be extracted) or a list of str (specific aliases will be extracted)""" # todo: handle additional alias definition sets in gnd_apilist.json by user # category_sets = {'base': [list(self.apilist[self.apiindex]["baseAliases"].keys()), 'baseAliases'], # 'custom': [list(self.apilist[self.apiindex]["custom"].keys()), 'custom'] # } # selected_categories_list = category_sets.get(mode)[0] if type(mode) == str else mode # selected_categories_alias = category_sets.get(mode)[1] if type(mode) == str else 'baseAliases' # => allow parsing a list of categories to get_gnd_data() only if they are defined in baseAlias set? base_categories = list(self.apilist[self.apiindex]["baseAliases"].keys()) selected_categories = base_categories if mode == "base" else mode selected_categories_data = {} for category in selected_categories: _temp_data = [] try: _temp_data = result[gnd_id][self.apilist[self.apiindex]["baseAliases"][category][0]] except KeyError: _temp_data = [] print( f"GndConnector get_gnd_data() filtering note: could not find {category} information for {gnd_id} in raw data. continuing processing..." ) if self.show_printmessages else None # handling of categorical data types if ( len(_temp_data) > 0 and self.apilist[self.apiindex]["baseAliases"][category][2] == "categorial" and type(self.apilist[self.apiindex]["baseAliases"][category][3] == dict) ): _temp_category_data_form = self.apilist[self.apiindex]["baseAliases"][category][1] _temp_categorial_values = self.apilist[self.apiindex]["baseAliases"][category][3] # change found categorial string to selfdefined string (i.e. 'Person' to 'person') if type(_temp_category_data_form) == str: for _type in _temp_categorial_values: if _temp_data == _temp_categorial_values[_type]: _temp_data = _type # replace found categorial list with selfdefined string (i.e. ['Person', 'PoliticalLeader'] to 'person') elif type(_temp_category_data_form) == list: for _type in _temp_categorial_values: if _temp_categorial_values[_type] in _temp_data: _temp_data = _type selected_categories_data[category] = _temp_data return selected_categories_data # executing sub method for filtering if data_selection is not None: if type(self.gnd_id) == str: _new_dict = {list(result.keys())[0]: filter_received_data(self.gnd_id, data_selection)} elif type(self.gnd_id) == list: _new_dict = {} for key in result: _new_dict[key] = filter_received_data(key, data_selection) result = _new_dict return result
2.296875
2
neslter/workflow/__init__.py
WHOIGit/nes-lter-ims
3
4707
<filename>neslter/workflow/__init__.py import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) logger.level = logging.DEBUG
1.453125
1
inference/_archive/render_section.py
emitch/SEAMLeSS
4
4708
<filename>inference/_archive/render_section.py from args import get_argparser, parse_args, get_aligner, get_bbox def render(aligner, bbox, z): aligner.total_bbox = bbox aligner.zs = z aligner.render_section_all_mips(z, bbox) if __name__ == '__main__': parser = get_argparser() args = parse_args(parser) a = get_aligner(args) bbox = get_bbox(args) for z in range(args.bbox_start[2], args.bbox_stop[2]): print('Rendering z={0}'.format(z)) render(a, bbox, z)
2.40625
2
venv/lib/python3.9/site-packages/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
qarik-hanrattyjen/apache-airflow-backport-providers-google-2021.3.3
0
4709
<reponame>qarik-hanrattyjen/apache-airflow-backport-providers-google-2021.3.3 # -*- coding: utf-8 -*- # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Accesses the google.spanner.admin.instance.v1 InstanceAdmin API.""" import functools import pkg_resources import warnings from google.oauth2 import service_account import google.api_core.client_options import google.api_core.gapic_v1.client_info import google.api_core.gapic_v1.config import google.api_core.gapic_v1.method import google.api_core.gapic_v1.routing_header import google.api_core.grpc_helpers import google.api_core.operation import google.api_core.operations_v1 import google.api_core.page_iterator import google.api_core.path_template import grpc from google.cloud.spanner_admin_instance_v1.gapic import enums from google.cloud.spanner_admin_instance_v1.gapic import instance_admin_client_config from google.cloud.spanner_admin_instance_v1.gapic.transports import ( instance_admin_grpc_transport, ) from google.cloud.spanner_admin_instance_v1.proto import spanner_instance_admin_pb2 from google.cloud.spanner_admin_instance_v1.proto import spanner_instance_admin_pb2_grpc from google.iam.v1 import iam_policy_pb2 from google.iam.v1 import options_pb2 from google.iam.v1 import policy_pb2 from google.longrunning import operations_pb2 from google.protobuf import empty_pb2 from google.protobuf import field_mask_pb2 _GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-spanner").version class InstanceAdminClient(object): """ Cloud Spanner Instance Admin API The Cloud Spanner Instance Admin API can be used to create, delete, modify and list instances. Instances are dedicated Cloud Spanner serving and storage resources to be used by Cloud Spanner databases. Each instance has a "configuration", which dictates where the serving resources for the Cloud Spanner instance are located (e.g., US-central, Europe). Configurations are created by Google based on resource availability. Cloud Spanner billing is based on the instances that exist and their sizes. After an instance exists, there are no additional per-database or per-operation charges for use of the instance (though there may be additional network bandwidth charges). Instances offer isolation: problems with databases in one instance will not affect other instances. However, within an instance databases can affect each other. For example, if one database in an instance receives a lot of requests and consumes most of the instance resources, fewer resources are available for other databases in that instance, and their performance may suffer. """ SERVICE_ADDRESS = "spanner.googleapis.com:443" """The default address of the service.""" # The name of the interface for this client. This is the key used to # find the method configuration in the client_config dictionary. _INTERFACE_NAME = "google.spanner.admin.instance.v1.InstanceAdmin" @classmethod def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: InstanceAdminClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @classmethod def instance_path(cls, project, instance): """Return a fully-qualified instance string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}", project=project, instance=instance, ) @classmethod def instance_config_path(cls, project, instance_config): """Return a fully-qualified instance_config string.""" return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, instance_config=instance_config, ) @classmethod def project_path(cls, project): """Return a fully-qualified project string.""" return google.api_core.path_template.expand( "projects/{project}", project=project ) def __init__( self, transport=None, channel=None, credentials=None, client_config=None, client_info=None, client_options=None, ): """Constructor. Args: transport (Union[~.InstanceAdminGrpcTransport, Callable[[~.Credentials, type], ~.InstanceAdminGrpcTransport]): A transport instance, responsible for actually making the API calls. The default transport uses the gRPC protocol. This argument may also be a callable which returns a transport instance. Callables will be sent the credentials as the first argument and the default transport class as the second argument. channel (grpc.Channel): DEPRECATED. A ``Channel`` instance through which to make calls. This argument is mutually exclusive with ``credentials``; providing both will raise an exception. credentials (google.auth.credentials.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. This argument is mutually exclusive with providing a transport instance to ``transport``; doing so will raise an exception. client_config (dict): DEPRECATED. A dictionary of call options for each method. If not specified, the default configuration is used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. client_options (Union[dict, google.api_core.client_options.ClientOptions]): Client options used to set user options on the client. API Endpoint should be set through client_options. """ # Raise deprecation warnings for things we want to go away. if client_config is not None: warnings.warn( "The `client_config` argument is deprecated.", PendingDeprecationWarning, stacklevel=2, ) else: client_config = instance_admin_client_config.config if channel: warnings.warn( "The `channel` argument is deprecated; use " "`transport` instead.", PendingDeprecationWarning, stacklevel=2, ) api_endpoint = self.SERVICE_ADDRESS if client_options: if type(client_options) == dict: client_options = google.api_core.client_options.from_dict( client_options ) if client_options.api_endpoint: api_endpoint = client_options.api_endpoint # Instantiate the transport. # The transport is responsible for handling serialization and # deserialization and actually sending data to the service. if transport: if callable(transport): self.transport = transport( credentials=credentials, default_class=instance_admin_grpc_transport.InstanceAdminGrpcTransport, address=api_endpoint, ) else: if credentials: raise ValueError( "Received both a transport instance and " "credentials; these are mutually exclusive." ) self.transport = transport else: self.transport = instance_admin_grpc_transport.InstanceAdminGrpcTransport( address=api_endpoint, channel=channel, credentials=credentials ) if client_info is None: client_info = google.api_core.gapic_v1.client_info.ClientInfo( gapic_version=_GAPIC_LIBRARY_VERSION ) else: client_info.gapic_version = _GAPIC_LIBRARY_VERSION self._client_info = client_info # Parse out the default settings for retry and timeout for each RPC # from the client configuration. # (Ordinarily, these are the defaults specified in the `*_config.py` # file next to this one.) self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( client_config["interfaces"][self._INTERFACE_NAME] ) # Save a dictionary of cached API call functions. # These are the actual callables which invoke the proper # transport methods, wrapped with `wrap_method` to add retry, # timeout, and the like. self._inner_api_calls = {} # Service calls def create_instance( self, parent, instance_id, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_EXISTS``. Immediately upon completion of this request: - The instance is readable via the API, with all requested attributes but no allocated resources. Its state is ``CREATING``. Until completion of the returned operation: - Cancelling the operation renders the instance immediately unreadable via the API. - The instance can be deleted. - All other attempts to modify the instance are rejected. Upon completion of the returned operation: - Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). - Databases can be created in the instance. - The instance's allocated resource levels are readable via the API. - The instance's state becomes ``READY``. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track creation of the instance. The ``metadata`` field type is ``CreateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instance_id`: >>> instance_id = '' >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> response = client.create_instance(parent, instance_id, instance) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the project in which to create the instance. Values are of the form ``projects/<project>``. instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 2 and 64 characters in length. instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if specified must be ``<parent>/instances/<instance_id>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.operation.Operation` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_instance" not in self._inner_api_calls: self._inner_api_calls[ "create_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instance, default_retry=self._method_configs["CreateInstance"].retry, default_timeout=self._method_configs["CreateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.CreateInstanceRequest( parent=parent, instance_id=instance_id, instance=instance ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["create_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.CreateInstanceMetadata, ) def update_instance( self, instance, field_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: - For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: - Cancelling the operation sets its metadata's ``cancel_time``, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a ``CANCELLED`` status. - All other attempts to modify the instance are rejected. - Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: - Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). - All newly-reserved resources are available for serving the instance's tables. - The instance's new resource levels are readable via the API. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track the instance modification. The ``metadata`` field type is ``UpdateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Authorization requires ``spanner.instances.update`` permission on resource ``name``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `field_mask`: >>> field_mask = {} >>> >>> response = client.update_instance(instance, field_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance name. Otherwise, only fields mentioned in ``field_mask`` need be included. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in ``Instance`` should be updated. The field mask must always be specified; this prevents any future fields in ``Instance`` from being erased accidentally by clients that do not know about them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.operation.Operation` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "update_instance" not in self._inner_api_calls: self._inner_api_calls[ "update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_instance, default_retry=self._method_configs["UpdateInstance"].retry, default_timeout=self._method_configs["UpdateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.UpdateInstanceRequest( instance=instance, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.UpdateInstanceMetadata, ) def list_instance_configs( self, parent, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists the supported instance configurations for a given project. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # Iterate over all results >>> for element in client.list_instance_configs(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_instance_configs(parent).pages: ... for element in page: ... # process element ... pass Args: parent (str): Required. The name of the project for which a list of supported instance configurations is requested. Values are of the form ``projects/<project>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.page_iterator.PageIterator` instance. An iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instances. You can also iterate over the pages of the response using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_instance_configs" not in self._inner_api_calls: self._inner_api_calls[ "list_instance_configs" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_instance_configs, default_retry=self._method_configs["ListInstanceConfigs"].retry, default_timeout=self._method_configs["ListInstanceConfigs"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.ListInstanceConfigsRequest( parent=parent, page_size=page_size ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_instance_configs"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="instance_configs", request_token_field="page_token", response_token_field="next_page_token", ) return iterator def get_instance_config( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets information about a particular instance configuration. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> name = client.instance_config_path('[PROJECT]', '[INSTANCE_CONFIG]') >>> >>> response = client.get_instance_config(name) Args: name (str): Required. The name of the requested instance configuration. Values are of the form ``projects/<project>/instanceConfigs/<config>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_instance_config" not in self._inner_api_calls: self._inner_api_calls[ "get_instance_config" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_instance_config, default_retry=self._method_configs["GetInstanceConfig"].retry, default_timeout=self._method_configs["GetInstanceConfig"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.GetInstanceConfigRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_instance_config"]( request, retry=retry, timeout=timeout, metadata=metadata ) def list_instances( self, parent, page_size=None, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists all instances in the given project. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # Iterate over all results >>> for element in client.list_instances(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_instances(parent).pages: ... for element in page: ... # process element ... pass Args: parent (str): Required. The name of the project for which a list of instances is requested. Values are of the form ``projects/<project>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. filter_ (str): An expression for filtering the results of the request. Filter rules are case insensitive. The fields eligible for filtering are: - ``name`` - ``display_name`` - ``labels.key`` where key is the name of a label Some examples of using filters are: - ``name:*`` --> The instance has a name. - ``name:Howl`` --> The instance's name contains the string "howl". - ``name:HOWL`` --> Equivalent to above. - ``NAME:howl`` --> Equivalent to above. - ``labels.env:*`` --> The instance has the label "env". - ``labels.env:dev`` --> The instance has the label "env" and the value of the label contains the string "dev". - ``name:howl labels.env:dev`` --> The instance's name contains "howl" and it has the label "env" with its value containing "dev". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.page_iterator.PageIterator` instance. An iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instances. You can also iterate over the pages of the response using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_instances" not in self._inner_api_calls: self._inner_api_calls[ "list_instances" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_instances, default_retry=self._method_configs["ListInstances"].retry, default_timeout=self._method_configs["ListInstances"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.ListInstancesRequest( parent=parent, page_size=page_size, filter=filter_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_instances"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="instances", request_token_field="page_token", response_token_field="next_page_token", ) return iterator def get_instance( self, name, field_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets information about a particular instance. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> response = client.get_instance(name) Args: name (str): Required. The name of the requested instance. Values are of the form ``projects/<project>/instances/<instance>``. field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): If field_mask is present, specifies the subset of ``Instance`` fields that should be returned. If absent, all ``Instance`` fields are returned. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_instance" not in self._inner_api_calls: self._inner_api_calls[ "get_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_instance, default_retry=self._method_configs["GetInstance"].retry, default_timeout=self._method_configs["GetInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.GetInstanceRequest( name=name, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) def delete_instance( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes an instance. Immediately upon completion of the request: - Billing ceases for all of the instance's reserved resources. Soon afterward: - The instance and *all of its databases* immediately and irrevocably disappear from the API. All data in the databases is permanently deleted. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> client.delete_instance(name) Args: name (str): Required. The name of the instance to be deleted. Values are of the form ``projects/<project>/instances/<instance>`` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_instance" not in self._inner_api_calls: self._inner_api_calls[ "delete_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_instance, default_retry=self._method_configs["DeleteInstance"].retry, default_timeout=self._method_configs["DeleteInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.DeleteInstanceRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["delete_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) def set_iam_policy( self, resource, policy, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Sets the access control policy on an instance resource. Replaces any existing policy. Authorization requires ``spanner.instances.setIamPolicy`` on ``resource``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `resource`: >>> resource = '' >>> >>> # TODO: Initialize `policy`: >>> policy = {} >>> >>> response = client.set_iam_policy(resource, policy) Args: resource (str): REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. policy (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "set_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ "set_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_iam_policy, default_retry=self._method_configs["SetIamPolicy"].retry, default_timeout=self._method_configs["SetIamPolicy"].timeout, client_info=self._client_info, ) request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, policy=policy) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("resource", resource)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_iam_policy"]( request, retry=retry, timeout=timeout, metadata=metadata ) def get_iam_policy( self, resource, options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the access control policy for an instance resource. Returns an empty policy if an instance exists but does not have a policy set. Authorization requires ``spanner.instances.getIamPolicy`` on ``resource``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `resource`: >>> resource = '' >>> >>> response = client.get_iam_policy(resource) Args: resource (str): REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. options_ (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to ``GetIamPolicy``. This field is only used by Cloud IAM. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.GetPolicyOptions` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ "get_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_iam_policy, default_retry=self._method_configs["GetIamPolicy"].retry, default_timeout=self._method_configs["GetIamPolicy"].timeout, client_info=self._client_info, ) request = iam_policy_pb2.GetIamPolicyRequest( resource=resource, options=options_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("resource", resource)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_iam_policy"]( request, retry=retry, timeout=timeout, metadata=metadata ) def test_iam_permissions( self, resource, permissions, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns permissions that the caller has on the specified instance resource. Attempting this RPC on a non-existent Cloud Spanner instance resource will result in a NOT_FOUND error if the user has ``spanner.instances.list`` permission on the containing Google Cloud Project. Otherwise returns an empty set of permissions. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `resource`: >>> resource = '' >>> >>> # TODO: Initialize `permissions`: >>> permissions = [] >>> >>> response = client.test_iam_permissions(resource, permissions) Args: resource (str): REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. permissions (list[str]): The set of permissions to check for the ``resource``. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see `IAM Overview <https://cloud.google.com/iam/docs/overview#permissions>`__. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.TestIamPermissionsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "test_iam_permissions" not in self._inner_api_calls: self._inner_api_calls[ "test_iam_permissions" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.test_iam_permissions, default_retry=self._method_configs["TestIamPermissions"].retry, default_timeout=self._method_configs["TestIamPermissions"].timeout, client_info=self._client_info, ) request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("resource", resource)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["test_iam_permissions"]( request, retry=retry, timeout=timeout, metadata=metadata )
1.101563
1
src/ScaleHD/__backend.py
helloabunai/ScaleHD
3
4710
#/usr/bin/python __version__ = '1.0' __author__ = '<EMAIL>' ## ## Imports import string import os import errno import shutil import sys import glob import datetime import subprocess import logging as log import numpy as np import csv from io import StringIO import PyPDF2 from sklearn import preprocessing from collections import defaultdict from xml.etree import cElementTree from lxml import etree from reportlab.pdfgen import canvas class Colour: def __init__(self): pass purple = '\033[95m' cyan = '\033[96m' darkcyan = '\033[36m' blue = '\033[94m' green = '\033[92m' yellow = '\033[93m' red = '\033[91m' bold = '\033[1m' underline = '\033[4m' end = '\033[0m' class ConfigReader(object): """ The configuration file reader. Opens a configuration file, and if valid, converts the parameters within the file to a dictionary object, reader to be viewed through accessing the config_dict variable. """ def __init__(self, scriptdir, config_filename=None): ## ## Instance variables self.scriptdir = scriptdir self.config_filename = config_filename self.dtd_filename = scriptdir + "/config/config.dtd" ## ## Check for configuration file (just incase) if self.config_filename is None: log.error("No configuration file specified!") else: self.config_file = etree.parse(self.config_filename) ## ## Check config vs dtd, parse info to dictionary, validate vs ruleset self.validate_against_dtd() self.set_dictionary() self.validate_config() def validate_against_dtd(self): """ Validate input config against DTD ruleset i.e. confirms conformation of XML structure """ ## ## Open > etree.DTD object dtd_file = open(self.dtd_filename, 'r') dtd_object = etree.DTD(dtd_file) ## ## If validation fails, close the object (memory) and raise an error if not dtd_object.validate(self.config_file): dtd_file.close() log.error("DTD validation failure {0}: {1}".format(self.config_filename, dtd_object.error_log.filter_from_errors()[0])) sys.exit(2) dtd_file.close() def set_dictionary(self): """ Takes the now validated XML and extracts information from the tree into a python dictionary {key: value}. This dictionary will be used for variables within the pipeline. Recursion adapted from http://stackoverflow.com/a/9286702 """ def recursive_generation(t): d = {t.tag: {} if t.attrib else None} children = list(t) ## ## If list was populated, create dictionary, Append keys if children: dd = defaultdict(list) for dc in map(recursive_generation, children): for k, v in dc.items(): dd[k].append(v) d = {t.tag: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}} ## ## Values for key if t.attrib: d[t.tag].update(('@' + k, v) for k, v in t.attrib.items()) if t.text: text = t.text.strip() if children or t.attrib: if text: d[t.tag]['#text'] = text else: d[t.tag] = text return d ## ## Takes the formatted xml doc, puts through generator, returns dictionary string_repr = etree.tostring(self.config_file, pretty_print=True) element_tree = cElementTree.XML(string_repr) self.config_dict = recursive_generation(element_tree) self.config_dict = self.config_dict[list(self.config_dict.keys())[0]] def validate_config(self): """ Method which validates the configuration file's contents. If all pass, guarantees that the settings dictionary is full of valid settings! """ trigger = False ## ## Main configuration instance settings data_directory = self.config_dict['@data_dir'] if not os.path.exists(data_directory): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified data directory could not be found.')) trigger = True for fqfile in glob.glob(os.path.join(data_directory, '*')): if not (fqfile.endswith('.fq') or fqfile.endswith('.fastq') or fqfile.endswith('.fq.gz') or fqfile.endswith('.fastq.gz')): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Non FastQ/GZ data detected in specified input directory.')) trigger = True forward_reference = self.config_dict['@forward_reference'] if not os.path.isfile(forward_reference): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified forward reference file could not be found.')) trigger = True if not (forward_reference.endswith('.fa') or forward_reference.endswith('.fasta')): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified forward reference file is not a fa/fas file.')) trigger = True reverse_reference = self.config_dict['@reverse_reference'] if not os.path.isfile(reverse_reference): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified reverse reference file could not be found.')) trigger = True if not (reverse_reference.endswith('fa') or reverse_reference.endswith('.fasta')): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified reverse reference file is not a fa/fas file.')) trigger = True if forward_reference.split('/')[-1] == reverse_reference.split('/')[-1]: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: FW and RV references have identical filenames. Will create indexing issue.')) trigger = True ## ## Instance flag settings demultiplexing_flag = self.config_dict['instance_flags']['@demultiplex'] if not (demultiplexing_flag == 'True' or demultiplexing_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Demultiplexing flag is not set to True/False.')) trigger = True sequence_qc_flag = self.config_dict['instance_flags']['@quality_control'] if not (sequence_qc_flag == 'True' or sequence_qc_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Sequence Quality control flag is not set to True/False.')) trigger = True alignment_flag = self.config_dict['instance_flags']['@sequence_alignment'] if not (alignment_flag == 'True' or alignment_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Sequence Alignment flag is not set to True/False.')) trigger = True atypical_flag = self.config_dict['instance_flags']['@atypical_realignment'] if not (atypical_flag == 'True' or atypical_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Atypical Realignment flag is not True/False.')) trigger = True genotype_flag = self.config_dict['instance_flags']['@genotype_prediction'] if not (genotype_flag == 'True' or genotype_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Genotype Prediction control flag is not True/False.')) trigger = True snpcall_flag = self.config_dict['instance_flags']['@snp_calling'] if not (snpcall_flag == 'True' or snpcall_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: SNP Calling flag is not True/False.')) trigger = True ## ## Demultiplexing flag settings trim_adapter_base = ['A', 'G', 'C', 'T'] if demultiplexing_flag == 'True': forward_adapter = self.config_dict['demultiplex_flags']['@forward_adapter'] for charbase in forward_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in forward_adapter demultiplexing flag.')) trigger = True forward_position = self.config_dict['demultiplex_flags']['@forward_position'] if forward_position not in ['5P', '3P', 'AP']: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Given demultiplexing forward adapter position invalid! [5P, 3P, AP]')) trigger = True reverse_adapter = self.config_dict['demultiplex_flags']['@reverse_adapter'] for charbase in reverse_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in reverse_adapter demultiplexing flag.')) trigger = True reverse_position = self.config_dict['demultiplex_flags']['@reverse_position'] if reverse_position not in ['5P', '3P', 'AP']: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Given demultiplexing reverse adapter position invalid! [5P, 3P, AP]')) trigger = True error_rate = self.config_dict['demultiplex_flags']['@error_rate'] if not error_rate.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified error_rate is not a valid integer.')) trigger = True minimum_overlap = self.config_dict['demultiplex_flags']['@min_overlap'] if not minimum_overlap.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified min_overlap is not a valid integer.')) trigger = True minimum_length = self.config_dict['demultiplex_flags']['@min_length'] if not minimum_length == '': if not minimum_length.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified min_length is not a valid integer.')) trigger = True maximum_length = self.config_dict['demultiplex_flags']['@max_length'] if not maximum_length == '': if not maximum_length.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified max_length is not a valid integer.')) trigger = True ## ## Trimming flag settings if sequence_qc_flag == 'True': trimming_type = self.config_dict['trim_flags']['@trim_type'] if not (trimming_type == 'Quality' or trimming_type == 'Adapter' or trimming_type == 'Both'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Trimming type is not Quality/Adapter/Both.')) trigger = True quality_threshold = self.config_dict['trim_flags']['@quality_threshold'] if not quality_threshold.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified quality threshold integer is invalid.')) trigger = True elif not int(quality_threshold) in range(0,39): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified quality threshold integer out of range (0-38).')) trigger = True trim_adapters = ['-a','-g','-a$','-g^','-b'] adapter_flag = self.config_dict['trim_flags']['@adapter_flag'] if not (adapter_flag in trim_adapters): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified trimming adapter not valid selection.')) trigger = True forward_adapter = self.config_dict['trim_flags']['@forward_adapter'] for charbase in forward_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in FW adapter sequence.')) trigger = True reverse_adapter = self.config_dict['trim_flags']['@reverse_adapter'] for charbase in reverse_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in RV adapter sequence.')) trigger = True error_tolerance = self.config_dict['trim_flags']['@error_tolerance'] if not isinstance(float(error_tolerance), float): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified error tolerance is not a valid float.')) trigger = True if not float(error_tolerance) in np.arange(0,1.1,0.01): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified error tolerance is not 0.0 < x < 1.0.')) trigger = True ## ## Alignment flag settings if alignment_flag == 'True': min_seed_length = self.config_dict['alignment_flags']['@min_seed_length'] if not min_seed_length.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified min_seed_length integer is invalid.')) trigger=True band_width = self.config_dict['alignment_flags']['@band_width'] if not band_width.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified band_width integer is invalid.')) trigger=True seed_length_extension = self.config_dict['alignment_flags']['@seed_length_extension'] if not isinstance(float(seed_length_extension), float): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified seed_length_extension float is invalid.')) trigger=True skip_seed_with_occurrence = self.config_dict['alignment_flags']['@skip_seed_with_occurrence'] if not skip_seed_with_occurrence.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified skip_seed_with_occurrence integer is invalid.')) trigger=True chain_drop = self.config_dict['alignment_flags']['@chain_drop'] if not isinstance(float(chain_drop), float): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified chain_drop float is invalid.')) trigger=True seeded_chain_drop = self.config_dict['alignment_flags']['@seeded_chain_drop'] if not seeded_chain_drop.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified seeded_chain_drop integer is invalid.')) trigger=True seq_match_score = self.config_dict['alignment_flags']['@seq_match_score'] if not seq_match_score.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified seq_match_score integer is invalid.')) trigger=True mismatch_penalty = self.config_dict['alignment_flags']['@mismatch_penalty'] if not mismatch_penalty.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified mismatch_penalty integer is invalid.')) trigger=True indel_penalty_raw = self.config_dict['alignment_flags']['@indel_penalty'] indel_penalty = indel_penalty_raw.split(',') for individual_indelpen in indel_penalty: if not individual_indelpen.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified indel_penalty integer(s) is(are) invalid.')) trigger=True gap_extend_penalty_raw = self.config_dict['alignment_flags']['@gap_extend_penalty'] gap_extend_penalty = gap_extend_penalty_raw.split(',') for individual_gaextend in gap_extend_penalty: if not individual_gaextend.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified gap_extend_penalty integer(s) is(are) invalid.')) trigger=True prime_clipping_penalty_raw = self.config_dict['alignment_flags']['@prime_clipping_penalty'] prime_clipping_penalty = prime_clipping_penalty_raw.split(',') for individual_prclip in prime_clipping_penalty: if not individual_prclip.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified prime_clipping_penalty integer(s) is(are) invalid.')) trigger=True unpaired_pairing_penalty = self.config_dict['alignment_flags']['@unpaired_pairing_penalty'] if not unpaired_pairing_penalty.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified unpaired_pairing_penalty integer is invalid.')) trigger=True ## ## Genotype prediction flag settings if genotype_flag == 'True': snp_observation_pcnt = self.config_dict['prediction_flags']['@snp_observation_threshold'] if not snp_observation_pcnt.isdigit(): if not int(snp_observation_pcnt) in range(1,5): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: SNP Observation value invalid! Please use 1-10.')) trigger = True quality_cutoff = self.config_dict['prediction_flags']['@quality_cutoff'] if not quality_cutoff.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: SNP Quality Cutoff value is not an integer.')) trigger = True if trigger: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Failure, exiting.')) sys.exit(2) else: log.info('{}{}{}{}'.format(Colour.green, 'shd__ ', Colour.end, 'XML Config: Parsing parameters successful!')) class DataClump(dict): """Container object for datasets: dictionary-like object that exposes its keys as attributes.""" def __init__(self, **kwargs): dict.__init__(self, kwargs) self.__dict__ = self class DataLoader: def __init__(self, database, descriptor): self.database = database self.descriptor = descriptor def load_model(self): ## Loads description file for respective data set modeldescr_name = self.descriptor with open(modeldescr_name) as f: descr_text = f.read() ## Loads data set from csv, into objects in preparation for bunch() data_file_name = self.database with open(data_file_name) as f: data_file = csv.reader(f) temp = next(data_file) n_samples = int(temp[0]) n_features = int(temp[1]) data = np.empty((n_samples, n_features)) temp = next(data_file) feature_names = np.array(temp) labels = [] for i, d in enumerate(data_file): data[i] = d[:-1] label = d[-1] labels.append(label) le = preprocessing.LabelEncoder() le.fit(labels) hash_int_labels = le.transform(labels) return DataClump(DATA=data, TARGET=hash_int_labels, FTRNAME=feature_names[:-1], DESCR=descr_text, ENCDR=le) def parse_boolean(boolean_value): """ Given a string (boolean_value), returns a boolean value representing the string contents. For example, a string with 'true', 't', 'y' or 'yes' will yield True. """ boolean_value = string.lower(boolean_value) in ('yes', 'y', 'true', 't', '1') return boolean_value def empty_string_check(string, raise_exception=True): """ Simple check to see if the string provided by parameter string is empty. False indicates the string is NOT empty. Parameter raise_exception determines if a ValueError exception should be raised if the string is empty. If raise_exception is False and the string is empty, True is returned. """ if string != '': return False if raise_exception: raise ValueError("Empty string detected!") return True def sanitise_inputs(parsed_arguments): """ Utilises filesystem_exists_check and check_input_files if either return false, path is invalid or unsupported files present so, quit """ trigger = False ## ## Jobname prefix validity check if parsed_arguments.jobname: for character in parsed_arguments.jobname: if character is ' ' or character is '/': log.error('{}{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Specified Job Name has invalid characters: "', character, '"')) trigger = True ## ## Config mode check if parsed_arguments.config: if not filesystem_exists_check(parsed_arguments.config[0]): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Specified config file could not be found.')) trigger = True for xmlfile in parsed_arguments.config: if not check_input_files('.xml',xmlfile): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Specified config file is not an XML file.')) trigger = True return trigger def extract_data(input_data_directory): target_files = glob.glob(os.path.join(input_data_directory, '*')) for extract_target in target_files: if extract_target.lower().endswith(('.fq.gz', '.fastq.gz')): log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Detected compressed input data. Extracting!')) break for extract_target in target_files: unzipd = subprocess.Popen(['gzip', '-q', '-f', '-d', extract_target], stderr=subprocess.PIPE) unzipd.wait() return True def sequence_pairings(data_path, instance_rundir): ## ## Get input files from data path ## Sort so that ordering isn't screwy on linux input_files = glob.glob(os.path.join(data_path, '*')) sorted_input = sorted(input_files) sequence_pairs = [] file_count = len(sorted_input) if not file_count % 2 == 0: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'I/O: Non-even number of input files specified. Cannot continue without pairing!')) sys.exit(2) ## ## Optimise so code isn't recycled for i in range(0, len(sorted_input), 2): file_pair = {} forward_data = sorted_input[i] reverse_data = sorted_input[i+1] ## ## Check forward ends with R1 forward_data_name = sorted_input[i].split('/')[-1].split('.')[0] if not forward_data_name.endswith('_R1'): log.error('{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'I/O: Forward input file does not end in _R1. ', forward_data)) sys.exit(2) ## ## Check reverse ends with R2 reverse_data_name = sorted_input[i+1].split('/')[-1].split('.')[0] if not reverse_data_name.endswith('_R2'): log.error('{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'I/O: Reverse input file does not end in _R2. ', reverse_data)) sys.exit(2) ## ## Make Stage outputs for use in everywhere else in pipeline sample_root = '_'.join(forward_data_name.split('_')[:-1]) instance_path = os.path.join(instance_rundir) seq_qc_path = os.path.join(instance_rundir, sample_root, 'SeqQC') align_path = os.path.join(instance_rundir, sample_root, 'Align') predict_path = os.path.join(instance_rundir, sample_root, 'Predict') file_pair[sample_root] = [forward_data, reverse_data, instance_path, seq_qc_path, align_path, predict_path] sequence_pairs.append(file_pair) return sequence_pairs def filesystem_exists_check(path, raise_exception=True): """ Checks to see if the path, specified by parameter path, exists. Can be either a directory or file. If the path exists, True is returned. If the path does not exist, and raise_exception is set to True, an IOError is raised - else False is returned. """ if os.path.lexists(path): return True if raise_exception: log.error('{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Specified input path could not be found.')) return False def check_input_files(input_format, input_file): if input_file.endswith(input_format): return True return False def initialise_libraries(instance_params): trigger = False ## ## Subfunction for recycling code ## Calls UNIX type for checking binaries present ## Changed from WHICH as apparently type functions over different shells/config files def type_func(binary): binary_result = [] binary_string = 'type {}'.format(binary) binary_subprocess = subprocess.Popen([binary_string], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) binary_result = binary_subprocess.communicate() binary_subprocess.wait() if 'not found'.encode() in binary_result[0] or binary_result[1]: log.critical('{}{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Missing binary: ', binary, '!')) raise NameError ## ## To determine which binaries to check for ## AttributeError in the situation where instance_params origin differs ## try for -c style, except AttributeError for -b style try: quality_control = instance_params.config_dict['instance_flags']['@quality_control'] alignment = instance_params.config_dict['instance_flags']['@sequence_alignment'] genotyping = instance_params.config_dict['instance_flags']['@genotype_prediction'] snp_calling = instance_params.config_dict['instance_flags']['@snp_calling'] except AttributeError: quality_control = instance_params['quality_control'] alignment = instance_params['sequence_alignment'] genotyping = instance_params['genotype_prediction'] snp_calling = instance_params['snp_calling'] if quality_control == 'True': try:type_func('java') except NameError: trigger=True try:type_func('fastqc') except NameError: trigger=True try:type_func('cutadapt') except NameError: trigger=True if alignment == 'True': try:type_func('seqtk') except NameError: trigger=True try:type_func('bwa') except NameError: trigger=True try:type_func('samtools') except NameError: trigger=True try:type_func('generatr') except NameError: trigger=True if genotyping == 'True': try:type_func('samtools') except NameError: trigger=True try:type_func('generatr') except NameError: trigger=True if snp_calling == 'True': try: type_func('picard') except NameError: trigger=True try: type_func('freebayes') except NameError: trigger=True return trigger def sanitise_outputs(jobname, output_argument): run_dir = '' output_root = output_argument[0] if jobname: target_output = os.path.join(output_root, jobname) if not os.path.exists(target_output): log.info('{}{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating Output with prefix: ', jobname)) run_dir = os.path.join(output_root, jobname) mkdir_p(run_dir) else: purge_choice = '' while True: purge_choice = input('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Job folder already exists. Delete existing folder? Y/N: ')) if not (purge_choice.lower() == 'y') and not (purge_choice.lower() == 'n'): log.info('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Invalid input. Please input Y or N.')) continue else: break if purge_choice.lower() == 'y': log.info('{}{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Clearing pre-existing Jobname Prefix: ', jobname)) run_dir = os.path.join(output_root, jobname) if os.path.exists(run_dir): shutil.rmtree(run_dir, ignore_errors=True) mkdir_p(run_dir) else: raise Exception('User chose not to delete pre-existing Job folder. Cannot write output.') else: ## Ensures root output is a real directory ## Generates folder name based on date (for run ident) date = datetime.date.today().strftime('%d-%m-%Y') walltime = datetime.datetime.now().strftime('%H%M%S') today = date + '-' + walltime ## If the user specified root doesn't exist, make it ## Then make the run directory for datetime if not os.path.exists(output_root): log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating output root... ')) mkdir_p(output_root) run_dir = os.path.join(output_root, 'ScaleHDRun_'+today) log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating instance run directory.. ')) mkdir_p(run_dir) ## Inform user it's all gonna be okaaaayyyy log.info('{}{}{}{}'.format(Colour.green, 'shd__ ', Colour.end, 'Output directories OK!')) return run_dir def replace_fqfile(mutate_list, target_fqfile, altered_path): if target_fqfile in mutate_list: loc = mutate_list.index(target_fqfile) mutate_list[loc] = altered_path return mutate_list def scrape_summary_data(stage, input_report_file): ## ## If the argument input_report_file is from trimming.. if stage == 'trim': with open(input_report_file, 'r') as trpf: trim_lines = trpf.readlines() ## ## Determine buffer size to slice from above array scraping_buffer = 8 if '-q' in trim_lines[1]: scraping_buffer += 1 ## ## Get Anchor summary_start = 0 for i in range(0, len(trim_lines)): if '== Summary ==' in trim_lines[i]: summary_start = i ## ## Slice and close summary_data = trim_lines[summary_start:summary_start + scraping_buffer] trpf.close() return summary_data[2:] ## ## If the argument input_report_file is from alignment.. if stage == 'align': with open(input_report_file, 'r') as alnrpf: align_lines = alnrpf.readlines() alnrpf.close() ## ## No ranges required, only skip first line return align_lines[1:] ## ## No need to tidy up report for genotyping ## since we already have the data from our own objects if stage == 'gtype': pass def generate_atypical_xml(label, allele_object, index_path, direction): """ :param allele_object: :param index_path: :return: """ ##TODO docstring atypical_path = os.path.join(index_path, '{}{}_{}.xml'.format(direction, label, allele_object.get_reflabel())) fp_flank = 'GCGACCCTGGAAAAGCTGATGAAGGCCTTCGAGTCCCTCAAGTCCTTC' cagstart = ''; cagend = '' intv = allele_object.get_intervening() ccgstart = ''; ccgend = '' ccglen = allele_object.get_ccg() cctlen = allele_object.get_cct() tp_flank = 'CAGCTTCCTCAGCCGCCGCCGCAGGCACAGCCGCTGCT' if direction == 'fw': cagstart = '1'; cagend = '200' ccgstart = '1'; ccgend = '20' if direction == 'rv': cagstart = '100'; cagend = '100' ccgstart = '1'; ccgend = '20' ## ## Create XML data_root = etree.Element('data') loci_root = etree.Element('loci', label=allele_object.get_reflabel()); data_root.append(loci_root) ## ## Loci Nodes fp_input = etree.Element('input', type='fiveprime', flank=fp_flank) cag_region = etree.Element('input', type='repeat_region', order='1', unit='CAG', start=cagstart, end=cagend) intervening = etree.Element('input', type='intervening', sequence=intv, prior='1') ccg_region = etree.Element('input', type='repeat_region', order='2', unit='CCG', start=ccgstart, end=ccgend) cct_region = etree.Element('input', type='repeat_region', order='3', unit='CCT', start=str(cctlen), end=str(cctlen)) tp_input = etree.Element('input', type='threeprime', flank=tp_flank) for node in [fp_input, cag_region, intervening, ccg_region, cct_region, tp_input]: loci_root.append(node) s = etree.tostring(data_root, pretty_print=True) with open(atypical_path, 'w') as xmlfi: xmlfi.write(s.decode()) xmlfi.close() return atypical_path def generate_reference(input_xml, index_path, ref_indexes, direction): ##TODO docstring label = input_xml.split('/')[-1].split('.')[0] target_output = os.path.join(index_path, label + '.fa') temp_output = os.path.join(index_path, label + '_concat.fa') gen_process = subprocess.Popen(['generatr', '-i', input_xml, '-o', target_output], stdout=subprocess.PIPE, stderr=subprocess.PIPE) gen_process.wait() ## ## Join typical and atypical reference into one file if direction == 'fw': toutfi = open(temp_output, 'w') cat_process = subprocess.Popen(['cat', target_output, ref_indexes[0]], stdout=toutfi, stderr=subprocess.PIPE) cat_process.wait() toutfi.close() target_output = temp_output return target_output def seek_target(input_list, target): for i in range(0, len(input_list)): if target in input_list[i]: return i def sanitise_trimming_output(input_object, input_list): if type(input_object) is int: cleanse_target = input_list[input_object].split(':')[1].lstrip().rstrip() return cleanse_target else: return '*' def sanitise_alignment_output(input_object, input_list, stage): if type(input_object) is int: if stage == 3: cleanse_target = input_list[input_object].lstrip().rstrip().split(' ')[0:1] return ''.join(cleanse_target) else: cleanse_target = input_list[input_object].lstrip().rstrip().split(' ')[0:2] return ' '.join(cleanse_target) else: return '*' def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
2.4375
2
tests/test_models/test_backbones/test_encoder_decoders/test_deepfill_encoder.py
Jian137/mmediting-1
1,884
4711
<gh_stars>1000+ # Copyright (c) OpenMMLab. All rights reserved. import torch from mmedit.models.backbones import ContextualAttentionNeck, DeepFillEncoder from mmedit.models.common import SimpleGatedConvModule def test_deepfill_enc(): encoder = DeepFillEncoder() x = torch.randn((2, 5, 256, 256)) outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.stride == (2, 2) assert encoder.enc2.out_channels == 64 encoder = DeepFillEncoder(encoder_type='stage2_conv') x = torch.randn((2, 5, 256, 256)) outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.out_channels == 32 assert encoder.enc3.out_channels == 64 assert encoder.enc4.out_channels == 64 encoder = DeepFillEncoder(encoder_type='stage2_attention') x = torch.randn((2, 5, 256, 256)) outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.out_channels == 32 assert encoder.enc3.out_channels == 64 assert encoder.enc4.out_channels == 128 if torch.cuda.is_available(): encoder = DeepFillEncoder().cuda() x = torch.randn((2, 5, 256, 256)).cuda() outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.stride == (2, 2) assert encoder.enc2.out_channels == 64 encoder = DeepFillEncoder(encoder_type='stage2_conv').cuda() x = torch.randn((2, 5, 256, 256)).cuda() outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.out_channels == 32 assert encoder.enc3.out_channels == 64 assert encoder.enc4.out_channels == 64 encoder = DeepFillEncoder(encoder_type='stage2_attention').cuda() x = torch.randn((2, 5, 256, 256)).cuda() outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.out_channels == 32 assert encoder.enc3.out_channels == 64 assert encoder.enc4.out_channels == 128 encoder = DeepFillEncoder( conv_type='gated_conv', channel_factor=0.75).cuda() x = torch.randn((2, 5, 256, 256)).cuda() outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 96, 64, 64) assert isinstance(encoder.enc2, SimpleGatedConvModule) assert encoder.enc2.conv.stride == (2, 2) assert encoder.enc2.conv.out_channels == 48 * 2 def test_deepfill_contextual_attention_neck(): # TODO: add unittest for contextual attention module neck = ContextualAttentionNeck(in_channels=128) x = torch.rand((2, 128, 64, 64)) mask = torch.zeros((2, 1, 64, 64)) mask[..., 20:100, 23:90] = 1. res, offset = neck(x, mask) assert res.shape == (2, 128, 64, 64) assert offset.shape == (2, 32, 32, 32, 32) if torch.cuda.is_available(): neck.cuda() res, offset = neck(x.cuda(), mask.cuda()) assert res.shape == (2, 128, 64, 64) assert offset.shape == (2, 32, 32, 32, 32) neck = ContextualAttentionNeck( in_channels=128, conv_type='gated_conv').cuda() res, offset = neck(x.cuda(), mask.cuda()) assert res.shape == (2, 128, 64, 64) assert offset.shape == (2, 32, 32, 32, 32) assert isinstance(neck.conv1, SimpleGatedConvModule)
2.1875
2
mvp/migrations/0004_auto_20201127_0649.py
Wastecoinng/mvp_beta
0
4712
# Generated by Django 2.2.13 on 2020-11-27 05:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mvp', '0003_hublocation'), ] operations = [ migrations.RemoveField( model_name='hublocation', name='longitude', ), migrations.AddField( model_name='hublocation', name='longi', field=models.TextField(default=654433, max_length=90, unique=True, verbose_name='Longitude'), preserve_default=False, ), ]
1.625
2
adminapp/migrations/0012_auto_20210714_1155.py
mofresh27/MuseumExperience-Group2-Python-BE-1
0
4713
<filename>adminapp/migrations/0012_auto_20210714_1155.py # Generated by Django 3.2.4 on 2021-07-14 11:55 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('adminapp', '0011_faq'), ] operations = [ migrations.AddField( model_name='faq', name='uuid', field=models.UUIDField(blank=True, default=uuid.uuid4, null=True), ), migrations.AlterField( model_name='faq', name='answer', field=models.TextField(blank=True, default=None, null=True), ), migrations.AlterField( model_name='faq', name='question', field=models.TextField(blank=True, default=None, null=True), ), ]
1.632813
2
scripts/json_parse.py
andrewsimonds14/Capstone
0
4714
<reponame>andrewsimonds14/Capstone import json import os import nibabel as nib import csv from operator import itemgetter # PATH TO PREPROCESSED DATA raw_data_path = '/home/lab/nnUNet_data/nnUNet_raw_data_base/nnUNet_raw_data/Task500_BrainMets' pixdim_ind = [1,2,3] # Indexes at which the voxel size [x,y,z] is stored # PATH TO JSON FILE with open('/home/lab/nnUNet_data/RESULTS_FOLDER/nnUNet/3d_fullres/Task500_BrainMets/nnUNetTrainerV2__nnUNetPlansv2.1/fold_4/validation_raw/summary.json') as file: data = json.load(file) with open('json_parsed.csv', mode='w') as csv_file: csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(['Case Number', 'Dice Score', 'Voxel Size-X', 'Voxel Size-Y', 'Voxel Size-Z']) for img in data['results']['all']: # Get dice score on image dice = img['1']['Dice'] # Get nifti data on image img_filename = (os.path.basename(img['reference']).split('.'))[0] img_ni = nib.load(raw_data_path + '/imagesTr/' + img_filename + '_0000.nii.gz') label_ni = nib.load(raw_data_path + '/labelsTr/' + img_filename + '.nii.gz') voxel_size = itemgetter(*pixdim_ind)(img_ni.header["pixdim"]) # Get tumor dimensions # tumor_size = # Get case number corresponding to image case_number = img_filename.split('_')[1] # Write to csv file csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow([case_number, dice, voxel_size[0], voxel_size[1], voxel_size[2]])
2.953125
3
tests/gen_test.py
tinylambda/tornadio2
0
4715
# -*- coding: utf-8 -*- """ tornadio2.tests.gen ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by the <NAME>, see AUTHORS for more details. :license: Apache, see LICENSE for more details. """ from collections import deque from nose.tools import eq_ from tornadio2 import gen _queue = None def init_environment(): global _queue _queue = deque() def run_sync(test, callback): callback(test) def queue_async(test, callback): global _queue _queue.append((callback, test)) def step_async(): callback = _queue.popleft() callback[0](callback[1]) def run_async(): global _queue while True: try: step_async() except IndexError: break def run_async_oor(): global _queue while True: try: callback = _queue.pop() callback[0](callback[1]) except IndexError: break class Dummy(): def __init__(self, queue_type): self.v = None self.queue_type = queue_type @gen.sync_engine def test(self, value): self.v = yield gen.Task(self.queue_type, value) class DummyList(): def __init__(self, queue_type): self.v = [] self.queue_type = queue_type @gen.sync_engine def test(self, value): self.v.append((yield gen.Task(self.queue_type, value))) class DummyListOutOfOrder(): def __init__(self, queue_type): self.v = [] self.queue_type = queue_type @gen.engine def test(self, value): self.v.append((yield gen.Task(self.queue_type, value))) class DummyLoop(): def __init__(self, queue_type): self.v = 0 self.queue_type = queue_type @gen.sync_engine def test(self, value): for n in range(2): self.v += (yield gen.Task(self.queue_type, value)) def test(): init_environment() dummy = Dummy(run_sync) dummy.test('test') eq_(dummy.v, 'test') def test_async(): init_environment() dummy = Dummy(queue_async) dummy.test('test') run_async() # Verify value eq_(dummy.v, 'test') def test_sync_queue(): init_environment() dummy = DummyList(queue_async) dummy.test('1') dummy.test('2') dummy.test('3') run_async() # Verify value eq_(dummy.v, ['1', '2', '3']) def test_sync_queue_oor(): init_environment() dummy = DummyList(queue_async) dummy.test('1') dummy.test('2') dummy.test('3') run_async_oor() # Verify value eq_(dummy.v, ['1', '2', '3']) def test_async_queue_oor(): init_environment() dummy = DummyListOutOfOrder(queue_async) dummy.test('1') dummy.test('2') dummy.test('3') run_async_oor() # Verify value eq_(dummy.v, ['3', '2', '1'])
1.992188
2
DeepBrainSeg/tumor/Tester.py
JordanMicahBennett/DeepBrainSeg
1
4716
#! /usr/bin/env python # -*- coding: utf-8 -*- # # author: <NAME> # contact: <EMAIL> import torch import SimpleITK as sitk import numpy as np import nibabel as nib from torch.autograd import Variable from skimage.transform import resize from torchvision import transforms from time import gmtime, strftime from tqdm import tqdm import pdb import os from ..helpers.helper import * from os.path import expanduser home = expanduser("~") #======================================================================================== # prediction functions..................... bin_path = os.path.join('/opt/ANTs/bin/') class tumorSeg(): """ class performs segmentation for a given sequence of patient data. to main platform for segmentation mask estimation one for the patient data in brats format other with any random format step followed for in estimation of segmentation mask 1. ABLnet for reducing false positives outside the brain Air Brain Lesson model (2D model, 103 layered) 2. BNet3Dnet 3D network for inner class classification Dual Path way network 3. MNet2D 57 layered convolutional network for inner class classification 4. Tir3Dnet 57 layered 3D convolutional network for inner class classification more on training details and network information: (https://link.springer.com/chapter/10.1007/978-3-030-11726-9_43<Paste>) ========================= quick: True (just evaluates on Dual path network (BNet3D) else copmutes an ensumble over all four networks """ def __init__(self, quick = False, ants_path = bin_path): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # device = "cpu" map_location = device #======================================================================================== ckpt_tir2D = os.path.join(home, '.DeepBrainSeg/BestModels/Tramisu_2D_FC57_best_loss.pth.tar') ckpt_tir3D = os.path.join(home, '.DeepBrainSeg/BestModels/Tramisu_3D_FC57_best_acc.pth.tar') ckpt_BNET3D = os.path.join(home, '.DeepBrainSeg/BestModels/BrainNet_3D_best_acc.pth.tar') ckpt_ABL = os.path.join(home, '.DeepBrainSeg/BestModels/ABL_CE_best_model_loss_based.pth.tar') #======================================================================================== # air brain lesion segmentation.............. from .models.modelABL import FCDenseNet103 self.ABLnclasses = 3 self.ABLnet = FCDenseNet103(n_classes = self.ABLnclasses) ## intialize the graph saved_parms=torch.load(ckpt_ABL, map_location=map_location) self.ABLnet.load_state_dict(saved_parms['state_dict']) ## fill the model with trained params print ("=================================== ABLNET2D Loaded =================================") self.ABLnet.eval() self.ABLnet = self.ABLnet.to(device) #======================================================================================== # Tir2D net....................... from .models.modelTir2D import FCDenseNet57 self.Mnclasses = 4 self.MNET2D = FCDenseNet57(self.Mnclasses) ckpt = torch.load(ckpt_tir2D, map_location=map_location) self.MNET2D.load_state_dict(ckpt['state_dict']) print ("=================================== MNET2D Loaded ===================================") self.MNET2D.eval() self.MNET2D = self.MNET2D.to(device) #======================================================================================== if not quick: # BrainNet3D model...................... from .models.model3DBNET import BrainNet_3D_Inception self.B3Dnclasses = 5 self.BNET3Dnet = BrainNet_3D_Inception() ckpt = torch.load(ckpt_BNET3D, map_location=map_location) self.BNET3Dnet.load_state_dict(ckpt['state_dict']) print ("=================================== KAMNET3D Loaded =================================") self.BNET3Dnet.eval() self.BNET3Dnet = self.BNET3Dnet.to(device) #======================================================================================== # Tir3D model................... from .models.modelTir3D import FCDenseNet57 self.T3Dnclasses = 5 self.Tir3Dnet = FCDenseNet57(self.T3Dnclasses) ckpt = torch.load(ckpt_tir3D, map_location=map_location) self.Tir3Dnet.load_state_dict(ckpt['state_dict']) print ("================================== TIRNET2D Loaded =================================") self.Tir3Dnet.eval() self.Tir3Dnet = self.Tir3Dnet.to(device) #======================================================================================== self.device = device self.quick = quick self.ants_path = ants_path def get_ants_mask(self, t1_path): """ We make use of ants framework for generalized skull stripping t1_path: t1 volume path (str) saves the mask in the same location as t1 data directory returns: maskvolume (numpy uint8 type) """ mask_path = os.path.join(os.path.dirname(t1_path), 'mask.nii.gz') os.system(self.ants_path +'ImageMath 3 '+ mask_path +' Normalize '+ t1_path) os.system(self.ants_path +'ThresholdImage 3 '+ mask_path +' '+ mask_path +' 0.01 1') os.system(self.ants_path +'ImageMath 3 '+ mask_path +' MD '+ mask_path +' 1') os.system(self.ants_path +'ImageMath 3 '+ mask_path +' ME '+ mask_path +' 1') os.system(self.ants_path +'CopyImageHeaderInformation '+ t1_path+' '+ mask_path +' '+ mask_path +' 1 1 1') mask = np.uint8(nib.load(mask_path).get_data()) return mask def get_localization(self, t1_v, t1c_v, t2_v, flair_v, brain_mask): """ ABLnetwork output, finds the brain, Whole tumor region t1_v = t1 volume (numpy array) t1c_v = t1c volume (numpy array) t2_v = t2 volume (numpy array) flair_v = flair volume (numpy array) brain_mask = brain, whole tumor mask (numpy array, output of ANTs pieline) """ t1_v = normalize(t1_v, brain_mask) t1c_v = normalize(t1c_v, brain_mask) t2_v = normalize(t2_v, brain_mask) flair_v = normalize(flair_v, brain_mask) generated_output_logits = np.empty((self.ABLnclasses, flair_v.shape[0],flair_v.shape[1],flair_v.shape[2])) for slices in tqdm(range(flair_v.shape[2])): flair_slice = np.transpose(flair_v[:,:,slices]) t2_slice = np.transpose(t2_v[:,:,slices]) t1ce_slice = np.transpose(t1c_v[:,:,slices]) t1_slice = np.transpose(t1_v[:,:,slices]) array = np.zeros((flair_slice.shape[0],flair_slice.shape[1],4)) array[:,:,0] = flair_slice array[:,:,1] = t2_slice array[:,:,2] = t1ce_slice array[:,:,3] = t1_slice transformed_array = torch.from_numpy(convert_image(array)).float() transformed_array = transformed_array.unsqueeze(0) ## neccessary if batch size == 1 transformed_array = transformed_array.to(self.device) logits = self.ABLnet(transformed_array).detach().cpu().numpy()# 3 x 240 x 240 generated_output_logits[:,:,:, slices] = logits.transpose(0, 1, 3, 2) final_pred = apply_argmax_to_logits(generated_output_logits) final_pred = perform_postprocessing(final_pred) final_pred = adjust_classes_air_brain_tumour(np.uint8(final_pred)) return np.uint8(final_pred) def inner_class_classification_with_logits_NCube(self, t1, t1ce, t2, flair, brain_mask, mask, N = 64): """ output of 3D tiramisu model (tir3Dnet) mask = numpy array output of ABLnet N = patch size during inference """ t1 = normalize(t1, brain_mask) t1ce = normalize(t1ce, brain_mask) t2 = normalize(t2, brain_mask) flair = normalize(flair, brain_mask) shape = t1.shape # to exclude batch_size final_prediction = np.zeros((self.T3Dnclasses, shape[0], shape[1], shape[2])) x_min, x_max, y_min, y_max, z_min, z_max = bbox(mask, pad = N) x_min, x_max, y_min, y_max, z_min, z_max = x_min, min(shape[0] - N, x_max), y_min, min(shape[1] - N, y_max), z_min, min(shape[2] - N, z_max) with torch.no_grad(): for x in tqdm(range(x_min, x_max, N//2)): for y in range(y_min, y_max, N//2): for z in range(z_min, z_max, N//2): high = np.zeros((1, 4, N, N, N)) high[0, 0, :, :, :] = flair[x:x+N, y:y+N, z:z+N] high[0, 1, :, :, :] = t2[x:x+N, y:y+N, z:z+N] high[0, 2, :, :, :] = t1[x:x+N, y:y+N, z:z+N] high[0, 3, :, :, :] = t1ce[x:x+N, y:y+N, z:z+N] high = Variable(torch.from_numpy(high)).to(self.device).float() pred = torch.nn.functional.softmax(self.Tir3Dnet(high).detach().cpu()) pred = pred.data.numpy() final_prediction[:, x:x+N, y:y+N, z:z+N] = pred[0] final_prediction = convert5class_logitsto_4class(final_prediction) return final_prediction def inner_class_classification_with_logits_DualPath(self, t1, t1ce, t2, flair, brain_mask, mask=None, prediction_size = 9): """ output of BNet3D prediction_size = mid inference patch size """ t1 = normalize(t1, brain_mask) t1ce = normalize(t1ce, brain_mask) t2 = normalize(t2, brain_mask) flair = normalize(flair, brain_mask) shape = t1.shape # to exclude batch_size final_prediction = np.zeros((self.B3Dnclasses, shape[0], shape[1], shape[2])) x_min, x_max, y_min, y_max, z_min, z_max = bbox(mask, pad = prediction_size) # obtained by aspect ratio calculation high_res_size = prediction_size + 16 resize_to = int(prediction_size ** 0.5) + 16 low_res_size = int(51*resize_to/19) hl_pad = (high_res_size - prediction_size)//2 hr_pad = hl_pad + prediction_size ll_pad = (low_res_size - prediction_size)//2 lr_pad = ll_pad + prediction_size for x in tqdm(range(x_min, x_max - prediction_size, prediction_size)): for y in (range(y_min, y_max - prediction_size, prediction_size)): for z in (range(z_min, z_max - prediction_size, prediction_size)): high = np.zeros((1, 4, high_res_size, high_res_size, high_res_size)) low = np.zeros((1, 4, low_res_size, low_res_size, low_res_size)) low1 = np.zeros((1, 4, resize_to, resize_to, resize_to)) high[0, 0], high[0, 1], high[0, 2], high[0, 3] = high[0, 0] + flair[0,0,0], high[0, 1] + t2[0,0,0], high[0, 2] + t1[0,0,0], high[0, 2] + t1ce[0,0,0] low[0, 0], low[0, 1], low[0, 2], low[0, 3] = low[0, 0] + flair[0,0,0], low[0, 1] + t2[0,0,0], low[0, 2] + t1[0,0,0], low[0, 2] + t1ce[0,0,0] low1[0, 0], low1[0, 1], low1[0, 2], low1[0, 3] = low1[0, 0] + flair[0,0,0], low1[0, 1] + t2[0,0,0], low1[0, 2] + t1[0,0,0], low1[0, 2] + t1ce[0,0,0] # ========================================================================= vxf, vxt = max(0, x-hl_pad), min(shape[0], x+hr_pad) vyf, vyt = max(0, y-hl_pad), min(shape[1], y+hr_pad) vzf, vzt = max(0, z-hl_pad), min(shape[2], z+hr_pad) txf, txt = max(0, hl_pad-x), max(0, hl_pad-x) + vxt - vxf tyf, tyt = max(0, hl_pad-y), max(0, hl_pad-y) + vyt - vyf tzf, tzt = max(0, hl_pad-z), max(0, hl_pad-z) + vzt - vzf high[0, 0, txf:txt, tyf:tyt, tzf:tzt] = flair[vxf:vxt, vyf:vyt, vzf:vzt] high[0, 1, txf:txt, tyf:tyt, tzf:tzt] = t2[vxf:vxt, vyf:vyt, vzf:vzt] high[0, 2, txf:txt, tyf:tyt, tzf:tzt] = t1[vxf:vxt, vyf:vyt, vzf:vzt] high[0, 3, txf:txt, tyf:tyt, tzf:tzt] = t1ce[vxf:vxt, vyf:vyt, vzf:vzt] # ========================================================================= vxf, vxt = max(0, x-ll_pad), min(shape[0], x+lr_pad) vyf, vyt = max(0, y-ll_pad), min(shape[1], y+lr_pad) vzf, vzt = max(0, z-ll_pad), min(shape[2], z+lr_pad) txf, txt = max(0, ll_pad-x), max(0, ll_pad-x) + vxt - vxf tyf, tyt = max(0, ll_pad-y), max(0, ll_pad-y) + vyt - vyf tzf, tzt = max(0, ll_pad-z), max(0, ll_pad-z) + vzt - vzf low[0, 0, txf:txt, tyf:tyt, tzf:tzt] = flair[vxf:vxt, vyf:vyt, vzf:vzt] low[0, 1, txf:txt, tyf:tyt, tzf:tzt] = t2[vxf:vxt, vyf:vyt, vzf:vzt] low[0, 2, txf:txt, tyf:tyt, tzf:tzt] = t1[vxf:vxt, vyf:vyt, vzf:vzt] low[0, 3, txf:txt, tyf:tyt, tzf:tzt] = t1ce[vxf:vxt, vyf:vyt, vzf:vzt] # ========================================================================= low1[0] = [resize(low[0, i, :, :, :], (resize_to, resize_to, resize_to)) for i in range(4)] high = Variable(torch.from_numpy(high)).to(self.device).float() low1 = Variable(torch.from_numpy(low1)).to(self.device).float() pred = torch.nn.functional.softmax(self.BNET3Dnet(high, low1, pred_size=prediction_size).detach().cpu()) pred = pred.numpy() final_prediction[:, x:x+prediction_size, y:y+prediction_size, z:z+prediction_size] = pred[0] final_prediction = convert5class_logitsto_4class(final_prediction) return final_prediction def inner_class_classification_with_logits_2D(self, t1ce_volume, t2_volume, flair_volume): """ output of 2D tiramisu model (MNet) """ normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) transformList = [] transformList.append(transforms.ToTensor()) transformList.append(normalize) transformSequence=transforms.Compose(transformList) generated_output = np.empty((self.Mnclasses,flair_volume.shape[0],flair_volume.shape[1],flair_volume.shape[2])) for slices in tqdm(range(flair_volume.shape[2])): flair_slice = scale_every_slice_between_0_to_255(np.transpose(flair_volume[:,:,slices])) t2_slice = scale_every_slice_between_0_to_255(np.transpose(t2_volume[:,:,slices])) t1ce_slice = scale_every_slice_between_0_to_255(np.transpose(t1ce_volume[:,:,slices])) array = np.zeros((flair_slice.shape[0],flair_slice.shape[1],3)) array[:,:,0] = flair_slice array[:,:,1] = t2_slice array[:,:,2] = t1ce_slice array = np.uint8(array) transformed_array = transformSequence(array) transformed_array = transformed_array.unsqueeze(0) transformed_array = transformed_array.to(self.device) outs = torch.nn.functional.softmax(self.MNET2D(transformed_array).detach().cpu()).numpy() outs = np.swapaxes(generated_output,1, 2) return outs def get_segmentation(self, t1_path, t2_path, t1ce_path, flair_path, save_path = None): """ Generates segmentation for the data not in brats format if save_path provided function saves the prediction with DeepBrainSeg_Prediction.nii.qz name in the provided directory returns: segmentation mask """ t1 = nib.load(t1_path).get_data() t2 = nib.load(t2_path).get_data() t1ce = nib.load(t1ce_path).get_data() flair = nib.load(flair_path).get_data() affine = nib.load(flair_path).affine brain_mask = self.get_ants_mask(t2_path) mask = self.get_localization(t1, t1ce, t2, flair, brain_mask) # mask = np.swapaxes(mask,1, 0) if not self.quick: final_predictionTir3D_logits = self.inner_class_classification_with_logits_NCube(t1, t1ce, t2, flair, brain_mask, mask) final_predictionBNET3D_logits = self.inner_class_classification_with_logits_DualPath(t1, t1ce, t2, flair, brain_mask, mask) final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair).transpose(0, 2, 1, 3) final_prediction_array = np.array([final_predictionTir3D_logits, final_predictionBNET3D_logits, final_predictionMnet_logits]) else: final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair) final_prediction_array = np.array([final_predictionMnet_logits]) final_prediction_logits = combine_logits_AM(final_prediction_array) final_pred = postprocessing_pydensecrf(final_prediction_logits) final_pred = combine_mask_prediction(mask, final_pred) final_pred = perform_postprocessing(final_pred) final_pred = adjust_classes(final_pred) if save_path: os.makedirs(save_path, exist_ok=True) save_volume(final_pred, affine, os.path.join(save_path, 'DeepBrainSeg_Prediction')) return final_pred def get_segmentation_brats(self, path, save = True): """ Generates segmentation for the data in BraTs format if save True saves the prediction in the save directory in the patients data path returns : segmentation mask """ name = path.split("/")[-1] + "_" flair = nib.load(os.path.join(path, name + 'flair.nii.gz')).get_data() t1 = nib.load(os.path.join(path, name + 't1.nii.gz')).get_data() t1ce = nib.load(os.path.join(path, name + 't1ce.nii.gz')).get_data() t2 = nib.load(os.path.join(path, name + 't2.nii.gz')).get_data() affine= nib.load(os.path.join(path, name + 'flair.nii.gz')).affine print ("[INFO: DeepBrainSeg] (" + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) + ") Working on: ", path) brain_mask = self.get_ants_mask(os.path.join(path, name + 't2.nii.gz')) # brain_mask = get_brain_mask(t1) mask = self.get_localization(t1, t1ce, t2, flair, brain_mask) mask = np.swapaxes(mask,1, 0) if not self.quick: final_predictionTir3D_logits = self.inner_class_classification_with_logits_NCube(t1, t1ce, t2, flair, brain_mask, mask) final_predictionBNET3D_logits = self.inner_class_classification_with_logits_DualPath(t1, t1ce, t2, flair, brain_mask, mask) final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair) final_prediction_array = np.array([final_predictionTir3D_logits, final_predictionBNET3D_logits, final_predictionMnet_logits]) else: final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair) final_prediction_array = np.array([final_predictionMnet_logits]) final_prediction_logits = combine_logits_AM(final_prediction_array) final_pred = postprocessing_pydensecrf(final_prediction_logits) final_pred = combine_mask_prediction(mask, final_pred) final_pred = perform_postprocessing(final_pred) final_pred = adjust_classes(final_pred) if save: save_volume(final_pred, affine, os.path.join(path, 'DeepBrainSeg_Prediction')) return final_pred # ======================================================================================== if __name__ == '__main__': ext = deepSeg(True) ext.get_segmentation_brats('../../sample_volume/Brats18_CBICA_AVG_1/')
2.421875
2
statsmodels/discrete/tests/test_conditional.py
porcpine1967/statsmodels
0
4717
import numpy as np from statsmodels.discrete.conditional_models import ( ConditionalLogit, ConditionalPoisson) from statsmodels.tools.numdiff import approx_fprime from numpy.testing import assert_allclose import pandas as pd def test_logit_1d(): y = np.r_[0, 1, 0, 1, 0, 1, 0, 1, 1, 1] g = np.r_[0, 0, 0, 1, 1, 1, 2, 2, 2, 2] x = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x = x[:, None] model = ConditionalLogit(y, x, groups=g) # Check the gradient for the denominator of the partial likelihood for x in -1, 0, 1, 2: params = np.r_[x, ] _, grad = model._denom_grad(0, params) ngrad = approx_fprime(params, lambda x: model._denom(0, x)) assert_allclose(grad, ngrad) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: grad = approx_fprime(np.r_[x, ], model.loglike) score = model.score(np.r_[x, ]) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[0.9272407], rtol=1e-5) assert_allclose(result.bse, np.r_[1.295155], rtol=1e-5) def test_logit_2d(): y = np.r_[0, 1, 0, 1, 0, 1, 0, 1, 1, 1] g = np.r_[0, 0, 0, 1, 1, 1, 2, 2, 2, 2] x1 = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x2 = np.r_[0, 0, 1, 0, 0, 1, 0, 1, 1, 1] x = np.empty((10, 2)) x[:, 0] = x1 x[:, 1] = x2 model = ConditionalLogit(y, x, groups=g) # Check the gradient for the denominator of the partial likelihood for x in -1, 0, 1, 2: params = np.r_[x, -1.5*x] _, grad = model._denom_grad(0, params) ngrad = approx_fprime(params, lambda x: model._denom(0, x)) assert_allclose(grad, ngrad, rtol=1e-5) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: params = np.r_[-0.5*x, 0.5*x] grad = approx_fprime(params, model.loglike) score = model.score(params) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[1.011074, 1.236758], rtol=1e-3) assert_allclose(result.bse, np.r_[1.420784, 1.361738], rtol=1e-5) result.summary() def test_formula(): for j in 0, 1: np.random.seed(34234) n = 200 y = np.random.randint(0, 2, size=n) x1 = np.random.normal(size=n) x2 = np.random.normal(size=n) g = np.random.randint(0, 25, size=n) x = np.hstack((x1[:, None], x2[:, None])) if j == 0: model1 = ConditionalLogit(y, x, groups=g) else: model1 = ConditionalPoisson(y, x, groups=g) result1 = model1.fit() df = pd.DataFrame({"y": y, "x1": x1, "x2": x2, "g": g}) if j == 0: model2 = ConditionalLogit.from_formula( "y ~ 0 + x1 + x2", groups="g", data=df) else: model2 = ConditionalPoisson.from_formula( "y ~ 0 + x1 + x2", groups="g", data=df) result2 = model2.fit() assert_allclose(result1.params, result2.params, rtol=1e-5) assert_allclose(result1.bse, result2.bse, rtol=1e-5) assert_allclose(result1.cov_params(), result2.cov_params(), rtol=1e-5) assert_allclose(result1.tvalues, result2.tvalues, rtol=1e-5) def test_poisson_1d(): y = np.r_[3, 1, 1, 4, 5, 2, 0, 1, 6, 2] g = np.r_[0, 0, 0, 0, 1, 1, 1, 1, 1, 1] x = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x = x[:, None] model = ConditionalPoisson(y, x, groups=g) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: grad = approx_fprime(np.r_[x, ], model.loglike) score = model.score(np.r_[x, ]) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[0.6466272], rtol=1e-4) assert_allclose(result.bse, np.r_[0.4170918], rtol=1e-5) def test_poisson_2d(): y = np.r_[3, 1, 4, 8, 2, 5, 4, 7, 2, 6] g = np.r_[0, 0, 0, 1, 1, 1, 2, 2, 2, 2] x1 = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x2 = np.r_[2, 1, 0, 0, 1, 2, 3, 2, 0, 1] x = np.empty((10, 2)) x[:, 0] = x1 x[:, 1] = x2 model = ConditionalPoisson(y, x, groups=g) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: params = np.r_[-0.5*x, 0.5*x] grad = approx_fprime(params, model.loglike) score = model.score(params) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[-.9478957, -.0134279], rtol=1e-3) assert_allclose(result.bse, np.r_[.3874942, .1686712], rtol=1e-5) result.summary() def test_lasso_logistic(): np.random.seed(3423948) n = 200 groups = np.arange(10) groups = np.kron(groups, np.ones(n // 10)) group_effects = np.random.normal(size=10) group_effects = np.kron(group_effects, np.ones(n // 10)) x = np.random.normal(size=(n, 4)) params = np.r_[0, 0, 1, 0] lin_pred = np.dot(x, params) + group_effects mean = 1 / (1 + np.exp(-lin_pred)) y = (np.random.uniform(size=n) < mean).astype(np.int) model0 = ConditionalLogit(y, x, groups=groups) result0 = model0.fit() # Should be the same as model0 model1 = ConditionalLogit(y, x, groups=groups) result1 = model1.fit_regularized(L1_wt=0, alpha=0) assert_allclose(result0.params, result1.params, rtol=1e-3) model2 = ConditionalLogit(y, x, groups=groups) result2 = model2.fit_regularized(L1_wt=1, alpha=0.05) # Rxegression test assert_allclose(result2.params, np.r_[0, 0, 0.55235152, 0], rtol=1e-4) # Test with formula df = pd.DataFrame({"y": y, "x1": x[:, 0], "x2": x[:, 1], "x3": x[:, 2], "x4": x[:, 3], "groups": groups}) fml = "y ~ 0 + x1 + x2 + x3 + x4" model3 = ConditionalLogit.from_formula(fml, groups="groups", data=df) result3 = model3.fit_regularized(L1_wt=1, alpha=0.05) assert_allclose(result2.params, result3.params) def test_lasso_poisson(): np.random.seed(342394) n = 200 groups = np.arange(10) groups = np.kron(groups, np.ones(n // 10)) group_effects = np.random.normal(size=10) group_effects = np.kron(group_effects, np.ones(n // 10)) x = np.random.normal(size=(n, 4)) params = np.r_[0, 0, 1, 0] lin_pred = np.dot(x, params) + group_effects mean = np.exp(lin_pred) y = np.random.poisson(mean) model0 = ConditionalPoisson(y, x, groups=groups) result0 = model0.fit() # Should be the same as model0 model1 = ConditionalPoisson(y, x, groups=groups) result1 = model1.fit_regularized(L1_wt=0, alpha=0) assert_allclose(result0.params, result1.params, rtol=1e-3) model2 = ConditionalPoisson(y, x, groups=groups) result2 = model2.fit_regularized(L1_wt=1, alpha=0.2) # Regression test assert_allclose(result2.params, np.r_[0, 0, 0.91697508, 0], rtol=1e-4) # Test with formula df = pd.DataFrame({"y": y, "x1": x[:, 0], "x2": x[:, 1], "x3": x[:, 2], "x4": x[:, 3], "groups": groups}) fml = "y ~ 0 + x1 + x2 + x3 + x4" model3 = ConditionalPoisson.from_formula(fml, groups="groups", data=df) result3 = model3.fit_regularized(L1_wt=1, alpha=0.2) assert_allclose(result2.params, result3.params)
2.53125
3
bert_e/workflow/gitwaterflow/utils.py
tcarmet/bert-e
0
4718
<reponame>tcarmet/bert-e def bypass_incompatible_branch(job): return (job.settings.bypass_incompatible_branch or job.author_bypass.get('bypass_incompatible_branch', False)) def bypass_peer_approval(job): return (job.settings.bypass_peer_approval or job.author_bypass.get('bypass_peer_approval', False)) def bypass_leader_approval(job): return (job.settings.bypass_leader_approval or job.author_bypass.get('bypass_leader_approval', False)) def bypass_author_approval(job): return (job.settings.bypass_author_approval or job.author_bypass.get('bypass_author_approval', False)) def bypass_build_status(job): return (job.settings.bypass_build_status or job.author_bypass.get('bypass_build_status', False)) def bypass_jira_check(job): return (job.settings.bypass_jira_check or job.author_bypass.get('bypass_jira_check', False))
1.945313
2
bkt/library/powerpoint/elements.py
pyro-team/bkt-toolbox
12
4719
<filename>bkt/library/powerpoint/elements.py # -*- coding: utf-8 -*- ''' Created on 02.11.2017 @author: fstallmann ''' from __future__ import absolute_import from collections import deque import bkt from bkt import dotnet Drawing = dotnet.import_drawing() from . import helpers as pplib class TextframeSpinnerBox(bkt.ribbon.RoundingSpinnerBox): ### Instance initialization attr = 'MarginTop' def __init__(self, **kwargs): ''' attr examples: MarginTop, MarginBottom, MarginLeft, MarginRight ''' #self.attr is automatically set through RibbonControl attribute handling self.fallback_value = 0 my_kwargs = dict( size_string = '###', round_cm = True, convert = 'pt_to_cm', get_enabled = bkt.apps.ppt_selection_contains_textframe, ) my_kwargs.update(kwargs) super(TextframeSpinnerBox, self).__init__(**my_kwargs) ### Spinner Box callbacks ### def get_text(self, shapes, selection): value = self.get_attr_from_shapes(shapes, selection) if value is None: #e.g. no textframe detected return None elif int(value) == -2147483648: #replace large negative number (values differ between selected items) with fallback value return self.fallback_value else: return value def on_change(self, shapes, selection, value): self.set_attr_for_shapes(shapes, selection, value) ### Getter Methods ### def get_attr_from_shapes(self, shapes, selection): ''' Get attr for shapes ''' for textframe in pplib.iterate_shape_textframes(shapes): try: return self.get_attr_from_textframe(textframe) except: # produces error for certain chart types, e.g. Treemap continue return None def get_attr_from_textframe(self, textframe): return getattr(textframe, self.attr) ### Setter methods ### def set_attr_for_shapes(self, shapes, selection, value): ''' Set attr for shapes ''' value = max(0,value) for textframe in pplib.iterate_shape_textframes(shapes): self.set_attr_for_textframe(textframe, value) def set_attr_for_textframe(self, textframe, value): setattr(textframe, self.attr, value) class ParagraphFormatSpinnerBox(bkt.ribbon.RoundingSpinnerBox): ### Instance initialization attr = 'SpaceBefore' def __init__(self, **kwargs): ''' attr examples: SpaceBefore, SpaceAfter, LeftIndent, FirstLineIndent, LineSpacing ''' #self.attr is automatically set through RibbonControl attribute handling self.fallback_value = 0 my_kwargs = dict( size_string = '-###', get_enabled = bkt.apps.ppt_selection_contains_textframe, ) if self.attr in ["SpaceBefore", "SpaceAfter", "SpaceWithin"]: my_kwargs["round_pt"] = True else: my_kwargs["round_cm"] = True my_kwargs["convert"] = "pt_to_cm" if self.attr in ["LeftIndent", "FirstLineIndent"]: my_kwargs["big_step"] = 0.25 my_kwargs["small_step"] = 0.125 my_kwargs["rounding_factor"] = 0.125 my_kwargs.update(kwargs) super(ParagraphFormatSpinnerBox, self).__init__(**my_kwargs) ### Spinner Box callbacks ### def get_text(self, shapes, selection): value = self.get_attr_from_shapes(shapes, selection) if value is None: #e.g. no textframe detected return None elif int(value) == -2147483648: #replace large negative number (values differ between selected items) with fallback value return self.fallback_value else: return value def on_change(self, shapes, selection, value): self.set_attr_for_shapes(shapes, selection, value) ### Getter Methods ### def get_attr_from_shapes(self, shapes, selection): if selection.Type == 3: # text selected try: # produces error if no text is selected return self._get_attr(selection.TextRange2.Paragraphs(1,1).ParagraphFormat) except: try: # produces error if there is no textrange, e.g. selection within a chart return self._get_attr(selection.TextRange2.ParagraphFormat) except: return None else: # shapes selected for textframe in pplib.iterate_shape_textframes(shapes): try: value = self.get_attr_from_textrange(textframe.TextRange) except: # produces error for certain chart types, e.g. Treemap continue try: if int(value) == -2147483648: #different values for each paragraph, so get value from first paragraph value = self._get_attr(textframe.TextRange.Paragraphs(1,1).ParagraphFormat) except: pass return value return None def get_attr_from_textrange(self, textrange): return self._get_attr(textrange.ParagraphFormat) def _get_attr(self, par_format): if self.attr in ["SpaceBefore", "SpaceAfter", "SpaceWithin"]: if (self.attr == "SpaceBefore" and par_format.LineRuleBefore == 0) or (self.attr == "SpaceAfter" and par_format.LineRuleAfter == 0) or (self.attr == "SpaceWithin" and par_format.LineRuleWithin == 0): self.huge_step = 10 self.big_step = 3 self.small_step = 1 self.round_at = 0 else: self.huge_step = 0.5 self.big_step = 0.2 self.small_step = 0.1 self.round_at = 1 return getattr(par_format, self.attr) ### Setter methods ### def set_attr_for_shapes(self, shapes, selection, value): if self.attr != "FirstLineIndent": #FirstLineIndent can be negative! value = max(0,value) if selection.Type == 3: # text selected self.set_attr_for_textrange(selection.TextRange2, value) #need to use TextRange2 as TextRange does not contain LeftIndent, etc. else: for textframe in pplib.iterate_shape_textframes(shapes): self.set_attr_for_textrange(textframe.TextRange, value) def set_attr_for_textrange(self, textrange, value): #using textrange instead of textframe! if self.attr == "SpaceBefore" and textrange.ParagraphFormat.LineRuleBefore == -2: #if values differ, set the same value as in the first paragraph textrange.ParagraphFormat.LineRuleBefore = textrange.Paragraphs(1,1).ParagraphFormat.LineRuleBefore if self.attr == "SpaceAfter" and textrange.ParagraphFormat.LineRuleAfter == -2: #if values differ, set the same value as in the first paragraph textrange.ParagraphFormat.LineRuleAfter = textrange.Paragraphs(1,1).ParagraphFormat.LineRuleAfter if self.attr == "SpaceWithin" and textrange.ParagraphFormat.LineRuleWithin == -2: #if values differ, set the same value as in the first paragraph textrange.ParagraphFormat.LineRuleWithin = textrange.Paragraphs(1,1).ParagraphFormat.LineRuleWithin setattr(textrange.ParagraphFormat, self.attr, value) class PPTSymbolsSettings(object): recent_symbols = deque(bkt.settings.get("bkt.symbols.recent_symbols", []), maxlen=3) convert_into_shape = bkt.settings.get("bkt.symbols.convert_into_shape", True) #always convert newly inserted symbols into shapes convert_into_bitmap = bkt.settings.get("bkt.symbols.convert_into_bitmap", False) #always convert newly inserted symbols into bitmap picture unicode_font = bkt.settings.get("bkt.symbols.unicode_font", None) #insert unicode characters as symbol with special font (e.g. Arial Unicode) @classmethod def add_to_recent(cls, item): try: #try to remove if already exists and add to beginning cls.recent_symbols.remove(item) cls.recent_symbols.append(item) except ValueError: cls.recent_symbols.append(item) bkt.settings["bkt.symbols.recent_symbols"] = cls.recent_symbols @classmethod def switch_unicode_font(cls, font=None): cls.unicode_font = font #if font else SymbolsGallery.fallback_font bkt.settings["bkt.symbols.unicode_font"] = cls.unicode_font @classmethod def convert_into_text(cls): return not (cls.convert_into_shape or cls.convert_into_bitmap) @classmethod def switch_convert_into_text(cls, pressed): cls.convert_into_shape = False cls.convert_into_bitmap = False bkt.settings["bkt.symbols.convert_into_shape"] = cls.convert_into_shape bkt.settings["bkt.symbols.convert_into_bitmap"] = cls.convert_into_bitmap @classmethod def switch_convert_into_shape(cls, pressed): cls.convert_into_shape = pressed cls.convert_into_bitmap = False bkt.settings["bkt.symbols.convert_into_shape"] = cls.convert_into_shape bkt.settings["bkt.symbols.convert_into_bitmap"] = cls.convert_into_bitmap @classmethod def get_convert_into_shape(cls): return (cls.convert_into_shape or bkt.get_key_state(bkt.KeyCodes.SHIFT)) and not bkt.get_key_state(bkt.KeyCodes.CTRL) @classmethod def switch_convert_into_bitmap(cls, pressed): cls.convert_into_shape = False cls.convert_into_bitmap = pressed bkt.settings["bkt.symbols.convert_into_shape"] = cls.convert_into_shape bkt.settings["bkt.symbols.convert_into_bitmap"] = cls.convert_into_bitmap @classmethod def get_convert_into_bitmap(cls): return (cls.convert_into_bitmap or bkt.get_key_state(bkt.KeyCodes.CTRL)) and not bkt.get_key_state(bkt.KeyCodes.SHIFT) class PPTSymbolsGallery(bkt.ribbon.SymbolsGallery): @property def fallback_font(self): return PPTSymbolsSettings.unicode_font or bkt.ribbon.SymbolsGallery.fallback_font def on_action_indexed(self, selected_item, index, context, selection, **kwargs): ''' create numberd shape according of settings in clicked element ''' item = self.symbols[index] self._add_to_recent(item) shift_or_ctrl = bkt.get_key_state(bkt.KeyCodes.CTRL) or bkt.get_key_state(bkt.KeyCodes.SHIFT) if selection.Type == 3 and not shift_or_ctrl: #text selected selection.TextRange2.Text = "" #remove selected text first and then insert symbol self.insert_symbol_into_text(selection.TextRange2, item) elif PPTSymbolsSettings.convert_into_text() and selection.Type == 2 and not shift_or_ctrl: #shapes selected self.insert_symbol_into_shapes(pplib.get_shapes_from_selection(selection), item) else: #convert into shape or bitmap if PPTSymbolsSettings.get_convert_into_bitmap(): self.create_symbol_bitmap(selection.SlideRange(1), item) else: self.create_symbol_shape(selection.SlideRange(1), item) def _add_to_recent(self, item): PPTSymbolsSettings.add_to_recent(item) def insert_symbol_into_text(self, textrange, item): if item[0] or PPTSymbolsSettings.unicode_font is not None: #font name is given, then insert as symbol font = item[0] or self.fallback_font try: char_number = ord(item[1]) #ord does not work for higher level unicode, e.g. emojis, and throws TypeError if char_number > 61695: #for higher numbers (f0ff works, f100 doesnt work) InsertSymbol does not work anymore. Also the default ppt symbol-picker only shows unicode chars til f0ff. raise TypeError("character number to large for InsertSymbol") #fallback to InsertAfter placeholder_char = textrange.InsertAfter("X") #append placeholder symbol so that InsertSymbol behaves the same as InsertAfter return placeholder_char.InsertSymbol(font, char_number, -1) #symbol: FontName, CharNumber (decimal), Unicode=True except TypeError: char_inserted = textrange.InsertAfter(item[1]) #append symbol text #so, NameFarEast and NameComplexScript should be writable, but they are not if InsertSymbol is used before (it remains the font of the symbol). only way to replace these values and correctly show icon is setting it to '+mn-..' char_inserted.Font.NameFarEast = "+mn-ea" char_inserted.Font.NameComplexScript = "+mn-cs" char_inserted.Font.Name = font #font name return char_inserted else: return textrange.InsertAfter(item[1]) #append symbol text # if item[0]: # char_inserted.Font.Name = item[0] #font name def insert_symbol_into_shapes(self, shapes, item): #pplib.iterate_shape_textframes(shapes, lambda textframe: self.insert_symbol_into_text(textframe.TextRange, item)) for textframe in pplib.iterate_shape_textframes(shapes): self.insert_symbol_into_text(textframe.TextRange, item) # for shape in shapes: # if shape.HasTextFrame == -1: # self.insert_symbol_into_text(shape.TextFrame2.TextRange, item) def create_symbol_shape(self, slide, item): shape = slide.shapes.addTextbox( #office.MsoAutoShapeType.msoShapeRectangle.value__, 1, 100,100,200,200) shape.TextFrame2.WordWrap = 0 shape.TextFrame2.AutoSize = 1 #ppAutoSizeShapeToFitText shape.TextFrame2.MarginBottom = 0 shape.TextFrame2.MarginTop = 0 shape.TextFrame2.MarginLeft = 0 shape.TextFrame2.MarginRight = 0 self.insert_symbol_into_text(shape.TextFrame2.TextRange, item) # if item[0]: # shape.TextFrame.TextRange.Font.Name = item[0] #font name # shape.TextFrame.TextRange.Text = item[1] #symbol text if PPTSymbolsSettings.get_convert_into_shape(): #convert into shape try: orig_fontsize = shape.TextFrame2.TextRange.Font.Size shape.TextFrame2.TextRange.Font.Size = 60 shape.TextFrame2.TextRange.ParagraphFormat.Bullet.Visible = 0 new_shape = pplib.convert_text_into_shape(shape) new_shape.TextFrame2.TextRange.Font.Size = orig_fontsize except: shape.select() else: new_shape.select() else: shape.select() def create_symbol_bitmap(self, slide, item): import tempfile, os font = item[0] or self.fallback_font img = bkt.ribbon.SymbolsGallery.create_symbol_image(font, item[1], 400, None) tmpfile = os.path.join(tempfile.gettempdir(), "bkt-symbol.png") img.Save(tmpfile, Drawing.Imaging.ImageFormat.Png) shape = slide.shapes.AddPicture(tmpfile, 0, -1, 200, 200) #FileName, LinkToFile, SaveWithDocument, Left, Top shape.select() os.remove(tmpfile) class PPTSymbolsGalleryRecent(PPTSymbolsGallery): @property def symbols(self): return PPTSymbolsSettings.recent_symbols @symbols.setter def symbols(self, value): pass def get_item_image(self, index): try: return super(PPTSymbolsGalleryRecent, self).get_item_image(index) except: return super(PPTSymbolsGalleryRecent, self).create_symbol_image("Arial", "?") def button_get_label(self, index): try: return self.symbols[index][2] except: return "Zuletzt verwendet: Undefined" def button_get_visible(self, index): try: return self.symbols[index] is not None except: return False def get_index_as_button(self, index): return bkt.ribbon.Button( id="{}_button_{}".format(self.id, index), get_label=bkt.Callback(lambda: self.button_get_label(index)), on_action=bkt.Callback(lambda context, selection: self.on_action_indexed(None, index, context, selection)), get_image=bkt.Callback(lambda: self.get_item_image(index)), get_visible=bkt.Callback(lambda: self.button_get_visible(index)), ) class LocpinGallery(bkt.ribbon.Gallery): def __init__(self, locpin=None, item_supertip="Shape-Fixpunkt bzw. Fixierung bei Änderung {}", **kwargs): self.locpin = locpin or pplib.GlobalLocPin self.items = [ ("fix_locpin_tl", "Oben-links", item_supertip.format("oben-links")), ("fix_locpin_tm", "Oben-mitte", item_supertip.format("oben-mitte")), ("fix_locpin_tr", "Oben-rechts", item_supertip.format("oben-rechts")), ("fix_locpin_ml", "Mitte-links", item_supertip.format("mitte-links")), ("fix_locpin_mm", "Mitte-mitte", item_supertip.format("mitte-mitte")), ("fix_locpin_mr", "Mitte-rechts", item_supertip.format("mitte-rechts")), ("fix_locpin_bl", "Unten-links", item_supertip.format("unten-links")), ("fix_locpin_bm", "Unten-mitte", item_supertip.format("unten-mitte")), ("fix_locpin_br", "Unten-rechts", item_supertip.format("unten-rechts")), ] my_kwargs = dict( # get_enabled=bkt.apps.ppt_shapes_or_text_selected, columns="3", item_height="24", item_width="24", show_item_label=False, on_action_indexed = bkt.Callback(self.locpin_on_action_indexed), get_selected_item_index = bkt.Callback(lambda: self.locpin.index), get_item_count = bkt.Callback(lambda: len(self.items)), get_item_label = bkt.Callback(lambda index: self.items[index][1]), get_item_image = bkt.Callback(self.locpin_get_image, context=True), get_item_screentip = bkt.Callback(lambda index: self.items[index][1]), get_item_supertip = bkt.Callback(lambda index: self.items[index][2]), # children = [ # Item(image=gal_item[0], screentip=gal_item[1], supertip=gal_item[2]) # for gal_item in self.items # ] ) if not "image" in kwargs and not "image_mso" in kwargs: my_kwargs["get_image"] = bkt.Callback(self.locpin_get_image, context=True) my_kwargs.update(kwargs) super(LocpinGallery, self).__init__(**my_kwargs) def locpin_on_action_indexed(self, selected_item, index): self.locpin.index = index def locpin_get_image(self, context, index=None): if index is None: return context.python_addin.load_image(self.items[self.locpin.index][0]) else: return context.python_addin.load_image(self.items[index][0]) class PositionGallery(bkt.ribbon.Gallery): # items: [label, position, reference] # position: [left, top, width, height] # values can be absolute or percentage # reference: CONTENTE / SLIDE / ABS # values are converted according to reference items = [ [u"<NAME>", [ 0, 0, 1, 1], 'CONTENT'], [u"2/3 Links", [ 0, 0, 2./3, 1], 'CONTENT'], [u"2/3 Rechts", [1./3, 0, 2./3, 1], 'CONTENT'], [u"1/2 Links", [ 0, 0, .5, 1], 'CONTENT'], [u"1/2 Mitte", [.25, 0, .5, 1], 'CONTENT'], [u"1/2 Rechts", [ .5, 0, .5, 1], 'CONTENT'], [u"1/3 Links", [ 0, 0, 1./3, 1], 'CONTENT'], [u"1/3 Mitte", [1./3, 0, 1./3, 1], 'CONTENT'], [u"1/3 Rechts", [2./3, 0, 1./3, 1], 'CONTENT'], [u"1/6 Oben", [ 0, 0, 1, 1./6], 'CONTENT'], [u"1/6 Unten", [ 0, 5./6, 1, 1./6], 'CONTENT'] ] def __init__(self, positions=None, label="Standardpositionen", columns=3, **kwargs): self.items = positions or PositionGallery.items super(PositionGallery, self).__init__( label = label, columns = columns, image_mso='PositionAnchoringGallery', supertip=u"Positioniere die ausgewählten Shapes auf eine Standardposition.", children=[ bkt.ribbon.Button( label="Benutzerdef. Bereich festlegen", supertip="Der benutzerdefinierte Bereich wird anhand des gewählten Shapes festgelegt. Dieser Bereich ist anschließend über die Gallery wählbar und wird dauerhaft in der aktuellen Prästentation vorgehalten.", on_action=bkt.Callback(self.set_userdefined_area), get_enabled = bkt.get_enabled_auto ) ], **kwargs ) def on_action_indexed(self, selected_item, index, context, **kwargs): ''' reposition shapes according of settings in clicked element ''' item = self.items[index] position = item[1] reference = item[2] #self.change_position(selection, shapes, item[1]) # reference size if reference == 'CONTENT': ref_left,ref_top,ref_width,ref_height = pplib.slide_content_size(context.slide) else: # SLIDE / ABS page_setup = context.presentation.PageSetup ref_left,ref_top = 0, 0 ref_width,ref_height = page_setup.SlideWidth, page_setup.SlideHeight # target size left,top,width,height = self.rect_from_definition(position, ref_frame=[ref_left,ref_top,ref_width, ref_height]) frame = pplib.BoundingFrame.from_rect(left, top, width, height) if 'on_position_change' in self._callbacks: if context: return context.invoke_callback(self._callbacks['on_position_change'], target_frame=frame, **kwargs) def get_item_count(self, presentation): self.init_userdefined_area_item(presentation) return len(self.items) # def get_enabled(self, shapes): # return True # def get_item_label(self, index): # item = self.items[index] # return "%s" % getattr(NumberedShapes, 'label_' + item['label'])[index%self.columns] def get_item_image(self, index, presentation): ''' creates an item image with target area according to settings in the specified item ''' # retrieve item-settings item = self.items[index] return self.create_image(item[1], item[2], presentation) def get_item_screentip(self, index): # retrieve item-settings item = self.items[index] return 'Positionierung: ' + item[0] def get_item_supertip(self, index): return 'Verwende angezeigten Position/Größe.' def create_image(self, position, reference, presentation): # create bitmap, define pen/brush height = 40 width = height*16./9 img = Drawing.Bitmap(width, height) g = Drawing.Graphics.FromImage(img) # reference size if reference == 'CONTENT': v_offset = height/5 v_ref = (height*4)/5 left,top,fill_width,fill_height = self.rect_from_definition(position, ref_frame=[0,v_offset,width, v_ref]) else: # SLIDE / ABS ref_width,ref_height = presentation.PageSetup.SlideWidth, presentation.PageSetup.SlideHeight left,top,fill_width,fill_height = self.rect_from_definition(position, ref_frame=[0,0,ref_width, ref_height]) left = left /ref_width * width fill_width = fill_width /ref_width * width top = top /ref_height * height fill_height = fill_height/ref_height * height color = Drawing.ColorTranslator.FromHtml('#ffdd0000') brush = Drawing.SolidBrush(color) g.FillRectangle(brush, Drawing.Rectangle(round(left),round(top), round(fill_width), round(fill_height))) color = Drawing.ColorTranslator.FromHtml('#ff999999') pen = Drawing.Pen(color,1) g.DrawRectangle(pen, Drawing.Rectangle(0,0, width-1, height/5-1)) g.DrawRectangle(pen, Drawing.Rectangle(0,0, width-1, height-1)) return img def rect_from_definition(self, pos_definition, ref_frame=[0,0,640,480]): left = self.length_from_definition(pos_definition[0], ref_frame[2]) + ref_frame[0] top = self.length_from_definition(pos_definition[1], ref_frame[3]) + ref_frame[1] width = self.length_from_definition(pos_definition[2], ref_frame[2]) height = self.length_from_definition(pos_definition[3], ref_frame[3]) return left, top, width, height def length_from_definition(self, length_definition, reference): if type(length_definition) == list: # allow [150, 50%] l = 0 for ldef in length_definition: l += self.length_from_definition(ldef, reference) return l elif type(length_definition) in [int, float, long]: if length_definition < 0: # negative values specify distance 'from right' return reference - self.length_from_definition(-length_definition, reference) elif length_definition <= 1: # percentage values return reference * length_definition else: # absolute values return length_definition else: return 10 ## userdefined area def set_userdefined_area(self, presentation, shapes): if len(shapes) == 1: pplib.ContentArea.define_contentarea(presentation, shapes[0]) else: frame = pplib.BoundingFrame.from_shapes(shapes) pplib.ContentArea.define_contentarea(presentation, frame) self.init_userdefined_area_item(presentation) def init_userdefined_area_item(self, presentation): #due to performance check first if tag exists at all if pplib.ContentArea.isset_contentarea(presentation): left, top, width, height = pplib.ContentArea.read_contentarea(presentation) if len(self.items) == 12: self.items.pop() self.items.append([u"Benutzerdef. Bereich", [left, top, width, height], 'ABS'])
1.90625
2
sc2/unit.py
guliverza/AdditionalPylons
0
4720
<filename>sc2/unit.py from __future__ import annotations import warnings from typing import Any, Dict, List, Optional, Set, Tuple, Union, TYPE_CHECKING from .cache import property_immutable_cache, property_mutable_cache from .constants import ( transforming, IS_STRUCTURE, IS_LIGHT, IS_ARMORED, IS_BIOLOGICAL, IS_MECHANICAL, IS_MASSIVE, IS_PSIONIC, UNIT_BATTLECRUISER, UNIT_ORACLE, TARGET_GROUND, TARGET_AIR, TARGET_BOTH, IS_SNAPSHOT, IS_VISIBLE, IS_MINE, IS_ENEMY, IS_CLOAKED, IS_REVEALED, CAN_BE_ATTACKED, IS_CARRYING_MINERALS, IS_CARRYING_VESPENE, IS_CARRYING_RESOURCES, IS_ATTACKING, IS_PATROLLING, IS_GATHERING, IS_RETURNING, IS_COLLECTING, IS_CONSTRUCTING_SCV, IS_REPAIRING, IS_DETECTOR, UNIT_PHOTONCANNON, UNIT_COLOSSUS, ) from .data import Alliance, Attribute, CloakState, DisplayType, Race, TargetType, warpgate_abilities, TargetType, Target from .ids.ability_id import AbilityId from .ids.buff_id import BuffId from .ids.upgrade_id import UpgradeId from .ids.unit_typeid import UnitTypeId from .position import Point2, Point3 from .unit_command import UnitCommand warnings.simplefilter("once") if TYPE_CHECKING: from .bot_ai import BotAI from .game_data import AbilityData class UnitOrder: @classmethod def from_proto(cls, proto, bot_object: BotAI): return cls( bot_object._game_data.abilities[proto.ability_id], (proto.target_world_space_pos if proto.HasField("target_world_space_pos") else proto.target_unit_tag), proto.progress, ) def __init__(self, ability: AbilityData, target, progress: float = None): """ :param ability: :param target: :param progress: """ self.ability = ability self.target = target self.progress = progress def __repr__(self) -> str: return f"UnitOrder({self.ability}, {self.target}, {self.progress})" class Unit: def __init__(self, proto_data, bot_object: BotAI): """ :param proto_data: :param bot_object: """ self._proto = proto_data self._bot_object = bot_object # Used by property_immutable_cache self.cache = {} def __repr__(self) -> str: """ Returns string of this form: Unit(name='SCV', tag=4396941328). """ return f"Unit(name={self.name !r}, tag={self.tag})" @property_immutable_cache def type_id(self) -> UnitTypeId: """ UnitTypeId found in sc2/ids/unit_typeid. Caches all type_ids of the same unit type. """ unit_type = self._proto.unit_type if unit_type not in self._bot_object._game_data.unit_types: self._bot_object._game_data.unit_types[unit_type] = UnitTypeId(unit_type) return self._bot_object._game_data.unit_types[unit_type] @property_immutable_cache def _type_data(self) -> "UnitTypeData": """ Provides the unit type data. """ return self._bot_object._game_data.units[self._proto.unit_type] @property def name(self) -> str: """ Returns the name of the unit. """ return self._type_data.name @property def race(self) -> Race: """ Returns the race of the unit """ return Race(self._type_data._proto.race) @property def tag(self) -> int: """ Returns the unique tag of the unit. """ return self._proto.tag @property def is_structure(self) -> bool: """ Checks if the unit is a structure. """ return IS_STRUCTURE in self._type_data.attributes @property def is_light(self) -> bool: """ Checks if the unit has the 'light' attribute. """ return IS_LIGHT in self._type_data.attributes @property def is_armored(self) -> bool: """ Checks if the unit has the 'armored' attribute. """ return IS_ARMORED in self._type_data.attributes @property def is_biological(self) -> bool: """ Checks if the unit has the 'biological' attribute. """ return IS_BIOLOGICAL in self._type_data.attributes @property def is_mechanical(self) -> bool: """ Checks if the unit has the 'mechanical' attribute. """ return IS_MECHANICAL in self._type_data.attributes @property def is_massive(self) -> bool: """ Checks if the unit has the 'massive' attribute. """ return IS_MASSIVE in self._type_data.attributes @property def is_psionic(self) -> bool: """ Checks if the unit has the 'psionic' attribute. """ return IS_PSIONIC in self._type_data.attributes @property def tech_alias(self) -> Optional[List[UnitTypeId]]: """ Building tech equality, e.g. OrbitalCommand is the same as CommandCenter For Hive, this returns [UnitTypeId.Hatchery, UnitTypeId.Lair] For SCV, this returns None """ return self._type_data.tech_alias @property def unit_alias(self) -> Optional[UnitTypeId]: """ Building type equality, e.g. FlyingOrbitalCommand is the same as OrbitalCommand For flying OrbitalCommand, this returns UnitTypeId.OrbitalCommand For SCV, this returns None """ return self._type_data.unit_alias @property_immutable_cache def _weapons(self): """ Returns the weapons of the unit. """ try: return self._type_data._proto.weapons except: return None @property_immutable_cache def can_attack(self) -> bool: """ Checks if the unit can attack at all. """ # TODO BATTLECRUISER doesnt have weapons in proto?! return bool(self._weapons) or self.type_id in {UNIT_BATTLECRUISER, UNIT_ORACLE} @property_immutable_cache def can_attack_both(self) -> bool: """ Checks if the unit can attack both ground and air units. """ if self.type_id == UNIT_BATTLECRUISER: return True if self._weapons: return any(weapon.type in TARGET_BOTH for weapon in self._weapons) return False @property_immutable_cache def can_attack_ground(self) -> bool: """ Checks if the unit can attack ground units. """ if self.type_id in {UNIT_BATTLECRUISER, UNIT_ORACLE}: return True if self._weapons: return any(weapon.type in TARGET_GROUND for weapon in self._weapons) return False @property_immutable_cache def ground_dps(self) -> Union[int, float]: """ Returns the dps against ground units. Does not include upgrades. """ if self.can_attack_ground: weapon = next((weapon for weapon in self._weapons if weapon.type in TARGET_GROUND), None) if weapon: return (weapon.damage * weapon.attacks) / weapon.speed return 0 @property_immutable_cache def ground_range(self) -> Union[int, float]: """ Returns the range against ground units. Does not include upgrades. """ if self.type_id == UNIT_ORACLE: return 4 if self.type_id == UNIT_BATTLECRUISER: return 6 if self.can_attack_ground: weapon = next((weapon for weapon in self._weapons if weapon.type in TARGET_GROUND), None) if weapon: return weapon.range return 0 @property_immutable_cache def can_attack_air(self) -> bool: """ Checks if the unit can air attack at all. Does not include upgrades. """ if self.type_id == UNIT_BATTLECRUISER: return True if self._weapons: return any(weapon.type in TARGET_AIR for weapon in self._weapons) return False @property_immutable_cache def air_dps(self) -> Union[int, float]: """ Returns the dps against air units. Does not include upgrades. """ if self.can_attack_air: weapon = next((weapon for weapon in self._weapons if weapon.type in TARGET_AIR), None) if weapon: return (weapon.damage * weapon.attacks) / weapon.speed return 0 @property_immutable_cache def air_range(self) -> Union[int, float]: """ Returns the range against air units. Does not include upgrades. """ if self.type_id == UNIT_BATTLECRUISER: return 6 if self.can_attack_air: weapon = next((weapon for weapon in self._weapons if weapon.type in TARGET_AIR), None) if weapon: return weapon.range return 0 @property_immutable_cache def bonus_damage(self): """ Returns a tuple of form '(bonus damage, armor type)' if unit does 'bonus damage' against 'armor type'. Possible armor typs are: 'Light', 'Armored', 'Biological', 'Mechanical', 'Psionic', 'Massive', 'Structure'. """ # TODO: Consider units with ability attacks (Oracle, Baneling) or multiple attacks (Thor). if self._weapons: for weapon in self._weapons: if weapon.damage_bonus: b = weapon.damage_bonus[0] return (b.bonus, Attribute(b.attribute).name) else: return None @property def armor(self) -> Union[int, float]: """ Returns the armor of the unit. Does not include upgrades """ return self._type_data._proto.armor @property def sight_range(self) -> Union[int, float]: """ Returns the sight range of the unit. """ return self._type_data._proto.sight_range @property def movement_speed(self) -> Union[int, float]: """ Returns the movement speed of the unit. Does not include upgrades or buffs. """ return self._type_data._proto.movement_speed @property def is_mineral_field(self) -> bool: """ Checks if the unit is a mineral field. """ return self._type_data.has_minerals @property def is_vespene_geyser(self) -> bool: """ Checks if the unit is a non-empty vespene geyser or gas extraction building. """ return self._type_data.has_vespene @property def health(self) -> Union[int, float]: """ Returns the health of the unit. Does not include shields. """ return self._proto.health @property def health_max(self) -> Union[int, float]: """ Returns the maximum health of the unit. Does not include shields. """ return self._proto.health_max @property def health_percentage(self) -> Union[int, float]: """ Returns the percentage of health the unit has. Does not include shields. """ if self._proto.health_max == 0: return 0 return self._proto.health / self._proto.health_max @property def shield(self) -> Union[int, float]: """ Returns the shield points the unit has. Returns 0 for non-protoss units. """ return self._proto.shield @property def shield_max(self) -> Union[int, float]: """ Returns the maximum shield points the unit can have. Returns 0 for non-protoss units. """ return self._proto.shield_max @property def shield_percentage(self) -> Union[int, float]: """ Returns the percentage of shield points the unit has. Returns 0 for non-protoss units. """ if self._proto.shield_max == 0: return 0 return self._proto.shield / self._proto.shield_max @property def energy(self) -> Union[int, float]: """ Returns the amount of energy the unit has. Returns 0 for units without energy. """ return self._proto.energy @property def energy_max(self) -> Union[int, float]: """ Returns the maximum amount of energy the unit can have. Returns 0 for units without energy. """ return self._proto.energy_max @property def energy_percentage(self) -> Union[int, float]: """ Returns the percentage of amount of energy the unit has. Returns 0 for units without energy. """ if self._proto.energy_max == 0: return 0 return self._proto.energy / self._proto.energy_max @property def is_snapshot(self) -> bool: """ Checks if the unit is only available as a snapshot for the bot. Enemy buildings that have been scouted and are in the fog of war or attacking enemy units on higher, not visible ground appear this way. """ return self._proto.display_type == IS_SNAPSHOT @property def is_visible(self) -> bool: """ Checks if the unit is visible for the bot. NOTE: This means the bot has vision of the position of the unit! It does not give any information about the cloak status of the unit.""" return self._proto.display_type == IS_VISIBLE @property def alliance(self) -> Alliance: """ Returns the team the unit belongs to. """ return self._proto.alliance @property def is_mine(self) -> bool: """ Checks if the unit is controlled by the bot. """ return self._proto.alliance == IS_MINE @property def is_enemy(self) -> bool: """ Checks if the unit is hostile. """ return self._proto.alliance == IS_ENEMY @property def owner_id(self) -> int: """ Returns the owner of the unit. This is a value of 1 or 2 in a two player game. """ return self._proto.owner @property def position_tuple(self) -> Tuple[float, float]: """ Returns the 2d position of the unit as tuple without conversion to Point2. """ return self._proto.pos.x, self._proto.pos.y @property_immutable_cache def position(self) -> Point2: """ Returns the 2d position of the unit. """ return Point2.from_proto(self._proto.pos) @property_immutable_cache def position3d(self) -> Point3: """ Returns the 3d position of the unit. """ return Point3.from_proto(self._proto.pos) def distance_to(self, p: Union[Unit, Point2, Point3]) -> Union[int, float]: """ Using the 2d distance between self and p. To calculate the 3d distance, use unit.position3d.distance_to(p) :param p: """ if isinstance(p, Unit): return self._bot_object._distance_squared_unit_to_unit(self, p) ** 0.5 return self._bot_object.distance_math_hypot(self.position_tuple, p) def target_in_range(self, target: Unit, bonus_distance: Union[int, float] = 0) -> bool: """ Checks if the target is in range. Includes the target's radius when calculating distance to target. :param target: :param bonus_distance: """ # TODO: Fix this because immovable units (sieged tank, planetary fortress etc.) have a little lower range than this formula if self.can_attack_ground and not target.is_flying: unit_attack_range = self.ground_range elif self.can_attack_air and (target.is_flying or target.type_id == UNIT_COLOSSUS): unit_attack_range = self.air_range else: return False return ( self._bot_object._distance_squared_unit_to_unit(self, target) <= (self.radius + target.radius + unit_attack_range + bonus_distance) ** 2 ) def in_ability_cast_range( self, ability_id: AbilityId, target: Union[Unit, Point2], bonus_distance: float = 0 ) -> bool: """ Test if a unit is able to cast an ability on the target without checking ability cooldown (like stalker blink) or if ability is made available through research (like HT storm). :param ability_id: :param target: :param bonus_distance: """ cast_range = self._bot_object._game_data.abilities[ability_id.value]._proto.cast_range assert cast_range > 0, f"Checking for an ability ({ability_id}) that has no cast range" ability_target_type = self._bot_object._game_data.abilities[ability_id.value]._proto.target # For casting abilities that target other units, like transfuse, feedback, snipe, yamato if ability_target_type in {Target.Unit.value, Target.PointOrUnit.value} and isinstance(target, Unit): return ( self._bot_object._distance_squared_unit_to_unit(self, target) <= (cast_range + self.radius + target.radius + bonus_distance) ** 2 ) # For casting abilities on the ground, like queen creep tumor, ravager bile, HT storm if ability_target_type in {Target.Point.value, Target.PointOrUnit.value} and isinstance( target, (Point2, tuple) ): return ( self._bot_object._distance_pos_to_pos(self.position_tuple, target) <= cast_range + self.radius + bonus_distance ) return False @property def facing(self) -> Union[int, float]: """ Returns direction the unit is facing as a float in range [0,2π). 0 is in direction of x axis.""" return self._proto.facing # TODO: a function that checks if this unit is facing another unit def is_facing_unit(self, other_unit: Unit, angle_error: float = 1e-3) -> bool: """ Function not completed yet :param other_unit: :param angle_error: """ pass @property def radius(self) -> Union[int, float]: """ Half of unit size. See https://liquipedia.net/starcraft2/Unit_Statistics_(Legacy_of_the_Void) """ return self._proto.radius @property def build_progress(self) -> Union[int, float]: """ Returns completion in range [0,1].""" return self._proto.build_progress @property def is_ready(self) -> bool: """ Checks if the unit is completed. """ return self.build_progress == 1 @property def cloak(self) -> CloakState: """ Returns cloak state. See https://github.com/Blizzard/s2client-api/blob/d9ba0a33d6ce9d233c2a4ee988360c188fbe9dbf/include/sc2api/sc2_unit.h#L95 """ return self._proto.cloak @property def is_cloaked(self) -> bool: """ Checks if the unit is cloaked. """ return self._proto.cloak in IS_CLOAKED @property def is_revealed(self) -> bool: """ Checks if the unit is revealed. """ return self._proto.cloak is IS_REVEALED @property def can_be_attacked(self) -> bool: """ Checks if the unit is revealed or not cloaked and therefore can be attacked. """ return self._proto.cloak in CAN_BE_ATTACKED @property_immutable_cache def buffs(self) -> Set: """ Returns the set of current buffs the unit has. """ return {BuffId(buff_id) for buff_id in self._proto.buff_ids} @property_immutable_cache def is_carrying_minerals(self) -> bool: """ Checks if a worker or MULE is carrying (gold-)minerals. """ return not IS_CARRYING_MINERALS.isdisjoint(self.buffs) @property_immutable_cache def is_carrying_vespene(self) -> bool: """ Checks if a worker is carrying vespene gas. """ return not IS_CARRYING_VESPENE.isdisjoint(self.buffs) @property_immutable_cache def is_carrying_resource(self) -> bool: """ Checks if a worker is carrying a resource. """ return not IS_CARRYING_RESOURCES.isdisjoint(self.buffs) @property def detect_range(self) -> Union[int, float]: """ Returns the detection distance of the unit. """ return self._proto.detect_range @property_immutable_cache def is_detector(self) -> bool: """ Checks if the unit is a detector. Has to be completed in order to detect and Photoncannons also need to be powered. """ return self.is_ready and (self.type_id in IS_DETECTOR or self.type_id == UNIT_PHOTONCANNON and self.is_powered) @property def radar_range(self) -> Union[int, float]: return self._proto.radar_range @property def is_selected(self) -> bool: """ Checks if the unit is currently selected. """ return self._proto.is_selected @property def is_on_screen(self) -> bool: """ Checks if the unit is on the screen. """ return self._proto.is_on_screen @property def is_blip(self) -> bool: """ Checks if the unit is detected by a sensor tower. """ return self._proto.is_blip @property def is_powered(self) -> bool: """ Checks if the unit is powered by a pylon or warppism. """ return self._proto.is_powered @property def is_active(self) -> bool: """ Checks if the unit is currently training or researching. """ return self._proto.is_active # PROPERTIES BELOW THIS COMMENT ARE NOT POPULATED FOR SNAPSHOTS @property def mineral_contents(self) -> int: """ Returns the amount of minerals remaining in a mineral field. """ return self._proto.mineral_contents @property def vespene_contents(self) -> int: """ Returns the amount of gas remaining in a geyser. """ return self._proto.vespene_contents @property def has_vespene(self) -> bool: """ Checks if a geyser has any gas remaining. You can't build extractors on empty geysers. """ return bool(self._proto.vespene_contents) @property def is_flying(self) -> bool: """ Checks if the unit is flying. """ return self._proto.is_flying or self.has_buff(BuffId.GRAVITONBEAM) @property def is_burrowed(self) -> bool: """ Checks if the unit is burrowed. """ return self._proto.is_burrowed @property def is_hallucination(self) -> bool: """ Returns True if the unit is your own hallucination or detected. """ return self._proto.is_hallucination @property def attack_upgrade_level(self) -> int: """ Returns the upgrade level of the units attack. # NOTE: Returns 0 for units without a weapon. """ return self._proto.attack_upgrade_level @property def armor_upgrade_level(self) -> int: """ Returns the upgrade level of the units armor. """ return self._proto.armor_upgrade_level @property def shield_upgrade_level(self) -> int: """ Returns the upgrade level of the units shield. # NOTE: Returns 0 for units without a shield. """ return self._proto.shield_upgrade_level @property def buff_duration_remain(self) -> int: """ Returns the amount of remaining frames of the visible timer bar. # NOTE: Returns 0 for units without a timer bar. """ return self._proto.buff_duration_remain @property def buff_duration_max(self) -> int: """ Returns the maximum amount of frames of the visible timer bar. # NOTE: Returns 0 for units without a timer bar. """ return self._proto.buff_duration_max # PROPERTIES BELOW THIS COMMENT ARE NOT POPULATED FOR ENEMIES @property_mutable_cache def orders(self) -> List[UnitOrder]: """ Returns the a list of the current orders. """ return [UnitOrder.from_proto(order, self._bot_object) for order in self._proto.orders] @property_immutable_cache def order_target(self) -> Optional[Union[int, Point2]]: """ Returns the target tag (if it is a Unit) or Point2 (if it is a Position) from the first order, returns None if the unit is idle """ if self.orders: if isinstance(self.orders[0].target, int): return self.orders[0].target else: return Point2.from_proto(self.orders[0].target) return None @property def noqueue(self) -> bool: """ Checks if the unit is idle. """ warnings.warn("noqueue will be removed soon, please use is_idle instead", DeprecationWarning, stacklevel=2) return self.is_idle @property def is_idle(self) -> bool: """ Checks if unit is idle. """ return not self._proto.orders def is_using_ability(self, abilities: Union[AbilityId, Set[AbilityId]]) -> bool: """ Check if the unit is using one of the given abilities. Only works for own units. """ if not self.orders: return False if isinstance(abilities, AbilityId): abilities = {abilities} return self.orders[0].ability.id in abilities @property_immutable_cache def is_moving(self) -> bool: """ Checks if the unit is moving. Only works for own units. """ return self.is_using_ability(AbilityId.MOVE) @property_immutable_cache def is_attacking(self) -> bool: """ Checks if the unit is attacking. Only works for own units. """ return self.is_using_ability(IS_ATTACKING) @property_immutable_cache def is_patrolling(self) -> bool: """ Checks if a unit is patrolling. Only works for own units. """ return self.is_using_ability(IS_PATROLLING) @property_immutable_cache def is_gathering(self) -> bool: """ Checks if a unit is on its way to a mineral field or vespene geyser to mine. Only works for own units. """ return self.is_using_ability(IS_GATHERING) @property_immutable_cache def is_returning(self) -> bool: """ Checks if a unit is returning from mineral field or vespene geyser to deliver resources to townhall. Only works for own units. """ return self.is_using_ability(IS_RETURNING) @property_immutable_cache def is_collecting(self) -> bool: """ Checks if a unit is gathering or returning. Only works for own units. """ return self.is_using_ability(IS_COLLECTING) @property_immutable_cache def is_constructing_scv(self) -> bool: """ Checks if the unit is an SCV that is currently building. Only works for own units. """ return self.is_using_ability(IS_CONSTRUCTING_SCV) @property_immutable_cache def is_transforming(self) -> bool: """ Checks if the unit transforming. Only works for own units. """ return self.type_id in transforming and self.is_using_ability(transforming[self.type_id]) @property_immutable_cache def is_repairing(self) -> bool: """ Checks if the unit is an SCV or MULE that is currently repairing. Only works for own units. """ return self.is_using_ability(IS_REPAIRING) @property def add_on_tag(self) -> int: """ Returns the tag of the addon of unit. """ return self._proto.add_on_tag @property def has_add_on(self) -> bool: """ Checks if unit has an addon attached. """ return bool(self._proto.add_on_tag) @property_immutable_cache def add_on_land_position(self) -> Point2: """ If unit is addon (techlab or reactor), returns the position where a terran building has to land to connect to addon """ return self.position.offset(Point2((-2.5, 0.5))) @property_mutable_cache def passengers(self) -> Set[Unit]: """ Returns the units inside a Bunker, CommandCenter, PlanetaryFortress, Medivac, Nydus, Overlord or WarpPrism. """ return {Unit(unit, self._bot_object) for unit in self._proto.passengers} @property_mutable_cache def passengers_tags(self) -> Set[int]: """ Returns the tags of the units inside a Bunker, CommandCenter, PlanetaryFortress, Medivac, Nydus, Overlord or WarpPrism. """ return {unit.tag for unit in self._proto.passengers} @property def cargo_used(self) -> Union[float, int]: """ Returns how much cargo space is currently used in the unit. Note that some units take up more than one space. """ return self._proto.cargo_space_taken @property def has_cargo(self) -> bool: """ Checks if this unit has any units loaded. """ return bool(self._proto.cargo_space_taken) @property def cargo_size(self) -> Union[float, int]: """ Returns the amount of cargo space the unit needs. """ return self._type_data.cargo_size @property def cargo_max(self) -> Union[float, int]: """ How much cargo space is available at maximum. """ return self._proto.cargo_space_max @property def cargo_left(self) -> Union[float, int]: """ Returns how much cargo space is currently left in the unit. """ return self._proto.cargo_space_max - self._proto.cargo_space_taken @property def assigned_harvesters(self) -> int: """ Returns the number of workers currently gathering resources at a geyser or mining base.""" return self._proto.assigned_harvesters @property def ideal_harvesters(self) -> int: """ Returns the ideal harverster count for unit. 3 for gas buildings, 2*n for n mineral patches on that base.""" return self._proto.ideal_harvesters @property def surplus_harvesters(self) -> int: """ Returns a positive int if unit has too many harvesters mining, a negative int if it has too few mining.""" return self._proto.assigned_harvesters - self._proto.ideal_harvesters @property_immutable_cache def weapon_cooldown(self) -> Union[int, float]: """ Returns the time until the unit can fire again, returns -1 for units that can't attack. Usage: if unit.weapon_cooldown == 0: self.actions.append(unit.attack(target)) elif unit.weapon_cooldown < 0: self.actions.append(unit.move(closest_allied_unit_because_cant_attack)) else: self.actions.append(unit.move(retreatPosition)) """ if self.can_attack: return self._proto.weapon_cooldown return -1 @property def engaged_target_tag(self) -> int: # TODO What does this do? return self._proto.engaged_target_tag # Unit functions def has_buff(self, buff: BuffId) -> bool: """ Checks if unit has buff 'buff'. """ assert isinstance(buff, BuffId), f"{buff} is no BuffId" return buff in self.buffs def train(self, unit: UnitTypeId, queue: bool = False) -> UnitCommand: """ Orders unit to train another 'unit'. Usage: self.actions.append(COMMANDCENTER.train(SCV)) :param unit: :param queue: """ return self(self._bot_object._game_data.units[unit.value].creation_ability.id, queue=queue) def build(self, unit: UnitTypeId, position: Union[Point2, Point3] = None, queue: bool = False) -> UnitCommand: """ Orders unit to build another 'unit' at 'position'. Usage: self.actions.append(SCV.build(COMMANDCENTER, position)) :param unit: :param position: :param queue: """ return self(self._bot_object._game_data.units[unit.value].creation_ability.id, target=position, queue=queue) def research(self, upgrade: UpgradeId, queue: bool = False) -> UnitCommand: """ Orders unit to research 'upgrade'. Requires UpgradeId to be passed instead of AbilityId. :param upgrade: :param queue: """ return self(self._bot_object._game_data.upgrades[upgrade.value].research_ability.id, queue=queue) def warp_in(self, unit: UnitTypeId, position: Union[Point2, Point3]) -> UnitCommand: """ Orders Warpgate to warp in 'unit' at 'position'. :param unit: :param queue: """ normal_creation_ability = self._bot_object._game_data.units[unit.value].creation_ability.id return self(warpgate_abilities[normal_creation_ability], target=position) def attack(self, target: Union[Unit, Point2, Point3], queue: bool = False) -> UnitCommand: """ Orders unit to attack. Target can be a Unit or Point2. Attacking a position will make the unit move there and attack everything on its way. :param target: :param queue: """ return self(AbilityId.ATTACK, target=target, queue=queue) def gather(self, target: Unit, queue: bool = False) -> UnitCommand: """ Orders a unit to gather minerals or gas. 'Target' must be a mineral patch or a gas extraction building. :param target: :param queue: """ return self(AbilityId.HARVEST_GATHER, target=target, queue=queue) def return_resource(self, target: Unit = None, queue: bool = False) -> UnitCommand: """ Orders the unit to return resource. Does not need a 'target'. :param target: :param queue: """ return self(AbilityId.HARVEST_RETURN, target=target, queue=queue) def move(self, position: Union[Point2, Point3], queue: bool = False) -> UnitCommand: """ Orders the unit to move to 'position'. Target can be a Unit (to follow that unit) or Point2. :param position: :param queue: """ return self(AbilityId.MOVE_MOVE, target=position, queue=queue) def scan_move(self, *args, **kwargs) -> UnitCommand: """ Deprecated: This ability redirects to 'AbilityId.ATTACK' """ return self(AbilityId.SCAN_MOVE, *args, **kwargs) def hold_position(self, queue: bool = False) -> UnitCommand: """ Orders a unit to stop moving. It will not move until it gets new orders. :param queue: """ return self(AbilityId.HOLDPOSITION, queue=queue) def stop(self, queue: bool = False) -> UnitCommand: """ Orders a unit to stop, but can start to move on its own if it is attacked, enemy unit is in range or other friendly units need the space. :param queue: """ return self(AbilityId.STOP, queue=queue) def patrol(self, position: Union[Point2, Point3], queue: bool = False) -> UnitCommand: """ Orders a unit to patrol between position it has when the command starts and the target position. Can be queued up to seven patrol points. If the last point is the same as the starting point, the unit will patrol in a circle. :param position: :param queue: """ return self(AbilityId.PATROL, target=position, queue=queue) def repair(self, repair_target: Unit, queue: bool = False) -> UnitCommand: """ Order an SCV or MULE to repair. :param repair_target: :param queue: """ return self(AbilityId.EFFECT_REPAIR, target=repair_target, queue=queue) def __hash__(self): return self.tag def __eq__(self, other): try: return self.tag == other.tag except: return False def __call__(self, ability, target=None, queue: bool = False): return UnitCommand(ability, self, target=target, queue=queue)
2.15625
2
healthy_candies/load/__init__.py
striantafyllouEPFL/healthy-candies
1
4721
from .load import load_data, NUTRI_COLS, load_clean_rel_to_nutri
1.046875
1
simglucose/sensor/cgm.py
mia-jingyi/simglucose
0
4722
<gh_stars>0 # from .noise_gen import CGMNoiseGenerator from .noise_gen import CGMNoise import pandas as pd import logging logger = logging.getLogger(__name__) class CGMSensor(object): def __init__(self, params, seed=None): self._params = params self.name = params.Name self.sample_time = params.sample_time self.seed = seed self._last_CGM = 0 @classmethod def withName(cls, name, sensor_para_file, **kwargs): sensor_params = pd.read_csv(sensor_para_file) params = sensor_params.loc[sensor_params.Name == name].squeeze() return cls(params, **kwargs) def measure(self, patient): if patient.t % self.sample_time == 0: BG = patient.observation.Gsub CGM = BG + next(self._noise_generator) CGM = max(CGM, self._params["min"]) CGM = min(CGM, self._params["max"]) self._last_CGM = CGM return CGM # Zero-Order Hold return self._last_CGM @property def seed(self): return self._seed @seed.setter def seed(self, seed): self._seed = seed self._noise_generator = CGMNoise(self._params, seed=seed) def reset(self): logger.debug('Resetting CGM sensor ...') self._noise_generator = CGMNoise(self._params, seed=self.seed) self._last_CGM = 0 if __name__ == '__main__': pass
2.515625
3
var/spack/repos/builtin/packages/thepeg/package.py
carlabguillen/spack
1
4723
<reponame>carlabguillen/spack # Copyright 2013-2020 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 Thepeg(AutotoolsPackage): """Toolkit for High Energy Physics Event Generation""" homepage = "http://home.thep.lu.se/~leif/ThePEG/" url = "https://thepeg.hepforge.org/downloads/?f=ThePEG-2.2.1.tar.bz2" # The commented out versions exist, but may need patches # and/or recipe changes version('2.2.1', sha256='63abc7215e6ad45c11cf9dac013738e194cc38556a8368b850b70ab1b57ea58f') version('2.2.0', sha256='d3e1474811b7d9f61a4a98db1e9d60d8ef8f913a50de4cae4dc2cc4f98e6fbf8') # version('2.1.7', sha256='2e15727afc1fbfb158fa42ded31c4b1e5b51c25ed6bb66a38233e1fc594329c8') version('2.1.6', sha256='c1e51f83716bfca815b55100fbab3805ef5f9b9215e4373b22762693f5353f4f') version('2.1.5', sha256='c61a00fb6cf406f0f98e8c934683d8d5efcb655747842113abc92e9526e4b5e6') # version('2.1.4', sha256='400c37319aa967ed993fdbec84fc65b24f6cb3779fb1b173d7f5d7a56b772df5') version('2.1.3', sha256='16e8f6507530c2b80ed873ad22946efefed7355d15c7026f3465f18acebc1c0c') # version('2.1.2', sha256='6a0f675a27e10863d495de069f25b892e532beb32e9cbfe5a58317d015387f49') version('2.1.1', sha256='e1b0bdc116fbc9a6e598b601f2aa670530cf2e1cd46b4572814a9b0130b10281') # version('2.1.0', sha256='fe6e7740ce3cd4a3ce3d7a0079a16c9214ad18f432e29d034ae763bfc40f3d39') # version('2.0.4', sha256='f3b625b411667e2708995f1d1379b5b8691406853c8c2cca2f4e4e6e062da0e4') # version('2.0.3', sha256='c57ba68fbfda06a0ba256e06f276f91434bf2529a13f6287c051a4cd6da44634') # version('2.0.2', sha256='d4249e019543d5c7520733292d2edfb0bdd9733177200a63837781ed6194789b') # version('2.0.1', sha256='ec284abdc82ceaf10a8736f908e7955f49f872b79aaa62d22aa33bc5c7679bdb') # version('2.0.0', sha256='571730cc956027dc82780dc04ef6e7382ab5ea853fcfebe259e488c6df302a04') version('1.9.2', sha256='ff7bbb256866f994dae04ade1f57c92d2670edaac3df11c9a300419a5343faf4') # version('1.9.1', sha256='8ec6d0669eba51e308be4e33aeb219999418170eae3aad93ec1491c942c2a4e9') version('1.9.0', sha256='3ee58e5e3a26184567df1b9a10ca70df228e86f322e72f018dd7d8d5a4700a5d') version('1.8.3', sha256='55ede3a3dd0bd07b90d0d49cf7ae28c18cd965780fdf53528508b97d57152fc7') # version('1.8.2', sha256='44ccd0d70e42bb6ecd801a51bade6c25b3953c56f33017402d4f52ee6492dffa') # version('1.8.1', sha256='84c2a212a681545cddd541dca191eb65d96f41df86c87480b6f4f7d4f9683562') # version('1.8.0', sha256='4b22fda1078f410b999a23a17f611c9ae3a7f0f4cee4e83dc82c9336b7adf037') # version('1.7.3', sha256='066d5df74118d6e984bb60e1c0bea08a8edcbcf917d83d8bc32ec6fea0726187') # version('1.7.2', sha256='3b885c6c5a39b7399ccd45d1f5a866b7a65c96174a56a7ff4ae423347843d013') # version('1.7.1', sha256='13434dc7a8623cacb94c0b5c8d7e15b4c5d5187fe9322d1afc1c91b2c940102e') # version('1.7.0', sha256='40eb7196139a8bf4c35f5bb69818135943d534457df64aeb1cf60b6621435312') # version('1.6.1', sha256='5bc074b78f8b663a6a33df9c94dcaa3100269f8da59f9553a565298e55af270f') # version('1.6.0', sha256='c0ac06b70f3e8046fce4e49ba5916c9b49450f528d0e25f8f7f1427c62fec680') # version('1.5.0', sha256='ccbf102cf1d350a21487518d12e7e03e6e50010e5604f0201f256fa46a7a50c2') # version('1.4.2', sha256='40444304e40e07fd417a8ebf8e5c1cf07e895ceac52ef4f7c1eecc911f6f775c') # version('1.4.1', sha256='156d06fd1ce68466d1f2adb9cc13f412b8b87073ec6a1d02102b173c34c29b8a') # version('1.4.0', sha256='b1f55e9a3bec713e9abf2fe71c5bd8cf8df936ea00b09f96df9123d0d5ab233f') # version('1.3.0', sha256='f731ebf3ce5a52b6d750d6e3c282fdc74d8ffd78bccb47b68f10a4daf44c7045') patch('thepeg-1.8.3.patch', when='@1.8.3', level=0) patch('thepeg-1.9.0.patch', when='@1.9.0', level=0) patch('thepeg-1.9.2.patch', when='@1.9.2', level=0) patch('thepeg-2.1.1.patch', when='@2.1.1:2.2.1', level=0) depends_on('gsl') depends_on('lhapdf') depends_on('lhapdf@:6.2.999', when='@:1.9.999') depends_on('hepmc', when='hepmc=2') depends_on('hepmc3', when='hepmc=3') conflicts('hepmc=3', when='@:2.1.999', msg='HepMC3 support was added in 2.2.0') depends_on('fastjet', when='@2.0.0:') depends_on('rivet', when='@2.0.3:') depends_on('boost', when='@2.1.1:') depends_on('autoconf', type='build') depends_on('automake', type='build') depends_on('libtool', type='build') depends_on('m4', type='build') variant('hepmc', default='2', values=('2', '3'), description='HepMC interface to build ') install_targets = ['install-strip'] def configure_args(self): args = ['--with-gsl=' + self.spec['gsl'].prefix, '--without-javagui'] if self.spec.satisfies('@:1.8.999'): args += ['--with-LHAPDF=' + self.spec['lhapdf'].prefix] else: args += ['--with-lhapdf=' + self.spec['lhapdf'].prefix] if self.spec.satisfies('hepmc=2'): args += ['--with-hepmc=' + self.spec['hepmc'].prefix] else: args += ['--with-hepmc=' + self.spec['hepmc3'].prefix] if self.spec.satisfies('@2.2.0:'): args += ['--with-hepmcversion=' + self.spec.variants['hepmc'].value] if self.spec.satisfies('@2.0.0:'): args += ['--with-fastjet=' + self.spec['fastjet'].prefix] if self.spec.satisfies('@2.0.3:'): args += ['--with-rivet=' + self.spec['rivet'].prefix] if self.spec.satisfies('@:2.1.999'): args += ['--with-boost=' + self.spec['boost'].prefix] args += ['CFLAGS=-O2', 'CXXFLAGS=-O2', 'FFLAGS=-O2'] return args
1.359375
1
vmca/python/get_cert.py
wfu8/lightwave
357
4724
<gh_stars>100-1000 #!/usr/bin/env python # # Copyright © 2012-2016 VMware, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the “License”); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an “AS IS” BASIS, without # warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the # License for the specific language governing permissions and limitations # under the License. # # Helper function that gets certificates from VMWare Certificate Authority # More details. If this module can be used as a main program, include usage information. """ certool.py : This is the standard library function for cloudVM/vcenterwindows first boot to integrate with VMCA Certificate Generation. if not running under a cloudVM, then it is assumed that the OS.Environment has the following defined. VMWARE_SKIP_VISL = True system.urlhostname vmdir.ldu-guid system.hostname.type vmca.cert.password vmca.cert.dir """ __copyright__ = "Copyright 2012, VMware Inc." __version__ = 0.1 __author__ = "VMware, Inc." import logging import os import subprocess class CerTool: __vislInstall__ = "" __systemUrlHostname__ = "" __systemHosttype__ = "" __vmcaPassword__ = "" __vmcaCertPath__ = "" __skipInstallParams__ = False __certfileName__ = "" __privateKeyFileName__ = "" __publicKeyFileName__ = "" __pfxFileName__ = "" def __init__(self): self.FindEnvParams() self.GetVislParams() def GetHostName(self): return self.__systemUrlHostname__ def GetHostType(self): return self.__systemHosttype__ def GetPassword(self): return self.__vmcaPassword__ def GetCertDir(self): return self.__vmcaCertPath__ def GetCertFileName(self): return self.__certfileName__ def GetPrivateKeyFileName(self): return self.__privateKeyFile__ def GetPublicKeyFileName(self): return self.__publicKeyFile__ def GetPfxFileName(self): return self.__pfxFileName__ def GenCert(self, componentName): """ Generates the Certificates in the Cert directory""" # Generate full file names for all artifacts self.__certfileName__ = \ os.path.join(self.GetCertDir(), componentName, componentName + ".crt") logging.debug("cert File Name : " + self.GetCertFileName()) self.__privateKeyFile__ = \ os.path.join(self.GetCertDir(), componentName, componentName + ".priv") logging.debug("Private Key Name : " + self.GetPrivateKeyFileName()) self.__publicKeyFile__ = \ os.path.join(self.GetCertDir(), componentName, componentName + ".pub") logging.debug("Public Key Name : " + self.GetPublicKeyFileName()) self.__pfxFileName__ = \ os.path.join(self.GetCertDir(), componentName, componentName + ".pfx") logging.debug("pfx file Name : " + self.GetPfxFileName()) dir = os.path.join(self.GetCertDir(),componentName) logging.debug("Target Dir : " + dir) try: if not os.path.exists(dir): os.makedirs(dir) logging.debug("Created directory") except OSError as e: raise Exception("I/O error({0}): {1}".format(e.errno, e.strerror)) # Generate Private Key and Public Keys First cmd = [self.GetCertToolPath(), '--genkey', '--priv=' + self.GetPrivateKeyFileName(), '--pub=' + self.GetPublicKeyFileName()] output = self.RunCmd(cmd) logging.info(output) cmd = [self.GetCertToolPath(), '--genCIScert', '--priv=' + self.GetPrivateKeyFileName(), '--cert=' + self.GetCertFileName(), '--Name=' + componentName] # if we know the host name, put that into the certificate if (self.GetHostType() == 'fqdn'): cmd.append('--FQDN=' + self.GetHostName()) # elif (self.GetHostType() == 'ipv4'): # # Possible TODO : support IPv4 in certificates # elif (self.GetHostType() == 'ipv6'): # # Possible TODO : support IPv6 in certificates output = self.RunCmd(cmd) logging.info(output) # TODO : Replace this with certool PKCS12 capabilities cmd = [self.GetOpenSSLPath(), 'pkcs12', '-export', '-in', self.GetCertFileName(), '-inkey', self.GetPrivateKeyFileName(), '-out', self.GetPfxFileName(), '-name', componentName, '-passout', 'pass:' + self.GetPassword()] output = self.RunCmd(cmd) logging.info(output) def FindEnvParams(self): """ Finds the Default Environment parameters. if you are not running inside the cloudVM, set VMWARE_SKIP_VISL = True in your environment. This will enable this script to look for values in the env. block instead of VISL namespace.""" # Find VISL Install Parameter INSTALL_PARAM_ENV_VAR = 'VMWARE_INSTALL_PARAMETER' VMWARE_SKIP_VISL = 'VMWARE_SKIP_VISL' if INSTALL_PARAM_ENV_VAR in os.environ: self.__vislInstall__ = os.environ[INSTALL_PARAM_ENV_VAR] if VMWARE_SKIP_VISL in os.environ: skip = os.environ[VMWARE_SKIP_VISL] if (skip in ['true', 'True', 'yes', '1', 'skip']): self.__skipInstallParams__ = True if (not self.__vislInstall__ and self.__skipInstallParams__ is False): errString = 'Unable to find install param script' logging.error(errString) raise Exception(errString) logging.debug('Using install param script : ' + self.__vislInstall__) def GetInstallParams(self, key): """ Waits on Install Parameter to return the value from visl. Or if the VMWARE_SKIP_VISL = True, then reads the value from the os environment""" if (self.__skipInstallParams__ is False): cmd = [self.__vislInstall__, '-d', key] output = self.RunCmd(cmd) logging.debug('Install param found :' + output) return output else: if val in os.environ: param = os.environ[key] logging.debug('Env. param found : ' + param) return param else: raise Exception('Requested Value not found in Env : ' + key) def RunCmd(self, args): """ Runs a given command""" logging.info('running %s' % args) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if p.returncode: raise Exception('Failed to execute last cmd') else: return p.communicate()[0].rstrip() def GetVislParams(self): """ Waits for all VISL parameters that VMCA certool needs""" INSTALL_PARAM_SYSTEM_URL_HOSTNAME = "system.urlhostname" INSTALL_PARAM_LDU_GUID = "vmdir.ldu-guid" INSTALL_PARAM_SYSTEM_HOST_TYPE = "system.hostname.type" INSTALL_PARAM_PASSWORD = "<PASSWORD>" INSTALL_PARAM_CERT_DIR = "vmca.cert.dir" # Please note that each of this is a blocking call. # VISL will wait until these value are populated by the # appropriate Script self.__systemUrlHostname__ = \ self.GetInstallParams(INSTALL_PARAM_SYSTEM_URL_HOSTNAME) self.__systemHosttype__ = \ self.GetInstallParams(INSTALL_PARAM_SYSTEM_HOST_TYPE) self.__vmcaPassword__ = \ self.GetInstallParams(INSTALL_PARAM_PASSWORD) self.__vmcaCertPath__ = \ self.GetInstallParams(INSTALL_PARAM_CERT_DIR) # We really don't need this value, # it is a technique on waiting for directory # first boot to finish. discardldu = self.GetInstallParams(INSTALL_PARAM_LDU_GUID) def GetCertToolPath(self): """returns the path to certool""" #TODO : Publish Certool Path from VMCA First Boot if(os.name == "nt"): PROGRAM_FILES = os.environ['PROGRAMFILES'] return os.path.normpath(PROGRAM_FILES + '/VMware/CIS/Vmcad/certool.exe') elif (os.name == 'posix'): return '/opt/vmware/bin/certool' def GetOpenSSLPath(self): if(os.name == "nt"): PROGRAM_FILES = os.environ['PROGRAMFILES'] return os.path.normpath(PROGRAM_FILES + '/VMware/CIS/OpenSSL/openssl.exe') elif (os.name == 'posix'): return '/usr/lib/vmware-openSSL/openssl' def main(): """ Example Code Usage """ testComponent = 'sso' VmcaCertool = CerTool() VmcaCertool.GenCert(testComponent) print 'Generated a pfx file : %s' % VmcaCertool.GetPfxFileName() print 'Using Password : %s' % VmcaCertool.GetPassword() if __name__ == "__main__": main()
2.25
2
sdk/python/pulumi_gcp/securitycenter/notification_config.py
sisisin/pulumi-gcp
121
4725
<filename>sdk/python/pulumi_gcp/securitycenter/notification_config.py # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['NotificationConfigArgs', 'NotificationConfig'] @pulumi.input_type class NotificationConfigArgs: def __init__(__self__, *, config_id: pulumi.Input[str], organization: pulumi.Input[str], pubsub_topic: pulumi.Input[str], streaming_config: pulumi.Input['NotificationConfigStreamingConfigArgs'], description: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a NotificationConfig resource. :param pulumi.Input[str] config_id: This must be unique within the organization. :param pulumi.Input[str] organization: The organization whose Cloud Security Command Center the Notification Config lives in. :param pulumi.Input[str] pubsub_topic: The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". :param pulumi.Input['NotificationConfigStreamingConfigArgs'] streaming_config: The config for triggering streaming-based notifications. Structure is documented below. :param pulumi.Input[str] description: The description of the notification config (max of 1024 characters). """ pulumi.set(__self__, "config_id", config_id) pulumi.set(__self__, "organization", organization) pulumi.set(__self__, "pubsub_topic", pubsub_topic) pulumi.set(__self__, "streaming_config", streaming_config) if description is not None: pulumi.set(__self__, "description", description) @property @pulumi.getter(name="configId") def config_id(self) -> pulumi.Input[str]: """ This must be unique within the organization. """ return pulumi.get(self, "config_id") @config_id.setter def config_id(self, value: pulumi.Input[str]): pulumi.set(self, "config_id", value) @property @pulumi.getter def organization(self) -> pulumi.Input[str]: """ The organization whose Cloud Security Command Center the Notification Config lives in. """ return pulumi.get(self, "organization") @organization.setter def organization(self, value: pulumi.Input[str]): pulumi.set(self, "organization", value) @property @pulumi.getter(name="pubsubTopic") def pubsub_topic(self) -> pulumi.Input[str]: """ The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". """ return pulumi.get(self, "pubsub_topic") @pubsub_topic.setter def pubsub_topic(self, value: pulumi.Input[str]): pulumi.set(self, "pubsub_topic", value) @property @pulumi.getter(name="streamingConfig") def streaming_config(self) -> pulumi.Input['NotificationConfigStreamingConfigArgs']: """ The config for triggering streaming-based notifications. Structure is documented below. """ return pulumi.get(self, "streaming_config") @streaming_config.setter def streaming_config(self, value: pulumi.Input['NotificationConfigStreamingConfigArgs']): pulumi.set(self, "streaming_config", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: """ The description of the notification config (max of 1024 characters). """ return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @pulumi.input_type class _NotificationConfigState: def __init__(__self__, *, config_id: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, organization: Optional[pulumi.Input[str]] = None, pubsub_topic: Optional[pulumi.Input[str]] = None, service_account: Optional[pulumi.Input[str]] = None, streaming_config: Optional[pulumi.Input['NotificationConfigStreamingConfigArgs']] = None): """ Input properties used for looking up and filtering NotificationConfig resources. :param pulumi.Input[str] config_id: This must be unique within the organization. :param pulumi.Input[str] description: The description of the notification config (max of 1024 characters). :param pulumi.Input[str] name: The resource name of this notification config, in the format 'organizations/{{organization}}/notificationConfigs/{{config_id}}'. :param pulumi.Input[str] organization: The organization whose Cloud Security Command Center the Notification Config lives in. :param pulumi.Input[str] pubsub_topic: The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". :param pulumi.Input[str] service_account: The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. :param pulumi.Input['NotificationConfigStreamingConfigArgs'] streaming_config: The config for triggering streaming-based notifications. Structure is documented below. """ if config_id is not None: pulumi.set(__self__, "config_id", config_id) if description is not None: pulumi.set(__self__, "description", description) if name is not None: pulumi.set(__self__, "name", name) if organization is not None: pulumi.set(__self__, "organization", organization) if pubsub_topic is not None: pulumi.set(__self__, "pubsub_topic", pubsub_topic) if service_account is not None: pulumi.set(__self__, "service_account", service_account) if streaming_config is not None: pulumi.set(__self__, "streaming_config", streaming_config) @property @pulumi.getter(name="configId") def config_id(self) -> Optional[pulumi.Input[str]]: """ This must be unique within the organization. """ return pulumi.get(self, "config_id") @config_id.setter def config_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "config_id", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: """ The description of the notification config (max of 1024 characters). """ return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The resource name of this notification config, in the format 'organizations/{{organization}}/notificationConfigs/{{config_id}}'. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def organization(self) -> Optional[pulumi.Input[str]]: """ The organization whose Cloud Security Command Center the Notification Config lives in. """ return pulumi.get(self, "organization") @organization.setter def organization(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "organization", value) @property @pulumi.getter(name="pubsubTopic") def pubsub_topic(self) -> Optional[pulumi.Input[str]]: """ The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". """ return pulumi.get(self, "pubsub_topic") @pubsub_topic.setter def pubsub_topic(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "pubsub_topic", value) @property @pulumi.getter(name="serviceAccount") def service_account(self) -> Optional[pulumi.Input[str]]: """ The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. """ return pulumi.get(self, "service_account") @service_account.setter def service_account(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "service_account", value) @property @pulumi.getter(name="streamingConfig") def streaming_config(self) -> Optional[pulumi.Input['NotificationConfigStreamingConfigArgs']]: """ The config for triggering streaming-based notifications. Structure is documented below. """ return pulumi.get(self, "streaming_config") @streaming_config.setter def streaming_config(self, value: Optional[pulumi.Input['NotificationConfigStreamingConfigArgs']]): pulumi.set(self, "streaming_config", value) class NotificationConfig(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, config_id: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, organization: Optional[pulumi.Input[str]] = None, pubsub_topic: Optional[pulumi.Input[str]] = None, streaming_config: Optional[pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']]] = None, __props__=None): """ A Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC resource that contains the configuration to send notifications for create/update events of findings, assets and etc. > **Note:** In order to use Cloud SCC resources, your organization must be enrolled in [SCC Standard/Premium](https://cloud.google.com/security-command-center/docs/quickstart-security-command-center). Without doing so, you may run into errors during resource creation. To get more information about NotificationConfig, see: * [API documentation](https://cloud.google.com/security-command-center/docs/reference/rest/v1/organizations.notificationConfigs) * How-to Guides * [Official Documentation](https://cloud.google.com/security-command-center/docs) ## Example Usage ### Scc Notification Config Basic ```python import pulumi import pulumi_gcp as gcp scc_notification = gcp.pubsub.Topic("sccNotification") custom_notification_config = gcp.securitycenter.NotificationConfig("customNotificationConfig", config_id="my-config", organization="123456789", description="My custom Cloud Security Command Center Finding Notification Configuration", pubsub_topic=scc_notification.id, streaming_config=gcp.securitycenter.NotificationConfigStreamingConfigArgs( filter="category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\"", )) ``` ## Import NotificationConfig can be imported using any of these accepted formats ```sh $ pulumi import gcp:securitycenter/notificationConfig:NotificationConfig default organizations/{{organization}}/notificationConfigs/{{name}} ``` ```sh $ pulumi import gcp:securitycenter/notificationConfig:NotificationConfig default {{organization}}/{{name}} ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] config_id: This must be unique within the organization. :param pulumi.Input[str] description: The description of the notification config (max of 1024 characters). :param pulumi.Input[str] organization: The organization whose Cloud Security Command Center the Notification Config lives in. :param pulumi.Input[str] pubsub_topic: The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". :param pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']] streaming_config: The config for triggering streaming-based notifications. Structure is documented below. """ ... @overload def __init__(__self__, resource_name: str, args: NotificationConfigArgs, opts: Optional[pulumi.ResourceOptions] = None): """ A Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC resource that contains the configuration to send notifications for create/update events of findings, assets and etc. > **Note:** In order to use Cloud SCC resources, your organization must be enrolled in [SCC Standard/Premium](https://cloud.google.com/security-command-center/docs/quickstart-security-command-center). Without doing so, you may run into errors during resource creation. To get more information about NotificationConfig, see: * [API documentation](https://cloud.google.com/security-command-center/docs/reference/rest/v1/organizations.notificationConfigs) * How-to Guides * [Official Documentation](https://cloud.google.com/security-command-center/docs) ## Example Usage ### Scc Notification Config Basic ```python import pulumi import pulumi_gcp as gcp scc_notification = gcp.pubsub.Topic("sccNotification") custom_notification_config = gcp.securitycenter.NotificationConfig("customNotificationConfig", config_id="my-config", organization="123456789", description="My custom Cloud Security Command Center Finding Notification Configuration", pubsub_topic=scc_notification.id, streaming_config=gcp.securitycenter.NotificationConfigStreamingConfigArgs( filter="category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\"", )) ``` ## Import NotificationConfig can be imported using any of these accepted formats ```sh $ pulumi import gcp:securitycenter/notificationConfig:NotificationConfig default organizations/{{organization}}/notificationConfigs/{{name}} ``` ```sh $ pulumi import gcp:securitycenter/notificationConfig:NotificationConfig default {{organization}}/{{name}} ``` :param str resource_name: The name of the resource. :param NotificationConfigArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(NotificationConfigArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, config_id: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, organization: Optional[pulumi.Input[str]] = None, pubsub_topic: Optional[pulumi.Input[str]] = None, streaming_config: Optional[pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = NotificationConfigArgs.__new__(NotificationConfigArgs) if config_id is None and not opts.urn: raise TypeError("Missing required property 'config_id'") __props__.__dict__["config_id"] = config_id __props__.__dict__["description"] = description if organization is None and not opts.urn: raise TypeError("Missing required property 'organization'") __props__.__dict__["organization"] = organization if pubsub_topic is None and not opts.urn: raise TypeError("Missing required property 'pubsub_topic'") __props__.__dict__["pubsub_topic"] = pubsub_topic if streaming_config is None and not opts.urn: raise TypeError("Missing required property 'streaming_config'") __props__.__dict__["streaming_config"] = streaming_config __props__.__dict__["name"] = None __props__.__dict__["service_account"] = None super(NotificationConfig, __self__).__init__( 'gcp:securitycenter/notificationConfig:NotificationConfig', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, config_id: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, organization: Optional[pulumi.Input[str]] = None, pubsub_topic: Optional[pulumi.Input[str]] = None, service_account: Optional[pulumi.Input[str]] = None, streaming_config: Optional[pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']]] = None) -> 'NotificationConfig': """ Get an existing NotificationConfig resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] config_id: This must be unique within the organization. :param pulumi.Input[str] description: The description of the notification config (max of 1024 characters). :param pulumi.Input[str] name: The resource name of this notification config, in the format 'organizations/{{organization}}/notificationConfigs/{{config_id}}'. :param pulumi.Input[str] organization: The organization whose Cloud Security Command Center the Notification Config lives in. :param pulumi.Input[str] pubsub_topic: The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". :param pulumi.Input[str] service_account: The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. :param pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']] streaming_config: The config for triggering streaming-based notifications. Structure is documented below. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _NotificationConfigState.__new__(_NotificationConfigState) __props__.__dict__["config_id"] = config_id __props__.__dict__["description"] = description __props__.__dict__["name"] = name __props__.__dict__["organization"] = organization __props__.__dict__["pubsub_topic"] = pubsub_topic __props__.__dict__["service_account"] = service_account __props__.__dict__["streaming_config"] = streaming_config return NotificationConfig(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="configId") def config_id(self) -> pulumi.Output[str]: """ This must be unique within the organization. """ return pulumi.get(self, "config_id") @property @pulumi.getter def description(self) -> pulumi.Output[Optional[str]]: """ The description of the notification config (max of 1024 characters). """ return pulumi.get(self, "description") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ The resource name of this notification config, in the format 'organizations/{{organization}}/notificationConfigs/{{config_id}}'. """ return pulumi.get(self, "name") @property @pulumi.getter def organization(self) -> pulumi.Output[str]: """ The organization whose Cloud Security Command Center the Notification Config lives in. """ return pulumi.get(self, "organization") @property @pulumi.getter(name="pubsubTopic") def pubsub_topic(self) -> pulumi.Output[str]: """ The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". """ return pulumi.get(self, "pubsub_topic") @property @pulumi.getter(name="serviceAccount") def service_account(self) -> pulumi.Output[str]: """ The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. """ return pulumi.get(self, "service_account") @property @pulumi.getter(name="streamingConfig") def streaming_config(self) -> pulumi.Output['outputs.NotificationConfigStreamingConfig']: """ The config for triggering streaming-based notifications. Structure is documented below. """ return pulumi.get(self, "streaming_config")
1.835938
2
malib/agents/tabular/q_learning/base_tabular_agent.py
wwxFromTju/malib
6
4726
from abc import ABCMeta, abstractmethod import numpy as np class Agent(object): __metaclass__ = ABCMeta def __init__(self, name, id_, action_num, env): self.name = name self.id_ = id_ self.action_num = action_num # len(env.action_space[id_]) # self.opp_action_space = env.action_space[0:id_] + env.action_space[id_:-1] def set_pi(self, pi): # assert len(pi) == self.actin_num self.pi = pi def done(self, env): pass @abstractmethod def act(self, s, exploration, env): pass def update(self, s, a, o, r, s2, env): pass @staticmethod def format_time(n): return "" # s = humanfriendly.format_size(n) # return s.replace(' ', '').replace('bytes', '').replace('byte', '').rstrip('B') def full_name(self, env): return "{}_{}_{}".format(env.name, self.name, self.id_) class StationaryAgent(Agent): def __init__(self, id_, action_num, env, pi=None): super().__init__("stationary", id_, action_num, env) if pi is None: pi = np.random.dirichlet([1.0] * self.action_num) self.pi = np.array(pi, dtype=np.double) StationaryAgent.normalize(self.pi) def act(self, s, exploration, env): if self.verbose: print("pi of agent {}: {}".format(self.id_, self.pi)) return StationaryAgent.sample(self.pi) @staticmethod def normalize(pi): minprob = np.min(pi) if minprob < 0.0: pi -= minprob pi /= np.sum(pi) @staticmethod def sample(pi): return np.random.choice(pi.size, size=1, p=pi)[0] class RandomAgent(StationaryAgent): def __init__(self, id_, action_num, env): assert action_num > 0 super().__init__(id_, env, action_num, pi=[1.0 / action_num] * action_num) self.name = "random"
3.21875
3
290.word-pattern.py
Lonitch/hackerRank
0
4727
# # @lc app=leetcode id=290 lang=python3 # # [290] Word Pattern # # https://leetcode.com/problems/word-pattern/description/ # # algorithms # Easy (35.86%) # Likes: 825 # Dislikes: 113 # Total Accepted: 164K # Total Submissions: 455.9K # Testcase Example: '"abba"\n"dog cat cat dog"' # # Given a pattern and a string str, find if str follows the same pattern. # # Here follow means a full match, such that there is a bijection between a # letter in pattern and a non-empty word in str. # # Example 1: # # # Input: pattern = "abba", str = "dog cat cat dog" # Output: true # # Example 2: # # # Input:pattern = "abba", str = "dog cat cat fish" # Output: false # # Example 3: # # # Input: pattern = "aaaa", str = "dog cat cat dog" # Output: false # # Example 4: # # # Input: pattern = "abba", str = "dog dog dog dog" # Output: false # # Notes: # You may assume pattern contains only lowercase letters, and str contains # lowercase letters that may be separated by a single space. # # # @lc code=start from collections import defaultdict class Solution: def wordPattern(self, pattern: str, str1: str) -> bool: if len(pattern)!=len(str1.split()): return False abmap = defaultdict(str) bamap = defaultdict(str) for a,b in zip(pattern, str1.split()): if abmap[a]=='' and bamap[b]=='': abmap[a]=b bamap[b]=a elif abmap[a]!=b or bamap[b]!=a: return False return True # @lc code=end
3.84375
4
s1_getting_started/exercise_files/final_exercise/model.py
jaschn/dtu_mlops
0
4728
from torch import nn class MyAwesomeModel(nn.Module): def __init__(self): super().__init__() self.cnn = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=5, kernel_size=3), nn.ReLU(), nn.Conv2d(in_channels=5, out_channels=3, kernel_size=3, stride=2) ) self.fc = nn.Sequential(nn.Linear(432, 100), nn.ReLU(), nn.Linear(100,10), nn.LogSoftmax(dim=1) ) def forward(self, x): x = self.cnn(x).view(x.size(0), -1) return self.fc(x)
3.1875
3
musket_core/tests/coders_test.py
dreamflyer/musket_core
16
4729
import unittest from musket_core import coders import numpy as np import pandas as pd import os import math fl=__file__ fl=os.path.dirname(fl) class TestCoders(unittest.TestCase): def test_binary_num(self): a=np.array([0,1,0,1]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 0, "should be zero") self.assertEqual(bc[1], 1, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, 1, "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, 0, "should be zero") pass def test_binary_str(self): a=np.array(["0","1","0","1"]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 0, "should be zero") self.assertEqual(bc[1], 1, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, "1", "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, "0", "should be zero") pass def test_binary_str2(self): a=np.array(["","1","","1"]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 0, "should be zero") self.assertEqual(bc[1], 1, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, "1", "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, "", "should be zero") pass def test_binary_bool(self): a=np.array([True,False,True,False]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 1, "should be zero") self.assertEqual(bc[1], 0, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, True, "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, False, "should be zero") pass def test_categorical_num(self): a=np.array([0,1,2,1]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][0], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(v, 2, "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, 0, "should be zero") pass def test_categorical_str(self): a=np.array(["a","b","c","b"]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][0], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(v, "c", "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, "a", "should be zero") pass def test_categorical_str2(self): a=np.array(["","b","c","b"]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][0], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(v, "c", "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, "", "should be zero") pass def test_categorical_pd(self): a=np.array([math.nan,1,2,1]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][2], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(math.isnan(v),True, "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, 1, "should be zero") pass def test_multiclass(self): a=np.array(["1 2","0 2","0",""]) bc=coders.get_coder("multi_class",a, None) val=bc[0] self.assertEqual((val==np.array([False,True,True])).sum(), 3,"Fixing format") for i in range(len(a)): val=bc[i] r=bc._decode(val) self.assertEqual(r, a[i], "Decoding should work also") pass def test_multiclass1(self): a=np.array(["1_2","0_2","0",""]) bc=coders.get_coder("multi_class",a, None) val=bc[0] self.assertEqual((val==np.array([False,True,True])).sum(), 3,"Fixing format") for i in range(len(a)): val=bc[i] r=bc._decode(val) self.assertEqual(r, a[i], "Decoding should work also") pass def test_multiclass2(self): a=np.array(["1","","",""]) bc=coders.get_coder("multi_class",a, None) val=bc[0] self.assertEqual((val==np.array([True])).sum(), 1,"Fixing format") for i in range(len(a)): val=bc[i] r=bc._decode(val) self.assertEqual(r, a[i], "Decoding should work also") pass
2.921875
3
manage.py
isijara/zulip
1
4730
#!/usr/bin/env python3 import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) import scripts.lib.setup_path_on_import if __name__ == "__main__": if 'posix' in os.name and os.geteuid() == 0: print("manage.py should not be run as root. Use `su zulip` to drop root.") sys.exit(1) if (os.access('/etc/zulip/zulip.conf', os.R_OK) and not os.access('/etc/zulip/zulip-secrets.conf', os.R_OK)): # The best way to detect running manage.py as another user in # production before importing anything that would require that # access is to check for access to /etc/zulip/zulip.conf (in # which case it's a production server, not a dev environment) # and lack of access for /etc/zulip/zulip-secrets.conf (which # should be only readable by root and zulip) print("Error accessing Zulip secrets; manage.py in production must be run as the zulip user.") sys.exit(1) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zproject.settings") from django.conf import settings from django.core.management import execute_from_command_line from django.core.management.base import CommandError from scripts.lib.zulip_tools import log_management_command log_management_command(" ".join(sys.argv), settings.MANAGEMENT_LOG_PATH) os.environ.setdefault("PYTHONSTARTUP", os.path.join(BASE_DIR, "scripts/lib/pythonrc.py")) if "--no-traceback" not in sys.argv and len(sys.argv) > 1: sys.argv.append("--traceback") try: execute_from_command_line(sys.argv) except CommandError as e: print(e, file=sys.stderr) sys.exit(1)
1.96875
2
core/scripts/fetch_instructions_specs.py
merwaaan/mr.system
0
4731
<filename>core/scripts/fetch_instructions_specs.py<gh_stars>0 import json, requests from bs4 import BeautifulSoup def fetch(): r = requests.get('http://clrhome.org/table/') if not r.ok: print('Cannot fetch {})'.format(r.url)) return None # remove newlines text = r.text.replace('\n', '') # Return the data as a BeautifulSoup object for easy querying return BeautifulSoup(text, 'html.parser') def table_title(table): return 'main' if table['title'] == '' else table['title'].lower() def parse_tables(page): return {table_title(table): parse_table(table) for table in page.find_all('table')} def parse_table(table): print('Table {}'.format(table_title(table))) opcodes = [] for td in table.find_all('td', axis=True): hi = int(td.parent.find('th').text, 16) # row lo = td.parent.index(td) - 1 # column code = hi << 4 | lo specs = td['axis'].split('|') # Conditional instructions have different durations depending on how they # branch so the possible durations are stored in an array. Otherwise, the # duration is just stored as a single value. cycles = list(map(int, specs[2].split('/'))) if '/' in specs[2] else int(specs[2]) opcodes.append({ 'opcode': code, 'mnemonics': normalize(td.text).strip(), 'size': int(specs[1]), 'cycles': cycles, 'flags': specs[0], 'description': specs[3] }) print(' {}: {}'.format(hex(code), td.text)) return opcodes def normalize(mnemonics): parts = mnemonics.split(' ') name = parts[0] operands = parts[1].split(',') if len(parts) > 1 else [] return '{} {}'.format(name, ','.join(normalize_operand(o, name) for o in operands)) def normalize_operand(operand, instr_name): # Flag condition if instr_name in ['jr', 'jp', 'ret', 'call'] and operand in ['c', 'nc', 'z', 'nz', 'po', 'pe', 'p', 'm']: operand = 'f_' + { 'po': 'np', 'pe': 'p', 'p': 'ns', 'm': 's' }.get(operand, operand) # Alt registers elif operand == 'af\'': operand = 'af_' return operand if __name__ == '__main__': """ This scripts fetches the contents of a webpage that contains nicely formatted data about the Z80 opcodes and outputs it to JSON. """ page = fetch() if page is not None: opcodes = parse_tables(page) with open('opcodes.json', 'w') as output: json.dump(opcodes, output, indent=2)
2.765625
3
unittests/tools/test_intsights_parser.py
M-Rod101/django-DefectDojo
249
4732
from ..dojo_test_case import DojoTestCase from dojo.models import Test from dojo.tools.intsights.parser import IntSightsParser class TestIntSightsParser(DojoTestCase): def test_intsights_parser_with_one_critical_vuln_has_one_findings_json( self): testfile = open("unittests/scans/intsights/intsights_one_vul.json") parser = IntSightsParser() findings = parser.get_findings(testfile, Test()) testfile.close() self.assertEqual(1, len(findings)) finding = list(findings)[0] self.assertEqual( '5c80dbf83b4a3900078b6be6', finding.unique_id_from_tool) self.assertEqual( 'HTTP headers weakness in initech.com web server', finding.title) self.assertEquals('Critical', finding.severity) self.assertEquals( "https://dashboard.intsights.com/#/threat-command/alerts?search=5c80dbf83b4a3900078b6be6", finding.references) def test_intsights_parser_with_one_critical_vuln_has_one_findings_csv( self): testfile = open("unittests/scans/intsights/intsights_one_vuln.csv") parser = IntSightsParser() findings = parser.get_findings(testfile, Test()) testfile.close() self.assertEqual(1, len(findings)) finding = list(findings)[0] self.assertEqual( "mn7xy83finmmth4ja363rci9", finding.unique_id_from_tool) self.assertEqual( "HTTP headers weakness in company-domain.com web server", finding.title) def test_intsights_parser_with_many_vuln_has_many_findings_json(self): testfile = open("unittests/scans/intsights/intsights_many_vul.json") parser = IntSightsParser() findings = parser.get_findings(testfile, Test()) testfile.close() self.assertEqual(3, len(findings)) def test_intsights_parser_with_many_vuln_has_many_findings_csv(self): testfile = open("unittests/scans/intsights/intsights_many_vuln.csv") parser = IntSightsParser() findings = parser.get_findings(testfile, Test()) testfile.close() self.assertEqual(9, len(findings)) def test_intsights_parser_invalid_text_with_error_csv(self): with self.assertRaises(ValueError): testfile = open( "unittests/scans/intsights/intsights_invalid_file.txt") parser = IntSightsParser() findings = parser.get_findings(testfile, Test())
2.609375
3
tools/testutils.py
sktollman/p4c
1
4733
<reponame>sktollman/p4c #!/usr/bin/env python # Copyright 2013-present Barefoot Networks, Inc. # Copyright 2018 VMware, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Defines helper functions for a general testing framework. Used by multiple Python testing scripts in the backends folder.""" from __future__ import print_function import subprocess from subprocess import Popen from threading import Timer import sys import os TIMEOUT = 10 * 60 SUCCESS = 0 FAILURE = 1 SKIPPED = 2 # used occasionally to indicate that a test was not executed def is_err(p4filename): """ True if the filename represents a p4 program that should fail. """ return "_errors" in p4filename def report_err(file, *message): """ Write message to given file, report to stderr if verbose """ print("***", file=sys.stderr, *message) if (file and file != sys.stderr): err_file = open(file, "a+") print("***", file=err_file, *message) err_file.close() def report_output(file, verbose, *message): """ Write message to given file, report to stdout if verbose """ if (verbose): print(file=sys.stdout, *message) if (file and file != sys.stdout): out_file = open(file, "a+") print("", file=out_file, *message) out_file.close() def byte_to_hex(byteStr): """ Convert byte sequences to a hex string. """ return ''.join(["%02X " % ord(x) for x in byteStr]).strip() def hex_to_byte(hexStr): """ Convert hex strings to bytes. """ bytes = [] hexStr = ''.join(hexStr.split(" ")) for i in range(0, len(hexStr), 2): bytes.append(chr(int(hexStr[i:i + 2], 16))) return ''.join(bytes) def compare_pkt(outputs, expected, received): """ Compare two given byte sequences and check if they are the same. Report errors if this is not the case. """ received = ''.join(byte_to_hex(str(received)).split()).upper() expected = ''.join(expected.split()).upper() if len(received) < len(expected): report_err(outputs["stderr"], "Received packet too short", len(received), "vs", len(expected)) return FAILURE for i in range(0, len(expected)): if expected[i] == "*": continue if expected[i] != received[i]: report_err(outputs["stderr"], "Received packet ", received) report_err(outputs["stderr"], "Packet different at position", i, ": expected", expected[i], ", received", received[i]) report_err(outputs["stderr"], "Expected packet ", expected) return FAILURE return SUCCESS def open_process(verbose, args, outputs): """ Run the given arguments as a subprocess. Time out after TIMEOUT seconds and report failures or stdout. """ report_output(outputs["stdout"], verbose, "Writing", args) proc = None if outputs["stderr"] is not None: try: proc = Popen(args, stdout=subprocess.PIPE, shell=True, stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) except OSError as e: report_err(outputs["stderr"], "Failed executing: ", e) if proc is None: # Never even started report_err(outputs["stderr"], "Process failed to start") return proc def run_process(verbose, proc, timeout, outputs, errmsg): def kill(process): process.kill() timer = Timer(TIMEOUT, kill, [proc]) try: timer.start() out, err = proc.communicate() finally: timer.cancel() if out: msg = ("\n########### PROCESS OUTPUT BEGIN:\n" "%s########### PROCESS OUTPUT END\n" % out) report_output(outputs["stdout"], verbose, msg) if proc.returncode != SUCCESS: report_err(outputs["stderr"], "Error %d: %s\n%s" % (proc.returncode, errmsg, err)) else: # Also report non fatal warnings in stdout if err: report_err(outputs["stderr"], err) return proc.returncode def run_timeout(verbose, args, timeout, outputs, errmsg): proc = open_process(verbose, args, outputs) if proc is None: return FAILURE report_output(outputs["stdout"], verbose, "Executing", args) return run_process(verbose, proc, timeout, outputs, errmsg) def check_root(): """ This function returns False if the user does not have root privileges. Caution: Only works on Unix systems """ return (os.getuid() == 0)
2.390625
2
AlgorithmsAndDataStructures/mod2/Heap.py
BootyAss/bmstu
0
4734
<gh_stars>0 class Heap: def __init__(self): self.items = dict() # key - (value, index) self.indexes = [] # index - key // to know indexes # Usefull functions def swap(self, i, j): x = self.indexes[i] # key of 1 item y = self.indexes[j] # key of 2 item # swap keys in index array self.indexes[i] = y self.indexes[j] = x temp = self.items[x][1] # index of 1 item # swap indexes in dictionary self.items.update({x: (self.items[x][0], self.items[y][1])}) self.items.update({y: (self.items[y][0], temp)}) def bigger(self, i, j): if self.indexes[i] <= self.indexes[j]: return False else: return True # Check family UwU def hasParent(self, i): if (i - 1)/2 >= 0: return True return False def parentIndex(self, i): return int((i - 1)/2) def hasLeft(self, i): if i*2 + 1 < len(self.indexes): return True return False def leftIndex(self, i): return int(i*2 + 1) def hasRight(self, i): if i*2 + 2 < len(self.indexes): return True return False def rightIndex(self, i): return int(i*2 + 2) # heapifys def heapifyUp(self, i=None): if i: index = i else: index = len(self.indexes) - 1 while self.hasParent(index) and self.bigger(self.parentIndex(index), index): self.swap(self.parentIndex(index), index) index = self.parentIndex(index) def heapifyDown(self, i=0): index = i while self.hasLeft(index): smaller = self.leftIndex(index) if self.hasRight(index) and self.bigger(self.leftIndex(index), self.rightIndex(index)): smaller = self.rightIndex(index) if self.bigger(smaller, index): break else: self.swap(index, smaller) index = smaller # all needed methods def add(self, key, data): if self.items.get(key, None): raise(Exception) self.items[key] = (data, int(len(self.indexes))) self.indexes.append(key) self.heapifyUp() def set(self, key, data): temp = self.items.get(key, None) if not temp: raise(Exception) self.items[key] = (data, temp[1]) def delete(self, key): temp = self.items.get(key, None) if not temp: raise(Exception) if len(self.indexes) > 1: lastKey = self.indexes[-1] last = self.items.get(lastKey, None) # set last item index of deleted self.items.update({lastKey: (last[0], temp[1])}) # set key of last item to deleted index self.indexes[temp[1]] = lastKey self.indexes.pop() del self.items[key] if temp[1] < len(self.indexes): # dont heapify if deleted last element self.heapifyDown(i=temp[1]) self.heapifyUp(i=temp[1]) def search(self, key): temp = self.items.get(key, None) if temp: print('1', temp[1], temp[0]) else: print('0') def min(self): if len(self.indexes) == 0: raise(Exception) key = self.indexes[0] print(key, '0', self.items[key][0]) def max(self): if len(self.indexes) == 0: raise(Exception) i = int(len(self.indexes)/2) maxKey = self.indexes[i] index = i while i < len(self.indexes): if maxKey < self.indexes[i]: maxKey = self.indexes[i] index = i i += 1 print(maxKey, index, self.items[maxKey][0]) def extract(self): if len(self.indexes) == 0: raise(Exception) rootKey = self.indexes[0] rootData = self.items[rootKey][0] del self.items[rootKey] if len(self.indexes) > 1: self.indexes[0] = self.indexes.pop() # set top item index to 0 self.items.update({self.indexes[0] : (self.items[self.indexes[0]][0], 0)}) self.heapifyDown() else: self.indexes.pop() print(rootKey, rootData) def print(self): height = 0 index = 0 out = '' i = 0 if len(self.indexes) == 0: out += '_\n' print('_') return while i < len(self.indexes): lineLen = 1 << height index += 1 key = self.indexes[i] out += '[' + str(key) + ' ' + self.items[key][0] if height != 0: out += ' ' + str(self.indexes[self.parentIndex(i)]) out += ']' if index == lineLen: out += '\n' index = 0 height += 1 else: out += ' ' i += 1 if index != 0 and index < lineLen: out += '_ ' * (lineLen - index) print(out[0:-1]) else: print(out, end='') cycle = True heap = Heap() while cycle: try: line = input() cmd = line.split(' ', 2) try: if len(cmd) == 1 and cmd[0] == '': continue if len(cmd) == 2 and cmd[0] == '' and cmd[1] == '': continue if cmd[0] == 'add': heap.add(int(cmd[1]), cmd[2]) elif cmd[0] == 'set': heap.set(int(cmd[1]), cmd[2]) elif cmd[0] == 'delete': heap.delete(int(cmd[1])) elif cmd[0] == 'search': heap.search(int(cmd[1])) elif cmd[0] == 'min': heap.min() elif cmd[0] == 'max': heap.max() elif cmd[0] == 'extract': heap.extract() elif cmd[0] == 'print': heap.print() else: raise(Exception) except Exception: print('error') continue except Exception: cycle = False
3.671875
4
django_comments_xtd/tests/test_api_views.py
Boondockers-Welcome/django-comments-xtd
1
4735
from __future__ import unicode_literals try: from unittest.mock import patch except ImportError: from mock import patch from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.test import TestCase from django.urls import reverse from rest_framework.test import APIRequestFactory, force_authenticate from django_comments_xtd import django_comments from django_comments_xtd.api.views import CommentCreate from django_comments_xtd.tests.models import Article, Diary request_factory = APIRequestFactory() def post_comment(data, auth_user=None): request = request_factory.post(reverse('comments-xtd-api-create'), data) if auth_user: force_authenticate(request, user=auth_user) view = CommentCreate.as_view() return view(request) class CommentCreateTestCase(TestCase): def setUp(self): patcher = patch('django_comments_xtd.views.send_mail') self.mock_mailer = patcher.start() self.article = Article.objects.create( title="October", slug="october", body="What I did on October...") self.form = django_comments.get_form()(self.article) def test_post_returns_2xx_response(self): data = {"name": "Bob", "email": "<EMAIL>", "followup": True, "reply_to": 0, "level": 1, "order": 1, "comment": "Es war einmal eine kleine...", "honeypot": ""} data.update(self.form.initial) response = post_comment(data) self.assertEqual(response.status_code, 204) self.assertEqual(self.mock_mailer.call_count, 1) def test_post_returns_4xx_response(self): # It uses an authenticated user, but the user has no mail address. self.user = User.objects.create_user("bob", "", "pwd") data = {"name": "", "email": "", "followup": True, "reply_to": 0, "level": 1, "order": 1, "comment": "Es war einmal eine kleine...", "honeypot": ""} data.update(self.form.initial) response = post_comment(data, auth_user=self.user) self.assertEqual(response.status_code, 400) self.assertTrue('name' in response.data) self.assertTrue('email' in response.data) self.assertEqual(self.mock_mailer.call_count, 0)
2.421875
2
LC/358.py
szhu3210/LeetCode_Solutions
2
4736
class Solution(object): def rearrangeString(self, str, k): """ :type str: str :type k: int :rtype: str """ ## greedy: count keeps the # of chars, valid keeps the leftmost valid index of a char. res=[] # count # of chars d=collections.defaultdict(int) for c in str: d[c]+=1 # create a valid dict v=collections.defaultdict(int) # add char one by one, that with max # first, must have valid leftmost index for i in range(len(str)): c=None for key in d: if (not c or d[key]>d[c]) and d[key]>0 and v[key]<=i: # get c with max # and be valid c=key if not c: return '' res.append(c) d[c]-=1 v[c]=i+k return ''.join(res)
3.234375
3
momentumopt/python/momentumopt/kinoptpy/momentum_kinematics_optimizer.py
ferdinand-wood/kino_dynamic_opt
0
4737
''' @file momentum_kinematics_optimizer.py @package momentumopt @author <NAME> (<EMAIL>) @license License BSD-3-Clause @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft. @date 2019-10-08 ''' import os import numpy as np from momentumopt.kinoptpy.qp import QpSolver from momentumopt.kinoptpy.inverse_kinematics import PointContactInverseKinematics from pinocchio import RobotWrapper import pinocchio as se3 from pinocchio.utils import zero from pymomentum import * from momentumopt.quadruped.quadruped_wrapper import QuadrupedWrapper from momentumopt.kinoptpy.min_jerk_traj import * from pymomentum import \ PlannerVectorParam_KinematicDefaultJointPositions, \ PlannerIntParam_NumTimesteps, \ PlannerDoubleParam_TimeStep class Contact(object): def __init__(self, position, start_time, end_time): self.pos = position self.init_time = start_time self.final_time = end_time def position(self): return self.pos def start_time(self): return self.init_time def end_time(self): return self.final_time def get_contact_plan(contact_states, effs): contacts = {} for i, eff in enumerate(effs): num_contacts = len(contact_states(i)) contacts[eff] = [] for j in range(num_contacts): contact_ = contact_states(i)[j] start_time = contact_.start_time end_time = contact_.end_time position = contact_.position contacts[eff].append(Contact(position, start_time, end_time)) return contacts def generate_eff_traj(contacts, z_offset): effs = contacts.keys() eff_traj_poly = {} for eff in effs: cnt = contacts[eff] num_contacts = len(cnt) poly_traj = [ PolynominalList(), PolynominalList(), PolynominalList() ] for i in range(num_contacts): # Create a constant polynominal for endeffector on the ground. t = [cnt[i].start_time(), cnt[i].end_time()] for idx in range(3): poly_traj[idx].append(t, constant_poly(cnt[i].position()[idx])) # If there is a contact following, add the transition between # the two contact points. if i < num_contacts - 1: t = [cnt[i].end_time(), cnt[i+1].start_time()] for idx in range(3): via = None if idx == 2: via = z_offset + cnt[i].position()[idx] poly = poly_points(t, cnt[i].position()[idx], cnt[i+1].position()[idx], via) poly_traj[idx].append(t, poly) eff_traj_poly[eff] = poly_traj # returns end eff trajectories return eff_traj_poly class EndeffectorTrajectoryGenerator(object): def __init__(self): self.z_offset = 0.1 def get_z_bound(self, mom_kin_optimizer): z_max = min(max(mom_kin_optimizer.com_dyn[:, 2]), self.max_bound) z_min = max(min(mom_kin_optimizer.com_dyn[:, 2]), self.min_bound) return z_max, z_min def __call__(self, mom_kin_optimizer): ''' Computes the endeffector positions and velocities. Returns endeff_pos_ref, endeff_vel_ref [0]: endeff_pos_ref: np.array, shape=[num_time_steps, num_eff, 3={x, y, z}] [1]: endeff_vel_ref: np.array, shape=[num_time_steps, num_eff, 3={x, y, z}] ''' dt = mom_kin_optimizer.dt num_eff = len(mom_kin_optimizer.eff_names) num_time_steps = mom_kin_optimizer.num_time_steps contacts = get_contact_plan(mom_kin_optimizer.contact_sequence.contact_states, mom_kin_optimizer.eff_names) # Generate minimum jerk trajectories eff_traj_poly = generate_eff_traj(contacts, self.z_offset) # Compute the endeffector position and velocity trajectories. endeff_pos_ref = np.zeros((num_time_steps, num_eff, 3)) endeff_vel_ref = np.zeros((num_time_steps, num_eff, 3)) endeff_contact = np.zeros((num_time_steps, num_eff)) for it in range(num_time_steps): for eff, name in enumerate(mom_kin_optimizer.eff_names): endeff_pos_ref[it][eff] = [eff_traj_poly[name][i].eval(it * dt) for i in range(3)] endeff_vel_ref[it][eff] = [eff_traj_poly[name][i].deval(it * dt) for i in range(3)] # HACK: If the velocity is zero, assume the endeffector is in # contact with the ground. if np.all(endeff_vel_ref[it][eff] == 0.): endeff_contact[it][eff] = 1. else: endeff_contact[it][eff] = 0. return endeff_pos_ref, endeff_vel_ref, endeff_contact class JointTrajectoryGenerator(object): def __init__(self): self.dt =.01 self.num_time_steps = None self.q_init = None self.poly_traj = None def joint_traj(self, q_via): self.poly_traj = [] for i in range(len(self.q_init)): self.poly_traj = np.append(self.poly_traj, [PolynominalList()]) for j in range(len(self.q_init)): for i in range (len(q_via[:,0])+1): if i==0: t = [0, q_via[0,0]/self.dt] poly = poly_points(t, self.q_init[j], q_via[i,j+1]) self.poly_traj[j].append(t, poly) elif(i==len(q_via[:,0])): t = [q_via[i-1,0]/self.dt, self.num_time_steps] poly = poly_points(t, q_via[i-1,j+1], self.q_init[j]) self.poly_traj[j].append(t, poly) else: t = [q_via[i-1,0]/self.dt, q_via[i,0]/self.dt] poly = poly_points(t, q_via[i-1,j+1], q_via[i,j+1]) self.poly_traj[j].append(t, poly) def eval_traj(self,t): q = np.zeros((1,len(self.q_init)),float) for j in range(len(self.q_init)): q[0,j] = self.poly_traj[j].eval(t) return np.matrix(q) class MomentumKinematicsOptimizer(object): def __init__(self): self.q_init = None self.dq_init = None self.reg_orientation = 1e-2 self.reg_joint_position = 2. self.joint_des = None def reset(self): self.kinematics_sequence = KinematicsSequence() self.kinematics_sequence.resize(self.planner_setting.get(PlannerIntParam_NumTimesteps), self.planner_setting.get(PlannerIntParam_NumDofs)) def initialize(self, planner_setting, max_iterations=50, eps=0.001, endeff_traj_generator=None, RobotWrapper=QuadrupedWrapper): self.planner_setting = planner_setting if endeff_traj_generator is None: endeff_traj_generator = EndeffectorTrajectoryGenerator() self.endeff_traj_generator = endeff_traj_generator self.dt = planner_setting.get(PlannerDoubleParam_TimeStep) self.num_time_steps = planner_setting.get(PlannerIntParam_NumTimesteps) self.max_iterations = max_iterations self.eps = eps self.robot = RobotWrapper() self.reset() # Holds dynamics and kinematics results self.com_dyn = np.zeros((self.num_time_steps, 3)) self.lmom_dyn = np.zeros((self.num_time_steps, 3)) self.amom_dyn = np.zeros((self.num_time_steps, 3)) self.com_kin = np.zeros((self.num_time_steps, 3)) self.lmom_kin = np.zeros((self.num_time_steps, 3)) self.amom_kin = np.zeros((self.num_time_steps, 3)) self.q_kin = np.zeros((self.num_time_steps, self.robot.model.nq)) self.dq_kin = np.zeros((self.num_time_steps, self.robot.model.nv)) self.hip_names = ['{}_HFE'.format(eff) for eff in self.robot.effs] self.hip_ids = [self.robot.model.getFrameId(name) for name in self.hip_names] self.eff_names = ['{}_{}'.format(eff, self.robot.joints_list[-1]) for eff in self.robot.effs] self.inv_kin = PointContactInverseKinematics(self.robot.model, self.eff_names) self.motion_eff = { 'trajectory': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)), 'velocity': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)), 'trajectory_wrt_base': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)), 'velocity_wrt_base': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)) } def fill_data_from_dynamics(self): # The centroidal information for it in range(self.num_time_steps): self.com_dyn[it] = self.dynamic_sequence.dynamics_states[it].com self.lmom_dyn[it] = self.dynamic_sequence.dynamics_states[it].lmom self.amom_dyn[it] = self.dynamic_sequence.dynamics_states[it].amom def fill_endeffector_trajectory(self): self.endeff_pos_ref, self.endeff_vel_ref, self.endeff_contact = \ self.endeff_traj_generator(self) def fill_kinematic_result(self, it, q, dq): def framesPos(frames): return np.vstack([data.oMf[idx].translation for idx in frames]).reshape(-1) def framesVel(frames): return np.vstack([ self.inv_kin.get_world_oriented_frame_jacobian(q, idx).dot(dq)[:3] for idx in frames ]).reshape(-1) data = self.inv_kin.robot.data hg = self.inv_kin.robot.centroidalMomentum(q, dq) # Storing on the internal array. self.com_kin[it] = self.inv_kin.robot.com(q).T self.lmom_kin[it] = hg.linear.T self.amom_kin[it] = hg.angular.T self.q_kin[it] = q.T self.dq_kin[it] = dq.T # The endeffector informations as well. self.motion_eff['trajectory'][it] = framesPos(self.inv_kin.endeff_ids) self.motion_eff['velocity'][it] = self.inv_kin.J[6:(self.inv_kin.ne + 2) * 3].dot(dq).T self.motion_eff['trajectory_wrt_base'][it] = \ self.motion_eff['trajectory'][it] - framesPos(self.hip_ids) self.motion_eff['velocity_wrt_base'][it] = \ self.motion_eff['velocity'][it] - framesVel(self.hip_ids) # Storing on the kinematic sequence. kinematic_state = self.kinematics_sequence.kinematics_states[it] kinematic_state.com = self.com_kin[it] kinematic_state.lmom = self.lmom_kin[it] kinematic_state.amom = self.amom_kin[it] kinematic_state.robot_posture.base_position = q[:3] kinematic_state.robot_posture.base_orientation = q[3:7] kinematic_state.robot_posture.joint_positions = q[7:] kinematic_state.robot_velocity.base_linear_velocity = dq[:3] kinematic_state.robot_velocity.base_angular_velocity = dq[3:6] kinematic_state.robot_velocity.joint_velocities = dq[6:] def optimize_initial_position(self, init_state): # Optimize the initial configuration q = se3.neutral(self.robot.model) plan_joint_init_pos = self.planner_setting.get( PlannerVectorParam_KinematicDefaultJointPositions) if len(plan_joint_init_pos) != self.robot.num_ctrl_joints: raise ValueError( 'Number of joints in config file not same as required for robot\n' + 'Got %d joints but robot expects %d joints.' % ( len(plan_joint_init_pos), self.robot.num_ctrl_joints)) q[7:] = np.matrix(plan_joint_init_pos).T q[2] = self.robot.floor_height + 0.32 dq = np.matrix(np.zeros(self.robot.robot.nv)).T com_ref = init_state.com lmom_ref = np.zeros(3) amom_ref = np.zeros(3) endeff_pos_ref = np.array([init_state.effPosition(i) for i in range(init_state.effNum())]) endeff_vel_ref = np.matrix(np.zeros((init_state.effNum(), 3))) endeff_contact = np.ones(init_state.effNum()) quad_goal = se3.Quaternion(se3.rpy.rpyToMatrix(np.matrix([0.0, 0, 0.]).T)) q[3:7] = quad_goal.coeffs() for iters in range(self.max_iterations): # Adding small P controller for the base orientation to always start with flat # oriented base. quad_q = se3.Quaternion(float(q[6]), float(q[3]), float(q[4]), float(q[5])) amom_ref = 1e-1 * se3.log((quad_goal * quad_q.inverse()).matrix()) res = self.inv_kin.compute(q, dq, com_ref, lmom_ref, amom_ref, endeff_pos_ref, endeff_vel_ref, endeff_contact, None) q = se3.integrate(self.robot.model, q, res) if np.linalg.norm(res) < 1e-3: print('Found initial configuration after {} iterations'.format(iters + 1)) break if iters == self.max_iterations - 1: print('Failed to converge for initial setup.') print("initial configuration: \n", q) self.q_init = q.copy() self.dq_init = dq.copy() def optimize(self, init_state, contact_sequence, dynamic_sequence, plotting=False): self.init_state = init_state self.contact_sequence = contact_sequence self.dynamic_sequence = dynamic_sequence self.q_via = None # Create array with centroidal and endeffector informations. self.fill_data_from_dynamics() self.fill_endeffector_trajectory() # Run the optimization for the initial configuration only once. if self.q_init is None: self.optimize_initial_position(init_state) # Get the desired joint trajectory # print "num_joint_via:",self.planner_setting.get(PlannerIntParam_NumJointViapoints) # print "joint_via:",self.planner_setting.get(PlannerCVectorParam_JointViapoints) # TODO: this is for jump, should go to config file # q_jump = [1., 0.1, -0.2 ,0.1, -0.2 ,-0.1, 0.2 ,-0.1, 0.2] # q_via = np.matrix([.75, np.pi/2, -np.pi, np.pi/2, -np.pi, -np.pi/2, np.pi, -np.pi/2, np.pi]).T # q_max = np.matrix([1.35, .7*np.pi/2, -.7*np.pi, .7*np.pi/2, -.7*np.pi, -.7*np.pi/2, .7*np.pi, -.7*np.pi/2, .7*np.pi]).T # q_via0 = np.vstack((q_via.T, q_jump)) # self.q_via = np.vstack((q_via0, q_max.T)) joint_traj_gen = JointTrajectoryGenerator() joint_traj_gen.num_time_steps = self.num_time_steps joint_traj_gen.q_init = self.q_init[7:] self.joint_des = np.zeros((len(self.q_init[7:]),self.num_time_steps), float) if self.q_via is None: for i in range (self.num_time_steps): self.joint_des[:,i] = self.q_init[7 : ].T else: joint_traj_gen.joint_traj(self.q_via) for it in range(self.num_time_steps): self.joint_des[:,it] = joint_traj_gen.eval_traj(it) # Compute inverse kinematics over the full trajectory. self.inv_kin.is_init_time = 0 q, dq = self.q_init.copy(), self.dq_init.copy() for it in range(self.num_time_steps): quad_goal = se3.Quaternion(se3.rpy.rpyToMatrix(np.matrix([0.0, 0, 0.]).T)) quad_q = se3.Quaternion(float(q[6]), float(q[3]), float(q[4]), float(q[5])) amom_ref = (self.reg_orientation * se3.log((quad_goal * quad_q.inverse()).matrix()).T + self.amom_dyn[it]).reshape(-1) joint_regularization_ref = self.reg_joint_position * (np.matrix(self.joint_des[:,it]).T - q[7 : ]) # joint_regularization_ref = self.reg_joint_position * (self.q_init[7 : ] - q[7 : ]) # Fill the kinematics results for it. self.inv_kin.forward_robot(q, dq) self.fill_kinematic_result(it, q, dq) dq = self.inv_kin.compute( q, dq, self.com_dyn[it], self.lmom_dyn[it], amom_ref, self.endeff_pos_ref[it], self.endeff_vel_ref[it], self.endeff_contact[it], joint_regularization_ref) # Integrate to the next state. q = se3.integrate(self.robot.model, q, dq * self.dt)
2.265625
2
gullveig/web/__init__.py
Addvilz/gullveig
8
4738
<reponame>Addvilz/gullveig import logging from gullveig import bootstrap_default_logger # Configure default logging def _configure_default_web_logger(): logger = logging.getLogger('gullveig-web') bootstrap_default_logger(logger) api_logger = logging.getLogger('gullveig-api') bootstrap_default_logger(api_logger) aio_logger = logging.getLogger('aiohttp.server') bootstrap_default_logger(aio_logger) _configure_default_web_logger()
1.632813
2
jupyterhub_http_authenticator/httpauthenticator.py
clockfly/jupterhub_http_authenticator
0
4739
import json import urllib import os import jupyterhub from tornado.httpclient import HTTPRequest, AsyncHTTPClient from traitlets import Unicode from jupyterhub.auth import Authenticator from tornado import gen class HttpAuthenticator(Authenticator): server = Unicode( None, allow_none=True, config=True, help=""" Http authentication server. """ ) appid = Unicode( None, allow_none=True, config=True, help=""" Application Id recognized by the http authentication server """ ) @gen.coroutine def authenticate(self, handler, data): http_client = AsyncHTTPClient() headers = { "Accept": "application/json", "User-Agent": "JupyterHub", } params = dict( type="json", appid=self.appid, ac=data['username'], pw=data['password'] ) req = HTTPRequest(self.server, method="POST", headers=headers, body=urllib.parse.urlencode(params), validate_cert = False ) resp = yield http_client.fetch(req) reply = json.loads(resp.body.decode('utf8', 'replace')) if reply.get("code") == 200: return (reply.get("data").get("UserCN")) else: return None
2.65625
3
src/lr_find.py
KushajveerSingh/fastai_without_fastai
12
4740
import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt # NOT -> ParameterModule # NOT -> children_and_parameters # NOT -> flatten_model # NOT -> lr_range # NOT -> scheduling functions # NOT -> SmoothenValue # YES -> lr_find # NOT -> plot_lr_find # NOT TO BE MODIFIED class ParameterModule(nn.Module): "Register a lone parameter 'p' in a module" def __init__(self, p:nn.Parameter): super().__init__() self.val = p def forward(self, x): return x # NOT TO BE MODIFIED # To be used to flatten_model def children_and_parameters(m:nn.Module): "Return the children of `m` and its direct parameters not registered in modules." children = list(m.children()) children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],[]) for p in m.parameters(): if id(p) not in children_p: children.append(ParameterModule(p)) return children # NOT TO BE MODIFIED flatten_model = lambda m: sum(map(flatten_model,children_and_parameters(m)),[]) if len(list(m.children())) else [m] # NOT TO BE MODIFIED def lr_range(model, lr): """ Build differential learning rate from lr. It will give you the Arguments: model :- torch.nn.Module lr :- float or slice Returns: Depending upon lr """ if not isinstance(lr, slice): return lr num_layer = len([nn.Sequential(*flatten_model(model))]) if lr.start: mult = lr.stop / lr.start step = mult**(1/(num_layer-1)) res = np.array([lr.start*(step**i) for i in range(num_layer)]) else: res = [lr.stop/10.]*(num_layer-1) + [lr.stop] return np.array(res) # NOT TO BE MODIFIED # These are the functions that would give us the values of lr. Liks for linearly # increasing lr we would use annealing_linear. # You can add your own custom function, for producing lr. # By defualt annealing_exp is used for both lr and momentum def annealing_no(start, end, pct:float): "No annealing, always return `start`." return start def annealing_linear(start, end, pct:float): "Linearly anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start + pct * (end-start) def annealing_exp(start, end, pct:float): "Exponentially anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start * (end/start) ** pct def annealing_cos(start, end, pct:float): "Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0." cos_out = np.cos(np.pi * pct) + 1 return end + (start-end)/2 * cos_out def do_annealing_poly(start, end, pct:float, degree): return end + (start-end) * (1-pct)**degree # NOT TO BE MODIFIED class Stepper(): """ Used to step from start, end ('vals') over 'n_iter' iterations on a schedule. We will create a stepper object and then use one of the above annelaing functions, to step from start lr to end lr. """ def __init__(self, vals, n_iter:int, func=None): self.start, self.end = (vals[0], vals[1]) if isinstance(vals, tuple) else (vals,0) self.n_iter = max(1, n_iter) if func is None: self.func = annealing_linear if isinstance(vals, tuple) else annealing_no else: self.func = func self.n = 0 def step(self): "Return next value along annealed schedule" self.n += 1 return self.func(self.start, self.end, self.n/self.n_iter) @property def is_done(self)->bool: "Return 'True' if schedule completed" return self.n >= self.n_iter # NOT TO BE MODIFIED class SmoothenValue(): "Create a smooth moving average for a value (loss, etc) using `beta`." def __init__(self, beta:float): self.beta,self.n,self.mov_avg = beta,0,0 def add_value(self, val:float)->None: "Add `val` to calculate updated smoothed value." self.n += 1 self.mov_avg = self.beta * self.mov_avg + (1 - self.beta) * val self.smooth = self.mov_avg / (1 - self.beta ** self.n) # TO BE MODIFIED IN SOME CASES def lr_find(data_loader, model, loss_fn, opt, wd:int=0, start_lr:float=1e-7, end_lr:float=10, num_it:int=100, stop_div:bool=True, smooth_beta:float=0.98, use_gpu:bool=True, device=torch.device('cuda'), anneal_func=annealing_exp): """ The main function that you will call to plot learning_rate vs losses graph. It is the only function from lr_find.py that you will call. By default it will use GPU. It assumes your model is already on GPU if you use use_gpu. Arguments:- data_loader :- torch.utils.data.DataLoader model :- torch.nn.Module loss_fn :- torch.nn.LossFunction opt :- torch.optim.Optimizer wd :- weight decay (default=0). start_lr :- The learning rate from where to start in lr_find (default=1e-7) end_lr :- The learning rate at which to end lr_find (default=10) num_it :- Number of iterations for lr_find (default=100) stop_div :- If the loss diverges, then stop early (default=True) smooth_beta :- The beta value to smoothen the running avergae of the loss function (default=0.98) use_gpu :- True (train on GPU) else CPU anneal_func :- The step function you want to use (default exp) device :- Torch device to use for training model (default GPU) Returns: losses :- list of smoothened version of losses lrs :- list of all lrs that we test """ model.train() stop = False flag = False best_loss = 0. iteration = 0 losses = [] lrs = [] lrs.append(start_lr) start_lr = lr_range(model, start_lr) start_lr = np.array(start_lr) if isinstance(start_lr, (tuple, list)) else start_lr end_lr = lr_range(model, end_lr) end_lr = np.array(end_lr) if isinstance(end_lr, (tuple, list)) else end_lr sched = Stepper((start_lr, end_lr), num_it, anneal_func) smoothener = SmoothenValue(smooth_beta) epochs = int(np.ceil(num_it/len(data_loader))) # save model_dict model_state = model.state_dict() opt_state = opt.state_dict() # Set optimizer learning_rate = start_lr for group in opt.param_groups: group['lr'] = sched.start for i in range(epochs): for data in data_loader: opt.zero_grad() ################### TO BE MODIFIED ################### # Depending on your model, you will have to modify your # data pipeline and how you give inputs to your model. inputs, labels = data if use_gpu: inputs = inputs.to(device) labels = labels.to(device) outputs = model(inputs) loss = loss_fn(outputs, labels) ##################################################### if use_gpu: smoothener.add_value(loss.detach().cpu()) else: smoothener.add_value(loss.detach()) smooth_loss = smoothener.smooth losses.append(smooth_loss) loss.backward() ################### TO BE MODIFIED ################### # For AdamW. If you want to use Adam, comment these lines for group in opt.param_groups: for param in group['params']: param.data = param.data.add(-wd * group['lr'], param.data) ##################################################### opt.step() # Change lr new_lr = sched.step() lrs.append(new_lr) for group in opt.param_groups: group['lr'] = new_lr ################### TO BE MODIFIED ################### # You necessarily don't want to change it. But in cases # when you are maximizing the loss, then you will have # to change it. if iteration == 0 or smooth_loss < best_loss: best_loss = smooth_loss iteration += 1 if sched.is_done or (stop_div and (smooth_loss > 4*best_loss or torch.isnan(loss))): flag = True break ##################################################### if iteration%10 == 0: print(f'Iteration: {iteration}') if flag: break # Load state dict model.load_state_dict(model_state) opt.load_state_dict(opt_state) lrs.pop() print(f'LR Finder is complete.') return losses, lrs # NOT TO BE MODIFIED def plot_lr_find(losses, lrs, skip_start:int=10, skip_end:int=5, suggestion:bool=False, return_fig:bool=None): """ It will take the losses and lrs returned by lr_find as input. Arguments:- skip_start -> It will skip skip_start lrs from the start skip_end -> It will skip skip_end lrs from the end suggestion -> If you want to see the point where the gradient changes most return_fig -> True then get the fig in the return statement """ lrs = lrs[skip_start:-skip_end] if skip_end > 0 else lrs[skip_start:] losses = losses[skip_start:-skip_end] if skip_end > 0 else losses[skip_start:] losses = [x.item() for x in losses] fig, ax = plt.subplots(1, 1) ax.plot(lrs, losses) ax.set_ylabel("Loss") ax.set_xlabel("Learning Rate") ax.set_xscale('log') ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.0e')) if suggestion: try: mg = (np.gradient(np.array(losses))).argmin() except: print("Failed to compute the gradients, there might not be enough points.") return print(f"Min numerical gradient: {lrs[mg]:.2E}") ax.plot(lrs[mg], losses[mg], markersize=10, marker='o', color='red') if return_fig is not None: return fig
2.546875
3
SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py
Polidea/SiriusObfuscator
427
4741
<gh_stars>100-1000 """ Test the lldb disassemble command on each call frame when stopped on C's ctor. """ from __future__ import print_function import os import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class IterateFrameAndDisassembleTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def test_and_run_command(self): """Disassemble each call frame when stopped on C's constructor.""" self.build() self.breakOnCtor() raw_output = self.res.GetOutput() frameRE = re.compile(r""" ^\s\sframe # heading for the frame info, .* # wildcard, and 0x[0-9a-f]{16} # the frame pc, and \sa.out`(.+) # module`function, and \s\+\s # the rest ' + ....' """, re.VERBOSE) for line in raw_output.split(os.linesep): match = frameRE.search(line) if match: function = match.group(1) #print("line:", line) #print("function:", function) self.runCmd("disassemble -n '%s'" % function) @add_test_categories(['pyapi']) def test_and_python_api(self): """Disassemble each call frame when stopped on C's constructor.""" self.build() self.breakOnCtor() # Now use the Python API to get at each function on the call stack and # disassemble it. target = self.dbg.GetSelectedTarget() process = target.GetProcess() thread = lldbutil.get_stopped_thread( process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) depth = thread.GetNumFrames() for i in range(depth - 1): frame = thread.GetFrameAtIndex(i) function = frame.GetFunction() # Print the function header. if self.TraceOn(): print() print(function) if function: # Get all instructions for this function and print them out. insts = function.GetInstructions(target) for inst in insts: # We could simply do 'print inst' to print out the disassembly. # But we want to print to stdout only if self.TraceOn() is # True. disasm = str(inst) if self.TraceOn(): print(disasm) def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.cpp. self.line = line_number('main.cpp', '// Set break point at this line.') def breakOnCtor(self): """Setup/run the program so it stops on C's constructor.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break on the ctor function of class C. bpno = lldbutil.run_break_set_by_file_and_line( self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, substrs=['stopped', 'stop reason = breakpoint %d.' % (bpno)]) # This test was failing because we fail to put the C:: in front of constructore. # We should maybe make another testcase to cover that specifically, but we shouldn't # fail this whole testcase for an inessential issue. # We should be stopped on the ctor function of class C. # self.expect("thread backtrace", BACKTRACE_DISPLAYED_CORRECTLY, # substrs = ['C::C'])
2.28125
2
reservedwords.py
irinaid/MAlice
1
4742
''' All the reserved, individual words used in MAlice. ''' A = "a" ALICE = "Alice" AND = "and" ATE = "ate" BECAME = "became" BECAUSE = "because" BUT = "but" CLOSED = "closed" COMMA = "," CONTAINED = "contained" DOT = "." DRANK = "drank" EITHER = "either" ENOUGH = "enough" EVENTUALLY = "eventually" FOUND = "found" HAD = "had" HATTA = "hatta" LETTER = "letter" LOOKING_GLASS = "looking-glass" LPAR = "(" MAYBE = "maybe" NUMBER = "number" OF = "of" OPENED = "opened" OR = "or" PERHAPS = "perhaps" PIECE = "piece" QUESTION = "?" ROOM = "room" RPAR = ")" S = "'s" SAID = "said" SENTENCE = "sentence" SO = "so" SPIDER = "spider" SPOKE = "spoke" THE = "The" THEN = "then" TIMES = "times" TOO = "too" UNDERSCORE = "_" UNSURE = "unsure" WAS = "was" WHAT = "what" WHICH = "which" RESTRICTED = [ A, ALICE, AND, ATE, BECAME ,BECAUSE ,BUT ,CLOSED ,COMMA ,CONTAINED ,DOT ,DRANK ,EITHER ,ENOUGH ,EVENTUALLY ,FOUND ,HAD ,HATTA ,LETTER ,LOOKING_GLASS ,LPAR ,MAYBE ,NUMBER ,OF ,OPENED ,OR ,PERHAPS ,PIECE ,QUESTION ,ROOM ,RPAR ,S ,SAID, SENTENCE ,SO ,SPIDER ,SPOKE ,THE ,THEN ,TIMES ,TOO ,UNDERSCORE ,UNSURE ,WAS ,WHAT ,WHICH]
2.265625
2
leetcode/0057_Insert_Interval/result.py
theck17/notes
0
4743
# !/usr/bin/env python3 # Author: C.K # Email: <EMAIL> # DateTime:2021-04-12 18:35:15 # Description: import os import sys class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: res, i = [], 0 for interval in intervals: if interval[1] < newInterval[0]: res.append(interval) elif interval[0] > newInterval[1]: res.append(newInterval) newInterval = interval elif interval[1] >= newInterval[0] or newInterval[1] >= interval[0]: newInterval = [ min(interval[0], newInterval[0]), max(interval[1], newInterval[1]) ] res.append(newInterval) return res if __name__ == "__main__": pass
3.546875
4
src/pymortests/benchmarks.py
TiKeil/pymor
1
4744
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2020 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) from pymortests.base import runmodule if __name__ == "__main__": runmodule(filename=__file__)
1.09375
1
storage3/_sync/client.py
anand2312/storage-py
0
4745
<reponame>anand2312/storage-py<gh_stars>0 from ..utils import SyncClient, __version__ from .bucket import SyncStorageBucketAPI from .file_api import SyncBucketProxy __all__ = [ "SyncStorageClient", ] class SyncStorageClient(SyncStorageBucketAPI): """Manage storage buckets and files.""" def __init__(self, url: str, headers: dict[str, str]) -> None: super().__init__( url, {"User-Agent": f"supabase-py/storage3 v{__version__}", **headers}, SyncClient(), ) def from_(self, id: str) -> SyncBucketProxy: """Run a storage file operation. Parameters ---------- id The unique identifier of the bucket """ return SyncBucketProxy(id, self.url, self.headers, self._client)
2.484375
2
repo/script.module.liveresolver/lib/js2py/translators/__init__.py
Hades01/Addons
3
4746
# The MIT License # # Copyright 2014, 2015 <NAME> # # 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 __all__ = ['PyJsParser', 'Node', 'WrappingNode', 'node_to_dict', 'parse', 'translate_js', 'translate', 'syntax_tree_translate', 'DEFAULT_HEADER'] __author__ = '<NAME>' __version__ = '2.2.0' from pyjsparser import PyJsParser, Node, WrappingNode, node_to_dict from translator import translate_js, trasnlate, syntax_tree_translate, DEFAULT_HEADER def parse(javascript_code): """Returns syntax tree of javascript_code. Syntax tree has the same structure as syntax tree produced by esprima.js Same as PyJsParser().parse For your convenience :) """ p = PyJsParser() return p.parse(javascript_code)
1.703125
2
src/test/python/test_scc_pacs.py
xchange11/ttconv-1
66
4747
<filename>src/test/python/test_scc_pacs.py #!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2020, Sandflow Consulting LLC # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit tests for the SCC PACs""" # pylint: disable=R0201,C0115,C0116 import unittest from ttconv.scc.codes.preambles_address_codes import SccPreambleAddressCode from ttconv.style_properties import TextDecorationType, NamedColors, FontStyleType class SCCPreambleAddressCodesTest(unittest.TestCase): def test_scc_pac_values(self): channel_1_byte_1 = [0x11, 0x12, 0x15, 0x16, 0x17, 0x10, 0x13, 0x14] channel_2_byte_1 = [0x19, 0x1A, 0x1D, 0x1E, 0x1F, 0x18, 0x1B, 0x1C] all_range = list(range(0x00, 0XFF)) byte_2_range = range(0x40, 0x80) other_bytes_1 = [item for item in all_range if item not in channel_1_byte_1 and item not in channel_2_byte_1] other_bytes_2 = [item for item in all_range if item not in list(byte_2_range)] for b1 in channel_1_byte_1: for b2 in byte_2_range: pac = SccPreambleAddressCode.find(b1, b2) if b2 > 0x5F and b1 % 0x08 == 0: # row 11 case self.assertIsNone(pac) else: self.assertIsNotNone(pac) for b2 in other_bytes_2: self.assertIsNone(SccPreambleAddressCode.find(b1, b2)) for b1 in channel_2_byte_1: for b2 in byte_2_range: pac = SccPreambleAddressCode.find(b1, b2) if b2 > 0x5F and b1 % 0x08 == 0: # row 11 case self.assertIsNone(pac) else: self.assertIsNotNone(pac) for b2 in other_bytes_2: self.assertIsNone(SccPreambleAddressCode.find(b1, b2)) for b1 in other_bytes_1: for b2 in range(0x00, 0xFF): self.assertIsNone(SccPreambleAddressCode.find(b1, b2)) def check_scc_pac_attributes(self, pac, channel, row, indent, color, font_style, text_decoration): self.assertEqual(channel, pac.get_channel()) self.assertEqual(row, pac.get_row()) self.assertEqual(indent, pac.get_indent()) self.assertEqual(color, pac.get_color()) self.assertEqual(font_style, pac.get_font_style()) self.assertEqual(text_decoration, pac.get_text_decoration()) def test_scc_pac_white(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x40), 1, 1, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x60), 1, 2, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x40), 1, 3, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x60), 1, 4, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x40), 1, 5, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x60), 1, 6, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x40), 1, 7, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x60), 1, 8, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x40), 1, 9, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x60), 1, 10, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x40), 1, 11, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x40), 1, 12, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x60), 1, 13, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x40), 1, 14, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x60), 1, 15, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x40), 2, 1, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x60), 2, 2, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x40), 2, 3, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x60), 2, 4, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x40), 2, 5, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x60), 2, 6, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x40), 2, 7, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x60), 2, 8, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x40), 2, 9, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x60), 2, 10, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x40), 2, 11, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x40), 2, 12, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x60), 2, 13, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x40), 2, 14, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x60), 2, 15, None, NamedColors.white.value, None, None) def test_scc_pac_white_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x41), 1, 1, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x61), 1, 2, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x41), 1, 3, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x61), 1, 4, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x41), 1, 5, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x61), 1, 6, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x41), 1, 7, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x61), 1, 8, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x41), 1, 9, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x61), 1, 10, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x41), 1, 11, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x41), 1, 12, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x61), 1, 13, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x41), 1, 14, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x61), 1, 15, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x41), 2, 1, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x61), 2, 2, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x41), 2, 3, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x61), 2, 4, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x41), 2, 5, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x61), 2, 6, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x41), 2, 7, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x61), 2, 8, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x41), 2, 9, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x61), 2, 10, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x41), 2, 11, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x41), 2, 12, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x61), 2, 13, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x41), 2, 14, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x61), 2, 15, None, NamedColors.white.value, None, TextDecorationType(underline=True)) def test_scc_pac_green(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x42), 1, 1, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x62), 1, 2, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x42), 1, 3, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x62), 1, 4, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x42), 1, 5, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x62), 1, 6, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x42), 1, 7, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x62), 1, 8, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x42), 1, 9, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x62), 1, 10, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x42), 1, 11, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x42), 1, 12, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x62), 1, 13, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x42), 1, 14, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x62), 1, 15, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x42), 2, 1, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x62), 2, 2, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x42), 2, 3, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x62), 2, 4, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x42), 2, 5, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x62), 2, 6, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x42), 2, 7, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x62), 2, 8, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x42), 2, 9, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x62), 2, 10, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x42), 2, 11, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x42), 2, 12, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x62), 2, 13, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x42), 2, 14, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x62), 2, 15, None, NamedColors.green.value, None, None) def test_scc_pac_green_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x43), 1, 1, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x63), 1, 2, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x43), 1, 3, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x63), 1, 4, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x43), 1, 5, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x63), 1, 6, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x43), 1, 7, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x63), 1, 8, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x43), 1, 9, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x63), 1, 10, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x43), 1, 11, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x43), 1, 12, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x63), 1, 13, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x43), 1, 14, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x63), 1, 15, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x43), 2, 1, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x63), 2, 2, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x43), 2, 3, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x63), 2, 4, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x43), 2, 5, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x63), 2, 6, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x43), 2, 7, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x63), 2, 8, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x43), 2, 9, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x63), 2, 10, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x43), 2, 11, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x43), 2, 12, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x63), 2, 13, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x43), 2, 14, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x63), 2, 15, None, NamedColors.green.value, None, TextDecorationType(underline=True)) def test_scc_pac_blue(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x44), 1, 1, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x64), 1, 2, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x44), 1, 3, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x64), 1, 4, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x44), 1, 5, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x64), 1, 6, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x44), 1, 7, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x64), 1, 8, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x44), 1, 9, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x64), 1, 10, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x44), 1, 11, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x44), 1, 12, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x64), 1, 13, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x44), 1, 14, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x64), 1, 15, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x44), 2, 1, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x64), 2, 2, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x44), 2, 3, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x64), 2, 4, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x44), 2, 5, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x64), 2, 6, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x44), 2, 7, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x64), 2, 8, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x44), 2, 9, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x64), 2, 10, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x44), 2, 11, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x44), 2, 12, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x64), 2, 13, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x44), 2, 14, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x64), 2, 15, None, NamedColors.blue.value, None, None) def test_scc_pac_blue_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x45), 1, 1, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x65), 1, 2, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x45), 1, 3, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x65), 1, 4, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x45), 1, 5, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x65), 1, 6, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x45), 1, 7, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x65), 1, 8, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x45), 1, 9, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x65), 1, 10, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x45), 1, 11, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x45), 1, 12, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x65), 1, 13, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x45), 1, 14, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x65), 1, 15, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x45), 2, 1, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x65), 2, 2, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x45), 2, 3, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x65), 2, 4, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x45), 2, 5, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x65), 2, 6, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x45), 2, 7, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x65), 2, 8, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x45), 2, 9, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x65), 2, 10, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x45), 2, 11, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x45), 2, 12, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x65), 2, 13, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x45), 2, 14, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x65), 2, 15, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) def test_scc_pac_cyan(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x46), 1, 1, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x66), 1, 2, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x46), 1, 3, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x66), 1, 4, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x46), 1, 5, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x66), 1, 6, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x46), 1, 7, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x66), 1, 8, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x46), 1, 9, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x66), 1, 10, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x46), 1, 11, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x46), 1, 12, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x66), 1, 13, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x46), 1, 14, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x66), 1, 15, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x46), 2, 1, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x66), 2, 2, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x46), 2, 3, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x66), 2, 4, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x46), 2, 5, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x66), 2, 6, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x46), 2, 7, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x66), 2, 8, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x46), 2, 9, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x66), 2, 10, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x46), 2, 11, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x46), 2, 12, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x66), 2, 13, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x46), 2, 14, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x66), 2, 15, None, NamedColors.cyan.value, None, None) def test_scc_pac_cyan_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x47), 1, 1, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x67), 1, 2, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x47), 1, 3, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x67), 1, 4, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x47), 1, 5, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x67), 1, 6, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x47), 1, 7, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x67), 1, 8, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x47), 1, 9, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x67), 1, 10, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x47), 1, 11, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x47), 1, 12, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x67), 1, 13, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x47), 1, 14, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x67), 1, 15, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x47), 2, 1, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x67), 2, 2, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x47), 2, 3, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x67), 2, 4, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x47), 2, 5, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x67), 2, 6, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x47), 2, 7, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x67), 2, 8, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x47), 2, 9, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x67), 2, 10, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x47), 2, 11, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x47), 2, 12, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x67), 2, 13, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x47), 2, 14, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x67), 2, 15, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) def test_scc_pac_red(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x48), 1, 1, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x68), 1, 2, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x48), 1, 3, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x68), 1, 4, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x48), 1, 5, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x68), 1, 6, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x48), 1, 7, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x68), 1, 8, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x48), 1, 9, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x68), 1, 10, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x48), 1, 11, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x48), 1, 12, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x68), 1, 13, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x48), 1, 14, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x68), 1, 15, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x48), 2, 1, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x68), 2, 2, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x48), 2, 3, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x68), 2, 4, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x48), 2, 5, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x68), 2, 6, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x48), 2, 7, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x68), 2, 8, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x48), 2, 9, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x68), 2, 10, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x48), 2, 11, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x48), 2, 12, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x68), 2, 13, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x48), 2, 14, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x68), 2, 15, None, NamedColors.red.value, None, None) def test_scc_pac_red_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x49), 1, 1, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x69), 1, 2, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x49), 1, 3, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x69), 1, 4, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x49), 1, 5, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x69), 1, 6, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x49), 1, 7, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x69), 1, 8, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x49), 1, 9, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x69), 1, 10, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x49), 1, 11, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x49), 1, 12, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x69), 1, 13, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x49), 1, 14, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x69), 1, 15, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x49), 2, 1, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x69), 2, 2, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x49), 2, 3, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x69), 2, 4, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x49), 2, 5, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x69), 2, 6, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x49), 2, 7, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x69), 2, 8, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x49), 2, 9, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x69), 2, 10, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x49), 2, 11, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x49), 2, 12, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x69), 2, 13, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x49), 2, 14, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x69), 2, 15, None, NamedColors.red.value, None, TextDecorationType(underline=True)) def test_scc_pac_yellow(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4A), 1, 1, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6A), 1, 2, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4A), 1, 3, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6A), 1, 4, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4A), 1, 5, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6A), 1, 6, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4A), 1, 7, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6A), 1, 8, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4A), 1, 9, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6A), 1, 10, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4A), 1, 11, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4A), 1, 12, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6A), 1, 13, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4A), 1, 14, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6A), 1, 15, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4A), 2, 1, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6A), 2, 2, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4A), 2, 3, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6A), 2, 4, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4A), 2, 5, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6A), 2, 6, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4A), 2, 7, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6A), 2, 8, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4A), 2, 9, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6A), 2, 10, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4A), 2, 11, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4A), 2, 12, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6A), 2, 13, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4A), 2, 14, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6A), 2, 15, None, NamedColors.yellow.value, None, None) def test_scc_pac_yellow_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4B), 1, 1, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6B), 1, 2, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4B), 1, 3, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6B), 1, 4, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4B), 1, 5, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6B), 1, 6, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4B), 1, 7, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6B), 1, 8, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4B), 1, 9, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6B), 1, 10, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4B), 1, 11, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4B), 1, 12, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6B), 1, 13, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4B), 1, 14, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6B), 1, 15, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4B), 2, 1, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6B), 2, 2, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4B), 2, 3, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6B), 2, 4, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4B), 2, 5, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6B), 2, 6, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4B), 2, 7, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6B), 2, 8, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4B), 2, 9, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6B), 2, 10, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4B), 2, 11, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4B), 2, 12, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6B), 2, 13, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4B), 2, 14, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6B), 2, 15, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) def test_scc_pac_magenta(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4C), 1, 1, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6C), 1, 2, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4C), 1, 3, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6C), 1, 4, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4C), 1, 5, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6C), 1, 6, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4C), 1, 7, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6C), 1, 8, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4C), 1, 9, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6C), 1, 10, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4C), 1, 11, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4C), 1, 12, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6C), 1, 13, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4C), 1, 14, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6C), 1, 15, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4C), 2, 1, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6C), 2, 2, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4C), 2, 3, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6C), 2, 4, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4C), 2, 5, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6C), 2, 6, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4C), 2, 7, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6C), 2, 8, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4C), 2, 9, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6C), 2, 10, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4C), 2, 11, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4C), 2, 12, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6C), 2, 13, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4C), 2, 14, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6C), 2, 15, None, NamedColors.magenta.value, None, None) def test_scc_pac_magenta_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4D), 1, 1, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6D), 1, 2, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4D), 1, 3, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6D), 1, 4, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4D), 1, 5, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6D), 1, 6, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4D), 1, 7, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6D), 1, 8, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4D), 1, 9, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6D), 1, 10, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4D), 1, 11, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4D), 1, 12, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6D), 1, 13, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4D), 1, 14, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6D), 1, 15, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4D), 2, 1, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6D), 2, 2, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4D), 2, 3, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6D), 2, 4, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4D), 2, 5, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6D), 2, 6, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4D), 2, 7, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6D), 2, 8, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4D), 2, 9, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6D), 2, 10, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4D), 2, 11, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4D), 2, 12, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6D), 2, 13, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4D), 2, 14, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6D), 2, 15, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) def test_scc_pac_white_italics(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4E), 1, 1, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6E), 1, 2, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4E), 1, 3, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6E), 1, 4, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4E), 1, 5, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6E), 1, 6, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4E), 1, 7, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6E), 1, 8, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4E), 1, 9, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6E), 1, 10, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4E), 1, 11, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4E), 1, 12, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6E), 1, 13, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4E), 1, 14, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6E), 1, 15, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4E), 2, 1, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6E), 2, 2, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4E), 2, 3, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6E), 2, 4, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4E), 2, 5, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6E), 2, 6, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4E), 2, 7, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6E), 2, 8, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4E), 2, 9, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6E), 2, 10, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4E), 2, 11, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4E), 2, 12, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6E), 2, 13, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4E), 2, 14, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6E), 2, 15, None, NamedColors.white.value, FontStyleType.italic, None) def test_scc_pac_white_italics_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4F), 1, 1, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6F), 1, 2, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4F), 1, 3, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6F), 1, 4, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4F), 1, 5, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6F), 1, 6, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4F), 1, 7, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6F), 1, 8, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4F), 1, 9, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6F), 1, 10, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4F), 1, 11, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4F), 1, 12, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6F), 1, 13, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4F), 1, 14, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6F), 1, 15, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4F), 2, 1, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6F), 2, 2, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4F), 2, 3, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6F), 2, 4, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4F), 2, 5, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6F), 2, 6, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4F), 2, 7, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6F), 2, 8, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4F), 2, 9, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6F), 2, 10, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4F), 2, 11, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4F), 2, 12, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6F), 2, 13, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4F), 2, 14, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6F), 2, 15, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) def test_scc_pac_indent_0(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x50), 1, 1, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x70), 1, 2, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x50), 1, 3, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x70), 1, 4, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x50), 1, 5, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x70), 1, 6, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x50), 1, 7, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x70), 1, 8, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x50), 1, 9, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x70), 1, 10, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x50), 1, 11, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x50), 1, 12, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x70), 1, 13, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x50), 1, 14, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x70), 1, 15, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x50), 2, 1, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x70), 2, 2, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x50), 2, 3, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x70), 2, 4, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x50), 2, 5, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x70), 2, 6, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x50), 2, 7, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x70), 2, 8, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x50), 2, 9, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x70), 2, 10, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x50), 2, 11, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x50), 2, 12, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x70), 2, 13, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x50), 2, 14, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x70), 2, 15, 0, None, None, None) def test_scc_pac_indent_0_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x51), 1, 1, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x71), 1, 2, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x51), 1, 3, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x71), 1, 4, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x51), 1, 5, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x71), 1, 6, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x51), 1, 7, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x71), 1, 8, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x51), 1, 9, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x71), 1, 10, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x51), 1, 11, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x51), 1, 12, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x71), 1, 13, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x51), 1, 14, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x71), 1, 15, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x51), 2, 1, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x71), 2, 2, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x51), 2, 3, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x71), 2, 4, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x51), 2, 5, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x71), 2, 6, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x51), 2, 7, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x71), 2, 8, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x51), 2, 9, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x71), 2, 10, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x51), 2, 11, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x51), 2, 12, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x71), 2, 13, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x51), 2, 14, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x71), 2, 15, 0, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_4(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x52), 1, 1, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x72), 1, 2, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x52), 1, 3, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x72), 1, 4, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x52), 1, 5, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x72), 1, 6, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x52), 1, 7, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x72), 1, 8, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x52), 1, 9, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x72), 1, 10, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x52), 1, 11, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x52), 1, 12, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x72), 1, 13, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x52), 1, 14, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x72), 1, 15, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x52), 2, 1, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x72), 2, 2, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x52), 2, 3, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x72), 2, 4, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x52), 2, 5, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x72), 2, 6, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x52), 2, 7, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x72), 2, 8, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x52), 2, 9, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x72), 2, 10, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x52), 2, 11, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x52), 2, 12, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x72), 2, 13, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x52), 2, 14, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x72), 2, 15, 4, None, None, None) def test_scc_pac_indent_4_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x53), 1, 1, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x73), 1, 2, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x53), 1, 3, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x73), 1, 4, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x53), 1, 5, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x73), 1, 6, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x53), 1, 7, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x73), 1, 8, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x53), 1, 9, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x73), 1, 10, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x53), 1, 11, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x53), 1, 12, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x73), 1, 13, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x53), 1, 14, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x73), 1, 15, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x53), 2, 1, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x73), 2, 2, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x53), 2, 3, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x73), 2, 4, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x53), 2, 5, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x73), 2, 6, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x53), 2, 7, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x73), 2, 8, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x53), 2, 9, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x73), 2, 10, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x53), 2, 11, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x53), 2, 12, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x73), 2, 13, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x53), 2, 14, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x73), 2, 15, 4, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_8(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x54), 1, 1, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x74), 1, 2, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x54), 1, 3, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x74), 1, 4, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x54), 1, 5, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x74), 1, 6, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x54), 1, 7, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x74), 1, 8, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x54), 1, 9, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x74), 1, 10, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x54), 1, 11, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x54), 1, 12, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x74), 1, 13, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x54), 1, 14, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x74), 1, 15, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x54), 2, 1, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x74), 2, 2, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x54), 2, 3, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x74), 2, 4, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x54), 2, 5, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x74), 2, 6, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x54), 2, 7, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x74), 2, 8, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x54), 2, 9, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x74), 2, 10, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x54), 2, 11, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x54), 2, 12, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x74), 2, 13, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x54), 2, 14, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x74), 2, 15, 8, None, None, None) def test_scc_pac_indent_8_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x55), 1, 1, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x75), 1, 2, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x55), 1, 3, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x75), 1, 4, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x55), 1, 5, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x75), 1, 6, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x55), 1, 7, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x75), 1, 8, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x55), 1, 9, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x75), 1, 10, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x55), 1, 11, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x55), 1, 12, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x75), 1, 13, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x55), 1, 14, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x75), 1, 15, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x55), 2, 1, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x75), 2, 2, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x55), 2, 3, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x75), 2, 4, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x55), 2, 5, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x75), 2, 6, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x55), 2, 7, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x75), 2, 8, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x55), 2, 9, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x75), 2, 10, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x55), 2, 11, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x55), 2, 12, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x75), 2, 13, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x55), 2, 14, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x75), 2, 15, 8, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_12(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x56), 1, 1, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x76), 1, 2, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x56), 1, 3, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x76), 1, 4, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x56), 1, 5, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x76), 1, 6, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x56), 1, 7, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x76), 1, 8, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x56), 1, 9, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x76), 1, 10, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x56), 1, 11, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x56), 1, 12, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x76), 1, 13, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x56), 1, 14, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x76), 1, 15, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x56), 2, 1, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x76), 2, 2, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x56), 2, 3, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x76), 2, 4, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x56), 2, 5, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x76), 2, 6, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x56), 2, 7, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x76), 2, 8, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x56), 2, 9, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x76), 2, 10, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x56), 2, 11, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x56), 2, 12, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x76), 2, 13, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x56), 2, 14, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x76), 2, 15, 12, None, None, None) def test_scc_pac_indent_12_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x57), 1, 1, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x77), 1, 2, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x57), 1, 3, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x77), 1, 4, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x57), 1, 5, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x77), 1, 6, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x57), 1, 7, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x77), 1, 8, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x57), 1, 9, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x77), 1, 10, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x57), 1, 11, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x57), 1, 12, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x77), 1, 13, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x57), 1, 14, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x77), 1, 15, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x57), 2, 1, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x77), 2, 2, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x57), 2, 3, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x77), 2, 4, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x57), 2, 5, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x77), 2, 6, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x57), 2, 7, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x77), 2, 8, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x57), 2, 9, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x77), 2, 10, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x57), 2, 11, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x57), 2, 12, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x77), 2, 13, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x57), 2, 14, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x77), 2, 15, 12, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_16(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x58), 1, 1, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x78), 1, 2, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x58), 1, 3, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x78), 1, 4, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x58), 1, 5, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x78), 1, 6, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x58), 1, 7, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x78), 1, 8, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x58), 1, 9, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x78), 1, 10, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x58), 1, 11, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x58), 1, 12, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x78), 1, 13, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x58), 1, 14, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x78), 1, 15, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x58), 2, 1, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x78), 2, 2, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x58), 2, 3, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x78), 2, 4, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x58), 2, 5, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x78), 2, 6, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x58), 2, 7, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x78), 2, 8, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x58), 2, 9, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x78), 2, 10, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x58), 2, 11, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x58), 2, 12, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x78), 2, 13, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x58), 2, 14, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x78), 2, 15, 16, None, None, None) def test_scc_pac_indent_16_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x59), 1, 1, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x79), 1, 2, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x59), 1, 3, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x79), 1, 4, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x59), 1, 5, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x79), 1, 6, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x59), 1, 7, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x79), 1, 8, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x59), 1, 9, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x79), 1, 10, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x59), 1, 11, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x59), 1, 12, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x79), 1, 13, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x59), 1, 14, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x79), 1, 15, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x59), 2, 1, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x79), 2, 2, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x59), 2, 3, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x79), 2, 4, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x59), 2, 5, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x79), 2, 6, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x59), 2, 7, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x79), 2, 8, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x59), 2, 9, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x79), 2, 10, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x59), 2, 11, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x59), 2, 12, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x79), 2, 13, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x59), 2, 14, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x79), 2, 15, 16, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_20(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5A), 1, 1, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7A), 1, 2, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5A), 1, 3, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7A), 1, 4, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5A), 1, 5, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7A), 1, 6, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5A), 1, 7, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7A), 1, 8, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5A), 1, 9, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7A), 1, 10, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5A), 1, 11, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5A), 1, 12, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7A), 1, 13, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5A), 1, 14, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7A), 1, 15, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5A), 2, 1, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7A), 2, 2, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5A), 2, 3, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7A), 2, 4, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5A), 2, 5, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7A), 2, 6, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5A), 2, 7, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7A), 2, 8, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5A), 2, 9, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7A), 2, 10, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5A), 2, 11, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5A), 2, 12, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7A), 2, 13, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5A), 2, 14, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7A), 2, 15, 20, None, None, None) def test_scc_pac_indent_20_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5B), 1, 1, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7B), 1, 2, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5B), 1, 3, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7B), 1, 4, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5B), 1, 5, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7B), 1, 6, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5B), 1, 7, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7B), 1, 8, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5B), 1, 9, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7B), 1, 10, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5B), 1, 11, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5B), 1, 12, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7B), 1, 13, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5B), 1, 14, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7B), 1, 15, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5B), 2, 1, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7B), 2, 2, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5B), 2, 3, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7B), 2, 4, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5B), 2, 5, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7B), 2, 6, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5B), 2, 7, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7B), 2, 8, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5B), 2, 9, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7B), 2, 10, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5B), 2, 11, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5B), 2, 12, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7B), 2, 13, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5B), 2, 14, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7B), 2, 15, 20, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_24(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5C), 1, 1, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7C), 1, 2, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5C), 1, 3, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7C), 1, 4, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5C), 1, 5, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7C), 1, 6, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5C), 1, 7, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7C), 1, 8, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5C), 1, 9, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7C), 1, 10, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5C), 1, 11, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5C), 1, 12, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7C), 1, 13, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5C), 1, 14, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7C), 1, 15, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5C), 2, 1, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7C), 2, 2, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5C), 2, 3, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7C), 2, 4, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5C), 2, 5, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7C), 2, 6, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5C), 2, 7, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7C), 2, 8, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5C), 2, 9, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7C), 2, 10, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5C), 2, 11, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5C), 2, 12, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7C), 2, 13, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5C), 2, 14, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7C), 2, 15, 24, None, None, None) def test_scc_pac_indent_24_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5D), 1, 1, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7D), 1, 2, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5D), 1, 3, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7D), 1, 4, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5D), 1, 5, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7D), 1, 6, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5D), 1, 7, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7D), 1, 8, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5D), 1, 9, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7D), 1, 10, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5D), 1, 11, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5D), 1, 12, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7D), 1, 13, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5D), 1, 14, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7D), 1, 15, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5D), 2, 1, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7D), 2, 2, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5D), 2, 3, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7D), 2, 4, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5D), 2, 5, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7D), 2, 6, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5D), 2, 7, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7D), 2, 8, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5D), 2, 9, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7D), 2, 10, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5D), 2, 11, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5D), 2, 12, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7D), 2, 13, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5D), 2, 14, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7D), 2, 15, 24, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_28(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5E), 1, 1, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7E), 1, 2, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5E), 1, 3, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7E), 1, 4, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5E), 1, 5, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7E), 1, 6, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5E), 1, 7, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7E), 1, 8, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5E), 1, 9, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7E), 1, 10, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5E), 1, 11, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5E), 1, 12, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7E), 1, 13, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5E), 1, 14, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7E), 1, 15, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5E), 2, 1, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7E), 2, 2, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5E), 2, 3, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7E), 2, 4, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5E), 2, 5, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7E), 2, 6, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5E), 2, 7, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7E), 2, 8, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5E), 2, 9, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7E), 2, 10, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5E), 2, 11, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5E), 2, 12, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7E), 2, 13, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5E), 2, 14, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7E), 2, 15, 28, None, None, None) def test_scc_pac_indent_28_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5F), 1, 1, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7F), 1, 2, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5F), 1, 3, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7F), 1, 4, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5F), 1, 5, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7F), 1, 6, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5F), 1, 7, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7F), 1, 8, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5F), 1, 9, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7F), 1, 10, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5F), 1, 11, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5F), 1, 12, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7F), 1, 13, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5F), 1, 14, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7F), 1, 15, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5F), 2, 1, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7F), 2, 2, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5F), 2, 3, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7F), 2, 4, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5F), 2, 5, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7F), 2, 6, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5F), 2, 7, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7F), 2, 8, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5F), 2, 9, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7F), 2, 10, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5F), 2, 11, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5F), 2, 12, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7F), 2, 13, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5F), 2, 14, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7F), 2, 15, 28, None, None, TextDecorationType(underline=True)) if __name__ == '__main__': unittest.main()
1.375
1
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/custom_image_properties_custom.py
NMijat1024/azure-sdk-for-python
1
4748
<reponame>NMijat1024/azure-sdk-for-python # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class CustomImagePropertiesCustom(Model): """Properties for creating a custom image from a VHD. :param image_name: The image name. :type image_name: str :param sys_prep: Indicates whether sysprep has been run on the VHD. :type sys_prep: bool :param os_type: The OS type of the custom image (i.e. Windows, Linux). Possible values include: 'Windows', 'Linux', 'None' :type os_type: str or ~azure.mgmt.devtestlabs.models.CustomImageOsType """ _validation = { 'os_type': {'required': True}, } _attribute_map = { 'image_name': {'key': 'imageName', 'type': 'str'}, 'sys_prep': {'key': 'sysPrep', 'type': 'bool'}, 'os_type': {'key': 'osType', 'type': 'str'}, } def __init__(self, os_type, image_name=None, sys_prep=None): super(CustomImagePropertiesCustom, self).__init__() self.image_name = image_name self.sys_prep = sys_prep self.os_type = os_type
2.078125
2
distance_torch_no_compile/chamfer.py
nicolalandro/softpool
0
4749
import torch def expanded_pairwise_distances(x, y): ''' Input: x is a bxNxd matrix y is an optional bxMxd matirx Output: dist is a bxNxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:] if y is not given then use 'y=x'. i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2 ''' differences = x.unsqueeze(2) - y.unsqueeze(1) distances = torch.sum(differences * differences, -1) return distances def chamfer_distance(x, y): ''' input x and y are bxNxM matrix, b: batch, N:number of point, M: point dim (ex. 2 for 2D or 3 for 3D) output is a bx1 Matrix with the value of the chamfer distance for each sample of the batch ''' dist_vec = expanded_pairwise_distances(x, y) min_distances = torch.topk(dist_vec, k=1, dim=2, largest=False).values chamfer = torch.sum(min_distances, dim=1) / torch.tensor(x.shape[1]) return chamfer class ChamferLoss(torch.nn.Module): def forward(self, x, y): chamfer = chamfer_distance(x, y) return torch.sum(chamfer) if __name__ == "__main__": x = torch.tensor([ [ [0., 0., 0.], [0., 1., 0.], [0., 1., 0.], ], [ [1., 1., 0.], [1., 2., 0.], [0., 1., 0.], ] ]) y = torch.tensor([ [ [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], ], [ [1., 1., 0.], [1., 2., 0.], [0., 1., 0.], ] ]) chamfer = ChamferLoss() print('chamfer loss torch (cpu):', chamfer(x, y)) print('chamfer loss torch (cuda):', chamfer(x.cuda(), y.cuda())) # import sys # sys.path.append("../distance/chamfer/") # import dist_chamfer as cd # CD = cd.chamferDist() # dist1, dist2, _, _= CD(x, y) # print('orig', dist1)
3.1875
3
isiscb/curation/authority_views/relation_views.py
crispzips/IsisCB
4
4750
from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, QueryDict #, HttpResponseForbidden, Http404, , JsonResponse from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.contrib.admin.views.decorators import staff_member_required, user_passes_test from rules.contrib.views import permission_required, objectgetter from isisdata.models import * from isisdata.utils import strip_punctuation, normalize from isisdata import operations from isisdata.filters import * from isisdata import tasks as data_tasks from curation import p3_port_utils from curation.forms import * from curation.contrib.views import check_rules @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def create_acrelation_for_authority(request, authority_id): authority = get_object_or_404(Authority, pk=authority_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'search_key': search_key, 'current_index': current_index } if request.method == 'GET': initial = { 'authority': authority.id, 'name_for_display_in_citation': authority.name } type_controlled = request.GET.get('type_controlled', None) if type_controlled: initial.update({'type_controlled': type_controlled.upper()}) form = ACRelationForm(prefix='acrelation', initial=initial) elif request.method == 'POST': form = ACRelationForm(request.POST, prefix='acrelation') if form.is_valid(): form.save() target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=acrelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) context.update({ 'form': form, }) template = 'curation/authority_acrelation_changeview.html' return render(request, template, context) @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def create_aarelation_for_authority(request, authority_id): authority = get_object_or_404(Authority, pk=authority_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'search_key': search_key, 'current_index': current_index } if request.method == 'GET': initial = { 'subject': authority.id } aarelation=AARelation() aarelation.subject = authority type_controlled = request.GET.get('type_controlled', None) if type_controlled: aarelation = dict(AARelation.TYPE_CHOICES)[type_controlled] form = AARelationForm(prefix='aarelation', instance=aarelation) elif request.method == 'POST': form = AARelationForm(request.POST, prefix='aarelation') if form.is_valid(): form.save() target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=aarelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) context.update({ 'form': form, }) template = 'curation/authority_aarelation_changeview.html' return render(request, template, context) @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def acrelation_for_authority(request, authority_id, acrelation_id): authority = get_object_or_404(Authority, pk=authority_id) acrelation = get_object_or_404(ACRelation, pk=acrelation_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'acrelation': acrelation, 'search_key': search_key, 'current_index': current_index } if request.method == 'GET': form = ACRelationForm(instance=acrelation, prefix='acrelation') elif request.method == 'POST': form = ACRelationForm(request.POST, instance=acrelation, prefix='acrelation') if form.is_valid(): form.save() target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=acrelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) context.update({ 'form': form, }) template = 'curation/authority_acrelation_changeview.html' return render(request, template, context) @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def aarelation_for_authority(request, authority_id, aarelation_id): authority = get_object_or_404(Authority, pk=authority_id) aarelation = get_object_or_404(AARelation, pk=aarelation_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'aarelation': aarelation, 'search_key': search_key, 'current_index': current_index } if request.method == 'GET': form = AARelationForm(instance=aarelation, prefix='aarelation') elif request.method == 'POST': form = AARelationForm(request.POST, instance=aarelation, prefix='aarelation') if form.is_valid(): form.save() target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=aarelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) context.update({ 'form': form, }) template = 'curation/authority_aarelation_changeview.html' return render(request, template, context) @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def delete_aarelation_for_authority(request, authority_id, aarelation_id, format=None): authority = get_object_or_404(Authority, pk=authority_id) aarelation = get_object_or_404(AARelation, pk=aarelation_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'aarelation': aarelation, 'search_key': search_key, 'current_index': current_index } if request.POST.get('confirm', False) == 'true': if not aarelation.modified_on: aarelation.modified_on = datetime.datetime.now() aarelation.delete() if format == 'json': return JsonResponse({'result': True}) target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=aarelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) if format == 'json': return JsonResponse({'result': False}) template = 'curation/authority_aarelation_delete.html' return render(request, template, context)
1.796875
2
run_tests.py
silx-kit/silx
94
4751
#!/usr/bin/env python3 # coding: utf8 # /*########################################################################## # # Copyright (c) 2015-2021 European Synchrotron Radiation Facility # # 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. # # ###########################################################################*/ """Run the tests of the project. This script expects a suite function in <project_package>.test, which returns a unittest.TestSuite. Test coverage dependencies: coverage, lxml. """ __authors__ = ["<NAME>", "<NAME>"] __date__ = "30/09/2020" __license__ = "MIT" import distutils.util import logging import os import subprocess import sys import importlib # Capture all default warnings logging.captureWarnings(True) import warnings warnings.simplefilter('default') logger = logging.getLogger("run_tests") logger.setLevel(logging.WARNING) logger.info("Python %s %s", sys.version, tuple.__itemsize__ * 8) try: import numpy except Exception as error: logger.warning("Numpy missing: %s", error) else: logger.info("Numpy %s", numpy.version.version) try: import h5py except Exception as error: logger.warning("h5py missing: %s", error) else: logger.info("h5py %s", h5py.version.version) def get_project_name(root_dir): """Retrieve project name by running python setup.py --name in root_dir. :param str root_dir: Directory where to run the command. :return: The name of the project stored in root_dir """ logger.debug("Getting project name in %s", root_dir) p = subprocess.Popen([sys.executable, "setup.py", "--name"], shell=False, cwd=root_dir, stdout=subprocess.PIPE) name, _stderr_data = p.communicate() logger.debug("subprocess ended with rc= %s", p.returncode) return name.split()[-1].decode('ascii') def is_debug_python(): """Returns true if the Python interpreter is in debug mode.""" try: import sysconfig except ImportError: # pragma nocover # Python < 2.7 import distutils.sysconfig as sysconfig if sysconfig.get_config_var("Py_DEBUG"): return True return hasattr(sys, "gettotalrefcount") def build_project(name, root_dir): """Run python setup.py build for the project. Build directory can be modified by environment variables. :param str name: Name of the project. :param str root_dir: Root directory of the project :return: The path to the directory were build was performed """ platform = distutils.util.get_platform() architecture = "lib.%s-%i.%i" % (platform, sys.version_info[0], sys.version_info[1]) if is_debug_python(): architecture += "-pydebug" if os.environ.get("PYBUILD_NAME") == name: # we are in the debian packaging way home = os.environ.get("PYTHONPATH", "").split(os.pathsep)[-1] elif os.environ.get("BUILDPYTHONPATH"): home = os.path.abspath(os.environ.get("BUILDPYTHONPATH", "")) else: home = os.path.join(root_dir, "build", architecture) logger.warning("Building %s to %s", name, home) p = subprocess.Popen([sys.executable, "setup.py", "build"], shell=False, cwd=root_dir) logger.debug("subprocess ended with rc= %s", p.wait()) if os.path.isdir(home): return home alt_home = os.path.join(os.path.dirname(home), "lib") if os.path.isdir(alt_home): return alt_home def import_project_module(project_name, project_dir): """Import project module, from the system of from the project directory""" if "--installed" in sys.argv: try: module = importlib.import_module(project_name) except Exception: logger.error("Cannot run tests on installed version: %s not installed or raising error.", project_name) raise else: # Use built source build_dir = build_project(project_name, project_dir) if build_dir is None: logging.error("Built project is not available !!! investigate") sys.path.insert(0, build_dir) logger.warning("Patched sys.path, added: '%s'", build_dir) module = importlib.import_module(project_name) return module if __name__ == "__main__": # Needed for multiprocessing support on Windows import pytest PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_NAME = get_project_name(PROJECT_DIR) logger.info("Project name: %s", PROJECT_NAME) project_module = import_project_module(PROJECT_NAME, PROJECT_DIR) PROJECT_VERSION = getattr(project_module, 'version', '') PROJECT_PATH = project_module.__path__[0] def normalize_option(option): option_parts = option.split(os.path.sep) if option_parts == ["src", "silx"]: return PROJECT_PATH if option_parts[:2] == ["src", "silx"]: return os.path.join(PROJECT_PATH, *option_parts[2:]) return option args = [normalize_option(p) for p in sys.argv[1:] if p != "--installed"] # Run test on PROJECT_PATH if nothing is specified without_options = [a for a in args if not a.startswith("-")] if len(without_options) == 0: args += [PROJECT_PATH] argv = ["--rootdir", PROJECT_PATH] + args sys.exit(pytest.main(argv))
1.421875
1
src/robot/utils/error.py
vprashanth777/Selenium
1
4752
# Copyright 2008-2015 Nokia Solutions and Networks # # 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 os import re import sys import traceback from robot.errors import RobotError from .platform import JYTHON, RERAISED_EXCEPTIONS from .unic import unic EXCLUDE_ROBOT_TRACES = not os.getenv('ROBOT_INTERNAL_TRACES') if JYTHON: from java.io import StringWriter, PrintWriter from java.lang import Throwable, OutOfMemoryError else: Throwable = () def get_error_message(): """Returns error message of the last occurred exception. This method handles also exceptions containing unicode messages. Thus it MUST be used to get messages from all exceptions originating outside the framework. """ return ErrorDetails().message def get_error_details(exclude_robot_traces=EXCLUDE_ROBOT_TRACES): """Returns error message and details of the last occurred exception.""" details = ErrorDetails(exclude_robot_traces=exclude_robot_traces) return details.message, details.traceback def ErrorDetails(exc_info=None, exclude_robot_traces=EXCLUDE_ROBOT_TRACES): """This factory returns an object that wraps the last occurred exception It has attributes `message`, `traceback` and `error`, where `message` contains type and message of the original error, `traceback` contains the traceback/stack trace and `error` contains the original error instance. """ exc_type, exc_value, exc_traceback = exc_info or sys.exc_info() if exc_type in RERAISED_EXCEPTIONS: raise exc_value details = PythonErrorDetails \ if not isinstance(exc_value, Throwable) else JavaErrorDetails return details(exc_type, exc_value, exc_traceback, exclude_robot_traces) class _ErrorDetails(object): _generic_exception_names = ('AssertionError', 'AssertionFailedError', 'Exception', 'Error', 'RuntimeError', 'RuntimeException') def __init__(self, exc_type, exc_value, exc_traceback, exclude_robot_traces=True): self.error = exc_value self._exc_type = exc_type self._exc_traceback = exc_traceback self._exclude_robot_traces = exclude_robot_traces self._message = None self._traceback = None @property def message(self): if self._message is None: self._message = self._get_message() return self._message def _get_message(self): raise NotImplementedError @property def traceback(self): if self._traceback is None: self._traceback = self._get_details() return self._traceback def _get_details(self): raise NotImplementedError def _get_name(self, exc_type): try: return exc_type.__name__ except AttributeError: return unic(exc_type) def _format_message(self, name, message): message = unic(message or '') message = self._clean_up_message(message, name) name = name.split('.')[-1] # Use only last part of the name if not message: return name if self._is_generic_exception(name): return message return '%s: %s' % (name, message) def _is_generic_exception(self, name): return (name in self._generic_exception_names or isinstance(self.error, RobotError) or getattr(self.error, 'ROBOT_SUPPRESS_NAME', False)) def _clean_up_message(self, message, name): return message class PythonErrorDetails(_ErrorDetails): def _get_message(self): name = self._get_name(self._exc_type) return self._format_message(name, unic(self.error)) def _get_details(self): if isinstance(self.error, RobotError): return self.error.details return 'Traceback (most recent call last):\n' + self._get_traceback() def _get_traceback(self): tb = self._exc_traceback while tb and self._is_excluded_traceback(tb): tb = tb.tb_next return ''.join(traceback.format_tb(tb)).rstrip() or ' None' def _is_excluded_traceback(self, traceback): if not self._exclude_robot_traces: return False module = traceback.tb_frame.f_globals.get('__name__') return module and module.startswith('robot.') class JavaErrorDetails(_ErrorDetails): _java_trace_re = re.compile('^\s+at (\w.+)') _ignored_java_trace = ('org.python.', 'robot.running.', 'robot$py.', 'sun.reflect.', 'java.lang.reflect.') def _get_message(self): exc_name = self._get_name(self._exc_type) # OOME.getMessage and even toString seem to throw NullPointerException if not self._is_out_of_memory_error(self._exc_type): exc_msg = self.error.getMessage() else: exc_msg = str(self.error) return self._format_message(exc_name, exc_msg) def _is_out_of_memory_error(self, exc_type): return exc_type is OutOfMemoryError def _get_details(self): # OOME.printStackTrace seems to throw NullPointerException if self._is_out_of_memory_error(self._exc_type): return '' output = StringWriter() self.error.printStackTrace(PrintWriter(output)) details = '\n'.join(line for line in output.toString().splitlines() if not self._is_ignored_stack_trace_line(line)) msg = unic(self.error.getMessage() or '') if msg: details = details.replace(msg, '', 1) return details def _is_ignored_stack_trace_line(self, line): if not line: return True res = self._java_trace_re.match(line) if res is None: return False location = res.group(1) for entry in self._ignored_java_trace: if location.startswith(entry): return True return False def _clean_up_message(self, msg, name): msg = self._remove_stack_trace_lines(msg) return self._remove_exception_name(msg, name).strip() def _remove_stack_trace_lines(self, msg): lines = msg.splitlines() while lines: if self._java_trace_re.match(lines[-1]): lines.pop() else: break return '\n'.join(lines) def _remove_exception_name(self, msg, name): tokens = msg.split(':', 1) if len(tokens) == 2 and tokens[0] == name: msg = tokens[1] return msg
1.828125
2
dedupe/_init.py
neozhangthe1/dedupe
0
4753
from dedupe.api import StaticDedupe, Dedupe from dedupe.api import StaticRecordLink, RecordLink from dedupe.api import StaticGazetteer, Gazetteer from dedupe.core import randomPairs, randomPairsMatch, frozendict from dedupe.convenience import consoleLabel, trainingDataDedupe, trainingDataLink, canonicalize
1.046875
1
scalability/tests/test_misc.py
ggreif/ic
941
4754
import unittest from unittest import TestCase from misc import verify class TestVerify(TestCase): """Tests misc.py verifies function.""" def test_verify__with_zero_threshold_and_expected_succeeds(self): """Test passes when expected rate, actual rate and threshold are all zero.""" result = verify(metric="Query failure rate", actual=0.0, expected=0.0, threshold=0.0) self.assertEqual(result, 0) def test_verify__fails_when_positive_delta_is_larger_than_postive_threshold(self): """Test fails when positive delta between actual rate and expected rate exceeds positive threshold.""" result = verify(metric="Update latency", actual=200, expected=100, threshold=0.1) self.assertEqual(result, 1) def test_verify__fails_when_negative_delta_is_smaller_than_negative_threshold(self): """Test fails when negative delta between actual rate and expected rate exceeds negative threshold.""" result = verify(metric="Update latency", actual=50, expected=100, threshold=-0.01) self.assertEqual(result, 1) def test_verify__fails_when_negative_delta_and_positive_threshold(self): """Test fails when delta between actual rate and expected rate exceeds threshold.""" result = verify(metric="Update latency", actual=50, expected=100, threshold=0.01) self.assertEqual(result, 0) if __name__ == "__main__": unittest.main()
3.578125
4
mars/tensor/fft/ifft.py
tomzhang/mars-1
2
4755
<reponame>tomzhang/mars-1 #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding 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. import numpy as np from ... import opcodes as OperandDef from ..datasource import tensor as astensor from .core import TensorComplexFFTMixin, validate_fft, TensorStandardFFT class TensorIFFT(TensorStandardFFT, TensorComplexFFTMixin): _op_type_ = OperandDef.IFFT def __init__(self, n=None, axis=-1, norm=None, dtype=None, **kw): super().__init__(_n=n, _axis=axis, _norm=norm, _dtype=dtype, **kw) def ifft(a, n=None, axis=-1, norm=None): """ Compute the one-dimensional inverse discrete Fourier Transform. This function computes the inverse of the one-dimensional *n*-point discrete Fourier transform computed by `fft`. In other words, ``ifft(fft(a)) == a`` to within numerical accuracy. For a general description of the algorithm and definitions, see `mt.fft`. The input should be ordered in the same way as is returned by `fft`, i.e., * ``a[0]`` should contain the zero frequency term, * ``a[1:n//2]`` should contain the positive-frequency terms, * ``a[n//2 + 1:]`` should contain the negative-frequency terms, in increasing order starting from the most negative frequency. For an even number of input points, ``A[n//2]`` represents the sum of the values at the positive and negative Nyquist frequencies, as the two are aliased together. See `numpy.fft` for details. Parameters ---------- a : array_like Input tensor, can be complex. n : int, optional Length of the transformed axis of the output. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. See notes about padding issues. axis : int, optional Axis over which to compute the inverse DFT. If not given, the last axis is used. norm : {None, "ortho"}, optional Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex Tensor The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. Raises ------ IndexError If `axes` is larger than the last axis of `a`. See Also -------- mt.fft : An introduction, with definitions and general explanations. fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse ifft2 : The two-dimensional inverse FFT. ifftn : The n-dimensional inverse FFT. Notes ----- If the input parameter `n` is larger than the size of the input, the input is padded by appending zeros at the end. Even though this is the common approach, it might lead to surprising results. If a different padding is desired, it must be performed before calling `ifft`. Examples -------- >>> import mars.tensor as mt >>> mt.fft.ifft([0, 4, 0, 0]).execute() array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) Create and plot a band-limited signal with random phases: >>> import matplotlib.pyplot as plt >>> t = mt.arange(400) >>> n = mt.zeros((400,), dtype=complex) >>> n[40:60] = mt.exp(1j*mt.random.uniform(0, 2*mt.pi, (20,))) >>> s = mt.fft.ifft(n) >>> plt.plot(t.execute(), s.real.execute(), 'b-', t.execute(), s.imag.execute(), 'r--') ... >>> plt.legend(('real', 'imaginary')) ... >>> plt.show() """ a = astensor(a) validate_fft(a, axis, norm) op = TensorIFFT(n=n, axis=axis, norm=norm, dtype=np.dtype(np.complex_)) return op(a)
2.4375
2
server/api/src/db/migrate/versions/v_2.py
mminamina/311-data
0
4756
def migrate(): print('migrating to version 2')
1.1875
1
Physics250-ME29/magAverageEMFinCoil.py
illusion173/Physics250
0
4757
<reponame>illusion173/Physics250 import numpy as np import math extraNumber = 4 * math.pi * pow(10,-7) def avgEMF(): turns = input("Input how many turns: ") radius = input("Input the radius (cm):") resistance = input("Input resistance (Ω): ") magField0 = input("Input the first magnetic Field value (T): ") magField1 = input("Input the second magnetic Field value (T): ") time = input("Input the time (s): ") turns = float(turns) radius = float(radius) resistance = float(resistance) magField0 = float(magField0) magField1 = float(magField1) time = float(time) radius = radius/100 area = pow(radius,2)*math.pi averageEMF = turns * area * ((magField1-magField0)/time) print(averageEMF) avgEMF()
3.546875
4
bench_cupy.py
zhouxzh/Jetson_nano_stft_benchmark
0
4758
<reponame>zhouxzh/Jetson_nano_stft_benchmark #!/usr/bin/env python # -*- coding: utf-8 -*- """ Computes the spectrogram of a test signal using cupy and cuFFT. Author: <NAME> """ import sys import os import timeit import numpy as np import cupy as cp INPUT_ON_GPU = True OUTPUT_ON_GPU = True from testfile import make_test_signal def spectrogram(signal, sample_rate=22050, frame_len=1024, fps=70): """ Computes a magnitude spectrogram at a given sample rate (in Hz), frame length (in samples) and frame rate (in Hz), on CUDA using cupy. """ if not INPUT_ON_GPU: signal = cp.array(signal.astype(np.float32)) # already blown up to a list of frames win = cp.hanning(frame_len).astype(cp.float32) # apply window function #signal *= win # this doesn't work correctly for some reason. signal = signal * win # perform FFT spect = cp.fft.rfft(signal) # convert into magnitude spectrogram spect = cp.abs(spect) # return if OUTPUT_ON_GPU: cp.cuda.get_current_stream().synchronize() else: return spect.get() def main(): # load input global x, spectrogram x = make_test_signal() # we do the following here because cupy cannot do stride tricks # the actual copying work is included in the benchmark unless INPUT_ON_GPU hop_size = 22050 // 70 frame_len = 1024 frames = len(x) - frame_len + 1 x = np.lib.stride_tricks.as_strided( x, (frames, frame_len), (x.strides[0], x.strides[0]))[::hop_size] if INPUT_ON_GPU: x = cp.array(x.astype(np.float32)) # benchmark times = timeit.repeat( setup='from __main__ import x, spectrogram', stmt='spectrogram(x)', repeat=5, number=32) print("Took %.3fs." % (min(times) / 32)) # save result #assert not OUTPUT_ON_GPU #np.save(sys.argv[0][:-2] + 'npy', spectrogram(x)) if __name__=="__main__": main()
2.421875
2
geotrek/appconfig.py
Cynthia-Borot-PNE/Geotrek-admin
0
4759
from django.apps import AppConfig from django.contrib.admin.apps import AdminConfig from django.contrib.auth.apps import AuthConfig from django.contrib.contenttypes.apps import ContentTypesConfig from django.contrib.sessions.apps import SessionsConfig from django.db.models.signals import post_migrate from django_celery_results.apps import CeleryResultConfig from geotrek.common.utils.signals import check_srid_has_meter_unit, pm_callback class GeotrekConfig(AppConfig): """ Base class to handle table move on right schemas, and load SQL files !! WARNING !! need to create subclass in geotrek.myapp.apps for project apps, and create subclasses here for external subclasses """ def ready(self): post_migrate.connect(pm_callback, sender=self, dispatch_uid='geotrek.core.pm_callback') check_srid_has_meter_unit() class AuthGeotrekConfig(AuthConfig, GeotrekConfig): """ bind for django.contrib.auth """ pass class ContenttypeGeotrekConfig(ContentTypesConfig, GeotrekConfig): """ bind for django.contrib.contenttype """ pass class SessionsGeotrekConfig(SessionsConfig, GeotrekConfig): pass class AdminGeotrekConfig(AdminConfig, GeotrekConfig): pass class CeleryGeotrekConfig(GeotrekConfig, CeleryResultConfig): pass class EasyThumbnailsGeotrekConfig(GeotrekConfig): name = 'easy_thumbnails' verbose_name = 'Easy thumbnails'
1.804688
2
dtr_code/shared/run_torch_trial.py
merrymercy/dtr-prototype
1
4760
<reponame>merrymercy/dtr-prototype<gh_stars>1-10 """ To avoid any issues of memory hanging around between inputs, we run each input as a separate process. A little ugly but effective """ import gc import glob import json import os import random import time import numpy as np import torch from common import invoke_main, read_json, write_json, prepare_out_file, check_file_exists from validate_config import validate_trials_config from pt_trial_util import create_csv_writer from tqdm import tqdm import model_util def extend_simrd_config(dest_dir, sim_conf_filename, model_name, specific_params, log_name): if not check_file_exists(dest_dir, sim_conf_filename): prepare_out_file(dest_dir, sim_conf_filename) write_json(dest_dir, sim_conf_filename, dict()) conf = read_json(dest_dir, sim_conf_filename) if model_name not in conf: conf[model_name] = [] conf[model_name].append({ 'name': model_util.get_model_family(model_name), 'batch_size': str(specific_params['batch_size']), 'layers': specific_params.get('layers', model_util.get_model_layers(model_name)), 'type': model_util.get_model_type(model_name), 'log': log_name, 'has_start': True }) write_json(dest_dir, sim_conf_filename, conf) def save_trial_log(dest_dir, sim_conf_filename, model_name, specific_params, is_baseline=False): """ Find the last DTR log produced in the trial (if any exist) and move it to the directory """ all_logs = glob.glob(os.path.join(os.getcwd(), '*.log')) if not all_logs: return # if we delete all logs in advance, there should be at most one log assert len(all_logs) == 1 most_recent = all_logs[0] # rename and move # (new name just appends info to the old one) batch_size = specific_params['batch_size'] budget = specific_params['memory_budget'] if budget < 0: budget = 'inf' new_name = '{}-{}-{}-{}'.format(model_name, batch_size, budget, os.path.basename(most_recent)) filename = prepare_out_file(dest_dir, new_name) os.rename(most_recent, filename) if is_baseline and sim_conf_filename is not None: extend_simrd_config(dest_dir, sim_conf_filename, model_name, specific_params, filename) def delete_logs(): for log in glob.glob(os.path.join(os.getcwd(), '*.log')): os.remove(log) def run_single_measurement(model_name, produce_model, run_model, teardown, inp, criterion, extra_params, use_dtr, use_profiling): """ This function initializes a model and performs a single measurement of the model on the given input. While it might seem most reasonable to initialize the model outside of the loop, DTR's logs have shown that certain constants in the model persist between loop iterations; performing these actions in a separate *function scope* turned out to be the only way to prevent having those constants hang around. Returns a dict of measurements """ torch.cuda.reset_max_memory_allocated() # resetting means the count should be reset to # only what's in scope, meaning only the input input_mem = torch.cuda.max_memory_allocated() model = produce_model(extra_params=extra_params) params = [] for m in model: if hasattr(m, 'parameters'): params.extend(m.parameters()) model_mem = torch.cuda.max_memory_allocated() optimizer = torch.optim.SGD(model[0].parameters(), 1e-3, momentum=0.9, weight_decay=1e-4) start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) # start timing torch.cuda.synchronize() start_time = time.time() if use_dtr: torch.reset_profile() start.record() # with torch.autograd.profiler.profile(use_cuda=True) as prof: run_model(criterion, *model, *inp, optimizer=optimizer) end.record() start_sync = time.time() torch.cuda.synchronize() end_sync = time.time() end_time = time.time() # end timing if use_dtr: # operators-only time, tracked by DTR cuda_time = torch.compute_time() base_compute_time = -1 remat_compute_time = -1 search_time = -1 cost_time = -1 if use_profiling: base_compute_time = torch.base_compute_time() remat_compute_time = torch.remat_compute_time() search_time = torch.search_time() cost_time = torch.cost_time() torch.reset_profile() total_mem = torch.cuda.max_memory_allocated() teardown(*model) torch.cuda.reset_max_memory_allocated() del model if use_dtr: torch.toggle_log(False) del params batch_size = len(inp[0]) ips = batch_size / (end_time - start_time) result = { 'time': end_time - start_time, 'sync_time': end_sync - start_sync, 'gpu_time': start.elapsed_time(end), 'input_mem': input_mem, 'model_mem': model_mem, 'total_mem': total_mem, 'base_compute_time': base_compute_time, 'remat_compute_time': remat_compute_time, 'search_time': search_time, 'cost_time': cost_time, 'batch_size': batch_size, 'ips': ips } if use_dtr: result['cuda_time'] = cuda_time else: result['cuda_time'] = -1.0 return result def timing_loop(model_name, i, config, use_dtr, specific_params, writer, trial_run=False, trial_run_outfile=None, memory_budget=-1.0): dry_run = config['dry_run'] measurements = [] print(f'Running {model_name} : {specific_params}') # remove any logs hanging around (so we only have to look for one) delete_logs() # we only save logs for the final input on DTR save_log = use_dtr and specific_params.get('save_logs', config['save_logs']) and i == config['n_inputs'] - 1 if use_dtr: torch.toggle_log(False) # whether to report profiling info use_profiling = use_dtr and specific_params.get('use_profiling', False) use_cudnn = model_util.use_cudnn(model_name) with torch.backends.cudnn.flags(enabled=use_cudnn, benchmark=use_cudnn): criterion = model_util.get_criterion(model_name) produce_model, gen_input, run_model, teardown = model_util.prepare_model(model_name, specific_params['batch_size'], use_dtr=use_dtr) inp = gen_input(i, specific_params.get('extra_params', dict())) n_reps = specific_params.get('n_reps', config['n_reps']) if use_profiling: torch.toggle_profile(use_profiling) progress = tqdm(range(dry_run + n_reps)) for j in progress: progress.set_description(f'Rep [{j}]' + '' if j > dry_run else f'Dry run [{j}]') gc.collect() # Annotate where the final run starts in the log if save_log and j == dry_run + n_reps - 1: torch.toggle_log(True) torch.annotate_log('START') res = run_single_measurement(model_name, produce_model, run_model, teardown, inp, criterion, extra_params=specific_params.get('extra_params', dict()), use_dtr=use_dtr, use_profiling=use_profiling) if j >= dry_run: measurements.append(res) # Dump results model_name_replace_dict = { 'tv_resnet152': 'resnet152', 'tv_resnet50': 'resnet50', } train_ips_list = [] batch_size = None for res in measurements: batch_size = res['batch_size'] train_ips_list.append(res['ips']) out_file = "speed_results.tsv" with open(out_file, "a") as fout: val_dict = { 'network': model_name_replace_dict.get(model_name, model_name), 'algorithm': 'dtr', 'budget': specific_params['memory_budget'], 'batch_size': batch_size, 'ips': np.median(train_ips_list) if train_ips_list else -1, } print(val_dict) fout.write(json.dumps(val_dict) + "\n") print(f"save results to {out_file}") # write to csv file only when this trial is not # for getting a baseline memory usage if trial_run: write_json(os.getcwd(), trial_run_outfile, { 'mem' : max(map(lambda data: data['total_mem'], measurements)) }) return if save_log: save_trial_log(config['log_dest'], config.get('simrd_config', None), model_name, specific_params, is_baseline=specific_params['memory_budget'] == -1) # clean up after ourselves delete_logs() # do all the writing after the trial is over for j in range(len(measurements)): data = measurements[j] # do unit conversions now: times in ms, # memory in MB writer.writerow({ 'time': data['time']*1e3, 'sync_time': data['sync_time']*1e3, # pytorch's cuda elapsed time is already in ms 'gpu_time': float(data['gpu_time']), # 'cuda_time' : float(data['cuda_time']) * 1e-6, 'input_mem': data['input_mem']*1e-6, 'model_mem': data['model_mem']*1e-6, 'total_mem': data['total_mem']*1e-6, 'memory_budget': memory_budget, # profiling (reported in nanoseconds) 'base_compute_time': data['base_compute_time']*1e-6, 'remat_compute_time': data['remat_compute_time']*1e-6, 'search_time': data['search_time']*1e-6, 'cost_time': data['cost_time']*1e-6, 'rep': j - dry_run, 'input': i, **specific_params }) def main(config_dir, experiment_mode, model_name, input_idx, params_file, out_file, trial_run=False, trial_run_outfile=None): if 'DTR_MODEL_NAME' in os.environ: model_name = os.environ['DTR_MODEL_NAME'] config, msg = validate_trials_config(config_dir) if config is None: print(msg) return 1 use_dtr = (experiment_mode == 'dtr') i = int(input_idx) is_trial = trial_run == 'True' if config['set_seed']: torch.manual_seed(config['seed'] + i) random.seed(config['seed'] + i) cwd = os.getcwd() # handle specific params, esp. for DTR specific_params = read_json(cwd, params_file) if 'DTR_MEMORY_BUDGET' in os.environ: specific_params['memory_budget'] = float(os.environ['DTR_MEMORY_BUDGET']) assert 'batch_size' in specific_params if use_dtr: assert 'memory_budget' in specific_params if specific_params['memory_budget'] > 0: print(f'Setting budget to {int(specific_params["memory_budget"])}') torch.set_memory_budget(int(specific_params['memory_budget'])) if is_trial: timing_loop(model_name, i, config, use_dtr, specific_params, None, True, trial_run_outfile) return with open(out_file, 'a', newline='') as csvfile: writer = create_csv_writer(csvfile, specific_params) timing_loop(model_name, i, config, use_dtr, specific_params, writer, memory_budget=specific_params.get('memory_budget', -1)) if __name__ == '__main__': invoke_main(main, 'config_dir', 'experiment_mode', 'model_name', 'input_idx', 'params_file', 'out_file', 'trial_run', 'trial_run_outfile')
1.835938
2
pythonTools/downloadPDBsInList.py
rsanchezgarc/BIPSPI
5
4761
import sys, os from subprocess import call try: from downloadPdb import downloadPDB except ImportError: from .downloadPdb import downloadPDB pdbListFile="/home/rsanchez/Tesis/rriPredMethod/data/joanDimers/117_dimers_list.tsv" outPath="/home/rsanchez/Tesis/rriPredMethod/data/joanDimers/pdbFiles/rawPDBs" USE_BIO_UNIT=False ##def downloadPDB(pdbId, pdbOutPath, useBioUnit): #### descargar pdb: wget ftp://ftp.wwpdb.org/pub/pdb/data/biounit/coordinates/all/1i1q.pdb2.gz o ya descomprimido #### wget -qO- ftp://ftp.wwpdb.org/pub/pdb/data/biounit/coordinates/all/1i1q.pdb2.gz |zcat > 1i1q.pdb ## outName= os.path.join(pdbOutPath,pdbId+'.pdb') ## if not os.path.isfile(outName): ## if useBioUnit: ## cmd= 'wget -qO- ftp://ftp.wwpdb.org/pub/pdb/data/biounit/coordinates/all/%s.pdb1.gz |zcat > %s'%(pdbId.lower(), outName) ## else: ## cmd= 'wget -qO- http://www.pdb.org/pdb/files/%s.pdb | cat > %s'%(pdbId.upper(), outName) ## print(cmd) ## call(cmd, shell= True) def downloadInFile(fname, outPath, useBioUnit): with open(fname) as f: for line in f: pdbId= line.split()[0] print(pdbId) downloadPDB(pdbId, outPath, bioUnit= 0 if useBioUnit else None) if __name__=="__main__": if len(sys.argv)==3: pdbListFile= os.path.abspath(os.path.expanduser(sys.argv[1])) outPath= os.path.abspath(os.path.expanduser(sys.argv[2])) print( pdbListFile, outPath) downloadInFile(pdbListFile, outPath, USE_BIO_UNIT)
2.3125
2
code/python3/search_facets.py
hsethi2709/xapian-docsprint
47
4762
<gh_stars>10-100 #!/usr/bin/env python import json import sys import xapian import support def search(dbpath, querystring, offset=0, pagesize=10): # offset - defines starting point within result set # pagesize - defines number of records to retrieve # Open the database we're going to search. db = xapian.Database(dbpath) # Set up a QueryParser with a stemmer and suitable prefixes queryparser = xapian.QueryParser() queryparser.set_stemmer(xapian.Stem("en")) queryparser.set_stemming_strategy(queryparser.STEM_SOME) queryparser.add_prefix("title", "S") queryparser.add_prefix("description", "XD") # And parse the query query = queryparser.parse_query(querystring) # Use an Enquire object on the database to run the query enquire = xapian.Enquire(db) enquire.set_query(query) # And print out something about each match matches = [] ### Start of example code. # Set up a spy to inspect the MAKER value at slot 1 spy = xapian.ValueCountMatchSpy(1) enquire.add_matchspy(spy) for match in enquire.get_mset(offset, pagesize, 100): fields = json.loads(match.document.get_data().decode('utf8')) print(u"%(rank)i: #%(docid)3.3i %(title)s" % { 'rank': match.rank + 1, 'docid': match.docid, 'title': fields.get('TITLE', u''), }) matches.append(match.docid) # Fetch and display the spy values for facet in spy.values(): print("Facet: %(term)s; count: %(count)i" % { 'term' : facet.term.decode('utf-8'), 'count' : facet.termfreq }) # Finally, make sure we log the query and displayed results support.log_matches(querystring, offset, pagesize, matches) ### End of example code. if len(sys.argv) < 3: print("Usage: %s DBPATH QUERYTERM..." % sys.argv[0]) sys.exit(1) search(dbpath = sys.argv[1], querystring = " ".join(sys.argv[2:]))
2.671875
3
iconcollections/serializers.py
plrthink/myicons
83
4763
import re from rest_framework import serializers from .models import Collection, CollectionIcon class CollectionSerializer(serializers.ModelSerializer): """Collections's serializer""" class Meta: model = Collection read_only = ('token', ) class CollectionIconSerializer(serializers.ModelSerializer): """CollectionIcon's Serializer. """ class Meta: model = CollectionIcon def validate_width(self, attrs, source): width = attrs[source] if width < 1.0: raise serializers.ValidationError('Width should be greater than 1.0') return attrs def validate_name(self, attrs, source): name = attrs[source].lower() name = re.sub(r'[^a-z0-9\-]', '-', name).strip('-') name = re.sub(r'-+', '-', name) if name: attrs[source] = name else: raise serializers.ValidationError('Invalid name') return attrs def validate(self, attrs): packicon = attrs.get('packicon') svg_d = attrs.get('svg_d') width = attrs.get('width') if packicon or (svg_d and width): return attrs raise serializers.ValidationError( 'Either a packicon or the shape of icon should be given' )
2.5
2
Python/partition-to-k-equal-sum-subsets.py
sm2774us/leetcode_interview_prep_2021
0
4764
# Time: O(n*2^n) # Space: O(2^n) class Solution(object): def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ def dfs(nums, target, used, todo, lookup): if lookup[used] is None: targ = (todo-1)%target + 1 lookup[used] = any(dfs(nums, target, used | (1<<i), todo-num, lookup) \ for i, num in enumerate(nums) \ if ((used>>i) & 1) == 0 and num <= targ) return lookup[used] total = sum(nums) if total%k or max(nums) > total//k: return False lookup = [None] * (1 << len(nums)) lookup[-1] = True return dfs(nums, total//k, 0, total, lookup) # Time: O(k^(n-k) * k!) # Space: O(n) # DFS solution with pruning. class Solution2(object): def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ def dfs(nums, target, i, subset_sums): if i == len(nums): return True for k in range(len(subset_sums)): if subset_sums[k]+nums[i] > target: continue subset_sums[k] += nums[i] if dfs(nums, target, i+1, subset_sums): return True subset_sums[k] -= nums[i] if not subset_sums[k]: break return False total = sum(nums) if total%k != 0 or max(nums) > total//k: return False nums.sort(reverse=True) subset_sums = [0] * k return dfs(nums, total//k, 0, subset_sums)
3.03125
3
var/spack/repos/builtin/packages/aspell/package.py
jeanbez/spack
0
4765
# Copyright 2013-2022 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.package import * # See also: AspellDictPackage class Aspell(AutotoolsPackage, GNUMirrorPackage): """GNU Aspell is a Free and Open Source spell checker designed to eventually replace Ispell.""" homepage = "http://aspell.net/" gnu_mirror_path = "aspell/aspell-0.60.6.1.tar.gz" extendable = True # support activating dictionaries version('0.60.6.1', sha256='f52583a83a63633701c5f71db3dc40aab87b7f76b29723aeb27941eff42df6e1') patch('fix_cpp.patch') patch('issue-519.patch', when='@:0.60.6.1')
1.125
1
third_party_package/RDKit_2015_03_1/rdkit/ML/Descriptors/UnitTestParser.py
Ivy286/cluster_basedfps
9
4766
<reponame>Ivy286/cluster_basedfps<filename>third_party_package/RDKit_2015_03_1/rdkit/ML/Descriptors/UnitTestParser.py # # Copyright (C) 2001 <NAME> # """ unit testing code for compound descriptors """ from __future__ import print_function import unittest import Parser from rdkit.six.moves import xrange class TestCase(unittest.TestCase): def setUp(self): print('\n%s: '%self.shortDescription(),end='') self.piece1 = [['d1','d2'],['d1','d2']] self.aDict = {'Fe':{'d1':1,'d2':2},'Pt':{'d1':10,'d2':20}} self.pDict = {'d1':100.,'d2':200.} self.compos = [('Fe',1),('Pt',1)] self.cExprs = ["SUM($1)","SUM($1)+SUM($2)","MEAN($1)","DEV($2)","MAX($1)","MIN($2)","SUM($1)/$a"] self.results = [11.,33.,5.5,9.,10.,2.,0.11] self.tol = 0.0001 def testSingleCalcs(self): " testing calculation of a single descriptor " for i in xrange(len(self.cExprs)): cExpr= self.cExprs[i] argVect = self.piece1 + [cExpr] res = Parser.CalcSingleCompoundDescriptor(self.compos,argVect,self.aDict,self.pDict) self.assertAlmostEqual(res,self.results[i],2) def testMultipleCalcs(self): " testing calculation of multiple descriptors " for i in xrange(len(self.cExprs)): cExpr= self.cExprs[i] argVect = self.piece1 + [cExpr] res = Parser.CalcMultipleCompoundsDescriptor([self.compos,self.compos],argVect, self.aDict,[self.pDict,self.pDict]) self.assertAlmostEqual(res[0],self.results[i],2) self.assertAlmostEqual(res[1],self.results[i],2) #self.assertTrue(abs(res[0]-self.results[i])<self.tol,'Expression %s failed'%(cExpr)) #self.assertTrue((res[1]-self.results[i])<self.tol,'Expression %s failed'%(cExpr)) def TestSuite(): suite = unittest.TestSuite() suite.addTest(TestCase('testSingleCalcs')) suite.addTest(TestCase('testMultipleCalcs')) return suite if __name__ == '__main__': suite = TestSuite() unittest.TextTestRunner().run(suite)
2.1875
2
setup.py
maciek3000/data_dashboard
8
4767
from setuptools import setup, find_packages import pathlib here = pathlib.Path(__file__).parent.resolve() long_description = (here / "readme.md").read_text(encoding="utf-8") setup( name="data_dashboard", version="0.1.1", description="Dashboard to explore the data and to create baseline Machine Learning model.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/maciek3000/data_dashboard", author="<NAME>", author_email="<EMAIL>", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: Education", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Scientific/Engineering :: Visualization" ], package_dir={"data_dashboard": "data_dashboard"}, packages=find_packages(), python_requires=">=3.7", install_requires=[ "pandas>=1.2.3", "numpy>=1.19.5", "scipy>=1.6.1", "beautifulsoup4>=4.9.3", "scikit-learn>=0.24.1", "seaborn>=0.11.1", "bokeh>=2.3.0", "Jinja2>=2.11.3", "xgboost>=1.3.3", "lightgbm>=3.2.0" ], package_data={ "data_dashboard": ["static/*", "templates/*", "examples/*"] }, project_urls={ "Github": "https://github.com/maciek3000/data_dashboard", }, )
1.5625
2
test/e2e/tests/test_instance.py
acornett21/ack-ec2-controller
0
4768
<filename>test/e2e/tests/test_instance.py # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may # not use this file except in compliance with the License. A copy of the # License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is distributed # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the License for the specific language governing # permissions and limitations under the License. """Integration tests for Instance API. """ import datetime import pytest import time import logging from acktest.resources import random_suffix_name from acktest.k8s import resource as k8s from e2e import service_marker, CRD_GROUP, CRD_VERSION, load_ec2_resource from e2e.replacement_values import REPLACEMENT_VALUES from e2e.bootstrap_resources import get_bootstrap_resources RESOURCE_PLURAL = "instances" # highly available instance type for deterministic testing INSTANCE_TYPE = "m4.large" INSTANCE_AMI = "Amazon Linux 2 Kernel" INSTANCE_TAG_KEY = "owner" INSTANCE_TAG_VAL = "ack-controller" CREATE_WAIT_AFTER_SECONDS = 10 DELETE_WAIT_AFTER_SECONDS = 10 TIMEOUT_SECONDS = 300 def get_instance(ec2_client, instance_id: str) -> dict: instance = None try: resp = ec2_client.describe_instances( InstanceIds=[instance_id] ) instance = resp["Reservations"][0]["Instances"][0] except Exception as e: logging.debug(e) finally: return instance def get_instance_state(ec2_client, instance_id): instance_state = None try: instance = get_instance(ec2_client, instance_id) instance_state = instance["State"]["Name"] except Exception as e: logging.debug(e) finally: return instance_state def wait_for_instance_or_die(ec2_client, instance_id, desired_state, timeout_sec): while True: now = datetime.datetime.now() timeout = now + datetime.timedelta(seconds=timeout_sec) if datetime.datetime.now() >= timeout: pytest.fail(f"Timed out waiting for Instance to enter {desired_state} state") time.sleep(DELETE_WAIT_AFTER_SECONDS) instance_state = get_instance_state(ec2_client, instance_id) if instance_state == desired_state: break def get_ami_id(ec2_client): try: # Use latest AL2 resp = ec2_client.describe_images( Owners=['amazon'], Filters=[ {"Name": "architecture", "Values": ['x86_64']}, {"Name": "state", "Values": ['available']}, {"Name": "virtualization-type", "Values": ['hvm']}, ], ) for image in resp['Images']: if 'Description' in image: if INSTANCE_AMI in image['Description']: return image['ImageId'] except Exception as e: logging.debug(e) @pytest.fixture def instance(ec2_client): test_resource_values = REPLACEMENT_VALUES.copy() resource_name = random_suffix_name("instance-ack-test", 24) test_vpc = get_bootstrap_resources().SharedTestVPC subnet_id = test_vpc.public_subnets.subnet_ids[0] ami_id = get_ami_id(ec2_client) test_resource_values["INSTANCE_NAME"] = resource_name test_resource_values["INSTANCE_AMI_ID"] = ami_id test_resource_values["INSTANCE_TYPE"] = INSTANCE_TYPE test_resource_values["INSTANCE_SUBNET_ID"] = subnet_id test_resource_values["INSTANCE_TAG_KEY"] = INSTANCE_TAG_KEY test_resource_values["INSTANCE_TAG_VAL"] = INSTANCE_TAG_VAL # Load Instance CR resource_data = load_ec2_resource( "instance", additional_replacements=test_resource_values, ) logging.debug(resource_data) # Create k8s resource ref = k8s.CustomResourceReference( CRD_GROUP, CRD_VERSION, RESOURCE_PLURAL, resource_name, namespace="default", ) k8s.create_custom_resource(ref, resource_data) cr = k8s.wait_resource_consumed_by_controller(ref) assert cr is not None assert k8s.get_resource_exists(ref) yield (ref, cr) # Delete the instance when tests complete try: _, deleted = k8s.delete_custom_resource(ref, 3, 10) assert deleted except: pass @service_marker @pytest.mark.canary class TestInstance: def test_create_delete(self, ec2_client, instance): (ref, cr) = instance resource_id = cr["status"]["instanceID"] time.sleep(CREATE_WAIT_AFTER_SECONDS) # Check Instance exists instance = get_instance(ec2_client, resource_id) assert instance is not None # Give time for instance to come up wait_for_instance_or_die(ec2_client, resource_id, 'running', TIMEOUT_SECONDS) # Validate instance tags instance_tags = instance["Tags"] tag_present = False for t in instance_tags: if (t['Key'] == INSTANCE_TAG_KEY and t['Value'] == INSTANCE_TAG_VAL): tag_present = True assert tag_present # Delete k8s resource _, deleted = k8s.delete_custom_resource(ref, 2, 5) assert deleted is True # Reservation still exists, but instance will commence termination # State needs to be 'terminated' in order to remove the dependency on the shared subnet # for successful test cleanup wait_for_instance_or_die(ec2_client, resource_id, 'terminated', TIMEOUT_SECONDS)
2.296875
2
web/app/forms.py
Devidence7/Break
0
4769
<reponame>Devidence7/Break from flask_wtf import FlaskForm from wtforms import Form, StringField, PasswordField, BooleanField, SubmitField, IntegerField, validators, FileField, \ MultipleFileField, SelectField, RadioField, HiddenField, DecimalField, TextAreaField from wtforms.fields.html5 import DateField from wtforms.validators import DataRequired # Structure of the Login form class LoginForm(Form): email = StringField('Email', [ validators.DataRequired(message='Es necesario introducir un email')]) password = PasswordField('<PASSWORD>', [ validators.DataRequired(message='Es necesario introducir una contraseña')]) remember_me = BooleanField('Recuerdame') submit = SubmitField('Iniciar Sesión') # Structure of the Register form class RegisterForm(Form): name = StringField('Nombre', [ validators.DataRequired(message='Es necesario introducir un nombre'), validators.Length(min=4, max=50, message='El tamaño máximo del nombre son 50 carácteres')]) lastname = StringField('Apellidos', [ validators.DataRequired(message='Es necesario introducir apellidos'), validators.Length(min=4, max=50, message='El tamaño máximo del nombre son 50 carácteres')]) # username = StringField('Username', [ # validators.Length(min=4, max=25, message='El nombre de usuario debe tener entre 4 y 25 carácteres')]) email = StringField('Email', [ validators.DataRequired(message='Es necesario introducir un email'), validators.Length(min=1, max=50, message='El email no puede contener más de 50 carácteres')]) password = PasswordField('Contraseña', [ validators.DataRequired(message='Es necesario una contraseña'), validators.Length(min=8, message='La contraseña debe tener al menos 8 caracteres') ]) confirm = PasswordField('Confirmar Contraseña', [ validators.EqualTo('password', message='Las contraseñas no coinciden') ]) # Structure of the Login form class RestorePasswordForm(Form): email = StringField('Email', [ validators.DataRequired(message='Es necesario introducir un email')]) submit = SubmitField("Correo de Recuperación") class EditProfile(FlaskForm): name = StringField('Nombre', [ validators.DataRequired(message='Es necesario introducir un nombre'), validators.Length(min=4, max=50, message='El tamaño máximo del nombre son 50 carácteres')]) lastname = StringField('Apellidos', [ validators.DataRequired(message='Es necesario introducir apellidos'), validators.Length(min=4, max=50, message='El tamaño máximo del nombre son 50 carácteres')]) gender = RadioField('Género', choices = [('hombre','Hombre'),('mujer','Mujer')]) submit = SubmitField('Guardar cambios') class EditLocation(FlaskForm): lat = HiddenField('Latitud', [ validators.DataRequired(message='No se ha podido obtener la nueva localización') ]) lng = HiddenField('Longitud', [ validators.DataRequired(message='No se ha podido obtener la nueva localización') ]) submit = SubmitField('Establecer ubicación') class EditPassword(FlaskForm): old = PasswordField('Contraseña Anterior', [ validators.DataRequired(message='Es necesario introducir una contraseña') ]) password = PasswordField('<PASSWORD>aseña', [ validators.DataRequired(message='Es necesario introducir una contraseña'), validators.Length(min=8, message='La contraseña debe tener al menos 8 caracteres') ]) confirm = PasswordField('Confirme la contraseña', [ validators.EqualTo('password', message='Las contraseñas no coinciden') ]) submit = SubmitField('Cambiar contraseña') class EditEmail(FlaskForm): email = StringField('Correo electrónico', [ validators.DataRequired(message='Es necesario introducir una dirección de correo'), validators.Length(min=1, max=50, message='El correo no puede contener más de 50 carácteres')]) confirm = StringField('Confirmar correo electrónico', [ validators.EqualTo('email', message='Los correos no coinciden') ]) submit = SubmitField('Cambiar correo') class EditPicture(FlaskForm): picture = FileField('Imagen de perfil') submit = SubmitField('Establecer imagen') delete = SubmitField('Eliminar imagen') class DeleteAccount(FlaskForm): delete = SubmitField("Eliminar cuenta") # Structure of the Subir Anuncio form class SubirAnuncioForm(FlaskForm): # pictures = HiddenField("Imágenes") # mimes = HiddenField("Formatos de imagen") name = StringField('Nombre del producto', [ validators.DataRequired(message='Es necesario introducir un nombre de producto'), validators.Length(min=1, max=50, message='El tamaño máximo del nombre del producto son 50 carácteres')]) price = DecimalField('Precio (€)', [ validators.DataRequired(message='Es necesario introducir un precio'), validators.NumberRange(min=0, max=1000000, message='El precio intoducido no es válido (de 0 € a 999.999,99 €)')]) category = SelectField('Categoría', choices = [ ('Automoción', 'Automoción'), ('Informática', 'Informática'), ('Moda', 'Moda'), ('Deporte y ocio', 'Deporte y ocio'), ('Videojuegos', 'Videojuegos'), ('Libros y música', 'Libros y música'), ('Hogar y jardín', 'Hogar y jardín'), ('Foto y audio', 'Foto y audio') ], validators = [ validators.DataRequired(message='Es necesario seleccionar una categoría') ]) description = TextAreaField('Descripción', [ validators.DataRequired(message='Es necesario escribir una descripción')]) lat = HiddenField('Latitud') lng = HiddenField('Longitud') enddate = DateField('End', format = '%Y-%m-%d', description = 'Time that the event will occur', validators= [validators.Optional()] ) submit = SubmitField('Publicar') class ProductSearch(Form): categories = ['Automoción', 'Informática', 'Moda', 'Deporte y ocio', 'Videojuegos', 'Libros y música', 'Hogar y jardín', 'Foto y audio'] category = SelectField('Categoría', choices = [ ('Automoción', 'Automoción'), ('Informática', 'Informática'), ('Moda', 'Moda'), ('Deporte y ocio', 'Deporte y ocio'), ('Videojuegos', 'Videojuegos'), ('Libros y música', 'Libros y música'), ('Hogar y jardín', 'Hogar y jardín'), ('Foto y audio', 'Foto y audio') ]) estados = [('en venta', 'En Venta'), ('vendido', 'Vendido')] resultadosporpag = ['15', '30', '45', '60', '75', '90'] ordenacionlist = [('published ASC', 'Fecha (Más viejos primero)'), ('published DESC', 'Fecha (Más nuevos primero)'), ('distance DESC', 'Distancia Descendente'), ('distance ASC', 'Distancia Ascendente'), ('price ASC', 'Precio Ascendente'), ('price DESC', 'Precio Descendente'), ('views DESC', 'Popularidad descendente')] status = SelectField('Estado', choices = [ ('en venta','En Venta'), ('vendido','Vendido') ]) keywords = StringField('Palabras Clave') minprice = StringField('Precio Mínimo') maxprice = StringField('Precio Máximo') minpublished = DateField('Start', format = '%Y-%m-%d', description = 'Time that the event will occur') maxpublished = DateField('Start', format = '%Y-%m-%d', description = 'Time that the event will occur') resultados = SelectField('Resultados Por Página', choices = [ ('15', '15'), ('30', '30'), ('45', '45'), ('60', '60'), ('75', '75'), ('90', '90') ]) ordenacion = SelectField('Ordenación de Resultados', choices = [ ('published ASC', 'Fecha (Más viejos primero)'), ('published DESC', 'Fecha (Más nuevos primero)'), ('distance DESC', 'Distancia Descendente'), ('distance ASC', 'Distancia Ascendente'), ('price ASC', 'Precio Ascendente'), ('price DESC', 'Precio Descendente'), ('views DESC', 'Popularidad descendente') ]) distancia = StringField('Distancia') submit = SubmitField('Buscar') class Review(FlaskForm): stars = IntegerField('Puntuación', [ validators.DataRequired(message='Es necesario introducir una puntuación entre 1 y 5'), validators.NumberRange(min=1, max=5, message='La puntuación debe ser de 1 a 5 estrellas')]) comment = TextAreaField('Comentario', [ validators.DataRequired(message='Es necesario escribir un comentario')]) submit = SubmitField('Publicar Valoración') class bidPlacementForm(FlaskForm): amount = StringField('Cantidad') submit = SubmitField('Realizar Puja') class reportForm(Form): category = SelectField('Categoría', choices = [ ('Sospecha de fraude', 'Sospecha de fraude'), ('No acudió a la cita', 'No acudió a la cita'), ('Mal comportamiento', 'Mal comportamiento'), ('Artículo defectuoso', 'Artículo defectuoso'), ('Otros', 'Otros')]) description = TextAreaField('Descripción del informe', [ validators.DataRequired(message='Es necesario escribir una descripción')]) submit = SubmitField('Publicar Informe')
2.828125
3
hello.py
LMiceOrg/postdoc-voting
0
4770
#coding: utf-8 import sys import os import asyncio import websockets import json import socket import xlrd #global vars phd_data = None pro_data = None def get_host_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('192.168.127.12', 65535)) ip = s.getsockname()[0] finally: s.close() return ip def read_xls(name): try: book = xlrd.open_workbook(name) except: print("Open Excel(%s) failed!" % name) for i in range(book.nsheets): s = book.sheet_by_index(i) sname = s.name svalue = list() for r in range(s.nrows): svalue.append( s.row_values(r) ) ctx[i] = (sname, svalue) return ctx #生成json def gen_pro(): ret = { "header": [ { "name": "id", "title": "ID", "size": 50, "sortable": True, "sortDir": "asc", "format": "number" }, { "name": "name", "title": "Name", "sortable": True }, { "name": "start", "title": "Start", "sortable": True, "size": 150, "format": "date", "formatMask": "dd-mm-yyyy" }, { "name": "age", "title": "Age", "sortable": True, "size": 80 }, { "name": "salary", "title": "Salary", "sortable": True, "size": 150, "format": "money", "show": True } ], "data":[] } return ret async def proc_msg(ws, msg): method = msg.get('method') if method == 'host_ip': ip=get_host_ip() ret = { "method":method, "type":'success', 'return':ip } await ws.send(json.dumps(ret)) elif method=='genpro': phd_file = msg.get('phd_file') if phd_file: phd_data = read_xls(phd_file) pro_file = msg.get('pro_file') if pro_file: pro_data = read_xls(pro_file) data = gen_pro() ret = { "method":method, "type":'success', 'return':data } await ws.send(json.dumps(ret)) else: ret = {'type':'unknown'} await ws.send(json.dumps(ret)) async def recv_msg(websocket): while True: recv_text = await websocket.recv() try: msg = json.loads(recv_text) await proc_msg(websocket, msg) except: ret = {'type':'error'} await ws.send(json.dumps(ret)) async def main_logic(websocket, path): await recv_msg(websocket) port = 5678 if len(sys.argv) >=2: port = sys.argv[1] ws_server = websockets.serve(main_logic, '0.0.0.0', port) asyncio.get_event_loop().run_until_complete(ws_server) asyncio.get_event_loop().run_forever()
2.65625
3
runtime/Python3/src/antlr4/dfa/DFASerializer.py
maximmenshikov/antlr4
11,811
4771
# # Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. # Use of this file is governed by the BSD 3-clause license that # can be found in the LICENSE.txt file in the project root. #/ # A DFA walker that knows how to dump them to serialized strings.#/ from io import StringIO from antlr4 import DFA from antlr4.Utils import str_list from antlr4.dfa.DFAState import DFAState class DFASerializer(object): __slots__ = ('dfa', 'literalNames', 'symbolicNames') def __init__(self, dfa:DFA, literalNames:list=None, symbolicNames:list=None): self.dfa = dfa self.literalNames = literalNames self.symbolicNames = symbolicNames def __str__(self): if self.dfa.s0 is None: return None with StringIO() as buf: for s in self.dfa.sortedStates(): n = 0 if s.edges is not None: n = len(s.edges) for i in range(0, n): t = s.edges[i] if t is not None and t.stateNumber != 0x7FFFFFFF: buf.write(self.getStateString(s)) label = self.getEdgeLabel(i) buf.write("-") buf.write(label) buf.write("->") buf.write(self.getStateString(t)) buf.write('\n') output = buf.getvalue() if len(output)==0: return None else: return output def getEdgeLabel(self, i:int): if i==0: return "EOF" if self.literalNames is not None and i<=len(self.literalNames): return self.literalNames[i-1] elif self.symbolicNames is not None and i<=len(self.symbolicNames): return self.symbolicNames[i-1] else: return str(i-1) def getStateString(self, s:DFAState): n = s.stateNumber baseStateStr = ( ":" if s.isAcceptState else "") + "s" + str(n) + ( "^" if s.requiresFullContext else "") if s.isAcceptState: if s.predicates is not None: return baseStateStr + "=>" + str_list(s.predicates) else: return baseStateStr + "=>" + str(s.prediction) else: return baseStateStr class LexerDFASerializer(DFASerializer): def __init__(self, dfa:DFA): super().__init__(dfa, None) def getEdgeLabel(self, i:int): return "'" + chr(i) + "'"
1.9375
2
sw/calibrate.py
microsoft/moabian
13
4772
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ Calibration Controller Performs calibration for hue, center of camera position, and servo offsets """ import os import cv2 import time import json import argparse import datetime import numpy as np import logging as log from env import MoabEnv from typing import Tuple from common import Vector2 from detector import hsv_detector from controllers import pid_controller from dataclasses import dataclass, astuple from hardware import plate_angles_to_servo_positions @dataclass class CalibHue: hue: int = 44 # Reasonable default success: bool = False early_quit: bool = False # If menu is pressed before the calibration is complete def __iter__(self): return iter(astuple(self)) @dataclass class CalibPos: position: Tuple[float, float] = (0.0, 0.0) success: bool = False early_quit: bool = False # If menu is pressed before the calibration is complete def __iter__(self): return iter(astuple(self)) @dataclass class CalibServos: servos: Tuple[float, float, float] = (0.0, 0.0, 0.0) success: bool = False early_quit: bool = False # If menu is pressed before the calibration is complete def __iter__(self): return iter(astuple(self)) def ball_close_enough(x, y, radius, max_ball_dist=0.045, min_ball_dist=0.01): # reject balls which are too far from the center and too small return ( np.abs(x) < max_ball_dist and np.abs(y) < max_ball_dist and radius > min_ball_dist ) def calibrate_hue(camera_fn, detector_fn, is_menu_down_fn): hue_low = 0 hue_high = 360 hue_steps = 41 # Is 41 instead of 40 so that the steps are even img_frame, elapsed_time = camera_fn() hue_options = list(np.linspace(hue_low, hue_high, hue_steps)) detected_hues = [] for hue in hue_options: if is_menu_down_fn(): return CalibHue(early_quit=True) img_frame, elapsed_time = camera_fn() ball_detected, ((x, y), radius) = detector_fn(img_frame, hue=hue, debug=True) # If we found a ball roughly in the center that is large enough if ball_detected and ball_close_enough(x, y, radius): log.info( f"hue={hue:0.3f}, ball_detected={ball_detected}, " f"(x, y)={x:0.3f} {y:0.3f}, radius={radius:0.3f}" ) detected_hues.append(hue) if len(detected_hues) > 0: # https://en.wikipedia.org/wiki/Mean_of_circular_quantities detected_hues_rad = np.radians(detected_hues) sines, cosines = np.sin(detected_hues_rad), np.cos(detected_hues_rad) sin_mean, cos_mean = np.mean(sines), np.mean(cosines) avg_hue_rad = np.arctan2(sin_mean, cos_mean) avg_hue = np.degrees(avg_hue_rad) % 360 # Convert back to [0, 360] print(f"Hues are: {detected_hues}") print(f"Hue calibrated: {avg_hue:0.2f}") print(f"Avg hue: {avg_hue:0.2f}") return CalibHue(hue=int(avg_hue), success=True) else: log.warning(f"Hue calibration failed.") return CalibHue() def calibrate_pos(camera_fn, detector_fn, hue, is_menu_down_fn): for i in range(10): # Try and detect for 10 frames before giving up if is_menu_down_fn(): return CalibPos(early_quit=True) img_frame, elapsed_time = camera_fn() ball_detected, ((x, y), radius) = detector_fn(img_frame, hue=hue) # If we found a ball roughly in the center that is large enough if ball_detected and ball_close_enough(x, y, radius): x_offset = round(x, 3) y_offset = round(y, 3) log.info(f"Offset calibrated: [{x_offset:.3f}, {y_offset:.3f}]") return CalibPos(position=(x_offset, y_offset), success=True) log.warning(f"Offset calibration failed.") return CalibPos() def calibrate_servo_offsets(pid_fn, env, stationary_vel=0.005, time_limit=20): start_time = time.time() action = Vector2(0, 0) # Initial high vel_history (to use the vel_hist[-100:] later) vel_x_hist = [1.0 for _ in range(100)] vel_y_hist = [1.0 for _ in range(100)] # Run until the ball has stabilized or the time limit was reached while time.time() < start_time + time_limit: state = env.step(action) action, info = pid_fn(state) (x, y, vel_x, vel_y, sum_x, sum_y), ball_detected, buttons = state # Quit on menu down if buttons.menu_button: return CalibServos(early_quit=True) if ball_detected: vel_x_hist.append(vel_x) vel_y_hist.append(vel_y) prev_100_x = np.mean(np.abs(vel_x_hist[-100:])) prev_100_y = np.mean(np.abs(vel_y_hist[-100:])) print("Prev 100: ", (prev_100_x, prev_100_y)) # If the average velocity for the last 100 timesteps is under the limit if (prev_100_x < stationary_vel) and (prev_100_y < stationary_vel): # Calculate offsets by calculating servo positions at the # current stable position and subtracting the `default` zeroed # position of the servos. servos = np.array(plate_angles_to_servo_positions(*action)) servos_zeroed = np.array(plate_angles_to_servo_positions(0, 0)) servo_offsets = list(servos - servos_zeroed) return CalibServos(servos=servo_offsets, success=True) # If the plate could be stabilized in time_limit seconds, quit log.warning(f"Servo calibration failed.") return CalibServos() def write_calibration(calibration_dict, calibration_file="bot.json"): log.info("Writing calibration.") # write out stuff with open(calibration_file, "w+") as outfile: log.info(f"Creating calibration file {calibration_file}") json.dump(calibration_dict, outfile, indent=4, sort_keys=True) def read_calibration(calibration_file="bot.json"): log.info("Reading previous calibration.") if os.path.isfile(calibration_file): with open(calibration_file, "r") as f: calibration_dict = json.load(f) else: # Use defaults calibration_dict = { "ball_hue": 44, "plate_offsets": (0.0, 0.0), "servo_offsets": (0.0, 0.0, 0.0), } return calibration_dict def wait_for_joystick_or_menu(hardware, sleep_time=1 / 30): """Waits for either the joystick or the menu. Returns the buttons""" while True: buttons = hardware.get_buttons() if buttons.menu_button or buttons.joy_button: return buttons time.sleep(sleep_time) def wait_for_menu(hardware, sleep_time=1 / 30): while True: menu_button, joy_button, joy_x, joy_y = hardware.get_buttons() time.sleep(sleep_time) if menu_button: return def run_calibration(env, pid_fn, calibration_file): # Get some hidden things from env hardware = env.hardware camera_fn = hardware.camera detector_fn = hardware.detector def is_menu_down(hardware=hardware) -> bool: return hardware.get_buttons().menu_button # lift plate up first hardware.set_angles(0, 0) # Display message and wait for joystick hardware.display( "put ball on stand\nclick joystick", # "Place ball in\ncenter using\nclear stand.\n\n" "Click joystick\nwhen ready." scrolling=True, ) buttons = wait_for_joystick_or_menu(hardware) if buttons.menu_button: # Early quit hardware.go_up() return hardware.display("Calibrating...") hue_calib = calibrate_hue(camera_fn, detector_fn, is_menu_down) if hue_calib.early_quit: hardware.go_up() return # Calibrate position pos_calib = calibrate_pos(camera_fn, detector_fn, hue_calib.hue, is_menu_down) if pos_calib.early_quit: hardware.go_up() return # Save calibration calibration_dict = read_calibration(calibration_file) calibration_dict["ball_hue"] = hue_calib.hue calibration_dict["plate_offsets"] = pos_calib.position x_offset, y_offset = pos_calib.position write_calibration(calibration_dict) # Update the environment to use the new calibration # Warning! This mutates the state! hardware.reset_calibration(calibration_file=calibration_file) if pos_calib.success and hue_calib.success: # and servo_calib.success: hardware.display(f"Ok! Ball hue={hue_calib.hue}\nClick menu...", scrolling=True) elif not (pos_calib.success or hue_calib.success): # or servo_calib.success): hardware.display("Calibration failed\nClick menu...", scrolling=True) else: hue_str = ( f"Hue calib:\nsuccessful\nBall hue = {hue_calib.hue}\n\n" if hue_calib.success else "Hue calib:\nfailed\n\n" ) pos_str = ( f"Position \ncalib:\nsuccessful\nPosition = \n({100*x_offset:.1f}, {100*y_offset:.1f})cm\n\n" if hue_calib.success else "(X, Y) calib:\nfailed\n\n" ) hardware.display( "Calibration\npartially succeeded\n\n" + hue_str + pos_str + "Click menu\nto return...\n", scrolling=True, ) # When the calibration is complete, save the image of what the moab camera # sees (useful for debugging when the hue calibration fails) # Have a nice filename with the time and whether it succeeded or failed time_of_day = datetime.datetime.now().strftime("%H%M%S") filename = "/tmp/hue" if hue_calib.success: filename += f".{hue_calib.hue}.{time_of_day}.jpg" else: filename += f".fail.{time_of_day}.jpg" img_frame, _ = camera_fn() # Huemask keeps an internal cache. By sending a new hue (hue + 1) invalidates # the cache. TODO: added this while searching for a state bug detector_fn(img_frame, hue=hue_calib.hue + 1, debug=True, filename=filename) hardware.go_up() def run_servo_calibration(env, pid_fn, calibration_file): # Warning: servo calib works but doesn't currently give a good calibration raise NotImplementedError # Get some hidden things from env hardware = env.hardware camera_fn = hardware.camera detector_fn = hardware.detector # Start the calibration with uncalibrated servos hardware.servo_offsets = (0, 0, 0) # lift plate up fist hardware.set_angles(0, 0) # Calibrate servo offsets hardware.display( "Calibarating\nservos\n\n" "Place ball in\ncenter without\n stand.\n\n" "Click joystick\nto continue.", scrolling=True, ) buttons = wait_for_joystick_or_menu(hardware) if buttons.menu_button: # Early quit hardware.go_up() return hardware.display("Calibrating\nservos...", scrolling=True) servo_calib = calibrate_servo_offsets(pid_fn, env) # Save calibration calibration_dict = read_calibration(calibration_file) calibration_dict["servo_offsets"] = servo_calib.servos s1, s2, s3 = servo_calib.servos write_calibration(calibration_dict) # Update the environment to use the new calibration # Warning! This mutates the state! env.reset_calibration(calibration_file=calibration_file) if servo_calib.success: hardware.display( f"servo offsets =\n({s1:.2f}, {s2:.2f}, {s3:.2f})\n\n" "Click menu\nto return...\n", scrolling=True, ) print(f"servo offsets =\n({s1:.2f}, {s2:.2f}, {s3:.2f})") else: hardware.display( "Calibration\nfailed\n\nClick menu\nto return...", scrolling=True ) hardware.go_up() def calibrate_controller(**kwargs): run_calibration( kwargs["env"], kwargs["pid_fn"], kwargs["calibration_file"], ) def wait_for_menu_and_stream(): # Get some hidden things from env to be able to stream the calib results env = kwargs["env"] hardware = env.hardware camera_fn = hardware.camera detector_fn = hardware.detector menu_button = False while not menu_button: img_frame, _ = camera_fn() detector_fn(img_frame, debug=True) # Save to streaming menu, joy, _, _ = hardware.get_buttons() if menu or joy: break env.hardware.go_up() return wait_for_menu_and_stream def main(calibration_file, frequency=30, debug=True): pid_fn = pid_controller(frequency=frequency) with MoabEnv(frequency=frequency, debug=debug) as env: env.step((0, 0)) time.sleep(0.2) env.hardware.enable_servos() time.sleep(0.2) env.hardware.set_servos(133, 133, 133) run_calibration(env, pid_fn, calibration_file) env.hardware.disable_servos() if __name__ == "__main__": # Parse command line args parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action="store_true") parser.add_argument("-f", "--file", default="bot.json", type=str) args, _ = parser.parse_known_args() main(args.file, debug=args.debug)
3.03125
3
marketing/tests_celery_tasks.py
renzyndrome/lits-crm
1
4773
from datetime import datetime, timedelta from django.test import TestCase from django.test.utils import override_settings from marketing.tasks import ( delete_multiple_contacts_tasks, list_all_bounces_unsubscribes, run_all_campaigns, run_campaign, send_campaign_email_to_admin_contact, send_scheduled_campaigns, upload_csv_file, ) from marketing.tests import TestMarketingModel class TestCeleryTasks(TestMarketingModel, TestCase): @override_settings( CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_ALWAYS_EAGER=True, BROKER_BACKEND="memory", ) def test_celery_tasks(self): task = run_campaign.apply( (self.campaign.id,), ) self.assertEqual("SUCCESS", task.state) self.campaign.reply_to_email = None self.campaign.save() task = run_campaign.apply( (self.campaign.id,), ) self.assertEqual("SUCCESS", task.state) self.campaign.schedule_date_time = datetime.now() self.campaign.save() task = run_all_campaigns.apply() self.assertEqual("SUCCESS", task.state) task = list_all_bounces_unsubscribes.apply() self.assertEqual("SUCCESS", task.state) task = send_scheduled_campaigns.apply() self.assertEqual("SUCCESS", task.state) task = delete_multiple_contacts_tasks.apply( (self.contact_list.id,), ) self.assertEqual("SUCCESS", task.state) task = send_campaign_email_to_admin_contact.apply( (self.campaign.id,), ) self.assertEqual("SUCCESS", task.state) valid_rows = [ { "company name": "company_name_1", "email": "<EMAIL>", "first name": "first_name", "last name": "last_name", "city": "Hyderabad", "state": "Telangana", }, { "company name": "company_name_2", "email": "<EMAIL>", "first name": "first_name", "last name": "last_name", "city": "Hyderabad", "state": "Telangana", }, { "company name": "company_name_3", "email": "<EMAIL>", "first name": "first_name", "last name": "last_name", "city": "Hyderabad", "state": "Telangana", }, { "company name": "company_name_4", "email": "<EMAIL>", "first name": "first_name", "last name": "last_name", "city": "Hyderabad", "state": "Telangana", }, ] invalid_rows = [ { "company name": "company_name_1", "email": "useremail.com", "first name": "first_name", "last name": "last_name", "city": "Hyderabad", "state": "Telangana", }, { "company name": "company_name_2", "email": "user2@email", "first name": "first_name", "last name": "last_name", "city": "Hyderabad", "state": "Telangana", }, ] task = upload_csv_file.apply( ( valid_rows, invalid_rows, self.user.id, [ self.contact_list.id, ], self.company.id, ), ) self.assertEqual("SUCCESS", task.state)
2.15625
2
doc's/3-labels_and_titles.py
andreluispy/py2html
0
4774
<filename>doc's/3-labels_and_titles.py<gh_stars>0 from py2html.main import * page = web() page.create() # Header Parameters # text = header text # n = title level page.header(text='My Site', n=1) # Label Parameters # text = label text # color = label color page.label(text='', color='') page.compile()
2.59375
3
JorGpi/tests/test_pickup.py
adujovic/JorG
1
4775
import unittest from JorGpi.pickup.pickup import SmartPickUp,Reference,CommandLineOptions class TestPickupIron(unittest.TestCase): @staticmethod def options(*args): return CommandLineOptions(*args) def test_iron_001(self): _input = "test -R _VASP/Fe/noFlip -D _VASP/Fe/flip00000 -E Fe -J1 -U mRy".split(" ") options = TestPickupIron.options(*_input) elements = ''.join(options('elements')) self.assertEqual(elements,'Fe$') ref = Reference(options('reference')+"/POSCAR") self.assertEqual(ref(),0) self.assertEqual(options('number_of_interactions'),1) pickerUpper = SmartPickUp(options('number_of_interactions'),elements) pickerUpper.read(options('reference'),*options('directories'),reference=ref()) self.assertEqual(options('units'),'mRy') _J_ij = pickerUpper.solve(units=options('units')).flatten() self.assertEqual(_J_ij[0],1.1861042008301703) self.assertEqual(_J_ij[1],4.157645364906014)
2.515625
3
jwt_auth/admin.py
alaraayan/todo-backend
0
4776
<reponame>alaraayan/todo-backend<filename>jwt_auth/admin.py from django.contrib import admin from django.contrib.auth import get_user_model User = get_user_model() admin.site.register(User)
1.359375
1
spotseeker_server/test/search/distance.py
uw-it-aca/spotseeker_server
5
4777
<reponame>uw-it-aca/spotseeker_server # Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.test import TestCase from django.conf import settings from django.test.client import Client from spotseeker_server.models import Spot import simplejson as json from decimal import * from django.test.utils import override_settings from mock import patch from spotseeker_server import models @override_settings(SPOTSEEKER_AUTH_MODULE="spotseeker_server.auth.all_ok") class SpotSearchDistanceTest(TestCase): def test_invalid_latitude(self): c = Client() response = c.get( "/api/v1/spot", { "center_latitude": "bad_data", "center_longitude": -40, "distance": 10, }, ) self.assertEquals( response.status_code, 200, "Accepts a query with bad latitude" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) def test_invalid_longitude(self): c = Client() response = c.get( "/api/v1/spot", { "center_latitude": "30", "center_longitude": "bad_data", "distance": "10", }, ) self.assertEquals( response.status_code, 200, "Accepts a query with bad longitude" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) def test_invalid_height(self): c = Client() response = c.get( "/api/v1/spot", { "center_latitude": "30", "center_longitude": -40, "height_from_sea_level": "bad_data", "distance": "10", }, ) self.assertEquals( response.status_code, 200, "Accepts a query with bad height" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) def test_invalid_distance(self): c = Client() response = c.get( "/api/v1/spot", { "center_latitude": "30", "center_longitude": "-40", "distance": "bad_data", }, ) self.assertEquals( response.status_code, 200, "Accepts a query with bad distance" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) def test_large_longitude(self): c = Client() response = c.get( "/api/v1/spot", {"center_latitude": 30, "center_longitude": 190, "distance": 10}, ) self.assertEquals( response.status_code, 200, "Accepts a query with too large longitude", ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) def test_large_latitude(self): c = Client() response = c.get( "/api/v1/spot", {"center_latitude": 100, "center_longitude": -40, "distance": 10}, ) self.assertEquals( response.status_code, 200, "Accepts a query with too large latitude", ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) def test_large_negative_latitude(self): c = Client() response = c.get( "/api/v1/spot", {"center_latitude": -100, "center_longitude": -40, "distance": 10}, ) self.assertEquals( response.status_code, 200, "Accepts a query with too negative latitude", ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) def test_large_negative_longitude(self): c = Client() response = c.get( "/api/v1/spot", {"center_latitude": 40, "center_longitude": -190, "distance": 10}, ) self.assertEquals( response.status_code, 200, "Accepts a query with too negative longitude", ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) def test_no_params(self): c = Client() response = c.get("/api/v1/spot", {}) self.assertEquals( response.status_code, 200, "Accepts a query with no params" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) def test_distances(self): # Spots are in the atlantic to make them less likely to collide # with actual spots center_lat = 30.000000 center_long = -40.000000 # Inner spots are 10 meters away from the center # Mid spots are 50 meters away from the center # Outer spots are 100 meters away from the center # Far out spots are 120 meters away, at the north # Creating these from the outside in, so things that sort by # primary key will give bad results for things that should be # sorted by distance for i in range(0, 100): far_out = Spot.objects.create( name="Far Out %s" % i, latitude=Decimal("30.0010779783"), longitude=Decimal("-40.0"), ) far_out.save() outer_top = Spot.objects.create( name="Outer Top", latitude=Decimal("30.0008983153"), longitude=Decimal("-40.0"), ) outer_top.save() outer_bottom = Spot.objects.create( name="Outer Bottom", latitude=Decimal("29.9991016847"), longitude=Decimal("-40.0"), ) outer_bottom.save() outer_left = Spot.objects.create( name="Outer Left", latitude=Decimal("30.0"), longitude=Decimal("-40.0010372851"), ) outer_left.save() outer_right = Spot.objects.create( name="Outer Right", latitude=Decimal("30.0"), longitude=Decimal("-39.9989627149"), ) outer_right.save() mid_top = Spot.objects.create( name="Mid Top", latitude=Decimal(" 30.0004491576"), longitude=Decimal("-40.0"), ) mid_top.save() mid_bottom = Spot.objects.create( name="Mid Bottom", latitude=Decimal("29.9995508424"), longitude=Decimal("-40.0"), ) mid_bottom.save() mid_left = Spot.objects.create( name="Mid Left", latitude=Decimal("30.0"), longitude=Decimal("-40.0005186426"), ) mid_left.save() mid_right = Spot.objects.create( name="Mid Right", latitude=Decimal("30.0"), longitude=Decimal("-39.9994813574"), ) mid_right.save() inner_top = Spot.objects.create( name="Inner Top", latitude=Decimal("30.0000898315"), longitude=Decimal("-40.0"), ) inner_top.save() inner_bottom = Spot.objects.create( name="Inner Bottom", latitude=Decimal("29.9999101685"), longitude=Decimal("-40.0"), ) inner_bottom.save() inner_left = Spot.objects.create( name="Inner Left", latitude=Decimal("30.0"), longitude=Decimal("-40.0001037285"), ) inner_left.save() inner_right = Spot.objects.create( name="Inner Right", latitude=Decimal("30.0"), longitude=Decimal("-39.9998962715"), ) inner_right.save() # Testing to make sure too small of a radius returns nothing c = Client() response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 1, }, ) self.assertEquals( response.status_code, 200, "Accepts a query with no matches" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) self.assertEquals( response.content.decode(), "[]", "Should return no matches" ) # Testing the inner ring response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 12, }, ) self.assertEquals( response.status_code, 200, "Accepts the distance query" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) spots = json.loads(response.content) self.assertEquals(len(spots), 4, "Returns 4 spots") spot_ids = { inner_left.pk: 1, inner_right.pk: 1, inner_top.pk: 1, inner_bottom.pk: 1, } for spot in spots: self.assertEquals( spot_ids[spot["id"]], 1, "Spot matches a unique inner spot" ) spot_ids[spot["id"]] = 2 # Testing the mid ring response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 60, }, ) self.assertEquals( response.status_code, 200, "Accepts the distance query" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) spots = json.loads(response.content) self.assertEquals(len(spots), 8, "Returns 8 spots") spot_ids = { inner_left.pk: 1, inner_right.pk: 1, inner_top.pk: 1, inner_bottom.pk: 1, mid_left.pk: 1, mid_right.pk: 1, mid_top.pk: 1, mid_bottom.pk: 1, } for spot in spots: self.assertEquals( spot_ids[spot["id"]], 1, "Spot matches a unique inner or mid spot", ) spot_ids[spot["id"]] = 2 # Testing the outer ring response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 110, }, ) self.assertEquals( response.status_code, 200, "Accepts the distance query" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) spots = json.loads(response.content) self.assertEquals(len(spots), 12, "Returns 12 spots") spot_ids = { inner_left.pk: 1, inner_right.pk: 1, inner_top.pk: 1, inner_bottom.pk: 1, mid_left.pk: 1, mid_right.pk: 1, mid_top.pk: 1, mid_bottom.pk: 1, outer_left.pk: 1, outer_right.pk: 1, outer_top.pk: 1, outer_bottom.pk: 1, } for spot in spots: self.assertEquals( spot_ids[spot["id"]], 1, "Spot matches a unique inner, mid or outer spot", ) spot_ids[spot["id"]] = 2 # testing a limit - should get the inner 4, and any 2 of the mid response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 60, "limit": 6, }, ) self.assertEquals( response.status_code, 200, "Accepts the distance query" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) spots = json.loads(response.content) self.assertEquals(len(spots), 6, "Returns 6 spots") spot_ids = { inner_left.pk: 1, inner_right.pk: 1, inner_top.pk: 1, inner_bottom.pk: 1, mid_left.pk: 1, mid_right.pk: 1, mid_top.pk: 1, mid_bottom.pk: 1, } for spot in spots: self.assertEquals( spot_ids[spot["id"]], 1, "Spot matches a unique inner, mid or outer spot", ) spot_ids[spot["id"]] = 2 self.assertEquals( spot_ids[inner_left.pk], 2, "Inner left was selected" ) self.assertEquals( spot_ids[inner_right.pk], 2, "Inner right was selected" ) self.assertEquals(spot_ids[inner_top.pk], 2, "Inner top was selected") self.assertEquals( spot_ids[inner_bottom.pk], 2, "Inner bottom was selected" ) # Testing limits - should get all of the inner and mid, but # no outer spots response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 101, "limit": 8, }, ) self.assertEquals( response.status_code, 200, "Accepts the distance query" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) spots = json.loads(response.content) self.assertEquals(len(spots), 8, "Returns 8 spots") spot_ids = { inner_left.pk: 1, inner_right.pk: 1, inner_top.pk: 1, inner_bottom.pk: 1, mid_left.pk: 1, mid_right.pk: 1, mid_top.pk: 1, mid_bottom.pk: 1, } for spot in spots: self.assertEquals( spot_ids[spot["id"]], 1, "Spot matches a unique inner or mid spot", ) spot_ids[spot["id"]] = 2 # Testing limits - should get all inner and mid spots, and # 2 outer spots response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 101, "limit": 10, }, ) self.assertEquals( response.status_code, 200, "Accepts the distance query" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) spots = json.loads(response.content) self.assertEquals(len(spots), 10, "Returns 10 spots") spot_ids = { inner_left.pk: 1, inner_right.pk: 1, inner_top.pk: 1, inner_bottom.pk: 1, mid_left.pk: 1, mid_right.pk: 1, mid_top.pk: 1, mid_bottom.pk: 1, outer_left.pk: 1, outer_right.pk: 1, outer_top.pk: 1, outer_bottom.pk: 1, } for spot in spots: self.assertEquals( spot_ids[spot["id"]], 1, "Spot matches a unique inner, mid or outer spot", ) spot_ids[spot["id"]] = 2 self.assertEquals( spot_ids[inner_left.pk], 2, "Inner left was selected" ) self.assertEquals( spot_ids[inner_right.pk], 2, "Inner right was selected" ) self.assertEquals(spot_ids[inner_top.pk], 2, "Inner top was selected") self.assertEquals( spot_ids[inner_bottom.pk], 2, "Inner bottom was selected" ) self.assertEquals(spot_ids[mid_left.pk], 2, "Mid left was selected") self.assertEquals(spot_ids[mid_right.pk], 2, "Mid rightwas selected") self.assertEquals(spot_ids[mid_top.pk], 2, "Mid top was selected") self.assertEquals( spot_ids[mid_bottom.pk], 2, "Mid bottom was selected" ) # Testing that limit 0 = no limit - get all 12 spots response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 110, "limit": 0, }, ) self.assertEquals( response.status_code, 200, "Accepts the distance query" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) spots = json.loads(response.content) self.assertEquals(len(spots), 12, "Returns 12 spots with a limit of 0") spot_ids = { inner_left.pk: 1, inner_right.pk: 1, inner_top.pk: 1, inner_bottom.pk: 1, mid_left.pk: 1, mid_right.pk: 1, mid_top.pk: 1, mid_bottom.pk: 1, outer_left.pk: 1, outer_right.pk: 1, outer_top.pk: 1, outer_bottom.pk: 1, } for spot in spots: self.assertEquals( spot_ids[spot["id"]], 1, "Spot matches a unique inner, mid or outer spot", ) spot_ids[spot["id"]] = 2 # Testing that the default limit is 20 spaces response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 150, }, ) self.assertEquals( response.status_code, 200, "Accepts the distance query" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) spots = json.loads(response.content) self.assertEquals( len(spots), 20, "Returns 20 spots with no defined limit" ) spot_ids = { inner_left.pk: 1, inner_right.pk: 1, inner_top.pk: 1, inner_bottom.pk: 1, mid_left.pk: 1, mid_right.pk: 1, mid_top.pk: 1, mid_bottom.pk: 1, outer_left.pk: 1, outer_right.pk: 1, outer_top.pk: 1, outer_bottom.pk: 1, } far_out_count = 0 for spot in spots: if spot["id"] in spot_ids: self.assertEquals( spot_ids[spot["id"]], 1, "Spot matches a unique inner, mid or outer spot", ) else: far_out_count += 1 self.assertEquals( far_out_count, 8, "Found 8 far out spots to fill in the limit of 20", ) # Testing that with a limit of 0, we pull in all spots in range response = c.get( "/api/v1/spot", { "center_latitude": center_lat, "center_longitude": center_long, "distance": 130, "limit": 0, }, ) self.assertEquals( response.status_code, 200, "Accepts the distance query" ) self.assertEquals( response["Content-Type"], "application/json", "Has the json header" ) spots = json.loads(response.content) self.assertEquals( len(spots), 112, "Returns 112 spots with a limit of 0" ) spot_ids = { inner_left.pk: 1, inner_right.pk: 1, inner_top.pk: 1, inner_bottom.pk: 1, mid_left.pk: 1, mid_right.pk: 1, mid_top.pk: 1, mid_bottom.pk: 1, outer_left.pk: 1, outer_right.pk: 1, outer_top.pk: 1, outer_bottom.pk: 1, } far_out_count = 0 for spot in spots: if spot["id"] in spot_ids: self.assertEquals( spot_ids[spot["id"]], 1, "Spot matches a unique inner, mid or outer spot", ) else: far_out_count += 1 self.assertEquals(far_out_count, 100, "Found all 100 far out spots")
2.328125
2
get_active_LSPs.py
JNPRAutomate/northstar_SDN_controller_automation
3
4778
# this python script makes a rest call to Juniper Northstar to get active LSPs # usage: python get_active_LSPs.py import json import requests from requests.auth import HTTPBasicAuth from pprint import pprint import yaml from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) def get_token(): url = 'https://' + my_variables_in_yaml['northstar']['ip'] + ':8443/oauth2/token' data_to_get_token = {"grant_type":"password","username":authuser,"password":<PASSWORD>} r = requests.post(url, data=json.dumps(data_to_get_token), auth=(authuser, authpwd), headers=headers, verify=False) return str('Bearer ' + r.json()['access_token']) def import_variables_from_file(): my_variables_file=open('variables.yml', 'r') my_variables_in_string=my_variables_file.read() my_variables_in_yaml=yaml.load(my_variables_in_string) my_variables_file.close() return my_variables_in_yaml my_variables_in_yaml=import_variables_from_file() authuser = my_variables_in_yaml['northstar']['username'] authpwd = my_variables_in_yaml['northstar']['password'] url_base = 'http://' + my_variables_in_yaml['northstar']['ip'] + ':8091/NorthStar/API/v2/tenant/' url = url_base + '1/topology/1/te-lsps' headers = { 'Accept': 'application/json' } headers = { 'Content-type': 'application/json' } # r = requests.get(url, headers=headers, auth=(authuser, authpwd)) get_token() headers = {'Authorization':get_token(), 'Accept' : 'application/json', 'Content-Type' : 'application/json'} r = requests.get(url, headers=headers, verify=False) # type(r.json()) # pprint(r.json()) # This gives the names of all the LSPs that are active for item in r.json(): if item['operationalStatus'] == 'Active': print "This LSP is active: " + item['name']
2.625
3
bindings/python/tests/cdef_types.py
mewbak/dragonffi
0
4779
# Copyright 2018 <NAME> <<EMAIL>> # # 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. # RUN: "%python" "%s" # import pydffi import sys F = pydffi.FFI() CU = F.cdef(''' #include <stdint.h> typedef int32_t MyInt; typedef struct { int a; int b; } A; ''') assert(CU.types.MyInt == F.Int32Ty) assert(isinstance(CU.types.A, pydffi.StructType))
2.25
2
hierarchical_foresight/env/environment.py
deepneuralmachine/google-research
23,901
4780
<gh_stars>1000+ # coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Environment wrapper around the maze navigation environment. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy from . import simple_maze import cv2 import numpy as np class Environment(object): """Wrapper around the Simple maze environment.""" def __init__(self, difficulty=None): """Initialize the environment with the specified difficulty.""" self.difficulty = difficulty self._sim_env = simple_maze.navigate(difficulty=difficulty) self.stepcount = 0 def reset(self): """Resets the environment.""" self.stepcount = 0 time_step = self._sim_env.reset() return time_step def get_goal_im(self): """Computes and returns the goal image.""" currp = copy.deepcopy(self._sim_env.physics.data.qpos[:]) currv = copy.deepcopy(self._sim_env.physics.data.qvel[:]) self._sim_env.task.dontreset = True tg = copy.deepcopy(self._sim_env.physics.named.data.geom_xpos['target'][:2]) self._sim_env.physics.data.qpos[:] = tg self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) self._sim_env.physics.data.qpos[:] = tg self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() self._sim_env.physics.data.qpos[:] = currp self._sim_env.physics.data.qvel[:] = currv self.step([0, 0]) self._sim_env.task.dontreset = False return gim def get_subgoal_ims(self, numg): """Computes and returs the ground truth sub goal images.""" currp = copy.deepcopy(self._sim_env.physics.data.qpos[:]) currv = copy.deepcopy(self._sim_env.physics.data.qvel[:]) self._sim_env.task.dontreset = True tg = copy.deepcopy(self._sim_env.physics.named.data.geom_xpos['target'][:2]) sg = [] if self.difficulty == 'e': if numg == 1: self._sim_env.physics.data.qpos[:] = currp + (tg - currp) / 2 self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() sg.append(gim) elif numg == 2: self._sim_env.physics.data.qpos[:] = currp + (tg - currp) / 3 self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() sg.append(gim) self._sim_env.physics.data.qpos[:] = currp + 2 * (tg - currp) / 3 self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() sg.append(gim) elif self.difficulty == 'm': if numg == 1: self._sim_env.physics.data.qpos[:] = [ self._sim_env.physics.named.model.geom_pos['wall2A', 'x'], self._sim_env.physics.named.model.geom_pos['wall2A', 'y'] - 0.25] self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() sg.append(gim) elif numg == 2: self._sim_env.physics.data.qpos[:] = [ self._sim_env.physics.named.model.geom_pos['wall2A', 'x'], self._sim_env.physics.named.model.geom_pos['wall2A', 'y'] - 0.25] self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() sg.append(gim) self._sim_env.physics.data.qpos[:] = [ self._sim_env.physics.named.model.geom_pos['wall2A', 'x'], self._sim_env.physics.named.model.geom_pos['wall2A', 'y'] - 0.25] self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() sg.append(gim) elif self.difficulty == 'h': if numg == 1: self._sim_env.physics.data.qpos[:] = [ self._sim_env.physics.named.model.geom_pos['wall1A', 'x'], self._sim_env.physics.named.model.geom_pos['wall1A', 'y'] - 0.25] self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() sg.append(gim) elif numg == 2: self._sim_env.physics.data.qpos[:] = [ self._sim_env.physics.named.model.geom_pos['wall1A', 'x'], self._sim_env.physics.named.model.geom_pos['wall1A', 'y'] - 0.25] self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() sg.append(gim) self._sim_env.physics.data.qpos[:] = [ self._sim_env.physics.named.model.geom_pos['wall2A', 'x'], self._sim_env.physics.named.model.geom_pos['wall2A', 'y'] - 0.25] self._sim_env.physics.data.qvel[:] = 0 self.step([0, 0]) _, gim = self.get_observation() sg.append(gim) sg = np.array(sg) self._sim_env.physics.data.qpos[:] = currp self._sim_env.physics.data.qvel[:] = currv self.step([0, 0]) self._sim_env.task.dontreset = False return sg def is_goal(self): """Checks if the current state is a goal state.""" return self._sim_env.task.is_goal(self._sim_env.physics) def step(self, action=None): """Steps the environment.""" time_step = self._sim_env.step(action) self._sim_env.physics.data.qvel[:] = 0 return time_step def get_observation(self): """Return image observation.""" obs = self._sim_env.task.get_observation(self._sim_env.physics) im = self._sim_env.physics.render(256, 256, camera_id='fixed') im = cv2.resize(im, (64, 64), interpolation=cv2.INTER_LANCZOS4) return obs, im
2.328125
2
trips/migrations/0004_invoice.py
chorna/taxi24
0
4781
<gh_stars>0 # Generated by Django 3.2.5 on 2021-07-11 23:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('trips', '0003_alter_trip_state'), ] operations = [ migrations.CreateModel( name='Invoice', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('serie', models.CharField(max_length=4)), ('number', models.CharField(max_length=8)), ('tax_amount', models.FloatField(default=0.0)), ('base_amount', models.FloatField()), ('trip_id', models.ForeignKey(db_column='trip_id', on_delete=django.db.models.deletion.PROTECT, to='trips.trip')), ], ), ]
1.679688
2
src/general_harvester.py
Badger-Finance/python-keepers
0
4782
<gh_stars>0 import logging import os from decimal import Decimal from time import sleep import requests from hexbytes import HexBytes from web3 import Web3 from web3 import contract from web3.contract import Contract from config.constants import BASE_CURRENCIES from config.constants import GAS_LIMITS from config.constants import MULTICHAIN_CONFIG from config.enums import Network from src.harvester import IHarvester from src.misc_utils import hours from src.misc_utils import seconds_to_blocks from src.tx_utils import get_effective_gas_price from src.tx_utils import get_gas_price_of_tx from src.tx_utils import get_priority_fee from src.web3_utils import confirm_transaction from src.utils import get_abi from src.discord_utils import get_hash_from_failed_tx_error from src.web3_utils import get_last_harvest_times from src.token_utils import get_token_price from src.discord_utils import send_error_to_discord from src.discord_utils import send_success_to_discord logging.basicConfig(level=logging.INFO) MAX_TIME_BETWEEN_HARVESTS = hours(120) HARVEST_THRESHOLD = 0.0005 # min ratio of want to total vault AUM required to harvest NUM_FLASHBOTS_BUNDLES = 6 class GeneralHarvester(IHarvester): def __init__( self, chain: Network = Network.Ethereum, web3: Web3 = None, keeper_acl: str = os.getenv("KEEPER_ACL"), keeper_address: str = os.getenv("KEEPER_ADDRESS"), keeper_key: str = os.getenv("KEEPER_KEY"), base_oracle_address: str = os.getenv("ETH_USD_CHAINLINK"), use_flashbots: bool = False, discord_url: str = None, ): self.logger = logging.getLogger(__name__) self.chain = chain self.web3 = web3 self.keeper_key = keeper_key self.keeper_address = keeper_address self.keeper_acl: Contract = self.web3.eth.contract( address=self.web3.toChecksumAddress(keeper_acl), abi=get_abi(self.chain, "keeper_acl"), ) self.base_usd_oracle: Contract = self.web3.eth.contract( address=self.web3.toChecksumAddress(base_oracle_address), abi=get_abi(self.chain, "oracle"), ) # Times of last harvest if self.chain in [Network.Ethereum, Network.Fantom]: self.last_harvest_times = get_last_harvest_times( self.web3, self.keeper_acl, start_block=self.web3.eth.block_number - seconds_to_blocks(MAX_TIME_BETWEEN_HARVESTS), chain=self.chain, ) else: # Don't care about poly/arbitrum self.last_harvest_times = {} self.use_flashbots = use_flashbots self.discord_url = discord_url def is_time_to_harvest( self, strategy: contract.Contract, harvest_interval_threshold: int = MAX_TIME_BETWEEN_HARVESTS, ) -> bool: """Calculates the time between harvests for the supplied strategy and returns true if it has been longer than the supplied harvest_interval_threshold which is measured in seconds Args: strategy (contract): Vault strategy web3 contract object harvest_interval_threshold (int, optional): Amount of time in seconds that is acceptable to not have harvested within. Defaults to MAX_TIME_BETWEEN_HARVESTS. Returns: bool: True if time since last harvest is > harvest_interval_threshold, else False """ # Only care about harvest gas costs on eth if self.chain not in [Network.Ethereum, Network.Fantom]: return True try: last_harvest = self.last_harvest_times[strategy.address] current_time = self.web3.eth.get_block("latest")["timestamp"] self.logger.info( f"Time since last harvest: {(current_time - last_harvest) / 3600}" ) return current_time - last_harvest > harvest_interval_threshold except KeyError: return True def harvest( self, strategy: contract.Contract, ): """Orchestration function that harvests outstanding rewards. Args: strategy (contract) Raises: ValueError: If the keeper isn't whitelisted, throw an error and alert user. """ strategy_name = strategy.functions.getName().call() # TODO: update for ACL if not self.__is_keeper_whitelisted("harvest"): raise ValueError("Keeper ACL is not whitelisted for calling harvest") want_address = strategy.functions.want().call() want = self.web3.eth.contract( address=want_address, abi=get_abi(self.chain, "erc20"), ) vault_balance = want.functions.balanceOf(strategy.address).call() self.logger.info(f"vault balance: {vault_balance}") want_to_harvest = ( self.estimate_harvest_amount(strategy) / 10 ** want.functions.decimals().call() ) self.logger.info(f"estimated want change: {want_to_harvest}") # TODO: figure out how to handle profit estimation # current_price_eth = self.get_current_rewards_price() # self.logger.info(f"current rewards price per token (ETH): {current_price_eth}") gas_fee = self.estimate_gas_fee(strategy.address) self.logger.info(f"estimated gas cost: {gas_fee}") # for now we'll just harvest every hour should_harvest = self.is_profitable() self.logger.info(f"Should we harvest: {should_harvest}") if should_harvest: self.__process_harvest( strategy=strategy, strategy_name=strategy_name, ) def harvest_no_return( self, strategy: contract, ): strategy_name = strategy.functions.getName().call() # TODO: update for ACL if not self.__is_keeper_whitelisted("harvestNoReturn"): raise ValueError( "Keeper ACL is not whitelisted for calling harvestNoReturn" ) want_address = strategy.functions.want().call() want = self.web3.eth.contract( address=want_address, abi=get_abi(self.chain, "erc20"), ) vault_balance = want.functions.balanceOf(strategy.address).call() self.logger.info(f"vault balance: {vault_balance}") # TODO: figure out how to handle profit estimation # current_price_eth = self.get_current_rewards_price() # self.logger.info(f"current rewards price per token (ETH): {current_price_eth}") gas_fee = self.estimate_gas_fee(strategy.address, returns=False) self.logger.info(f"estimated gas cost: {gas_fee}") # for now we'll just harvest every hour should_harvest = self.is_profitable() self.logger.info(f"Should we harvest: {should_harvest}") if should_harvest: self.__process_harvest( strategy=strategy, strategy_name=strategy_name, ) def harvest_rewards_manager( self, strategy: contract, ): strategy_name = strategy.functions.getName().call() self.keeper_acl = self.web3.eth.contract( address=self.web3.toChecksumAddress( MULTICHAIN_CONFIG[self.chain]["rewards_manager"] ), abi=get_abi(self.chain, "rewards_manager"), ) if not self.__is_keeper_whitelisted("rewards_manager"): raise ValueError(f"Keeper is not whitelisted for {strategy_name}") want_address = strategy.functions.want().call() want = self.web3.eth.contract( address=want_address, abi=get_abi(self.chain, "erc20"), ) vault_balance = want.functions.balanceOf(strategy.address).call() self.logger.info(f"vault balance: {vault_balance}") gas_fee = self.estimate_gas_fee(strategy.address) self.logger.info(f"estimated gas cost: {gas_fee}") self.__process_harvest( strategy=strategy, strategy_name=strategy_name, ) def harvest_mta( self, voter_proxy: contract, ): # TODO: update for ACL if not self.__is_keeper_whitelisted("harvestMta"): raise ValueError("Keeper ACL is not whitelisted for calling harvestMta") gas_fee = self.estimate_gas_fee(voter_proxy.address, function="harvestMta") self.logger.info(f"estimated gas cost: {gas_fee}") should_harvest_mta = self.is_profitable() self.logger.info(f"Should we call harvestMta: {should_harvest_mta}") if should_harvest_mta: self.__process_harvest_mta(voter_proxy) def tend(self, strategy: contract): strategy_name = strategy.functions.getName().call() # TODO: update for ACL if not self.__is_keeper_whitelisted("tend"): raise ValueError("Keeper ACL is not whitelisted for calling tend") # TODO: figure out how to handle profit estimation # current_price_eth = self.get_current_rewards_price() # self.logger.info(f"current rewards price per token (ETH): {current_price_eth}") gas_fee = self.estimate_gas_fee(strategy.address, function="tend") self.logger.info(f"estimated gas cost: {gas_fee}") self.__process_tend( strategy=strategy, strategy_name=strategy_name, ) def tend_then_harvest(self, strategy: contract): self.tend(strategy) sleep(60) self.harvest(strategy) def estimate_harvest_amount(self, strategy: contract) -> Decimal: want = self.web3.eth.contract( address=strategy.functions.want().call(), abi=get_abi(self.chain, "erc20"), ) want_gained = self.keeper_acl.functions.harvest(strategy.address).call( {"from": self.keeper_address} ) # call badger api to get prices currency = BASE_CURRENCIES[self.chain] if self.chain == Network.Fantom: price_per_want = get_token_price( want.address, currency, self.chain, use_staging=True ) else: price_per_want = get_token_price(want.address, currency, self.chain) self.logger.info(f"price per want: {price_per_want} {currency}") self.logger.info(f"want gained: {want_gained}") if type(want_gained) is list: want_gained = 0 return price_per_want * want_gained def is_profitable(self) -> bool: # TODO: Implement this # harvest if ideal want change is > 0.05% of total vault assets # should_harvest = want_to_harvest / vault_balance >= HARVEST_THRESHOLD return True def __is_keeper_whitelisted(self, function: str) -> bool: """Checks if the bot we're using is whitelisted for the strategy. Returns: bool: True if our bot is whitelisted to make function calls, False otherwise. """ if function in ["harvest", "harvestMta"]: key = self.keeper_acl.functions.HARVESTER_ROLE().call() elif function == "tend": key = self.keeper_acl.functions.TENDER_ROLE().call() elif function == "rewards_manager": key = self.keeper_acl.functions.KEEPER_ROLE().call() return self.keeper_acl.functions.hasRole(key, self.keeper_address).call() def __process_tend( self, strategy: contract = None, strategy_name: str = None, ): try: tx_hash = self.__send_tend_tx(strategy) succeeded, _ = confirm_transaction(self.web3, tx_hash) if succeeded: gas_price_of_tx = get_gas_price_of_tx( self.web3, self.base_usd_oracle, tx_hash, self.chain ) self.logger.info(f"got gas price of tx: {gas_price_of_tx}") send_success_to_discord( tx_type=f"Tend {strategy_name}", tx_hash=tx_hash, gas_cost=gas_price_of_tx, chain=self.chain, url=self.discord_url, ) elif tx_hash != HexBytes(0): send_success_to_discord( tx_type=f"Tend {strategy_name}", tx_hash=tx_hash, chain=self.chain, url=self.discord_url, ) except Exception as e: self.logger.error(f"Error processing tend tx: {e}") send_error_to_discord( strategy_name, "Tend", error=e, chain=self.chain, keeper_address=self.keeper_address, ) def __process_harvest( self, strategy: contract = None, strategy_name: str = None, harvested: Decimal = None, returns: bool = True, ): """Private function to create, broadcast, confirm tx on eth and then send transaction to Discord for monitoring Args: strategy (contract, optional): Defaults to None. strategy_name (str, optional): Defaults to None. harvested (Decimal, optional): Amount of Sushi harvested. Defaults to None. """ try: tx_hash, max_target_block = self.__send_harvest_tx( strategy, returns=returns ) succeeded, msg = confirm_transaction( self.web3, tx_hash, max_block=max_target_block ) if succeeded: # If successful, update last harvest harvest # time to make sure we don't double harvest self.update_last_harvest_time(strategy.address) gas_price_of_tx = get_gas_price_of_tx( self.web3, self.base_usd_oracle, tx_hash, self.chain ) self.logger.info(f"got gas price of tx: {gas_price_of_tx}") send_success_to_discord( tx_type=f"Harvest {strategy_name}", tx_hash=tx_hash, gas_cost=gas_price_of_tx, chain=self.chain, url=self.discord_url, ) elif tx_hash != HexBytes(0): if not self.use_flashbots: # And if pending self.update_last_harvest_time(strategy.address) send_success_to_discord( tx_type=f"Harvest {strategy_name}", tx_hash=tx_hash, chain=self.chain, url=self.discord_url, ) else: send_error_to_discord( strategy_name, "Harvest", tx_hash=tx_hash, message=msg, chain=self.chain, keeper_address=self.keeper_address, ) except Exception as e: self.logger.error(f"Error processing harvest tx: {e}") send_error_to_discord( strategy_name, "Harvest", error=e, chain=self.chain, keeper_address=self.keeper_address, ) def __process_harvest_mta( self, voter_proxy: contract, ): """Private function to create, broadcast, confirm tx on eth and then send transaction to Discord for monitoring Args: voter_proxy (contract): Mstable voter proxy contract """ try: tx_hash = self.__send_harvest_mta_tx(voter_proxy) succeeded, _ = confirm_transaction(self.web3, tx_hash) if succeeded: # If successful, update last harvest harvest time self.update_last_harvest_time(voter_proxy.address) gas_price_of_tx = get_gas_price_of_tx( self.web3, self.base_usd_oracle, tx_hash, self.chain ) self.logger.info(f"got gas price of tx: {gas_price_of_tx}") send_success_to_discord( tx_type="Harvest MTA", tx_hash=tx_hash, gas_cost=gas_price_of_tx, chain=self.chain, url=self.discord_url, ) elif tx_hash != HexBytes(0): send_success_to_discord( tx_type="Harvest MTA", tx_hash=tx_hash, chain=self.chain, url=self.discord_url, ) except Exception as e: self.logger.error(f"Error processing harvestMta tx: {e}") send_error_to_discord( "", "Harvest MTA", error=e, chain=self.chain, keeper_address=self.keeper_address, ) def __send_harvest_tx(self, strategy: contract, returns: bool = True) -> HexBytes: """Sends transaction to ETH node for confirmation. Args: strategy (contract) Raises: Exception: If we have an issue sending transaction (unable to communicate with node, etc.) we log the error and return a tx_hash of 0x00. Returns: HexBytes: Transaction hash for transaction that was sent. """ max_target_block = None tx_hash = HexBytes(0) try: tx = self.__build_transaction(strategy.address, returns=returns) signed_tx = self.web3.eth.account.sign_transaction( tx, private_key=self.keeper_key ) tx_hash = signed_tx.hash if not self.use_flashbots: self.web3.eth.send_raw_transaction(signed_tx.rawTransaction) else: bundle = [ {"signed_transaction": signed_tx.rawTransaction}, ] block_number = self.web3.eth.block_number for i in range(1, NUM_FLASHBOTS_BUNDLES + 1): self.web3.flashbots.send_bundle( bundle, target_block_number=block_number + i ) max_target_block = block_number + NUM_FLASHBOTS_BUNDLES self.logger.info(f"Bundle broadcasted at {max_target_block}") except ValueError as e: self.logger.error(f"Error in sending harvest tx: {e}") tx_hash = get_hash_from_failed_tx_error( e, "Harvest", chain=self.chain, keeper_address=self.keeper_address ) finally: return tx_hash, max_target_block def __send_tend_tx(self, strategy: contract) -> HexBytes: """Sends transaction to ETH node for confirmation. Args: strategy (contract) Raises: Exception: If we have an issue sending transaction (unable to communicate with node, etc.) we log the error and return a tx_hash of 0x00. Returns: HexBytes: Transaction hash for transaction that was sent. """ tx_hash = HexBytes(0) try: tx = self.__build_transaction(strategy.address, function="tend") signed_tx = self.web3.eth.account.sign_transaction( tx, private_key=self.keeper_key ) tx_hash = signed_tx.hash self.web3.eth.send_raw_transaction(signed_tx.rawTransaction) except ValueError as e: self.logger.error(f"Error in sending tend tx: {e}") tx_hash = get_hash_from_failed_tx_error( e, "Tend", chain=self.chain, keeper_address=self.keeper_address ) finally: return tx_hash def __send_harvest_mta_tx(self, voter_proxy: contract) -> HexBytes: """Sends transaction to ETH node for confirmation. Args: voter_proxy (contract) Raises: Exception: If we have an issue sending transaction (unable to communicate with node, etc.) we log the error and return a tx_hash of 0x00. Returns: HexBytes: Transaction hash for transaction that was sent. """ tx_hash = HexBytes(0) try: tx = self.__build_transaction(voter_proxy.address, function="harvestMta") signed_tx = self.web3.eth.account.sign_transaction( tx, private_key=self.keeper_key ) tx_hash = signed_tx.hash self.web3.eth.send_raw_transaction(signed_tx.rawTransaction) except ValueError as e: self.logger.error(f"Error in sending harvestMta tx: {e}") tx_hash = get_hash_from_failed_tx_error( e, "Harvest MTA", chain=self.chain, keeper_address=self.keeper_address ) finally: return tx_hash def __build_transaction( self, address: str, returns: bool = True, function: str = "harvest" ) -> dict: """Builds transaction depending on which chain we're harvesting. EIP-1559 requires different handling for ETH txs than the other EVM chains. Args: contract (contract): contract to use to build harvest tx Returns: dict: tx dictionary """ options = { "nonce": self.web3.eth.get_transaction_count( self.keeper_address, "pending" ), "from": self.keeper_address, "gas": GAS_LIMITS[self.chain], } if self.chain == Network.Ethereum: options["maxPriorityFeePerGas"] = get_priority_fee(self.web3) options["maxFeePerGas"] = self.__get_effective_gas_price() else: options["gasPrice"] = self.__get_effective_gas_price() if function == "harvest": self.logger.info( f"estimated gas fee: {self.__estimate_harvest_gas(address, returns)}" ) return self.__build_harvest_transaction(address, returns, options) elif function == "tend": self.logger.info(f"estimated gas fee: {self.__estimate_tend_gas(address)}") return self.__build_tend_transaction(address, options) elif function == "harvestMta": self.logger.info( f"estimated gas fee: {self.__estimate_harvest_mta_gas(address)}" ) return self.__build_harvest_mta_transaction(address, options) def __build_harvest_transaction( self, strategy_address: str, returns: bool, options: dict ) -> dict: if returns: return self.keeper_acl.functions.harvest(strategy_address).buildTransaction( options ) else: return self.keeper_acl.functions.harvestNoReturn( strategy_address ).buildTransaction(options) def __build_tend_transaction(self, strategy_address: str, options: dict) -> dict: return self.keeper_acl.functions.tend(strategy_address).buildTransaction( options ) def __build_harvest_mta_transaction( self, voter_proxy_address: str, options: dict ) -> dict: return self.keeper_acl.functions.harvestMta( voter_proxy_address ).buildTransaction(options) def estimate_gas_fee( self, address: str, returns: bool = True, function: str = "harvest" ) -> Decimal: current_gas_price = self.__get_effective_gas_price() if function == "harvest": estimated_gas = self.__estimate_harvest_gas(address, returns) elif function == "tend": estimated_gas = self.__estimate_tend_gas(address) elif function == "harvestMta": estimated_gas = self.__estimate_harvest_mta_gas(address) return Decimal(current_gas_price * estimated_gas) def __estimate_harvest_gas(self, strategy_address: str, returns: bool) -> Decimal: if returns: estimated_gas_to_harvest = self.keeper_acl.functions.harvest( strategy_address ).estimateGas({"from": self.keeper_address}) else: estimated_gas_to_harvest = self.keeper_acl.functions.harvestNoReturn( strategy_address ).estimateGas({"from": self.keeper_address}) return Decimal(estimated_gas_to_harvest) def __estimate_tend_gas(self, strategy_address: str) -> Decimal: return Decimal( self.keeper_acl.functions.tend(strategy_address).estimateGas( {"from": self.keeper_address} ) ) def __estimate_harvest_mta_gas(self, voter_proxy_address: str) -> Decimal: return Decimal( self.keeper_acl.functions.harvestMta(voter_proxy_address).estimateGas( {"from": self.keeper_address} ) ) def __get_effective_gas_price(self) -> int: if self.chain == Network.Polygon: response = requests.get("https://gasstation-mainnet.matic.network").json() gas_price = self.web3.toWei(int(response.get("fast") * 1.1), "gwei") elif self.chain in [Network.Arbitrum, Network.Fantom]: gas_price = int(1.1 * self.web3.eth.gas_price) # Estimated gas price + buffer elif self.chain == Network.Ethereum: # EIP-1559 gas_price = get_effective_gas_price(self.web3) return gas_price def update_last_harvest_time(self, strategy_address: str): self.last_harvest_times[strategy_address] = self.web3.eth.get_block("latest")[ "timestamp" ]
1.828125
2
clickhouse_plantuml/column.py
yonesko/clickhouse-plantuml
0
4783
<reponame>yonesko/clickhouse-plantuml #!/usr/bin/env python # License: Apache-2.0 # Copyright (C) 2020 <NAME> class Column(object): """ Represents ClickHouse column """ def __init__( self, database: str, table: str, name: str, type: str, default_kind: str, default_expression: str, comment: str, compression_codec: str, is_in_partition_key: bool, is_in_sorting_key: bool, is_in_primary_key: bool, is_in_sampling_key: bool, ): self.database = database self.table = table self.name = name self.type = type self.default_kind = default_kind self.default_expression = default_expression self.comment = comment self.compression_codec = compression_codec self.is_in_partition_key = is_in_partition_key self.is_in_sorting_key = is_in_sorting_key self.is_in_primary_key = is_in_primary_key self.is_in_sampling_key = is_in_sampling_key @property def db_table(self): return "{}.{}".format(self.database, self.table) def __str__(self): return self.name
2.4375
2
contrib/micronet/scripts/file2buf.py
pmalhaire/WireHub
337
4784
<reponame>pmalhaire/WireHub #!/usr/bin/env python3 import os import sys MAX = 8 fpath = sys.argv[1] name = sys.argv[2] with open(fpath, "rb") as fh: sys.stdout.write("char %s[] = {" % (name,) ) i = 0 while True: if i > 0: sys.stdout.write(", ") if i % MAX == 0: sys.stdout.write("\n\t") c = fh.read(1) if not c: sys.stdout.write("\n") break sys.stdout.write("0x%.2x" % (ord(c), )) i = i + 1 print("};") print("") print("unsigned int %s_sz = %s;" % (name, i)) print("")
2.4375
2
tests/test_observable/test_skip.py
christiansandberg/RxPY
0
4785
<reponame>christiansandberg/RxPY import unittest from reactivex import operators as ops from reactivex.testing import ReactiveTest, TestScheduler on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = ReactiveTest.subscribed disposed = ReactiveTest.disposed created = ReactiveTest.created class TestSkip(unittest.TestCase): def test_skip_complete_after(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(70, 6), on_next(150, 4), on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_completed(690), ) def create(): return xs.pipe(ops.skip(20)) results = scheduler.start(create) assert results.messages == [on_completed(690)] assert xs.subscriptions == [subscribe(200, 690)] def test_skip_complete_same(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(70, 6), on_next(150, 4), on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_completed(690), ) def create(): return xs.pipe(ops.skip(17)) results = scheduler.start(create) assert results.messages == [on_completed(690)] assert xs.subscriptions == [subscribe(200, 690)] def test_skip_complete_before(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(70, 6), on_next(150, 4), on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_completed(690), ) def create(): return xs.pipe(ops.skip(10)) results = scheduler.start(create) assert results.messages == [ on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_completed(690), ] assert xs.subscriptions == [subscribe(200, 690)] def test_skip_Complete_zero(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(70, 6), on_next(150, 4), on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_completed(690), ) def create(): return xs.pipe(ops.skip(0)) results = scheduler.start(create) assert results.messages == [ on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_completed(690), ] assert xs.subscriptions == [subscribe(200, 690)] def test_skip_error_after(self): ex = "ex" scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(70, 6), on_next(150, 4), on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_error(690, ex), ) def create(): return xs.pipe(ops.skip(20)) results = scheduler.start(create) assert results.messages == [on_error(690, ex)] assert xs.subscriptions == [subscribe(200, 690)] def test_skip_error_same(self): ex = "ex" scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(70, 6), on_next(150, 4), on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_error(690, ex), ) def create(): return xs.pipe(ops.skip(17)) results = scheduler.start(create) assert results.messages == [on_error(690, ex)] assert xs.subscriptions == [subscribe(200, 690)] def test_skip_error_before(self): ex = "ex" scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(70, 6), on_next(150, 4), on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_error(690, ex), ) def create(): return xs.pipe(ops.skip(3)) results = scheduler.start(create) assert results.messages == [ on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), on_error(690, ex), ] assert xs.subscriptions == [subscribe(200, 690)] def test_skip_dispose_before(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(70, 6), on_next(150, 4), on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), ) def create(): return xs.pipe(ops.skip(3)) results = scheduler.start(create, disposed=250) assert results.messages == [] assert xs.subscriptions == [subscribe(200, 250)] def test_skip_dispose_after(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(70, 6), on_next(150, 4), on_next(210, 9), on_next(230, 13), on_next(270, 7), on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), on_next(410, 15), on_next(415, 16), on_next(460, 72), on_next(510, 76), on_next(560, 32), on_next(570, -100), on_next(580, -3), on_next(590, 5), on_next(630, 10), ) def create(): return xs.pipe(ops.skip(3)) results = scheduler.start(create, disposed=400) assert results.messages == [ on_next(280, 1), on_next(300, -1), on_next(310, 3), on_next(340, 8), on_next(370, 11), ] assert xs.subscriptions == [subscribe(200, 400)] if __name__ == "__main__": unittest.main()
2.609375
3
CF#691/python/A.py
chaitanya1243/CP
0
4786
def solve(n, red , blue): rcount = bcount = 0 for i in range(n): if int(red[i]) > int(blue[i]): rcount = rcount +1 elif int(red[i]) < int(blue[i]): bcount = bcount + 1 print( 'RED' if rcount>bcount else ('BLUE' if bcount>rcount else 'EQUAL')) if __name__ == "__main__": T = int(input()) for t in range(T): n = int(input()) red = input() blue = input() solve(n, red, blue)
3.359375
3
shudder/__main__.py
fitpay/shudder
0
4787
# Copyright 2014 Scopely, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Start polling of SQS and metadata.""" import shudder.queue as queue import shudder.metadata as metadata from shudder.config import CONFIG import time import os import requests import signal import subprocess import sys if __name__ == '__main__': sqs_connection, sqs_queue = queue.create_queue() sns_connection, subscription_arn = queue.subscribe_sns(sqs_queue) def receive_signal(signum, stack): if signum in [1, 2, 3, 15]: print 'Caught signal %s, exiting.' % (str(signum)) queue.clean_up_sns(sns_connection, subscription_arn, sqs_queue) sys.exit() else: print 'Caught signal %s, ignoring.' % (str(signum)) uncatchable = ['SIG_DFL','SIGSTOP','SIGKILL'] for i in [x for x in dir(signal) if x.startswith("SIG")]: if not i in uncatchable: signum = getattr(signal,i) signal.signal(signum, receive_signal) while True: message = queue.poll_queue(sqs_connection, sqs_queue) if message or metadata.poll_instance_metadata(): queue.clean_up_sns(sns_connection, subscription_arn, sqs_queue) if 'endpoint' in CONFIG: requests.get(CONFIG["endpoint"]) if 'endpoints' in CONFIG: for endpoint in CONFIG["endpoints"]: requests.get(endpoint) if 'commands' in CONFIG: for command in CONFIG["commands"]: print 'Running command: %s' % command process = subprocess.Popen(command) while process.poll() is None: time.sleep(30) """Send a heart beat to aws""" queue.record_lifecycle_action_heartbeat(message) """Send a complete lifecycle action""" queue.complete_lifecycle_action(message) sys.exit(0) time.sleep(5)
2.03125
2
example/hydrogen.py
NLESC-JCER/pyCHAMP
4
4788
import autograd.numpy as np from pyCHAMP.wavefunction.wf_base import WF from pyCHAMP.optimizer.minimize import Minimize from pyCHAMP.sampler.metropolis import Metropolis from pyCHAMP.sampler.hamiltonian import Hamiltonian from pyCHAMP.solver.vmc import VMC class Hydrogen(WF): def __init__(self, nelec, ndim): WF.__init__(self, nelec, ndim) def values(self, parameters, pos): """ Compute the value of the wave function. Args: parameters : parameters of th wf x: position of the electron Returns: values of psi """ beta = parameters[0] if pos.ndim == 1: pos = pos.reshape(1, -1) r = np.sqrt(np.sum(pos**2, 1)) return 2*np.exp(-beta*r).reshape(-1, 1) def nuclear_potential(self, pos): r = np.sqrt(np.sum(pos**2, 1)) rm1 = - 1. / r return rm1.reshape(-1, 1) def electronic_potential(self, pos): return 0 if __name__ == "__main__": wf = Hydrogen(nelec=1, ndim=3) sampler = Metropolis(nwalkers=1000, nstep=1000, step_size=3, nelec=1, ndim=3, domain={'min': -5, 'max': 5}) sampler = Hamiltonian(nwalkers=1000, nstep=1000, step_size=3, nelec=1, ndim=3) optimizer = Minimize(method='bfgs', maxiter=25, tol=1E-4) # VMS solver vmc = VMC(wf=wf, sampler=sampler, optimizer=optimizer) # single point opt_param = [1.] pos, e, s = vmc.single_point(opt_param) print('Energy : ', e) print('Variance : ', s) vmc.plot_density(pos) # optimization init_param = [0.5] vmc.optimize(init_param) vmc.plot_history()
2.421875
2
braintree/account_updater_daily_report.py
futureironman/braintree_python
182
4789
from braintree.configuration import Configuration from braintree.resource import Resource class AccountUpdaterDailyReport(Resource): def __init__(self, gateway, attributes): Resource.__init__(self, gateway, attributes) if "report_url" in attributes: self.report_url = attributes.pop("report_url") if "report_date" in attributes: self.report_date = attributes.pop("report_date") def __repr__(self): detail_list = ["report_url", "report_date"] return super(AccountUpdaterDailyReport, self).__repr__(detail_list)
2.3125
2
game/ball.py
geoncic/PyBlock
0
4790
import pygame import pygame.gfxdraw from constants import Constants class Balls(object): def __init__(self, all_sprites, all_balls): self.all_sprites = all_sprites self.all_balls = all_balls def spawn_ball(self, pos, vel, team): # Todo: Figure out how to spawn multiple balls with some sort of delay ball = Ball(pos, vel, team) self.all_sprites.add(ball) self.all_balls.add(ball) def ball_test(self): print("This is a Ball Test!") print(self) def update(self): print(self.__dict__) print(type(self)) class Ball(pygame.sprite.Sprite): def __init__(self, pos, vel, team): super().__init__() self.color = team self.file = Constants.BALL_TEAMS[self.color] self.rad = int(Constants.BALL_SIZE/2) self.image = pygame.Surface([Constants.BALL_SIZE, Constants.BALL_SIZE], pygame.SRCALPHA) pygame.draw.circle(self.image, self.file, (self.rad, self.rad), self.rad) self.x_pos = pos[0] self.y_pos = pos[1] self.rect = self.image.get_rect(center=(self.x_pos, self.y_pos)) self.dx = vel[0] self.dy = vel[1] def update(self): self.check_boundary() self.x_pos += self.dx self.y_pos += self.dy self.rect.center = [self.x_pos, self.y_pos] # self.rect.center = pygame.mouse.get_pos() # has sprite follow the mouse def check_boundary(self): if not Constants.PLAYER_WIDTH <= self.x_pos <= (Constants.PLAYER_WIDTH+Constants.BOARD_WIDTH): self.dx = -1*self.dx if not 0 <= self.y_pos <= Constants.SCREEN_HEIGHT: self.dy = -1*self.dy
3.09375
3
program/eggUI.py
otills/embryocv
1
4791
<gh_stars>1-10 from pyqtgraph.Qt import QtCore, QtGui import numpy as np from scipy.spatial import distance as dist import glob import re import os from PyQt5 import QtGui from PyQt5.QtCore import * from PyQt5.QtGui import * import sys import cv2 import pandas as pd from PyQt5.Qt import * import pyqtgraph as pg #from PyQt4.Qt import * #%% class eggUI(QDialog): ''' createOpenCVEggROI : take eggID defined ROIs and visualise ''' sliderUpdate = QtCore.pyqtSignal() embryoUpdate = QtCore.pyqtSignal() keyPressed = QtCore.pyqtSignal() def __init__(self, parent=None): super(eggUI, self).__init__(parent) # Make QDialog self.diag = QtGui.QDialog() global parentPath, vidTime self.diag.setWindowTitle('Identify eggs') self.diag.imv = pg.ImageView() self.btn_save = QPushButton('Save', self) #============================================================================== # #============================================================================== def showUI(self,ims,eggRotBBox, eggBoxPoints, embryoLabels, eggInt): self.eggInt = eggInt self.embryoLabels = embryoLabels self.diag.setWindowTitle('Identify eggs') # Make ImageView self.diag.imv = pg.ImageView() self.diag.resize(1000,600) # Make ROI self.importOpenCVROIs(eggRotBBox, eggBoxPoints) if (eggRotBBox[0][0][0] != 'nan'): self.createOpenCVEggROI() self.diag.imv.addItem(self.roi) # Remove buttons from ImageView widget self.diag.imv.ui.roiBtn.hide() self.diag.imv.ui.menuBtn.hide() # Make tableview self.diag.table = QtGui.QTableWidget() self.diag.table.setShowGrid(True) self.diag.table.setHorizontalHeaderLabels(['Embryo', 'Sorted']) # Sets different alignment data just on the first column self.diag.table.setRowCount(int(len(self.embryoLabels))) self.diag.table.setColumnCount(2) # Highlight first row self.diag.table.selectRow(0) # Make layout checkLayout = QGridLayout() # Deal with stretching for approrpraite formatting. checkLayout.setColumnStretch(0, 3) checkLayout.setColumnStretch(1, 1) checkLayout.setRowStretch(0, 1) checkLayout.setRowStretch(1, 3) # Add to layout checkLayout.addWidget(self.diag.imv,0,0,2,2) checkLayout.addWidget(self.diag.table,1,5) # Apply layout self.diag.setLayout(checkLayout) # Make buttons self.cpROI_btn = QtGui.QPushButton('&Copy ROI') self.cpROI_btn.setMinimumHeight(40); self.useCpROI_btn = QtGui.QPushButton('&Use Copied ROI') self.useCpROI_btn.setMinimumHeight(40); self.noEgg_btn = QtGui.QPushButton('&No Egg') self.noEgg_btn.setMinimumHeight(40); self.approveROI_btn = QtGui.QPushButton('&Approve ROIs') self.approveROI_btn.setMinimumHeight(40); self.exit_btn = QtGui.QPushButton('Exit') self.exit_btn.setMinimumHeight(40); # Make button layout self.btnLayout = QGridLayout() self.btnLayout.addWidget(self.cpROI_btn,0,0) self.btnLayout.addWidget(self.useCpROI_btn,0,1) self.btnLayout.addWidget(self.noEgg_btn,1,1) self.btnLayout.addWidget(self.approveROI_btn,1,0) # Exit button not implemented, just use window x (topRight). # self.btnLayout.addWidget(self.exit_btn,2,1) # Add button layout to GridLayout. checkLayout.addLayout(self.btnLayout,0,5) # Format images for pyqtgraph and put in ImageView # self.formatSequence(ims) self.imImport() self.diag.imv.setImage(self.compSeq) # Add the ROI to ImageItem self.diag.show() # Call function to add data self.dataForTable() # Function for modifying the table when ROI is approved. self.approveROI_btn.clicked.connect(self.updateTable) # Copy current ROI self.cpROI_btn.clicked.connect(self.cpROI) # Apply copied ROI self.useCpROI_btn.clicked.connect(self.applyCopiedROI) # Assign nan to frames not containing egg self.noEgg_btn.clicked.connect(self.recordNoEgg) # Exit - prompt user to confirm #self.exit_btn.clicked.connect(self.closeEvent) # Connect changes in timeline so correct ROI is created and displayed. self.diag.imv.timeLine.sigPositionChanged.connect(self.updateOpenCVEggROICurrEmbryo) #self.diag.keyPressEvent(self.keyPressEvent) #============================================================================== # Generate data for populating the embryo/approveROI table. #============================================================================== def dataForTable(self): self.tableData = {'Embryo':list(self.embryoLabels), 'ROI approved':['No'] * len(list(self.embryoLabels))} self.tableCols = [QtGui.QColor(0,0,100,120)]* len(list(self.embryoLabels)) # Enter data onto Table horHeaders = [] for n, key in enumerate(sorted(self.tableData.keys())): horHeaders.append(key) for m, item in enumerate(self.tableData[key]): newitem = QtGui.QTableWidgetItem(item) newitem.setBackground(QtGui.QColor(0,0,100,120)) self.diag.table.setItem(m, n, newitem) # Add Header self.diag.table.setHorizontalHeaderLabels(horHeaders) # Adjust size of Table self.diag.table.resizeRowsToContents() # self.diag.table.resizeColumnsToContents() #============================================================================== # Update table when approve ROI button clicked. #============================================================================== def updateTable(self): self.tableData['ROI approved'][self.diag.table.currentRow()] = 'Approved' self.tableCols[self.diag.table.currentRow()] = QtGui.QColor(0,100,0,120) horHeaders = [] for n, key in enumerate(sorted(self.tableData.keys())): horHeaders.append(key) for m, item in enumerate(self.tableData[key]): newitem = QtGui.QTableWidgetItem(item) self.diag.table.setItem(m, n, newitem) newitem.setBackground(self.tableCols[m]) #Add Header self.diag.table.setHorizontalHeaderLabels(horHeaders) #Adjust size of Table self.diag.table.resizeRowsToContents() #============================================================================== # Update the user interface #============================================================================== def updateUI(self,ims,eggRotBBox, eggBoxPoints): self.imImport() self.diag.imv.setImage(self.compSeq) self.importOpenCVROIs(eggRotBBox, eggBoxPoints) self.getSeqValsAndCurrROI() self.updateOpenCVEggROINewEmbryo() # Add the ROI to ImageItem #self.diag.imv.addItem(self.roi) #============================================================================== # Deal with data from the dataHandling class #============================================================================== def formatSequence(self,ims): # Format seq appropriately for pyqtgraph ROIs self.tSeqd = np.zeros_like(ims) for l in range(len(self.tSeqd)): self.tSeqd[l] = ims[l].T #============================================================================== # Get folders for a particular embryo #============================================================================== def getEmbryoFolders(self, parentPath, embryo): self.parentPath = parentPath self.embryo = embryo self.embryoFolders = glob.glob(parentPath + "*/" + embryo +"/") self.embryoFolders.sort(key=os.path.getctime) #============================================================================== # Get image #============================================================================== def imImport(self): for f in range(len(self.eggUIimPaths)): im = cv2.imread(self.eggUIimPaths[f],cv2.IMREAD_ANYDEPTH) ran = (im.max()-im.min())/255. out = (im/ran) out = out-out.min() self.compSeq[int(f)] = out.astype(np.uint8) self.compSeq[f] = self.compSeq[f].T #============================================================================== # Update image iteratively when slider moved #============================================================================== #============================================================================== # def updateImage(self): # self.getSeqValsAndCurrROI() # #self.UI.compSeq[e*len(self.eggIDIms):(e*len(self.eggIDIms)+len(self.eggIDIms))] = self.seq # #self.UI.comp(self.imImport(self.diag.imv.currentIndex())) # im = cv2.imread(self.eggUIimPaths[self.diag.imv.currentIndex],cv2.IMREAD_ANYDEPTH) # ran = (im.max()-im.min())/255. # out = (im/ran) # out = out-out.min() # self.compSeq[self.diag.imv.currentIndex] = out.astype(np.uint8) # self.diag.imv.setImage(self.compSeq.T) # self.diag.imv.show() # #======== #============================================================================== #============================================================================== # ROI functions #============================================================================== #============================================================================== # Import OpenCV determined ROIs from dataHandling instance. Called from showUI and updateUI. #============================================================================== def importOpenCVROIs(self,eggRotBBox, eggBoxPoints): self.eggRotBBox = eggRotBBox self.eggBoxPoints = eggBoxPoints self.originalEggRotBBox = eggRotBBox.copy() self.originalEggBoxPoints = eggBoxPoints.copy() #============================================================================== # Get index values for ROI data. #============================================================================== def getSeqValsAndCurrROI(self): # Calculate the indices for current frame if self.eggInt != 1234: self.divVal = self.diag.imv.currentIndex/float(len(self.eggRotBBox[1])) self.intDivVal = int(self.divVal) self.withinSeqVal = int((self.divVal - self.intDivVal)*len(self.eggRotBBox[self.intDivVal])) self.currROI_eggRotBBox = self.eggRotBBox[self.intDivVal,self.withinSeqVal] self.currROI_eggBoxPoints = self.eggBoxPoints[self.intDivVal,self.withinSeqVal] else: self.divVal = self.diag.imv.currentIndex self.intDivVal = int(self.divVal) self.currROI_eggRotBBox = self.eggRotBBox[0,self.intDivVal] self.currROI_eggBoxPoints = self.eggBoxPoints[0,self.intDivVal] #============================================================================== # Generate a pyqtgraph ROI, using data from OpenCV. #============================================================================== def createOpenCVEggROI(self): # Get relevant sequence position and ROI. self.getSeqValsAndCurrROI() if (self.currROI_eggRotBBox[0] != 'nan'): # 0 or 90 degree angles seem very buggy. Shift to 1 and 89 as a bodge fix. if self.currROI_eggRotBBox[4] == -90: #self.currROI_eggRotBBox[4] = -89 # Get rotated bounding box points ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) elif self.currROI_eggRotBBox[4] == -0: #self.currROI_eggRotBBox[4] = -1 ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) elif self.currROI_eggRotBBox[4] == -180: #self.currROI_eggRotBBox[4] = -179 ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) else: # Get rotated bounding box points ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] # Make ROI - note non 0,or 90 degree angles, require different of the X size # Rectangular ROI used to enable more easy handling of corner handles for tracking user chagnges. if (self.currROI_eggRotBBox[4] == -90.0) | (self.currROI_eggRotBBox[4] == -0.0)| (self.currROI_eggRotBBox[4] == 0.0): self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) # roi = pg.EllipseROI([bottomMost[0][0], bottomMost[0][1]], [eggRotBBox[vidTime][2], eggRotBBox[vidTime][3]]) # Debug # print 'no angle' else: # Random angle ROIs self.roi = pg.ROI([bottomMost[0][0], bottomMost[0][1]], [-self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) self.roi.setAngle(self.currROI_eggRotBBox[4], update=True) # roi = pg.EllipseROI([bottomMost[0][0], bottomMost[0][1]], [-eggRotBBox[vidTime][2], eggRotBBox[vidTime][3]]) # Add handles self.roi.addRotateHandle([1, 0],[0.5,0.5]) self.roi.addRotateHandle([0, 1], [0.5,0.5]) self.roi.addScaleHandle([1, 1], [0, 0]) self.roi.addScaleHandle([0, 0], [1, 1]) self.roi.setPen('y',width=3) self.roi.removable self.roi.invertible = 'True' # Make var for dealing with modifications to roi self.updatedEggROI=[] self.roi.sigRegionChangeFinished.connect(self.updateROI) #else: #============================================================================== # Update the ROI for current embryo. #============================================================================== def updateOpenCVEggROICurrEmbryo(self): # Remove previous if (hasattr(self, 'roi')): self.diag.imv.removeItem(self.roi) # Get relevant video position and ROI. self.getSeqValsAndCurrROI() # 0 or 90 degree angles seem very buggy. Shift to 1 and 89 as a bodge fix. if self.currROI_eggRotBBox[4] == -90: #self.currROI_eggRotBBox[4] = -89 # Get rotated bounding box points ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) elif self.currROI_eggRotBBox[4] == -0: #self.currROI_eggRotBBox[4] = -1 ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) elif self.currROI_eggRotBBox[4] == -180: #self.currROI_eggRotBBox[4] = -179 ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) else: # Get rotated bounding box points ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] # Make ROI - note non 0,or 90 degree angles, require different of the X size # Rectangular ROI used to enable more easy handling of corner handles for tracking user chagnges. if (self.currROI_eggRotBBox[4] == -90.0) | (self.currROI_eggRotBBox[4] == -0.0)| (self.currROI_eggRotBBox[4] == 0.0): self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) # roi = pg.EllipseROI([bottomMost[0][0], bottomMost[0][1]], [eggRotBBox[vidTime][2], eggRotBBox[vidTime][3]]) # Debug # print 'no angle' else: # Random angle ROIs self.roi = pg.ROI([bottomMost[0][0], bottomMost[0][1]], [-self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) self.roi.setAngle(self.currROI_eggRotBBox[4], update=True) # roi = pg.EllipseROI([bottomMost[0][0], bottomMost[0][1]], [-eggRotBBox[vidTime][2], eggRotBBox[vidTime][3]]) # roi = pg.EllipseROI([bottomMost[0][0], bottomMost[0][1]], [-eggRotBBox[vidTime][2], eggRotBBox[vidTime][3]]) # Add handles self.roi.addRotateHandle([1, 0],[0.5,0.5]) self.roi.addRotateHandle([0, 1], [0.5,0.5]) self.roi.addScaleHandle([1, 1], [0, 0]) self.roi.addScaleHandle([0, 0], [1, 1]) self.roi.setPen('y',width=3) self.roi.removable self.roi.invertible = 'True' # Make var for dealing with modifications to roi self.updatedEggROI=[] ### Still to do... self.diag.imv.addItem(self.roi) self.roi.sigRegionChangeFinished.connect(self.updateROI) #============================================================================== # Update ROI for new embryo. #============================================================================== def updateOpenCVEggROINewEmbryo(self): # Remove old ROI if (hasattr(self, 'roi')): self.diag.imv.removeItem(self.roi) # Get relevant video position and ROI self.getSeqValsAndCurrROI() # 0 or 90 degree angles seem very buggy. Shift to 1 and 89 as a bodge fix. if self.currROI_eggRotBBox[4] == -90: #self.currROI_eggRotBBox[4] = -89 # Get rotated bounding box points ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) elif self.currROI_eggRotBBox[4] == -0: #self.currROI_eggRotBBox[4] = -1 ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) elif self.currROI_eggRotBBox[4] == -180: #self.currROI_eggRotBBox[4] = -179 ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) else: # Get rotated bounding box points ySorted = self.currROI_eggBoxPoints[np.argsort(self.currROI_eggBoxPoints[:, 1]), :] # Get bottom most, and top most sorted corner points bottomMost = ySorted[:2, :] topMost = ySorted[2:, :] # Get bottom most bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] (bl, br) = bottomMost # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # The point with the largest distance will be our bottom-right point D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] (tl, tr) = topMost[np.argsort(D)[::-1], :] # Make ROI - note non 0,or 90 degree angles, require different of the X size # Rectangular ROI used to enable more easy handling of corner handles for tracking user chagnges. if (self.currROI_eggRotBBox[4] == -90.0) | (self.currROI_eggRotBBox[4] == -0.0)| (self.currROI_eggRotBBox[4] == 0.0): self.roi = pg.ROI([bl[0], bl[1]], [self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) # roi = pg.EllipseROI([bottomMost[0][0], bottomMost[0][1]], [eggRotBBox[vidTime][2], eggRotBBox[vidTime][3]]) # Debug # print 'no angle' else: # Random angle ROIs self.roi = pg.ROI([bottomMost[0][0], bottomMost[0][1]], [-self.currROI_eggRotBBox[2], self.currROI_eggRotBBox[3]]) self.roi.setAngle(self.currROI_eggRotBBox[4], update=True) # Add handles self.roi.addRotateHandle([1, 0],[0.5,0.5]) self.roi.addRotateHandle([0, 1], [0.5,0.5]) self.roi.addScaleHandle([1, 1], [0, 0]) self.roi.addScaleHandle([0, 0], [1, 1]) self.roi.setPen('y',width=3) self.roi.removable self.roi.invertible = 'True' # Make var for dealing with modifications to roi self.updatedEggROI=[] ### Still to do... self.diag.imv.addItem(self.roi) self.roi.sigRegionChangeFinished.connect(self.updateROI) #============================================================================== # Update ROI. #============================================================================== def updateROI(self): #global vidTime, xyPosHandles, ellipse, changeAngle, roiChanges,updatedEggROI, changeX, changeY, changeScaleX, changeScaleY, changeAngle # Get changes to ROI scale, angle and position roiChanges = self.roi.getGlobalTransform() changeX = -roiChanges.getTranslation()[0] changeY = roiChanges.getTranslation()[1] changeScaleX = roiChanges.getScale()[0] changeScaleY = roiChanges.getScale()[1] changeAngle = roiChanges.getAngle() # Update ROI, either updating the previously updated or taking the unaltered ROI from OpenCV as a starting point. #if len(self.updatedEggROI) == 0: self.updatedEggROI = (((self.currROI_eggRotBBox[0]-changeX),(self.currROI_eggRotBBox[1]+changeY)),((max((self.currROI_eggRotBBox[3]*changeScaleX),(self.currROI_eggRotBBox[2]*changeScaleY))),(min((self.currROI_eggRotBBox[3]*changeScaleX),(self.currROI_eggRotBBox[2]*changeScaleY)))),self.currROI_eggRotBBox[4]+changeAngle) #else: #self.updatedEggROI = (((self.updatedEggROI[0][0]-changeX),(self.updatedEggROI[0][1]+changeY)),((max((self.updatedEggROI[1][0]*changeScaleX),(self.updatedEggROI[1][1]*changeScaleY))),(min((self.updatedEggROI[1][0]*changeScaleX),(self.updatedEggROI[1][1]*changeScaleY)))),self.updatedEggROI[2]+changeAngle) hh = self.roi.getHandles() hh = [self.roi.mapToItem(self.diag.imv.getImageItem(), h.pos()) for h in hh] # Handle on each corner. Get handle positions self.xyPosHandles =[] for h in hh: self.xyPosHandles.append([h.x(),h.y()]) (eggBBX, eggBBY), (eggBBW, eggBBH), eggBBAng = cv2.minAreaRect(np.array(self.xyPosHandles, dtype=np.int32) ) if eggBBAng == -90: eggBBAng = -89 elif eggBBAng == -180: eggBBAng = -179 elif eggBBAng == -0: eggBBAng = -1 # Save updated # If more than one frame eggID per sequence.. if self.eggInt != 1234: self.eggRotBBox[self.intDivVal,self.withinSeqVal] = [eggBBX, eggBBY, eggBBW, eggBBH, eggBBAng] self.eggBoxPoints[self.intDivVal,self.withinSeqVal] = cv2.boxPoints(((eggBBX, eggBBY), (eggBBW, eggBBH), eggBBAng)) # Otherwise just save simply else: self.eggRotBBox[0,self.intDivVal] = [eggBBX, eggBBY, eggBBW, eggBBH, eggBBAng] self.eggBoxPoints[0,self.intDivVal] = cv2.boxPoints(((eggBBX, eggBBY), (eggBBW, eggBBH), eggBBAng)) #============================================================================== # Copy ROI on button click. #============================================================================== def cpROI(self): self.originalEggRotBBox = self.currROI_eggRotBBox self.originalEggBoxPoints = self.currROI_eggBoxPoints #============================================================================== # Assign nan to current ROI if 'No Egg' button clicked #============================================================================== def recordNoEgg(self): # Remove ROI self.diag.imv.removeItem(self.roi) # Store nans in place of ROI if self.eggInt != 1234: self.eggRotBBox[self.intDivVal,self.withinSeqVal] = [np.nan, np.nan, np.nan, np.nan, np.nan] self.eggBoxPoints[0,self.intDivVal] = [np.nan,np.nan,np.nan,np.nan] else: self.eggBoxPoints[0,self.intDivVal] = [np.nan,np.nan,np.nan,np.nan] self.eggRotBBox[0,self.intDivVal] = [np.nan, np.nan, np.nan, np.nan, np.nan] #============================================================================== # Copy ROI on button click. #============================================================================== def applyCopiedROI(self): self.getSeqValsAndCurrROI() # Store copied ROI to embryo sequence ROIs if self.eggInt != 1234: self.divVal = self.diag.imv.currentIndex/float(len(self.eggRotBBox[1])) self.intDivVal = int(self.divVal) self.withinSeqVal = int((self.divVal - self.intDivVal)*len(self.eggRotBBox[self.intDivVal])) self.eggRotBBox[self.intDivVal,self.withinSeqVal] = self.originalEggRotBBox self.eggBoxPoints[self.intDivVal,self.withinSeqVal] = self.originalEggBoxPoints else: self.divVal = self.diag.imv.currentIndex self.intDivVal = int(self.divVal) self.eggRotBBox[0,self.intDivVal] = self.originalEggRotBBox self.eggBoxPoints[0,self.intDivVal] = self.originalEggBoxPoints self.updateOpenCVEggROICurrEmbryo() #============================================================================== # #============================================================================== #============================================================================== # Close button - not implemented (hidden) #============================================================================== #============================================================================== # def closeEvent(self, event): # # quit_msg = "Are you sure you want to exit the program?" # reply = QtGui.QMessageBox.question(self, 'Message', # quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) # # if reply == QtGui.QMessageBox.Yes: # #event.accept() # app.quit() # else: # event.ignore() # #============================================================================== #============================================================================== # #self.originalEggRotBBox = eggRotBBox.copy() # #self.originalEggBoxPoints = eggBoxPoints.copy() # #self.currROI_eggRotBBox = self.eggRotBBox[self.intDivVal,self.withinSeqVal] # #self.currROI_eggBoxPoints = self.eggBoxPoints[self.intDivVal,self.withinSeqVal] # # # Modified version of updateOpenCVEggROICurrEmbryo # # Remove previous # self.diag.imv.removeItem(self.roi) # # Get relevant video position and ROI. # self.getSeqValsAndCurrROI() # # Get rotated bounding box points # ySorted = self.originalEggBoxPoints[np.argsort(self.originalEggBoxPoints[:, 1]), :] # # Get bottom most, and top most sorted corner points # bottomMost = ySorted[:2, :] # topMost = ySorted[2:, :] # # Get bottom most # bottomMost = bottomMost[np.argsort(bottomMost[:, 1]), :] # (bl, br) = bottomMost # # Use bottom-left coordinate as anchor to calculate the Euclidean distance between the # # The point with the largest distance will be our bottom-right point # D = dist.cdist(bl[np.newaxis], topMost, "euclidean")[0] # (tl, tr) = topMost[np.argsort(D)[::-1], :] # # Make ROI - note non 0,or 90 degree angles, require different of the X size # # Rectangular ROI used to enable more easy handling of corner handles for tracking user chagnges. # if (self.originalEggRotBBox[4] == -90.0) | (self.originalEggRotBBox[4] == -0.0)| (self.originalEggRotBBox[4] == 0.0): # self.roi = pg.ROI([bottomMost[0][0], bottomMost[0][1]], [self.originalEggRotBBox[2], self.originalEggRotBBox[3]]) # # roi = pg.EllipseROI([bottomMost[0][0], bottomMost[0][1]], [eggRotBBox[vidTime][2], eggRotBBox[vidTime][3]]) # else: # # Random angle ROIs # self.roi = pg.ROI([bottomMost[0][0], bottomMost[0][1]], [-self.originalEggRotBBox[2], self.originalEggRotBBox[3]]) # self.roi.setAngle(self.originalEggRotBBox[4], update=True) # # roi = pg.EllipseROI([bottomMost[0][0], bottomMost[0][1]], [-eggRotBBox[vidTime][2], eggRotBBox[vidTime][3]]) # # Add handles # self.roi.addRotateHandle([1, 0],[0.5,0.5]) # self.roi.addRotateHandle([0, 1], [0.5,0.5]) # self.roi.addScaleHandle([1, 1], [0, 0]) # self.roi.addScaleHandle([0, 0], [1, 1]) # self.roi.setPen('y',width=3) # self.roi.removable # self.roi.invertible = 'True' # # Make var for dealing with modifications to roi # self.updatedEggROI=[] # ### Still to do... # self.diag.imv.addItem(self.roi) # self.roi.sigRegionChangeFinished.connect(self.updateROI) #============================================================================== #===============
2.4375
2
Curso em Vídeo/Mundo 2 Estruturas de Controle/Desafios/desafio053.py
henriqueumeda/-Estudo-python
0
4792
frase = input('Digite uma frase: ').upper().strip().replace(' ', '') tamanho = int(len(frase)) inverso = '' #Opção mais simples: # inverso = frase[::-1] for contador in range(tamanho-1, -1, -1): inverso += frase[contador] print('O inverso de {} é {}'.format(frase, inverso)) if frase == inverso: print('Temos um palíndromo!') else: print('A frase digitada não é um palíndromo!')
3.984375
4
tests/unittest/options/pricing/test_binomial_trees.py
yiluzhu/quant
1
4793
from unittest import TestCase from options.pricing.binomial_trees import BinomialTreePricer from options.option import OptionType, Option class BinomialTreeTestCase(TestCase): def test_basic(self): """European option, spot price 50, strike price 52, risk free interest rate 5% expiry 2 years, volatility 30% """ pricer = BinomialTreePricer(steps=100) option = Option(OptionType.PUT, 50, 52, 0.05, 2, 0.3) result = pricer.price_option(option) self.assertEqual(6.7781, result)
3.28125
3
mctimer.py
Sharpieman20/MCtimer
0
4794
import atexit import os import sys import platform import json import glob import datetime import time import threading import tkinter as tk from pynput import mouse from pathlib import Path from playsound import playsound from enum import Enum import copy #"THE BEER-WARE LICENSE" (Revision 42): #bleach86 wrote this file. As long as you retain this notice you can do whatever you want with this stuff. #If we meet some day, and you think this stuff is worth it, you can buy me a beer in return input_fil = Path("/Users/sharpieman20/MCtimer/MCtimer") / "input.txt" # continuously read from input file every 10ms # when you get a "reset timer" message, reset the timer # # class Category: # def __init__(): # self.actions = [] # self.attempts = [] # # convert actions to attempts # def read(): # def write(): # class Actions(Enum): # CREATE_WORLD = 0 # START = 1 # class Attempt: stage = 0 ind = 0 time_count = 0 rsg = [ ("World Created", True), ([ "Savannah", "Desert", "Plains", "Other" ], False), ([ "0-15", "15-30", "30-45", "45-60", "60-75", "75+" ], False), ([ "Iron", "Logs", "Feathers", "Wool", "Gravel" ], True), ("Enter Nether", True), ("Find Fortress", True), ("Find Spawner", True), ("Exit Spawner", True), ("Exit Nether", True), ("Tower Build Start", True), ("Tower Build Finished", True), ("Tower Leave", True), ("Enter Stronghold", True), ("Enter End", True), ("Finish", True) ] cur_stages = {} json_file = 'mct_config.json' with open(json_file) as json_file: data2 = json.load(json_file) if data2['borderless'] == 'true': data2['borderless'] else: data2['borderless'] = False running_path = Path.cwd() NUM_CHARS = 11 system_type = platform.system() if system_type == 'Linux': directory = os.path.expanduser(data2['linux_saves']) elif system_type == 'Darwin': directory = os.path.expanduser(data2['mac_saves']) elif system_type == 'Windows': directory = os.path.expanduser(data2['windows_saves']) amount2 = 0 last_amount = 0 window = tk.Tk() # bg = BindGlobal(widget=window) window.text = tk.StringVar() window.text2 = tk.StringVar() window.text3 = tk.StringVar() window.text4 = tk.StringVar() window.geometry("{}x{}".format(data2["width"], data2["height"])) window.configure(bg='black') rt = time.time() old_version = False did_change = False count = 0 ig = 0 base = 0 program_time = 0 metronome_armed = False metronome_running = False metronome_active = False metronome_beats = int(data2['metronome_beats']) listener = None metronome_time = 0 base_update = int(data2['base_update']) rta_update = int(data2['rta_update']) * base_update metronome_bpm = int(data2['metronome_bpm']) metronome_interval = 0 if data2['auto_start'] == 'true': click1 = 1 click2 = 1 else: click1 = 0 click2 = 0 cur_fil = None world_base_time = 0 def get_time(): global last_amount global old_version global amount2 global ig global did_change # print("-------------------------") if data2['1.7+'] == 'false': try: global cur_fil global world_base_time mc_dir = Path(directory).parent stats_dir = mc_dir / "stats" os.chdir(stats_dir) json_file = glob.glob('*.dat') stats_file = json_file[0] amount = 0 with open(stats_file) as timer_file: # print(timer_file) data = json.load(timer_file) for item in data["stats-change"]: if "1100" in item: amount = item["1100"] # print(amount) latest = max([os.path.join(directory,d) for d in os.listdir(directory)], key=os.path.getmtime) # print(latest) if latest != cur_fil: cur_fil = latest world_base_time = amount # print("world base time now {}".format(world_base_time)) # print(amount) amount2 = float(amount - world_base_time) / 20 # print(amount2) run_time = str(datetime.timedelta(seconds=amount2, milliseconds=0.5)) # print(run_time) if last_amount == amount: ig = 0 return run_time[:-3] else: did_change = True # print(latest + "\nTime: " + run_time) last_amount = amount ig = 0 return run_time[:-3] except: ig = 1 return '0:00:00.000' else: try: latest = max([os.path.join(directory,d) for d in os.listdir(directory)], key=os.path.getmtime) if system_type == "Linux" or system_type == "Darwin": os.chdir(latest + '/stats/') else: os.chdir(latest + '\\stats\\') json_file = glob.glob('*.json') timer = json_file[0] with open(timer) as json_file: data = json.load(json_file) try: amount = data['stats']['minecraft:custom']['minecraft:play_one_minute'] except: amount = data['stat.playOneMinute'] old_version = True json_file.close() amount2 = float(amount) / 20 run_time = str(datetime.timedelta(seconds=amount2, milliseconds=0.5)) if last_amount == amount: ig = 0 return run_time[:-3] else: did_change = True print(latest + "\nTime: " + run_time) last_amount = amount ig = 0 return run_time[:-3] except: ig = 1 return '0:00:00.000' def window2(): font_name = data2['font_name'] rta_font_size = data2['rta_font_size'] igt_font_size = data2['igt_font_size'] font_modifiers = data2['font_modifiers'] rta_font = (font_name, rta_font_size, font_modifiers) igt_font = (font_name, igt_font_size, font_modifiers) greeting = tk.Label(fg=data2['rta_color'], bg=data2['bg_color'], font=rta_font, textvariable=window.text) greeting.pack() if data2['show_igt'] == 'true': greeting2 = tk.Label(fg=data2['igt_color'], bg=data2['bg_color'], font=igt_font, textvariable=window.text2) greeting2.pack() if data2['use_counter'] == 'true': greeting3 = tk.Label(fg=data2['counter_color'], bg=data2['bg_color'], font=rta_font, textvariable=window.text3) greeting3.pack() # bg.gbind(data2['increment'], on_increment_counter) # greeting.after(0, update_count) if data2['use_splits'] == 'true': split_font_size = data2['split_font_size'] split_font = (font_name, split_font_size, font_modifiers) greeting4 = tk.Label(fg=data2['split_color'], bg=data2['bg_color'], font=split_font, textvariable=window.text4) greeting4.pack() # bg.gbind(data2['cycle'], cycle) # bg.gbind(data2['split'], split) # bg.gbind(data2['skip'], skip) reset_split() # greeting.after(0, update_count) # bg.gbind(data2['pause'], on_press) # bg.gbind(data2['reset_start'], on_press2) # if data2['enable_metronome'] == 'true': # bg.gbind(data2['arm_metronome'], arm_metronome) # bg.gbind(data2['start_metronome'], start_metronome) # bg.gbind(data2['exit'], clicked3) # bg.bind(data2['start_metronome'], start_metronome) ''' this works for the window detecting right click ''' # window.bind(data2['start_metronome'], start_metronome) #window.bind("<Button-1>", clicked) #window.bind("<Button-3>", clicked2) greeting.after(0, tick_time) greeting.after(0, update_time2) window.title("MCtimer") window.attributes('-topmost', True) window.overrideredirect(data2['borderless']) window.geometry(data2['window_pos']) window.mainloop() def update_time(): global rt global program_time # do_metronome_action() if click1 == 1: window.text.set(real_time()) elif click1 == 0: # rt = time.time() diff = amount2 - base rtc = str(datetime.timedelta(seconds=diff)) diff_txt = rtc[:-3] # print(diff_txt) window.text.set(diff_txt) # print(base) if click2 == 0: rt = time.time() window.text.set("0:00:00.000") # window.after(int(data2['rta_update'])/10, update_time) def tick_time(): global time_count global metronome_armed time_count += 1 update_time() if metronome_armed or time_count % 20 == 0: check_input() window.after(rta_update, tick_time) def check_input(): txt = input_fil.read_text() input_fil.write_text("") global metronome_armed # print(txt) if "start_metronome" in txt: print(data2['enable_metronome']) if data2['enable_metronome'] == 'true': start_metronome(None) if "arm_metronome" in txt: metronome_armed = True if "pause_timer" in txt: left_click() if "start_timer" in txt: right_click() def update_time2(): window.text2.set(get_time()) window.after(1000, update_time2) def update_count(): count_str = str(count) text_str = "" for i in range(0, int(NUM_CHARS/2)): text_str += " " text_str += count_str for i in range(0, int(NUM_CHARS/2)): text_str += " " window.text3.set(text_str) window.after(rta_update, update_count) # def update_split() def on_press(event): left_click() def on_press2(event): right_click() def update_split(): global stage text_str = cur_stages[stage][0] if type(text_str) == type([]): text_str = text_str[ind] window.text4.set(text_str) def reset_split(): global ind, stage, cur_stages ind = 0 stage = 0 cur_stages = copy.deepcopy(rsg) update_split() def cycle(event): global ind, stage ind += 1 item = cur_stages[stage] if type(item[0]) == type([]): if ind == len(item[0]): ind = 0 else: ind = 0 update_split() def split(event): global stage, ind item = cur_stages[stage] if item[1]: if type(item[0]) == type([]): item[0].remove(item[0][ind]) if len(item[0]) == 0: stage += 1 ind = 0 update_split() return stage += 1 ind = 0 update_split() def skip(event): global stage stage += 1 update_split() def on_increment_counter(event): increment_counter() def clicked3(event): sys.exit(1) def clicked2(event): right_click() def clicked(event): left_click() def write_to_log(text): pass # log_dir = Path("/Users/sharpieman20/MCtimer/MCtimer/logs") # log_fil = log_dir / data2["current_section"] # log_fil.touch() # log_fil = log_fil.open("a") # log_fil.write(str(text)+"\n") def left_click(): global click1 if click1 == 1: click1 = 0 elif click1 == 0: click1 = 0 # global base # write_to_log(str(amount2-base)) # base = amount2 def right_click(): global click1 global click2 global count global did_change count = 0 did_change = True if click2 == 1: click1 = 0 click2 = 0 elif click2 == 0: click2 = 1 click1 = 1 # print(float(amount2)) # print("hehe") global base write_to_log("reset {}".format(str(amount2-base))) base = amount2 def increment_counter(): global count count += 1 ''' METRONOME CODE ''' ''' Metronome mouse listener ''' def exit_handler(): global listener mouse.Listener.stop(listener) window.quit() atexit.register(exit_handler) def listen_for_right_click(): def on_click(x, y, button, pressed): # print(button) if pressed: if pressed and button == mouse.Button.right: start_metronome(None) return False # mouse.Listener.stop(listener) # print("Right Click Detected (pressed)") with mouse.Listener(on_click=on_click) as listener: # listener.start() listener.join() ''' Sound playing code ''' def play_file_named(str_name): playsound((running_path / str_name).as_posix(), block = True) def play_up_beep(): play_file_named("MetronomeHit.mp3") def play_normal_beep(): play_file_named("MetronomeBase.mp3") def play_metronome_preset(): time.sleep(0.06) play_file_named("MetronomePreset.mp3") ''' Metronome functions ''' def arm_metronome(event): global metronome_armed global metronome_running if metronome_armed or metronome_running: return metronome_armed = True # x = threading.Thread(target=listen_for_right_click, daemon=True) # x.start() listen_for_right_click() print("armed and ready") def start_metronome(event): run_metronome() # print(metronome_running) # arm_metronome = False def run_metronome(): global metronome_time global metronome_interval global metronome_running if data2['has_metronome_preset'] == 'true': play_metronome_preset() metronome_running = False return metronome_time = 0 base_time = round(time.time()*1000) metronome_interval = int(100 * 60 / metronome_bpm)*10 time.sleep(float(data2['beat_offset'])*metronome_interval/1000.0) # print(metronome_interval)555 while metronome_running: start_time = round(time.time()*1000) - base_time do_metronome_action() end_time = round(time.time()*1000) - base_time elapsed = end_time - start_time time.sleep((metronome_interval - elapsed)/1000.0) # print("{} {} {}".format(start_time, end_time, )) metronome_time += metronome_interval def do_metronome_action(): global metronome_running global metronome_interval if not metronome_running: return # print(metronome_interval) # metronome_time = program_time - metronome_start_time if metronome_time >= metronome_interval * metronome_beats: metronome_running = False return # print(metronome_time) # print(metronome_interval) # print(time.time()*1000) if metronome_time % metronome_interval == 0: if (metronome_time % (metronome_interval*4)) == metronome_interval*3: # print("up beep") play_up_beep() # pass else: # print("normal beep") play_normal_beep() # pass # print(time.time()*1000) # print() def real_time(): global rt global click1 global click2 global amount2 global old_version global stage global ig global did_change if data2['auto_adjust'] == 'true': # print(did_change) # print(base) if did_change: rt = float(time.time()) - float(amount2) if data2['allow_offset'] == 'true': rt += base did_change = False if data2['auto_start'] == 'true': if ig == 1: rt = time.time() click1 = 1 click2 = 1 stage = 0 reset_split() return '0:00:00.000' elif click1 == 1: if old_version == True and stage == 0: ig = 0 rt = float(time.time()) - float(amount2) rtc = str(datetime.timedelta(seconds=rt)) stage = 1 print("stop") return rtc[:-3] else: ig = 0 rt2 = time.time() real_time = rt2 - rt rtc = str(datetime.timedelta(seconds=real_time)) # rt = float(amount2) - float(base) # rtc = str(datetime.timedelta(seconds=rt)) return rtc[:-3] else: if click1 == 1: rt2 = time.time() real_time = rt2 - rt rtc = str(datetime.timedelta(seconds=real_time)) return rtc[:-3] def main(): window2() main()
2.421875
2
kafka/structs.py
informatique-cdc/kafka-python
4,389
4795
""" Other useful structs """ from __future__ import absolute_import from collections import namedtuple """A topic and partition tuple Keyword Arguments: topic (str): A topic name partition (int): A partition id """ TopicPartition = namedtuple("TopicPartition", ["topic", "partition"]) """A Kafka broker metadata used by admin tools. Keyword Arguments: nodeID (int): The Kafka broker id. host (str): The Kafka broker hostname. port (int): The Kafka broker port. rack (str): The rack of the broker, which is used to in rack aware partition assignment for fault tolerance. Examples: `RACK1`, `us-east-1d`. Default: None """ BrokerMetadata = namedtuple("BrokerMetadata", ["nodeId", "host", "port", "rack"]) """A topic partition metadata describing the state in the MetadataResponse. Keyword Arguments: topic (str): The topic name of the partition this metadata relates to. partition (int): The id of the partition this metadata relates to. leader (int): The id of the broker that is the leader for the partition. replicas (List[int]): The ids of all brokers that contain replicas of the partition. isr (List[int]): The ids of all brokers that contain in-sync replicas of the partition. error (KafkaError): A KafkaError object associated with the request for this partition metadata. """ PartitionMetadata = namedtuple("PartitionMetadata", ["topic", "partition", "leader", "replicas", "isr", "error"]) """The Kafka offset commit API The Kafka offset commit API allows users to provide additional metadata (in the form of a string) when an offset is committed. This can be useful (for example) to store information about which node made the commit, what time the commit was made, etc. Keyword Arguments: offset (int): The offset to be committed metadata (str): Non-null metadata """ OffsetAndMetadata = namedtuple("OffsetAndMetadata", # TODO add leaderEpoch: OffsetAndMetadata(offset, leaderEpoch, metadata) ["offset", "metadata"]) """An offset and timestamp tuple Keyword Arguments: offset (int): An offset timestamp (int): The timestamp associated to the offset """ OffsetAndTimestamp = namedtuple("OffsetAndTimestamp", ["offset", "timestamp"]) MemberInformation = namedtuple("MemberInformation", ["member_id", "client_id", "client_host", "member_metadata", "member_assignment"]) GroupInformation = namedtuple("GroupInformation", ["error_code", "group", "state", "protocol_type", "protocol", "members", "authorized_operations"]) """Define retry policy for async producer Keyword Arguments: Limit (int): Number of retries. limit >= 0, 0 means no retries backoff_ms (int): Milliseconds to backoff. retry_on_timeouts: """ RetryOptions = namedtuple("RetryOptions", ["limit", "backoff_ms", "retry_on_timeouts"])
2.78125
3
Vehicle_Counting_colab.py
manolosolalinde/Vehicle-Counting
0
4796
import cv2 from trackers.tracker import create_blob, add_new_blobs, remove_duplicates import numpy as np from collections import OrderedDict from detectors.detector import get_bounding_boxes import uuid import os import contextlib from datetime import datetime import argparse from utils.detection_roi import get_roi_frame, draw_roi from counter import get_counting_line, is_passed_counting_line # parse CLI arguments parser = argparse.ArgumentParser() parser.add_argument('video', help='relative/absolute path to video or camera input of traffic scene') parser.add_argument('--iscam', action='store_true', help='specify if video capture is from a camera') parser.add_argument('--droi', help='specify a detection region of interest (ROI) \ i.e a set of vertices that represent the area (polygon) \ where you want detections to be made (format: 1,2|3,4|5,6|7,8|9,10 \ default: 0,0|frame_width,0|frame_width,frame_height|0,frame_height \ [i.e the whole video frame])') parser.add_argument('--showdroi', action='store_true', help='display/overlay the detection roi on the video') parser.add_argument('--mctf', type=int, help='maximum consecutive tracking failures \ i.e number of tracking failures before the tracker concludes \ the tracked object has left the frame') parser.add_argument('--di', type=int, help='detection interval i.e number of frames \ before detection is carried out again (in order to find new vehicles \ and update the trackers of old ones)') parser.add_argument('--detector', help='select a model/algorithm to use for vehicle detection \ (options: yolo, haarc, bgsub, ssd | default: yolo)') parser.add_argument('--tracker', help='select a model/algorithm to use for vehicle tracking \ (options: csrt, kcf, camshift | default: kcf)') parser.add_argument('--record', action='store_true', help='record video and vehicle count logs') parser.add_argument('--clposition', help='position of counting line (options: top, bottom, \ left, right | default: bottom)') parser.add_argument('--hideimage', action='store_true', help='hide resulting image') args = parser.parse_args() # capture traffic scene video video = int(args.video) if args.iscam else args.video cap = cv2.VideoCapture(video) _, frame = cap.read() # configs blobs = OrderedDict() blob_id = 1 frame_counter = 0 DETECTION_INTERVAL = 10 if args.di == None else args.di MAX_CONSECUTIVE_TRACKING_FAILURES = 3 if args.mctf == None else args.mctf detector = 'yolo' if args.detector == None else args.detector tracker = 'kcf' if args.tracker == None else args.tracker f_height, f_width, _ = frame.shape # init video object and log file to record counting if args.record: output_video = cv2.VideoWriter('./videos/output.avi', cv2.VideoWriter_fourcc('M','J','P','G'), 30, (f_width, f_height)) log_file_name = 'log.txt' with contextlib.suppress(FileNotFoundError): os.remove(log_file_name) log_file = open(log_file_name, 'a') log_file.write('vehicle_id, count, datetime\n') log_file.flush() # set counting line clposition = 'bottom' if args.clposition == None else args.clposition counting_line = get_counting_line(clposition, f_width, f_height) vehicle_count = 0 # create detection ROI droi = [(0, 0), (f_width, 0), (f_width, f_height), (0, f_height)] if args.droi: droi = [] points = args.droi.replace(' ', '').split('|') for point_str in points: point = tuple(map(int, point_str.split(','))) droi.append(point) # initialize trackers and create new blobs droi_frame = get_roi_frame(frame, droi) initial_bboxes = get_bounding_boxes(droi_frame, detector) for box in initial_bboxes: _blob = create_blob(box, frame, tracker) blobs[blob_id] = _blob blob_id += 1 while True: k = cv2.waitKey(1) if args.iscam or cap.get(cv2.CAP_PROP_POS_FRAMES) + 1 < cap.get(cv2.CAP_PROP_FRAME_COUNT): _, frame = cap.read() nframes = cap.get(cv2.CAP_PROP_POS_FRAMES) frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) if nframes % 10 == 0 or nframes == 1: print("Processing {} of {} frames".format(nframes,frame_count)) for _id, blob in list(blobs.items()): # update trackers success, box = blob.tracker.update(frame) if success: blob.num_consecutive_tracking_failures = 0 blob.update(box) else: blob.num_consecutive_tracking_failures += 1 # delete untracked blobs if blob.num_consecutive_tracking_failures >= MAX_CONSECUTIVE_TRACKING_FAILURES: del blobs[_id] # count vehicles if is_passed_counting_line(blob.centroid, counting_line, clposition) and not blob.counted: blob.counted = True vehicle_count += 1 # log count data to a file (vehicle_id, count, datetime) if args.record: _row = '{0}, {1}, {2}\n'.format('v_' + str(_id), vehicle_count, datetime.now()) log_file.write(_row) log_file.flush() if frame_counter >= DETECTION_INTERVAL: # rerun detection droi_frame = get_roi_frame(frame, droi) boxes = get_bounding_boxes(droi_frame, detector) blobs, current_blob_id = add_new_blobs(boxes, blobs, frame, tracker, blob_id, counting_line, clposition) blob_id = current_blob_id blobs = remove_duplicates(blobs) frame_counter = 0 # draw and label blob bounding boxes for _id, blob in blobs.items(): (x, y, w, h) = [int(v) for v in blob.bounding_box] cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(frame, 'v_' + str(_id), (x, y - 2), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA) # draw counting line cv2.line(frame, counting_line[0], counting_line[1], (0, 255, 0), 3) # display vehicle count cv2.putText(frame, 'Count: ' + str(vehicle_count), (20, 60), cv2.FONT_HERSHEY_DUPLEX, 2, (255, 0, 0), 2, cv2.LINE_AA) # show detection roi if args.showdroi: frame = draw_roi(frame, droi) # save frame in video output if args.record: output_video.write(frame) # visualize vehicle counting if not args.hideimage: resized_frame = cv2.resize(frame, (858, 480)) cv2.imshow('tracking', resized_frame) frame_counter += 1 # save frame if 's' key is pressed if k & 0xFF == ord('s'): cv2.imwrite(os.path.join('screenshots', 'ss_' + uuid.uuid4().hex + '.png'), frame) print('Screenshot taken.') else: print('End of video.') # end video loop if on the last frame break # end video loop if 'q' key is pressed if k & 0xFF == ord('q'): print('Video exited.') break # end capture, close window, close log file and video objects if any cap.release() if not args.hideimage: cv2.destroyAllWindows() if args.record: log_file.close() output_video.release()
2.5
2
app/resources/magic_castle_api.py
ComputeCanada/mc-hub
5
4797
<filename>app/resources/magic_castle_api.py from flask import request from resources.api_view import ApiView from exceptions.invalid_usage_exception import InvalidUsageException from models.user.user import User from models.user.authenticated_user import AuthenticatedUser class MagicCastleAPI(ApiView): def get(self, user: User, hostname): if hostname: magic_castle = user.get_magic_castle_by_hostname(hostname) return magic_castle.dump_configuration() else: if type(user) == AuthenticatedUser: return [ { **magic_castle.dump_configuration(planned_only=True), "hostname": magic_castle.get_hostname(), "status": magic_castle.get_status().value, "freeipa_passwd": <PASSWORD>(), "owner": magic_castle.get_owner_username(), } for magic_castle in user.get_all_magic_castles() ] else: return [ { **magic_castle.dump_configuration(planned_only=True), "hostname": magic_castle.get_hostname(), "status": magic_castle.get_status().value, "freeipa_passwd": <PASSWORD>(), } for magic_castle in user.get_all_magic_castles() ] def post(self, user: User, hostname, apply=False): if apply: magic_castle = user.get_magic_castle_by_hostname(hostname) magic_castle.apply() return {} else: magic_castle = user.create_empty_magic_castle() json_data = request.get_json() if not json_data: raise InvalidUsageException("No json data was provided") magic_castle.set_configuration(json_data) magic_castle.plan_creation() return {} def put(self, user: User, hostname): magic_castle = user.get_magic_castle_by_hostname(hostname) json_data = request.get_json() if not json_data: raise InvalidUsageException("No json data was provided") magic_castle.set_configuration(json_data) magic_castle.plan_modification() return {} def delete(self, user: User, hostname): magic_castle = user.get_magic_castle_by_hostname(hostname) magic_castle.plan_destruction() return {}
2.40625
2
tests/rbac/api/role/propose_member_test.py
kthblmfld/sawtooth-next-directory
0
4798
# Copyright 2018 Contributors to Hyperledger Sawtooth # # 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. # ----------------------------------------------------------------------------- """ Propose Role Add Member Test """ # pylint: disable=invalid-name import time import requests import pytest from rbac.common.logs import get_logger from tests.rbac import helper from tests.rbac.api.assertions import assert_api_error from tests.rbac.api.assertions import assert_api_success from tests.rbac.api.assertions import assert_api_post_requires_auth LOGGER = get_logger(__name__) @pytest.mark.api @pytest.mark.api_role def test_api_propose_role_member(): """ Test a user proposing to add themselves to a role """ owner = helper.api.user.current role = helper.api.role.create.new(user=owner) user = helper.api.user.current2 url = helper.api.role.member.propose.url(role_id=role["id"]) data = {"id": user["user_id"]} assert assert_api_post_requires_auth(url=url, json=data) response = requests.post( url=url, headers={"Authorization": user["token"]}, json=data ) result = assert_api_success(response) assert result["proposal_id"] time.sleep(0.5) # temporary until API refactored to return the proposal proposal = helper.api.proposal.get(result["proposal_id"], owner) assert proposal["id"] == result["proposal_id"] assert proposal["status"] == "OPEN" assert proposal["type"] == "ADD_ROLE_MEMBER" assert proposal["object"] == role["id"] assert proposal["target"] == user["user_id"] assert proposal["opener"] == user["user_id"] @pytest.mark.api @pytest.mark.api_role def test_api_propose_role_member_required_fields(): """ Test proposing adding a member to a role with missing fields """ role, _ = helper.api.role.current user = helper.api.user.create.current url = helper.api.role.member.propose.url(role_id=role["id"]) data = {} response = requests.post( url=url, headers={"Authorization": user["token"]}, json=data ) assert_api_error(response, "Bad Request: id field is required", 400)
1.9375
2
f2v.py
ClimberY/video_super_resolution_toolbox
0
4799
import cv2 import os import numpy as np from PIL import Image def frame2video(im_dir, video_dir, fps): im_list = os.listdir(im_dir) im_list.sort(key=lambda x: int(x.replace("_RBPNF7", "").split('.')[0])) img = Image.open(os.path.join(im_dir, im_list[0])) img_size = img.size # 获得图片分辨率,im_dir文件夹下的图片分辨率需要一致 fourcc = cv2.VideoWriter_fourcc(*'XVID') videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size) for i in im_list: im_name = os.path.join(im_dir + i) frame = cv2.imdecode(np.fromfile(im_name, dtype=np.uint8), -1) videoWriter.write(frame) videoWriter.release() if __name__ == '__main__': im_dir = '/media/hy/Seagate Expansion Drive/Results/merge_dir/' # 帧存放路径 video_dir = '/media/hy/Seagate Expansion Drive/Results/sandy.mp4' # 合成视频存放的路径 fps = 15 # 帧率 frame2video(im_dir, video_dir, fps)
2.75
3