repo_name
stringlengths
7
94
repo_path
stringlengths
4
237
repo_head_hexsha
stringlengths
40
40
content
stringlengths
10
680k
apis
stringlengths
2
840k
Inrixia/pyais
examples/single_message.py
b50fd4d75c687d71b3c70ee939ac9112cfec991e
from pyais.messages import NMEAMessage message = NMEAMessage(b"!AIVDM,1,1,,B,15M67FC000G?ufbE`FepT@3n00Sa,0*5C") print(message.decode()) # or message = NMEAMessage.from_string("!AIVDM,1,1,,B,15M67FC000G?ufbE`FepT@3n00Sa,0*5C") print(message.decode())
[((3, 10, 3, 73), 'pyais.messages.NMEAMessage', 'NMEAMessage', ({(3, 22, 3, 72): "b'!AIVDM,1,1,,B,15M67FC000G?ufbE`FepT@3n00Sa,0*5C'"}, {}), "(b'!AIVDM,1,1,,B,15M67FC000G?ufbE`FepT@3n00Sa,0*5C')", False, 'from pyais.messages import NMEAMessage\n'), ((8, 10, 8, 84), 'pyais.messages.NMEAMessage.from_string', 'NMEAMessage.from_string', ({(8, 34, 8, 83): '"""!AIVDM,1,1,,B,15M67FC000G?ufbE`FepT@3n00Sa,0*5C"""'}, {}), "('!AIVDM,1,1,,B,15M67FC000G?ufbE`FepT@3n00Sa,0*5C')", False, 'from pyais.messages import NMEAMessage\n')]
sercangul/HackerRank
30_days_of_code_10.py
e6d7056babe03baafee8d7f1cacdca7c28b72ded
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 3 19:02:33 2019 @author: sercangul """ def maxConsecutiveOnes(x): # Initialize result count = 0 # Count the number of iterations to # reach x = 0. while (x!=0): # This operation reduces length # of every sequence of 1s by one. x = (x & (x << 1)) count=count+1 return count if __name__ == '__main__': n = int(input()) result = maxConsecutiveOnes(n) print(result)
[]
artap-framework/artap
artap/algorithm_cmaes.py
7e4b01abbe5ca0fce9fa87a1a307ebd11ace36b4
import numpy as np from .problem import Problem from .algorithm_genetic import GeneralEvolutionaryAlgorithm from .individual import Individual from .operators import CustomGenerator, nondominated_truncate, RandomGenerator, UniformGenerator import time class CMA_ES(GeneralEvolutionaryAlgorithm): """ Implementation of CMA_ES, Covariance Matrix Adaptation Evolutionary strategy (CMA_ES). The Covariance Matrix Adaptation Evolution Strategy (CMA-ES) [1] is one of the most effective approaches for black-box optimization, in which objective functions cannot be specified explicitly in general. CMA-ES outperformed over 100 black-box optimization approaches for a variety of benchmark problems [2]. The CMA-ES algorithm selects solutions from a multivariate gaussian distribution. Following the evaluation of all solutions, the solutions are sorted by evaluation values, and the distribution parameters (i.e., the mean vector and the covariance matrix) are updated depending on the ranking of evaluation values. [1] Nikolaus Hansen and Andreas Ostermeier. Completely derandomized self-adaptation in evolution strategies. Evol. Comput., 9(2):159–195, June 2001. DOI: http://dx.doi.org/10.1162/106365601750190398. [2] Nikolaus Hansen. The CMA Evolution Strategy: A Comparing Review, pages 75–102. Springer Berlin Heidelberg, Berlin, Heidelberg, 2006. DOI: https://doi.org/10.1007/3-540-32494-1_4. """ def __init__(self, problem: Problem, name="Covariance Matrix Adaptation Evolutionary Strategy"): super().__init__(problem, name) # Population Size self.n_samples = self.options['max_population_size'] # Number of generation self.t = self.options['max_population_number'] self.individual_features['velocity'] = dict() self.individual_features['best_cost'] = dict() self.individual_features['best_vector'] = dict() self.individual_features['dominate'] = [] self.individual_features['crowding_distance'] = 0 self.individual_features['domination_counter'] = 0 # Add front_number feature self.individual_features['front_number'] = 0 self.dim_theta = len(self.problem.parameters) # Elite ratio percentage self.top_p = 30 # Range of values self.min_val = 0 self.max_val = 1 # Number of Runs self.runs = 1 self.theta_mean = np.random.uniform(self.min_val, self.max_val, self.dim_theta) # self.individuals = [] theta_std = np.random.uniform(self.max_val - 1, self.max_val, self.dim_theta) self.theta_cov = np.diag(theta_std) self.generator = CustomGenerator(self.problem.parameters, self.individual_features) # self.fit_gaussian() def fit_gaussian(self): """ generates individuals from a multivariate gaussian distribution :param :return population: list of individuals """ theta = np.random.multivariate_normal(self.theta_mean, self.theta_cov, self.options['max_population_size']) individuals = np.clip(theta, self.min_val, self.max_val) self.generator.init(individuals) individuals = self.generator.generate() return individuals def take_elite(self, candidates): """ Based on the fitness, it will take top individuals :param candidates :return elite: list of top individuals """ n_top = int((self.n_samples * self.top_p) / 100) elite = candidates[:n_top] return elite def compute_new_mean(self, e_candidates): """ Update distribution parameters. Here, the mean vector will be updated depending on the ranking of evaluation values. :param e_candidates :return new_means vector """ new_means = np.mean(e_candidates, axis=0) return new_means def compute_new_cov(self, e_candidates): """ Update distribution parameters. Here, the covariance matrix will be updated depending on the ranking of evaluation values :param e_candidates :return new_covariance matrix """ e_candidates = np.array(e_candidates) I = np.identity(self.dim_theta) cov = np.zeros((self.dim_theta, self.dim_theta)) for i in range(self.dim_theta): for j in range(self.dim_theta): cov[i, j] = np.sum( ((e_candidates[:, i] - self.theta_mean[i]) * (e_candidates[:, j] - self.theta_mean[j])), axis=0) return 1 / e_candidates.shape[0] * cov + I * 1e-3 def run(self): mean_fitness = [] best_fitness = [] worst_fitness = [] fitness = [] individuals = self.fit_gaussian() for individual in individuals: # append to problem self.problem.individuals.append(individual) # add to population individual.population_id = 0 self.problem.data_store.sync_individual(individual) self.evaluate(individuals) start = time.time() self.problem.logger.info("CMA_ES: {}/{}".format(self.options['max_population_number'], self.options['max_population_size'])) for it in range(self.options['max_population_number']): lists = [] for individual in individuals: # fitness.append(individual.costs) lists.append(individual.costs) lists = np.array(lists) mean_fitness.append(np.mean(lists)) best_fitness.append(np.min(lists)) worst_fitness.append(np.max(lists)) fitness.append(lists) elite = self.take_elite(individuals) e_candidates = [i.vector for i in elite] self.theta_cov = self.compute_new_cov(e_candidates) self.theta_mean = self.compute_new_mean(e_candidates) individuals = self.fit_gaussian() # individuals = nondominated_truncate(new_individuals, self.options['max_population_size']) self.evaluate(individuals) for individual in individuals: # add to population individual.population_id = it + 1 # append to problem self.problem.individuals.append(individual) # sync to datastore self.problem.data_store.sync_individual(individual) t = time.time() - start self.problem.logger.info("CMA_ES: elapsed time: {} s".format(t)) # sync changed individual informations self.problem.data_store.sync_all()
[((55, 26, 55, 87), 'numpy.random.uniform', 'np.random.uniform', ({(55, 44, 55, 56): 'self.min_val', (55, 58, 55, 70): 'self.max_val', (55, 72, 55, 86): 'self.dim_theta'}, {}), '(self.min_val, self.max_val, self.dim_theta)', True, 'import numpy as np\n'), ((57, 20, 57, 85), 'numpy.random.uniform', 'np.random.uniform', ({(57, 38, 57, 54): 'self.max_val - 1', (57, 56, 57, 68): 'self.max_val', (57, 70, 57, 84): 'self.dim_theta'}, {}), '(self.max_val - 1, self.max_val, self.dim_theta)', True, 'import numpy as np\n'), ((58, 25, 58, 43), 'numpy.diag', 'np.diag', ({(58, 33, 58, 42): 'theta_std'}, {}), '(theta_std)', True, 'import numpy as np\n'), ((68, 16, 68, 115), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', ({(68, 46, 68, 61): 'self.theta_mean', (68, 63, 68, 77): 'self.theta_cov', (68, 79, 68, 114): "self.options['max_population_size']"}, {}), "(self.theta_mean, self.theta_cov, self.options\n ['max_population_size'])", True, 'import numpy as np\n'), ((69, 22, 69, 64), 'numpy.clip', 'np.clip', ({(69, 30, 69, 35): 'theta', (69, 37, 69, 49): 'self.min_val', (69, 51, 69, 63): 'self.max_val'}, {}), '(theta, self.min_val, self.max_val)', True, 'import numpy as np\n'), ((92, 20, 92, 49), 'numpy.mean', 'np.mean', (), '', True, 'import numpy as np\n'), ((102, 23, 102, 45), 'numpy.array', 'np.array', ({(102, 32, 102, 44): 'e_candidates'}, {}), '(e_candidates)', True, 'import numpy as np\n'), ((103, 12, 103, 39), 'numpy.identity', 'np.identity', ({(103, 24, 103, 38): 'self.dim_theta'}, {}), '(self.dim_theta)', True, 'import numpy as np\n'), ((104, 14, 104, 56), 'numpy.zeros', 'np.zeros', ({(104, 23, 104, 55): '(self.dim_theta, self.dim_theta)'}, {}), '((self.dim_theta, self.dim_theta))', True, 'import numpy as np\n'), ((128, 16, 128, 27), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((136, 20, 136, 35), 'numpy.array', 'np.array', ({(136, 29, 136, 34): 'lists'}, {}), '(lists)', True, 'import numpy as np\n'), ((162, 12, 162, 23), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((107, 28, 108, 116), 'numpy.sum', 'np.sum', (), '', True, 'import numpy as np\n'), ((138, 32, 138, 46), 'numpy.mean', 'np.mean', ({(138, 40, 138, 45): 'lists'}, {}), '(lists)', True, 'import numpy as np\n'), ((139, 32, 139, 45), 'numpy.min', 'np.min', ({(139, 39, 139, 44): 'lists'}, {}), '(lists)', True, 'import numpy as np\n'), ((140, 33, 140, 46), 'numpy.max', 'np.max', ({(140, 40, 140, 45): 'lists'}, {}), '(lists)', True, 'import numpy as np\n')]
hagino3000/apns-proxy-client-py
apns_proxy_client/core.py
b5ce34be940a8f8a990dc369e293408380d0c359
# -*- coding: utf-8 -*- """ APNS Proxy Serverのクライアント """ import time import zmq import simplejson as json READ_TIMEOUT = 1500 # msec FLUSH_TIMEOUT = 5000 # msec COMMAND_ASK_ADDRESS = b'\1' COMMAND_SEND = b'\2' COMMAND_FEEDBACK = b'\3' DEVICE_TOKEN_LENGTH = 64 JSON_ALERT_KEY_SET = set(['body', 'action_loc_key', 'loc_key', 'loc_args', 'launch_image']) class APNSProxyClient(object): def __init__(self, host, port, application_id): """ ZMQコンテキストとソケットの初期化 """ if host is None or not isinstance(host, str): raise ValueError("host must be string") if port is None or not isinstance(port, int): raise ValueError("host must be int type") self.host = host self.port = port self.context = zmq.Context() self.context.setsockopt(zmq.LINGER, FLUSH_TIMEOUT) self.communicator = self.context.socket(zmq.REQ) self.publisher = self.context.socket(zmq.PUSH) self.connected = False if not isinstance(application_id, str): raise ValueError("application_id must be string type") self.application_id = application_id def __enter__(self): self.connect() def connect(self): """リモートサーバーへ接続""" if self.connected is False: self.communicator.connect(self.build_address(self.port)) push_port = self.get_push_port() self.publisher.connect(self.build_address(push_port)) self.connected = True def build_address(self, port): return "tcp://%s:%s" % (self.host, port) def get_push_port(self): """ PUSH-PULL接続用のポートを取得する """ self.communicator.send(COMMAND_ASK_ADDRESS) poller = zmq.Poller() poller.register(self.communicator, zmq.POLLIN) if poller.poll(READ_TIMEOUT): return self.communicator.recv() else: self.close() raise IOError("Cannot connect to APNs Proxy Server. Timeout!!") def send(self, token, alert, sound='default', badge=None, content_available=False, custom=None, expiry=None, priority=None, test=False): """ デバイストークンの送信 """ self._check_token(token) self._check_alert(alert) self._check_custom(custom) self.publisher.send(self._serialize( COMMAND_SEND, token, alert, sound, badge, content_available, custom, expiry, priority, test )) def get_feedback(self): data = { 'appid': self.application_id, } command = COMMAND_FEEDBACK + json.dumps(data, ensure_ascii=True) self.communicator.send(command) return json.loads(self.communicator.recv()) @staticmethod def _check_token(token): if len(token) != DEVICE_TOKEN_LENGTH: raise ValueError('Invalid token length %s' % token) @staticmethod def _check_alert(alert): if (alert is None or isinstance(alert, basestring)): return elif isinstance(alert, dict): if len(set(alert.keys()) - JSON_ALERT_KEY_SET) > 0: raise ValueError('JSON Alert allows only' 'body, action_loc_key, loc_key, loc_args, launch_image') else: raise ValueError('alert must be string, unicode or dict type') @staticmethod def _check_custom(custom): if custom is None or isinstance(custom, dict): return raise ValueError('custom must be dict type') def _serialize(self, command, token, alert, sound, badge, content_available, custom, expiry, priority, test): """ 送信データのフォーマット """ aps = {} if alert is not None: aps['alert'] = alert if sound is not None: aps['sound'] = sound if badge is not None: aps['badge'] = badge if content_available is True: aps['content_available'] = True if custom is not None: aps['custom'] = custom data = { 'appid': self.application_id, 'token': token, 'aps': aps, 'test': test } if expiry is not None: data['expiry'] = expiry if priority is not None: data['priority'] = priority return command + json.dumps(data, ensure_ascii=True) def __exit__(self, exc_type, exc_value, traceback): if exc_type: self._close() return False self.close() def close(self): start_time = time.time() self._close() end_time = time.time() if (end_time - start_time) > (FLUSH_TIMEOUT - 20)/1000.0: raise IOError('Timeout close operation. Some messages may not reached to server.') return True def _close(self): self.publisher.close() self.communicator.close() self.context.term()
[((35, 23, 35, 36), 'zmq.Context', 'zmq.Context', ({}, {}), '()', False, 'import zmq\n'), ((65, 17, 65, 29), 'zmq.Poller', 'zmq.Poller', ({}, {}), '()', False, 'import zmq\n'), ((153, 21, 153, 32), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((155, 19, 155, 30), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((90, 37, 90, 72), 'simplejson.dumps', 'json.dumps', (), '', True, 'import simplejson as json\n'), ((144, 25, 144, 60), 'simplejson.dumps', 'json.dumps', (), '', True, 'import simplejson as json\n')]
svetlanama/snowball
003_joint_probabilities.py
a41865a866dae124b4a22134f091a7d09bd0896e
import sys sys.path.insert(0, '..') import numpy import time import ConfigParser import topicmodel def main(): # read configuration file config = ConfigParser.ConfigParser() config.readfp(open('config.ini')) dataDir = config.get('main', 'dataDir') io = topicmodel.io(dataDir) model = topicmodel.model(dataDir) wordDictionary = io.load_csv_as_dict('out-word-dictionary-rare-words-excluded.csv') model.set_word_dictionary(wordDictionary) # print wordDictionary # return wwcovar=model.coccurences('tmp-all-paper-tokens.csv','+','.') numpy.save(dataDir + '/tmp-joint-probabilities.npy', wwcovar) return if __name__ == "__main__": t0 = time.time() main() t1 = time.time() print "finished" print "time=", t1 - t0
[]
FirebirdSQL/firebird-qa
tests/bugs/core_4318_test.py
96af2def7f905a06f178e2a80a2c8be4a4b44782
#coding:utf-8 # # id: bugs.core_4318 # title: Regression: Predicates involving PSQL variables/parameters are not pushed inside the aggregation # decription: # tracker_id: CORE-4318 # min_versions: ['3.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0 # resources: None substitutions_1 = [] init_script_1 = """ recreate table t2 ( id integer not null, t1_id integer ); commit; recreate table t1 ( id integer not null ); commit; set term ^; execute block as declare variable i integer = 0; begin while (i < 1000) do begin i = i + 1; insert into t2(id, t1_id) values(:i, mod(:i, 10)); merge into t1 using ( select mod(:i, 10) as f from rdb$database ) src on t1.id = src.f when not matched then insert (id) values(src.f); end -- while (i < 1000) do begin end^ set term ;^ commit; alter table t1 add constraint pk_t1 primary key (id); alter table t2 add constraint pk_t2 primary key (id); alter table t2 add constraint fk_t2_ref_t1 foreign key (t1_id) references t1(id); commit; """ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1) test_script_1 = """ set explain on; set planonly; set term ^; execute block returns ( s integer ) as declare variable v integer = 1; begin with t as ( select t1_id as t1_id, sum(id) as s from t2 group by 1 ) select s from t where t1_id = :v into :s; suspend; end ^ set term ;^ -- In 3.0.0.30837 plan was: -- Select Expression -- -> Singularity Check -- -> Filter -- -> Aggregate -- -> Table "T T2" Access By ID -- -> Index "FK_T2_REF_T1" Scan -- (i.e. there was NO "Filter" between "Aggregate" and "Table "T T2" Access By ID") """ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ Select Expression -> Singularity Check -> Filter -> Aggregate -> Filter -> Table "T2" as "T T2" Access By ID -> Index "FK_T2_REF_T1" Range Scan (full match) """ @pytest.mark.version('>=3.0') def test_1(act_1: Action): act_1.expected_stdout = expected_stdout_1 act_1.execute() assert act_1.clean_stdout == act_1.clean_expected_stdout
[((60, 7, 60, 68), 'firebird.qa.db_factory', 'db_factory', (), '', False, 'from firebird.qa import db_factory, isql_act, Action\n'), ((98, 8, 98, 70), 'firebird.qa.isql_act', 'isql_act', (), '', False, 'from firebird.qa import db_factory, isql_act, Action\n'), ((110, 1, 110, 29), 'pytest.mark.version', 'pytest.mark.version', ({(110, 21, 110, 28): '""">=3.0"""'}, {}), "('>=3.0')", False, 'import pytest\n')]
WilliamHackspeare/profanity-percentage
dictionary.py
4aab708620b7543a2a5cb30c9cee8404dcc836cb
#Import the json library to parse JSON file to Python import json #Import list of punctuation characters from the string library from string import punctuation as p #This method checks if the given word is a profanity def is_profanity(word): #Open the JSON file words_file = open('data.json') #Parse the JSON file as a dictionary and extract the values bad_words = json.load(words_file).values() #Check and return if the word is a bad work return word in bad_words #This method calculates the degree of profanity for a list of strings def calculate_profanity(sentence): #Initialise the count of bad words count_bad = 0 #Initialise the total count of words count = 0 #Loop through the list of words for word in sentence: #Check if the word, stripped of any leading or trailing punctuations or spaces, is a bad word and update count if is_profanity(word.strip(p+" ")): count_bad += 1 count += 1 #Calculate the degree of the list deg = (count_bad/count)*100 #Return the degree return deg
[((14, 14, 14, 35), 'json.load', 'json.load', ({(14, 24, 14, 34): 'words_file'}, {}), '(words_file)', False, 'import json\n')]
cyfrmedia/cerridwen
setup.py
6ac9193d41d7c6fdea0abab5e5f207132844fb4e
from setuptools import setup import os here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() #NEWS = open(os.path.join(here, 'NEWS.txt')).read() rootdir = os.path.dirname(os.path.abspath(__file__)) exec(open(rootdir + '/cerridwen/version.py').read()) version = __VERSION__ setup(name='cerridwen', version=version, description='Accurate solar system data for everyone', long_description=README, author='Leslie P. Polzer', author_email='[email protected]', url='http://cerridwen.bluemagician.vc/', license='MIT', classifiers=[ # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers "Development Status :: 4 - Beta" , "Environment :: Console" , "Intended Audience :: Science/Research" , "Intended Audience :: Developers" , "License :: OSI Approved :: MIT License" , "Operating System :: OS Independent" , "Programming Language :: Python :: 3" , "Topic :: Scientific/Engineering :: Astronomy" , "Topic :: Other/Nonlisted Topic" , "Topic :: Software Development :: Libraries :: Python Modules" , "Topic :: Utilities" ], maintainer='Leslie P. Polzer', maintainer_email='[email protected]', packages=['cerridwen'], requires=['pyswisseph', 'numpy', 'astropy(>=0.4)'], extras_require={'Flask':['flask']}, entry_points={ 'console_scripts': ['cerridwen = cerridwen.cli:main', 'cerridwen-server = cerridwen.api_server:main [Flask]'] })
[((12, 0, 43, 8), 'setuptools.setup', 'setup', (), '', False, 'from setuptools import setup\n'), ((4, 23, 4, 48), 'os.path.dirname', 'os.path.dirname', ({(4, 39, 4, 47): '__file__'}, {}), '(__file__)', False, 'import os\n'), ((8, 26, 8, 51), 'os.path.abspath', 'os.path.abspath', ({(8, 42, 8, 50): '__file__'}, {}), '(__file__)', False, 'import os\n'), ((5, 14, 5, 46), 'os.path.join', 'os.path.join', ({(5, 27, 5, 31): 'here', (5, 33, 5, 45): '"""README.rst"""'}, {}), "(here, 'README.rst')", False, 'import os\n')]
JoachimFlottorp/pajbot
pajbot/apiwrappers/authentication/access_token.py
4fb88c403dedb20d95be80e38da72be1ed064901
import datetime from abc import ABC, abstractmethod import pajbot class AccessToken(ABC): SHOULD_REFRESH_THRESHOLD = 0.9 """Fraction between 0 and 1 indicating what fraction/percentage of the specified full validity period should actually be utilized. E.g. if this is set to 0.9, the implementation will refresh the token once at least 90% of the full validity period (expires_in) is over.""" def __init__(self, access_token, created_at, expires_in, token_type, refresh_token, scope): self.access_token = access_token self.created_at = created_at # can both be None self.expires_in = expires_in if self.expires_in is not None: self.expires_at = self.created_at + self.expires_in else: self.expires_at = None self.token_type = token_type # can be None self.refresh_token = refresh_token # always a list, can be empty list self.scope = scope @abstractmethod def can_refresh(self): pass def should_refresh(self): """Returns True if less than 10% of the token's lifetime remains, False otherwise""" if not self.can_refresh(): return False # intended lifetime of the token if self.expires_at is not None: expires_after = self.expires_at - self.created_at else: # this is a token that never expires # because we don't want any issues, refresh it anyways expires_after = datetime.timedelta(hours=1) # how much time has passed since token creation token_age = pajbot.utils.now() - self.created_at # maximum token age before token should be refreshed (90% of the total token lifetime) max_token_age = expires_after * self.SHOULD_REFRESH_THRESHOLD # expired? return token_age >= max_token_age def jsonify(self): """serialize for storage""" if self.expires_in is None: expires_in_milliseconds = None else: expires_in_milliseconds = self.expires_in.total_seconds() * 1000 return { "access_token": self.access_token, "created_at": self.created_at.timestamp() * 1000, "expires_in": expires_in_milliseconds, "token_type": self.token_type, "refresh_token": self.refresh_token, "scope": self.scope, } @classmethod def from_json(cls, json_data): """deserialize json produced by jsonify()""" if json_data["expires_in"] is None: expires_in = None else: expires_in = datetime.timedelta(milliseconds=json_data["expires_in"]) return cls( access_token=json_data["access_token"], created_at=pajbot.utils.datetime_from_utc_milliseconds(json_data["created_at"]), expires_in=expires_in, token_type=json_data["token_type"], refresh_token=json_data["refresh_token"], scope=json_data["scope"], ) @classmethod def from_api_response(cls, response): """Construct new object from twitch response json data""" # expires_in is only missing for old Client-IDs to which twitch will respond with # infinitely-lived tokens (the "expires_in" field is absent in that case). expires_in_seconds = response.get("expires_in", None) if expires_in_seconds is None: expires_in = None else: expires_in = datetime.timedelta(seconds=expires_in_seconds) return cls( access_token=response["access_token"], created_at=pajbot.utils.now(), expires_in=expires_in, token_type=response["token_type"], refresh_token=response.get("refresh_token", None), scope=response.get("scope", []), ) @abstractmethod def refresh(self, api): pass class UserAccessToken(AccessToken): def can_refresh(self): return self.refresh_token is not None def refresh(self, api): if not self.can_refresh(): raise ValueError("This user access token cannot be refreshed, it has no refresh token") return api.refresh_user_access_token(self.refresh_token) @staticmethod def from_implicit_auth_flow_token(access_token): return UserAccessToken( access_token=access_token, created_at=None, expires_in=None, token_type="bearer", refresh_token=None, scope=[], ) class AppAccessToken(AccessToken): def can_refresh(self): return True def refresh(self, api): return api.get_app_access_token(self.scope)
[((50, 28, 50, 55), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((53, 20, 53, 38), 'pajbot.utils.now', 'pajbot.utils.now', ({}, {}), '()', False, 'import pajbot\n'), ((83, 25, 83, 81), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((104, 25, 104, 71), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((87, 23, 87, 91), 'pajbot.utils.datetime_from_utc_milliseconds', 'pajbot.utils.datetime_from_utc_milliseconds', ({(87, 67, 87, 90): "json_data['created_at']"}, {}), "(json_data['created_at'])", False, 'import pajbot\n'), ((108, 23, 108, 41), 'pajbot.utils.now', 'pajbot.utils.now', ({}, {}), '()', False, 'import pajbot\n')]
RadicalAjay/Ghost_data
GHOST.py
b151b0b92d27c3b8454e28d4f037eafb587d7b23
#! /usr/bin/python3 # Description: Data_Ghost, concealing data into spaces and tabs making it imperceptable to human eyes. # Author: Ajay Dyavathi # Github: Radical Ajay class Ghost(): def __init__(self, file_name, output_format='txt'): ''' Converts ascii text to spaces and tabs ''' self.file_name = file_name self.output_format = output_format def ascii2bin(self, asc): ''' Converting ascii to bianry ''' return ''.join('{:08b}'.format(ord(i)) for i in asc) def bin2ascii(self, bid): ''' Converting binary to ascii ''' return ''.join(chr(int(bid[i:i + 8], 2)) for i in range(0, len(bid), 8)) def ghost(self, filename): ''' Ghosting data converting it to spaces and tabs ''' with open(filename, 'w') as out_f: with open(self.file_name, 'r') as in_f: for in_data in in_f.readlines(): bin_data = self.ascii2bin(in_data) out_data = bin_data.replace('1', '\t') out_data = out_data.replace('0', ' ') out_f.write(out_data) def unghost(self, in_filename, out_filename): ''' Unghosting data converting back from spaces and tabs to human-readable text ''' with open(out_filename, 'w') as out_f: with open(in_filename, 'r') as in_f: for line in in_f.readlines(): line = line.replace('\t', '1') line = line.replace(' ', '0') out_f.write(self.bin2ascii(line)) # USAGE: # ghoster = Ghost('data.txt') # ghoster.ghost('ghosted.txt') # ghoster.unghost('ghosted.txt', 'unghosted.txt')
[]
ychu196/chicago_scan
scan_predict.py
ed5f32a9f27fd5b9350cb3232a2631c3aaa60744
# Image classification using AWS Sagemaker and Linear Learner # Program set up and import libraries import numpy as np import pandas as pd import os from sagemaker import get_execution_role role = get_execution_role() bucket = 'chi-hackathon-skin-images' # Import Data import boto3 from sagemaker import get_execution_role role = get_execution_role() bucket='chi-hackathon-skin-images' data_key = 'ISIC_0000000.json' # need a way to go through entire library data_location = 's3://{}/{}'.format(bucket, data_key) metadata_set = pd.read_json(data_location) image_set = np.asarray(data_location) # TBD - transform json data to array # TBD - transform image data to dataframe train_set = zip(image_set, metadata_set) # Split Data into Train and Validate import random random.seed(9001) split = np.random.rand(len(df)) < 0.8 valid_set = train_set[split] train_set = train_set[~split] # Train Model import boto import sagemaker data_location = 's3://{}/linearlearner_highlevel_example/data'.format(bucket) output_location = 's3://{}/linearlearner_highlevel_example/output'.format(bucket) print('training data will be uploaded to: {}'.format(data_location)) print('training artifacts will be uploaded to: {}'.format(output_location)) sess = sagemaker.Session() linear = sagemaker.estimator.Estimator(container, role, train_instance_count=1, rain_instance_type='ml.c4.xlarge', output_path=output_location, sagemaker_session=sess) linear.set_hyperparameters(feature_dim=784, predictor_type='binary_classifier', mini_batch_size=200) linear.fit({'train': train_set}) # Deploy Model linear_predictor = linear.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge') # Validate from sagemaker.predictor import csv_serializer, json_deserializer linear_predictor.content_type = 'text/csv' linear_predictor.serializer = csv_serializer linear_predictor.deserializer = json_deserializer result = linear_predictor.predict(train_set[0][30:31]) print(result)
[((9, 7, 9, 27), 'sagemaker.get_execution_role', 'get_execution_role', ({}, {}), '()', False, 'from sagemaker import get_execution_role\n'), ((16, 7, 16, 27), 'sagemaker.get_execution_role', 'get_execution_role', ({}, {}), '()', False, 'from sagemaker import get_execution_role\n'), ((21, 15, 21, 42), 'pandas.read_json', 'pd.read_json', ({(21, 28, 21, 41): 'data_location'}, {}), '(data_location)', True, 'import pandas as pd\n'), ((22, 12, 22, 37), 'numpy.asarray', 'np.asarray', ({(22, 23, 22, 36): 'data_location'}, {}), '(data_location)', True, 'import numpy as np\n'), ((30, 0, 30, 17), 'random.seed', 'random.seed', ({(30, 12, 30, 16): '(9001)'}, {}), '(9001)', False, 'import random\n'), ((44, 7, 44, 26), 'sagemaker.Session', 'sagemaker.Session', ({}, {}), '()', False, 'import sagemaker\n'), ((46, 9, 47, 56), 'sagemaker.estimator.Estimator', 'sagemaker.estimator.Estimator', (), '', False, 'import sagemaker\n')]
FixturFab/pcb-tools
gerber/am_statements.py
7b8d1c6ccd9c242c162ede47557bb816233cf66f
#!/usr/bin/env python # -*- coding: utf-8 -*- # copyright 2015 Hamilton Kibbe <[email protected]> and Paulo Henrique Silva # <[email protected]> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from math import asin import math from .primitives import * from .utils import validate_coordinates, inch, metric, rotate_point # TODO: Add support for aperture macro variables __all__ = ['AMPrimitive', 'AMCommentPrimitive', 'AMCirclePrimitive', 'AMVectorLinePrimitive', 'AMOutlinePrimitive', 'AMPolygonPrimitive', 'AMMoirePrimitive', 'AMThermalPrimitive', 'AMCenterLinePrimitive', 'AMLowerLeftLinePrimitive', 'AMUnsupportPrimitive'] class AMPrimitive(object): """ Aperture Macro Primitive Base Class Parameters ---------- code : int primitive shape code exposure : str on or off Primitives with exposure on create a slid part of the macro aperture, and primitives with exposure off erase the solid part created previously in the aperture macro definition. .. note:: The erasing effect is limited to the aperture definition in which it occurs. Returns ------- primitive : :class: `gerber.am_statements.AMPrimitive` Raises ------ TypeError, ValueError """ def __init__(self, code, exposure=None): VALID_CODES = (0, 1, 2, 4, 5, 6, 7, 20, 21, 22, 9999) if not isinstance(code, int): raise TypeError('Aperture Macro Primitive code must be an integer') elif code not in VALID_CODES: raise ValueError('Invalid Code. Valid codes are %s.' % ', '.join(map(str, VALID_CODES))) if exposure is not None and exposure.lower() not in ('on', 'off'): raise ValueError('Exposure must be either on or off') self.code = code self.exposure = exposure.lower() if exposure is not None else None def to_inch(self): raise NotImplementedError('Subclass must implement `to-inch`') def to_metric(self): raise NotImplementedError('Subclass must implement `to-metric`') @property def _level_polarity(self): if self.exposure == 'off': return 'clear' return 'dark' def to_primitive(self, units): """ Return a Primitive instance based on the specified macro params. """ print('Rendering {}s is not supported yet.'.format(str(self.__class__))) def __eq__(self, other): return self.__dict__ == other.__dict__ class AMCommentPrimitive(AMPrimitive): """ Aperture Macro Comment primitive. Code 0 The comment primitive has no image meaning. It is used to include human- readable comments into the AM command. .. seealso:: `The Gerber File Format Specification <http://www.ucamco.com/files/downloads/file/81/the_gerber_file_format_specification.pdf>`_ **Section 4.12.3.1:** Comment, primitive code 0 Parameters ---------- code : int Aperture Macro primitive code. 0 Indicates an AMCommentPrimitive comment : str The comment as a string. Returns ------- CommentPrimitive : :class:`gerbers.am_statements.AMCommentPrimitive` An Initialized AMCommentPrimitive Raises ------ ValueError """ @classmethod def from_gerber(cls, primitive): primitive = primitive.strip() code = int(primitive[0]) comment = primitive[1:] return cls(code, comment) def __init__(self, code, comment): if code != 0: raise ValueError('Not a valid Aperture Macro Comment statement') super(AMCommentPrimitive, self).__init__(code) self.comment = comment.strip(' *') def to_inch(self): pass def to_metric(self): pass def to_gerber(self, settings=None): return '0 %s *' % self.comment def to_primitive(self, units): """ Returns None - has not primitive representation """ return None def __str__(self): return '<Aperture Macro Comment: %s>' % self.comment class AMCirclePrimitive(AMPrimitive): """ Aperture macro Circle primitive. Code 1 A circle primitive is defined by its center point and diameter. .. seealso:: `The Gerber File Format Specification <http://www.ucamco.com/files/downloads/file/81/the_gerber_file_format_specification.pdf>`_ **Section 4.12.3.2:** Circle, primitive code 1 Parameters ---------- code : int Circle Primitive code. Must be 1 exposure : string 'on' or 'off' diameter : float Circle diameter position : tuple (<float>, <float>) Position of the circle relative to the macro origin Returns ------- CirclePrimitive : :class:`gerbers.am_statements.AMCirclePrimitive` An initialized AMCirclePrimitive Raises ------ ValueError, TypeError """ @classmethod def from_gerber(cls, primitive): modifiers = primitive.strip(' *').split(',') code = int(modifiers[0]) exposure = 'on' if float(modifiers[1]) == 1 else 'off' diameter = float(modifiers[2]) position = (float(modifiers[3]), float(modifiers[4])) return cls(code, exposure, diameter, position) @classmethod def from_primitive(cls, primitive): return cls(1, 'on', primitive.diameter, primitive.position) def __init__(self, code, exposure, diameter, position): validate_coordinates(position) if code != 1: raise ValueError('CirclePrimitive code is 1') super(AMCirclePrimitive, self).__init__(code, exposure) self.diameter = diameter self.position = position def to_inch(self): self.diameter = inch(self.diameter) self.position = tuple([inch(x) for x in self.position]) def to_metric(self): self.diameter = metric(self.diameter) self.position = tuple([metric(x) for x in self.position]) def to_gerber(self, settings=None): data = dict(code=self.code, exposure='1' if self.exposure == 'on' else 0, diameter=self.diameter, x=self.position[0], y=self.position[1]) return '{code},{exposure},{diameter},{x},{y}*'.format(**data) def to_primitive(self, units): return Circle((self.position), self.diameter, units=units, level_polarity=self._level_polarity) class AMVectorLinePrimitive(AMPrimitive): """ Aperture Macro Vector Line primitive. Code 2 or 20. A vector line is a rectangle defined by its line width, start, and end points. The line ends are rectangular. .. seealso:: `The Gerber File Format Specification <http://www.ucamco.com/files/downloads/file/81/the_gerber_file_format_specification.pdf>`_ **Section 4.12.3.3:** Vector Line, primitive code 2 or 20. Parameters ---------- code : int Vector Line Primitive code. Must be either 2 or 20. exposure : string 'on' or 'off' width : float Line width start : tuple (<float>, <float>) coordinate of line start point end : tuple (<float>, <float>) coordinate of line end point rotation : float Line rotation about the origin. Returns ------- LinePrimitive : :class:`gerbers.am_statements.AMVectorLinePrimitive` An initialized AMVectorLinePrimitive Raises ------ ValueError, TypeError """ @classmethod def from_primitive(cls, primitive): return cls(2, 'on', primitive.aperture.width, primitive.start, primitive.end, 0) @classmethod def from_gerber(cls, primitive): modifiers = primitive.strip(' *').split(',') code = int(modifiers[0]) exposure = 'on' if float(modifiers[1]) == 1 else 'off' width = float(modifiers[2]) start = (float(modifiers[3]), float(modifiers[4])) end = (float(modifiers[5]), float(modifiers[6])) rotation = float(modifiers[7]) return cls(code, exposure, width, start, end, rotation) def __init__(self, code, exposure, width, start, end, rotation): validate_coordinates(start) validate_coordinates(end) if code not in (2, 20): raise ValueError('VectorLinePrimitive codes are 2 or 20') super(AMVectorLinePrimitive, self).__init__(code, exposure) self.width = width self.start = start self.end = end self.rotation = rotation def to_inch(self): self.width = inch(self.width) self.start = tuple([inch(x) for x in self.start]) self.end = tuple([inch(x) for x in self.end]) def to_metric(self): self.width = metric(self.width) self.start = tuple([metric(x) for x in self.start]) self.end = tuple([metric(x) for x in self.end]) def to_gerber(self, settings=None): fmtstr = '{code},{exp},{width},{startx},{starty},{endx},{endy},{rotation}*' data = dict(code=self.code, exp=1 if self.exposure == 'on' else 0, width=self.width, startx=self.start[0], starty=self.start[1], endx=self.end[0], endy=self.end[1], rotation=self.rotation) return fmtstr.format(**data) def to_primitive(self, units): """ Convert this to a primitive. We use the Outline to represent this (instead of Line) because the behaviour of the end caps is different for aperture macros compared to Lines when rotated. """ # Use a line to generate our vertices easily line = Line(self.start, self.end, Rectangle(None, self.width, self.width)) vertices = line.vertices aperture = Circle((0, 0), 0) lines = [] prev_point = rotate_point(vertices[-1], self.rotation, (0, 0)) for point in vertices: cur_point = rotate_point(point, self.rotation, (0, 0)) lines.append(Line(prev_point, cur_point, aperture)) return Outline(lines, units=units, level_polarity=self._level_polarity) class AMOutlinePrimitive(AMPrimitive): """ Aperture Macro Outline primitive. Code 4. An outline primitive is an area enclosed by an n-point polygon defined by its start point and n subsequent points. The outline must be closed, i.e. the last point must be equal to the start point. Self intersecting outlines are not allowed. .. seealso:: `The Gerber File Format Specification <http://www.ucamco.com/files/downloads/file/81/the_gerber_file_format_specification.pdf>`_ **Section 4.12.3.6:** Outline, primitive code 4. Parameters ---------- code : int OutlinePrimitive code. Must be 6. exposure : string 'on' or 'off' start_point : tuple (<float>, <float>) coordinate of outline start point points : list of tuples (<float>, <float>) coordinates of subsequent points rotation : float outline rotation about the origin. Returns ------- OutlinePrimitive : :class:`gerber.am_statements.AMOutlineinePrimitive` An initialized AMOutlinePrimitive Raises ------ ValueError, TypeError """ @classmethod def from_primitive(cls, primitive): start_point = (round(primitive.primitives[0].start[0], 6), round(primitive.primitives[0].start[1], 6)) points = [] for prim in primitive.primitives: points.append((round(prim.end[0], 6), round(prim.end[1], 6))) rotation = 0.0 return cls(4, 'on', start_point, points, rotation) @classmethod def from_gerber(cls, primitive): modifiers = primitive.strip(' *').split(",") code = int(modifiers[0]) exposure = "on" if float(modifiers[1]) == 1 else "off" n = int(float(modifiers[2])) start_point = (float(modifiers[3]), float(modifiers[4])) points = [] for i in range(n): points.append((float(modifiers[5 + i * 2]), float(modifiers[5 + i * 2 + 1]))) rotation = float(modifiers[-1]) return cls(code, exposure, start_point, points, rotation) def __init__(self, code, exposure, start_point, points, rotation): """ Initialize AMOutlinePrimitive """ validate_coordinates(start_point) for point in points: validate_coordinates(point) if code != 4: raise ValueError('OutlinePrimitive code is 4') super(AMOutlinePrimitive, self).__init__(code, exposure) self.start_point = start_point if points[-1] != start_point: raise ValueError('OutlinePrimitive must be closed') self.points = points self.rotation = rotation def to_inch(self): self.start_point = tuple([inch(x) for x in self.start_point]) self.points = tuple([(inch(x), inch(y)) for x, y in self.points]) def to_metric(self): self.start_point = tuple([metric(x) for x in self.start_point]) self.points = tuple([(metric(x), metric(y)) for x, y in self.points]) def to_gerber(self, settings=None): data = dict( code=self.code, exposure="1" if self.exposure == "on" else "0", n_points=len(self.points), start_point="%.6g,%.6g" % self.start_point, points=",\n".join(["%.6g,%.6g" % point for point in self.points]), rotation=str(self.rotation) ) return "{code},{exposure},{n_points},{start_point},{points},{rotation}*".format(**data) def to_primitive(self, units): """ Convert this to a drawable primitive. This uses the Outline instead of Line primitive to handle differences in end caps when rotated. """ lines = [] prev_point = rotate_point(self.start_point, self.rotation) for point in self.points: cur_point = rotate_point(point, self.rotation) lines.append(Line(prev_point, cur_point, Circle((0,0), 0))) prev_point = cur_point if lines[0].start != lines[-1].end: raise ValueError('Outline must be closed') return Outline(lines, units=units, level_polarity=self._level_polarity) class AMPolygonPrimitive(AMPrimitive): """ Aperture Macro Polygon primitive. Code 5. A polygon primitive is a regular polygon defined by the number of vertices, the center point, and the diameter of the circumscribed circle. .. seealso:: `The Gerber File Format Specification <http://www.ucamco.com/files/downloads/file/81/the_gerber_file_format_specification.pdf>`_ **Section 4.12.3.8:** Polygon, primitive code 5. Parameters ---------- code : int PolygonPrimitive code. Must be 5. exposure : string 'on' or 'off' vertices : int, 3 <= vertices <= 12 Number of vertices position : tuple (<float>, <float>) X and Y coordinates of polygon center diameter : float diameter of circumscribed circle. rotation : float polygon rotation about the origin. Returns ------- PolygonPrimitive : :class:`gerbers.am_statements.AMPolygonPrimitive` An initialized AMPolygonPrimitive Raises ------ ValueError, TypeError """ @classmethod def from_primitive(cls, primitive): return cls(5, 'on', primitive.sides, primitive.position, primitive.diameter, primitive.rotation) @classmethod def from_gerber(cls, primitive): modifiers = primitive.strip(' *').split(",") code = int(modifiers[0]) exposure = "on" if float(modifiers[1]) == 1 else "off" vertices = int(float(modifiers[2])) position = (float(modifiers[3]), float(modifiers[4])) try: diameter = float(modifiers[5]) except: diameter = 0 rotation = float(modifiers[6]) return cls(code, exposure, vertices, position, diameter, rotation) def __init__(self, code, exposure, vertices, position, diameter, rotation): """ Initialize AMPolygonPrimitive """ if code != 5: raise ValueError('PolygonPrimitive code is 5') super(AMPolygonPrimitive, self).__init__(code, exposure) if vertices < 3 or vertices > 12: raise ValueError('Number of vertices must be between 3 and 12') self.vertices = vertices validate_coordinates(position) self.position = position self.diameter = diameter self.rotation = rotation def to_inch(self): self.position = tuple([inch(x) for x in self.position]) self.diameter = inch(self.diameter) def to_metric(self): self.position = tuple([metric(x) for x in self.position]) self.diameter = metric(self.diameter) def to_gerber(self, settings=None): data = dict( code=self.code, exposure="1" if self.exposure == "on" else "0", vertices=self.vertices, position="%.4g,%.4g" % self.position, diameter='%.4g' % self.diameter, rotation=str(self.rotation) ) fmt = "{code},{exposure},{vertices},{position},{diameter},{rotation}*" return fmt.format(**data) def to_primitive(self, units): return Polygon(self.position, self.vertices, self.diameter / 2.0, 0, rotation=math.radians(self.rotation), units=units, level_polarity=self._level_polarity) class AMMoirePrimitive(AMPrimitive): """ Aperture Macro Moire primitive. Code 6. The moire primitive is a cross hair centered on concentric rings (annuli). Exposure is always on. .. seealso:: `The Gerber File Format Specification <http://www.ucamco.com/files/downloads/file/81/the_gerber_file_format_specification.pdf>`_ **Section 4.12.3.9:** Moire, primitive code 6. Parameters ---------- code : int Moire Primitive code. Must be 6. position : tuple (<float>, <float>) X and Y coordinates of moire center diameter : float outer diameter of outer ring. ring_thickness : float thickness of concentric rings. gap : float gap between concentric rings. max_rings : float maximum number of rings crosshair_thickness : float thickness of crosshairs crosshair_length : float length of crosshairs rotation : float moire rotation about the origin. Returns ------- MoirePrimitive : :class:`gerbers.am_statements.AMMoirePrimitive` An initialized AMMoirePrimitive Raises ------ ValueError, TypeError """ @classmethod def from_gerber(cls, primitive): modifiers = primitive.strip(' *').split(",") code = int(modifiers[0]) position = (float(modifiers[1]), float(modifiers[2])) diameter = float(modifiers[3]) ring_thickness = float(modifiers[4]) gap = float(modifiers[5]) max_rings = int(float(modifiers[6])) crosshair_thickness = float(modifiers[7]) crosshair_length = float(modifiers[8]) rotation = float(modifiers[9]) return cls(code, position, diameter, ring_thickness, gap, max_rings, crosshair_thickness, crosshair_length, rotation) def __init__(self, code, position, diameter, ring_thickness, gap, max_rings, crosshair_thickness, crosshair_length, rotation): """ Initialize AMoirePrimitive """ if code != 6: raise ValueError('MoirePrimitive code is 6') super(AMMoirePrimitive, self).__init__(code, 'on') validate_coordinates(position) self.position = position self.diameter = diameter self.ring_thickness = ring_thickness self.gap = gap self.max_rings = max_rings self.crosshair_thickness = crosshair_thickness self.crosshair_length = crosshair_length self.rotation = rotation def to_inch(self): self.position = tuple([inch(x) for x in self.position]) self.diameter = inch(self.diameter) self.ring_thickness = inch(self.ring_thickness) self.gap = inch(self.gap) self.crosshair_thickness = inch(self.crosshair_thickness) self.crosshair_length = inch(self.crosshair_length) def to_metric(self): self.position = tuple([metric(x) for x in self.position]) self.diameter = metric(self.diameter) self.ring_thickness = metric(self.ring_thickness) self.gap = metric(self.gap) self.crosshair_thickness = metric(self.crosshair_thickness) self.crosshair_length = metric(self.crosshair_length) def to_gerber(self, settings=None): data = dict( code=self.code, position="%.4g,%.4g" % self.position, diameter=self.diameter, ring_thickness=self.ring_thickness, gap=self.gap, max_rings=self.max_rings, crosshair_thickness=self.crosshair_thickness, crosshair_length=self.crosshair_length, rotation=self.rotation ) fmt = "{code},{position},{diameter},{ring_thickness},{gap},{max_rings},{crosshair_thickness},{crosshair_length},{rotation}*" return fmt.format(**data) def to_primitive(self, units): #raise NotImplementedError() return None class AMThermalPrimitive(AMPrimitive): """ Aperture Macro Thermal primitive. Code 7. The thermal primitive is a ring (annulus) interrupted by four gaps. Exposure is always on. .. seealso:: `The Gerber File Format Specification <http://www.ucamco.com/files/downloads/file/81/the_gerber_file_format_specification.pdf>`_ **Section 4.12.3.10:** Thermal, primitive code 7. Parameters ---------- code : int Thermal Primitive code. Must be 7. position : tuple (<float>, <float>) X and Y coordinates of thermal center outer_diameter : float outer diameter of thermal. inner_diameter : float inner diameter of thermal. gap : float gap thickness rotation : float thermal rotation about the origin. Returns ------- ThermalPrimitive : :class:`gerbers.am_statements.AMThermalPrimitive` An initialized AMThermalPrimitive Raises ------ ValueError, TypeError """ @classmethod def from_gerber(cls, primitive): modifiers = primitive.strip(' *').split(",") code = int(modifiers[0]) position = (float(modifiers[1]), float(modifiers[2])) outer_diameter = float(modifiers[3]) inner_diameter = float(modifiers[4]) gap = float(modifiers[5]) rotation = float(modifiers[6]) return cls(code, position, outer_diameter, inner_diameter, gap, rotation) def __init__(self, code, position, outer_diameter, inner_diameter, gap, rotation): if code != 7: raise ValueError('ThermalPrimitive code is 7') super(AMThermalPrimitive, self).__init__(code, 'on') validate_coordinates(position) self.position = position self.outer_diameter = outer_diameter self.inner_diameter = inner_diameter self.gap = gap self.rotation = rotation def to_inch(self): self.position = tuple([inch(x) for x in self.position]) self.outer_diameter = inch(self.outer_diameter) self.inner_diameter = inch(self.inner_diameter) self.gap = inch(self.gap) def to_metric(self): self.position = tuple([metric(x) for x in self.position]) self.outer_diameter = metric(self.outer_diameter) self.inner_diameter = metric(self.inner_diameter) self.gap = metric(self.gap) def to_gerber(self, settings=None): data = dict( code=self.code, position="%.4g,%.4g" % self.position, outer_diameter=self.outer_diameter, inner_diameter=self.inner_diameter, gap=self.gap, rotation=self.rotation ) fmt = "{code},{position},{outer_diameter},{inner_diameter},{gap},{rotation}*" return fmt.format(**data) def _approximate_arc_cw(self, start_angle, end_angle, radius, center): """ Get an arc as a series of points Parameters ---------- start_angle : The start angle in radians end_angle : The end angle in radians radius`: Radius of the arc center : The center point of the arc (x, y) tuple Returns ------- array of point tuples """ # The total sweep sweep_angle = end_angle - start_angle num_steps = 10 angle_step = sweep_angle / num_steps radius = radius center = center points = [] for i in range(num_steps + 1): current_angle = start_angle + (angle_step * i) nextx = (center[0] + math.cos(current_angle) * radius) nexty = (center[1] + math.sin(current_angle) * radius) points.append((nextx, nexty)) return points def to_primitive(self, units): # We start with calculating the top right section, then duplicate it inner_radius = self.inner_diameter / 2.0 outer_radius = self.outer_diameter / 2.0 # Calculate the start angle relative to the horizontal axis inner_offset_angle = asin(self.gap / 2.0 / inner_radius) outer_offset_angle = asin(self.gap / 2.0 / outer_radius) rotation_rad = math.radians(self.rotation) inner_start_angle = inner_offset_angle + rotation_rad inner_end_angle = math.pi / 2 - inner_offset_angle + rotation_rad outer_start_angle = outer_offset_angle + rotation_rad outer_end_angle = math.pi / 2 - outer_offset_angle + rotation_rad outlines = [] aperture = Circle((0, 0), 0) points = (self._approximate_arc_cw(inner_start_angle, inner_end_angle, inner_radius, self.position) + list(reversed(self._approximate_arc_cw(outer_start_angle, outer_end_angle, outer_radius, self.position)))) # Add in the last point since outlines should be closed points.append(points[0]) # There are four outlines at rotated sections for rotation in [0, 90.0, 180.0, 270.0]: lines = [] prev_point = rotate_point(points[0], rotation, self.position) for point in points[1:]: cur_point = rotate_point(point, rotation, self.position) lines.append(Line(prev_point, cur_point, aperture)) prev_point = cur_point outlines.append(Outline(lines, units=units, level_polarity=self._level_polarity)) return outlines class AMCenterLinePrimitive(AMPrimitive): """ Aperture Macro Center Line primitive. Code 21. The center line primitive is a rectangle defined by its width, height, and center point. .. seealso:: `The Gerber File Format Specification <http://www.ucamco.com/files/downloads/file/81/the_gerber_file_format_specification.pdf>`_ **Section 4.12.3.4:** Center Line, primitive code 21. Parameters ---------- code : int Center Line Primitive code. Must be 21. exposure : str 'on' or 'off' width : float Width of rectangle height : float Height of rectangle center : tuple (<float>, <float>) X and Y coordinates of line center rotation : float rectangle rotation about its center. Returns ------- CenterLinePrimitive : :class:`gerbers.am_statements.AMCenterLinePrimitive` An initialized AMCenterLinePrimitive Raises ------ ValueError, TypeError """ @classmethod def from_primitive(cls, primitive): width = primitive.width height = primitive.height center = primitive.position rotation = math.degrees(primitive.rotation) return cls(21, 'on', width, height, center, rotation) @classmethod def from_gerber(cls, primitive): modifiers = primitive.strip(' *').split(",") code = int(modifiers[0]) exposure = 'on' if float(modifiers[1]) == 1 else 'off' width = float(modifiers[2]) height = float(modifiers[3]) center = (float(modifiers[4]), float(modifiers[5])) rotation = float(modifiers[6]) return cls(code, exposure, width, height, center, rotation) def __init__(self, code, exposure, width, height, center, rotation): if code != 21: raise ValueError('CenterLinePrimitive code is 21') super(AMCenterLinePrimitive, self).__init__(code, exposure) self.width = width self.height = height validate_coordinates(center) self.center = center self.rotation = rotation def to_inch(self): self.center = tuple([inch(x) for x in self.center]) self.width = inch(self.width) self.height = inch(self.height) def to_metric(self): self.center = tuple([metric(x) for x in self.center]) self.width = metric(self.width) self.height = metric(self.height) def to_gerber(self, settings=None): data = dict( code=self.code, exposure = '1' if self.exposure == 'on' else '0', width = self.width, height = self.height, center="%.4g,%.4g" % self.center, rotation=self.rotation ) fmt = "{code},{exposure},{width},{height},{center},{rotation}*" return fmt.format(**data) def to_primitive(self, units): x = self.center[0] y = self.center[1] half_width = self.width / 2.0 half_height = self.height / 2.0 points = [] points.append((x - half_width, y + half_height)) points.append((x - half_width, y - half_height)) points.append((x + half_width, y - half_height)) points.append((x + half_width, y + half_height)) aperture = Circle((0, 0), 0) lines = [] prev_point = rotate_point(points[3], self.rotation, self.center) for point in points: cur_point = rotate_point(point, self.rotation, self.center) lines.append(Line(prev_point, cur_point, aperture)) return Outline(lines, units=units, level_polarity=self._level_polarity) class AMLowerLeftLinePrimitive(AMPrimitive): """ Aperture Macro Lower Left Line primitive. Code 22. The lower left line primitive is a rectangle defined by its width, height, and the lower left point. .. seealso:: `The Gerber File Format Specification <http://www.ucamco.com/files/downloads/file/81/the_gerber_file_format_specification.pdf>`_ **Section 4.12.3.5:** Lower Left Line, primitive code 22. Parameters ---------- code : int Center Line Primitive code. Must be 22. exposure : str 'on' or 'off' width : float Width of rectangle height : float Height of rectangle lower_left : tuple (<float>, <float>) X and Y coordinates of lower left corner rotation : float rectangle rotation about its origin. Returns ------- LowerLeftLinePrimitive : :class:`gerbers.am_statements.AMLowerLeftLinePrimitive` An initialized AMLowerLeftLinePrimitive Raises ------ ValueError, TypeError """ @classmethod def from_gerber(cls, primitive): modifiers = primitive.strip(' *').split(",") code = int(modifiers[0]) exposure = 'on' if float(modifiers[1]) == 1 else 'off' width = float(modifiers[2]) height = float(modifiers[3]) lower_left = (float(modifiers[4]), float(modifiers[5])) rotation = float(modifiers[6]) return cls(code, exposure, width, height, lower_left, rotation) def __init__(self, code, exposure, width, height, lower_left, rotation): if code != 22: raise ValueError('LowerLeftLinePrimitive code is 22') super (AMLowerLeftLinePrimitive, self).__init__(code, exposure) self.width = width self.height = height validate_coordinates(lower_left) self.lower_left = lower_left self.rotation = rotation def to_inch(self): self.lower_left = tuple([inch(x) for x in self.lower_left]) self.width = inch(self.width) self.height = inch(self.height) def to_metric(self): self.lower_left = tuple([metric(x) for x in self.lower_left]) self.width = metric(self.width) self.height = metric(self.height) def to_gerber(self, settings=None): data = dict( code=self.code, exposure = '1' if self.exposure == 'on' else '0', width = self.width, height = self.height, lower_left="%.4g,%.4g" % self.lower_left, rotation=self.rotation ) fmt = "{code},{exposure},{width},{height},{lower_left},{rotation}*" return fmt.format(**data) class AMUnsupportPrimitive(AMPrimitive): @classmethod def from_gerber(cls, primitive): return cls(primitive) def __init__(self, primitive): super(AMUnsupportPrimitive, self).__init__(9999) self.primitive = primitive def to_inch(self): pass def to_metric(self): pass def to_gerber(self, settings=None): return self.primitive
[((798, 29, 798, 64), 'math.asin', 'asin', ({(798, 34, 798, 63): 'self.gap / 2.0 / inner_radius'}, {}), '(self.gap / 2.0 / inner_radius)', False, 'from math import asin\n'), ((799, 29, 799, 64), 'math.asin', 'asin', ({(799, 34, 799, 63): 'self.gap / 2.0 / outer_radius'}, {}), '(self.gap / 2.0 / outer_radius)', False, 'from math import asin\n'), ((801, 23, 801, 50), 'math.radians', 'math.radians', ({(801, 36, 801, 49): 'self.rotation'}, {}), '(self.rotation)', False, 'import math\n'), ((877, 19, 877, 51), 'math.degrees', 'math.degrees', ({(877, 32, 877, 50): 'primitive.rotation'}, {}), '(primitive.rotation)', False, 'import math\n'), ((550, 86, 550, 113), 'math.radians', 'math.radians', ({(550, 99, 550, 112): 'self.rotation'}, {}), '(self.rotation)', False, 'import math\n'), ((783, 33, 783, 56), 'math.cos', 'math.cos', ({(783, 42, 783, 55): 'current_angle'}, {}), '(current_angle)', False, 'import math\n'), ((784, 33, 784, 56), 'math.sin', 'math.sin', ({(784, 42, 784, 55): 'current_angle'}, {}), '(current_angle)', False, 'import math\n')]
DeividVM/heroquest
heroquest/migrations/0002_auto_20160819_1747.py
c693d664717a849de645908ae78d62ec2a5837a5
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-08-19 17:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('heroquest', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='player', name='armor', ), migrations.AlterField( model_name='player', name='spell', field=models.ManyToManyField(related_name='spells', to='armery.Spell', verbose_name='Hechizos'), ), ]
[((15, 8, 18, 9), 'django.db.migrations.RemoveField', 'migrations.RemoveField', (), '', False, 'from django.db import migrations, models\n'), ((22, 18, 22, 107), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (), '', False, 'from django.db import migrations, models\n')]
epervago/dask
dask/array/utils.py
958732ce6c51ef6af39db4727d948bfa66a0a8d6
from distutils.version import LooseVersion import difflib import os import numpy as np from .core import Array from ..async import get_sync if LooseVersion(np.__version__) >= '1.10.0': allclose = np.allclose else: def allclose(a, b, **kwargs): if kwargs.pop('equal_nan', False): a_nans = np.isnan(a) b_nans = np.isnan(b) if not (a_nans == b_nans).all(): return False a = a[~a_nans] b = b[~b_nans] return np.allclose(a, b, **kwargs) def _not_empty(x): return x.shape and 0 not in x.shape def _maybe_check_dtype(a, dtype=None): # Only check dtype matches for non-empty if _not_empty(a): assert a.dtype == dtype def assert_eq(a, b, **kwargs): if isinstance(a, Array): adt = a.dtype a = a.compute(get=get_sync) _maybe_check_dtype(a, adt) else: adt = getattr(a, 'dtype', None) if isinstance(b, Array): bdt = b.dtype assert bdt is not None b = b.compute(get=get_sync) _maybe_check_dtype(b, bdt) else: bdt = getattr(b, 'dtype', None) if str(adt) != str(bdt): diff = difflib.ndiff(str(adt).splitlines(), str(bdt).splitlines()) raise AssertionError('string repr are different' + os.linesep + os.linesep.join(diff)) try: if _not_empty(a) and _not_empty(b): # Treat all empty arrays as equivalent assert a.shape == b.shape assert allclose(a, b, **kwargs) return except TypeError: pass c = a == b if isinstance(c, np.ndarray): assert c.all() else: assert c return True
[]
inniyah/launchpad-py
launchpad_py/__init__.py
b8dd4815b05d7e75ba5ca09ced64ddc38f515bad
# more specific selections for Python 3 (ASkr, 2/2018) from launchpad_py.launchpad import Launchpad from launchpad_py.launchpad import LaunchpadMk2 from launchpad_py.launchpad import LaunchpadPro from launchpad_py.launchpad import LaunchControlXL from launchpad_py.launchpad import LaunchKeyMini from launchpad_py.launchpad import Dicer from launchpad_py import charset
[]
EvoCargo/mono_depth
networks/adabins/utils.py
3a77291a7fc8f3eaad5f93aa17e2b60c9339a0b1
import base64 import math import re from io import BytesIO import matplotlib.cm import numpy as np import torch import torch.nn from PIL import Image # Compute edge magnitudes from scipy import ndimage class RunningAverage: def __init__(self): self.avg = 0 self.count = 0 def append(self, value): self.avg = (value + self.count * self.avg) / (self.count + 1) self.count += 1 def get_value(self): return self.avg def denormalize(x, device='cpu'): mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(device) std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(device) return x * std + mean class RunningAverageDict: def __init__(self): self._dict = None def update(self, new_dict): if self._dict is None: self._dict = dict() for key, _ in new_dict.items(): self._dict[key] = RunningAverage() for key, value in new_dict.items(): self._dict[key].append(value) def get_value(self): return {key: value.get_value() for key, value in self._dict.items()} def colorize(value, vmin=10, vmax=1000, cmap='magma_r'): value = value.cpu().numpy()[0, :, :] invalid_mask = value == -1 # normalize vmin = value.min() if vmin is None else vmin vmax = value.max() if vmax is None else vmax if vmin != vmax: value = (value - vmin) / (vmax - vmin) # vmin..vmax else: # Avoid 0-division value = value * 0.0 # squeeze last dim if it exists # value = value.squeeze(axis=0) cmapper = matplotlib.cm.get_cmap(cmap) value = cmapper(value, bytes=True) # (nxmx4) value[invalid_mask] = 255 img = value[:, :, :3] # return img.transpose((2, 0, 1)) return img def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) def compute_errors(gt, pred): thresh = np.maximum((gt / pred), (pred / gt)) a1 = (thresh < 1.25).mean() a2 = (thresh < 1.25 ** 2).mean() a3 = (thresh < 1.25 ** 3).mean() abs_rel = np.mean(np.abs(gt - pred) / gt) sq_rel = np.mean(((gt - pred) ** 2) / gt) rmse = (gt - pred) ** 2 rmse = np.sqrt(rmse.mean()) rmse_log = (np.log(gt) - np.log(pred)) ** 2 rmse_log = np.sqrt(rmse_log.mean()) err = np.log(pred) - np.log(gt) silog = np.sqrt(np.mean(err ** 2) - np.mean(err) ** 2) * 100 log_10 = (np.abs(np.log10(gt) - np.log10(pred))).mean() return dict( a1=a1, a2=a2, a3=a3, abs_rel=abs_rel, rmse=rmse, log_10=log_10, rmse_log=rmse_log, silog=silog, sq_rel=sq_rel, ) # Demo Utilities def b64_to_pil(b64string): image_data = re.sub('^data:image/.+;base64,', '', b64string) # image = Image.open(cStringIO.StringIO(image_data)) return Image.open(BytesIO(base64.b64decode(image_data))) def edges(d): dx = ndimage.sobel(d, 0) # horizontal derivative dy = ndimage.sobel(d, 1) # vertical derivative return np.abs(dx) + np.abs(dy) class PointCloudHelper: def __init__(self, width=640, height=480): self.xx, self.yy = self.worldCoords(width, height) def worldCoords(self, width=640, height=480): hfov_degrees, vfov_degrees = 57, 43 hFov = math.radians(hfov_degrees) vFov = math.radians(vfov_degrees) cx, cy = width / 2, height / 2 fx = width / (2 * math.tan(hFov / 2)) fy = height / (2 * math.tan(vFov / 2)) xx, yy = np.tile(range(width), height), np.repeat(range(height), width) xx = (xx - cx) / fx yy = (yy - cy) / fy return xx, yy def depth_to_points(self, depth): depth[edges(depth) > 0.3] = np.nan # Hide depth edges length = depth.shape[0] * depth.shape[1] # depth[edges(depth) > 0.3] = 1e6 # Hide depth edges z = depth.reshape(length) return np.dstack((self.xx * z, self.yy * z, z)).reshape((length, 3))
[((80, 13, 80, 49), 'numpy.maximum', 'np.maximum', ({(80, 25, 80, 34): 'gt / pred', (80, 38, 80, 47): 'pred / gt'}, {}), '(gt / pred, pred / gt)', True, 'import numpy as np\n'), ((86, 13, 86, 45), 'numpy.mean', 'np.mean', ({(86, 21, 86, 44): '(gt - pred) ** 2 / gt'}, {}), '((gt - pred) ** 2 / gt)', True, 'import numpy as np\n'), ((113, 17, 113, 64), 're.sub', 're.sub', ({(113, 24, 113, 48): '"""^data:image/.+;base64,"""', (113, 50, 113, 52): '""""""', (113, 54, 113, 63): 'b64string'}, {}), "('^data:image/.+;base64,', '', b64string)", False, 'import re\n'), ((119, 9, 119, 28), 'scipy.ndimage.sobel', 'ndimage.sobel', ({(119, 23, 119, 24): 'd', (119, 26, 119, 27): '0'}, {}), '(d, 0)', False, 'from scipy import ndimage\n'), ((120, 9, 120, 28), 'scipy.ndimage.sobel', 'ndimage.sobel', ({(120, 23, 120, 24): 'd', (120, 26, 120, 27): '1'}, {}), '(d, 1)', False, 'from scipy import ndimage\n'), ((94, 10, 94, 22), 'numpy.log', 'np.log', ({(94, 17, 94, 21): 'pred'}, {}), '(pred)', True, 'import numpy as np\n'), ((94, 25, 94, 35), 'numpy.log', 'np.log', ({(94, 32, 94, 34): 'gt'}, {}), '(gt)', True, 'import numpy as np\n'), ((121, 11, 121, 21), 'numpy.abs', 'np.abs', ({(121, 18, 121, 20): 'dx'}, {}), '(dx)', True, 'import numpy as np\n'), ((121, 24, 121, 34), 'numpy.abs', 'np.abs', ({(121, 31, 121, 33): 'dy'}, {}), '(dy)', True, 'import numpy as np\n'), ((130, 15, 130, 41), 'math.radians', 'math.radians', ({(130, 28, 130, 40): 'hfov_degrees'}, {}), '(hfov_degrees)', False, 'import math\n'), ((131, 15, 131, 41), 'math.radians', 'math.radians', ({(131, 28, 131, 40): 'vfov_degrees'}, {}), '(vfov_degrees)', False, 'import math\n'), ((85, 22, 85, 39), 'numpy.abs', 'np.abs', ({(85, 29, 85, 38): 'gt - pred'}, {}), '(gt - pred)', True, 'import numpy as np\n'), ((91, 16, 91, 26), 'numpy.log', 'np.log', ({(91, 23, 91, 25): 'gt'}, {}), '(gt)', True, 'import numpy as np\n'), ((91, 29, 91, 41), 'numpy.log', 'np.log', ({(91, 36, 91, 40): 'pred'}, {}), '(pred)', True, 'import numpy as np\n'), ((115, 30, 115, 58), 'base64.b64decode', 'base64.b64decode', ({(115, 47, 115, 57): 'image_data'}, {}), '(image_data)', False, 'import base64\n'), ((95, 20, 95, 37), 'numpy.mean', 'np.mean', ({(95, 28, 95, 36): '(err ** 2)'}, {}), '(err ** 2)', True, 'import numpy as np\n'), ((133, 26, 133, 44), 'math.tan', 'math.tan', ({(133, 35, 133, 43): '(hFov / 2)'}, {}), '(hFov / 2)', False, 'import math\n'), ((134, 27, 134, 45), 'math.tan', 'math.tan', ({(134, 36, 134, 44): '(vFov / 2)'}, {}), '(vFov / 2)', False, 'import math\n'), ((146, 15, 146, 55), 'numpy.dstack', 'np.dstack', ({(146, 25, 146, 54): '(self.xx * z, self.yy * z, z)'}, {}), '((self.xx * z, self.yy * z, z))', True, 'import numpy as np\n'), ((30, 11, 30, 46), 'torch.Tensor', 'torch.Tensor', ({(30, 24, 30, 45): '[0.485, 0.456, 0.406]'}, {}), '([0.485, 0.456, 0.406])', False, 'import torch\n'), ((31, 10, 31, 45), 'torch.Tensor', 'torch.Tensor', ({(31, 23, 31, 44): '[0.229, 0.224, 0.225]'}, {}), '([0.229, 0.224, 0.225])', False, 'import torch\n'), ((95, 40, 95, 52), 'numpy.mean', 'np.mean', ({(95, 48, 95, 51): 'err'}, {}), '(err)', True, 'import numpy as np\n'), ((97, 21, 97, 33), 'numpy.log10', 'np.log10', ({(97, 30, 97, 32): 'gt'}, {}), '(gt)', True, 'import numpy as np\n'), ((97, 36, 97, 50), 'numpy.log10', 'np.log10', ({(97, 45, 97, 49): 'pred'}, {}), '(pred)', True, 'import numpy as np\n')]
simbilod/gdsfactory
gdsfactory/types.py
4d76db32674c3edb4d16260e3177ee29ef9ce11d
"""In programming, a factory is a function that returns an object. Functions are easy to understand because they have clear inputs and outputs. Most gdsfactory functions take some inputs and return a Component object. Some of these inputs parameters are also functions. - Component: Object with. - name. - references: to other components (x, y, rotation). - polygons in different layers. - ports dict. - Route: dataclass with 3 attributes. - references: list of references (straights, bends and tapers). - ports: dict(input=PortIn, output=PortOut). - length: how long is this route? Factories: - ComponentFactory: function that returns a Component. - RouteFactory: function that returns a Route. Specs: - ComponentSpec: Component, ComponentFactory or dict(component=mzi, settings=dict(delta_length=20)). - LayerSpec: (3, 0), 3 (asumes 0 as datatype) or string. """ import json import pathlib from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np from omegaconf import OmegaConf from phidl.device_layout import Label as LabelPhidl from phidl.device_layout import Path from pydantic import BaseModel, Extra from typing_extensions import Literal from gdsfactory.component import Component, ComponentReference from gdsfactory.cross_section import CrossSection from gdsfactory.port import Port Anchor = Literal[ "ce", "cw", "nc", "ne", "nw", "sc", "se", "sw", "center", "cc", ] Axis = Literal["x", "y"] NSEW = Literal["N", "S", "E", "W"] class Label(LabelPhidl): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v): """check with pydantic Label valid type""" assert isinstance(v, LabelPhidl), f"TypeError, Got {type(v)}, expecting Label" return v Float2 = Tuple[float, float] Float3 = Tuple[float, float, float] Floats = Tuple[float, ...] Strs = Tuple[str, ...] Int2 = Tuple[int, int] Int3 = Tuple[int, int, int] Ints = Tuple[int, ...] Layer = Tuple[int, int] Layers = Tuple[Layer, ...] LayerSpec = NewType("LayerSpec", Union[Layer, int, str, None]) LayerSpecs = Tuple[LayerSpec, ...] ComponentFactory = Callable[..., Component] ComponentFactoryDict = Dict[str, ComponentFactory] PathFactory = Callable[..., Path] PathType = Union[str, pathlib.Path] PathTypes = Tuple[PathType, ...] ComponentOrPath = Union[PathType, Component] ComponentOrReference = Union[Component, ComponentReference] NameToFunctionDict = Dict[str, ComponentFactory] Number = Union[float, int] Coordinate = Tuple[float, float] Coordinates = Tuple[Coordinate, ...] ComponentOrPath = Union[Component, PathType] CrossSectionFactory = Callable[..., CrossSection] CrossSectionOrFactory = Union[CrossSection, Callable[..., CrossSection]] PortSymmetries = Dict[str, Dict[str, List[str]]] PortsDict = Dict[str, Port] PortsList = Dict[str, Port] ComponentSpec = NewType( "ComponentSpec", Union[str, ComponentFactory, Component, Dict[str, Any]] ) ComponentSpecOrList = Union[ComponentSpec, List[ComponentSpec]] CellSpec = Union[str, ComponentFactory, Dict[str, Any]] ComponentSpecDict = Dict[str, ComponentSpec] CrossSectionSpec = NewType( "CrossSectionSpec", Union[str, CrossSectionFactory, CrossSection, Dict[str, Any]] ) MultiCrossSectionAngleSpec = List[Tuple[CrossSectionSpec, Tuple[int, ...]]] class Route(BaseModel): references: List[ComponentReference] labels: Optional[List[Label]] = None ports: Tuple[Port, Port] length: float class Config: extra = Extra.forbid class Routes(BaseModel): references: List[ComponentReference] lengths: List[float] ports: Optional[List[Port]] = None bend_radius: Optional[List[float]] = None class Config: extra = Extra.forbid class ComponentModel(BaseModel): component: Union[str, Dict[str, Any]] settings: Optional[Dict[str, Any]] class Config: extra = Extra.forbid class PlacementModel(BaseModel): x: Union[str, float] = 0 y: Union[str, float] = 0 xmin: Optional[Union[str, float]] = None ymin: Optional[Union[str, float]] = None xmax: Optional[Union[str, float]] = None ymax: Optional[Union[str, float]] = None dx: float = 0 dy: float = 0 port: Optional[Union[str, Anchor]] = None rotation: int = 0 mirror: bool = False class Config: extra = Extra.forbid class RouteModel(BaseModel): links: Dict[str, str] settings: Optional[Dict[str, Any]] = None routing_strategy: Optional[str] = None class Config: extra = Extra.forbid class NetlistModel(BaseModel): """Netlist defined component. Attributes: instances: dict of instances (name, settings, component). placements: dict of placements. connections: dict of connections. routes: dict of routes. name: component name. info: information (polarization, wavelength ...). settings: input variables. pdk: pdk module name. ports: exposed component ports. """ instances: Dict[str, ComponentModel] placements: Optional[Dict[str, PlacementModel]] = None connections: Optional[List[Dict[str, str]]] = None routes: Optional[Dict[str, RouteModel]] = None name: Optional[str] = None info: Optional[Dict[str, Any]] = None settings: Optional[Dict[str, Any]] = None pdk: Optional[str] = None ports: Optional[Dict[str, str]] = None class Config: extra = Extra.forbid # factory: Dict[str, ComponentFactory] = {} # def add_instance(self, name: str, component: str, **settings) -> None: # assert component in self.factory.keys() # component_model = ComponentModel(component=component, settings=settings) # self.instances[name] = component_model # def add_route(self, port1: Port, port2: Port, **settings) -> None: # self.routes = component_model RouteFactory = Callable[..., Route] class TypedArray(np.ndarray): """based on https://github.com/samuelcolvin/pydantic/issues/380""" @classmethod def __get_validators__(cls): yield cls.validate_type @classmethod def validate_type(cls, val): return np.array(val, dtype=cls.inner_type) class ArrayMeta(type): def __getitem__(self, t): return type("Array", (TypedArray,), {"inner_type": t}) class Array(np.ndarray, metaclass=ArrayMeta): pass __all__ = ( "ComponentFactory", "ComponentFactoryDict", "ComponentSpec", "ComponentOrPath", "ComponentOrReference", "Coordinate", "Coordinates", "CrossSectionFactory", "CrossSectionOrFactory", "MultiCrossSectionAngleSpec", "Float2", "Float3", "Floats", "Int2", "Int3", "Ints", "Layer", "Layers", "NameToFunctionDict", "Number", "PathType", "PathTypes", "Route", "RouteFactory", "Routes", "Strs", ) def write_schema(model: BaseModel = NetlistModel) -> None: s = model.schema_json() d = OmegaConf.create(s) dirpath = pathlib.Path(__file__).parent / "schemas" f1 = dirpath / "netlist.yaml" f1.write_text(OmegaConf.to_yaml(d)) f2 = dirpath / "netlist.json" f2.write_text(json.dumps(OmegaConf.to_container(d))) if __name__ == "__main__": write_schema() import jsonschema import yaml from gdsfactory.config import CONFIG schema_path = CONFIG["schema_netlist"] schema_dict = json.loads(schema_path.read_text()) yaml_text = """ name: mzi pdk: ubcpdk settings: dy: -90 info: polarization: te wavelength: 1.55 description: mzi for ubcpdk instances: yr: component: y_splitter yl: component: y_splitter placements: yr: rotation: 180 x: 100 y: 0 routes: route_top: links: yl,opt2: yr,opt3 settings: cross_section: strip route_bot: links: yl,opt3: yr,opt2 routing_strategy: get_bundle_from_steps settings: steps: [dx: 30, dy: '${settings.dy}', dx: 20] cross_section: strip ports: o1: yl,opt1 o2: yr,opt1 """ yaml_dict = yaml.safe_load(yaml_text) jsonschema.validate(yaml_dict, schema_dict) # from gdsfactory.components import factory # c = NetlistModel(factory=factory) # c.add_instance("mmi1", "mmi1x2", length=13.3)
[((83, 12, 83, 62), 'typing.NewType', 'NewType', ({(83, 20, 83, 31): '"""LayerSpec"""', (83, 33, 83, 61): 'Union[Layer, int, str, None]'}, {}), "('LayerSpec', Union[Layer, int, str, None])", False, 'from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union\n'), ((104, 16, 106, 1), 'typing.NewType', 'NewType', ({(105, 4, 105, 19): '"""ComponentSpec"""', (105, 21, 105, 76): 'Union[str, ComponentFactory, Component, Dict[str, Any]]'}, {}), "('ComponentSpec', Union[str, ComponentFactory, Component, Dict[str,\n Any]])", False, 'from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union\n'), ((110, 19, 112, 1), 'typing.NewType', 'NewType', ({(111, 4, 111, 22): '"""CrossSectionSpec"""', (111, 24, 111, 85): 'Union[str, CrossSectionFactory, CrossSection, Dict[str, Any]]'}, {}), "('CrossSectionSpec', Union[str, CrossSectionFactory, CrossSection,\n Dict[str, Any]])", False, 'from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union\n'), ((264, 8, 264, 27), 'omegaconf.OmegaConf.create', 'OmegaConf.create', ({(264, 25, 264, 26): 's'}, {}), '(s)', False, 'from omegaconf import OmegaConf\n'), ((331, 16, 331, 41), 'yaml.safe_load', 'yaml.safe_load', ({(331, 31, 331, 40): 'yaml_text'}, {}), '(yaml_text)', False, 'import yaml\n'), ((332, 4, 332, 47), 'jsonschema.validate', 'jsonschema.validate', ({(332, 24, 332, 33): 'yaml_dict', (332, 35, 332, 46): 'schema_dict'}, {}), '(yaml_dict, schema_dict)', False, 'import jsonschema\n'), ((220, 15, 220, 50), 'numpy.array', 'np.array', (), '', True, 'import numpy as np\n'), ((269, 18, 269, 38), 'omegaconf.OmegaConf.to_yaml', 'OmegaConf.to_yaml', ({(269, 36, 269, 37): 'd'}, {}), '(d)', False, 'from omegaconf import OmegaConf\n'), ((266, 14, 266, 36), 'pathlib.Path', 'pathlib.Path', ({(266, 27, 266, 35): '__file__'}, {}), '(__file__)', False, 'import pathlib\n'), ((272, 29, 272, 54), 'omegaconf.OmegaConf.to_container', 'OmegaConf.to_container', ({(272, 52, 272, 53): 'd'}, {}), '(d)', False, 'from omegaconf import OmegaConf\n')]
ahmetdaglarbas/e-commerce
tests/_site/myauth/models.py
ff190244ccd422b4e08d7672f50709edcbb6ebba
# -*- coding: utf-8 -*- # Code will only work with Django >= 1.5. See tests/config.py import re from django.utils.translation import ugettext_lazy as _ from django.db import models from django.core import validators from django.contrib.auth.models import BaseUserManager from oscar.apps.customer.abstract_models import AbstractUser class CustomUserManager(BaseUserManager): def create_user(self, username, email, password): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=CustomUserManager.normalize_email(email), username=username, is_active=True, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): u = self.create_user(username, email, password=password) u.is_admin = True u.is_staff = True u.save(using=self._db) return u class User(AbstractUser): """ Custom user based on Oscar's AbstractUser """ username = models.CharField(_('username'), max_length=30, unique=True, help_text=_('Required. 30 characters or fewer. Letters, numbers and ' '@/./+/-/_ characters'), validators=[ validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid') ]) extra_field = models.CharField( _('Nobody needs me'), max_length=5, blank=True) objects = CustomUserManager() class Meta: app_label = 'myauth'
[((45, 32, 45, 45), 'django.utils.translation.ugettext_lazy', '_', ({(45, 34, 45, 44): '"""username"""'}, {}), "('username')", True, 'from django.utils.translation import ugettext_lazy as _\n'), ((52, 8, 52, 28), 'django.utils.translation.ugettext_lazy', '_', ({(52, 10, 52, 27): '"""Nobody needs me"""'}, {}), "('Nobody needs me')", True, 'from django.utils.translation import ugettext_lazy as _\n'), ((46, 18, 47, 43), 'django.utils.translation.ugettext_lazy', '_', ({(46, 20, 47, 42): '"""Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters"""'}, {}), "('Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters'\n )", True, 'from django.utils.translation import ugettext_lazy as _\n'), ((49, 38, 49, 63), 're.compile', 're.compile', ({(49, 49, 49, 62): '"""^[\\\\w.@+-]+$"""'}, {}), "('^[\\\\w.@+-]+$')", False, 'import re\n'), ((49, 65, 49, 93), 'django.utils.translation.ugettext_lazy', '_', ({(49, 67, 49, 92): '"""Enter a valid username."""'}, {}), "('Enter a valid username.')", True, 'from django.utils.translation import ugettext_lazy as _\n')]
brouwa/CNNs-on-FPSPs
5 - FC layers retraining/4 - FC weights to C++ code/weights_pck_to_cpp_unrolled_loop.py
71bcc2335e6d71ad21ba66e04a651d4db218356d
import pickle import numpy as np INPUT_FILENAME = 'NP_WEIGHTS.pck' PRECISION = 100 # Open weights fc1_k, fc1_b, fc2_k, fc2_b = pickle.load( open(INPUT_FILENAME, 'rb')) # Round them fc1_k, fc1_b, fc2_k, fc2_b = fc1_k*PRECISION//1, fc1_b*PRECISION//1, fc2_k*PRECISION//1, fc2_b*PRECISION*PRECISION//1 fc1_k, fc1_b, fc2_k, fc2_b = fc1_k.astype(np.int), fc1_b.astype(np.int), fc2_k.astype(np.int), fc2_b.astype(np.int) """ 0: GENERATE C++ ARRAYS, TO BE USED IN A STANDARD LOOP """ OUTPUT_FILENAME = 'fc_weights_arrays.cpp' def to_cpp_1_dim(array): txt = '{\t' for coeff in array[:-1]: txt += str(coeff) + ',\t' txt += str(array[-1]) + '}' return txt def to_cpp_2_dims(array): txt = '{' for line in array[:-1]: txt += to_cpp_1_dim(line) + ',\n' txt += to_cpp_1_dim(array[-1]) + '}' return txt # Generate .cpp text out = 'int fc1_k[' + str(fc1_k.shape[0]) + '][' + str(fc1_k.shape[1]) + '] = ' out += to_cpp_2_dims(fc1_k) + ';\n\n' out += 'int fc1_b[' + str(fc1_b.shape[0]) + '] = ' out += to_cpp_1_dim(fc1_b) + ';\n\n' out += 'int fc2_k[' + str(fc2_k.shape[0]) + '][' + str(fc2_k.shape[1]) + '] = ' out += to_cpp_2_dims(fc2_k) + ';\n\n' out += 'int fc2_b[' + str(fc2_b.shape[0]) + '] = ' out += to_cpp_1_dim(fc2_b) + ';\n\n' # Output it with open(OUTPUT_FILENAME, 'w+', encoding='utf-8') as f: f.write(out) """ 1: GENERATE C++ LOOP, USING THE ABOVE ARRAY """ OUTPUT_FILENAME = 'fc_loop_unrolled.cpp' def to_cpp_function(k, b, function_name, in_dim, out_dim): """ Generates C++ code for computing a fully connected layer of int values, applying weights k and bias b, with hardcoded values in the source code. The function is names after function_name. """ out = "" out += "inline void "+function_name+"(int in["+str(in_dim)+"], int out["+str(out_dim)+"]){\n" for j in range(out_dim): out += "\tout["+str(j)+"] = \n" for i in range(in_dim): out += "\t\tin["+str(i)+"]*("+k+"["+str(i)+"]["+str(j)+"]) +\n" out += "\t\t("+b+"["+str(j)+"]);\n" out += "}\n\n" return out ## Generate .cpp text out = "" # First layer out += to_cpp_function('fc1_k', 'fc1_b', 'fc_1', 27, 50) # Second layer out += to_cpp_function('fc2_k', 'fc2_b', 'fc_2', 50, 10) # Output it with open(OUTPUT_FILENAME, 'w+', encoding='utf-8') as f: f.write(out) """ 3: GENERATE C++ LOOP, WITH HARDCODED WEIGHTS """ OUTPUT_FILENAME = 'fc_loop_unrolled_hardcoded_weights.cpp' def to_cpp_function(k, b, function_name): """ Generates C++ code for computing a fully connected layer of int values, applying weights k and bias b, with hardcoded values in the source code. The function is names after function_name. """ out = "" (in_dim, out_dim) = k.shape out += "inline void "+function_name+"(int in["+str(in_dim)+"], int out["+str(out_dim)+"]){\n" for j in range(out_dim): out += "\tout["+str(j)+"] = \n" for i in range(in_dim): out += "\t\tin["+str(i)+"]*("+str(k[i][j])+") +\n" out += "\t\t("+str(b[j])+");\n" out += "}\n\n" return out ## Generate .cpp text out = "" # First layer out += to_cpp_function(fc1_k, fc1_b, 'fc_1') # Second layer out += to_cpp_function(fc2_k, fc2_b, 'fc_2') # Output it with open(OUTPUT_FILENAME, 'w+', encoding='utf-8') as f: f.write(out)
[]
yubaoliu/Computer-Vision
python/Canny_EdgeDetection.py
2fe4d3e1db0a65ef8c9def5f84d5e494bec3faa9
import cv2 import numpy as np import random img = cv2.imread('../../Assets/Images/flower-white.jpeg', 1) imgInfo = img.shape height = imgInfo[0] width = imgInfo[1] cv2.imshow('img', img) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) imgG = cv2.GaussianBlur(gray, (3, 3), 0) dst = cv2.Canny(img, 50, 50) cv2.imshow('dst', dst) cv2.waitKey(0)
[((6, 6, 6, 60), 'cv2.imread', 'cv2.imread', ({(6, 17, 6, 56): '"""../../Assets/Images/flower-white.jpeg"""', (6, 58, 6, 59): '1'}, {}), "('../../Assets/Images/flower-white.jpeg', 1)", False, 'import cv2\n'), ((12, 0, 12, 22), 'cv2.imshow', 'cv2.imshow', ({(12, 11, 12, 16): '"""img"""', (12, 18, 12, 21): 'img'}, {}), "('img', img)", False, 'import cv2\n'), ((14, 7, 14, 44), 'cv2.cvtColor', 'cv2.cvtColor', ({(14, 20, 14, 23): 'img', (14, 25, 14, 43): 'cv2.COLOR_BGR2GRAY'}, {}), '(img, cv2.COLOR_BGR2GRAY)', False, 'import cv2\n'), ((16, 7, 16, 40), 'cv2.GaussianBlur', 'cv2.GaussianBlur', ({(16, 24, 16, 28): 'gray', (16, 30, 16, 36): '(3, 3)', (16, 38, 16, 39): '0'}, {}), '(gray, (3, 3), 0)', False, 'import cv2\n'), ((17, 6, 17, 28), 'cv2.Canny', 'cv2.Canny', ({(17, 16, 17, 19): 'img', (17, 21, 17, 23): '50', (17, 25, 17, 27): '50'}, {}), '(img, 50, 50)', False, 'import cv2\n'), ((19, 0, 19, 22), 'cv2.imshow', 'cv2.imshow', ({(19, 11, 19, 16): '"""dst"""', (19, 18, 19, 21): 'dst'}, {}), "('dst', dst)", False, 'import cv2\n'), ((20, 0, 20, 14), 'cv2.waitKey', 'cv2.waitKey', ({(20, 12, 20, 13): '(0)'}, {}), '(0)', False, 'import cv2\n')]
Guoxs/DODT
avod/core/trainer_stride.py
f354cda6ef08465018fdeec1a8b4be4002e6a71f
"""Detection model trainer. This file provides a generic training method to train a DetectionModel. """ import datetime import os import tensorflow as tf import time from avod.builders import optimizer_builder from avod.core import trainer_utils from avod.core import summary_utils slim = tf.contrib.slim def train(model, train_config): """Training function for detection models. Args: model: The detection model object. train_config: a train_*pb2 protobuf. training i.e. loading RPN weights onto AVOD model. """ model = model train_config = train_config # Get model configurations model_config = model.model_config # Create a variable tensor to hold the global step global_step_tensor = tf.Variable( 0, trainable=False, name='global_step') ############################# # Get training configurations ############################# max_iterations = train_config.max_iterations summary_interval = train_config.summary_interval checkpoint_interval = train_config.checkpoint_interval max_checkpoints = train_config.max_checkpoints_to_keep paths_config = model_config.paths_config logdir = paths_config.logdir if not os.path.exists(logdir): os.makedirs(logdir) checkpoint_dir = paths_config.checkpoint_dir if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) checkpoint_path = checkpoint_dir + '/' + \ model_config.checkpoint_name pretrained_checkpoint_dir = checkpoint_dir + '/../../' + \ 'pyramid_cars_with_aug_dt_5_tracking_corr_pretrained/checkpoints' global_summaries = set([]) # The model should return a dictionary of predictions prediction_dict = model.build() summary_histograms = train_config.summary_histograms summary_img_images = train_config.summary_img_images summary_bev_images = train_config.summary_bev_images # get variables to train if not train_config.use_pretrained_model: variable_to_train = None else: trainable_variables = tf.trainable_variables() variable_to_train = trainable_variables[68:72] + \ trainable_variables[96:] ############################## # Setup loss ############################## losses_dict, total_loss = model.loss(prediction_dict) # Optimizer training_optimizer = optimizer_builder.build( train_config.optimizer, global_summaries, global_step_tensor) # Create the train op with tf.variable_scope('train_op'): train_op = slim.learning.create_train_op( total_loss, training_optimizer, variables_to_train=variable_to_train, clip_gradient_norm=1.0, global_step=global_step_tensor) # Add the result of the train_op to the summary tf.summary.scalar("training_loss", train_op) # Add maximum memory usage summary op # This op can only be run on device with gpu # so it's skipped on travis is_travis = 'TRAVIS' in os.environ if not is_travis: # tf.summary.scalar('bytes_in_use', # tf.contrib.memory_stats.BytesInUse()) tf.summary.scalar('max_bytes', tf.contrib.memory_stats.MaxBytesInUse()) summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES)) summary_merged = summary_utils.summaries_to_keep( summaries, global_summaries, histograms=summary_histograms, input_imgs=summary_img_images, input_bevs=summary_bev_images ) allow_gpu_mem_growth = train_config.allow_gpu_mem_growth if allow_gpu_mem_growth: # GPU memory config config = tf.ConfigProto() config.gpu_options.allow_growth = allow_gpu_mem_growth sess = tf.Session(config=config) else: sess = tf.Session() # Create unique folder name using datetime for summary writer datetime_str = str(datetime.datetime.now()) logdir = logdir + '/train' train_writer = tf.summary.FileWriter(logdir + '/' + datetime_str, sess.graph) # Save checkpoints regularly. saver = tf.train.Saver(max_to_keep=max_checkpoints, pad_step_number=True) # Create init op # if train_config.use_pretrained_model: # init = tf.initialize_variables(variable_to_train) # else: # init = tf.global_variables_initializer() init = tf.global_variables_initializer() # Continue from last saved checkpoint if not train_config.overwrite_checkpoints: trainer_utils.load_checkpoints(checkpoint_dir,saver) if len(saver.last_checkpoints) > 0: checkpoint_to_restore = saver.last_checkpoints[-1] saver.restore(sess, checkpoint_to_restore) else: sess.run(init) # load pretrained model if train_config.use_pretrained_model: variable_to_restore = tf.trainable_variables() variable_to_restore = variable_to_restore[:68] + \ variable_to_restore[72:96] variable_to_restore = {var.op.name: var for var in variable_to_restore} saver2 = tf.train.Saver(var_list=variable_to_restore) print('Loading pretrained model...') trainer_utils.load_checkpoints(pretrained_checkpoint_dir, saver2) checkpoint_to_restore = saver2.last_checkpoints[11] saver2.restore(sess, checkpoint_to_restore) else: sess.run(init) # load pretrained model if train_config.use_pretrained_model: variable_to_restore = tf.trainable_variables() variable_to_restore = variable_to_restore[:68] + \ variable_to_restore[72:96] variable_to_restore = {var.op.name: var for var in variable_to_restore} saver2 = tf.train.Saver(var_list=variable_to_restore) print('Loading pretrained model...') trainer_utils.load_checkpoints(pretrained_checkpoint_dir, saver2) checkpoint_to_restore = saver2.last_checkpoints[11] saver2.restore(sess, checkpoint_to_restore) # Read the global step if restored global_step = tf.train.global_step(sess, global_step_tensor) print('Starting from step {} / {}'.format( global_step, max_iterations)) # Main Training Loop last_time = time.time() for step in range(global_step, max_iterations + 1): # Save checkpoint if step % checkpoint_interval == 0: global_step = tf.train.global_step(sess, global_step_tensor) saver.save(sess, save_path=checkpoint_path, global_step=global_step) print('Step {} / {}, Checkpoint saved to {}-{:08d}'.format( step, max_iterations, checkpoint_path, global_step)) feed_dict = model.create_feed_dict() # Write summaries and train op if step % summary_interval == 0: current_time = time.time() time_elapsed = current_time - last_time last_time = current_time train_op_loss, summary_out = sess.run( [train_op, summary_merged], feed_dict=feed_dict) print('Step {}, Total Loss {:0.3f}, Time Elapsed {:0.3f} s'.format( step, train_op_loss, time_elapsed)) train_writer.add_summary(summary_out, step) else: # Run the train op only sess.run(train_op, feed_dict) # Close the summary writers train_writer.close()
[((32, 25, 33, 47), 'tensorflow.Variable', 'tf.Variable', (), '', True, 'import tensorflow as tf\n'), ((81, 25, 84, 27), 'avod.builders.optimizer_builder.build', 'optimizer_builder.build', ({(82, 8, 82, 30): 'train_config.optimizer', (83, 8, 83, 24): 'global_summaries', (84, 8, 84, 26): 'global_step_tensor'}, {}), '(train_config.optimizer, global_summaries,\n global_step_tensor)', False, 'from avod.builders import optimizer_builder\n'), ((96, 4, 96, 48), 'tensorflow.summary.scalar', 'tf.summary.scalar', ({(96, 22, 96, 37): '"""training_loss"""', (96, 39, 96, 47): 'train_op'}, {}), "('training_loss', train_op)", True, 'import tensorflow as tf\n'), ((109, 21, 115, 5), 'avod.core.summary_utils.summaries_to_keep', 'summary_utils.summaries_to_keep', (), '', False, 'from avod.core import summary_utils\n'), ((129, 19, 130, 52), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', ({(129, 41, 129, 68): "logdir + '/' + datetime_str", (130, 41, 130, 51): 'sess.graph'}, {}), "(logdir + '/' + datetime_str, sess.graph)", True, 'import tensorflow as tf\n'), ((132, 12, 132, 77), 'tensorflow.train.Saver', 'tf.train.Saver', (), '', True, 'import tensorflow as tf\n'), ((140, 11, 140, 44), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((177, 18, 177, 64), 'tensorflow.train.global_step', 'tf.train.global_step', ({(177, 39, 177, 43): 'sess', (177, 45, 177, 63): 'global_step_tensor'}, {}), '(sess, global_step_tensor)', True, 'import tensorflow as tf\n'), ((182, 16, 182, 27), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((45, 11, 45, 33), 'os.path.exists', 'os.path.exists', ({(45, 26, 45, 32): 'logdir'}, {}), '(logdir)', False, 'import os\n'), ((46, 8, 46, 27), 'os.makedirs', 'os.makedirs', ({(46, 20, 46, 26): 'logdir'}, {}), '(logdir)', False, 'import os\n'), ((49, 11, 49, 41), 'os.path.exists', 'os.path.exists', ({(49, 26, 49, 40): 'checkpoint_dir'}, {}), '(checkpoint_dir)', False, 'import os\n'), ((50, 8, 50, 35), 'os.makedirs', 'os.makedirs', ({(50, 20, 50, 34): 'checkpoint_dir'}, {}), '(checkpoint_dir)', False, 'import os\n'), ((70, 30, 70, 54), 'tensorflow.trainable_variables', 'tf.trainable_variables', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((87, 9, 87, 38), 'tensorflow.variable_scope', 'tf.variable_scope', ({(87, 27, 87, 37): '"""train_op"""'}, {}), "('train_op')", True, 'import tensorflow as tf\n'), ((108, 20, 108, 61), 'tensorflow.get_collection', 'tf.get_collection', ({(108, 38, 108, 60): 'tf.GraphKeys.SUMMARIES'}, {}), '(tf.GraphKeys.SUMMARIES)', True, 'import tensorflow as tf\n'), ((120, 17, 120, 33), 'tensorflow.ConfigProto', 'tf.ConfigProto', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((122, 15, 122, 40), 'tensorflow.Session', 'tf.Session', (), '', True, 'import tensorflow as tf\n'), ((124, 15, 124, 27), 'tensorflow.Session', 'tf.Session', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((127, 23, 127, 46), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((144, 8, 144, 60), 'avod.core.trainer_utils.load_checkpoints', 'trainer_utils.load_checkpoints', ({(144, 39, 144, 53): 'checkpoint_dir', (144, 54, 144, 59): 'saver'}, {}), '(checkpoint_dir, saver)', False, 'from avod.core import trainer_utils\n'), ((106, 26, 106, 65), 'tensorflow.contrib.memory_stats.MaxBytesInUse', 'tf.contrib.memory_stats.MaxBytesInUse', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((165, 34, 165, 58), 'tensorflow.trainable_variables', 'tf.trainable_variables', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((169, 21, 169, 65), 'tensorflow.train.Saver', 'tf.train.Saver', (), '', True, 'import tensorflow as tf\n'), ((171, 12, 171, 77), 'avod.core.trainer_utils.load_checkpoints', 'trainer_utils.load_checkpoints', ({(171, 43, 171, 68): 'pretrained_checkpoint_dir', (171, 70, 171, 76): 'saver2'}, {}), '(pretrained_checkpoint_dir, saver2)', False, 'from avod.core import trainer_utils\n'), ((187, 26, 188, 66), 'tensorflow.train.global_step', 'tf.train.global_step', ({(187, 47, 187, 51): 'sess', (188, 47, 188, 65): 'global_step_tensor'}, {}), '(sess, global_step_tensor)', True, 'import tensorflow as tf\n'), ((202, 27, 202, 38), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((152, 38, 152, 62), 'tensorflow.trainable_variables', 'tf.trainable_variables', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((156, 25, 156, 69), 'tensorflow.train.Saver', 'tf.train.Saver', (), '', True, 'import tensorflow as tf\n'), ((158, 16, 158, 81), 'avod.core.trainer_utils.load_checkpoints', 'trainer_utils.load_checkpoints', ({(158, 47, 158, 72): 'pretrained_checkpoint_dir', (158, 74, 158, 80): 'saver2'}, {}), '(pretrained_checkpoint_dir, saver2)', False, 'from avod.core import trainer_utils\n')]
nickc92/django-rest-framework-hmac
rest_framework_hmac/hmac_key/models.py
c32e37cf00ef0c13957a6e02eb0a7fabac3d1ac1
import binascii import os from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ class HMACKey(models.Model): """ The default HMACKey model that can auto generate a key/secret for HMAC Auth via a signal """ def generate_key(): """ Returns a 40 character hex string based on binary random data """ return binascii.hexlify(os.urandom(20)).decode() key = models.CharField( _("Key"), primary_key=True, max_length=40, default=generate_key) secret = models.CharField( _("Secret"), max_length=40, default=generate_key) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='hmac_key', on_delete=models.CASCADE, verbose_name=_("User") ) nonce = models.BigIntegerField(default=1) created = models.DateTimeField(_("Created"), auto_now_add=True) class Meta: # Only create a DB table for this Model if this app is registered abstract = 'rest_framework_hmac.hmac_key' \ not in settings.INSTALLED_APPS verbose_name = _("HMACKey") verbose_name_plural = _("HMACKey") def __str__(self): return self.key
[((28, 12, 28, 45), 'django.db.models.BigIntegerField', 'models.BigIntegerField', (), '', False, 'from django.db import models\n'), ((21, 8, 21, 16), 'django.utils.translation.ugettext_lazy', '_', ({(21, 10, 21, 15): '"""Key"""'}, {}), "('Key')", True, 'from django.utils.translation import ugettext_lazy as _\n'), ((23, 8, 23, 19), 'django.utils.translation.ugettext_lazy', '_', ({(23, 10, 23, 18): '"""Secret"""'}, {}), "('Secret')", True, 'from django.utils.translation import ugettext_lazy as _\n'), ((29, 35, 29, 47), 'django.utils.translation.ugettext_lazy', '_', ({(29, 37, 29, 46): '"""Created"""'}, {}), "('Created')", True, 'from django.utils.translation import ugettext_lazy as _\n'), ((35, 23, 35, 35), 'django.utils.translation.ugettext_lazy', '_', ({(35, 25, 35, 34): '"""HMACKey"""'}, {}), "('HMACKey')", True, 'from django.utils.translation import ugettext_lazy as _\n'), ((36, 30, 36, 42), 'django.utils.translation.ugettext_lazy', '_', ({(36, 32, 36, 41): '"""HMACKey"""'}, {}), "('HMACKey')", True, 'from django.utils.translation import ugettext_lazy as _\n'), ((26, 47, 26, 56), 'django.utils.translation.ugettext_lazy', '_', ({(26, 49, 26, 55): '"""User"""'}, {}), "('User')", True, 'from django.utils.translation import ugettext_lazy as _\n'), ((18, 32, 18, 46), 'os.urandom', 'os.urandom', ({(18, 43, 18, 45): '(20)'}, {}), '(20)', False, 'import os\n')]
Geoiv/river
test/conftest.py
d013985145c09f263172b054819e811689002ae9
import os from tempfile import NamedTemporaryFile import boto3 from moto import mock_s3 import pandas as pd import pandavro as pdx import pickle import pytest @pytest.fixture(autouse=True, scope='session') def aws_credentials(): """ Sets AWS credentials to invalid values. Applied to all test functions and scoped to the entire testing session, so there's no chance of interfering with production buckets. """ os.environ['AWS_ACCESS_KEY_ID'] = 'testing' os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing' os.environ['AWS_SECURITY_TOKEN'] = 'testing' os.environ['AWS_SESSION_TOKEN'] = 'testing' @pytest.fixture def test_bucket(): """Universal bucket name for use throughout testing""" return 'test_bucket' @pytest.fixture def test_keys(): """List of keys to be used for populating a bucket with empty objects""" return sorted([ 'test_key_0.csv', 'folder0/test_key_1.pq', 'folder1/test_key_2.pkl', 'folder1/subfolder0/test_key_3.pkl', 'folder2/' ]) @pytest.fixture def test_df_keys(): """List of keys to be used for populating a bucket with DataFrames""" return { 'avro': ['df.avro'], 'csv': ['df.csv'], 'csv.gz': ['df.csv.gz'], 'csv.zip': ['df.csv.zip'], 'csv.bz2': ['df.csv.bz2'], 'csv.xz': ['df.csv.xz'], 'psv': ['df.psv'], 'psv.gz': ['df.psv.gz'], 'psv.zip': ['df.psv.zip'], 'psv.bz2': ['df.psv.bz2'], 'psv.xz': ['df.psv.xz'], 'feather': ['df.feather'], 'json': ['df.json'], 'pkl': ['df.pkl', 'df.pickle'], 'pq': ['df.pq', 'df.parquet'] } @pytest.fixture def test_df(): """ Universal dataframe for use throughout testing. Multiple data types used to test for proper encoding/decoding. """ return pd.DataFrame({ 'intcol': [1, 2, 3], 'strcol': ['four', 'five', 'six'], 'floatcol': [7.0, 8.5, 9.0] }) @pytest.fixture def mock_s3_client(): """Mocks all s3 connections in any test or fixture that includes it""" with mock_s3(): yield @pytest.fixture def setup_bucket_w_contents(mock_s3_client, test_bucket, test_keys): """ Sets up a bucket with objects containing the empty string, based off keys in 'test_keys' """ s3 = boto3.client('s3') s3.create_bucket(Bucket=test_bucket) for key in test_keys: s3.put_object(Bucket=test_bucket, Key=key, Body='') yield @pytest.fixture def setup_bucket_wo_contents(mock_s3_client, test_bucket): """Sets up a bucket with no contents.""" s3 = boto3.client('s3') s3.create_bucket(Bucket=test_bucket) yield @pytest.fixture def setup_bucket_w_dfs(mock_s3_client, test_bucket, test_df, test_df_keys): """ Sets up a bucket populated with dataframes that contain the data as defined in 'test_df', at the keys and storage formats defined in 'test_df_keys' """ s3 = boto3.client('s3') s3.create_bucket(Bucket=test_bucket) for key in test_df_keys['avro']: with NamedTemporaryFile() as tmpfile: pdx.to_avro(tmpfile, test_df) s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['csv']: with NamedTemporaryFile() as tmpfile: test_df.to_csv(tmpfile.name, index=False) s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['csv.gz']: with NamedTemporaryFile(suffix='.csv.gz') as tmpfile: test_df.to_csv(tmpfile.name, index=False) s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['csv.zip']: with NamedTemporaryFile(suffix='.csv.zip') as tmpfile: test_df.to_csv(tmpfile.name, index=False) s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['csv.bz2']: with NamedTemporaryFile(suffix='.csv.bz2') as tmpfile: test_df.to_csv(tmpfile.name, index=False) s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['csv.xz']: with NamedTemporaryFile(suffix='.csv.xz') as tmpfile: test_df.to_csv(tmpfile.name, index=False) s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['psv']: with NamedTemporaryFile() as tmpfile: test_df.to_csv(tmpfile.name, index=False, sep='|') s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['psv.gz']: with NamedTemporaryFile(suffix='.psv.gz') as tmpfile: test_df.to_csv(tmpfile.name, index=False, sep='|') s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['psv.zip']: with NamedTemporaryFile(suffix='.psv.zip') as tmpfile: test_df.to_csv(tmpfile.name, index=False, sep='|') s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['psv.bz2']: with NamedTemporaryFile(suffix='.psv.bz2') as tmpfile: test_df.to_csv(tmpfile.name, index=False, sep='|') s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['psv.xz']: with NamedTemporaryFile(suffix='.psv.xz') as tmpfile: test_df.to_csv(tmpfile.name, index=False, sep='|') s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['feather']: with NamedTemporaryFile() as tmpfile: test_df.to_feather(tmpfile.name) s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['json']: with NamedTemporaryFile() as tmpfile: test_df.to_json(tmpfile.name) s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['pkl']: with NamedTemporaryFile() as tmpfile: pickle.dump(test_df, tmpfile, protocol=pickle.HIGHEST_PROTOCOL) tmpfile.flush() s3.upload_file(tmpfile.name, test_bucket, key) for key in test_df_keys['pq']: with NamedTemporaryFile() as tmpfile: test_df.to_parquet(tmpfile.name, index=False) s3.upload_file(tmpfile.name, test_bucket, key) yield
[((12, 1, 12, 46), 'pytest.fixture', 'pytest.fixture', (), '', False, 'import pytest\n'), ((71, 11, 75, 6), 'pandas.DataFrame', 'pd.DataFrame', ({(71, 24, 75, 5): "{'intcol': [1, 2, 3], 'strcol': ['four', 'five', 'six'], 'floatcol': [7.0, \n 8.5, 9.0]}"}, {}), "({'intcol': [1, 2, 3], 'strcol': ['four', 'five', 'six'],\n 'floatcol': [7.0, 8.5, 9.0]})", True, 'import pandas as pd\n'), ((91, 9, 91, 27), 'boto3.client', 'boto3.client', ({(91, 22, 91, 26): '"""s3"""'}, {}), "('s3')", False, 'import boto3\n'), ((102, 9, 102, 27), 'boto3.client', 'boto3.client', ({(102, 22, 102, 26): '"""s3"""'}, {}), "('s3')", False, 'import boto3\n'), ((115, 9, 115, 27), 'boto3.client', 'boto3.client', ({(115, 22, 115, 26): '"""s3"""'}, {}), "('s3')", False, 'import boto3\n'), ((81, 9, 81, 18), 'moto.mock_s3', 'mock_s3', ({}, {}), '()', False, 'from moto import mock_s3\n'), ((119, 13, 119, 33), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ({}, {}), '()', False, 'from tempfile import NamedTemporaryFile\n'), ((120, 12, 120, 41), 'pandavro.to_avro', 'pdx.to_avro', ({(120, 24, 120, 31): 'tmpfile', (120, 33, 120, 40): 'test_df'}, {}), '(tmpfile, test_df)', True, 'import pandavro as pdx\n'), ((124, 13, 124, 33), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ({}, {}), '()', False, 'from tempfile import NamedTemporaryFile\n'), ((129, 13, 129, 49), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', (), '', False, 'from tempfile import NamedTemporaryFile\n'), ((134, 13, 134, 50), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', (), '', False, 'from tempfile import NamedTemporaryFile\n'), ((139, 13, 139, 50), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', (), '', False, 'from tempfile import NamedTemporaryFile\n'), ((144, 13, 144, 49), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', (), '', False, 'from tempfile import NamedTemporaryFile\n'), ((149, 13, 149, 33), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ({}, {}), '()', False, 'from tempfile import NamedTemporaryFile\n'), ((154, 13, 154, 49), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', (), '', False, 'from tempfile import NamedTemporaryFile\n'), ((159, 13, 159, 50), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', (), '', False, 'from tempfile import NamedTemporaryFile\n'), ((164, 13, 164, 50), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', (), '', False, 'from tempfile import NamedTemporaryFile\n'), ((169, 13, 169, 49), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', (), '', False, 'from tempfile import NamedTemporaryFile\n'), ((174, 13, 174, 33), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ({}, {}), '()', False, 'from tempfile import NamedTemporaryFile\n'), ((179, 13, 179, 33), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ({}, {}), '()', False, 'from tempfile import NamedTemporaryFile\n'), ((184, 13, 184, 33), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ({}, {}), '()', False, 'from tempfile import NamedTemporaryFile\n'), ((185, 12, 185, 75), 'pickle.dump', 'pickle.dump', (), '', False, 'import pickle\n'), ((190, 13, 190, 33), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ({}, {}), '()', False, 'from tempfile import NamedTemporaryFile\n')]
uktrade/directory-api
company/migrations/0021_auto_20161208_1113.py
45a9024a7ecc2842895201cbb51420ba9e57a168
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-12-08 11:13 from __future__ import unicode_literals from django.db import migrations from company import helpers def ensure_verification_code(apps, schema_editor): Company = apps.get_model("company", "Company") for company in Company.objects.filter(verification_code=''): company.verification_code = helpers.generate_verification_code() company.save() class Migration(migrations.Migration): dependencies = [ ('company', '0020_auto_20161208_1056'), ] operations = [ migrations.RunPython(ensure_verification_code), ]
[((13, 36, 13, 72), 'company.helpers.generate_verification_code', 'helpers.generate_verification_code', ({}, {}), '()', False, 'from company import helpers\n'), ((25, 8, 25, 54), 'django.db.migrations.RunPython', 'migrations.RunPython', ({(25, 29, 25, 53): 'ensure_verification_code'}, {}), '(ensure_verification_code)', False, 'from django.db import migrations\n')]
Toktar/indy-test-automation
system/indy-node-tests/TestAuthMapSuite.py
4d583dda7cbf2a9f451b3a01312a90e55c7bacc8
import pytest import asyncio from system.utils import * from random import randrange as rr import hashlib import time from datetime import datetime, timedelta, timezone from indy import payment import logging logger = logging.getLogger(__name__) @pytest.mark.usefixtures('docker_setup_and_teardown') class TestAuthMapSuite: @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.asyncio async def test_case_nym(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num, editor_role, editor_role_num): trustee_did, _ = get_default_trustee new_did, new_vk = await did.create_and_store_my_did(wallet_handler, '{}') # add adder to add nym adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' # add editor to edit nym editor_did, editor_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did, editor_vk, None, editor_role) assert res['op'] == 'REPLY' req = await ledger.build_auth_rule_request(trustee_did, '1', 'ADD', 'role', '*', '', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' req = await ledger.build_auth_rule_request(trustee_did, '1', 'EDIT', 'verkey', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res3) assert res3['op'] == 'REPLY' # add nym with verkey by adder res4 = await send_nym(pool_handler, wallet_handler, adder_did, new_did, adder_vk) # push adder vk print(res4) assert res4['op'] == 'REPLY' # edit verkey by editor res5 = await send_nym(pool_handler, wallet_handler, editor_did, new_did, editor_vk) # push editor vk print(res5) assert res5['op'] == 'REPLY' # negative cases if adder_role != editor_role: # try to add another nym with editor did - should be rejected res6 = await send_nym(pool_handler, wallet_handler, editor_did, random_did_and_json()[0]) print(res6) assert res6['op'] == 'REJECT' # try to edit initial nym one more time with adder did - should be rejected res7 = await send_nym(pool_handler, wallet_handler, adder_did, new_did, adder_vk) print(res7) assert res7['op'] == 'REJECT' @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.asyncio async def test_case_attrib(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num, editor_role, editor_role_num): trustee_did, _ = get_default_trustee # add target nym target_did, target_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, target_did, target_vk) assert res['op'] == 'REPLY' # add adder to add attrib adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' # add editor to edit attrib editor_did, editor_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did, editor_vk, None, editor_role) assert res['op'] == 'REPLY' # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '100', 'ADD', '*', None, '*', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' # set rule for editing req = await ledger.build_auth_rule_request(trustee_did, '100', 'EDIT', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res3) assert res3['op'] == 'REPLY' # add attrib for target did by non-owner adder res4 = await send_attrib(pool_handler, wallet_handler, adder_did, target_did, None, json.dumps({'key1': 'value1'}), None) print(res4) assert res4['op'] == 'REPLY' # edit attrib for target did by non-owner editor res5 = await send_attrib(pool_handler, wallet_handler, editor_did, target_did, None, json.dumps({'key1': 'value2'}), None) print(res5) assert res5['op'] == 'REPLY' # negative cases if adder_role != editor_role: # try to add another attrib with editor did - should be rejected res6 = await send_attrib(pool_handler, wallet_handler, editor_did, target_did, None, json.dumps({'key2': 'value1'}), None) print(res6) assert res6['op'] == 'REJECT' # try to edit initial attrib one more time with adder did - should be rejected res7 = await send_attrib(pool_handler, wallet_handler, adder_did, target_did, None, json.dumps({'key1': 'value3'}), None) print(res7) assert res7['op'] == 'REJECT' @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.asyncio async def test_case_schema(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num): # we can add schema only trustee_did, _ = get_default_trustee # add adder to add schema adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '101', 'ADD', '*', None, '*', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' # add schema res4 = await send_schema(pool_handler, wallet_handler, adder_did, 'schema1', '1.0', json.dumps(['attr1'])) print(res4) assert res4[1]['op'] == 'REPLY' # edit schema - nobody can edit schemas - should be rejected res5 = await send_schema(pool_handler, wallet_handler, adder_did, 'schema1', '1.0', json.dumps(['attr1', 'attr2'])) print(res5) assert res5[1]['op'] == 'REJECT' @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.asyncio # use the same did with different roles to ADD and EDIT since adder did is a part of unique cred def id async def test_case_cred_def(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num, editor_role, editor_role_num): trustee_did, _ = get_default_trustee # add adder to add cred def adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' schema_id, _ = await send_schema(pool_handler, wallet_handler, trustee_did, 'schema1', '1.0', json.dumps(["age", "sex", "height", "name"])) await asyncio.sleep(1) res = await get_schema(pool_handler, wallet_handler, trustee_did, schema_id) schema_id, schema_json = await ledger.parse_get_schema_response(json.dumps(res)) # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '102', 'ADD', '*', None, '*', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' # set rule for editing req = await ledger.build_auth_rule_request(trustee_did, '102', 'EDIT', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res3) assert res3['op'] == 'REPLY' # add cred def cred_def_id, cred_def_json = \ await anoncreds.issuer_create_and_store_credential_def(wallet_handler, adder_did, schema_json, 'TAG1', None, json.dumps({'support_revocation': False})) request = await ledger.build_cred_def_request(adder_did, cred_def_json) res4 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, request)) print(res4) assert res4['op'] == 'REPLY' if adder_role != editor_role: # try to edit cred def as adder - should be rejected _request = json.loads(request) _request['operation']['data']['primary']['n'] = '123456789' _request['reqId'] += _request['reqId'] res5 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, json.dumps(_request))) print(res5) assert res5['op'] == 'REJECT' # change adder role to edit cred def res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, None, None, editor_role) print(res) assert res['op'] == 'REPLY' # edit cred def request = json.loads(request) request['operation']['data']['primary']['n'] = '123456' request['reqId'] += request['reqId'] res6 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, json.dumps(request))) print(res6) assert res6['op'] == 'REPLY' if adder_role != editor_role: # try to add another cred def as editor - should be rejected cred_def_id, cred_def_json = \ await anoncreds.issuer_create_and_store_credential_def(wallet_handler, adder_did, schema_json, 'TAG2', None, json.dumps({'support_revocation': True})) request = await ledger.build_cred_def_request(adder_did, cred_def_json) res7 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, request)) print(res7) assert res7['op'] == 'REJECT' @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.asyncio # use the same did with different roles to ADD and EDIT since adder did is a part of unique revoc reg def id async def test_case_revoc_reg_def(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num, editor_role, editor_role_num): trustee_did, _ = get_default_trustee # add adder to add revoc reg def adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' schema_id, _ = await send_schema(pool_handler, wallet_handler, trustee_did, 'schema1', '1.0', json.dumps(['age', 'sex', 'height', 'name'])) await asyncio.sleep(1) res = await get_schema(pool_handler, wallet_handler, trustee_did, schema_id) schema_id, schema_json = await ledger.parse_get_schema_response(json.dumps(res)) cred_def_id, _, res = await send_cred_def(pool_handler, wallet_handler, trustee_did, schema_json, 'cred_def_tag', None, json.dumps({'support_revocation': True})) # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '113', 'ADD', '*', None, '*', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' # set rule for editing req = await ledger.build_auth_rule_request(trustee_did, '113', 'EDIT', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res3) assert res3['op'] == 'REPLY' # add revoc reg def tails_writer_config = json.dumps({'base_dir': 'tails', 'uri_pattern': ''}) tails_writer_handle = await blob_storage.open_writer('default', tails_writer_config) revoc_reg_def_id, revoc_reg_def_json, revoc_reg_entry_json = \ await anoncreds.issuer_create_and_store_revoc_reg(wallet_handler, adder_did, None, 'TAG1', cred_def_id, json.dumps({ 'max_cred_num': 1, 'issuance_type': 'ISSUANCE_BY_DEFAULT'}), tails_writer_handle) request = await ledger.build_revoc_reg_def_request(adder_did, revoc_reg_def_json) res4 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, request)) print(res4) assert res4['op'] == 'REPLY' if adder_role != editor_role: # try to edit revoc reg def as adder - should be rejected _request = json.loads(request) _request['operation']['value']['tailsHash'] = random_string(30) _request['reqId'] += _request['reqId'] res5 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, json.dumps(_request))) print(res5) assert res5['op'] == 'REJECT' # change adder role to edit revoc reg def res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, None, None, editor_role) print(res) assert res['op'] == 'REPLY' # edit revoc reg def request = json.loads(request) request['operation']['value']['tailsHash'] = random_string(20) request['reqId'] += request['reqId'] res6 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, json.dumps(request))) print(res6) assert res6['op'] == 'REPLY' if adder_role != editor_role: # try to add another revoc reg def as editor - should be rejected revoc_reg_def_id, revoc_reg_def_json, revoc_reg_entry_json = \ await anoncreds.issuer_create_and_store_revoc_reg(wallet_handler, adder_did, None, 'TAG2', cred_def_id, json.dumps({ 'max_cred_num': 2, 'issuance_type': 'ISSUANCE_BY_DEFAULT'}), tails_writer_handle) request = await ledger.build_revoc_reg_def_request(adder_did, revoc_reg_def_json) res7 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, request)) print(res7) assert res7['op'] == 'REJECT' @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.asyncio async def test_case_revoc_reg_entry(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num, editor_role, editor_role_num): trustee_did, _ = get_default_trustee # add adder to add revoc reg entry adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' schema_id, _ = await send_schema(pool_handler, wallet_handler, trustee_did, 'schema1', '1.0', json.dumps(['age', 'sex', 'height', 'name'])) await asyncio.sleep(1) res = await get_schema(pool_handler, wallet_handler, trustee_did, schema_id) schema_id, schema_json = await ledger.parse_get_schema_response(json.dumps(res)) cred_def_id, _, res = await send_cred_def(pool_handler, wallet_handler, trustee_did, schema_json, 'cred_def_tag', None, json.dumps({'support_revocation': True})) # set rule for revoc reg def adding - network monitor case req = await ledger.build_auth_rule_request(trustee_did, '113', 'ADD', '*', None, '*', json.dumps({ 'constraint_id': 'ROLE', 'role': '*', 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res21 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res21) assert res21['op'] == 'REPLY' # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '114', 'ADD', '*', None, '*', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res22 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res22) assert res22['op'] == 'REPLY' # set rule for editing req = await ledger.build_auth_rule_request(trustee_did, '114', 'EDIT', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res3) assert res3['op'] == 'REPLY' # add revoc reg entry tails_writer_config = json.dumps({'base_dir': 'tails', 'uri_pattern': ''}) tails_writer_handle = await blob_storage.open_writer('default', tails_writer_config) revoc_reg_def_id, revoc_reg_def_json, revoc_reg_entry_json = \ await anoncreds.issuer_create_and_store_revoc_reg(wallet_handler, adder_did, None, 'TAG1', cred_def_id, json.dumps({ 'max_cred_num': 10, 'issuance_type': 'ISSUANCE_BY_DEFAULT'}), tails_writer_handle) req = await ledger.build_revoc_reg_def_request(adder_did, revoc_reg_def_json) res = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) assert res['op'] == 'REPLY' request = await ledger.build_revoc_reg_entry_request(adder_did, revoc_reg_def_id, 'CL_ACCUM', revoc_reg_entry_json) res4 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, request)) print(res4) assert res4['op'] == 'REPLY' if adder_role != editor_role: # try to edit revoc reg entry as adder - should be rejected _request = json.loads(request) _request['operation']['value']['prevAccum'] = _request['operation']['value']['accum'] _request['operation']['value']['accum'] = random_string(20) _request['operation']['value']['revoked'] = [7, 8, 9] _request['reqId'] += _request['reqId'] res5 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, json.dumps(_request))) print(res5) assert res5['op'] == 'REJECT' # change adder role to edit revoc reg def res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, None, None, editor_role) print(res) assert res['op'] == 'REPLY' # edit revoc reg entry request = json.loads(request) request['operation']['value']['prevAccum'] = request['operation']['value']['accum'] request['operation']['value']['accum'] = random_string(10) request['operation']['value']['revoked'] = [1, 2, 3] request['reqId'] += request['reqId'] res6 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, json.dumps(request))) print(res6) assert res6['op'] == 'REPLY' if adder_role != editor_role: # try to add another revoc reg entry as editor - should be rejected revoc_reg_def_id, revoc_reg_def_json, revoc_reg_entry_json = \ await anoncreds.issuer_create_and_store_revoc_reg(wallet_handler, adder_did, None, 'TAG2', cred_def_id, json.dumps({ 'max_cred_num': 20, 'issuance_type': 'ISSUANCE_BY_DEFAULT'}), tails_writer_handle) req = await ledger.build_revoc_reg_def_request(adder_did, revoc_reg_def_json) res = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) assert res['op'] == 'REPLY' request = await ledger.build_revoc_reg_entry_request(adder_did, revoc_reg_def_id, 'CL_ACCUM', revoc_reg_entry_json) res7 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, request)) print(res7) assert res7['op'] == 'REJECT' @pytest.mark.skip('INDY-2024') @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.asyncio async def test_case_node(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num, editor_role, editor_role_num): trustee_did, _ = get_default_trustee # add adder to add node adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' # add editor to edit node editor_did, editor_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did, editor_vk, None, editor_role) assert res['op'] == 'REPLY' # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '0', 'ADD', 'services', '*', str(['VALIDATOR']), json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' # set rule for editing req = await ledger.build_auth_rule_request(trustee_did, '0', 'EDIT', 'services', str(['VALIDATOR']), str([]), json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res3) assert res3['op'] == 'REPLY' # add node alias = random_string(5) client_ip = '{}.{}.{}.{}'.format(rr(1, 255), 0, 0, rr(1, 255)) client_port = rr(1, 32767) node_ip = '{}.{}.{}.{}'.format(rr(1, 255), 0, 0, rr(1, 255)) node_port = rr(1, 32767) req = await ledger.build_node_request(adder_did, adder_vk, # adder_vk is used as node target did here json.dumps( { 'alias': alias, 'client_ip': client_ip, 'client_port': client_port, 'node_ip': node_ip, 'node_port': node_port, 'services': ['VALIDATOR'] })) res4 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) print(res4) assert res4['op'] == 'REPLY' # edit node req = await ledger.build_node_request(editor_did, adder_vk, # adder_vk is used as node target did here json.dumps( { 'alias': alias, 'services': [] })) res5 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, editor_did, req)) print(res5) assert res5['op'] == 'REPLY' @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.asyncio async def test_case_pool_upgrade(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num, editor_role, editor_role_num): trustee_did, _ = get_default_trustee # add adder to start pool upgrdae adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' # add editor to cancel pool upgrade editor_did, editor_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did, editor_vk, None, editor_role) assert res['op'] == 'REPLY' # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '109', 'ADD', 'action', '*', 'start', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' # set rule for editing req = await ledger.build_auth_rule_request(trustee_did, '109', 'EDIT', 'action', 'start', 'cancel', json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res3) assert res3['op'] == 'REPLY' # start pool upgrade init_time = 30 version = '1.9.999' name = 'upgrade' + '_' + version + '_' + datetime.now(tz=timezone.utc).strftime('%Y-%m-%dT%H:%M:%S%z') _sha256 = hashlib.sha256().hexdigest() _timeout = 5 reinstall = False force = False package = 'indy-node' dests = ['Gw6pDLhcBcoQesN72qfotTgFa7cbuqZpkX3Xo6pLhPhv', '8ECVSk179mjsjKRLWiQtssMLgp6EPhWXtaYyStWPSGAb', 'DKVxG2fXXTU8yT5N7hGEbXB3dfdAnYv1JczDUHpmDxya', '4PS3EDQ3dW1tci1Bp6543CfuuebjFrg36kLAUcskGfaA', '4SWokCJWJc69Tn74VvLS6t2G2ucvXqM9FDMsWJjmsUxe', 'Cv1Ehj43DDM5ttNBmC6VPpEfwXWwfGktHwjDJsTV5Fz8', 'BM8dTooz5uykCbYSAAFwKNkYfT4koomBHsSWHTDtkjhW'] docker_7_schedule = json.dumps(dict( {dest: datetime.strftime(datetime.now(tz=timezone.utc) + timedelta(minutes=init_time + i * 5), '%Y-%m-%dT%H:%M:%S%z') for dest, i in zip(dests, range(len(dests)))} )) req = await ledger.build_pool_upgrade_request(adder_did, name, version, 'start', _sha256, _timeout, docker_7_schedule, None, reinstall, force, package) res4 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) print(res4) assert res4['op'] == 'REPLY' # cancel pool upgrade req = await ledger.build_pool_upgrade_request(editor_did, name, version, 'cancel', _sha256, _timeout, docker_7_schedule, None, reinstall, force, package) res5 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, editor_did, req)) print(res5) assert res5['op'] == 'REPLY' @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.asyncio async def test_case_pool_restart(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num): # we can add pool restart only trustee_did, _ = get_default_trustee # add adder to restart pool adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' await asyncio.sleep(15) # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '118', 'ADD', 'action', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' # restart pool req = await ledger.build_pool_restart_request\ (adder_did, 'start', datetime.strftime(datetime.now(tz=timezone.utc) + timedelta(minutes=60), '%Y-%m-%dT%H:%M:%S%z')) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) res3 = [json.loads(v) for k, v in res3.items()] print(res3) assert all([res['op'] == 'REPLY' for res in res3]) @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.asyncio async def test_case_validator_info(self, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num): # we can add validator info only trustee_did, _ = get_default_trustee # add adder to get validator info adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' await asyncio.sleep(15) # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '119', 'ADD', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' req = await ledger.build_get_validator_info_request(adder_did) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) res3 = [json.loads(v) for k, v in res3.items()] print(res3) assert all([res['op'] == 'REPLY' for res in res3]) @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.asyncio async def test_case_pool_config(self, pool_handler, wallet_handler, get_default_trustee, editor_role, editor_role_num): # we can edit pool config only trustee_did, _ = get_default_trustee # add editor to edit pool config editor_did, editor_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did, editor_vk, None, editor_role) assert res['op'] == 'REPLY' # set rule for editing req = await ledger.build_auth_rule_request(trustee_did, '111', 'EDIT', 'action', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' req = await ledger.build_pool_config_request(editor_did, False, False) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, editor_did, req)) print(res3) assert res3['op'] == 'REPLY' @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.asyncio async def test_case_auth_rule(self, pool_handler, wallet_handler, get_default_trustee, editor_role, editor_role_num): # we can edit auth rule only trustee_did, _ = get_default_trustee # add editor to edit auth rule editor_did, editor_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did, editor_vk, None, editor_role) assert res['op'] == 'REPLY' # set rule for editing req = await ledger.build_auth_rule_request(trustee_did, '120', 'EDIT', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' await asyncio.sleep(15) req = await ledger.build_auth_rule_request(editor_did, '111', 'EDIT', 'action', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': '*', 'sig_count': 5, 'need_to_be_owner': True, 'metadata': {} })) res3 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, editor_did, req)) print(res3) assert res3['op'] == 'REPLY' @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.parametrize('sig_count', [0, 1, 3]) @pytest.mark.asyncio async def test_case_mint(self, payment_init, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num, sig_count): libsovtoken_payment_method = 'sov' trustee_did, _ = get_default_trustee address = await payment.create_payment_address(wallet_handler, libsovtoken_payment_method, json.dumps( {"seed": str('0000000000000000000000000Wallet0')})) # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '10000', 'ADD', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': sig_count, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' if sig_count == 0: # add identity owner adder to mint tokens adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, None) assert res['op'] == 'REPLY' req, _ = await payment.build_mint_req(wallet_handler, adder_did, json.dumps([{"recipient": address, "amount": 100}]), None) res1 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) print(res1) assert res1['op'] == 'REPLY' elif sig_count == 1: # add adder to mint tokens adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' req, _ = await payment.build_mint_req(wallet_handler, adder_did, json.dumps([{"recipient": address, "amount": 100}]), None) res1 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) print(res1) assert res1['op'] == 'REPLY' else: # add adders to mint tokens adder_did1, adder_vk1 = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did1, adder_vk1, None, adder_role) assert res['op'] == 'REPLY' adder_did2, adder_vk2 = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did2, adder_vk2, None, adder_role) assert res['op'] == 'REPLY' adder_did3, adder_vk3 = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did3, adder_vk3, None, adder_role) assert res['op'] == 'REPLY' req, _ = await payment.build_mint_req(wallet_handler, adder_did1, json.dumps([{"recipient": address, "amount": 100}]), None) req = await ledger.multi_sign_request(wallet_handler, adder_did1, req) req = await ledger.multi_sign_request(wallet_handler, adder_did2, req) req = await ledger.multi_sign_request(wallet_handler, adder_did3, req) res1 = json.loads(await ledger.submit_request(pool_handler, req)) print(res1) assert res1['op'] == 'REPLY' @pytest.mark.parametrize('editor_role, editor_role_num', [ ('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0') ]) @pytest.mark.parametrize('sig_count', [0, 1, 3]) @pytest.mark.asyncio async def test_case_set_fees(self, payment_init, pool_handler, wallet_handler, get_default_trustee, editor_role, editor_role_num, sig_count): libsovtoken_payment_method = 'sov' fees = {'1': 1, '100': 1, '101': 1, '102': 1, '113': 1, '114': 1, '10001': 1} trustee_did, _ = get_default_trustee # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '20000', 'EDIT', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': editor_role_num, 'sig_count': sig_count, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' if sig_count == 0: # add identity owner editor to set fees editor_did, editor_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did, editor_vk, None, None) assert res['op'] == 'REPLY' req = await payment.build_set_txn_fees_req(wallet_handler, editor_did, libsovtoken_payment_method, json.dumps(fees)) res1 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, editor_did, req)) print(res1) assert res1['op'] == 'REPLY' elif sig_count == 1: # add editor to set fees editor_did, editor_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did, editor_vk, None, editor_role) assert res['op'] == 'REPLY' req = await payment.build_set_txn_fees_req(wallet_handler, editor_did, libsovtoken_payment_method, json.dumps(fees)) res1 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, editor_did, req)) print(res1) assert res1['op'] == 'REPLY' else: # add editors to set fees editor_did1, editor_vk1 = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did1, editor_vk1, None, editor_role) assert res['op'] == 'REPLY' editor_did2, editor_vk2 = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did2, editor_vk2, None, editor_role) assert res['op'] == 'REPLY' editor_did3, editor_vk3 = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, editor_did3, editor_vk3, None, editor_role) assert res['op'] == 'REPLY' req = await payment.build_set_txn_fees_req(wallet_handler, editor_did1, libsovtoken_payment_method, json.dumps(fees)) req = await ledger.multi_sign_request(wallet_handler, editor_did1, req) req = await ledger.multi_sign_request(wallet_handler, editor_did2, req) req = await ledger.multi_sign_request(wallet_handler, editor_did3, req) res1 = json.loads(await ledger.submit_request(pool_handler, req)) print(res1) assert res1['op'] == 'REPLY' @pytest.mark.parametrize('adder_role, adder_role_num', [ ('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201') ]) @pytest.mark.parametrize('sig_count', [0, 1, 3]) @pytest.mark.asyncio async def test_case_payment(self, payment_init, pool_handler, wallet_handler, get_default_trustee, adder_role, adder_role_num, sig_count): libsovtoken_payment_method = 'sov' trustee_did, _ = get_default_trustee address1 = await payment.create_payment_address(wallet_handler, libsovtoken_payment_method, json.dumps( {"seed": str('0000000000000000000000000Wallet1')})) address2 = await payment.create_payment_address(wallet_handler, libsovtoken_payment_method, json.dumps( {"seed": str('0000000000000000000000000Wallet2')})) # set rule for easier mint adding req = await ledger.build_auth_rule_request(trustee_did, '10000', 'ADD', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': '*', 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} })) res1 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res1) assert res1['op'] == 'REPLY' # set rule for adding req = await ledger.build_auth_rule_request(trustee_did, '10001', 'ADD', '*', '*', '*', json.dumps({ 'constraint_id': 'ROLE', 'role': adder_role_num, 'sig_count': sig_count, 'need_to_be_owner': False, 'metadata': {} })) res2 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res2) assert res2['op'] == 'REPLY' # initial minting req, _ = await payment.build_mint_req(wallet_handler, trustee_did, json.dumps([{"recipient": address1, "amount": 100}]), None) res11 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) print(res11) assert res11['op'] == 'REPLY' req, _ = await payment.build_get_payment_sources_request(wallet_handler, trustee_did, address1) res111 = await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req) source1 = \ json.loads(await payment.parse_get_payment_sources_response(libsovtoken_payment_method, res111))[0]['source'] if sig_count == 0: # add identity owner adder to send xfer adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, None) assert res['op'] == 'REPLY' req, _ = await payment.build_payment_req(wallet_handler, adder_did, json.dumps([source1]), json.dumps([{"recipient": address2, "amount": 100}]), None) res1 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) print(res1) assert res1['op'] == 'REPLY' elif sig_count == 1: # add adder to send xfer adder_did, adder_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did, adder_vk, None, adder_role) assert res['op'] == 'REPLY' req, _ = await payment.build_payment_req(wallet_handler, adder_did, json.dumps([source1]), json.dumps([{"recipient": address2, "amount": 100}]), None) res1 = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, adder_did, req)) print(res1) assert res1['op'] == 'REPLY' else: # add adders to send xfer adder_did1, adder_vk1 = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did1, adder_vk1, None, adder_role) assert res['op'] == 'REPLY' adder_did2, adder_vk2 = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did2, adder_vk2, None, adder_role) assert res['op'] == 'REPLY' adder_did3, adder_vk3 = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, adder_did3, adder_vk3, None, adder_role) assert res['op'] == 'REPLY' req, _ = await payment.build_payment_req(wallet_handler, adder_did1, json.dumps([source1]), json.dumps([{"recipient": address2, "amount": 100}]), None) req = await ledger.multi_sign_request(wallet_handler, adder_did1, req) req = await ledger.multi_sign_request(wallet_handler, adder_did2, req) req = await ledger.multi_sign_request(wallet_handler, adder_did3, req) res1 = json.loads(await ledger.submit_request(pool_handler, req)) print(res1) assert res1['op'] == 'REPLY' # TODO might make sense to move to separate module since other tests here # organized per txn type @pytest.mark.asyncio async def test_case_forbidden(self, pool_handler, wallet_handler, get_default_trustee): trustee_did, _ = get_default_trustee trustee_role, trustee_role_num = 'TRUSTEE', '0' logger.info("1 Adding new trustee to ledger") new_trustee_did, new_trustee_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym( pool_handler, wallet_handler, trustee_did, new_trustee_did, new_trustee_vk, None, trustee_role ) assert res['op'] == 'REPLY' logger.info("2 Setting forbidden auth rule for adding trustees") req = await ledger.build_auth_rule_request(trustee_did, '1', 'ADD', 'role', '*', trustee_role_num, json.dumps({ 'constraint_id': 'FORBIDDEN', })) res = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) assert res['op'] == 'REPLY' logger.info("3 Getting newly set forbidden constraint") req = await ledger.build_get_auth_rule_request(trustee_did, '1', 'ADD', 'role', '*', trustee_role_num) res = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) assert res['op'] == 'REPLY' assert res['result']['data'][0]['constraint']['constraint_id'] == 'FORBIDDEN' logger.info("4 Trying to add one more trustee") one_more_new_trustee_did, one_more_new_trustee_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym( pool_handler, wallet_handler, trustee_did, one_more_new_trustee_did, one_more_new_trustee_vk, None, trustee_role ) assert res['op'] == 'REJECT' # TODO might make sense to move to separate module since other tests here # organized per txn type @pytest.mark.asyncio async def test_case_auth_rules(self, pool_handler, wallet_handler, get_default_trustee): trustee_did, _ = get_default_trustee trustee_role, trustee_role_num = 'TRUSTEE', '0' steward_role, steward_role_num = 'STEWARD', '2' logger.info("1 Creating new steward") steward_did, steward_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, steward_did, steward_vk, None, steward_role) assert res['op'] == 'REPLY' logger.info("2 Creating some new trustee") _new_trustee_did, _new_trustee_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym(pool_handler, wallet_handler, trustee_did, _new_trustee_did, _new_trustee_vk, None, trustee_role) assert res['op'] == 'REPLY' logger.info("3 Trying to add new trustee using steward as submitter") new_trustee_did, new_trustee_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym( pool_handler, wallet_handler, steward_did, new_trustee_did, new_trustee_vk, None, trustee_role ) assert res['op'] == 'REJECT' logger.info("4 Trying to add new steward using steward as submitter") new_steward_did, new_steward_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym( pool_handler, wallet_handler, steward_did, new_steward_did, new_steward_vk, None, trustee_role ) assert res['op'] == 'REJECT' logger.info("5 Send auth rules txn to allow stewards to add new trustees and stewrds") one_steward_constraint = { 'constraint_id': 'ROLE', 'role': steward_role_num, 'sig_count': 1, 'need_to_be_owner': False, 'metadata': {} } req = await ledger.build_auth_rules_request(trustee_did, json.dumps([ { 'auth_type': '1', 'auth_action': 'ADD', 'field': 'role', 'old_value': '*', 'new_value': trustee_role_num, 'constraint': one_steward_constraint }, { 'auth_type': '1', 'auth_action': 'ADD', 'field': 'role', 'old_value': '*', 'new_value': steward_role_num, 'constraint': one_steward_constraint }, ])) res = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) assert res['op'] == 'REPLY' logger.info("6 Getting recently set auth rules") for role_num in (trustee_role_num, steward_role_num): req = await ledger.build_get_auth_rule_request(trustee_did, '1', 'ADD', 'role', '*', role_num) res = json.loads(await ledger.sign_and_submit_request(pool_handler, wallet_handler, trustee_did, req)) assert res['op'] == 'REPLY' assert res['result']['data'][0]['constraint'] == one_steward_constraint logger.info("7 Trying to add new trustee using trustee as submitter") res = await send_nym( pool_handler, wallet_handler, trustee_did, new_trustee_did, new_trustee_vk, None, trustee_role ) assert res['op'] == 'REJECT' logger.info("8 Trying to add new steward using trustee as submitter") res = await send_nym( pool_handler, wallet_handler, trustee_did, new_trustee_did, new_steward_vk, None, trustee_role ) assert res['op'] == 'REJECT' logger.info("9 Adding new trustee using steward as submitter") new_trustee_did, new_trustee_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym( pool_handler, wallet_handler, steward_did, new_trustee_did, new_trustee_vk, None, trustee_role ) assert res['op'] == 'REPLY' logger.info("10 Adding new steward using steward as submitter") new_steward_did, new_steward_vk = await did.create_and_store_my_did(wallet_handler, '{}') res = await send_nym( pool_handler, wallet_handler, steward_did, new_steward_did, new_steward_vk, None, trustee_role ) assert res['op'] == 'REPLY'
[((12, 9, 12, 36), 'logging.getLogger', 'logging.getLogger', ({(12, 27, 12, 35): '__name__'}, {}), '(__name__)', False, 'import logging\n'), ((15, 1, 15, 53), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', ({(15, 25, 15, 52): '"""docker_setup_and_teardown"""'}, {}), "('docker_setup_and_teardown')", False, 'import pytest\n'), ((18, 5, 23, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(18, 29, 18, 57): '"""adder_role, adder_role_num"""', (18, 59, 23, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((24, 5, 29, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(24, 29, 24, 59): '"""editor_role, editor_role_num"""', (24, 61, 29, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((84, 5, 89, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(84, 29, 84, 57): '"""adder_role, adder_role_num"""', (84, 59, 89, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((90, 5, 95, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(90, 29, 90, 59): '"""editor_role, editor_role_num"""', (90, 61, 95, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((159, 5, 164, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(159, 29, 159, 57): '"""adder_role, adder_role_num"""', (159, 59, 164, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((195, 5, 200, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(195, 29, 195, 57): '"""adder_role, adder_role_num"""', (195, 59, 200, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((201, 5, 206, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(201, 29, 201, 59): '"""editor_role, editor_role_num"""', (201, 61, 206, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((284, 5, 289, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(284, 29, 284, 57): '"""adder_role, adder_role_num"""', (284, 59, 289, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((290, 5, 295, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(290, 29, 290, 59): '"""editor_role, editor_role_num"""', (290, 61, 295, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((383, 5, 388, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(383, 29, 383, 57): '"""adder_role, adder_role_num"""', (383, 59, 388, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((389, 5, 394, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(389, 29, 389, 59): '"""editor_role, editor_role_num"""', (389, 61, 394, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((505, 5, 505, 34), 'pytest.mark.skip', 'pytest.mark.skip', ({(505, 22, 505, 33): '"""INDY-2024"""'}, {}), "('INDY-2024')", False, 'import pytest\n'), ((506, 5, 511, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(506, 29, 506, 57): '"""adder_role, adder_role_num"""', (506, 59, 511, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((512, 5, 517, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(512, 29, 512, 59): '"""editor_role, editor_role_num"""', (512, 61, 517, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((584, 5, 589, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(584, 29, 584, 57): '"""adder_role, adder_role_num"""', (584, 59, 589, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((590, 5, 595, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(590, 29, 590, 59): '"""editor_role, editor_role_num"""', (590, 61, 595, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((662, 5, 667, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(662, 29, 662, 57): '"""adder_role, adder_role_num"""', (662, 59, 667, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((698, 5, 703, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(698, 29, 698, 57): '"""adder_role, adder_role_num"""', (698, 59, 703, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((731, 5, 736, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(731, 29, 731, 59): '"""editor_role, editor_role_num"""', (731, 61, 736, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((762, 5, 767, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(762, 29, 762, 59): '"""editor_role, editor_role_num"""', (762, 61, 767, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((801, 5, 806, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(801, 29, 801, 57): '"""adder_role, adder_role_num"""', (801, 59, 806, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((807, 5, 807, 52), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(807, 29, 807, 40): '"""sig_count"""', (807, 42, 807, 51): '[0, 1, 3]'}, {}), "('sig_count', [0, 1, 3])", False, 'import pytest\n'), ((867, 5, 872, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(867, 29, 867, 59): '"""editor_role, editor_role_num"""', (867, 61, 872, 5): "[('NETWORK_MONITOR', '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), (\n 'TRUSTEE', '0')]"}, {}), "('editor_role, editor_role_num', [('NETWORK_MONITOR',\n '201'), ('TRUST_ANCHOR', '101'), ('STEWARD', '2'), ('TRUSTEE', '0')])", False, 'import pytest\n'), ((873, 5, 873, 52), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(873, 29, 873, 40): '"""sig_count"""', (873, 42, 873, 51): '[0, 1, 3]'}, {}), "('sig_count', [0, 1, 3])", False, 'import pytest\n'), ((932, 5, 937, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(932, 29, 932, 57): '"""adder_role, adder_role_num"""', (932, 59, 937, 5): "[('TRUSTEE', '0'), ('STEWARD', '2'), ('TRUST_ANCHOR', '101'), (\n 'NETWORK_MONITOR', '201')]"}, {}), "('adder_role, adder_role_num', [('TRUSTEE', '0'), (\n 'STEWARD', '2'), ('TRUST_ANCHOR', '101'), ('NETWORK_MONITOR', '201')])", False, 'import pytest\n'), ((938, 5, 938, 52), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(938, 29, 938, 40): '"""sig_count"""', (938, 42, 938, 51): '[0, 1, 3]'}, {}), "('sig_count', [0, 1, 3])", False, 'import pytest\n'), ((557, 22, 557, 34), 'random.randrange', 'rr', ({(557, 25, 557, 26): '1', (557, 28, 557, 33): '32767'}, {}), '(1, 32767)', True, 'from random import randrange as rr\n'), ((559, 20, 559, 32), 'random.randrange', 'rr', ({(559, 23, 559, 24): '1', (559, 26, 559, 31): '32767'}, {}), '(1, 32767)', True, 'from random import randrange as rr\n'), ((218, 14, 218, 30), 'asyncio.sleep', 'asyncio.sleep', ({(218, 28, 218, 29): '(1)'}, {}), '(1)', False, 'import asyncio\n'), ((307, 14, 307, 30), 'asyncio.sleep', 'asyncio.sleep', ({(307, 28, 307, 29): '(1)'}, {}), '(1)', False, 'import asyncio\n'), ((405, 14, 405, 30), 'asyncio.sleep', 'asyncio.sleep', ({(405, 28, 405, 29): '(1)'}, {}), '(1)', False, 'import asyncio\n'), ((556, 41, 556, 51), 'random.randrange', 'rr', ({(556, 44, 556, 45): '1', (556, 47, 556, 50): '255'}, {}), '(1, 255)', True, 'from random import randrange as rr\n'), ((556, 59, 556, 69), 'random.randrange', 'rr', ({(556, 62, 556, 63): '1', (556, 65, 556, 68): '255'}, {}), '(1, 255)', True, 'from random import randrange as rr\n'), ((558, 39, 558, 49), 'random.randrange', 'rr', ({(558, 42, 558, 43): '1', (558, 45, 558, 48): '255'}, {}), '(1, 255)', True, 'from random import randrange as rr\n'), ((558, 57, 558, 67), 'random.randrange', 'rr', ({(558, 60, 558, 61): '1', (558, 63, 558, 66): '255'}, {}), '(1, 255)', True, 'from random import randrange as rr\n'), ((676, 14, 676, 31), 'asyncio.sleep', 'asyncio.sleep', ({(676, 28, 676, 30): '(15)'}, {}), '(15)', False, 'import asyncio\n'), ((712, 14, 712, 31), 'asyncio.sleep', 'asyncio.sleep', ({(712, 28, 712, 30): '(15)'}, {}), '(15)', False, 'import asyncio\n'), ((788, 14, 788, 31), 'asyncio.sleep', 'asyncio.sleep', ({(788, 28, 788, 30): '(15)'}, {}), '(15)', False, 'import asyncio\n'), ((978, 23, 978, 103), 'indy.payment.build_get_payment_sources_request', 'payment.build_get_payment_sources_request', ({(978, 65, 978, 79): 'wallet_handler', (978, 81, 978, 92): 'trustee_did', (978, 94, 978, 102): 'address1'}, {}), '(wallet_handler, trustee_did, address1\n )', False, 'from indy import payment\n'), ((636, 18, 636, 34), 'hashlib.sha256', 'hashlib.sha256', ({}, {}), '()', False, 'import hashlib\n'), ((635, 49, 635, 78), 'datetime.datetime.now', 'datetime.now', (), '', False, 'from datetime import datetime, timedelta, timezone\n'), ((691, 51, 691, 80), 'datetime.datetime.now', 'datetime.now', (), '', False, 'from datetime import datetime, timedelta, timezone\n'), ((691, 83, 691, 104), 'datetime.timedelta', 'timedelta', (), '', False, 'from datetime import datetime, timedelta, timezone\n'), ((981, 29, 982, 79), 'indy.payment.parse_get_payment_sources_response', 'payment.parse_get_payment_sources_response', ({(981, 72, 981, 98): 'libsovtoken_payment_method', (982, 72, 982, 78): 'res111'}, {}), '(libsovtoken_payment_method, res111)', False, 'from indy import payment\n'), ((646, 37, 646, 66), 'datetime.datetime.now', 'datetime.now', (), '', False, 'from datetime import datetime, timedelta, timezone\n'), ((646, 69, 646, 105), 'datetime.timedelta', 'timedelta', (), '', False, 'from datetime import datetime, timedelta, timezone\n')]
jgough/opensearch-curator
test/integration/test_reindex.py
e8d7eb4d969eac551db9f99bd021d0c05e28dc35
import opensearchpy import curator import os import json import string import random import tempfile import click from click import testing as clicktest import time from . import CuratorTestCase from unittest.case import SkipTest from . import testvars as testvars import logging logger = logging.getLogger(__name__) host, port = os.environ.get('TEST_ES_SERVER', 'localhost:9200').split(':') rhost, rport = os.environ.get('REMOTE_ES_SERVER', 'localhost:9201').split(':') port = int(port) if port else 9200 rport = int(rport) if rport else 9201 class TestActionFileReindex(CuratorTestCase): def test_reindex_manual(self): wait_interval = 1 max_wait = 3 source = 'my_source' dest = 'my_dest' expected = 3 self.create_index(source) self.add_docs(source) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.reindex.format(wait_interval, max_wait, source, dest)) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.assertEqual(expected, self.client.count(index=dest)['count']) def test_reindex_selected(self): wait_interval = 1 max_wait = 3 source = 'my_source' dest = 'my_dest' expected = 3 self.create_index(source) self.add_docs(source) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.reindex.format(wait_interval, max_wait, 'REINDEX_SELECTION', dest)) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.assertEqual(expected, self.client.count(index=dest)['count']) def test_reindex_empty_list(self): wait_interval = 1 max_wait = 3 source = 'my_source' dest = 'my_dest' expected = '.tasks' self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.reindex.format(wait_interval, max_wait, source, dest)) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.assertEqual(expected, curator.get_indices(self.client)[0]) def test_reindex_selected_many_to_one(self): wait_interval = 1 max_wait = 3 source1 = 'my_source1' source2 = 'my_source2' dest = 'my_dest' expected = 6 self.create_index(source1) self.add_docs(source1) self.create_index(source2) for i in ["4", "5", "6"]: ver = curator.get_version(self.client) if ver >= (7, 0, 0): self.client.create( index=source2, doc_type='doc', id=i, body={"doc" + i :'TEST DOCUMENT'}) else: self.client.create( index=source2, doc_type='doc', id=i, body={"doc" + i :'TEST DOCUMENT'}) # Decorators make this pylint exception necessary # pylint: disable=E1123 self.client.indices.flush(index=source2, force=True) self.client.indices.refresh(index=source2) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config( self.args['actionfile'], testvars.reindex.format(wait_interval, max_wait, 'REINDEX_SELECTION', dest) ) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.client.indices.refresh(index=dest) self.assertEqual(expected, self.client.count(index=dest)['count']) def test_reindex_selected_empty_list_fail(self): wait_interval = 1 max_wait = 3 source1 = 'my_source1' source2 = 'my_source2' dest = 'my_dest' expected = 6 self.create_index(source1) self.add_docs(source1) self.create_index(source2) for i in ["4", "5", "6"]: self.client.create( index=source2, doc_type='log', id=i, body={"doc" + i :'TEST DOCUMENT'}, ) # Decorators make this pylint exception necessary # pylint: disable=E1123 self.client.indices.flush(index=source2, force=True) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.reindex_empty_list.format('false', wait_interval, max_wait, dest)) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.assertEqual(_.exit_code, 1) def test_reindex_selected_empty_list_pass(self): wait_interval = 1 max_wait = 3 source1 = 'my_source1' source2 = 'my_source2' dest = 'my_dest' expected = 6 self.create_index(source1) self.add_docs(source1) self.create_index(source2) for i in ["4", "5", "6"]: self.client.create( index=source2, doc_type='log', id=i, body={"doc" + i :'TEST DOCUMENT'}, ) # Decorators make this pylint exception necessary # pylint: disable=E1123 self.client.indices.flush(index=source2, force=True) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.reindex_empty_list.format('true', wait_interval, max_wait, dest)) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.assertEqual(_.exit_code, 0) def test_reindex_from_remote(self): wait_interval = 1 max_wait = 3 source1 = 'my_source1' source2 = 'my_source2' prefix = 'my_' dest = 'my_dest' expected = 6 # Build remote client try: rclient = curator.get_client( host=rhost, port=rport, skip_version_test=True) rclient.info() except: raise SkipTest( 'Unable to connect to host at {0}:{1}'.format(rhost, rport)) # Build indices remotely. counter = 0 for rindex in [source1, source2]: rclient.indices.create(index=rindex) for i in range(0, 3): rclient.create( index=rindex, doc_type='log', id=str(counter+1), body={"doc" + str(counter+i) :'TEST DOCUMENT'}, ) counter += 1 # Decorators make this pylint exception necessary # pylint: disable=E1123 rclient.indices.flush(index=rindex, force=True) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.remote_reindex.format( wait_interval, max_wait, 'http://{0}:{1}'.format(rhost, rport), 'REINDEX_SELECTION', dest, prefix ) ) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) # Do our own cleanup here. rclient.indices.delete(index='{0},{1}'.format(source1, source2)) self.assertEqual(expected, self.client.count(index=dest)['count']) def test_reindex_migrate_from_remote(self): wait_interval = 1 max_wait = 3 source1 = 'my_source1' source2 = 'my_source2' prefix = 'my_' dest = 'MIGRATION' expected = 3 # Build remote client try: rclient = curator.get_client( host=rhost, port=rport, skip_version_test=True) rclient.info() except: raise SkipTest( 'Unable to connect to host at {0}:{1}'.format(rhost, rport)) # Build indices remotely. counter = 0 for rindex in [source1, source2]: rclient.indices.create(index=rindex) for i in range(0, 3): rclient.create( index=rindex, doc_type='log', id=str(counter+1), body={"doc" + str(counter+i) :'TEST DOCUMENT'}, ) counter += 1 # Decorators make this pylint exception necessary # pylint: disable=E1123 rclient.indices.flush(index=rindex, force=True) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.remote_reindex.format( wait_interval, max_wait, 'http://{0}:{1}'.format(rhost, rport), 'REINDEX_SELECTION', dest, prefix ) ) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) # Do our own cleanup here. rclient.indices.delete(index='{0},{1}'.format(source1, source2)) # And now the neat trick of verifying that the reindex worked to both # indices, and they preserved their names self.assertEqual(expected, self.client.count(index=source1)['count']) self.assertEqual(expected, self.client.count(index=source2)['count']) def test_reindex_migrate_from_remote_with_pre_suf_fixes(self): wait_interval = 1 max_wait = 3 source1 = 'my_source1' source2 = 'my_source2' prefix = 'my_' dest = 'MIGRATION' expected = 3 mpfx = 'pre-' msfx = '-fix' # Build remote client try: rclient = curator.get_client( host=rhost, port=rport, skip_version_test=True) rclient.info() except: raise SkipTest( 'Unable to connect to host at {0}:{1}'.format(rhost, rport)) # Build indices remotely. counter = 0 for rindex in [source1, source2]: rclient.indices.create(index=rindex) for i in range(0, 3): rclient.create( index=rindex, doc_type='log', id=str(counter+1), body={"doc" + str(counter+i) :'TEST DOCUMENT'}, ) counter += 1 # Decorators make this pylint exception necessary # pylint: disable=E1123 rclient.indices.flush(index=rindex, force=True) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.migration_reindex.format( wait_interval, max_wait, mpfx, msfx, 'http://{0}:{1}'.format(rhost, rport), 'REINDEX_SELECTION', dest, prefix ) ) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) # Do our own cleanup here. rclient.indices.delete(index='{0},{1}'.format(source1, source2)) # And now the neat trick of verifying that the reindex worked to both # indices, and they preserved their names self.assertEqual(expected, self.client.count(index='{0}{1}{2}'.format(mpfx,source1,msfx))['count']) self.assertEqual(expected, self.client.count(index='{0}{1}{2}'.format(mpfx,source1,msfx))['count']) def test_reindex_from_remote_no_connection(self): wait_interval = 1 max_wait = 3 bad_port = 70000 dest = 'my_dest' expected = 1 self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.remote_reindex.format( wait_interval, max_wait, 'http://{0}:{1}'.format(rhost, bad_port), 'REINDEX_SELECTION', dest, 'my_' ) ) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.assertEqual(expected, _.exit_code) def test_reindex_from_remote_no_indices(self): wait_interval = 1 max_wait = 3 source1 = 'wrong1' source2 = 'wrong2' prefix = 'my_' dest = 'my_dest' expected = 1 # Build remote client try: rclient = curator.get_client( host=rhost, port=rport, skip_version_test=True) rclient.info() except: raise SkipTest( 'Unable to connect to host at {0}:{1}'.format(rhost, rport)) # Build indices remotely. counter = 0 for rindex in [source1, source2]: rclient.indices.create(index=rindex) for i in range(0, 3): rclient.create( index=rindex, doc_type='log', id=str(counter+1), body={"doc" + str(counter+i) :'TEST DOCUMENT'}, ) counter += 1 # Decorators make this pylint exception necessary # pylint: disable=E1123 rclient.indices.flush(index=rindex, force=True) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.remote_reindex.format( wait_interval, max_wait, 'http://{0}:{1}'.format(rhost, rport), 'REINDEX_SELECTION', dest, prefix ) ) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) # Do our own cleanup here. rclient.indices.delete(index='{0},{1}'.format(source1, source2)) self.assertEqual(expected, _.exit_code) def test_reindex_into_alias(self): wait_interval = 1 max_wait = 3 source = 'my_source' dest = 'my_dest' expected = 3 alias_body = {'aliases' : {dest : {}}} self.client.indices.create(index='dummy', body=alias_body) self.add_docs(source) self.write_config(self.args['configfile'], testvars.client_config.format(host, port)) self.write_config( self.args['actionfile'], testvars.reindex.format(wait_interval, max_wait, source, dest) ) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.assertEqual(expected, self.client.count(index=dest)['count']) def test_reindex_manual_date_math(self): wait_interval = 1 max_wait = 3 source = '<source-{now/d}>' dest = '<target-{now/d}>' expected = 3 self.create_index(source) self.add_docs(source) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.reindex.format(wait_interval, max_wait, source, dest)) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.assertEqual(expected, self.client.count(index=dest)['count']) def test_reindex_bad_mapping(self): # This test addresses GitHub issue #1260 wait_interval = 1 max_wait = 3 source = 'my_source' dest = 'my_dest' expected = 1 ver = curator.get_version(self.client) if ver < (7, 0, 0): request_body = { "settings": { "number_of_shards": 1, "number_of_replicas": 0}, "mappings": { "doc": { "properties": { "doc1": { "type": "keyword" }}}} } else: request_body = { "settings": { "number_of_shards": 1, "number_of_replicas": 0}, "mappings": { "properties": { "doc1": { "type": "keyword" }}} } self.client.indices.create(index=source, body=request_body) self.add_docs(source) # Create the dest index with a different mapping. if ver < (7, 0, 0): request_body['mappings']['doc']['properties']['doc1']['type'] = 'integer' else: request_body['mappings']['properties']['doc1']['type'] = 'integer' self.client.indices.create(index=dest, body=request_body) self.write_config( self.args['configfile'], testvars.client_config.format(host, port)) self.write_config(self.args['actionfile'], testvars.reindex.format(wait_interval, max_wait, source, dest)) test = clicktest.CliRunner() _ = test.invoke( curator.cli, ['--config', self.args['configfile'], self.args['actionfile']], ) self.assertEqual(expected, _.exit_code)
[((17, 9, 17, 36), 'logging.getLogger', 'logging.getLogger', ({(17, 27, 17, 35): '__name__'}, {}), '(__name__)', False, 'import logging\n'), ((19, 15, 19, 67), 'os.environ.get', 'os.environ.get', ({(19, 30, 19, 46): '"""TEST_ES_SERVER"""', (19, 50, 19, 66): '"""localhost:9200"""'}, {}), "('TEST_ES_SERVER', 'localhost:9200')", False, 'import os\n'), ((20, 15, 20, 67), 'os.environ.get', 'os.environ.get', ({(20, 30, 20, 48): '"""REMOTE_ES_SERVER"""', (20, 50, 20, 66): '"""localhost:9201"""'}, {}), "('REMOTE_ES_SERVER', 'localhost:9201')", False, 'import os\n'), ((38, 15, 38, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((57, 15, 57, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((74, 15, 74, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((109, 15, 109, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((139, 15, 139, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((168, 15, 168, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((216, 15, 216, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((267, 15, 267, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((326, 15, 326, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((356, 15, 356, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((404, 15, 404, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((425, 15, 425, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((444, 15, 444, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((457, 14, 457, 46), 'curator.get_version', 'curator.get_version', ({(457, 34, 457, 45): 'self.client'}, {}), '(self.client)', False, 'import curator\n'), ((481, 15, 481, 36), 'click.testing.CliRunner', 'clicktest.CliRunner', ({}, {}), '()', True, 'from click import testing as clicktest\n'), ((92, 18, 92, 50), 'curator.get_version', 'curator.get_version', ({(92, 38, 92, 49): 'self.client'}, {}), '(self.client)', False, 'import curator\n'), ((185, 22, 186, 63), 'curator.get_client', 'curator.get_client', (), '', False, 'import curator\n'), ((236, 22, 237, 63), 'curator.get_client', 'curator.get_client', (), '', False, 'import curator\n'), ((293, 22, 294, 63), 'curator.get_client', 'curator.get_client', (), '', False, 'import curator\n'), ((373, 22, 374, 63), 'curator.get_client', 'curator.get_client', (), '', False, 'import curator\n'), ((79, 35, 79, 67), 'curator.get_indices', 'curator.get_indices', ({(79, 55, 79, 66): 'self.client'}, {}), '(self.client)', False, 'import curator\n')]
naivekun/libhustpass
libhustpass/login.py
d8d487e3af996898e4a7b21b924fbf0fc4fbe419
import libhustpass.sbDes as sbDes import libhustpass.captcha as captcha import requests import re import random def toWideChar(data): data_bytes = bytes(data, encoding="utf-8") ret = [] for i in data_bytes: ret.extend([0, i]) while len(ret) % 8 != 0: ret.append(0) return ret def Enc(data, first_key, second_key, third_key): data_bytes = toWideChar(data) key1_bytes = toWideChar(first_key) key2_bytes = toWideChar(second_key) key3_bytes = toWideChar(third_key) ret_ = [] i = 0 while i < len(data_bytes): tmp = data_bytes[i : i + 8] x = 0 y = 0 z = 0 while x < len(key1_bytes): enc1_ = sbDes.des(key1_bytes[x : x + 8], sbDes.ECB) tmp = list(enc1_.encrypt(tmp)) x += 8 while y < len(key2_bytes): enc2_ = sbDes.des(key2_bytes[y : y + 8], sbDes.ECB) tmp = list(enc2_.encrypt(tmp)) y += 8 while z < len(key3_bytes): enc3_ = sbDes.des(key3_bytes[z : z + 8], sbDes.ECB) tmp = list(enc3_.encrypt(tmp)) z += 8 ret_.extend(tmp) i += 8 ret = "" for i in ret_: ret += "%02X" % i return ret def login(username, password, url): r = requests.session() login_html = r.get(url) captcha_content = r.get("https://pass.hust.edu.cn/cas/code?"+str(random.random()), stream=True) captcha_content.raw.decode_content = True nonce = re.search( '<input type="hidden" id="lt" name="lt" value="(.*)" />', login_html.text ).group(1) action = re.search( '<form id="loginForm" action="(.*)" method="post">', login_html.text ).group(1) post_params = { "code": captcha.deCaptcha(captcha_content.raw), "rsa": Enc(username + password + nonce, "1", "2", "3"), "ul": len(username), "pl": len(password), "lt": nonce, "execution": "e1s1", "_eventId": "submit", } redirect_html = r.post( "https://pass.hust.edu.cn" + action, data=post_params, allow_redirects=False ) try: return redirect_html.headers["Location"] except: raise Exception("login failed")
[((52, 8, 52, 26), 'requests.session', 'requests.session', ({}, {}), '()', False, 'import requests\n'), ((63, 16, 63, 54), 'libhustpass.captcha.deCaptcha', 'captcha.deCaptcha', ({(63, 34, 63, 53): 'captcha_content.raw'}, {}), '(captcha_content.raw)', True, 'import libhustpass.captcha as captcha\n'), ((30, 20, 30, 63), 'libhustpass.sbDes.des', 'sbDes.des', ({(30, 30, 30, 51): 'key1_bytes[x:x + 8]', (30, 53, 30, 62): 'sbDes.ECB'}, {}), '(key1_bytes[x:x + 8], sbDes.ECB)', True, 'import libhustpass.sbDes as sbDes\n'), ((34, 20, 34, 63), 'libhustpass.sbDes.des', 'sbDes.des', ({(34, 30, 34, 51): 'key2_bytes[y:y + 8]', (34, 53, 34, 62): 'sbDes.ECB'}, {}), '(key2_bytes[y:y + 8], sbDes.ECB)', True, 'import libhustpass.sbDes as sbDes\n'), ((38, 20, 38, 63), 'libhustpass.sbDes.des', 'sbDes.des', ({(38, 30, 38, 51): 'key3_bytes[z:z + 8]', (38, 53, 38, 62): 'sbDes.ECB'}, {}), '(key3_bytes[z:z + 8], sbDes.ECB)', True, 'import libhustpass.sbDes as sbDes\n'), ((56, 12, 58, 5), 're.search', 're.search', ({(57, 8, 57, 64): '"""<input type="hidden" id="lt" name="lt" value="(.*)" />"""', (57, 66, 57, 81): 'login_html.text'}, {}), '(\'<input type="hidden" id="lt" name="lt" value="(.*)" />\',\n login_html.text)', False, 'import re\n'), ((59, 13, 61, 5), 're.search', 're.search', ({(60, 8, 60, 59): '"""<form id="loginForm" action="(.*)" method="post">"""', (60, 61, 60, 76): 'login_html.text'}, {}), '(\'<form id="loginForm" action="(.*)" method="post">\', login_html.text)', False, 'import re\n'), ((54, 69, 54, 84), 'random.random', 'random.random', ({}, {}), '()', False, 'import random\n')]
Asadullah-Dal17/contours-detection-advance
code/contours_sorting_by_area.py
45522492363cc01cb8c66b18790b1859c4efe44d
import cv2 as cv import numpy as np def areaFinder(contours): areas = [] for c in contours: a =cv.contourArea(c) areas.append(a) return areas def sortedContoursByArea(img, larger_to_smaller=True): edges_img = cv.Canny(img, 100, 150) contours , h = cv.findContours(edges_img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE) sorted_contours = sorted(contours, key=cv.contourArea, reverse=larger_to_smaller) return sorted_contours img = cv.imread('./Images/sample-image.png') sorted_contours = sortedContoursByArea(img, larger_to_smaller=True) # print(areaFinder(contours)) print(areaFinder(sorted_contours)) for c in sorted_contours: cv.drawContours(img, c, -1, 244, 3) cv.imshow('img', img) cv.waitKey(0) cv.destroyAllWindows()
[((14, 6, 14, 44), 'cv2.imread', 'cv.imread', ({(14, 16, 14, 43): '"""./Images/sample-image.png"""'}, {}), "('./Images/sample-image.png')", True, 'import cv2 as cv\n'), ((22, 0, 22, 22), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ({}, {}), '()', True, 'import cv2 as cv\n'), ((10, 16, 10, 39), 'cv2.Canny', 'cv.Canny', ({(10, 25, 10, 28): 'img', (10, 30, 10, 33): '100', (10, 35, 10, 38): '150'}, {}), '(img, 100, 150)', True, 'import cv2 as cv\n'), ((11, 19, 11, 85), 'cv2.findContours', 'cv.findContours', ({(11, 35, 11, 44): 'edges_img', (11, 46, 11, 62): 'cv.RETR_EXTERNAL', (11, 64, 11, 84): 'cv.CHAIN_APPROX_NONE'}, {}), '(edges_img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)', True, 'import cv2 as cv\n'), ((19, 4, 19, 40), 'cv2.drawContours', 'cv.drawContours', ({(19, 20, 19, 23): 'img', (19, 25, 19, 26): 'c', (19, 29, 19, 31): '(-1)', (19, 33, 19, 36): '(244)', (19, 38, 19, 39): '(3)'}, {}), '(img, c, -1, 244, 3)', True, 'import cv2 as cv\n'), ((20, 4, 20, 25), 'cv2.imshow', 'cv.imshow', ({(20, 14, 20, 19): '"""img"""', (20, 21, 20, 24): 'img'}, {}), "('img', img)", True, 'import cv2 as cv\n'), ((21, 4, 21, 17), 'cv2.waitKey', 'cv.waitKey', ({(21, 15, 21, 16): '(0)'}, {}), '(0)', True, 'import cv2 as cv\n'), ((6, 11, 6, 28), 'cv2.contourArea', 'cv.contourArea', ({(6, 26, 6, 27): 'c'}, {}), '(c)', True, 'import cv2 as cv\n')]
ChrisRBXiong/MatchZoo-py
matchzoo/metrics/precision.py
8883d0933a62610d71fec0215dce643630e03b1c
"""Precision for ranking.""" import numpy as np from matchzoo.engine.base_metric import ( BaseMetric, sort_and_couple, RankingMetric ) class Precision(RankingMetric): """Precision metric.""" ALIAS = 'precision' def __init__(self, k: int = 1, threshold: float = 0.): """ :class:`PrecisionMetric` constructor. :param k: Number of results to consider. :param threshold: the label threshold of relevance degree. """ self._k = k self._threshold = threshold def __repr__(self) -> str: """:return: Formated string representation of the metric.""" return f"{self.ALIAS}@{self._k}({self._threshold})" def __call__(self, y_true: np.array, y_pred: np.array) -> float: """ Calculate precision@k. Example: >>> y_true = [0, 0, 0, 1] >>> y_pred = [0.2, 0.4, 0.3, 0.1] >>> Precision(k=1)(y_true, y_pred) 0.0 >>> Precision(k=2)(y_true, y_pred) 0.0 >>> Precision(k=4)(y_true, y_pred) 0.25 >>> Precision(k=5)(y_true, y_pred) 0.2 :param y_true: The ground true label of each document. :param y_pred: The predicted scores of each document. :return: Precision @ k :raises: ValueError: len(r) must be >= k. """ if self._k <= 0: raise ValueError(f"k must be greater than 0." f"{self._k} received.") coupled_pair = sort_and_couple(y_true, y_pred) precision = 0.0 for idx, (label, score) in enumerate(coupled_pair): if idx >= self._k: break if label > self._threshold: precision += 1. return precision / self._k
[((52, 23, 52, 54), 'matchzoo.engine.base_metric.sort_and_couple', 'sort_and_couple', ({(52, 39, 52, 45): 'y_true', (52, 47, 52, 53): 'y_pred'}, {}), '(y_true, y_pred)', False, 'from matchzoo.engine.base_metric import BaseMetric, sort_and_couple, RankingMetric\n')]
forkunited/ltprg
src/main/py/ltprg/config/seq.py
4e40d3571d229023df0f845c68643024e04bc202
from mung.torch_ext.eval import Loss from ltprg.model.seq import DataParameter, SequenceModelNoInput, SequenceModelInputToHidden, SequenceModelAttendedInput from ltprg.model.seq import VariableLengthNLLLoss # Expects config of the form: # { # data_parameter : { # seq : [SEQUENCE PARAMETER NAME] # input : [INPUT PARAMETER NAME] # } # name : [ID FOR MODEL] # arch_type : [SequenceModelNoInput|SequenceModelInputToHidden] # dropout : [DROPOUT] # rnn_layers : [RNN_LAYERS] # rnn_size : [SIZE OF RNN HIDDEN LAYER] # embedding_size : [EMBEDDING_SIZE] # rnn_type : [RNN TYPE] # (SequenceModelAttendedInput) attn_type : [EMBEDDING|OUTPUT] # (SequenceModelInputToHidden) conv_input : [INDICATOR OF WHETHER OR NOT TO CONVOLVE THE INPUT] # (SequenceModelInputToHidden|SequenceModelAttendedInput) conv_kernel : [KERNEL SIZE FOR CONVOLUTION] # (SequenceModelInputToHidden|SequenceModelAttendedInput) conv_stride : [STRIDE LENGTH FOR CONVOLUTION] # } def load_seq_model(config, D, gpu=False): data_parameter = DataParameter.make(**config["data_parameter"]) seq_field = data_parameter["seq"] utterance_size = D[seq_field].get_matrix(0).get_feature_set().get_token_count() dropout = float(config["dropout"]) rnn_layers = int(config["rnn_layers"]) rnn_size = int(config["rnn_size"]) embedding_size = int(config["embedding_size"]) rnn_type = config["rnn_type"] if config["arch_type"] == "SequenceModelNoInput": model = SequenceModelNoInput(config["name"], utterance_size, \ embedding_size, rnn_size, rnn_layers, dropout=dropout, rnn_type=rnn_type) elif config["arch_type"] == "SequenceModelAttendedInput": input_field = data_parameter["input"] input_size = D[input_field].get_feature_set().get_token_count() conv_kernel = int(config["conv_kernel"]) conv_stride = int(config["conv_stride"]) attn_type = "EMBEDDING" if "attn_type" in config: attn_type = config["attn_type"] model = SequenceModelAttendedInput(config["name"], utterance_size, input_size, \ embedding_size, rnn_size, rnn_layers, dropout=dropout, rnn_type=rnn_type, \ conv_kernel=conv_kernel, conv_stride=conv_stride, attn_type=attn_type) else: input_field = data_parameter["input"] input_size = D[input_field].get_feature_set().get_token_count() conv_input = False conv_kernel = 1 conv_stride = 1 if "conv_input" in config: conv_input = bool(int(config["conv_input"])) conv_kernel = int(config["conv_kernel"]) conv_stride = int(config["conv_stride"]) model = SequenceModelInputToHidden(config["name"], utterance_size, input_size, \ embedding_size, rnn_size, rnn_layers, dropout=dropout, rnn_type=rnn_type, \ conv_input=conv_input, conv_kernel=conv_kernel, conv_stride=conv_stride) return data_parameter, model # Expects config of the form: # { # data_parameter : { # seq : [SEQUENCE PARAMETER NAME] # input : [INPUT PARAMETER NAME] # }, # evaluations : [ # name : [NAME FOR EVALUATION] # type : (VariableLengthNLLLoss) # data : [NAME OF DATA SUBSET] # (Optional) data_size : [SIZE OF RANDOM SUBET OF DATA TO TAKE] # ] # } def load_evaluations(config, D, gpu=False): data_parameter = DataParameter.make(**config["data_parameter"]) evaluations = [] loss_criterion = VariableLengthNLLLoss(norm_dim=True) if gpu: loss_criterion = loss_criterion.cuda() for eval_config in config["evaluations"]: data = D[eval_config["data"]] if "data_size" in eval_config: data = data.get_random_subset(int(eval_config["data_size"])) if eval_config["type"] == "VariableLengthNLLLoss": loss = Loss(eval_config["name"], data, data_parameter, loss_criterion, norm_dim=True) evaluations.append(loss) else: raise ValueError("Invalid seq evaluation type in config (" + str(eval_config["type"])) return evaluations
[((24, 21, 24, 67), 'ltprg.model.seq.DataParameter.make', 'DataParameter.make', ({}, {}), "(**config['data_parameter'])", False, 'from ltprg.model.seq import DataParameter, SequenceModelNoInput, SequenceModelInputToHidden, SequenceModelAttendedInput\n'), ((78, 21, 78, 67), 'ltprg.model.seq.DataParameter.make', 'DataParameter.make', ({}, {}), "(**config['data_parameter'])", False, 'from ltprg.model.seq import DataParameter, SequenceModelNoInput, SequenceModelInputToHidden, SequenceModelAttendedInput\n'), ((81, 21, 81, 57), 'ltprg.model.seq.VariableLengthNLLLoss', 'VariableLengthNLLLoss', (), '', False, 'from ltprg.model.seq import VariableLengthNLLLoss\n'), ((35, 16, 36, 81), 'ltprg.model.seq.SequenceModelNoInput', 'SequenceModelNoInput', (), '', False, 'from ltprg.model.seq import DataParameter, SequenceModelNoInput, SequenceModelInputToHidden, SequenceModelAttendedInput\n'), ((45, 16, 47, 78), 'ltprg.model.seq.SequenceModelAttendedInput', 'SequenceModelAttendedInput', (), '', False, 'from ltprg.model.seq import DataParameter, SequenceModelNoInput, SequenceModelInputToHidden, SequenceModelAttendedInput\n'), ((58, 16, 60, 80), 'ltprg.model.seq.SequenceModelInputToHidden', 'SequenceModelInputToHidden', (), '', False, 'from ltprg.model.seq import DataParameter, SequenceModelNoInput, SequenceModelInputToHidden, SequenceModelAttendedInput\n'), ((91, 19, 91, 97), 'mung.torch_ext.eval.Loss', 'Loss', (), '', False, 'from mung.torch_ext.eval import Loss\n')]
sigseg5/nometa-tg
src/Utilities/metadata_worker.py
7d0d9f0cf5d8fd98a3808c07a5c44d30f1b13032
from shutil import move import piexif from PIL import Image def delete_metadata(full_path_to_img): """ This function used for remove metadata only from documents, if you send image 'as image' Telegram automatically removes all metadata at sending. This function removes all metadata via 'piexif' lib, saved image in '/app' folder, and after that move it to 'documents' folder. :param full_path_to_img: path to folder with documents e.g.'documents/image.jpg' """ piexif.remove(full_path_to_img, "clean_image.jpg") move("clean_image.jpg", "documents/clean_image.jpg") def delete_metadata_from_png(full_path_to_img): """ This function used for remove metadata only from png documents, if you send image 'as image' Telegram automatically removes all metadata at sending. This function removes all metadata via 'PIL' lib and saved image in 'documents' folder. :param full_path_to_img: path to folder with documents e.g.'documents/image.png' """ image = Image.open(full_path_to_img) image.save("documents/clean_image.png")
[((14, 4, 14, 54), 'piexif.remove', 'piexif.remove', ({(14, 18, 14, 34): 'full_path_to_img', (14, 36, 14, 53): '"""clean_image.jpg"""'}, {}), "(full_path_to_img, 'clean_image.jpg')", False, 'import piexif\n'), ((15, 4, 15, 56), 'shutil.move', 'move', ({(15, 9, 15, 26): '"""clean_image.jpg"""', (15, 28, 15, 55): '"""documents/clean_image.jpg"""'}, {}), "('clean_image.jpg', 'documents/clean_image.jpg')", False, 'from shutil import move\n'), ((25, 12, 25, 40), 'PIL.Image.open', 'Image.open', ({(25, 23, 25, 39): 'full_path_to_img'}, {}), '(full_path_to_img)', False, 'from PIL import Image\n')]
pbarton666/virtual_classroom
dkr-py310/docker-student-portal-310/course_files/begin_advanced/py_unit_2.py
a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675
#py_unit_2.py import unittest class FirstTest(unittest.TestCase): def setUp(self): "setUp() runs before every test" self.msg="Sorry, Charlie, but {} is not the same as {}." def tearDown(self): "tearDown runs after every test" pass def test_me(self): "this test should pass" first=1 second=2 self.assertEqual(first,1, msg=self.msg.format(first, second)) def test_failing(self): "this test should fail" first=1 second=2 self.assertEqual(second,1, msg=self.msg.format(first, second)) def test_passing(self): "this test should pass, too" self.assertEqual("b", "b") def test_passing_a_failing_test(self): "this test should pass, even though it 'fails'" self.assertNotEqual("a", "b") if __name__=='__main__': unittest.main()
[((30, 1, 30, 16), 'unittest.main', 'unittest.main', ({}, {}), '()', False, 'import unittest\n')]
Sciocatti/python_scheduler_and_clean_forced_exit
src/scheduled_task/__init__.py
4e5373ba33798c08096087058773412257230662
from .scheduled_task import ScheduledTask
[]
davidnegrazis/PyPlayText-Workshop
scripts/game.py
70156b73c1d2ab52daaef839b72450e331ff1e80
from sys import exit # ------------------------------------------------------------------------------ global dev_name global game_title dev_name = "" # enter your name in the quotes! game_title = "" # enter the game title in the quotes! # ------------------------------------------------------------------------------ # ---------- initial values ---------- # these are used to define the starting values of your game variables init_health = 100 init_mana = 200 init_boss_health = 50 # ---------- game variables ---------- # these will be used during the game health = 0 mana = 0 boss_health = 0 # ---------- some useful functions ---------- # initialize game variables def init(): global health global mana health = init_health mana = init_mana # game over def game_over(msg): print(msg) print("Play again? (y / n)") while (True): choice = input("> ") if (choice == "y"): start() break elif (choice == "n"): exit(0) else: print("Options: y / n") # ---------- room definitions ---------- # here is where you'll create the flow of the game! # room 0: where the game starts def room_0(): global health print("This is the first stage of the game. Create a custom description and get coding!") print("Current health: " + str(health)) choice = input("> "); if "end" in choice: game_over("The game is over") def start(): start_msg = "Now playing " + game_title + " by " + dev_name print(start_msg) init() room_0() # ---------- game start ---------- start()
[((43, 12, 43, 19), 'sys.exit', 'exit', ({(43, 17, 43, 18): '(0)'}, {}), '(0)', False, 'from sys import exit\n')]
moheed/algo
lc1108_defangip.py
921bb55852fa49d97e469694a64bffe6c285319e
class Solution: def defangIPaddr(self, address: str) -> str: i=0 j=0 strlist=list(address) defang=[] while i< len(strlist): if strlist[i] == '.': defang.append('[') defang.append('.') defang.append(']') else: defang.append(address[i]) i+=1 retstr="" # return string return (retstr.join(defang))
[]
gregbunce/assign_vista_pcts_to_sgid_addrpnts
src/elections_address_files/commands/zip_files.py
c1a3210e68c8c1e94c0b68547d0c26697de77ff7
import os, zipfile # Zip files. def zipfiles(directory): # File extension to zip. #ext = ('.gdb', '.csv') ext = ('.gdb') # Iterate over all files and check for desired extentions for zipping. for file in os.listdir(directory): if file.endswith(ext): #: Zip it. input_fgdb_name = file.rsplit( ".", 1)[0] output_zipped_fgdb_name = "/" + input_fgdb_name + "_gdb.zip" full_path_to_fgdb = directory + "/" + file print(" Zipping " + str(full_path_to_fgdb)) outFile = f'{full_path_to_fgdb[0:-4]}_gdb.zip' gdbName = os.path.basename(full_path_to_fgdb) with zipfile.ZipFile(outFile,mode='w',compression=zipfile.ZIP_DEFLATED,allowZip64=True) as myzip: for f in os.listdir(full_path_to_fgdb): if f[-5:] != '.lock': myzip.write(os.path.join(full_path_to_fgdb,f),gdbName+'\\'+os.path.basename(f)) else: continue
[((11, 16, 11, 37), 'os.listdir', 'os.listdir', ({(11, 27, 11, 36): 'directory'}, {}), '(directory)', False, 'import os, zipfile\n'), ((21, 22, 21, 57), 'os.path.basename', 'os.path.basename', ({(21, 39, 21, 56): 'full_path_to_fgdb'}, {}), '(full_path_to_fgdb)', False, 'import os, zipfile\n'), ((23, 17, 23, 99), 'zipfile.ZipFile', 'zipfile.ZipFile', (), '', False, 'import os, zipfile\n'), ((24, 25, 24, 54), 'os.listdir', 'os.listdir', ({(24, 36, 24, 53): 'full_path_to_fgdb'}, {}), '(full_path_to_fgdb)', False, 'import os, zipfile\n'), ((26, 36, 26, 69), 'os.path.join', 'os.path.join', ({(26, 49, 26, 66): 'full_path_to_fgdb', (26, 67, 26, 68): 'f'}, {}), '(full_path_to_fgdb, f)', False, 'import os, zipfile\n'), ((26, 83, 26, 102), 'os.path.basename', 'os.path.basename', ({(26, 100, 26, 101): 'f'}, {}), '(f)', False, 'import os, zipfile\n')]
erezsh/tartiflette
tartiflette/parser/nodes/node.py
c945b02e9025e2524393c1eaec2191745bfc38f4
class Node: def __init__(self, path, libgraphql_type, location, name): self.path = path self.parent = None self.children = [] self.libgraphql_type = libgraphql_type self.location = location self.name = name def __repr__(self): return "%s(%s)" % (self.libgraphql_type, self.name)
[]
yuyiming/mars
mars/services/web/tests/test_core.py
5e6990d1ea022444dd646c56697e596ef5d7e747
# Copyright 1999-2021 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 asyncio import os import sys import pytest from tornado import httpclient from .... import oscar as mo from ....utils import get_next_port from .. import WebActor, web_api, MarsServiceWebAPIHandler, MarsWebAPIClientMixin from ..api.web import MarsApiEntryHandler class TestAPIHandler(MarsServiceWebAPIHandler): __test__ = False _root_pattern = "/api/test/(?P<test_id>[^/]+)" @web_api("", method="get") def get_method_root(self, test_id): self.write(f"get_root_value_{test_id}") @web_api("", method="post") def post_method_root(self, test_id): self.write(f"post_root_value_{test_id}") @web_api("subtest/(?P<subtest_id>[^/]+)", method="get") def get_method_sub_patt(self, test_id, subtest_id): self.write(f"get_sub_value_{test_id}_{subtest_id}") @web_api("subtest/(?P<subtest_id>[^/]+)", method="get", arg_filter={"action": "a1"}) async def get_method_sub_patt_match_arg1(self, test_id, subtest_id): self.write(f"get_sub_value_{test_id}_{subtest_id}_action1") @web_api("subtest/(?P<subtest_id>[^/]+)", method="get", arg_filter={"action": "a2"}) async def get_method_sub_patt_match_arg2(self, test_id, subtest_id): self.write(f"get_sub_value_{test_id}_{subtest_id}_action2") @web_api("subtest_error", method="get") def get_with_error(self, test_id): raise ValueError @web_api("subtest_delay", method="get") async def get_with_timeout(self, test_id): await asyncio.sleep(100) raise ValueError(test_id) @pytest.fixture async def actor_pool(): start_method = ( os.environ.get("POOL_START_METHOD", "forkserver") if sys.platform != "win32" else None ) pool = await mo.create_actor_pool( "127.0.0.1", n_process=0, subprocess_start_method=start_method ) async with pool: web_config = { "host": "127.0.0.1", "port": get_next_port(), "web_handlers": { "/api": MarsApiEntryHandler, TestAPIHandler.get_root_pattern(): TestAPIHandler, }, "extra_discovery_modules": ["mars.services.web.tests.extra_handler"], } await mo.create_actor(WebActor, web_config, address=pool.external_address) yield pool, web_config["port"] class SimpleWebClient(MarsWebAPIClientMixin): async def fetch(self, path, method="GET", **kwargs): return await self._request_url(method, path, **kwargs) @pytest.mark.asyncio async def test_web_api(actor_pool): _pool, web_port = actor_pool recorded_urls = [] def url_recorder(request): recorded_urls.append(request.url) return request client = SimpleWebClient() client.request_rewriter = url_recorder res = await client.fetch(f"http://localhost:{web_port}/") assert res.body.decode() res = await client.fetch(f"http://localhost:{web_port}/api") assert res.body.decode() res = await client.fetch(f"http://localhost:{web_port}/api/test/test_id") assert res.body.decode() == "get_root_value_test_id" res = await client.fetch( f"http://localhost:{web_port}/api/test/test_id", method="POST", data=b"" ) assert res.body.decode() == "post_root_value_test_id" res = await client.fetch( f"http://localhost:{web_port}/api/test/test_id/subtest/sub_tid" ) assert res.body.decode() == "get_sub_value_test_id_sub_tid" res = await client.fetch( f"http://localhost:{web_port}/api/test/test_id/subtest/sub_tid?action=a1" ) assert res.body.decode() == "get_sub_value_test_id_sub_tid_action1" res = await client.fetch( f"http://localhost:{web_port}/api/test/test_id/subtest/sub_tid?action=a2" ) assert res.body.decode() == "get_sub_value_test_id_sub_tid_action2" with pytest.raises(httpclient.HTTPError) as excinfo: await client.fetch(f"http://localhost:{web_port}/api/test/test_id/non_exist") assert excinfo.value.code == 404 with pytest.raises(ValueError): await client.fetch( f"http://localhost:{web_port}/api/test/test_id/subtest_error" ) with pytest.raises(TimeoutError): await client.fetch( f"http://localhost:{web_port}/api/test/test_id/subtest_delay", request_timeout=0.5, ) res = await client.fetch(f"http://localhost:{web_port}/api/extra_test") assert "Test" in res.body.decode() assert len(recorded_urls) > 0
[((65, 8, 65, 57), 'os.environ.get', 'os.environ.get', ({(65, 23, 65, 42): '"""POOL_START_METHOD"""', (65, 44, 65, 56): '"""forkserver"""'}, {}), "('POOL_START_METHOD', 'forkserver')", False, 'import os\n'), ((132, 9, 132, 44), 'pytest.raises', 'pytest.raises', ({(132, 23, 132, 43): 'httpclient.HTTPError'}, {}), '(httpclient.HTTPError)', False, 'import pytest\n'), ((136, 9, 136, 34), 'pytest.raises', 'pytest.raises', ({(136, 23, 136, 33): 'ValueError'}, {}), '(ValueError)', False, 'import pytest\n'), ((141, 9, 141, 36), 'pytest.raises', 'pytest.raises', ({(141, 23, 141, 35): 'TimeoutError'}, {}), '(TimeoutError)', False, 'import pytest\n'), ((58, 14, 58, 32), 'asyncio.sleep', 'asyncio.sleep', ({(58, 28, 58, 31): '(100)'}, {}), '(100)', False, 'import asyncio\n')]
caizhanjin/deepseg
test/test.py
5e91a387683ad73075b51b49da8957d8f4bb6b7f
""" 例子为MNIST,对手写图片进行分类。 神经网络hello world。 """ import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # 封装网络用到的API def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides= [1, 1, 1, 1], padding= 'SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize= [1, 2, 2, 1], strides= [1, 2, 2, 1], padding='SAME') """ MNIST进阶 """ sess = tf.InteractiveSession() # [batch_size, 784] x = tf.placeholder('float', shape=[None, 784]) y_ = tf.placeholder('float', shape=[None, 10]) """ 第一层卷积 """ W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) # [batch_size, 28, 28, 1] x_image = tf.reshape(x, [-1, 28, 28, 1]) # [batch_size, 28, 28, 32] h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # [batch_size, 14, 14, 32] h_pool1 = max_pool_2x2(h_conv1) """ 第二层卷积 """ W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) # [batch_size, 14, 14, 64] h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # [batch_size, 7, 7, 64] h_pool2 = max_pool_2x2(h_conv2) """ 全连接层 """ w_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) # [batch_size, 7*7*64] h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) # [batch_size, 1024] h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1) """ dropout """ keep_prob = tf.placeholder("float") h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) """ 输出层 """ W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) # [batch_size, 10] y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) y_sum = tf.reduce_sum(y_conv[0]) # 计算损失和添加优化器 cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # 评估模型 correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # 初始化 sess.run(tf.initialize_all_variables()) for i in range(1): batch = mnist.train.next_batch(50) # train_accuracy = accuracy.eval(feed_dict={x:batch[0], # y_: batch[1], # keep_prob: 1.0}) # print("step %d, training accuracy %g" % (i, train_accuracy)) y_conv_re = y_conv.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) # print(y_conv_re.shape) print(y_conv_re) y_sum_re = y_sum.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) print(y_sum_re) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) print("test accuracy %g" % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
[((8, 8, 8, 61), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (), '', False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), ((40, 7, 40, 30), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((42, 4, 42, 46), 'tensorflow.placeholder', 'tf.placeholder', (), '', True, 'import tensorflow as tf\n'), ((43, 5, 43, 46), 'tensorflow.placeholder', 'tf.placeholder', (), '', True, 'import tensorflow as tf\n'), ((52, 10, 52, 40), 'tensorflow.reshape', 'tf.reshape', ({(52, 21, 52, 22): 'x', (52, 24, 52, 39): '[-1, 28, 28, 1]'}, {}), '(x, [-1, 28, 28, 1])', True, 'import tensorflow as tf\n'), ((77, 15, 77, 52), 'tensorflow.reshape', 'tf.reshape', ({(77, 26, 77, 33): 'h_pool2', (77, 35, 77, 51): '[-1, 7 * 7 * 64]'}, {}), '(h_pool2, [-1, 7 * 7 * 64])', True, 'import tensorflow as tf\n'), ((84, 12, 84, 35), 'tensorflow.placeholder', 'tf.placeholder', ({(84, 27, 84, 34): '"""float"""'}, {}), "('float')", True, 'import tensorflow as tf\n'), ((85, 13, 85, 44), 'tensorflow.nn.dropout', 'tf.nn.dropout', ({(85, 27, 85, 32): 'h_fc1', (85, 34, 85, 43): 'keep_prob'}, {}), '(h_fc1, keep_prob)', True, 'import tensorflow as tf\n'), ((95, 8, 95, 32), 'tensorflow.reduce_sum', 'tf.reduce_sum', ({(95, 22, 95, 31): 'y_conv[0]'}, {}), '(y_conv[0])', True, 'import tensorflow as tf\n'), ((14, 14, 14, 52), 'tensorflow.truncated_normal', 'tf.truncated_normal', (), '', True, 'import tensorflow as tf\n'), ((15, 11, 15, 31), 'tensorflow.Variable', 'tf.Variable', ({(15, 23, 15, 30): 'initial'}, {}), '(initial)', True, 'import tensorflow as tf\n'), ((19, 14, 19, 43), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((20, 11, 20, 31), 'tensorflow.Variable', 'tf.Variable', ({(20, 23, 20, 30): 'initial'}, {}), '(initial)', True, 'import tensorflow as tf\n'), ((24, 11, 27, 40), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (), '', True, 'import tensorflow as tf\n'), ((31, 11, 34, 41), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (), '', True, 'import tensorflow as tf\n'), ((102, 30, 102, 50), 'tensorflow.argmax', 'tf.argmax', ({(102, 40, 102, 46): 'y_conv', (102, 48, 102, 49): '1'}, {}), '(y_conv, 1)', True, 'import tensorflow as tf\n'), ((102, 52, 102, 68), 'tensorflow.argmax', 'tf.argmax', ({(102, 62, 102, 64): 'y_', (102, 66, 102, 67): '1'}, {}), '(y_, 1)', True, 'import tensorflow as tf\n'), ((103, 26, 103, 62), 'tensorflow.cast', 'tf.cast', ({(103, 34, 103, 52): 'correct_prediction', (103, 54, 103, 61): '"""float"""'}, {}), "(correct_prediction, 'float')", True, 'import tensorflow as tf\n'), ((106, 9, 106, 38), 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((79, 19, 79, 49), 'tensorflow.matmul', 'tf.matmul', ({(79, 29, 79, 41): 'h_pool2_flat', (79, 43, 79, 48): 'w_fc1'}, {}), '(h_pool2_flat, w_fc1)', True, 'import tensorflow as tf\n'), ((94, 23, 94, 51), 'tensorflow.matmul', 'tf.matmul', ({(94, 33, 94, 43): 'h_fc1_drop', (94, 45, 94, 50): 'W_fc2'}, {}), '(h_fc1_drop, W_fc2)', True, 'import tensorflow as tf\n'), ((99, 13, 99, 41), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ({(99, 36, 99, 40): '0.0001'}, {}), '(0.0001)', True, 'import tensorflow as tf\n'), ((98, 36, 98, 50), 'tensorflow.log', 'tf.log', ({(98, 43, 98, 49): 'y_conv'}, {}), '(y_conv)', True, 'import tensorflow as tf\n')]
jwvhewitt/gearhead-caramel
game/content/ghplots/lancemates.py
dfe1bc5dbf2960b82a97577f4bf687b60040d8bf
import pbge from game.content.plotutility import LMSkillsSelfIntro from game.content import backstory from pbge.plots import Plot from pbge.dialogue import Offer, ContextTag from game.ghdialogue import context import gears import game.content.gharchitecture import game.content.ghterrain import random from game import memobrowser Memo = memobrowser.Memo # ******************* # *** UTILITIES *** # ******************* def get_hire_cost(camp, npc): return (npc.renown * npc.renown * (200 - npc.get_reaction_score(camp.pc, camp)))//10 # ************************** # *** RANDOM_LANCEMATE *** # ************************** class UtterlyRandomLancemate(Plot): LABEL = "RANDOM_LANCEMATE" def custom_init(self, nart): npc = gears.selector.random_character(rank=min(random.randint(10, 50),random.randint(10, 50)), mecha_colors=gears.color.random_mecha_colors(), local_tags=tuple(self.elements["METROSCENE"].attributes), combatant=True) scene = self.seek_element(nart, "LOCALE", self._is_best_scene, scope=self.elements["METROSCENE"]) specialties = [sk for sk in gears.stats.NONCOMBAT_SKILLS if sk in npc.statline] if random.randint(-12,3) > len(specialties): npc.statline[random.choice(gears.stats.NONCOMBAT_SKILLS)] += random.randint(1,4) self.register_element("NPC", npc, dident="LOCALE") self.add_sub_plot(nart, "RLM_Relationship") return True def _is_best_scene(self,nart,candidate): return isinstance(candidate,pbge.scenes.Scene) and gears.tags.SCENE_PUBLIC in candidate.attributes class UtterlyGenericLancemate(Plot): LABEL = "RANDOM_LANCEMATE" JOBS = ("Mecha Pilot","Arena Pilot","Recon Pilot","Mercenary","Bounty Hunter") def custom_init(self, nart): npc = gears.selector.random_character(rank=min(random.randint(10, 50),random.randint(10, 50)), job=gears.jobs.ALL_JOBS[random.choice(self.JOBS)], mecha_colors=gears.color.random_mecha_colors(), local_tags=tuple(self.elements["METROSCENE"].attributes), combatant=True) if random.randint(1,20) == 1: npc.statline[random.choice(gears.stats.NONCOMBAT_SKILLS)] += random.randint(1,4) scene = self.seek_element(nart, "LOCALE", self._is_best_scene, scope=self.elements["METROSCENE"]) self.register_element("NPC", npc, dident="LOCALE") self.add_sub_plot(nart, "RLM_Relationship") return True def _is_best_scene(self,nart,candidate): return isinstance(candidate,pbge.scenes.Scene) and gears.tags.SCENE_PUBLIC in candidate.attributes class GiftedNewbieLancemate(Plot): # Amazing stats, amazingly crap skills. LABEL = "RANDOM_LANCEMATE" JOBS = ("Mecha Pilot","Arena Pilot","Citizen","Explorer","Factory Worker") UNIQUE = True def custom_init(self, nart): npc = gears.selector.random_character(statline=gears.base.Being.random_stats(random.randint(100, 110)), rank=random.randint(5, 15), job=gears.jobs.ALL_JOBS[random.choice(self.JOBS)], mecha_colors=gears.color.random_mecha_colors(), local_tags=tuple(self.elements["METROSCENE"].attributes), combatant=True, birth_year=nart.camp.year - random.randint(18,23)) if random.randint(1,10) == 1: npc.statline[random.choice(gears.stats.NONCOMBAT_SKILLS)] += random.randint(1,4) scene = self.seek_element(nart, "LOCALE", self._is_best_scene, scope=self.elements["METROSCENE"]) self.register_element("NPC", npc, dident="LOCALE") self.add_sub_plot(nart, "RLM_Relationship") return True def _is_best_scene(self,nart,candidate): return isinstance(candidate,pbge.scenes.Scene) and gears.tags.SCENE_PUBLIC in candidate.attributes class OlderMentorLancemate(Plot): LABEL = "RANDOM_LANCEMATE" UNIQUE = True def custom_init(self, nart): npc = gears.selector.random_character(rank=random.randint(41, 85), mecha_colors=gears.color.random_mecha_colors(), local_tags=tuple(self.elements["METROSCENE"].attributes), combatant=True, birth_year=nart.camp.year - random.randint(32,50)) npc.statline[random.choice(gears.stats.NONCOMBAT_SKILLS)] += random.randint(1, 4) scene = self.seek_element(nart, "LOCALE", self._is_best_scene, scope=self.elements["METROSCENE"]) self.register_element("NPC", npc, dident="LOCALE") self.add_sub_plot(nart, "RLM_Relationship") return True def _is_best_scene(self,nart,candidate): return isinstance(candidate,pbge.scenes.Scene) and gears.tags.SCENE_PUBLIC in candidate.attributes class DeadzonerInGreenZoneLancemate(Plot): LABEL = "RANDOM_LANCEMATE" JOBS = ("Mercenary","Bandit","Scavenger","Aristo","Tekno","Sheriff") UNIQUE = True @classmethod def matches( self, pstate ): """Returns True if this plot matches the current plot state.""" return gears.personality.GreenZone in pstate.elements["METROSCENE"].attributes def custom_init(self, nart): npc = gears.selector.random_character(rank=min(random.randint(20, 55),random.randint(20, 55)), job=gears.jobs.ALL_JOBS[random.choice(self.JOBS)], mecha_colors=gears.color.random_mecha_colors(), local_tags=(gears.personality.DeadZone,), combatant=True) scene = self.seek_element(nart, "LOCALE", self._is_best_scene, scope=self.elements["METROSCENE"]) self.register_element("NPC", npc, dident="LOCALE") self.add_sub_plot(nart, "RLM_Relationship") return True def _is_best_scene(self,nart,candidate): return isinstance(candidate,pbge.scenes.Scene) and gears.tags.SCENE_PUBLIC in candidate.attributes class GladiatorLancemate(Plot): LABEL = "RANDOM_LANCEMATE" UNIQUE = True @classmethod def matches( self, pstate ): """Returns True if this plot matches the current plot state.""" return gears.personality.DeadZone in pstate.elements["METROSCENE"].attributes def custom_init(self, nart): npc = gears.selector.random_character(rank=min(random.randint(25, 65),random.randint(25, 65)), can_cyberize=True, job=gears.jobs.ALL_JOBS["Gladiator"], mecha_colors=gears.color.random_mecha_colors(), local_tags=(gears.personality.DeadZone,), combatant=True) scene = self.seek_element(nart, "LOCALE", self._is_best_scene, scope=self.elements["METROSCENE"]) self.register_element("NPC", npc, dident="LOCALE") self.add_sub_plot(nart, "RLM_Relationship") return True def _is_best_scene(self,nart,candidate: gears.GearHeadScene): return isinstance(candidate,pbge.scenes.Scene) and gears.tags.SCENE_PUBLIC in candidate.attributes class MutantLancemate(Plot): LABEL = "RANDOM_LANCEMATE" UNIQUE = True @classmethod def matches( self, pstate ): """Returns True if this plot matches the current plot state.""" return {gears.personality.GreenZone,gears.personality.DeadZone}.intersection(pstate.elements["METROSCENE"].attributes) def custom_init(self, nart): npc = gears.selector.random_character(rank=random.randint(20, 45), mecha_colors=gears.color.random_mecha_colors(), local_tags=tuple(self.elements["METROSCENE"].attributes), combatant=True) scene = self.seek_element(nart, "LOCALE", self._is_best_scene, scope=self.elements["METROSCENE"]) mutation = random.choice(gears.personality.MUTATIONS) mutation.apply(npc) npc.personality.add(mutation) specialties = [sk for sk in gears.stats.NONCOMBAT_SKILLS if sk in npc.statline] if random.randint(-12,3) > len(specialties): npc.statline[random.choice(gears.stats.NONCOMBAT_SKILLS)] += random.randint(1,4) self.register_element("NPC", npc, dident="LOCALE") self.add_sub_plot(nart, "RLM_Relationship") return True def _is_best_scene(self,nart,candidate): return isinstance(candidate, pbge.scenes.Scene) and gears.tags.SCENE_PUBLIC in candidate.attributes class FormerLancemateReturns(Plot): LABEL = "RANDOM_LANCEMATE" active = True scope = "METRO" def custom_init(self, nart): npc: gears.base.Character = nart.camp.egg.seek_dramatis_person(nart.camp, self._is_good_npc, self) if npc: scene = self.seek_element(nart, "LOCALE", self._is_best_scene, scope=self.elements["METROSCENE"]) self.register_element("NPC", npc, dident="LOCALE") #print(npc,scene) self.bs = backstory.Backstory(("LONGTIMENOSEE",),keywords=[t.name.upper() for t in npc.get_tags()]) return npc def _is_good_npc(self,nart,candidate): return isinstance(candidate, gears.base.Character) and candidate.relationship and gears.relationships.RT_LANCEMATE in candidate.relationship.tags def _is_best_scene(self,nart,candidate): return isinstance(candidate,gears.GearHeadScene) and gears.tags.SCENE_PUBLIC in candidate.attributes def _get_dialogue_grammar(self, npc, camp): mygram = dict() if npc is self.elements["NPC"]: for k in self.bs.results.keys(): mygram[k] = [self.bs.get_one(k),] else: mygram["[News]"] = ["{NPC} has been hanging out at {LOCALE}".format(**self.elements), ] return mygram def NPC_offers(self, camp): mylist = list() mylist.append(Offer("[INFO_PERSONAL]", context=ContextTag([context.PERSONAL]), no_repeats=True, effect=self.end_plot)) return mylist def t_START(self, camp): if self.elements["NPC"] in camp.party: self.end_plot(camp) # ************************** # *** RLM_Relationship *** # ************************** # Elements: # NPC: The NPC who needs a personality # METROSCENE: The city or whatever that the NPC calls home # # These subplots contain a personality for a random (potential) lancemate. # Also include a means for the lancemate to gain the "RT_LANCEMATE" tag. class RLM_Beginner(Plot): LABEL = "RLM_Relationship" active = True scope = True UNIQUE = True @classmethod def matches( self, pstate ): """Returns True if this plot matches the current plot state.""" return pstate.elements["NPC"].renown < 25 def custom_init(self, nart): npc = self.elements["NPC"] npc.relationship = gears.relationships.Relationship(attitude=gears.relationships.A_JUNIOR) # This character gets fewer mecha points. npc.relationship.data["mecha_level_bonus"] = -10 self._got_rumor = False return True def NPC_offers(self, camp): mylist = list() npc = self.elements["NPC"] if gears.relationships.RT_LANCEMATE not in npc.relationship.tags: if camp.can_add_lancemate(): mylist.append(Offer("I can't believe you asked me... [LETSGO]", context=ContextTag((context.JOIN,)), effect=self._join_lance )) mylist.append(Offer( "[HELLO] Some day I want to become a cavalier like you.", context=ContextTag((context.HELLO,)) )) mylist.append(LMSkillsSelfIntro(npc)) return mylist def _get_dialogue_grammar(self, npc, camp): mygram = dict() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"]: # This is an NPC in Wujung. Give them some news. mygram["[News]"] = ["{} has dreams of someday becoming a cavalier".format(self.elements["NPC"]), ] return mygram def _join_lance(self, camp): npc = self.elements["NPC"] npc.relationship.tags.add(gears.relationships.RT_LANCEMATE) effect = game.content.plotutility.AutoJoiner(npc) effect(camp) self.end_plot(camp) def _get_generic_offers(self, npc, camp): """Get any offers that could apply to non-element NPCs.""" goffs = list() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"] and not self._got_rumor: mynpc = self.elements["NPC"] goffs.append(Offer( msg="As far as I know {} usually hangs out at {}.".format(mynpc,mynpc.get_scene()), context=ContextTag((context.INFO,)), effect=self._get_rumor, subject=str(mynpc), data={"subject": str(mynpc)}, no_repeats=True )) return goffs def _get_rumor(self,camp): mynpc = self.elements["NPC"] self._got_rumor = True self.memo = Memo( "{} dreams of becoming a cavalier.".format(mynpc) , mynpc.get_scene() ) class RLM_Friendly(Plot): LABEL = "RLM_Relationship" active = True scope = True UNIQUE = True def custom_init(self, nart): npc = self.elements["NPC"] npc.relationship = gears.relationships.Relationship(attitude=gears.relationships.A_FRIENDLY) self._got_rumor = False return True def NPC_offers(self, camp): mylist = list() npc = self.elements["NPC"] if gears.relationships.RT_LANCEMATE not in npc.relationship.tags: if camp.can_add_lancemate() and npc.get_reaction_score(camp.pc, camp) > 0: mylist.append(Offer("[THANKS_FOR_CHOOSING_ME] [LETSGO]", context=ContextTag((context.JOIN,)), effect=self._join_lance )) mylist.append(Offer( "[HELLO] [WAITINGFORMISSION]", context=ContextTag((context.HELLO,)) )) mylist.append(LMSkillsSelfIntro(npc)) return mylist def _join_lance(self, camp): npc = self.elements["NPC"] npc.relationship.tags.add(gears.relationships.RT_LANCEMATE) effect = game.content.plotutility.AutoJoiner(npc) effect(camp) self.end_plot(camp) def _get_dialogue_grammar(self, npc, camp): mygram = dict() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"] and not self._got_rumor: # This is an NPC in Wujung. Give them some news. mygram["[News]"] = ["{} is looking for a lance to join".format(self.elements["NPC"]), ] return mygram def _get_generic_offers(self, npc, camp): """Get any offers that could apply to non-element NPCs.""" goffs = list() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"] and not self._got_rumor: mynpc = self.elements["NPC"] goffs.append(Offer( msg="You can usually find {} at {}, if you're planning to invite {} to join your lance.".format(mynpc,mynpc.get_scene(),mynpc.gender.object_pronoun), context=ContextTag((context.INFO,)), effect=self._get_rumor, subject=str(mynpc), data={"subject": str(mynpc)}, no_repeats=True )) return goffs def _get_rumor(self,camp): mynpc = self.elements["NPC"] self._got_rumor = True self.memo = Memo( "{} is looking for a lance to join.".format(mynpc) , mynpc.get_scene() ) class RLM_Medic(Plot): LABEL = "RLM_Relationship" active = True scope = True UNIQUE = True VIRTUES = (gears.personality.Peace,gears.personality.Fellowship) @classmethod def matches( self, pstate ): """Returns True if this plot matches the current plot state.""" return pstate.elements["NPC"].job and gears.tags.Medic in pstate.elements["NPC"].job.tags def custom_init(self, nart): npc = self.elements["NPC"] npc.relationship = gears.relationships.Relationship(expectation=gears.relationships.E_GREATERGOOD) new_virtue = random.choice(self.VIRTUES) if new_virtue not in npc.personality: npc.personality.add(new_virtue) return True def NPC_offers(self, camp): mylist = list() npc = self.elements["NPC"] if gears.relationships.RT_LANCEMATE not in npc.relationship.tags: if camp.can_add_lancemate(): mylist.append(Offer("[THANKS_FOR_CHOOSING_ME] [LETSGO]", context=ContextTag((context.JOIN,)), effect=self._join_lance )) else: mylist.append(Offer("You've got a full crew right now, but if you ever find yourself in need of a qualified medic come back and find me.", context=ContextTag((context.JOIN,)), effect=self._defer_join )) mylist.append(Offer( "[HELLO] Lately I've been spending too much time here, when I'd rather be out in the danger zone saving lives.", context=ContextTag((context.HELLO,)) )) mylist.append(LMSkillsSelfIntro(npc)) return mylist def _get_dialogue_grammar(self, npc, camp): mygram = dict() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"]: # This is an NPC in Wujung. Give them some news. mygram["[News]"] = ["{} wants to leave {} so {} can make a positive difference in the world".format(self.elements["NPC"],self.elements["NPC"].get_scene(),self.elements["NPC"].gender.subject_pronoun), ] return mygram def _join_lance(self, camp): npc = self.elements["NPC"] npc.relationship.tags.add(gears.relationships.RT_LANCEMATE) effect = game.content.plotutility.AutoJoiner(npc) effect(camp) self.end_plot(camp) def _defer_join(self, camp): npc = self.elements["NPC"] npc.relationship.tags.add(gears.relationships.RT_LANCEMATE) self.end_plot(camp) class RLM_Mercenary(Plot): LABEL = "RLM_Relationship" active = True scope = True UNIQUE = True @classmethod def matches( self, pstate ): """Returns True if this plot matches the current plot state.""" return pstate.elements["NPC"].job and {gears.tags.Adventurer,gears.tags.Military}.intersection(pstate.elements["NPC"].job.tags) def custom_init(self, nart): npc = self.elements["NPC"] npc.relationship = gears.relationships.Relationship(expectation=gears.relationships.E_MERCENARY) # This character gets extra mecha points, showing their good investment sense. npc.relationship.data["mecha_level_bonus"] = 10 self._got_rumor = False return True def NPC_offers(self, camp): mylist = list() npc = self.elements["NPC"] self.hire_cost = get_hire_cost(camp,npc) if gears.relationships.RT_LANCEMATE not in npc.relationship.tags: if camp.can_add_lancemate(): mylist.append(Offer("I'll join your lance for a mere ${}. [DOYOUACCEPTMYOFFER]".format(self.hire_cost), context=ContextTag((context.PROPOSAL, context.JOIN)), data={"subject": "joining my lance"}, subject=self, subject_start=True, )) mylist.append(Offer("[DENY_JOIN] [GOODBYE]", context=ContextTag((context.DENY, context.JOIN)), subject=self )) if camp.credits >= self.hire_cost: mylist.append(Offer("[THANKS_FOR_CHOOSING_ME] [LETSGO]", context=ContextTag((context.ACCEPT, context.JOIN)), subject=self, effect=self._join_lance )) mylist.append(Offer( "[HELLO] I am a mercenary pilot, looking for my next contract.", context=ContextTag((context.HELLO,)) )) mylist.append(LMSkillsSelfIntro(npc)) return mylist def _get_dialogue_grammar(self, npc, camp): mygram = dict() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"]: # This is an NPC in Wujung. Give them some news. mygram["[News]"] = ["{} is hoping to make some quick cash".format(self.elements["NPC"]), ] return mygram def _join_lance(self, camp): npc = self.elements["NPC"] npc.relationship.tags.add(gears.relationships.RT_LANCEMATE) camp.credits -= self.hire_cost effect = game.content.plotutility.AutoJoiner(npc) effect(camp) self.end_plot(camp) def _get_generic_offers(self, npc, camp): """Get any offers that could apply to non-element NPCs.""" goffs = list() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"] and not self._got_rumor: mynpc = self.elements["NPC"] goffs.append(Offer( msg="As far as I know {} can usually be found at {}.".format(mynpc,mynpc.get_scene()), context=ContextTag((context.INFO,)), effect=self._get_rumor, subject=str(mynpc), data={"subject": str(mynpc)}, no_repeats=True )) return goffs def _get_rumor(self,camp): mynpc = self.elements["NPC"] self._got_rumor = True self.memo = Memo("{} is a mercenary pilot looking for a job.".format(mynpc) , mynpc.get_scene() ) class RLM_Professional(Plot): LABEL = "RLM_Relationship" active = True scope = True UNIQUE = True @classmethod def matches( self, pstate ): """Returns True if this plot matches the current plot state.""" return pstate.elements["NPC"].renown > 20 def custom_init(self, nart): npc = self.elements["NPC"] npc.relationship = gears.relationships.Relationship(expectation=gears.relationships.E_PROFESSIONAL) # This character gets 10 extra stat points, showing their elite nature. npc.roll_stats(10, clear_first=False) self._got_rumor = False return True def NPC_offers(self, camp): mylist = list() npc = self.elements["NPC"] self.hire_cost = get_hire_cost(camp,npc) if gears.relationships.RT_LANCEMATE not in npc.relationship.tags: if camp.can_add_lancemate(): mylist.append(Offer( "[NOEXPOSURE] I think ${} is a fair signing price. [DOYOUACCEPTMYOFFER]".format(self.hire_cost), context=ContextTag((context.PROPOSAL, context.JOIN)), data={"subject": "joining my lance"}, subject=self, subject_start=True, )) mylist.append(Offer("[DENY_JOIN] [GOODBYE]", context=ContextTag((context.DENY, context.JOIN)), subject=self )) if camp.credits >= self.hire_cost: mylist.append(Offer("[THANKS_FOR_CHOOSING_ME] [LETSGO]", context=ContextTag((context.ACCEPT, context.JOIN)), subject=self, effect=self._join_lance )) mylist.append(Offer( "[HELLO] I see you are also a cavalier.", context=ContextTag((context.HELLO,)) )) mylist.append(LMSkillsSelfIntro(npc)) return mylist def _get_dialogue_grammar(self, npc, camp): mygram = dict() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"]: # This is an NPC in Wujung. Give them some news. mygram["[News]"] = ["{} is an experienced pilot looking for work".format(self.elements["NPC"]), ] return mygram def _join_lance(self, camp): npc = self.elements["NPC"] npc.relationship.tags.add(gears.relationships.RT_LANCEMATE) camp.credits -= self.hire_cost effect = game.content.plotutility.AutoJoiner(npc) effect(camp) self.end_plot(camp) def _get_generic_offers(self, npc, camp): """Get any offers that could apply to non-element NPCs.""" goffs = list() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"] and not self._got_rumor: mynpc = self.elements["NPC"] goffs.append(Offer( msg="You can usually find {} at {}. Bring cash if you're planning to hire {}.".format(mynpc,mynpc.get_scene(),mynpc.gender.object_pronoun), context=ContextTag((context.INFO,)), effect=self._get_rumor, subject=str(mynpc), data={"subject": str(mynpc)}, no_repeats=True )) return goffs def _get_rumor(self,camp): mynpc = self.elements["NPC"] self._got_rumor = True self.memo = Memo( "{} is an experienced pilot looking for work.".format(mynpc) , mynpc.get_scene() ) class RLM_RatherGeneric(Plot): LABEL = "RLM_Relationship" active = True scope = True def custom_init(self, nart): npc = self.elements["NPC"] npc.relationship = gears.relationships.Relationship() self._got_rumor = False return True def NPC_offers(self, camp): mylist = list() npc = self.elements["NPC"] self.hire_cost = get_hire_cost(camp,npc) if gears.relationships.RT_LANCEMATE not in npc.relationship.tags: if camp.can_add_lancemate(): if npc.get_reaction_score(camp.pc, camp) > 60: mylist.append(Offer("[IWOULDLOVETO] [THANKS_FOR_CHOOSING_ME]", context=ContextTag((context.PROPOSAL, context.JOIN)), data={"subject": "joining my lance"}, effect=self._join_lance )) else: mylist.append(Offer("My regular signing rate is ${}. [DOYOUACCEPTMYOFFER]".format(self.hire_cost), context=ContextTag((context.PROPOSAL, context.JOIN)), data={"subject": "joining my lance"}, subject=self, subject_start=True, )) mylist.append(Offer("[DENY_JOIN] [GOODBYE]", context=ContextTag((context.DENY, context.JOIN)), subject=self )) if camp.credits >= self.hire_cost: mylist.append(Offer("[THANKS_FOR_CHOOSING_ME] [LETSGO]", context=ContextTag((context.ACCEPT, context.JOIN)), subject=self, effect=self._pay_to_join )) mylist.append(Offer( "[HELLO] [WAITINGFORMISSION]", context=ContextTag((context.HELLO,)) )) else: mylist.append(Offer( "[HELLO] Must be nice going off, having adventures with your lancemates. I'd like to do that again someday.", context=ContextTag((context.HELLO,)) )) mylist.append(LMSkillsSelfIntro(npc)) return mylist def _get_dialogue_grammar(self, npc, camp): mygram = dict() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"]: mygram["[News]"] = ["{} is looking for a new lance to join".format(self.elements["NPC"]), ] return mygram def _pay_to_join(self,camp): camp.credits -= self.hire_cost self._join_lance(camp) def _join_lance(self, camp): npc = self.elements["NPC"] npc.relationship.tags.add(gears.relationships.RT_LANCEMATE) effect = game.content.plotutility.AutoJoiner(npc) effect(camp) self.end_plot(camp) def _get_generic_offers(self, npc, camp): """Get any offers that could apply to non-element NPCs.""" goffs = list() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"] and not self._got_rumor: mynpc = self.elements["NPC"] goffs.append(Offer( msg="You can find {} at {}.".format(mynpc,mynpc.get_scene()), context=ContextTag((context.INFO,)), effect=self._get_rumor, subject=str(mynpc), data={"subject": str(mynpc)}, no_repeats=True )) return goffs def _get_rumor(self,camp): mynpc = self.elements["NPC"] self._got_rumor = True self.memo = Memo("{} is looking for a new lance.".format(mynpc) , mynpc.get_scene() ) class RLM_DamagedGoodsSale(Plot): LABEL = "RLM_Relationship" active = True scope = True UNIQUE = True def custom_init(self, nart): npc = self.elements["NPC"] npc.relationship = gears.relationships.Relationship(expectation=gears.relationships.E_IMPROVER) # This NPC gets a stat bonus but a crappy mech to show their history. npc.relationship.data["mecha_level_bonus"] = -15 npc.roll_stats(5, clear_first=False) self._got_rumor = False return True def NPC_offers(self, camp): mylist = list() npc = self.elements["NPC"] self.hire_cost = get_hire_cost(camp,npc)//2 if gears.relationships.RT_LANCEMATE not in npc.relationship.tags: if camp.can_add_lancemate(): if npc.get_reaction_score(camp.pc, camp) > 20: mylist.append(Offer("[IWOULDLOVETO] I'll do my best to not let you down.", context=ContextTag((context.PROPOSAL, context.JOIN)), data={"subject": "joining my lance"}, effect=self._join_lance )) else: mylist.append(Offer("I'll sign up with you for just ${}. [DOYOUACCEPTMYOFFER]".format(self.hire_cost), context=ContextTag((context.PROPOSAL, context.JOIN)), data={"subject": "joining my lance"}, subject=self, subject_start=True, )) mylist.append(Offer("[DENY_JOIN] [GOODBYE]", context=ContextTag((context.DENY, context.JOIN)), subject=self )) if camp.credits >= self.hire_cost: mylist.append(Offer("[THANKS_FOR_CHOOSING_ME] I'll do my best to not let you down.", context=ContextTag((context.ACCEPT, context.JOIN)), subject=self, effect=self._pay_to_join )) mylist.append(Offer( "[HELLO] The life of a cavalier is full of ups and downs... right now I'm in one of those downs.", context=ContextTag((context.HELLO,)) )) else: mylist.append(Offer( "[HELLO] Be careful out there... all it takes is one little mistake to cost you everything.", context=ContextTag((context.HELLO,)) )) mylist.append(LMSkillsSelfIntro(npc)) return mylist def _get_dialogue_grammar(self, npc, camp): mygram = dict() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"]: mygram["[News]"] = ["{NPC} is a down on {NPC.gender.possessive_determiner} luck cavalier looking for another chance".format(**self.elements), ] return mygram def _pay_to_join(self,camp): camp.credits -= self.hire_cost self._join_lance(camp) def _join_lance(self, camp): npc = self.elements["NPC"] npc.relationship.tags.add(gears.relationships.RT_LANCEMATE) effect = game.content.plotutility.AutoJoiner(npc) effect(camp) self.end_plot(camp) def _get_generic_offers(self, npc, camp): """Get any offers that could apply to non-element NPCs.""" goffs = list() if camp.scene.get_root_scene() is self.elements["METROSCENE"] and npc is not self.elements["NPC"] and not self._got_rumor: mynpc = self.elements["NPC"] goffs.append(Offer( msg="You can find {} at {}. Don't say that you weren't warned.".format(mynpc,mynpc.get_scene()), context=ContextTag((context.INFO,)), effect=self._get_rumor, subject=str(mynpc), data={"subject": str(mynpc)}, no_repeats=True )) return goffs def _get_rumor(self,camp): mynpc = self.elements["NPC"] self._got_rumor = True self.memo = Memo( "{} is looking for a new lance.".format(mynpc) , mynpc.get_scene() )
[((107, 69, 107, 89), 'random.randint', 'random.randint', ({(107, 84, 107, 85): '(1)', (107, 87, 107, 88): '(4)'}, {}), '(1, 4)', False, 'import random\n'), ((185, 19, 185, 61), 'random.choice', 'random.choice', ({(185, 33, 185, 60): 'gears.personality.MUTATIONS'}, {}), '(gears.personality.MUTATIONS)', False, 'import random\n'), ((265, 27, 265, 98), 'gears.relationships.Relationship', 'gears.relationships.Relationship', (), '', False, 'import gears\n'), ((328, 27, 328, 100), 'gears.relationships.Relationship', 'gears.relationships.Relationship', (), '', False, 'import gears\n'), ((396, 27, 396, 106), 'gears.relationships.Relationship', 'gears.relationships.Relationship', (), '', False, 'import gears\n'), ((397, 21, 397, 48), 'random.choice', 'random.choice', ({(397, 35, 397, 47): 'self.VIRTUES'}, {}), '(self.VIRTUES)', False, 'import random\n'), ((456, 27, 456, 104), 'gears.relationships.Relationship', 'gears.relationships.Relationship', (), '', False, 'import gears\n'), ((537, 27, 537, 107), 'gears.relationships.Relationship', 'gears.relationships.Relationship', (), '', False, 'import gears\n'), ((611, 27, 611, 61), 'gears.relationships.Relationship', 'gears.relationships.Relationship', ({}, {}), '()', False, 'import gears\n'), ((697, 27, 697, 103), 'gears.relationships.Relationship', 'gears.relationships.Relationship', (), '', False, 'import gears\n'), ((38, 11, 38, 32), 'random.randint', 'random.randint', ({(38, 26, 38, 29): '(-12)', (38, 30, 38, 31): '(3)'}, {}), '(-12, 3)', False, 'import random\n'), ((39, 73, 39, 92), 'random.randint', 'random.randint', ({(39, 88, 39, 89): '(1)', (39, 90, 39, 91): '(4)'}, {}), '(1, 4)', False, 'import random\n'), ((60, 11, 60, 31), 'random.randint', 'random.randint', ({(60, 26, 60, 27): '(1)', (60, 28, 60, 30): '(20)'}, {}), '(1, 20)', False, 'import random\n'), ((61, 73, 61, 92), 'random.randint', 'random.randint', ({(61, 88, 61, 89): '(1)', (61, 90, 61, 91): '(4)'}, {}), '(1, 4)', False, 'import random\n'), ((86, 11, 86, 31), 'random.randint', 'random.randint', ({(86, 26, 86, 27): '(1)', (86, 28, 86, 30): '(10)'}, {}), '(1, 10)', False, 'import random\n'), ((87, 73, 87, 92), 'random.randint', 'random.randint', ({(87, 88, 87, 89): '(1)', (87, 90, 87, 91): '(4)'}, {}), '(1, 4)', False, 'import random\n'), ((190, 11, 190, 32), 'random.randint', 'random.randint', ({(190, 26, 190, 29): '(-12)', (190, 30, 190, 31): '(3)'}, {}), '(-12, 3)', False, 'import random\n'), ((191, 73, 191, 92), 'random.randint', 'random.randint', ({(191, 88, 191, 89): '(1)', (191, 90, 191, 91): '(4)'}, {}), '(1, 4)', False, 'import random\n'), ((283, 22, 283, 44), 'game.content.plotutility.LMSkillsSelfIntro', 'LMSkillsSelfIntro', ({(283, 40, 283, 43): 'npc'}, {}), '(npc)', False, 'from game.content.plotutility import LMSkillsSelfIntro\n'), ((344, 22, 344, 44), 'game.content.plotutility.LMSkillsSelfIntro', 'LMSkillsSelfIntro', ({(344, 40, 344, 43): 'npc'}, {}), '(npc)', False, 'from game.content.plotutility import LMSkillsSelfIntro\n'), ((419, 22, 419, 44), 'game.content.plotutility.LMSkillsSelfIntro', 'LMSkillsSelfIntro', ({(419, 40, 419, 43): 'npc'}, {}), '(npc)', False, 'from game.content.plotutility import LMSkillsSelfIntro\n'), ((32, 59, 32, 92), 'gears.color.random_mecha_colors', 'gears.color.random_mecha_colors', ({}, {}), '()', False, 'import gears\n'), ((56, 59, 56, 92), 'gears.color.random_mecha_colors', 'gears.color.random_mecha_colors', ({}, {}), '()', False, 'import gears\n'), ((81, 51, 81, 72), 'random.randint', 'random.randint', ({(81, 66, 81, 67): '5', (81, 69, 81, 71): '15'}, {}), '(5, 15)', False, 'import random\n'), ((83, 59, 83, 92), 'gears.color.random_mecha_colors', 'gears.color.random_mecha_colors', ({}, {}), '()', False, 'import gears\n'), ((103, 51, 103, 73), 'random.randint', 'random.randint', ({(103, 66, 103, 68): '41', (103, 70, 103, 72): '85'}, {}), '(41, 85)', False, 'import random\n'), ((104, 59, 104, 92), 'gears.color.random_mecha_colors', 'gears.color.random_mecha_colors', ({}, {}), '()', False, 'import gears\n'), ((107, 21, 107, 64), 'random.choice', 'random.choice', ({(107, 35, 107, 63): 'gears.stats.NONCOMBAT_SKILLS'}, {}), '(gears.stats.NONCOMBAT_SKILLS)', False, 'import random\n'), ((131, 59, 131, 92), 'gears.color.random_mecha_colors', 'gears.color.random_mecha_colors', ({}, {}), '()', False, 'import gears\n'), ((157, 59, 157, 92), 'gears.color.random_mecha_colors', 'gears.color.random_mecha_colors', ({}, {}), '()', False, 'import gears\n'), ((180, 51, 180, 73), 'random.randint', 'random.randint', ({(180, 66, 180, 68): '20', (180, 70, 180, 72): '45'}, {}), '(20, 45)', False, 'import random\n'), ((181, 59, 181, 92), 'gears.color.random_mecha_colors', 'gears.color.random_mecha_colors', ({}, {}), '()', False, 'import gears\n'), ((484, 26, 484, 48), 'game.content.plotutility.LMSkillsSelfIntro', 'LMSkillsSelfIntro', ({(484, 44, 484, 47): 'npc'}, {}), '(npc)', False, 'from game.content.plotutility import LMSkillsSelfIntro\n'), ((565, 26, 565, 48), 'game.content.plotutility.LMSkillsSelfIntro', 'LMSkillsSelfIntro', ({(565, 44, 565, 47): 'npc'}, {}), '(npc)', False, 'from game.content.plotutility import LMSkillsSelfIntro\n'), ((648, 26, 648, 48), 'game.content.plotutility.LMSkillsSelfIntro', 'LMSkillsSelfIntro', ({(648, 44, 648, 47): 'npc'}, {}), '(npc)', False, 'from game.content.plotutility import LMSkillsSelfIntro\n'), ((737, 26, 737, 48), 'game.content.plotutility.LMSkillsSelfIntro', 'LMSkillsSelfIntro', ({(737, 44, 737, 47): 'npc'}, {}), '(npc)', False, 'from game.content.plotutility import LMSkillsSelfIntro\n'), ((31, 55, 31, 77), 'random.randint', 'random.randint', ({(31, 70, 31, 72): '10', (31, 74, 31, 76): '50'}, {}), '(10, 50)', False, 'import random\n'), ((31, 78, 31, 100), 'random.randint', 'random.randint', ({(31, 93, 31, 95): '10', (31, 97, 31, 99): '50'}, {}), '(10, 50)', False, 'import random\n'), ((39, 25, 39, 68), 'random.choice', 'random.choice', ({(39, 39, 39, 67): 'gears.stats.NONCOMBAT_SKILLS'}, {}), '(gears.stats.NONCOMBAT_SKILLS)', False, 'import random\n'), ((54, 55, 54, 77), 'random.randint', 'random.randint', ({(54, 70, 54, 72): '10', (54, 74, 54, 76): '50'}, {}), '(10, 50)', False, 'import random\n'), ((54, 78, 54, 100), 'random.randint', 'random.randint', ({(54, 93, 54, 95): '10', (54, 97, 54, 99): '50'}, {}), '(10, 50)', False, 'import random\n'), ((61, 25, 61, 68), 'random.choice', 'random.choice', ({(61, 39, 61, 67): 'gears.stats.NONCOMBAT_SKILLS'}, {}), '(gears.stats.NONCOMBAT_SKILLS)', False, 'import random\n'), ((80, 85, 80, 109), 'random.randint', 'random.randint', ({(80, 100, 80, 103): '100', (80, 105, 80, 108): '110'}, {}), '(100, 110)', False, 'import random\n'), ((85, 90, 85, 111), 'random.randint', 'random.randint', ({(85, 105, 85, 107): '18', (85, 108, 85, 110): '23'}, {}), '(18, 23)', False, 'import random\n'), ((87, 25, 87, 68), 'random.choice', 'random.choice', ({(87, 39, 87, 67): 'gears.stats.NONCOMBAT_SKILLS'}, {}), '(gears.stats.NONCOMBAT_SKILLS)', False, 'import random\n'), ((106, 90, 106, 111), 'random.randint', 'random.randint', ({(106, 105, 106, 107): '32', (106, 108, 106, 110): '50'}, {}), '(32, 50)', False, 'import random\n'), ((129, 55, 129, 77), 'random.randint', 'random.randint', ({(129, 70, 129, 72): '20', (129, 74, 129, 76): '55'}, {}), '(20, 55)', False, 'import random\n'), ((129, 78, 129, 100), 'random.randint', 'random.randint', ({(129, 93, 129, 95): '20', (129, 97, 129, 99): '55'}, {}), '(20, 55)', False, 'import random\n'), ((154, 55, 154, 77), 'random.randint', 'random.randint', ({(154, 70, 154, 72): '25', (154, 74, 154, 76): '65'}, {}), '(25, 65)', False, 'import random\n'), ((154, 78, 154, 100), 'random.randint', 'random.randint', ({(154, 93, 154, 95): '25', (154, 97, 154, 99): '65'}, {}), '(25, 65)', False, 'import random\n'), ((191, 25, 191, 68), 'random.choice', 'random.choice', ({(191, 39, 191, 67): 'gears.stats.NONCOMBAT_SKILLS'}, {}), '(gears.stats.NONCOMBAT_SKILLS)', False, 'import random\n'), ((233, 36, 233, 66), 'pbge.dialogue.ContextTag', 'ContextTag', ({(233, 47, 233, 65): '[context.PERSONAL]'}, {}), '([context.PERSONAL])', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((417, 133, 417, 161), 'pbge.dialogue.ContextTag', 'ContextTag', ({(417, 144, 417, 160): '(context.HELLO,)'}, {}), '((context.HELLO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((55, 70, 55, 94), 'random.choice', 'random.choice', ({(55, 84, 55, 93): 'self.JOBS'}, {}), '(self.JOBS)', False, 'import random\n'), ((82, 70, 82, 94), 'random.choice', 'random.choice', ({(82, 84, 82, 93): 'self.JOBS'}, {}), '(self.JOBS)', False, 'import random\n'), ((130, 70, 130, 94), 'random.choice', 'random.choice', ({(130, 84, 130, 93): 'self.JOBS'}, {}), '(self.JOBS)', False, 'import random\n'), ((281, 82, 281, 110), 'pbge.dialogue.ContextTag', 'ContextTag', ({(281, 93, 281, 109): '(context.HELLO,)'}, {}), '((context.HELLO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((307, 24, 307, 51), 'pbge.dialogue.ContextTag', 'ContextTag', ({(307, 35, 307, 50): '(context.INFO,)'}, {}), '((context.INFO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((342, 55, 342, 83), 'pbge.dialogue.ContextTag', 'ContextTag', ({(342, 66, 342, 82): '(context.HELLO,)'}, {}), '((context.HELLO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((369, 24, 369, 51), 'pbge.dialogue.ContextTag', 'ContextTag', ({(369, 35, 369, 50): '(context.INFO,)'}, {}), '((context.INFO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((482, 89, 482, 117), 'pbge.dialogue.ContextTag', 'ContextTag', ({(482, 100, 482, 116): '(context.HELLO,)'}, {}), '((context.HELLO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((510, 24, 510, 51), 'pbge.dialogue.ContextTag', 'ContextTag', ({(510, 35, 510, 50): '(context.INFO,)'}, {}), '((context.INFO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((563, 66, 563, 94), 'pbge.dialogue.ContextTag', 'ContextTag', ({(563, 77, 563, 93): '(context.HELLO,)'}, {}), '((context.HELLO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((591, 24, 591, 51), 'pbge.dialogue.ContextTag', 'ContextTag', ({(591, 35, 591, 50): '(context.INFO,)'}, {}), '((context.INFO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((676, 24, 676, 51), 'pbge.dialogue.ContextTag', 'ContextTag', ({(676, 35, 676, 50): '(context.INFO,)'}, {}), '((context.INFO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((765, 24, 765, 51), 'pbge.dialogue.ContextTag', 'ContextTag', ({(765, 35, 765, 50): '(context.INFO,)'}, {}), '((context.INFO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((277, 44, 277, 71), 'pbge.dialogue.ContextTag', 'ContextTag', ({(277, 55, 277, 70): '(context.JOIN,)'}, {}), '((context.JOIN,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((338, 44, 338, 71), 'pbge.dialogue.ContextTag', 'ContextTag', ({(338, 55, 338, 70): '(context.JOIN,)'}, {}), '((context.JOIN,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((408, 44, 408, 71), 'pbge.dialogue.ContextTag', 'ContextTag', ({(408, 55, 408, 70): '(context.JOIN,)'}, {}), '((context.JOIN,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((413, 44, 413, 71), 'pbge.dialogue.ContextTag', 'ContextTag', ({(413, 55, 413, 70): '(context.JOIN,)'}, {}), '((context.JOIN,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((469, 44, 469, 88), 'pbge.dialogue.ContextTag', 'ContextTag', ({(469, 55, 469, 87): '(context.PROPOSAL, context.JOIN)'}, {}), '((context.PROPOSAL, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((474, 44, 474, 84), 'pbge.dialogue.ContextTag', 'ContextTag', ({(474, 55, 474, 83): '(context.DENY, context.JOIN)'}, {}), '((context.DENY, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((551, 28, 551, 72), 'pbge.dialogue.ContextTag', 'ContextTag', ({(551, 39, 551, 71): '(context.PROPOSAL, context.JOIN)'}, {}), '((context.PROPOSAL, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((555, 44, 555, 84), 'pbge.dialogue.ContextTag', 'ContextTag', ({(555, 55, 555, 83): '(context.DENY, context.JOIN)'}, {}), '((context.DENY, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((642, 59, 642, 87), 'pbge.dialogue.ContextTag', 'ContextTag', ({(642, 70, 642, 86): '(context.HELLO,)'}, {}), '((context.HELLO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((646, 138, 646, 166), 'pbge.dialogue.ContextTag', 'ContextTag', ({(646, 149, 646, 165): '(context.HELLO,)'}, {}), '((context.HELLO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((731, 127, 731, 155), 'pbge.dialogue.ContextTag', 'ContextTag', ({(731, 138, 731, 154): '(context.HELLO,)'}, {}), '((context.HELLO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((735, 122, 735, 150), 'pbge.dialogue.ContextTag', 'ContextTag', ({(735, 133, 735, 149): '(context.HELLO,)'}, {}), '((context.HELLO,))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((478, 48, 478, 90), 'pbge.dialogue.ContextTag', 'ContextTag', ({(478, 59, 478, 89): '(context.ACCEPT, context.JOIN)'}, {}), '((context.ACCEPT, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((559, 48, 559, 90), 'pbge.dialogue.ContextTag', 'ContextTag', ({(559, 59, 559, 89): '(context.ACCEPT, context.JOIN)'}, {}), '((context.ACCEPT, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((623, 48, 623, 92), 'pbge.dialogue.ContextTag', 'ContextTag', ({(623, 59, 623, 91): '(context.PROPOSAL, context.JOIN)'}, {}), '((context.PROPOSAL, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((629, 48, 629, 92), 'pbge.dialogue.ContextTag', 'ContextTag', ({(629, 59, 629, 91): '(context.PROPOSAL, context.JOIN)'}, {}), '((context.PROPOSAL, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((634, 48, 634, 88), 'pbge.dialogue.ContextTag', 'ContextTag', ({(634, 59, 634, 87): '(context.DENY, context.JOIN)'}, {}), '((context.DENY, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((712, 48, 712, 92), 'pbge.dialogue.ContextTag', 'ContextTag', ({(712, 59, 712, 91): '(context.PROPOSAL, context.JOIN)'}, {}), '((context.PROPOSAL, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((718, 48, 718, 92), 'pbge.dialogue.ContextTag', 'ContextTag', ({(718, 59, 718, 91): '(context.PROPOSAL, context.JOIN)'}, {}), '((context.PROPOSAL, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((723, 48, 723, 88), 'pbge.dialogue.ContextTag', 'ContextTag', ({(723, 59, 723, 87): '(context.DENY, context.JOIN)'}, {}), '((context.DENY, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((638, 52, 638, 94), 'pbge.dialogue.ContextTag', 'ContextTag', ({(638, 63, 638, 93): '(context.ACCEPT, context.JOIN)'}, {}), '((context.ACCEPT, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n'), ((727, 52, 727, 94), 'pbge.dialogue.ContextTag', 'ContextTag', ({(727, 63, 727, 93): '(context.ACCEPT, context.JOIN)'}, {}), '((context.ACCEPT, context.JOIN))', False, 'from pbge.dialogue import Offer, ContextTag\n')]
zzzzzz0407/detectron2
projects/detr/scripts/dd.py
021fc5b1502bbba54e4714735736898803835ab0
import json if __name__ == '__main__': jsonFile = '/data00/home/zhangrufeng1/projects/detectron2/projects/detr/datasets/mot/mot17/annotations/mot17_train_half.json' with open(jsonFile, 'r') as f: infos = json.load(f) count_dict = dict() for info in infos["images"]: if info["file_name"] in ["MOT17-02-FRCNN/img1/000091.jpg"]: for ann in infos['annotations']: if ann["image_id"] not in count_dict.keys() and ann["iscrowd"] == 0 and ann["bbox"][2] >= 1e-5 and ann["bbox"][3] >= 1e-5: count_dict[ann["image_id"]] = 1 elif ann["image_id"] in count_dict.keys() and ann["iscrowd"] == 0: count_dict[ann["image_id"]] += 1 max_count = 0 min_count = 999 num_freq = 0 for key, value in count_dict.items(): max_count = max(max_count, value) min_count = min(min_count, value) if value > 100: num_freq += 1 print("max_count: {}".format(max_count)) print("min_count: {}".format(min_count)) print("num_freq: {}".format(num_freq))
[]
wesleibarboza/natasha-virtual
app/app.py
74c5ef9a4db5ce98dd72499d40775bfd65d34974
# -*- coding: utf-8 -*- """Archivo principal para el echobot. Main File for the echobot""" from fbmq import Page from flask import Flask, request # Token generado por la página web. Generated token in the facebook web page PAGE_ACCESS_TOKEN = "COPY_HERE_YOUR_PAGE_ACCES_TOKEN" # Token generado por nosotros. Token generated by us VERIFY_TOKEN = "EchoBotChido" # Si cambias este token, asegúrate de cambiarlo también en la página de configuración del webhook. If you change this token, verify that you changed it too in the webhook configuration. app = Flask(__name__) page = Page(PAGE_ACCESS_TOKEN) # Generamos la instancia de la página de facebook. We make the facebook page instance @app.route('/') def hello_world(): """La página principal del servidor. The server main page.""" return 'Inicio del servidor' @app.route('/webhook', methods=['GET', 'POST']) def webhook(): """El método que se ejecuta cuando Facebook se conecta. This method executes as Facebook connect to us.""" if request.method == 'POST': # if the message is a POST, we handle it with message_handler. Si el mensaje es POST, se maneja con el message_handler # Facebook sends the user messages with a POST. Facebook manda los mensajes del usuario con un POST. page.handle_webhook(request.get_data(as_text=True)) return 'ok' elif request.method == 'GET': # if the message is a GET, we handle it here. Si el mensaje es un GET, lo manejamos aquí. # The first you configure the webhook, FB sends a GET to your webhook to verify that it really is you, and you're not working on someone's else page. # La primera vez que se configura el webhook, FB manda un mensaje GET para ver que realmente eres tú, y no estás trabajando en la página de alguien más. if request.args.get('hub.verify_token') == VERIFY_TOKEN: # If the verify token in the url matches our verify token we answer with the challenge to prove our identity. # Si el verify token de la url concuerda con el de nosotros le respondemos con el challenge o reto para verificar que somos nosotros return request.args.get('hub.challenge') return 'Wrong Verify token' @page.handle_message def message_handler(event): """Este método se ejecuta cuando nos llega un mensaje a la página. This method executes whenever a message is sent to our page.""" # Se saca el id del sender. We get the sender id. sender_id = event.sender_id # Vemos si el mensaje es un texto o un adjunto (imagen, gif, sticker, etc) # We see if the message is a text or an attachment (image, GIF, sticker, etc) if event.is_text_message: # We get the message from the event variable and sent it back7 # Obtenemos el mensaje de la variable event y se lo regresamos al usuario page.send(sender_id, "Hey, you send me: {}".format(event.message_text)) elif event.is_attachment_message: page.send(sender_id, "Boo, you didn't send a text. ") if __name__ == '__main__': app.run(host="127.0.0.1", port=5000, debug=True, threaded=True)
[((11, 6, 11, 21), 'flask.Flask', 'Flask', ({(11, 12, 11, 20): '__name__'}, {}), '(__name__)', False, 'from flask import Flask, request\n'), ((12, 7, 12, 30), 'fbmq.Page', 'Page', ({(12, 12, 12, 29): 'PAGE_ACCESS_TOKEN'}, {}), '(PAGE_ACCESS_TOKEN)', False, 'from fbmq import Page\n'), ((26, 28, 26, 58), 'flask.request.get_data', 'request.get_data', (), '', False, 'from flask import Flask, request\n'), ((31, 11, 31, 47), 'flask.request.args.get', 'request.args.get', ({(31, 28, 31, 46): '"""hub.verify_token"""'}, {}), "('hub.verify_token')", False, 'from flask import Flask, request\n'), ((34, 19, 34, 52), 'flask.request.args.get', 'request.args.get', ({(34, 36, 34, 51): '"""hub.challenge"""'}, {}), "('hub.challenge')", False, 'from flask import Flask, request\n')]
Water2style/FCN-pytorch-CanRun
Camvid/CamVid_utlis.py
b2994f98930580cd2c32f58d19f94becb68a3ccb
# -*- coding: utf-8 -*- from __future__ import print_function from matplotlib import pyplot as plt import matplotlib.image as mpimg import numpy as np import scipy.misc import random import os import imageio ############################# # global variables # ############################# root_dir = "/home/water/DATA/camvid-master" data_dir = os.path.join(root_dir, "701_StillsRaw_full") # train data label_dir = os.path.join(root_dir, "LabeledApproved_full") # train label label_colors_file = os.path.join(root_dir, "label_colors.txt") # color to label val_label_file = os.path.join(root_dir, "val.csv") # validation file train_label_file = os.path.join(root_dir, "train.csv") # train file # create dir for label index label_idx_dir = os.path.join(root_dir, "Labeled_idx") if not os.path.exists(label_idx_dir): os.makedirs(label_idx_dir) label2color = {} color2label = {} label2index = {} index2label = {} def divide_train_val(val_rate=0.1, shuffle=True, random_seed=None): data_list = os.listdir(data_dir) #返回这个目录里,所有内容,‘图1’‘,图2’...... data_len = len(data_list) #702个图片 #注意这里是训练集 val_len = int(data_len * val_rate) #训练集700张,分10%的数量给验证集 if random_seed: #设置随机种子 random.seed(random_seed) #看看后面哪里用 if shuffle: #sample(seq, n) 从序列seq中选择n个随机且独立的元素 data_idx = random.sample(range(data_len), data_len) # data_idx 是从0到702 随机排序的数组 else: data_idx = list(range(data_len)) #这个就是从0到702 依次排序 val_idx = [data_list[i] for i in data_idx[:val_len]] # 前70个,图片名 List train_idx = [data_list[i] for i in data_idx[val_len:]] # 71到702个 # !创建 create val.csv # "w"打开一个文件只用于写入。如果该文件已存在则打开文件, # 并从开头开始编辑,即原有内容会被删除。 # 如果该文件不存在,创建新文件。 v = open(val_label_file, "w") v.write("img,label\n") #write() 方法用于向文件中写入指定字符串 for idx, name in enumerate(val_idx): if 'png' not in name: ##跳过损坏文件 continue img_name = os.path.join(data_dir, name) lab_name = os.path.join(label_idx_dir, name) lab_name = lab_name.split(".")[0] + "_L.png.npy" v.write("{},{}\n".format(img_name, lab_name)) #最后生成了一个.csv文件,位于根目录 ## 装的信息是: 2列,一列是验证集,70张 生图路径+名字,第二列是验证集对应的:标签图+名字+.npy #png.npy :后面parse_label函数,就是在标签图路径里 生成 标签图+名字+.npy 文件!!! # create train.csv 所以这2个.csv文件,这里存放的是信息 ,是: 生图信息和标签图+npy信息 t = open(train_label_file, "w") t.write("img,label\n") for idx, name in enumerate(train_idx): if 'png' not in name: continue img_name = os.path.join(data_dir, name) lab_name = os.path.join(label_idx_dir, name) lab_name = lab_name.split(".")[0] + "_L.png.npy" t.write("{},{}\n".format(img_name, lab_name)) #parse:分析 分析标签 def parse_label(): # change label to class index #“r”:以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 #label_colors.txt :!!装的是颜色和对应标签 64 128 64\tAnimal 颜色\t类别 # 只读,读好了之后 #不igore 就会bug f = open(label_colors_file, "r").read().split("\n")[:-1] # ignore the last empty line for idx, line in enumerate(f): label = line.split()[-1] #提取所有label形成一个字符串 #动物,人,墙.. color = tuple([int(x) for x in line.split()[:-1]]) #形成一个元组 对应动物,人,墙.. #的颜色,比如动物的颜色是红色 :[128,0,0].... print(label, color) #d[key] = value #设置d[key]的值为value,如果该key不存在,则为新增 #label2color[label] = color 运行后: #就形成了1个字典: 以label做key,以color做value的新字典 #包含内容:{'Animal': (64, 128, 64), 'Archway': (192, 0, 128).....} #后面有精彩用法.... label2color[label] = color color2label[color] = label #{颜色:标签} label2index[label] = idx # {标签:idx} {'Animal': 0, 'Archway': 1...} index2label[idx] = label # {idx:标签} #下面是作者自己标注的: # rgb = np.zeros((255, 255, 3), dtype=np.uint8) # rgb[..., 0] = color[0] # rgb[..., 1] = color[1] # rgb[..., 2] = color[2] # imshow(rgb, title=label) #enumerate :迭代器,0号,内容0;1号,内容1 for idx, name in enumerate(os.listdir(label_dir)): #os.listdir(label_dir) 是标签集里所有图片 #idx就是从0开始的序号 name是图片名 #os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表,这个列表以字母顺序。 filename = os.path.join(label_idx_dir, name) # labeled_idx/所有图片名 if os.path.exists(filename + '.npy'): #检查是否有图片名.png.npy,当前应该是没有的 print("Skip %s" % (name)) #有了就跳过这个图 npy是numpy文件 continue print("Parse %s" % (name)) ## 打出:Parse 图片名(不包含路径) img = os.path.join(label_dir, name) ## img是路径,LabeledApproved_full/所有图片名 ## 区分一下 和 filename之间的用法和关联? img = imageio.imread(img) #用numpy(npy)格式打开一个图 height, weight, _ = img.shape # numpy存储图片格式(高,宽,3通道) #Tensor是(3,高,宽) #在大for循环里,对每一张图执行下面操作 img是上面读取的一个npy格式的图哈 idx_mat = np.zeros((height, weight)) #720*960 for h in range(height): for w in range(weight): #前面也有个color啊,不同作用域功能不同 color = tuple(img[h, w]) # tuple(序列),把序列转为元组 #这里应该是把img[h,w]这个!像素点!(128,64,64) # 抓出来弄成了一个元组,又因为遍历 #所以color是一个有 height*weight个元素的tuple #color包含着这个图片里,所有的颜色 try: #try,except: 异常检测,try里顺序执行,如果,去执行except #tuple类型的color在这里作为key,输出相应的value,也就是label值,dict的存储是一一对应的 #所以 出来的label是和输入的color 一一对应 label = color2label[color] # 给彩图像素点,返回像素点的label,就像是上面那图里只有猫和北京,返回:cat space index = label2index[label] # 给label返回类型代表的号码,给cat sapce,返回1,5 idx_mat[h, w] = index #构成了一个由颜色到标签到标签序号处理后的图,一个点一个点送? except: print("error: img:%s, h:%d, w:%d" % (name, h, w)) idx_mat = idx_mat.astype(np.uint8) #转换数据类型 np.save(filename, idx_mat) #numpy.save(file, arr, allow_pickle=True, fix_imports=True) #把当前(因为这个for里是逐像素点处理一张图)这个图的信息(numpy)存起来 print("Finish %s" % (name)) #跳出for,这个位置就是处理好了所有的图,生成了702个 png.npy图 #生成的这个是一个numpy图,每个图上,是标记好的序号 #就像 一个张图里是 建筑和空白,建筑位置上显示:4,4 = buildings标签 = buildings颜色[128,0,0] # test some pixels' label ~~~~~~~~~~~~~~~~~~~~~~~~~~` #img = os.path.join(label_dir, os.listdir(label_dir)[0]) #img数据:img[height,weight,rgb] #img = imageio.imread(img) #test_cases = [(555, 405), (0, 0), (380, 645), (577, 943)] # img[555,405]:此图此点的!位置信息! #test_ans = ['Car', 'Building', 'Truck_Bus', 'Car'] #这个是肉眼去看哈,看上面的位置,对应的是啥label #for idx, t in enumerate(test_cases): #color = img[t] #相当于访问 img上的4个点的位置信息,输出的是这4个点对应的像素值(img是labeled,就那32个规整的颜色) #assert color2label[tuple(color)] == test_ans[idx] ##检查一下对不对 #上面是作者乱标的,所以报错,我在jupyter通过肉眼看图并且调试,就对了哈!! '''debug function''' def imshow(img, title=None): try: img = mpimg.imread(img) #mpimg: matplotlib.image 输入的img是个地址哈,不是啥处理后的numpy数组 imgplot = plt.imshow(img) except: plt.imshow(img, interpolation='nearest') if title is not None: plt.title(title) plt.show() if __name__ == '__main__': print("it starts working") divide_train_val(random_seed=1) parse_label() print("process finished")
[((17, 20, 17, 64), 'os.path.join', 'os.path.join', ({(17, 33, 17, 41): 'root_dir', (17, 43, 17, 63): '"""701_StillsRaw_full"""'}, {}), "(root_dir, '701_StillsRaw_full')", False, 'import os\n'), ((18, 20, 18, 66), 'os.path.join', 'os.path.join', ({(18, 33, 18, 41): 'root_dir', (18, 43, 18, 65): '"""LabeledApproved_full"""'}, {}), "(root_dir, 'LabeledApproved_full')", False, 'import os\n'), ((19, 20, 19, 62), 'os.path.join', 'os.path.join', ({(19, 33, 19, 41): 'root_dir', (19, 43, 19, 61): '"""label_colors.txt"""'}, {}), "(root_dir, 'label_colors.txt')", False, 'import os\n'), ((20, 20, 20, 53), 'os.path.join', 'os.path.join', ({(20, 33, 20, 41): 'root_dir', (20, 43, 20, 52): '"""val.csv"""'}, {}), "(root_dir, 'val.csv')", False, 'import os\n'), ((21, 20, 21, 55), 'os.path.join', 'os.path.join', ({(21, 33, 21, 41): 'root_dir', (21, 43, 21, 54): '"""train.csv"""'}, {}), "(root_dir, 'train.csv')", False, 'import os\n'), ((24, 16, 24, 53), 'os.path.join', 'os.path.join', ({(24, 29, 24, 37): 'root_dir', (24, 39, 24, 52): '"""Labeled_idx"""'}, {}), "(root_dir, 'Labeled_idx')", False, 'import os\n'), ((25, 7, 25, 36), 'os.path.exists', 'os.path.exists', ({(25, 22, 25, 35): 'label_idx_dir'}, {}), '(label_idx_dir)', False, 'import os\n'), ((26, 4, 26, 30), 'os.makedirs', 'os.makedirs', ({(26, 16, 26, 29): 'label_idx_dir'}, {}), '(label_idx_dir)', False, 'import os\n'), ((34, 18, 34, 38), 'os.listdir', 'os.listdir', ({(34, 29, 34, 37): 'data_dir'}, {}), '(data_dir)', False, 'import os\n'), ((179, 4, 179, 14), 'matplotlib.pyplot.show', 'plt.show', ({}, {}), '()', True, 'from matplotlib import pyplot as plt\n'), ((39, 8, 39, 32), 'random.seed', 'random.seed', ({(39, 20, 39, 31): 'random_seed'}, {}), '(random_seed)', False, 'import random\n'), ((61, 19, 61, 47), 'os.path.join', 'os.path.join', ({(61, 32, 61, 40): 'data_dir', (61, 42, 61, 46): 'name'}, {}), '(data_dir, name)', False, 'import os\n'), ((62, 19, 62, 52), 'os.path.join', 'os.path.join', ({(62, 32, 62, 45): 'label_idx_dir', (62, 47, 62, 51): 'name'}, {}), '(label_idx_dir, name)', False, 'import os\n'), ((74, 19, 74, 47), 'os.path.join', 'os.path.join', ({(74, 32, 74, 40): 'data_dir', (74, 42, 74, 46): 'name'}, {}), '(data_dir, name)', False, 'import os\n'), ((75, 19, 75, 52), 'os.path.join', 'os.path.join', ({(75, 32, 75, 45): 'label_idx_dir', (75, 47, 75, 51): 'name'}, {}), '(label_idx_dir, name)', False, 'import os\n'), ((112, 31, 112, 52), 'os.listdir', 'os.listdir', ({(112, 42, 112, 51): 'label_dir'}, {}), '(label_dir)', False, 'import os\n'), ((115, 19, 115, 52), 'os.path.join', 'os.path.join', ({(115, 32, 115, 45): 'label_idx_dir', (115, 47, 115, 51): 'name'}, {}), '(label_idx_dir, name)', False, 'import os\n'), ((116, 11, 116, 44), 'os.path.exists', 'os.path.exists', ({(116, 26, 116, 43): "(filename + '.npy')"}, {}), "(filename + '.npy')", False, 'import os\n'), ((120, 14, 120, 43), 'os.path.join', 'os.path.join', ({(120, 27, 120, 36): 'label_dir', (120, 38, 120, 42): 'name'}, {}), '(label_dir, name)', False, 'import os\n'), ((122, 14, 122, 33), 'imageio.imread', 'imageio.imread', ({(122, 29, 122, 32): 'img'}, {}), '(img)', False, 'import imageio\n'), ((128, 18, 128, 44), 'numpy.zeros', 'np.zeros', ({(128, 27, 128, 43): '(height, weight)'}, {}), '((height, weight))', True, 'import numpy as np\n'), ((146, 8, 146, 34), 'numpy.save', 'np.save', ({(146, 16, 146, 24): 'filename', (146, 26, 146, 33): 'idx_mat'}, {}), '(filename, idx_mat)', True, 'import numpy as np\n'), ((171, 14, 171, 31), 'matplotlib.image.imread', 'mpimg.imread', ({(171, 27, 171, 30): 'img'}, {}), '(img)', True, 'import matplotlib.image as mpimg\n'), ((172, 18, 172, 33), 'matplotlib.pyplot.imshow', 'plt.imshow', ({(172, 29, 172, 32): 'img'}, {}), '(img)', True, 'from matplotlib import pyplot as plt\n'), ((177, 8, 177, 24), 'matplotlib.pyplot.title', 'plt.title', ({(177, 18, 177, 23): 'title'}, {}), '(title)', True, 'from matplotlib import pyplot as plt\n'), ((174, 8, 174, 48), 'matplotlib.pyplot.imshow', 'plt.imshow', (), '', True, 'from matplotlib import pyplot as plt\n')]
patrik999/AdaptiveStreamReasoningMonitoring
stream-reasoner/ws_client.py
7bbfa1a394e0127e0c4ea670a632be216c83faea
#!/usr/bin/env python import websocket import time try: import thread except ImportError: import _thread as thread runs = 100 def on_message(ws, message): print(message) def on_error(ws, error): print(error) def on_close(ws): print("### closed ###") def on_open(ws): def run(*args): for i in range(runs): time.sleep(5) ws.send("Ping") time.sleep(1) ws.close() print("thread terminating...") thread.start_new_thread(run, ()) if __name__ == "__main__": websocket.enableTrace(True) url = "ws://localhost:8082" ws = websocket.WebSocketApp(url, on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()
[((31, 4, 31, 36), '_thread.start_new_thread', 'thread.start_new_thread', ({(31, 28, 31, 31): 'run', (31, 33, 31, 35): '()'}, {}), '(run, ())', True, 'import _thread as thread\n'), ((36, 4, 36, 31), 'websocket.enableTrace', 'websocket.enableTrace', ({(36, 26, 36, 30): '(True)'}, {}), '(True)', False, 'import websocket\n'), ((39, 9, 39, 103), 'websocket.WebSocketApp', 'websocket.WebSocketApp', (), '', False, 'import websocket\n'), ((27, 8, 27, 21), 'time.sleep', 'time.sleep', ({(27, 19, 27, 20): '(1)'}, {}), '(1)', False, 'import time\n'), ((25, 12, 25, 25), 'time.sleep', 'time.sleep', ({(25, 23, 25, 24): '(5)'}, {}), '(5)', False, 'import time\n')]
samuelterra22/Data-Mining
Main.py
0237bc6e86f28f7bf1306dfb60c41987f5e41bbd
import pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats import seaborn as sns from matplotlib import rcParams import statsmodels.api as sm from statsmodels.formula.api import ols df = pd.read_csv('kc_house_data.csv') # print(df.head()) # print(df.isnull().any()) # print(df.describe()) # fig = plt.figure(figsize=(12, 6)) # sqft = fig.add_subplot(121) # cost = fig.add_subplot(122) # # sqft.hist(df.sqft_living, bins=80) # sqft.set_xlabel('Ft^2') # sqft.set_title("Histogram of House Square Footage") # # cost.hist(df.price, bins=80) # cost.set_xlabel('Price ($)') # cost.set_title("Histogram of Housing Prices") # # plt.show() # m = ols('price ~ sqft_living', df).fit() # print(m.summary()) # m = ols('price ~ sqft_living + bedrooms + grade + condition',df).fit() # print (m.summary()) sns.jointplot(x="sqft_living", y="price", data=df, kind='reg', fit_reg=True, size=7) plt.show()
[((10, 5, 10, 37), 'pandas.read_csv', 'pd.read_csv', ({(10, 17, 10, 36): '"""kc_house_data.csv"""'}, {}), "('kc_house_data.csv')", True, 'import pandas as pd\n'), ((36, 0, 36, 84), 'seaborn.jointplot', 'sns.jointplot', (), '', True, 'import seaborn as sns\n'), ((37, 0, 37, 10), 'matplotlib.pyplot.show', 'plt.show', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n')]
11uc/whole_cell_patch
whole_cell_patch/filterDialog.py
84e11bbb904b363a6bb5af878d46e23d789c5be0
# Dialogs for setting filter parameters. from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, \ QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget from PyQt5.QtCore import pyqtSignal class FilterDialog(QDialog): ''' Dialog for choosing filter types. ''' def __init__(self, default, parent = None): ''' Build ui and set up parameter setting Parameters ---------- default: list List of filters, which are dictionaries with names under key "name" and parameter elements. parent: QWidget, optional Parent widget. Attributes ---------- fnames: dictionary Names of filters, two nested dictionaries to specify two properties about the type of filters. ''' self.defaultFilters = default super().__init__(parent) self.filterCb = QComboBox(self) # Filter type self.bandCb = QComboBox(self) # Band type self.fnames = {} count = 0 for f in default: names = f["name"].split(',') if names[0] not in self.fnames: self.fnames[names[0]] = {} self.filterCb.addItem(names[0]) if len(names) > 1: if names[1] not in self.fnames[names[0]]: self.fnames[names[0]][names[1]] = count else: self.fnames[names[0]][''] = count count += 1 okBtn = QPushButton("OK", self) cancelBtn = QPushButton("Cancel", self) okBtn.clicked.connect(self.accept) cancelBtn.clicked.connect(self.reject) self.filterCb.currentTextChanged.connect(self.updateBand) topVB = QVBoxLayout(self) topVB.addWidget(self.filterCb) topVB.addWidget(self.bandCb) topVB.addWidget(okBtn) topVB.addWidget(cancelBtn) def updateBand(self, name): ''' Update list of band in the band combobox. Parameters ---------- name: str Name of filter type. ''' self.bandCb.clear() self.bandCb.addItems(list(self.fnames[name].keys())) def exec_(self): ''' Override QDialog exec_ function. Alter return code to -1 for rejection and integer number for chosen filter's id. ''' ret = super().exec_() if ret: return self.fnames[self.filterCb.currentText()][ self.bandCb.currentText()] else: return -1 class FilterParamDialog(QDialog): ''' Dialog for setting filter parameters. ''' def __init__(self, parent = None): ''' Build ui and set up connections. Parameters ---------- parent: QWidget, optional Parent widget. Attributes ---------- form: dictionary Parameter names as keys and corresponding QLineEdit object as values. formWd: QWidget Container for displaying the parameter setting form. ''' super().__init__(parent) self.form = {} okBtn = QPushButton("OK", self) cancelBtn = QPushButton("Cancel", self) topVB = QVBoxLayout(self) self.formVB = QVBoxLayout() self.formWd = None btnHB = QHBoxLayout() btnHB.addWidget(okBtn) btnHB.addWidget(cancelBtn) cancelBtn.clicked.connect(self.reject) okBtn.clicked.connect(self.accept) topVB.addLayout(self.formVB) topVB.addLayout(btnHB) def makeForm(self, filt): ''' Build parameters setting grid layout for filter filt. Parameters ---------- filt: dictionary Filter information, parameters are in string format. ''' # clear the previous form widget if self.formWd != None: self.formVB.removeWidget(self.formWd) self.form = {} self.formWd.setParent(None) del self.formWd self.formWd = None self.formWd = QWidget() formGrid = QGridLayout(self.formWd) row = 0 for k, v in filt.items(): if k != "name": self.form[k] = QLineEdit(v, self.formWd) formGrid.addWidget(QLabel(k, self.formWd), row, 0) formGrid.addWidget(self.form[k], row, 1) row = row + 1 self.formVB.addWidget(self.formWd) def getForm(self): ''' Get the parameters filled in the QLineEdit objects. Returns ------- filt: dictionary Filter information, without name. ''' filt = {} for k, v in self.form.items(): filt[k] = v.text() return filt
[((31, 18, 31, 33), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ({(31, 28, 31, 32): 'self'}, {}), '(self)', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((32, 16, 32, 31), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ({(32, 26, 32, 30): 'self'}, {}), '(self)', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((46, 10, 46, 33), 'PyQt5.QtWidgets.QPushButton', 'QPushButton', ({(46, 22, 46, 26): '"""OK"""', (46, 28, 46, 32): 'self'}, {}), "('OK', self)", False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((47, 14, 47, 41), 'PyQt5.QtWidgets.QPushButton', 'QPushButton', ({(47, 26, 47, 34): '"""Cancel"""', (47, 36, 47, 40): 'self'}, {}), "('Cancel', self)", False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((51, 10, 51, 27), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ({(51, 22, 51, 26): 'self'}, {}), '(self)', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((105, 10, 105, 33), 'PyQt5.QtWidgets.QPushButton', 'QPushButton', ({(105, 22, 105, 26): '"""OK"""', (105, 28, 105, 32): 'self'}, {}), "('OK', self)", False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((106, 14, 106, 41), 'PyQt5.QtWidgets.QPushButton', 'QPushButton', ({(106, 26, 106, 34): '"""Cancel"""', (106, 36, 106, 40): 'self'}, {}), "('Cancel', self)", False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((107, 10, 107, 27), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ({(107, 22, 107, 26): 'self'}, {}), '(self)', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((108, 16, 108, 29), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ({}, {}), '()', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((110, 10, 110, 23), 'PyQt5.QtWidgets.QHBoxLayout', 'QHBoxLayout', ({}, {}), '()', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((134, 16, 134, 25), 'PyQt5.QtWidgets.QWidget', 'QWidget', ({}, {}), '()', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((135, 13, 135, 37), 'PyQt5.QtWidgets.QGridLayout', 'QGridLayout', ({(135, 25, 135, 36): 'self.formWd'}, {}), '(self.formWd)', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((139, 19, 139, 44), 'PyQt5.QtWidgets.QLineEdit', 'QLineEdit', ({(139, 29, 139, 30): 'v', (139, 32, 139, 43): 'self.formWd'}, {}), '(v, self.formWd)', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n'), ((140, 23, 140, 45), 'PyQt5.QtWidgets.QLabel', 'QLabel', ({(140, 30, 140, 31): 'k', (140, 33, 140, 44): 'self.formWd'}, {}), '(k, self.formWd)', False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QDialog, QComboBox, QWidget\n')]
zl930216/ParlAI
projects/controllable_dialogue/tasks/agents.py
abf0ad6d1779af0f8ce0b5aed00d2bab71416684
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import copy from .build import build, make_path from parlai.utils.misc import warn_once from parlai.core.teachers import ParlAIDialogTeacher def _path(opt): build(opt) datatype = opt['datatype'].split(':')[0] if datatype == 'test': warn_once("WARNING: Test set not included. Setting datatype to valid.") datatype = 'valid' return make_path(opt, datatype + '.txt') class DefaultTeacher(ParlAIDialogTeacher): def __init__(self, opt, shared=None): opt = copy.deepcopy(opt) opt['parlaidialogteacher_datafile'] = _path(opt) super().__init__(opt, shared)
[((17, 8, 17, 79), 'parlai.utils.misc.warn_once', 'warn_once', ({(17, 18, 17, 78): '"""WARNING: Test set not included. Setting datatype to valid."""'}, {}), "('WARNING: Test set not included. Setting datatype to valid.')", False, 'from parlai.utils.misc import warn_once\n'), ((24, 14, 24, 32), 'copy.deepcopy', 'copy.deepcopy', ({(24, 28, 24, 31): 'opt'}, {}), '(opt)', False, 'import copy\n')]
davisschenk/project-euler-python
problems/p009.py
1375412e6c8199ab02250bd67223c758d4df1725
from math import ceil, sqrt from problem import Problem from utils.math import gcd class PythagoreanTriplet(Problem, name="Special Pythagorean triplet", expected=31875000): @Problem.solution() def brute_force(self, ts=1000): for a in range(3, round((ts - 3) / 2)): for b in range(a + 1, round((ts - 1 - a) / 2)): c = ts - a - b if c * c == a * a + b * b: return a * b * c @Problem.solution() def parametrisation(self, ts=1000): s2 = ts / 2 mlimit = ceil(sqrt(s2)) - 1 for m in range(2, mlimit): if s2 % m == 0: sm = s2 / m while sm % 2 == 0: sm /= 2 if m % 2 == 1: k = m + 2 else: k = m + 1 while k < 2 * m and k <= sm: if sm % k == 0 and gcd(k, m) == 1: d = s2 / (k * m) n = k - m a = d * (m * m - n * n) b = 2 * d * m * n c = d * (m * m + n * n) return a * b * c k += 2
[((8, 5, 8, 23), 'problem.Problem.solution', 'Problem.solution', ({}, {}), '()', False, 'from problem import Problem\n'), ((17, 5, 17, 23), 'problem.Problem.solution', 'Problem.solution', ({}, {}), '()', False, 'from problem import Problem\n'), ((20, 22, 20, 30), 'math.sqrt', 'sqrt', ({(20, 27, 20, 29): 's2'}, {}), '(s2)', False, 'from math import ceil, sqrt\n'), ((34, 39, 34, 48), 'utils.math.gcd', 'gcd', ({(34, 43, 34, 44): 'k', (34, 46, 34, 47): 'm'}, {}), '(k, m)', False, 'from utils.math import gcd\n')]
murbanec/Roche2D
Roche.py
a4d7e85e893fd6f18c12b682c2c8ca33b2b549a6
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 10:37:04 2021 @author: martin urbanec """ #calculates trajectory of small mass positioned close to L4 Lagrange point #creates gif as output import math import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, PillowWriter DistanceJ = 778570000000. # m JUPITER FROM SUN G = 6.67259*10**-11 Jupiter_mass = 1.8982*10**27 # kg Sun_mass = 1.989*10**30 # kg M1=Sun_mass M2=Jupiter_mass a=DistanceJ Ang_vel=math.sqrt(G*(M1+M2)/(a**3)) #FROM KEPLER LAW P=2.*math.pi/Ang_vel #Period #center of mass is located at [0,0] massive object (Sun) is located at -r1, secondary object (Jupiter) is located at +r2 r2=M1*a/(M1+M2) r1=M2*a/(M1+M2) # Calculations are done in corotating frame # s1, s2 are distances from sources of gravity (Sun, Jupiter) def pot(x,y): r=math.sqrt(x*x + y*y) if x==0: if y>0: theta=math.pi/2. if y<0: theta=math.pi/2. if x>0: theta=math.atan(abs(y)/x) else: theta=math.pi-math.atan(abs(y)/x) s1=math.sqrt(r1*r1 + r*r + 2.*r1*r*math.cos(theta)) s2=math.sqrt(r2*r2 + r*r - 2.*r2*r*math.cos(theta)) result = -G*(M1/s1 + M2/s2) -1.*Ang_vel*Ang_vel*r*r/2. return result #Force per unit mass (acceleration) in x direction # ax = \partial pot(x,y) / \partial x - 2 \Omega \times v # in our case \Omega=(0,0,\Omega) and v=(vx,vy,0) # second term is corresponding to Coriolis force def ax(x,y,vx,vy): dx=a/1000. # result=-(pot(x+dx,y) -pot(x-dx,y))/(2.*dx) + 2.* Ang_vel*vy result=-(-pot(x+2.*dx,y) + 8.*pot(x+dx,y) - 8.*pot(x-dx,y) + pot(x-2.*dx,y))/(12.*dx) + 2.* Ang_vel*vy return result def ay(x,y,vx,vy): dy=a/1000. # result=-( pot(x,y+dy)-pot(x,y-dy))/(dy*2.) - 2.* Ang_vel*vx result=-(-pot(x,y+2.*dy) + 8.*pot(x,y+dy) - 8.*pot(x,y-dy) + pot(x,y-2*dy))/(dy*12.) - 2.* Ang_vel*vx return result pot2=np.vectorize(pot) #TRAJECTORY OF ASTEROID CLOSE STARTING CLOSE TO L4 in rest with respect to the rotating frame x0=a/2.-r1 y0=math.sqrt(3)*a/2. x0=1.005*x0 y0=1.005*y0 vx0=0. vy0=0. steps=300000 #initialize arrays x= np.linspace(0, 10, steps) y= np.linspace(0, 10, steps) vx=np.linspace(0, 10, steps) vy=np.linspace(0, 10, steps) t= np.linspace(0, 10, steps) x[0]=x0 vx[0]=vx0 y[0]=y0 vy[0]=vy0 t[0]=0. i=0 timescale = math.sqrt((a*a)**1.5 / G/(M1+M2)) dt=timescale/1000. #using 4th order Runge-Kutta to solve the a_x= d v_x/ dt # dt is constant set to timescale/1000 for i in range (1,steps): t[i]=(t[i-1]+dt) Kx1=dt*ax(x[i-1],y[i-1],vx[i-1],vy[i-1]) Kx2=dt*ax(x[i-1],y[i-1],vx[i-1]+Kx1/2.,vy[i-1]) Kx3=dt*ax(x[i-1],y[i-1],vx[i-1]+Kx2/2.,vy[i-1]) Kx4=dt*ax(x[i-1],y[i-1],vx[i-1]+Kx3,vy[i-1]) vx[i]=vx[i-1] + Kx1/6. + Kx2/3. + Kx3/3. + Kx4/6. Ky1=dt*ay(x[i-1],y[i-1],vx[i-1],vy[i-1]) Ky2=dt*ay(x[i-1],y[i-1],vx[i-1],vy[i-1]+Ky1/2.) Ky3=dt*ay(x[i-1],y[i-1],vx[i-1],vy[i-1]+Ky2/2.) Ky4=dt*ay(x[i-1],y[i-1],vx[i-1],vy[i-1]+Ky3) vy[i]=vy[i-1] + Ky1/6. + Ky2/3. + Ky3/3. + Ky4/6. x[i]=x[i-1] + (vx[i-1]+vx[i])*dt/2. #taking the average of velocities y[i]=y[i-1] + (vy[i-1]+vy[i])*dt/2. dt=timescale/1000. #LAGRANGE POINTS #L3, L1 and L2 points are lying on x-axis (left to right) for small values of alpha=M2/(M1+M2) the positions can are given analytically (to first order in alpha) alpha=M2/(M1+M2) L1X=a*(1.-(alpha/3.)**(1./3.)) L1Y=0. P1=pot(L1X,L1Y) L2X=a*(1.+(alpha/3.)**(1./3.)) L2Y=0. P2=pot(L2X,L2Y) L3X=-a*(1. + 5.*alpha/12) L3Y=0. P3=pot(L3X,L3Y) L4X=a/2.-r1 L4Y=math.sqrt(3)*a/2. P4=pot2(L4X,L4Y) P0=pot(x0,y0) steps=301 xx= np.arange(-2*a, 2.*a,a/steps) yy= np.arange(-1.5*a, 1.5*a,a/steps) X, Y = np.meshgrid(xx, yy) Z1=pot2(X,Y) fig, ax = plt.subplots() ax.set_aspect('equal','box') ln1, = plt.plot([],[], 'k+') ln2, = plt.plot([], [], 'm*') XXX,YYY=[],[] def init(): ax.set_xlim(-1.25,1.25) ax.set_ylim(-1.25,1.25) ax.contour(X/a, Y/a, Z1,levels=[P1,P2,P3,P0],colors=('r', 'green', 'blue', 'm')) def update(i): ln1.set_data(x[1000*i]/a, y[1000*i]/a) zed= np.arange(60) ani = FuncAnimation(fig, update, np.arange(300), init_func=init) plt.show() writer = PillowWriter(fps=25) ani.save("Animation.gif", writer=writer)
[((28, 8, 28, 35), 'math.sqrt', 'math.sqrt', ({(28, 18, 28, 34): 'G * (M1 + M2) / a ** 3'}, {}), '(G * (M1 + M2) / a ** 3)', False, 'import math\n'), ((75, 5, 75, 22), 'numpy.vectorize', 'np.vectorize', ({(75, 18, 75, 21): 'pot'}, {}), '(pot)', True, 'import numpy as np\n'), ((89, 3, 89, 28), 'numpy.linspace', 'np.linspace', ({(89, 15, 89, 16): '0', (89, 18, 89, 20): '10', (89, 22, 89, 27): 'steps'}, {}), '(0, 10, steps)', True, 'import numpy as np\n'), ((90, 3, 90, 28), 'numpy.linspace', 'np.linspace', ({(90, 15, 90, 16): '0', (90, 18, 90, 20): '10', (90, 22, 90, 27): 'steps'}, {}), '(0, 10, steps)', True, 'import numpy as np\n'), ((91, 3, 91, 28), 'numpy.linspace', 'np.linspace', ({(91, 15, 91, 16): '0', (91, 18, 91, 20): '10', (91, 22, 91, 27): 'steps'}, {}), '(0, 10, steps)', True, 'import numpy as np\n'), ((92, 3, 92, 28), 'numpy.linspace', 'np.linspace', ({(92, 15, 92, 16): '0', (92, 18, 92, 20): '10', (92, 22, 92, 27): 'steps'}, {}), '(0, 10, steps)', True, 'import numpy as np\n'), ((93, 3, 93, 28), 'numpy.linspace', 'np.linspace', ({(93, 15, 93, 16): '0', (93, 18, 93, 20): '10', (93, 22, 93, 27): 'steps'}, {}), '(0, 10, steps)', True, 'import numpy as np\n'), ((101, 12, 101, 45), 'math.sqrt', 'math.sqrt', ({(101, 22, 101, 44): '(a * a) ** 1.5 / G / (M1 + M2)'}, {}), '((a * a) ** 1.5 / G / (M1 + M2))', False, 'import math\n'), ((155, 4, 155, 33), 'numpy.arange', 'np.arange', ({(155, 14, 155, 18): '-2 * a', (155, 20, 155, 24): '2.0 * a', (155, 25, 155, 32): 'a / steps'}, {}), '(-2 * a, 2.0 * a, a / steps)', True, 'import numpy as np\n'), ((156, 4, 156, 36), 'numpy.arange', 'np.arange', ({(156, 14, 156, 20): '-1.5 * a', (156, 22, 156, 27): '1.5 * a', (156, 28, 156, 35): 'a / steps'}, {}), '(-1.5 * a, 1.5 * a, a / steps)', True, 'import numpy as np\n'), ((157, 7, 157, 26), 'numpy.meshgrid', 'np.meshgrid', ({(157, 19, 157, 21): 'xx', (157, 23, 157, 25): 'yy'}, {}), '(xx, yy)', True, 'import numpy as np\n'), ((162, 10, 162, 24), 'matplotlib.pyplot.subplots', 'plt.subplots', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((166, 7, 166, 28), 'matplotlib.pyplot.plot', 'plt.plot', ({(166, 16, 166, 18): '[]', (166, 19, 166, 21): '[]', (166, 23, 166, 27): '"""k+"""'}, {}), "([], [], 'k+')", True, 'import matplotlib.pyplot as plt\n'), ((167, 7, 167, 29), 'matplotlib.pyplot.plot', 'plt.plot', ({(167, 16, 167, 18): '[]', (167, 20, 167, 22): '[]', (167, 24, 167, 28): '"""m*"""'}, {}), "([], [], 'm*')", True, 'import matplotlib.pyplot as plt\n'), ((182, 5, 182, 18), 'numpy.arange', 'np.arange', ({(182, 15, 182, 17): '60'}, {}), '(60)', True, 'import numpy as np\n'), ((184, 0, 184, 10), 'matplotlib.pyplot.show', 'plt.show', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((186, 9, 186, 29), 'matplotlib.animation.PillowWriter', 'PillowWriter', (), '', False, 'from matplotlib.animation import FuncAnimation, PillowWriter\n'), ((39, 6, 39, 26), 'math.sqrt', 'math.sqrt', ({(39, 16, 39, 25): 'x * x + y * y'}, {}), '(x * x + y * y)', False, 'import math\n'), ((183, 33, 183, 47), 'numpy.arange', 'np.arange', ({(183, 43, 183, 46): '300'}, {}), '(300)', True, 'import numpy as np\n'), ((82, 3, 82, 15), 'math.sqrt', 'math.sqrt', ({(82, 13, 82, 14): '(3)'}, {}), '(3)', False, 'import math\n'), ((146, 4, 146, 16), 'math.sqrt', 'math.sqrt', ({(146, 14, 146, 15): '(3)'}, {}), '(3)', False, 'import math\n'), ((49, 39, 49, 54), 'math.cos', 'math.cos', ({(49, 48, 49, 53): 'theta'}, {}), '(theta)', False, 'import math\n'), ((50, 39, 50, 54), 'math.cos', 'math.cos', ({(50, 48, 50, 53): 'theta'}, {}), '(theta)', False, 'import math\n')]
LyleH/youtube-dl
youtube_dl/extractor/azubu.py
7564b09ef5c09454908f78cb91c3bd2d6daacac5
from __future__ import unicode_literals import json from .common import InfoExtractor from ..utils import ( ExtractorError, float_or_none, sanitized_Request, ) class AzubuIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?azubu\.tv/[^/]+#!/play/(?P<id>\d+)' _TESTS = [ { 'url': 'http://www.azubu.tv/GSL#!/play/15575/2014-hot6-cup-last-big-match-ro8-day-1', 'md5': 'a88b42fcf844f29ad6035054bd9ecaf4', 'info_dict': { 'id': '15575', 'ext': 'mp4', 'title': '2014 HOT6 CUP LAST BIG MATCH Ro8 Day 1', 'description': 'md5:d06bdea27b8cc4388a90ad35b5c66c01', 'thumbnail': 're:^https?://.*\.jpe?g', 'timestamp': 1417523507.334, 'upload_date': '20141202', 'duration': 9988.7, 'uploader': 'GSL', 'uploader_id': 414310, 'view_count': int, }, }, { 'url': 'http://www.azubu.tv/FnaticTV#!/play/9344/-fnatic-at-worlds-2014:-toyz---%22i-love-rekkles,-he-has-amazing-mechanics%22-', 'md5': 'b72a871fe1d9f70bd7673769cdb3b925', 'info_dict': { 'id': '9344', 'ext': 'mp4', 'title': 'Fnatic at Worlds 2014: Toyz - "I love Rekkles, he has amazing mechanics"', 'description': 'md5:4a649737b5f6c8b5c5be543e88dc62af', 'thumbnail': 're:^https?://.*\.jpe?g', 'timestamp': 1410530893.320, 'upload_date': '20140912', 'duration': 172.385, 'uploader': 'FnaticTV', 'uploader_id': 272749, 'view_count': int, }, 'skip': 'Channel offline', }, ] def _real_extract(self, url): video_id = self._match_id(url) data = self._download_json( 'http://www.azubu.tv/api/video/%s' % video_id, video_id)['data'] title = data['title'].strip() description = data.get('description') thumbnail = data.get('thumbnail') view_count = data.get('view_count') user = data.get('user', {}) uploader = user.get('username') uploader_id = user.get('id') stream_params = json.loads(data['stream_params']) timestamp = float_or_none(stream_params.get('creationDate'), 1000) duration = float_or_none(stream_params.get('length'), 1000) renditions = stream_params.get('renditions') or [] video = stream_params.get('FLVFullLength') or stream_params.get('videoFullLength') if video: renditions.append(video) if not renditions and not user.get('channel', {}).get('is_live', True): raise ExtractorError('%s said: channel is offline.' % self.IE_NAME, expected=True) formats = [{ 'url': fmt['url'], 'width': fmt['frameWidth'], 'height': fmt['frameHeight'], 'vbr': float_or_none(fmt['encodingRate'], 1000), 'filesize': fmt['size'], 'vcodec': fmt['videoCodec'], 'container': fmt['videoContainer'], } for fmt in renditions if fmt['url']] self._sort_formats(formats) return { 'id': video_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'timestamp': timestamp, 'duration': duration, 'uploader': uploader, 'uploader_id': uploader_id, 'view_count': view_count, 'formats': formats, } class AzubuLiveIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?azubu\.tv/(?P<id>[^/]+)$' _TEST = { 'url': 'http://www.azubu.tv/MarsTVMDLen', 'only_matching': True, } def _real_extract(self, url): user = self._match_id(url) info = self._download_json( 'http://api.azubu.tv/public/modules/last-video/{0}/info'.format(user), user)['data'] if info['type'] != 'STREAM': raise ExtractorError('{0} is not streaming live'.format(user), expected=True) req = sanitized_Request( 'https://edge-elb.api.brightcove.com/playback/v1/accounts/3361910549001/videos/ref:' + info['reference_id']) req.add_header('Accept', 'application/json;pk=BCpkADawqM1gvI0oGWg8dxQHlgT8HkdE2LnAlWAZkOlznO39bSZX726u4JqnDsK3MDXcO01JxXK2tZtJbgQChxgaFzEVdHRjaDoxaOu8hHOO8NYhwdxw9BzvgkvLUlpbDNUuDoc4E4wxDToV') bc_info = self._download_json(req, user) m3u8_url = next(source['src'] for source in bc_info['sources'] if source['container'] == 'M2TS') formats = self._extract_m3u8_formats(m3u8_url, user, ext='mp4') self._sort_formats(formats) return { 'id': info['id'], 'title': self._live_title(info['title']), 'uploader_id': user, 'formats': formats, 'is_live': True, 'thumbnail': bc_info['poster'], }
[((67, 24, 67, 57), 'json.loads', 'json.loads', ({(67, 35, 67, 56): "data['stream_params']"}, {}), "(data['stream_params'])", False, 'import json\n')]
dan-blanchard/conda-build
conda_build/main_develop.py
2db31bb2c48d2459e16df80172967d906f43b355
# (c) Continuum Analytics, Inc. / http://continuum.io # All Rights Reserved # # conda is distributed under the terms of the BSD 3-clause license. # Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause. from __future__ import absolute_import, division, print_function import sys from os.path import join, isdir, abspath, expanduser, exists import shutil from conda.cli.common import add_parser_prefix, get_prefix from conda.cli.conda_argparse import ArgumentParser from conda_build.main_build import args_func from conda_build.post import mk_relative_osx from conda_build.utils import _check_call, rec_glob from conda.install import linked def main(): p = ArgumentParser( description=""" Install a Python package in 'development mode'. This works by creating a conda.pth file in site-packages.""" # TODO: Use setup.py to determine any entry-points to install. ) p.add_argument( 'source', action="store", metavar='PATH', nargs='+', help="Path to the source directory." ) p.add_argument('-npf', '--no-pth-file', action='store_true', help=("Relink compiled extension dependencies against " "libraries found in current conda env. " "Do not add source to conda.pth.")) p.add_argument('-b', '--build_ext', action='store_true', help=("Build extensions inplace, invoking: " "python setup.py build_ext --inplace; " "add to conda.pth; relink runtime libraries to " "environment's lib/.")) p.add_argument('-c', '--clean', action='store_true', help=("Invoke clean on setup.py: " "python setup.py clean " "use with build_ext to clean before building.")) p.add_argument('-u', '--uninstall', action='store_true', help=("Removes package if installed in 'development mode' " "by deleting path from conda.pth file. Ignore other " "options - just uninstall and exit")) add_parser_prefix(p) p.set_defaults(func=execute) args = p.parse_args() args_func(args, p) def relink_sharedobjects(pkg_path, build_prefix): ''' invokes functions in post module to relink to libraries in conda env :param pkg_path: look for shared objects to relink in pkg_path :param build_prefix: path to conda environment which contains lib/. to find runtime libraries. .. note:: develop mode builds the extensions in place and makes a link to package in site-packages/. The build_prefix points to conda environment since runtime libraries should be loaded from environment's lib/. first ''' # find binaries in package dir and make them relocatable bin_files = rec_glob(pkg_path, ['.so']) for b_file in bin_files: if sys.platform == 'darwin': mk_relative_osx(b_file, build_prefix) else: print("Nothing to do on Linux or Windows.") def write_to_conda_pth(sp_dir, pkg_path): ''' Append pkg_path to conda.pth in site-packages directory for current environment. Only add path if it doens't already exist. :param sp_dir: path to site-packages/. directory :param pkg_path: the package path to append to site-packes/. dir. ''' c_file = join(sp_dir, 'conda.pth') with open(c_file, 'a') as f: with open(c_file, 'r') as cf: # make sure file exists, before we try to read from it hence nested # in append with block # expect conda.pth to be small so read it all in at once pkgs_in_dev_mode = cf.readlines() # only append pkg_path if it doesn't already exist in conda.pth if pkg_path + '\n' in pkgs_in_dev_mode: print("path exits, skipping " + pkg_path) else: f.write(pkg_path + '\n') print("added " + pkg_path) def get_site_pkg(prefix, py_ver): ''' Given the path to conda environment, find the site-packages directory :param prefix: path to conda environment. Look here for current environment's site-packages :returns: absolute path to site-packages directory ''' # get site-packages directory stdlib_dir = join(prefix, 'Lib' if sys.platform == 'win32' else 'lib/python%s' % py_ver) sp_dir = join(stdlib_dir, 'site-packages') return sp_dir def get_setup_py(path_): ''' Return full path to setup.py or exit if not found ''' # build path points to source dir, builds are placed in the setup_py = join(path_, 'setup.py') if not exists(setup_py): sys.exit("No setup.py found in {0}. Exiting.".format(path_)) return setup_py def clean(setup_py): ''' This invokes: $ python setup.py clean :param setup_py: path to setup.py ''' # first call setup.py clean cmd = ['python', setup_py, 'clean'] _check_call(cmd) print("Completed: " + " ".join(cmd)) print("===============================================") def build_ext(setup_py): ''' Define a develop function - similar to build function todo: need to test on win32 and linux It invokes: $ python setup.py build_ext --inplace :param setup_py: path to setup.py ''' # next call setup.py develop cmd = ['python', setup_py, 'build_ext', '--inplace'] _check_call(cmd) print("Completed: " + " ".join(cmd)) print("===============================================") def uninstall(sp_dir, pkg_path): ''' Look for pkg_path in conda.pth file in site-packages directory and remove it. If pkg_path is not found in conda.pth, it means package is not installed in 'development mode' via conda develop. :param sp_dir: path to site-packages/. directory :param pkg_path: the package path to be uninstalled. ''' o_c_pth = join(sp_dir, 'conda.pth') n_c_pth = join(sp_dir, 'conda.pth.temp') found = False with open(n_c_pth, 'w') as new_c: with open(o_c_pth, 'r') as orig_c: for line in orig_c: if line != pkg_path + '\n': new_c.write(line) else: print("uninstalled: " + pkg_path) found = True if not found: print("conda.pth does not contain path: " + pkg_path) print("package not installed via conda develop") shutil.move(n_c_pth, o_c_pth) def execute(args, parser): prefix = get_prefix(args) if not isdir(prefix): sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create the environment first. #""" % prefix) for package in linked(prefix): name, ver, _ = package .rsplit('-', 2) if name == 'python': py_ver = ver[:3] # x.y break else: raise RuntimeError("python is not installed in %s" % prefix) # current environment's site-packages directory sp_dir = get_site_pkg(prefix, py_ver) for path in args.source: pkg_path = abspath(expanduser(path)) if args.uninstall: # uninstall then exit - does not do any other operations uninstall(sp_dir, pkg_path) sys.exit(0) if args.clean or args.build_ext: setup_py = get_setup_py(pkg_path) if args.clean: clean(setup_py) if not args.build_ext: sys.exit(0) # build extensions before adding to conda.pth if args.build_ext: build_ext(setup_py) if not args.no_pth_file: write_to_conda_pth(sp_dir, pkg_path) # go through the source looking for compiled extensions and make sure # they use the conda environment for loading libraries at runtime relink_sharedobjects(pkg_path, prefix) print("completed operation for: " + pkg_path) if __name__ == '__main__': main()
[((23, 8, 30, 5), 'conda.cli.conda_argparse.ArgumentParser', 'ArgumentParser', (), '', False, 'from conda.cli.conda_argparse import ArgumentParser\n'), ((61, 4, 61, 24), 'conda.cli.common.add_parser_prefix', 'add_parser_prefix', ({(61, 22, 61, 23): 'p'}, {}), '(p)', False, 'from conda.cli.common import add_parser_prefix, get_prefix\n'), ((65, 4, 65, 22), 'conda_build.main_build.args_func', 'args_func', ({(65, 14, 65, 18): 'args', (65, 20, 65, 21): 'p'}, {}), '(args, p)', False, 'from conda_build.main_build import args_func\n'), ((81, 16, 81, 43), 'conda_build.utils.rec_glob', 'rec_glob', ({(81, 25, 81, 33): 'pkg_path', (81, 35, 81, 42): "['.so']"}, {}), "(pkg_path, ['.so'])", False, 'from conda_build.utils import _check_call, rec_glob\n'), ((97, 13, 97, 38), 'os.path.join', 'join', ({(97, 18, 97, 24): 'sp_dir', (97, 26, 97, 37): '"""conda.pth"""'}, {}), "(sp_dir, 'conda.pth')", False, 'from os.path import join, isdir, abspath, expanduser, exists\n'), ((122, 17, 123, 46), 'os.path.join', 'join', ({(122, 22, 122, 28): 'prefix', (122, 30, 123, 45): "'Lib' if sys.platform == 'win32' else 'lib/python%s' % py_ver"}, {}), "(prefix, 'Lib' if sys.platform == 'win32' else 'lib/python%s' % py_ver)", False, 'from os.path import join, isdir, abspath, expanduser, exists\n'), ((124, 13, 124, 46), 'os.path.join', 'join', ({(124, 18, 124, 28): 'stdlib_dir', (124, 30, 124, 45): '"""site-packages"""'}, {}), "(stdlib_dir, 'site-packages')", False, 'from os.path import join, isdir, abspath, expanduser, exists\n'), ((132, 15, 132, 38), 'os.path.join', 'join', ({(132, 20, 132, 25): 'path_', (132, 27, 132, 37): '"""setup.py"""'}, {}), "(path_, 'setup.py')", False, 'from os.path import join, isdir, abspath, expanduser, exists\n'), ((149, 4, 149, 20), 'conda_build.utils._check_call', '_check_call', ({(149, 16, 149, 19): 'cmd'}, {}), '(cmd)', False, 'from conda_build.utils import _check_call, rec_glob\n'), ((167, 4, 167, 20), 'conda_build.utils._check_call', '_check_call', ({(167, 16, 167, 19): 'cmd'}, {}), '(cmd)', False, 'from conda_build.utils import _check_call, rec_glob\n'), ((181, 14, 181, 39), 'os.path.join', 'join', ({(181, 19, 181, 25): 'sp_dir', (181, 27, 181, 38): '"""conda.pth"""'}, {}), "(sp_dir, 'conda.pth')", False, 'from os.path import join, isdir, abspath, expanduser, exists\n'), ((182, 14, 182, 44), 'os.path.join', 'join', ({(182, 19, 182, 25): 'sp_dir', (182, 27, 182, 43): '"""conda.pth.temp"""'}, {}), "(sp_dir, 'conda.pth.temp')", False, 'from os.path import join, isdir, abspath, expanduser, exists\n'), ((197, 4, 197, 33), 'shutil.move', 'shutil.move', ({(197, 16, 197, 23): 'n_c_pth', (197, 25, 197, 32): 'o_c_pth'}, {}), '(n_c_pth, o_c_pth)', False, 'import shutil\n'), ((201, 13, 201, 29), 'conda.cli.common.get_prefix', 'get_prefix', ({(201, 24, 201, 28): 'args'}, {}), '(args)', False, 'from conda.cli.common import add_parser_prefix, get_prefix\n'), ((208, 19, 208, 33), 'conda.install.linked', 'linked', ({(208, 26, 208, 32): 'prefix'}, {}), '(prefix)', False, 'from conda.install import linked\n'), ((134, 11, 134, 27), 'os.path.exists', 'exists', ({(134, 18, 134, 26): 'setup_py'}, {}), '(setup_py)', False, 'from os.path import join, isdir, abspath, expanduser, exists\n'), ((202, 11, 202, 24), 'os.path.isdir', 'isdir', ({(202, 17, 202, 23): 'prefix'}, {}), '(prefix)', False, 'from os.path import join, isdir, abspath, expanduser, exists\n'), ((203, 8, 207, 14), 'sys.exit', 'sys.exit', ({(203, 17, 207, 13): '("""Error: environment does not exist: %s\n#\n# Use \'conda create\' to create the environment first.\n#"""\n % prefix)'}, {}), '(\n """Error: environment does not exist: %s\n#\n# Use \'conda create\' to create the environment first.\n#"""\n % prefix)', False, 'import sys\n'), ((84, 12, 84, 49), 'conda_build.post.mk_relative_osx', 'mk_relative_osx', ({(84, 28, 84, 34): 'b_file', (84, 36, 84, 48): 'build_prefix'}, {}), '(b_file, build_prefix)', False, 'from conda_build.post import mk_relative_osx\n'), ((220, 27, 220, 43), 'os.path.expanduser', 'expanduser', ({(220, 38, 220, 42): 'path'}, {}), '(path)', False, 'from os.path import join, isdir, abspath, expanduser, exists\n'), ((225, 12, 225, 23), 'sys.exit', 'sys.exit', ({(225, 21, 225, 22): '(0)'}, {}), '(0)', False, 'import sys\n'), ((232, 20, 232, 31), 'sys.exit', 'sys.exit', ({(232, 29, 232, 30): '(0)'}, {}), '(0)', False, 'import sys\n')]
ltgoslo/norBERT
benchmarking/experiments/sanity_check.py
d75d5c12d9b7f9cc11c65757f2228b7e6070b69b
#!/bin/env python3 from transformers import TFBertForTokenClassification from data_preparation.data_preparation_pos import MBERTTokenizer as MBERT_Tokenizer_pos import sys if __name__ == "__main__": if len(sys.argv) > 1: modelname = sys.argv[1] else: modelname = "ltgoslo/norbert" model = TFBertForTokenClassification.from_pretrained(modelname, from_pt=True) tokenizer = MBERT_Tokenizer_pos.from_pretrained(modelname, do_lower_case=False) print(tokenizer)
[((12, 12, 12, 81), 'transformers.TFBertForTokenClassification.from_pretrained', 'TFBertForTokenClassification.from_pretrained', (), '', False, 'from transformers import TFBertForTokenClassification\n'), ((13, 16, 13, 83), 'data_preparation.data_preparation_pos.MBERTTokenizer.from_pretrained', 'MBERT_Tokenizer_pos.from_pretrained', (), '', True, 'from data_preparation.data_preparation_pos import MBERTTokenizer as MBERT_Tokenizer_pos\n')]
WosunOO/nca_xianshu
nca47/api/controllers/v1/firewall/securityZone.py
bbb548cb67b755a57528796d4c5a66ee68df2678
from oslo_serialization import jsonutils as json from nca47.api.controllers.v1 import base from nca47.common.i18n import _ from nca47.common.i18n import _LI, _LE from nca47.common.exception import Nca47Exception from oslo_log import log from nca47.api.controllers.v1 import tools from nca47.manager.central import CentralManager from nca47.common.exception import ParamFormatError from amqp.five import string from nca47.common.exception import BadRequest from oslo_messaging import RemoteError from nca47.common import exception LOG = log.getLogger(__name__) class SecurityZoneController(base.BaseRestController): def __init__(self): self.manager = CentralManager.get_instance() super(SecurityZoneController, self).__init__() def create(self, req, *args, **kwargs): try: url = req.url if len(args) > 1: raise BadRequest(resource="SecurityZone create", msg=url) context = req.context body_values = json.loads(req.body) valid_attributes = ['tenant_id', 'dc_name', 'network_zone', 'name', 'ifnames', 'priority', 'vfwname'] values = tools.validat_values(body_values, valid_attributes) LOG.info(_LI("input the SecurityZone values with dic format \ is %(json)s"), {"json": body_values}) values["name"] = (values["tenant_id"] + "_" + values["network_zone"] + "_" + values["name"]) response = self.manager.create_securityZone(context, values) return response except Nca47Exception as e: self.response.status = e.code LOG.error(_LE('Error exception! error info: %' + e.message)) LOG.exception(e) self.response.status = e.code return tools.ret_info(e.code, e.message) except RemoteError as exception: self.response.status = 500 message = exception.value return tools.ret_info(self.response.status, message) except Exception as e: LOG.exception(e) self.response.status = 500 return tools.ret_info(self.response.status, e.message) def remove(self, req, *args, **kwargs): try: url = req.url if len(args) > 1: raise BadRequest(resource="SecurityZone del", msg=url) context = req.context body_values = json.loads(req.body) valid_attributes = ['tenant_id', 'dc_name', 'network_zone', 'id'] values = tools.validat_values(body_values, valid_attributes) # input the SecurityZone values with dic format LOG.info(_LI("delete the SecurityZone values with dic forma \ is %(json)s"), {"json": body_values}) response = self.manager.del_securityZone(context, values) return response except Nca47Exception as e: self.response.status = e.code LOG.error(_LE('Error exception! error info: %' + e.message)) LOG.exception(e) self.response.status = e.code return tools.ret_info(e.code, e.message) except RemoteError as exception: self.response.status = 500 message = exception.value return tools.ret_info(self.response.status, message) except Exception as e: LOG.exception(e) self.response.status = 500 return tools.ret_info(self.response.status, e.message) def list(self, req, *args, **kwargs): try: url = req.url if len(args) > 1: raise BadRequest(resource="SecurityZone getAll", msg=url) context = req.context body_values = json.loads(req.body) valid_attributes = ['tenant_id', 'dc_name', 'network_zone', 'vfwname'] values = tools.validat_values(body_values, valid_attributes) # get_all the SecurityZone values with dic format LOG.info(_LI("get_all the SecurityZone values with dic format \ is %(json)s"), {"json": body_values}) response = self.manager.get_securityZones(context, values) return response except Nca47Exception as e: self.response.status = e.code LOG.error(_LE('Error exception! error info: %' + e.message)) LOG.exception(e) self.response.status = e.code return tools.ret_info(e.code, e.message) except RemoteError as exception: self.response.status = 500 message = exception.value return tools.ret_info(self.response.status, message) except Exception as e: LOG.exception(e) self.response.status = 500 return tools.ret_info(self.response.status, e.message) def show(self, req, *args, **kwargs): try: url = req.url if len(args) > 1: raise BadRequest(resource="SecurityZone get", msg=url) context = req.context body_values = json.loads(req.body) valid_attributes = ['id'] values = tools.validat_values(body_values, valid_attributes) # get the staticnat values with dic format LOG.info(_LI("get the SecurityZone values with dic format\ is %(json)s"), {"json": body_values}) response = self.manager.get_securityZone(context, values) return response except Nca47Exception as e: self.response.status = e.code LOG.error(_LE('Error exception! error info: %' + e.message)) LOG.exception(e) self.response.status = e.code return tools.ret_info(e.code, e.message) except RemoteError as exception: self.response.status = 500 message = exception.value return tools.ret_info(self.response.status, message) except Exception as e: LOG.exception(e) self.response.status = 500 return tools.ret_info(self.response.status, e.message) def addif(self, req, *args, **kwargs): try: url = req.url if len(args) > 1: raise BadRequest(resource="SecurityZone add vlan", msg=url) context = req.context body_values = json.loads(req.body) valid_attributes = ['tenant_id', 'dc_name', 'network_zone', 'id', 'ifname'] values = tools.validat_values(body_values, valid_attributes) # input the SecurityZone values with dic format LOG.info(_LI("input the SecurityZone values with dic formatO is\ %(json)s"), {"json": body_values}) response = self.manager.get_securityZone(context, values) if not isinstance(values["ifname"], string): raise ParamFormatError(param_name="ifname") if values["ifname"] in response.ifnames: message = ("securityZone with ifname=" + values["ifname"] + " already exists") return tools.ret_info("400", message) response.ifnames.append(values["ifname"]) values["ifnames"] = response.ifnames response = self.manager.update_securityZone(context, values) return response except Nca47Exception as e: self.response.status = e.code LOG.error(_LE('Error exception! error info: %' + e.message)) LOG.exception(e) self.response.status = e.code return tools.ret_info(e.code, e.message) except RemoteError as exception: self.response.status = 500 message = exception.value return tools.ret_info(self.response.status, message) except Exception as e: LOG.exception(e) self.response.status = 500 return tools.ret_info(self.response.status, e.message) def delif(self, req, *args, **kwargs): try: url = req.url if len(args) > 1: raise BadRequest(resource="SecurityZone del vlan", msg=url) context = req.context body_values = json.loads(req.body) valid_attributes = ['tenant_id', 'dc_name', 'network_zone', 'id', 'ifname'] values = tools.validat_values(body_values, valid_attributes) # input the SecurityZone values with dic format LOG.info(_LI("input the SecurityZone values with dic format\ is %(json)s"), {"json": body_values}) response = self.manager.get_securityZone(context, values) if not isinstance(values["ifname"], string): raise ParamFormatError(param_name="ifname") if values["ifname"] not in response.ifnames: message = ("securityZone with ifname=" + values["ifname"]+" don't exist!") return tools.ret_info("400", message) response.ifnames.remove(values["ifname"]) values["ifnames"] = response.ifnames response = self.manager.update_securityZone(context, values) return response except Nca47Exception as e: self.response.status = e.code LOG.error(_LE('Error exception! error info: %' + e.message)) LOG.exception(e) self.response.status = e.code return tools.ret_info(e.code, e.message) except RemoteError as exception: self.response.status = 500 message = exception.value return tools.ret_info(self.response.status, message) except Exception as e: LOG.exception(e) self.response.status = 500 return tools.ret_info(self.response.status, e.message)
[((15, 6, 15, 29), 'oslo_log.log.getLogger', 'log.getLogger', ({(15, 20, 15, 28): '__name__'}, {}), '(__name__)', False, 'from oslo_log import log\n'), ((20, 23, 20, 52), 'nca47.manager.central.CentralManager.get_instance', 'CentralManager.get_instance', ({}, {}), '()', False, 'from nca47.manager.central import CentralManager\n'), ((29, 26, 29, 46), 'oslo_serialization.jsonutils.loads', 'json.loads', ({(29, 37, 29, 45): 'req.body'}, {}), '(req.body)', True, 'from oslo_serialization import jsonutils as json\n'), ((32, 21, 32, 72), 'nca47.api.controllers.v1.tools.validat_values', 'tools.validat_values', ({(32, 42, 32, 53): 'body_values', (32, 55, 32, 71): 'valid_attributes'}, {}), '(body_values, valid_attributes)', False, 'from nca47.api.controllers.v1 import tools\n'), ((62, 26, 62, 46), 'oslo_serialization.jsonutils.loads', 'json.loads', ({(62, 37, 62, 45): 'req.body'}, {}), '(req.body)', True, 'from oslo_serialization import jsonutils as json\n'), ((64, 21, 64, 72), 'nca47.api.controllers.v1.tools.validat_values', 'tools.validat_values', ({(64, 42, 64, 53): 'body_values', (64, 55, 64, 71): 'valid_attributes'}, {}), '(body_values, valid_attributes)', False, 'from nca47.api.controllers.v1 import tools\n'), ((92, 26, 92, 46), 'oslo_serialization.jsonutils.loads', 'json.loads', ({(92, 37, 92, 45): 'req.body'}, {}), '(req.body)', True, 'from oslo_serialization import jsonutils as json\n'), ((95, 21, 95, 72), 'nca47.api.controllers.v1.tools.validat_values', 'tools.validat_values', ({(95, 42, 95, 53): 'body_values', (95, 55, 95, 71): 'valid_attributes'}, {}), '(body_values, valid_attributes)', False, 'from nca47.api.controllers.v1 import tools\n'), ((123, 26, 123, 46), 'oslo_serialization.jsonutils.loads', 'json.loads', ({(123, 37, 123, 45): 'req.body'}, {}), '(req.body)', True, 'from oslo_serialization import jsonutils as json\n'), ((125, 21, 125, 72), 'nca47.api.controllers.v1.tools.validat_values', 'tools.validat_values', ({(125, 42, 125, 53): 'body_values', (125, 55, 125, 71): 'valid_attributes'}, {}), '(body_values, valid_attributes)', False, 'from nca47.api.controllers.v1 import tools\n'), ((153, 26, 153, 46), 'oslo_serialization.jsonutils.loads', 'json.loads', ({(153, 37, 153, 45): 'req.body'}, {}), '(req.body)', True, 'from oslo_serialization import jsonutils as json\n'), ((156, 21, 156, 72), 'nca47.api.controllers.v1.tools.validat_values', 'tools.validat_values', ({(156, 42, 156, 53): 'body_values', (156, 55, 156, 71): 'valid_attributes'}, {}), '(body_values, valid_attributes)', False, 'from nca47.api.controllers.v1 import tools\n'), ((193, 26, 193, 46), 'oslo_serialization.jsonutils.loads', 'json.loads', ({(193, 37, 193, 45): 'req.body'}, {}), '(req.body)', True, 'from oslo_serialization import jsonutils as json\n'), ((196, 21, 196, 72), 'nca47.api.controllers.v1.tools.validat_values', 'tools.validat_values', ({(196, 42, 196, 53): 'body_values', (196, 55, 196, 71): 'valid_attributes'}, {}), '(body_values, valid_attributes)', False, 'from nca47.api.controllers.v1 import tools\n'), ((27, 22, 27, 73), 'nca47.common.exception.BadRequest', 'BadRequest', (), '', False, 'from nca47.common.exception import BadRequest\n'), ((33, 21, 34, 33), 'nca47.common.i18n._LI', '_LI', ({(33, 25, 34, 32): '"""input the SecurityZone values with dic format is %(json)s"""'}, {}), "('input the SecurityZone values with dic format is %(json)s'\n )", False, 'from nca47.common.i18n import _LI, _LE\n'), ((46, 19, 46, 52), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(46, 34, 46, 40): 'e.code', (46, 42, 46, 51): 'e.message'}, {}), '(e.code, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((50, 19, 50, 64), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(50, 34, 50, 54): 'self.response.status', (50, 56, 50, 63): 'message'}, {}), '(self.response.status, message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((54, 19, 54, 66), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(54, 34, 54, 54): 'self.response.status', (54, 56, 54, 65): 'e.message'}, {}), '(self.response.status, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((60, 22, 60, 70), 'nca47.common.exception.BadRequest', 'BadRequest', (), '', False, 'from nca47.common.exception import BadRequest\n'), ((66, 21, 67, 37), 'nca47.common.i18n._LI', '_LI', ({(66, 25, 67, 36): '"""delete the SecurityZone values with dic forma is %(json)s"""'}, {}), "('delete the SecurityZone values with dic forma is %(json)s'\n )", False, 'from nca47.common.i18n import _LI, _LE\n'), ((76, 19, 76, 52), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(76, 34, 76, 40): 'e.code', (76, 42, 76, 51): 'e.message'}, {}), '(e.code, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((80, 19, 80, 64), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(80, 34, 80, 54): 'self.response.status', (80, 56, 80, 63): 'message'}, {}), '(self.response.status, message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((84, 19, 84, 66), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(84, 34, 84, 54): 'self.response.status', (84, 56, 84, 65): 'e.message'}, {}), '(self.response.status, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((90, 22, 90, 73), 'nca47.common.exception.BadRequest', 'BadRequest', (), '', False, 'from nca47.common.exception import BadRequest\n'), ((97, 21, 98, 37), 'nca47.common.i18n._LI', '_LI', ({(97, 25, 98, 36): '"""get_all the SecurityZone values with dic format is %(json)s"""'}, {}), "('get_all the SecurityZone values with dic format is %(json)s'\n )", False, 'from nca47.common.i18n import _LI, _LE\n'), ((107, 19, 107, 52), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(107, 34, 107, 40): 'e.code', (107, 42, 107, 51): 'e.message'}, {}), '(e.code, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((111, 19, 111, 64), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(111, 34, 111, 54): 'self.response.status', (111, 56, 111, 63): 'message'}, {}), '(self.response.status, message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((115, 19, 115, 66), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(115, 34, 115, 54): 'self.response.status', (115, 56, 115, 65): 'e.message'}, {}), '(self.response.status, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((121, 22, 121, 70), 'nca47.common.exception.BadRequest', 'BadRequest', (), '', False, 'from nca47.common.exception import BadRequest\n'), ((127, 21, 128, 38), 'nca47.common.i18n._LI', '_LI', ({(127, 25, 128, 37): '"""get the SecurityZone values with dic format is %(json)s"""'}, {}), "('get the SecurityZone values with dic format is %(json)s'\n )", False, 'from nca47.common.i18n import _LI, _LE\n'), ((137, 19, 137, 52), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(137, 34, 137, 40): 'e.code', (137, 42, 137, 51): 'e.message'}, {}), '(e.code, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((141, 19, 141, 64), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(141, 34, 141, 54): 'self.response.status', (141, 56, 141, 63): 'message'}, {}), '(self.response.status, message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((145, 19, 145, 66), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(145, 34, 145, 54): 'self.response.status', (145, 56, 145, 65): 'e.message'}, {}), '(self.response.status, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((151, 22, 151, 75), 'nca47.common.exception.BadRequest', 'BadRequest', (), '', False, 'from nca47.common.exception import BadRequest\n'), ((158, 21, 159, 35), 'nca47.common.i18n._LI', '_LI', ({(158, 25, 159, 34): '"""input the SecurityZone values with dic formatO is %(json)s"""'}, {}), "('input the SecurityZone values with dic formatO is %(json)s'\n )", False, 'from nca47.common.i18n import _LI, _LE\n'), ((163, 22, 163, 59), 'nca47.common.exception.ParamFormatError', 'ParamFormatError', (), '', False, 'from nca47.common.exception import ParamFormatError\n'), ((167, 23, 167, 53), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(167, 38, 167, 43): '"""400"""', (167, 45, 167, 52): 'message'}, {}), "('400', message)", False, 'from nca47.api.controllers.v1 import tools\n'), ((177, 19, 177, 52), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(177, 34, 177, 40): 'e.code', (177, 42, 177, 51): 'e.message'}, {}), '(e.code, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((181, 19, 181, 64), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(181, 34, 181, 54): 'self.response.status', (181, 56, 181, 63): 'message'}, {}), '(self.response.status, message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((185, 19, 185, 66), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(185, 34, 185, 54): 'self.response.status', (185, 56, 185, 65): 'e.message'}, {}), '(self.response.status, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((191, 22, 191, 75), 'nca47.common.exception.BadRequest', 'BadRequest', (), '', False, 'from nca47.common.exception import BadRequest\n'), ((198, 21, 199, 38), 'nca47.common.i18n._LI', '_LI', ({(198, 25, 199, 37): '"""input the SecurityZone values with dic format is %(json)s"""'}, {}), "('input the SecurityZone values with dic format is %(json)s'\n )", False, 'from nca47.common.i18n import _LI, _LE\n'), ((203, 22, 203, 59), 'nca47.common.exception.ParamFormatError', 'ParamFormatError', (), '', False, 'from nca47.common.exception import ParamFormatError\n'), ((207, 23, 207, 53), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(207, 38, 207, 43): '"""400"""', (207, 45, 207, 52): 'message'}, {}), "('400', message)", False, 'from nca47.api.controllers.v1 import tools\n'), ((217, 19, 217, 52), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(217, 34, 217, 40): 'e.code', (217, 42, 217, 51): 'e.message'}, {}), '(e.code, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((221, 19, 221, 64), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(221, 34, 221, 54): 'self.response.status', (221, 56, 221, 63): 'message'}, {}), '(self.response.status, message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((225, 19, 225, 66), 'nca47.api.controllers.v1.tools.ret_info', 'tools.ret_info', ({(225, 34, 225, 54): 'self.response.status', (225, 56, 225, 65): 'e.message'}, {}), '(self.response.status, e.message)', False, 'from nca47.api.controllers.v1 import tools\n'), ((43, 22, 43, 71), 'nca47.common.i18n._LE', '_LE', ({(43, 26, 43, 70): "('Error exception! error info: %' + e.message)"}, {}), "('Error exception! error info: %' + e.message)", False, 'from nca47.common.i18n import _LI, _LE\n'), ((73, 22, 73, 71), 'nca47.common.i18n._LE', '_LE', ({(73, 26, 73, 70): "('Error exception! error info: %' + e.message)"}, {}), "('Error exception! error info: %' + e.message)", False, 'from nca47.common.i18n import _LI, _LE\n'), ((104, 22, 104, 71), 'nca47.common.i18n._LE', '_LE', ({(104, 26, 104, 70): "('Error exception! error info: %' + e.message)"}, {}), "('Error exception! error info: %' + e.message)", False, 'from nca47.common.i18n import _LI, _LE\n'), ((134, 22, 134, 71), 'nca47.common.i18n._LE', '_LE', ({(134, 26, 134, 70): "('Error exception! error info: %' + e.message)"}, {}), "('Error exception! error info: %' + e.message)", False, 'from nca47.common.i18n import _LI, _LE\n'), ((174, 22, 174, 71), 'nca47.common.i18n._LE', '_LE', ({(174, 26, 174, 70): "('Error exception! error info: %' + e.message)"}, {}), "('Error exception! error info: %' + e.message)", False, 'from nca47.common.i18n import _LI, _LE\n'), ((214, 22, 214, 71), 'nca47.common.i18n._LE', '_LE', ({(214, 26, 214, 70): "('Error exception! error info: %' + e.message)"}, {}), "('Error exception! error info: %' + e.message)", False, 'from nca47.common.i18n import _LI, _LE\n')]
gitter-badger/mlmodels
mlmodels/model_tch/nbeats/model.py
f08cc9b6ec202d4ad25ecdda2f44487da387569d
import numpy as np import torch from torch import nn from torch.nn import functional as F def seasonality_model(thetas, t, device): p = thetas.size()[-1] assert p < 10, 'thetas_dim is too big.' p1, p2 = (p // 2, p // 2) if p % 2 == 0 else (p // 2, p // 2 + 1) s1 = torch.tensor([np.cos(2 * np.pi * i * t) for i in range(p1)]).float() # H/2-1 s2 = torch.tensor([np.sin(2 * np.pi * i * t) for i in range(p2)]).float() S = torch.cat([s1, s2]) return thetas.mm(S.to(device)) def trend_model(thetas, t, device): p = thetas.size()[-1] assert p <= 4, 'thetas_dim is too big.' T = torch.tensor([t ** i for i in range(p)]).float() return thetas.mm(T.to(device)) def linspace(backcast_length, forecast_length): lin_space = np.linspace(-backcast_length, forecast_length, backcast_length + forecast_length) b_ls = lin_space[:backcast_length] f_ls = lin_space[backcast_length:] return b_ls, f_ls class Block(nn.Module): def __init__(self, units, thetas_dim, device, backcast_length=10, forecast_length=5, share_thetas=False): super(Block, self).__init__() self.units = units self.thetas_dim = thetas_dim self.backcast_length = backcast_length self.forecast_length = forecast_length self.share_thetas = share_thetas self.fc1 = nn.Linear(backcast_length, units) self.fc2 = nn.Linear(units, units) self.fc3 = nn.Linear(units, units) self.fc4 = nn.Linear(units, units) self.device = device self.backcast_linspace, self.forecast_linspace = linspace(backcast_length, forecast_length) if share_thetas: self.theta_f_fc = self.theta_b_fc = nn.Linear(units, thetas_dim) else: self.theta_b_fc = nn.Linear(units, thetas_dim) self.theta_f_fc = nn.Linear(units, thetas_dim) def forward(self, x): x = F.relu(self.fc1(x.to(self.device))) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) x = F.relu(self.fc4(x)) return x def __str__(self): block_type = type(self).__name__ return f'{block_type}(units={self.units}, thetas_dim={self.thetas_dim}, ' \ f'backcast_length={self.backcast_length}, forecast_length={self.forecast_length}, ' \ f'share_thetas={self.share_thetas}) at @{id(self)}' class SeasonalityBlock(Block): def __init__(self, units, thetas_dim, device, backcast_length=10, forecast_length=5): super(SeasonalityBlock, self).__init__(units, thetas_dim, device, backcast_length, forecast_length, share_thetas=True) def forward(self, x): x = super(SeasonalityBlock, self).forward(x) backcast = seasonality_model(self.theta_b_fc(x), self.backcast_linspace, self.device) forecast = seasonality_model(self.theta_f_fc(x), self.forecast_linspace, self.device) return backcast, forecast class TrendBlock(Block): def __init__(self, units, thetas_dim, device, backcast_length=10, forecast_length=5): super(TrendBlock, self).__init__(units, thetas_dim, device, backcast_length, forecast_length, share_thetas=True) def forward(self, x): x = super(TrendBlock, self).forward(x) backcast = trend_model(self.theta_b_fc(x), self.backcast_linspace, self.device) forecast = trend_model(self.theta_f_fc(x), self.forecast_linspace, self.device) return backcast, forecast class GenericBlock(Block): def __init__(self, units, thetas_dim, device, backcast_length=10, forecast_length=5): super(GenericBlock, self).__init__(units, thetas_dim, device, backcast_length, forecast_length) self.backcast_fc = nn.Linear(thetas_dim, backcast_length) self.forecast_fc = nn.Linear(thetas_dim, forecast_length) def forward(self, x): # no constraint for generic arch. x = super(GenericBlock, self).forward(x) theta_b = F.relu(self.theta_b_fc(x)) theta_f = F.relu(self.theta_f_fc(x)) backcast = self.backcast_fc(theta_b) # generic. 3.3. forecast = self.forecast_fc(theta_f) # generic. 3.3. return backcast, forecast class NBeatsNet(nn.Module): SEASONALITY_BLOCK = 'seasonality' TREND_BLOCK = 'trend' GENERIC_BLOCK = 'generic' def __init__(self, device, stack_types=[TREND_BLOCK, SEASONALITY_BLOCK], nb_blocks_per_stack=3, forecast_length=5, backcast_length=10, thetas_dims=[4, 8], share_weights_in_stack=False, hidden_layer_units=256, ): super(NBeatsNet, self).__init__() self.forecast_length = forecast_length self.backcast_length = backcast_length self.hidden_layer_units = hidden_layer_units self.nb_blocks_per_stack = nb_blocks_per_stack self.share_weights_in_stack = share_weights_in_stack self.stack_types = stack_types self.stacks = [] self.thetas_dim = thetas_dims self.parameters = [] self.device = device print(f'| N-Beats') for stack_id in range(len(self.stack_types)): self.stacks.append(self.create_stack(stack_id)) self.parameters = nn.ParameterList(self.parameters) self.to(self.device) def create_stack(self, stack_id): stack_type = self.stack_types[stack_id] print(f'| -- Stack {stack_type.title()} (#{stack_id}) (share_weights_in_stack={self.share_weights_in_stack})') blocks = [] for block_id in range(self.nb_blocks_per_stack): block_init = NBeatsNet.select_block(stack_type) if self.share_weights_in_stack and block_id != 0: block = blocks[-1] # pick up the last one to make the else: block = block_init(self.hidden_layer_units, self.thetas_dim[stack_id], self.device, self.backcast_length, self.forecast_length) self.parameters.extend(block.parameters()) print(f' | -- {block}') blocks.append(block) return blocks @staticmethod def select_block(block_type): if block_type == NBeatsNet.SEASONALITY_BLOCK: return SeasonalityBlock elif block_type == NBeatsNet.TREND_BLOCK: return TrendBlock else: return GenericBlock def forward(self, backcast): forecast = torch.zeros(size=(backcast.size()[0], self.forecast_length,)) # maybe batch size here. for stack_id in range(len(self.stacks)): for block_id in range(len(self.stacks[stack_id])): b, f = self.stacks[stack_id][block_id](backcast) backcast = backcast.to(self.device) - b forecast = forecast.to(self.device) + f return backcast, forecast
[((13, 8, 13, 27), 'torch.cat', 'torch.cat', ({(13, 18, 13, 26): '[s1, s2]'}, {}), '([s1, s2])', False, 'import torch\n'), ((25, 16, 25, 97), 'numpy.linspace', 'np.linspace', ({(25, 28, 25, 44): '-backcast_length', (25, 46, 25, 61): 'forecast_length', (25, 63, 25, 96): 'backcast_length + forecast_length'}, {}), '(-backcast_length, forecast_length, backcast_length +\n forecast_length)', True, 'import numpy as np\n'), ((40, 19, 40, 52), 'torch.nn.Linear', 'nn.Linear', ({(40, 29, 40, 44): 'backcast_length', (40, 46, 40, 51): 'units'}, {}), '(backcast_length, units)', False, 'from torch import nn\n'), ((41, 19, 41, 42), 'torch.nn.Linear', 'nn.Linear', ({(41, 29, 41, 34): 'units', (41, 36, 41, 41): 'units'}, {}), '(units, units)', False, 'from torch import nn\n'), ((42, 19, 42, 42), 'torch.nn.Linear', 'nn.Linear', ({(42, 29, 42, 34): 'units', (42, 36, 42, 41): 'units'}, {}), '(units, units)', False, 'from torch import nn\n'), ((43, 19, 43, 42), 'torch.nn.Linear', 'nn.Linear', ({(43, 29, 43, 34): 'units', (43, 36, 43, 41): 'units'}, {}), '(units, units)', False, 'from torch import nn\n'), ((97, 27, 97, 65), 'torch.nn.Linear', 'nn.Linear', ({(97, 37, 97, 47): 'thetas_dim', (97, 49, 97, 64): 'backcast_length'}, {}), '(thetas_dim, backcast_length)', False, 'from torch import nn\n'), ((98, 27, 98, 65), 'torch.nn.Linear', 'nn.Linear', ({(98, 37, 98, 47): 'thetas_dim', (98, 49, 98, 64): 'forecast_length'}, {}), '(thetas_dim, forecast_length)', False, 'from torch import nn\n'), ((141, 26, 141, 59), 'torch.nn.ParameterList', 'nn.ParameterList', ({(141, 43, 141, 58): 'self.parameters'}, {}), '(self.parameters)', False, 'from torch import nn\n'), ((47, 48, 47, 76), 'torch.nn.Linear', 'nn.Linear', ({(47, 58, 47, 63): 'units', (47, 65, 47, 75): 'thetas_dim'}, {}), '(units, thetas_dim)', False, 'from torch import nn\n'), ((49, 30, 49, 58), 'torch.nn.Linear', 'nn.Linear', ({(49, 40, 49, 45): 'units', (49, 47, 49, 57): 'thetas_dim'}, {}), '(units, thetas_dim)', False, 'from torch import nn\n'), ((50, 30, 50, 58), 'torch.nn.Linear', 'nn.Linear', ({(50, 40, 50, 45): 'units', (50, 47, 50, 57): 'thetas_dim'}, {}), '(units, thetas_dim)', False, 'from torch import nn\n'), ((11, 23, 11, 48), 'numpy.cos', 'np.cos', ({(11, 30, 11, 47): '2 * np.pi * i * t'}, {}), '(2 * np.pi * i * t)', True, 'import numpy as np\n'), ((12, 23, 12, 48), 'numpy.sin', 'np.sin', ({(12, 30, 12, 47): '2 * np.pi * i * t'}, {}), '(2 * np.pi * i * t)', True, 'import numpy as np\n')]
chaya-v/AI-ML-Lab-Programs
BACKPROPAGATION/Backprop.py
cb2e91cf62376f5f95395e89357fa0bef730deed
from math import exp from random import seed from random import random def initialize_network(n_inputs, n_hidden, n_outputs): network = list() hidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)] network.append(hidden_layer) output_layer = [{'weights':[random() for i in range(n_hidden + 1)]} for i in range(n_outputs)] network.append(output_layer) return network def activate(weights, inputs): activation = weights[-1] for i in range(len(weights)-1): activation += weights[i] * inputs[i] return activation def transfer(activation): return 1.0 / (1.0 + exp(-activation)) def forward_propagate(network, row): inputs = row for layer in network: new_inputs = [] for neuron in layer: activation = activate(neuron['weights'], inputs) neuron['output'] = transfer(activation) new_inputs.append(neuron['output']) inputs = new_inputs return inputs def transfer_derivative(output): return output * (1.0 - output) def backward_propagate_error(network, expected): for i in reversed(range(len(network))): layer = network[i] errors = list() if i != len(network)-1: for j in range(len(layer)): error = 0.0 for neuron in network[i + 1]: error += (neuron['weights'][j] * neuron['delta']) errors.append(error) else: for j in range(len(layer)): neuron = layer[j] errors.append(expected[j] - neuron['output']) for j in range(len(layer)): neuron = layer[j] neuron['delta'] = errors[j] * transfer_derivative(neuron['output']) def update_weights(network, row, l_rate): for i in range(len(network)): inputs = row[:-1] if i != 0: inputs = [neuron['output'] for neuron in network[i - 1]] for neuron in network[i]: for j in range(len(inputs)): neuron['weights'][j] += l_rate * neuron['delta'] * inputs[j] neuron['weights'][-1] += l_rate * neuron['delta'] def train_network(network, train, l_rate, n_epoch, n_outputs): for epoch in range(n_epoch): sum_error = 0 for row in train: outputs = forward_propagate(network, row) expected = [0 for i in range(n_outputs)] expected[row[-1]] = 1 sum_error += sum([(expected[i]-outputs[i])**2 for i in range(len(expected))]) backward_propagate_error(network, expected) update_weights(network, row, l_rate) print('>epoch=%d, lrate=%.3f, error=%.3f' % (epoch, l_rate, sum_error)) seed(1) dataset = [[2.7810836,2.550537003,0], [1.465489372,2.362125076,0], [3.396561688,4.400293529,0], [1.38807019,1.850220317,0], [3.06407232,3.005305973,0], [7.627531214,2.759262235,1], [5.332441248,2.088626775,1], [6.922596716,1.77106367,1], [8.675418651,-0.242068655,1], [7.673756466,3.508563011,1]] n_inputs = len(dataset[0]) - 1 n_outputs = len(set([row[-1] for row in dataset])) network = initialize_network(n_inputs, 2, n_outputs) train_network(network, dataset, 0.5, 30, n_outputs) for layer in network: print(layer)
[((84, 0, 84, 7), 'random.seed', 'seed', ({(84, 5, 84, 6): '(1)'}, {}), '(1)', False, 'from random import seed\n'), ((23, 21, 23, 37), 'math.exp', 'exp', ({(23, 25, 23, 36): '(-activation)'}, {}), '(-activation)', False, 'from math import exp\n'), ((8, 29, 8, 37), 'random.random', 'random', ({}, {}), '()', False, 'from random import random\n'), ((10, 29, 10, 37), 'random.random', 'random', ({}, {}), '()', False, 'from random import random\n')]
benoitc/hypercouch
tests/multi_design_test.py
23055c26529a7f2198288b249b45d05b796e78bf
"""\ Copyright (c) 2009 Paul J. Davis <[email protected]> This file is part of hypercouch which is released uner the MIT license. """ import time import unittest import couchdb COUCHURI = "http://127.0.0.1:5984/" TESTDB = "hyper_tests" class MultiDesignTest(unittest.TestCase): def setUp(self): self.srv = couchdb.Server(COUCHURI) if TESTDB in self.srv: del self.srv[TESTDB] self.db = self.srv.create(TESTDB) self.db["_design/test1"] = { "ft_index": """\ function(doc) { if(doc.body) index(doc.body); if(doc.foo != undefined) property("foo", doc.foo); } """ } self.db["_design/test2"] = { "ft_index": """\ function(doc) { if(doc.bar) property("bar", doc.bar) } """ } self._wait() def tearDown(self): del self.srv[TESTDB] def _query(self, **kwargs): resp, data = self.db.resource.get("_fti", **kwargs) return data def _wait(self, expect=0, retries=10): data = self._query(q="*.**") while retries > 0 and len(data["rows"]) != expect: retries -= 1 time.sleep(0.2) data = self._query(q="*.**") if retries < 1: raise RuntimeError("Failed to find expected index state.") def test_attr(self): docs = [{"_id": str(i), "body": "This is document %d" % i, "foo": i, "bar": str(i*i)} for i in range(10)] self.db.update(docs) self._wait(expect=10) data = self._query(q="*.**", foo="NUMEQ 3", bar="NUMEQ 9") self.assertEqual(data["total_rows"], 1) self.assertEqual(data["rows"][0]["id"], "3") data = self._query(q="*.**") self.assertEqual(len(data["rows"]), 10) for row in data["rows"]: self.assertEqual(int(row["foo"]) ** 2, int(row["bar"]))
[((14, 19, 14, 43), 'couchdb.Server', 'couchdb.Server', ({(14, 34, 14, 42): 'COUCHURI'}, {}), '(COUCHURI)', False, 'import couchdb\n'), ((43, 12, 43, 27), 'time.sleep', 'time.sleep', ({(43, 23, 43, 26): '(0.2)'}, {}), '(0.2)', False, 'import time\n')]
DanieleMancini/xled_plus
xled_plus/samples/colmeander.py
a6e9f3da56f95f508ec4fa2bb6ceae005450e654
from .sample_setup import * ctr = setup_control() eff = ColorMeanderEffect(ctr, "solid") eff.launch_rt() input() eff.stop_rt() ctr.turn_off()
[]
wcyjames/dgl
python/dgl/nn/pytorch/sparse_emb.py
00a668ac6898971aa154a8a3fe851010034fd6bf
"""Torch NodeEmbedding.""" from datetime import timedelta import torch as th from ...backend import pytorch as F from ...utils import get_shared_mem_array, create_shared_mem_array _STORE = None class NodeEmbedding: # NodeEmbedding '''Class for storing node embeddings. The class is optimized for training large-scale node embeddings. It updates the embedding in a sparse way and can scale to graphs with millions of nodes. It also supports partitioning to multiple GPUs (on a single machine) for more acceleration. It does not support partitioning across machines. Currently, DGL provides two optimizers that work with this NodeEmbedding class: ``SparseAdagrad`` and ``SparseAdam``. The implementation is based on torch.distributed package. It depends on the pytorch default distributed process group to collect multi-process information and uses ``torch.distributed.TCPStore`` to share meta-data information across multiple gpu processes. It use the local address of '127.0.0.1:12346' to initialize the TCPStore. Parameters ---------- num_embeddings : int The number of embeddings. Currently, the number of embeddings has to be the same as the number of nodes. embedding_dim : int The dimension size of embeddings. name : str The name of the embeddings. The name should uniquely identify the embeddings in the system. init_func : callable, optional The function to create the initial data. If the init function is not provided, the values of the embeddings are initialized to zero. Examples -------- Before launching multiple gpu processes >>> def initializer(emb): th.nn.init.xavier_uniform_(emb) return emb In each training process >>> emb = dgl.nn.NodeEmbedding(g.number_of_nodes(), 10, 'emb', init_func=initializer) >>> optimizer = dgl.optim.SparseAdam([emb], lr=0.001) >>> for blocks in dataloader: ... ... ... feats = emb(nids, gpu_0) ... loss = F.sum(feats + 1, 0) ... loss.backward() ... optimizer.step() ''' def __init__(self, num_embeddings, embedding_dim, name, init_func=None): global _STORE # Check whether it is multi-gpu training or not. if th.distributed.is_initialized(): rank = th.distributed.get_rank() world_size = th.distributed.get_world_size() else: rank = -1 world_size = 0 self._rank = rank self._world_size = world_size host_name = '127.0.0.1' port = 12346 if rank <= 0: emb = create_shared_mem_array(name, (num_embeddings, embedding_dim), th.float32) if init_func is not None: emb = init_func(emb) if rank == 0: if world_size > 1: # for multi-gpu training, setup a TCPStore for # embeding status synchronization across GPU processes if _STORE is None: _STORE = th.distributed.TCPStore( host_name, port, world_size, True, timedelta(seconds=30)) for _ in range(1, world_size): # send embs _STORE.set(name, name) elif rank > 0: # receive if _STORE is None: _STORE = th.distributed.TCPStore( host_name, port, world_size, False, timedelta(seconds=30)) _STORE.wait([name]) emb = get_shared_mem_array(name, (num_embeddings, embedding_dim), th.float32) self._store = _STORE self._tensor = emb self._num_embeddings = num_embeddings self._embedding_dim = embedding_dim self._name = name self._optm_state = None # track optimizer state self._trace = [] # track minibatch def __call__(self, node_ids, device=th.device('cpu')): """ node_ids : th.tensor Index of the embeddings to collect. device : th.device Target device to put the collected embeddings. """ emb = self._tensor[node_ids].to(device) if F.is_recording(): emb = F.attach_grad(emb) self._trace.append((node_ids.to(device, non_blocking=True), emb)) return emb @property def store(self): """Return torch.distributed.TCPStore for meta data sharing across processes. Returns ------- torch.distributed.TCPStore KVStore used for meta data sharing. """ return self._store @property def rank(self): """Return rank of current process. Returns ------- int The rank of current process. """ return self._rank @property def world_size(self): """Return world size of the pytorch distributed training env. Returns ------- int The world size of the pytorch distributed training env. """ return self._world_size @property def name(self): """Return the name of NodeEmbedding. Returns ------- str The name of NodeEmbedding. """ return self._name @property def num_embeddings(self): """Return the number of embeddings. Returns ------- int The number of embeddings. """ return self._num_embeddings def set_optm_state(self, state): """Store the optimizer related state tensor. Parameters ---------- state : tuple of torch.Tensor Optimizer related state. """ self._optm_state = state @property def optm_state(self): """Return the optimizer related state tensor. Returns ------- tuple of torch.Tensor The optimizer related state. """ return self._optm_state @property def trace(self): """Return a trace of the indices of embeddings used in the training step(s). Returns ------- [torch.Tensor] The indices of embeddings used in the training step(s). """ return self._trace def reset_trace(self): """Clean up the trace of the indices of embeddings used in the training step(s). """ self._trace = [] @property def emb_tensor(self): """Return the tensor storing the node embeddings Returns ------- torch.Tensor The tensor storing the node embeddings """ return self._tensor
[((63, 11, 63, 42), 'torch.distributed.is_initialized', 'th.distributed.is_initialized', ({}, {}), '()', True, 'import torch as th\n'), ((104, 40, 104, 56), 'torch.device', 'th.device', ({(104, 50, 104, 55): '"""cpu"""'}, {}), "('cpu')", True, 'import torch as th\n'), ((64, 19, 64, 44), 'torch.distributed.get_rank', 'th.distributed.get_rank', ({}, {}), '()', True, 'import torch as th\n'), ((65, 25, 65, 56), 'torch.distributed.get_world_size', 'th.distributed.get_world_size', ({}, {}), '()', True, 'import torch as th\n'), ((84, 59, 84, 80), 'datetime.timedelta', 'timedelta', (), '', False, 'from datetime import timedelta\n'), ((92, 56, 92, 77), 'datetime.timedelta', 'timedelta', (), '', False, 'from datetime import timedelta\n')]
seukjung/sentry-custom
tests/sentry/web/frontend/test_create_team.py
c5f6bb2019aef3caff7f3e2b619f7a70f2b9b963
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.models import OrganizationMember, OrganizationMemberTeam, Team from sentry.testutils import TestCase, PermissionTestCase class CreateTeamPermissionTest(PermissionTestCase): def setUp(self): super(CreateTeamPermissionTest, self).setUp() self.path = reverse('sentry-create-team', args=[self.organization.slug]) def test_teamless_admin_can_load(self): self.assert_teamless_admin_can_access(self.path) def test_team_admin_can_load(self): self.assert_team_admin_can_access(self.path) def test_member_cannot_load(self): self.assert_member_cannot_access(self.path) def test_owner_can_load(self): self.assert_owner_can_access(self.path) class CreateTeamTest(TestCase): def test_renders_with_context(self): organization = self.create_organization() path = reverse('sentry-create-team', args=[organization.slug]) self.login_as(self.user) resp = self.client.get(path) assert resp.status_code == 200 self.assertTemplateUsed(resp, 'sentry/create-team.html') assert resp.context['organization'] == organization assert resp.context['form'] def test_submission(self): organization = self.create_organization() path = reverse('sentry-create-team', args=[organization.slug]) self.login_as(self.user) resp = self.client.post(path, { 'name': 'bar', }) assert resp.status_code == 302, resp.context['form'].errors team = Team.objects.get(organization=organization, name='bar') member = OrganizationMember.objects.get( user=self.user, organization=organization, ) assert OrganizationMemberTeam.objects.filter( organizationmember=member, team=team, is_active=True, ).exists() redirect_uri = reverse('sentry-create-project', args=[organization.slug]) assert resp['Location'] == 'http://testserver%s?team=%s' % ( redirect_uri, team.slug) def test_admin_can_create_team(self): organization = self.create_organization() path = reverse('sentry-create-team', args=[organization.slug]) admin = self.create_user('[email protected]') self.create_member( organization=organization, user=admin, role='admin', teams=[], ) self.login_as(admin) resp = self.client.post(path, { 'name': 'bar', }) assert resp.status_code == 302, resp.context['form'].errors assert Team.objects.filter( organization=organization, name='bar', ).exists()
[((12, 20, 12, 80), 'django.core.urlresolvers.reverse', 'reverse', (), '', False, 'from django.core.urlresolvers import reverse\n'), ((30, 15, 30, 70), 'django.core.urlresolvers.reverse', 'reverse', (), '', False, 'from django.core.urlresolvers import reverse\n'), ((40, 15, 40, 70), 'django.core.urlresolvers.reverse', 'reverse', (), '', False, 'from django.core.urlresolvers import reverse\n'), ((47, 15, 47, 70), 'sentry.models.Team.objects.get', 'Team.objects.get', (), '', False, 'from sentry.models import OrganizationMember, OrganizationMemberTeam, Team\n'), ((49, 17, 52, 9), 'sentry.models.OrganizationMember.objects.get', 'OrganizationMember.objects.get', (), '', False, 'from sentry.models import OrganizationMember, OrganizationMemberTeam, Team\n'), ((60, 23, 60, 81), 'django.core.urlresolvers.reverse', 'reverse', (), '', False, 'from django.core.urlresolvers import reverse\n'), ((66, 15, 66, 70), 'django.core.urlresolvers.reverse', 'reverse', (), '', False, 'from django.core.urlresolvers import reverse\n'), ((54, 15, 58, 9), 'sentry.models.OrganizationMemberTeam.objects.filter', 'OrganizationMemberTeam.objects.filter', (), '', False, 'from sentry.models import OrganizationMember, OrganizationMemberTeam, Team\n'), ((83, 15, 86, 9), 'sentry.models.Team.objects.filter', 'Team.objects.filter', (), '', False, 'from sentry.models import OrganizationMember, OrganizationMemberTeam, Team\n')]
eym55/mango-client-python
baseCli.py
2cb1ce77d785343c24ecba913eaa9693c3db1181
import abc import datetime import enum import logging import time import typing import aysncio import Layout as layouts from decimal import Decimal from pyserum.market import Market from pyserum.open_orders_account import OpenOrdersAccount from solana.account import Account from solana.publickey import PublicKey from solana.rpc.commitment import Single from solana.rpc.types import MemcmpOpts, TokenAccountOpts, RPCMethod, RPCResponse from spl.token.client import Token as SplToken from spl.token.constants import TOKEN_PROGRAM_ID from Constants import NUM_MARKETS, NUM_TOKENS, SOL_DECIMALS, SYSTEM_PROGRAM_ADDRESS, MAX_RATE,OPTIMAL_RATE,OPTIMAL_UTIL from Context import Context from Decoder import decode_binary, encode_binary, encode_key class Version(enum.Enum): UNSPECIFIED = 0 V1 = 1 V2 = 2 V3 = 3 V4 = 4 V5 = 5 class InstructionType(enum.IntEnum): InitMangoGroup = 0 InitMarginAccount = 1 Deposit = 2 Withdraw = 3 Borrow = 4 SettleBorrow = 5 Liquidate = 6 DepositSrm = 7 WithdrawSrm = 8 PlaceOrder = 9 SettleFunds = 10 CancelOrder = 11 CancelOrderByClientId = 12 ChangeBorrowLimit = 13 PlaceAndSettle = 14 ForceCancelOrders = 15 PartialLiquidate = 16 def __str__(self): return self.name class AccountInfo: def __init__(self, address: PublicKey, executable: bool, lamports: Decimal, owner: PublicKey, rent_epoch: Decimal, data: bytes): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.address: PublicKey = address self.executable: bool = executable self.lamports: Decimal = lamports self.owner: PublicKey = owner self.rent_epoch: Decimal = rent_epoch self.data: bytes = data def encoded_data(self) -> typing.List: return encode_binary(self.data) def __str__(self) -> str: return f"""« AccountInfo [{self.address}]: Owner: {self.owner} Executable: {self.executable} Lamports: {self.lamports} Rent Epoch: {self.rent_epoch} »""" def __repr__(self) -> str: return f"{self}" @staticmethod async def load(context: Context, address: PublicKey) -> typing.Optional["AccountInfo"]: response: RPCResponse = context.client.get_account_info(address) result = context.unwrap_or_raise_exception(response) if result["value"] is None: return None return AccountInfo._from_response_values(result["value"], address) @staticmethod async def load_multiple(context: Context, addresses: typing.List[PublicKey]) -> typing.List["AccountInfo"]: address_strings = list(map(PublicKey.__str__, addresses)) response = await context.client._provider.make_request(RPCMethod("getMultipleAccounts"), address_strings) response_value_list = zip(response["result"]["value"], addresses) return list(map(lambda pair: AccountInfo._from_response_values(pair[0], pair[1]), response_value_list)) @staticmethod def _from_response_values(response_values: typing.Dict[str, typing.Any], address: PublicKey) -> "AccountInfo": executable = bool(response_values["executable"]) lamports = Decimal(response_values["lamports"]) owner = PublicKey(response_values["owner"]) rent_epoch = Decimal(response_values["rentEpoch"]) data = decode_binary(response_values["data"]) return AccountInfo(address, executable, lamports, owner, rent_epoch, data) @staticmethod def from_response(response: RPCResponse, address: PublicKey) -> "AccountInfo": return AccountInfo._from_response_values(response["result"]["value"], address) class AddressableAccount(metaclass=abc.ABCMeta): def __init__(self, account_info: AccountInfo): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.account_info = account_info @property def address(self) -> PublicKey: return self.account_info.address def __repr__(self) -> str: return f"{self}" class SerumAccountFlags: def __init__(self, version: Version, initialized: bool, market: bool, open_orders: bool, request_queue: bool, event_queue: bool, bids: bool, asks: bool, disabled: bool): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.version: Version = version self.initialized = initialized self.market = market self.open_orders = open_orders self.request_queue = request_queue self.event_queue = event_queue self.bids = bids self.asks = asks self.disabled = disabled @staticmethod def from_layout(layout: layouts.SERUM_ACCOUNT_FLAGS) -> "SerumAccountFlags": return SerumAccountFlags(Version.UNSPECIFIED, layout.initialized, layout.market, layout.open_orders, layout.request_queue, layout.event_queue, layout.bids, layout.asks, layout.disabled) def __str__(self) -> str: flags: typing.List[typing.Optional[str]] = [] flags += ["initialized" if self.initialized else None] flags += ["market" if self.market else None] flags += ["open_orders" if self.open_orders else None] flags += ["request_queue" if self.request_queue else None] flags += ["event_queue" if self.event_queue else None] flags += ["bids" if self.bids else None] flags += ["asks" if self.asks else None] flags += ["disabled" if self.disabled else None] flag_text = " | ".join(flag for flag in flags if flag is not None) or "None" return f"« SerumAccountFlags: {flag_text} »" def __repr__(self) -> str: return f"{self}" class MangoAccountFlags: def __init__(self, version: Version, initialized: bool, group: bool, margin_account: bool, srm_account: bool): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.version: Version = version self.initialized = initialized self.group = group self.margin_account = margin_account self.srm_account = srm_account @staticmethod def from_layout(layout: layouts.MANGO_ACCOUNT_FLAGS) -> "MangoAccountFlags": return MangoAccountFlags(Version.UNSPECIFIED, layout.initialized, layout.group, layout.margin_account, layout.srm_account) def __str__(self) -> str: flags: typing.List[typing.Optional[str]] = [] flags += ["initialized" if self.initialized else None] flags += ["group" if self.group else None] flags += ["margin_account" if self.margin_account else None] flags += ["srm_account" if self.srm_account else None] flag_text = " | ".join(flag for flag in flags if flag is not None) or "None" return f"« MangoAccountFlags: {flag_text} »" def __repr__(self) -> str: return f"{self}" class Index: def __init__(self, version: Version, last_update: datetime.datetime, borrow: Decimal, deposit: Decimal): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.version: Version = version self.last_update: datetime.datetime = last_update self.borrow: Decimal = borrow self.deposit: Decimal = deposit @staticmethod def from_layout(layout: layouts.INDEX, decimals: Decimal) -> "Index": borrow = layout.borrow / Decimal(10 ** decimals) deposit = layout.deposit / Decimal(10 ** decimals) return Index(Version.UNSPECIFIED, layout.last_update, borrow, deposit) def __str__(self) -> str: return f"« Index: Borrow: {self.borrow:,.8f}, Deposit: {self.deposit:,.8f} [last update: {self.last_update}] »" def __repr__(self) -> str: return f"{self}" class AggregatorConfig: def __init__(self, version: Version, description: str, decimals: Decimal, restart_delay: Decimal, max_submissions: Decimal, min_submissions: Decimal, reward_amount: Decimal, reward_token_account: PublicKey): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.version: Version = version self.description: str = description self.decimals: Decimal = decimals self.restart_delay: Decimal = restart_delay self.max_submissions: Decimal = max_submissions self.min_submissions: Decimal = min_submissions self.reward_amount: Decimal = reward_amount self.reward_token_account: PublicKey = reward_token_account @staticmethod def from_layout(layout: layouts.AGGREGATOR_CONFIG) -> "AggregatorConfig": return AggregatorConfig(Version.UNSPECIFIED, layout.description, layout.decimals, layout.restart_delay, layout.max_submissions, layout.min_submissions, layout.reward_amount, layout.reward_token_account) def __str__(self) -> str: return f"« AggregatorConfig: '{self.description}', Decimals: {self.decimals} [restart delay: {self.restart_delay}], Max: {self.max_submissions}, Min: {self.min_submissions}, Reward: {self.reward_amount}, Reward Account: {self.reward_token_account} »" def __repr__(self) -> str: return f"{self}" class Round: def __init__(self, version: Version, id: Decimal, created_at: datetime.datetime, updated_at: datetime.datetime): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.version: Version = version self.id: Decimal = id self.created_at: datetime.datetime = created_at self.updated_at: datetime.datetime = updated_at @staticmethod def from_layout(layout: layouts.ROUND) -> "Round": return Round(Version.UNSPECIFIED, layout.id, layout.created_at, layout.updated_at) def __str__(self) -> str: return f"« Round[{self.id}], Created: {self.updated_at}, Updated: {self.updated_at} »" def __repr__(self) -> str: return f"{self}" class Answer: def __init__(self, version: Version, round_id: Decimal, median: Decimal, created_at: datetime.datetime, updated_at: datetime.datetime): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.version: Version = version self.round_id: Decimal = round_id self.median: Decimal = median self.created_at: datetime.datetime = created_at self.updated_at: datetime.datetime = updated_at @staticmethod def from_layout(layout: layouts.ANSWER) -> "Answer": return Answer(Version.UNSPECIFIED, layout.round_id, layout.median, layout.created_at, layout.updated_at) def __str__(self) -> str: return f"« Answer: Round[{self.round_id}], Median: {self.median:,.8f}, Created: {self.updated_at}, Updated: {self.updated_at} »" def __repr__(self) -> str: return f"{self}" class Aggregator(AddressableAccount): def __init__(self, account_info: AccountInfo, version: Version, config: AggregatorConfig, initialized: bool, name: str, owner: PublicKey, round_: Round, round_submissions: PublicKey, answer: Answer, answer_submissions: PublicKey): super().__init__(account_info) self.version: Version = version self.config: AggregatorConfig = config self.initialized: bool = initialized self.name: str = name self.owner: PublicKey = owner self.round: Round = round_ self.round_submissions: PublicKey = round_submissions self.answer: Answer = answer self.answer_submissions: PublicKey = answer_submissions @property def price(self) -> Decimal: return self.answer.median / (10 ** self.config.decimals) @staticmethod def from_layout(layout: layouts.AGGREGATOR, account_info: AccountInfo, name: str) -> "Aggregator": config = AggregatorConfig.from_layout(layout.config) initialized = bool(layout.initialized) round_ = Round.from_layout(layout.round) answer = Answer.from_layout(layout.answer) return Aggregator(account_info, Version.UNSPECIFIED, config, initialized, name, layout.owner, round_, layout.round_submissions, answer, layout.answer_submissions) @staticmethod def parse(context: Context, account_info: AccountInfo) -> "Aggregator": data = account_info.data if len(data) != layouts.AGGREGATOR.sizeof(): raise Exception(f"Data length ({len(data)}) does not match expected size ({layouts.AGGREGATOR.sizeof()})") name = context.lookup_oracle_name(account_info.address) layout = layouts.AGGREGATOR.parse(data) return Aggregator.from_layout(layout, account_info, name) @staticmethod def load(context: Context, account_address: PublicKey): account_info = AccountInfo.load(context, account_address) if account_info is None: raise Exception(f"Aggregator account not found at address '{account_address}'") return Aggregator.parse(context, account_info) def __str__(self) -> str: return f""" « Aggregator '{self.name}' [{self.version}]: Config: {self.config} Initialized: {self.initialized} Owner: {self.owner} Round: {self.round} Round Submissions: {self.round_submissions} Answer: {self.answer} Answer Submissions: {self.answer_submissions} » """ class Token: def __init__(self, name: str, mint: PublicKey, decimals: Decimal): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.name: str = name.upper() self.mint: PublicKey = mint self.decimals: Decimal = decimals def round(self, value: Decimal) -> Decimal: rounded = round(value, int(self.decimals)) return Decimal(rounded) def name_matches(self, name: str) -> bool: return self.name.upper() == name.upper() @staticmethod def find_by_name(values: typing.List["Token"], name: str) -> "Token": found = [value for value in values if value.name_matches(name)] if len(found) == 0: raise Exception(f"Token '{name}' not found in token values: {values}") if len(found) > 1: raise Exception(f"Token '{name}' matched multiple tokens in values: {values}") return found[0] @staticmethod def find_by_mint(values: typing.List["Token"], mint: PublicKey) -> "Token": found = [value for value in values if value.mint == mint] if len(found) == 0: raise Exception(f"Token '{mint}' not found in token values: {values}") if len(found) > 1: raise Exception(f"Token '{mint}' matched multiple tokens in values: {values}") return found[0] # TokenMetadatas are equal if they have the same mint address. def __eq__(self, other): if hasattr(other, 'mint'): return self.mint == other.mint return False def __str__(self) -> str: return f"« Token '{self.name}' [{self.mint} ({self.decimals} decimals)] »" def __repr__(self) -> str: return f"{self}" SolToken = Token("SOL", SYSTEM_PROGRAM_ADDRESS, SOL_DECIMALS) class TokenLookup: @staticmethod def find_by_name(context: Context, name: str) -> Token: if SolToken.name_matches(name): return SolToken mint = context.lookup_token_address(name) if mint is None: raise Exception(f"Could not find token with name '{name}'.") return Token(name, mint, Decimal(6)) @staticmethod def find_by_mint(context: Context, mint: PublicKey) -> Token: if SolToken.mint == mint: return SolToken name = context.lookup_token_name(mint) if name is None: raise Exception(f"Could not find token with mint '{mint}'.") return Token(name, mint, Decimal(6)) class BasketToken: def __init__(self, token: Token, vault: PublicKey, index: Index): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.token: Token = token self.vault: PublicKey = vault self.index: Index = index @staticmethod def find_by_name(values: typing.List["BasketToken"], name: str) -> "BasketToken": found = [value for value in values if value.token.name_matches(name)] if len(found) == 0: raise Exception(f"Token '{name}' not found in token values: {values}") if len(found) > 1: raise Exception(f"Token '{name}' matched multiple tokens in values: {values}") return found[0] @staticmethod def find_by_mint(values: typing.List["BasketToken"], mint: PublicKey) -> "BasketToken": found = [value for value in values if value.token.mint == mint] if len(found) == 0: raise Exception(f"Token '{mint}' not found in token values: {values}") if len(found) > 1: raise Exception(f"Token '{mint}' matched multiple tokens in values: {values}") return found[0] @staticmethod def find_by_token(values: typing.List["BasketToken"], token: Token) -> "BasketToken": return BasketToken.find_by_mint(values, token.mint) # BasketTokens are equal if they have the same underlying token. def __eq__(self, other): if hasattr(other, 'token'): return self.token == other.token return False def __str__(self) -> str: return f"""« BasketToken [{self.token}]: Vault: {self.vault} Index: {self.index} »""" def __repr__(self) -> str: return f"{self}" class TokenValue: def __init__(self, token: Token, value: Decimal): self.token = token self.value = value @staticmethod async def fetch_total_value_or_none(context: Context, account_public_key: PublicKey, token: Token) -> typing.Optional["TokenValue"]: opts = TokenAccountOpts(mint=token.mint) token_accounts_response = await context.client.get_token_accounts_by_owner(account_public_key, opts, commitment=context.commitment) token_accounts = token_accounts_response["result"]["value"] if len(token_accounts) == 0: return None total_value = Decimal(0) for token_account in token_accounts: result = await context.client.get_token_account_balance(token_account["pubkey"], commitment=context.commitment) value = Decimal(result["result"]["value"]["amount"]) decimal_places = result["result"]["value"]["decimals"] divisor = Decimal(10 ** decimal_places) total_value += value / divisor return TokenValue(token, total_value) @staticmethod def fetch_total_value(context: Context, account_public_key: PublicKey, token: Token) -> "TokenValue": value = TokenValue.fetch_total_value_or_none(context, account_public_key, token) if value is None: return TokenValue(token, Decimal(0)) return value @staticmethod def report(reporter: typing.Callable[[str], None], values: typing.List["TokenValue"]) -> None: for value in values: reporter(f"{value.value:>18,.8f} {value.token.name}") @staticmethod def find_by_name(values: typing.List["TokenValue"], name: str) -> "TokenValue": found = [value for value in values if value.token.name_matches(name)] if len(found) == 0: raise Exception(f"Token '{name}' not found in token values: {values}") if len(found) > 1: raise Exception(f"Token '{name}' matched multiple tokens in values: {values}") return found[0] @staticmethod def find_by_mint(values: typing.List["TokenValue"], mint: PublicKey) -> "TokenValue": found = [value for value in values if value.token.mint == mint] if len(found) == 0: raise Exception(f"Token '{mint}' not found in token values: {values}") if len(found) > 1: raise Exception(f"Token '{mint}' matched multiple tokens in values: {values}") return found[0] @staticmethod def find_by_token(values: typing.List["TokenValue"], token: Token) -> "TokenValue": return TokenValue.find_by_mint(values, token.mint) @staticmethod def changes(before: typing.List["TokenValue"], after: typing.List["TokenValue"]) -> typing.List["TokenValue"]: changes: typing.List[TokenValue] = [] for before_balance in before: after_balance = TokenValue.find_by_token(after, before_balance.token) result = TokenValue(before_balance.token, after_balance.value - before_balance.value) changes += [result] return changes def __str__(self) -> str: return f"« TokenValue: {self.value:>18,.8f} {self.token.name} »" def __repr__(self) -> str: return f"{self}" class OwnedTokenValue: def __init__(self, owner: PublicKey, token_value: TokenValue): self.owner = owner self.token_value = token_value @staticmethod def find_by_owner(values: typing.List["OwnedTokenValue"], owner: PublicKey) -> "OwnedTokenValue": found = [value for value in values if value.owner == owner] if len(found) == 0: raise Exception(f"Owner '{owner}' not found in: {values}") if len(found) > 1: raise Exception(f"Owner '{owner}' matched multiple tokens in: {values}") return found[0] @staticmethod def changes(before: typing.List["OwnedTokenValue"], after: typing.List["OwnedTokenValue"]) -> typing.List["OwnedTokenValue"]: changes: typing.List[OwnedTokenValue] = [] for before_value in before: after_value = OwnedTokenValue.find_by_owner(after, before_value.owner) token_value = TokenValue(before_value.token_value.token, after_value.token_value.value - before_value.token_value.value) result = OwnedTokenValue(before_value.owner, token_value) changes += [result] return changes def __str__(self) -> str: return f"[{self.owner}]: {self.token_value}" def __repr__(self) -> str: return f"{self}" class MarketMetadata: def __init__(self, name: str, address: PublicKey, base: BasketToken, quote: BasketToken, spot: PublicKey, oracle: PublicKey, decimals: Decimal): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.name: str = name self.address: PublicKey = address self.base: BasketToken = base self.quote: BasketToken = quote self.spot: PublicKey = spot self.oracle: PublicKey = oracle self.decimals: Decimal = decimals self._market = None async def fetch_market(self, context: Context) -> Market: if self._market is None: self._market = await Market.load(context.client, self.spot) return self._market def __str__(self) -> str: return f"""« Market '{self.name}' [{self.spot}]: Base: {self.base} Quote: {self.quote} Oracle: {self.oracle} ({self.decimals} decimals) »""" def __repr__(self) -> str: return f"{self}" class Group(AddressableAccount): def __init__(self, account_info: AccountInfo, version: Version, context: Context, account_flags: MangoAccountFlags, basket_tokens: typing.List[BasketToken], markets: typing.List[MarketMetadata], signer_nonce: Decimal, signer_key: PublicKey, dex_program_id: PublicKey, total_deposits: typing.List[Decimal], total_borrows: typing.List[Decimal], maint_coll_ratio: Decimal, init_coll_ratio: Decimal, srm_vault: PublicKey, admin: PublicKey, borrow_limits: typing.List[Decimal]): super().__init__(account_info) self.version: Version = version self.context: Context = context self.account_flags: MangoAccountFlags = account_flags self.basket_tokens: typing.List[BasketToken] = basket_tokens self.markets: typing.List[MarketMetadata] = markets self.signer_nonce: Decimal = signer_nonce self.signer_key: PublicKey = signer_key self.dex_program_id: PublicKey = dex_program_id self.total_deposits: typing.List[Decimal] = total_deposits self.total_borrows: typing.List[Decimal] = total_borrows self.maint_coll_ratio: Decimal = maint_coll_ratio self.init_coll_ratio: Decimal = init_coll_ratio self.srm_vault: PublicKey = srm_vault self.admin: PublicKey = admin self.borrow_limits: typing.List[Decimal] = borrow_limits self.mint_decimals: typing.List[int] = [token.mint for token in basket_tokens] @property def shared_quote_token(self) -> BasketToken: return self.basket_tokens[-1] @staticmethod def from_layout(layout: layouts.GROUP, context: Context, account_info: AccountInfo) -> "Group": account_flags = MangoAccountFlags.from_layout(layout.account_flags) indexes = list(map(lambda pair: Index.from_layout(pair[0], pair[1]), zip(layout.indexes, layout.mint_decimals))) basket_tokens: typing.List[BasketToken] = [] for index in range(NUM_TOKENS): token_address = layout.tokens[index] token_name = context.lookup_token_name(token_address) if token_name is None: raise Exception(f"Could not find token with mint '{token_address}' in Group.") token = Token(token_name, token_address, layout.mint_decimals[index]) basket_token = BasketToken(token, layout.vaults[index], indexes[index]) basket_tokens += [basket_token] markets: typing.List[MarketMetadata] = [] for index in range(NUM_MARKETS): market_address = layout.spot_markets[index] market_name = context.lookup_market_name(market_address) base_name, quote_name = market_name.split("/") base_token = BasketToken.find_by_name(basket_tokens, base_name) quote_token = BasketToken.find_by_name(basket_tokens, quote_name) market = MarketMetadata(market_name, market_address, base_token, quote_token, layout.spot_markets[index], layout.oracles[index], layout.oracle_decimals[index]) markets += [market] maint_coll_ratio = layout.maint_coll_ratio.quantize(Decimal('.01')) init_coll_ratio = layout.init_coll_ratio.quantize(Decimal('.01')) return Group(account_info, Version.UNSPECIFIED, context, account_flags, basket_tokens, markets, layout.signer_nonce, layout.signer_key, layout.dex_program_id, layout.total_deposits, layout.total_borrows, maint_coll_ratio, init_coll_ratio, layout.srm_vault, layout.admin, layout.borrow_limits) @staticmethod def parse(context: Context, account_info: AccountInfo) -> "Group": data = account_info.data if len(data) != layouts.GROUP.sizeof(): raise Exception(f"Data length ({len(data)}) does not match expected size ({layouts.GROUP.sizeof()})") layout = layouts.GROUP.parse(data) return Group.from_layout(layout, context, account_info) @staticmethod def load(context: Context): account_info = AccountInfo.load(context, context.group_id) if account_info is None: raise Exception(f"Group account not found at address '{context.group_id}'") return Group.parse(context, account_info) #TODO Test this method, implement get_ui_total_borrow,get_ui_total_deposit def get_deposit_rate(self,token_index: int): borrow_rate = self.get_borrow_rate(token_index) total_borrows = self.get_ui_total_borrow(token_index) total_deposits = self.get_ui_total_deposit(token_index) if total_deposits == 0 and total_borrows == 0: return 0 elif total_deposits == 0: return MAX_RATE utilization = total_borrows / total_deposits return utilization * borrow_rate #TODO Test this method, implement get_ui_total_borrow, get_ui_total_deposit def get_borrow_rate(self,token_index: int): total_borrows = self.get_ui_total_borrow(token_index) total_deposits = self.get_ui_total_deposit(token_index) if total_deposits == 0 and total_borrows == 0: return 0 if total_deposits <= total_borrows : return MAX_RATE utilization = total_borrows / total_deposits if utilization > OPTIMAL_UTIL: extra_util = utilization - OPTIMAL_UTIL slope = (MAX_RATE - OPTIMAL_RATE) / (1 - OPTIMAL_UTIL) return OPTIMAL_RATE + slope * extra_util else: slope = OPTIMAL_RATE / OPTIMAL_UTIL return slope * utilization def get_token_index(self, token: Token) -> int: for index, existing in enumerate(self.basket_tokens): if existing.token == token: return index return -1 def get_prices(self) -> typing.List[TokenValue]: started_at = time.time() # Note: we can just load the oracle data in a simpler way, with: # oracles = map(lambda market: Aggregator.load(self.context, market.oracle), self.markets) # but that makes a network request for every oracle. We can reduce that to just one request # if we use AccountInfo.load_multiple() and parse the data ourselves. # # This seems to halve the time this function takes. oracle_addresses = list([market.oracle for market in self.markets]) oracle_account_infos = AccountInfo.load_multiple(self.context, oracle_addresses) oracles = map(lambda oracle_account_info: Aggregator.parse(self.context, oracle_account_info), oracle_account_infos) prices = list(map(lambda oracle: oracle.price, oracles)) + [Decimal(1)] token_prices = [] for index, price in enumerate(prices): token_prices += [TokenValue(self.basket_tokens[index].token, price)] time_taken = time.time() - started_at self.logger.info(f"Faster fetching prices complete. Time taken: {time_taken:.2f} seconds.") return token_prices def fetch_balances(self, root_address: PublicKey) -> typing.List[TokenValue]: balances: typing.List[TokenValue] = [] sol_balance = self.context.fetch_sol_balance(root_address) balances += [TokenValue(SolToken, sol_balance)] for basket_token in self.basket_tokens: balance = TokenValue.fetch_total_value(self.context, root_address, basket_token.token) balances += [balance] return balances def native_to_ui(self, amount, decimals) -> int: return amount / (10 ** decimals) def ui_to_native(self, amount, decimals) -> int: return amount * (10 ** decimals) def getUiTotalDeposit(self, tokenIndex: int) -> int: return Group.ui_to_native(self.totalDeposits[tokenIndex] * self.indexes[tokenIndex].deposit, self.mint_decimals[tokenIndex]) def getUiTotalBorrow(self, tokenIndex: int) -> int: return Group.native_to_ui(self.totalBorrows[tokenIndex] * self.indexes[tokenIndex].borrow, self.mint_decimals[tokenIndex]) def __str__(self) -> str: total_deposits = "\n ".join(map(str, self.total_deposits)) total_borrows = "\n ".join(map(str, self.total_borrows)) borrow_limits = "\n ".join(map(str, self.borrow_limits)) return f""" « Group [{self.version}] {self.address}: Flags: {self.account_flags} Tokens: {self.basket_tokens} Markets: {self.markets} DEX Program ID: « {self.dex_program_id} » SRM Vault: « {self.srm_vault} » Admin: « {self.admin} » Signer Nonce: {self.signer_nonce} Signer Key: « {self.signer_key} » Initial Collateral Ratio: {self.init_coll_ratio} Maintenance Collateral Ratio: {self.maint_coll_ratio} Total Deposits: {total_deposits} Total Borrows: {total_borrows} Borrow Limits: {borrow_limits} » """ class TokenAccount(AddressableAccount): def __init__(self, account_info: AccountInfo, version: Version, mint: PublicKey, owner: PublicKey, amount: Decimal): super().__init__(account_info) self.version: Version = version self.mint: PublicKey = mint self.owner: PublicKey = owner self.amount: Decimal = amount @staticmethod def create(context: Context, account: Account, token: Token): spl_token = await SplToken(context.client, token.mint, TOKEN_PROGRAM_ID, account) owner = account.public_key() new_account_address = spl_token.create_account(owner) return TokenAccount.load(context, new_account_address) @staticmethod def fetch_all_for_owner_and_token(context: Context, owner_public_key: PublicKey, token: Token) -> typing.List["TokenAccount"]: opts = TokenAccountOpts(mint=token.mint) token_accounts_response = await context.client.get_token_accounts_by_owner(owner_public_key, opts, commitment=context.commitment) all_accounts: typing.List[TokenAccount] = [] for token_account_response in token_accounts_response["result"]["value"]: account_info = AccountInfo._from_response_values(token_account_response["account"], PublicKey(token_account_response["pubkey"])) token_account = TokenAccount.parse(account_info) all_accounts += [token_account] return all_accounts @staticmethod def fetch_largest_for_owner_and_token(context: Context, owner_public_key: PublicKey, token: Token) -> typing.Optional["TokenAccount"]: all_accounts = TokenAccount.fetch_all_for_owner_and_token(context, owner_public_key, token) largest_account: typing.Optional[TokenAccount] = None for token_account in all_accounts: if largest_account is None or token_account.amount > largest_account.amount: largest_account = token_account return largest_account @staticmethod def fetch_or_create_largest_for_owner_and_token(context: Context, account: Account, token: Token) -> "TokenAccount": all_accounts = TokenAccount.fetch_all_for_owner_and_token(context, account.public_key(), token) largest_account: typing.Optional[TokenAccount] = None for token_account in all_accounts: if largest_account is None or token_account.amount > largest_account.amount: largest_account = token_account if largest_account is None: return TokenAccount.create(context, account, token) return largest_account @staticmethod def from_layout(layout: layouts.TOKEN_ACCOUNT, account_info: AccountInfo) -> "TokenAccount": return TokenAccount(account_info, Version.UNSPECIFIED, layout.mint, layout.owner, layout.amount) @staticmethod def parse(account_info: AccountInfo) -> "TokenAccount": data = account_info.data if len(data) != layouts.TOKEN_ACCOUNT.sizeof(): raise Exception(f"Data length ({len(data)}) does not match expected size ({layouts.TOKEN_ACCOUNT.sizeof()})") layout = layouts.TOKEN_ACCOUNT.parse(data) return TokenAccount.from_layout(layout, account_info) @staticmethod def load(context: Context, address: PublicKey) -> typing.Optional["TokenAccount"]: account_info = AccountInfo.load(context, address) if account_info is None or (len(account_info.data) != layouts.TOKEN_ACCOUNT.sizeof()): return None return TokenAccount.parse(account_info) def __str__(self) -> str: return f"« Token: Mint: {self.mint}, Owner: {self.owner}, Amount: {self.amount} »" class OpenOrders(AddressableAccount): def __init__(self, account_info: AccountInfo, version: Version, program_id: PublicKey, account_flags: SerumAccountFlags, market: PublicKey, owner: PublicKey, base_token_free: Decimal, base_token_total: Decimal, quote_token_free: Decimal, quote_token_total: Decimal, free_slot_bits: Decimal, is_bid_bits: Decimal, orders: typing.List[Decimal], client_ids: typing.List[Decimal], referrer_rebate_accrued: Decimal): super().__init__(account_info) self.version: Version = version self.program_id: PublicKey = program_id self.account_flags: SerumAccountFlags = account_flags self.market: PublicKey = market self.owner: PublicKey = owner self.base_token_free: Decimal = base_token_free self.base_token_total: Decimal = base_token_total self.quote_token_free: Decimal = quote_token_free self.quote_token_total: Decimal = quote_token_total self.free_slot_bits: Decimal = free_slot_bits self.is_bid_bits: Decimal = is_bid_bits self.orders: typing.List[Decimal] = orders self.client_ids: typing.List[Decimal] = client_ids self.referrer_rebate_accrued: Decimal = referrer_rebate_accrued # Sometimes pyserum wants to take its own OpenOrdersAccount as a parameter (e.g. in settle_funds()) def to_pyserum(self) -> OpenOrdersAccount: return OpenOrdersAccount.from_bytes(self.address, self.account_info.data) @staticmethod def from_layout(layout: layouts.OPEN_ORDERS, account_info: AccountInfo, base_decimals: Decimal, quote_decimals: Decimal) -> "OpenOrders": account_flags = SerumAccountFlags.from_layout(layout.account_flags) program_id = account_info.owner base_divisor = 10 ** base_decimals quote_divisor = 10 ** quote_decimals base_token_free: Decimal = layout.base_token_free / base_divisor base_token_total: Decimal = layout.base_token_total / base_divisor quote_token_free: Decimal = layout.quote_token_free / quote_divisor quote_token_total: Decimal = layout.quote_token_total / quote_divisor nonzero_orders: typing.List[Decimal] = list([order for order in layout.orders if order != 0]) nonzero_client_ids: typing.List[Decimal] = list([client_id for client_id in layout.client_ids if client_id != 0]) return OpenOrders(account_info, Version.UNSPECIFIED, program_id, account_flags, layout.market, layout.owner, base_token_free, base_token_total, quote_token_free, quote_token_total, layout.free_slot_bits, layout.is_bid_bits, nonzero_orders, nonzero_client_ids, layout.referrer_rebate_accrued) @staticmethod def parse(account_info: AccountInfo, base_decimals: Decimal, quote_decimals: Decimal) -> "OpenOrders": data = account_info.data if len(data) != layouts.OPEN_ORDERS.sizeof(): raise Exception(f"Data length ({len(data)}) does not match expected size ({layouts.OPEN_ORDERS.sizeof()})") layout = layouts.OPEN_ORDERS.parse(data) return OpenOrders.from_layout(layout, account_info, base_decimals, quote_decimals) @staticmethod async def load_raw_open_orders_account_infos(context: Context, group: Group) -> typing.Dict[str, AccountInfo]: filters = [ MemcmpOpts( offset=layouts.SERUM_ACCOUNT_FLAGS.sizeof() + 37, bytes=encode_key(group.signer_key) ) ] response = await context.client.get_program_accounts(group.dex_program_id, data_size=layouts.OPEN_ORDERS.sizeof(), memcmp_opts=filters, commitment=Single, encoding="base64") account_infos = list(map(lambda pair: AccountInfo._from_response_values(pair[0], pair[1]), [(result["account"], PublicKey(result["pubkey"])) for result in response["result"]])) account_infos_by_address = {key: value for key, value in [(str(account_info.address), account_info) for account_info in account_infos]} return account_infos_by_address @staticmethod def load(context: Context, address: PublicKey, base_decimals: Decimal, quote_decimals: Decimal) -> "OpenOrders": open_orders_account = AccountInfo.load(context, address) if open_orders_account is None: raise Exception(f"OpenOrders account not found at address '{address}'") return OpenOrders.parse(open_orders_account, base_decimals, quote_decimals) @staticmethod async def load_for_market_and_owner(context: Context, market: PublicKey, owner: PublicKey, program_id: PublicKey, base_decimals: Decimal, quote_decimals: Decimal): filters = [ MemcmpOpts( offset=layouts.SERUM_ACCOUNT_FLAGS.sizeof() + 5, bytes=encode_key(market) ), MemcmpOpts( offset=layouts.SERUM_ACCOUNT_FLAGS.sizeof() + 37, bytes=encode_key(owner) ) ] response = await context.client.get_program_accounts(context.dex_program_id, data_size=layouts.OPEN_ORDERS.sizeof(), memcmp_opts=filters, commitment=Single, encoding="base64") accounts = list(map(lambda pair: AccountInfo._from_response_values(pair[0], pair[1]), [(result["account"], PublicKey(result["pubkey"])) for result in response["result"]])) return list(map(lambda acc: OpenOrders.parse(acc, base_decimals, quote_decimals), accounts)) def __str__(self) -> str: orders = ", ".join(map(str, self.orders)) or "None" client_ids = ", ".join(map(str, self.client_ids)) or "None" return f"""« OpenOrders: Flags: {self.account_flags} Program ID: {self.program_id} Address: {self.address} Market: {self.market} Owner: {self.owner} Base Token: {self.base_token_free:,.8f} of {self.base_token_total:,.8f} Quote Token: {self.quote_token_free:,.8f} of {self.quote_token_total:,.8f} Referrer Rebate Accrued: {self.referrer_rebate_accrued} Orders: {orders} Client IDs: {client_ids} »""" class BalanceSheet: def __init__(self, token: Token, liabilities: Decimal, settled_assets: Decimal, unsettled_assets: Decimal): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.token: Token = token self.liabilities: Decimal = liabilities self.settled_assets: Decimal = settled_assets self.unsettled_assets: Decimal = unsettled_assets @property def assets(self) -> Decimal: return self.settled_assets + self.unsettled_assets @property def value(self) -> Decimal: return self.assets - self.liabilities @property def collateral_ratio(self) -> Decimal: if self.liabilities == Decimal(0): return Decimal(0) return self.assets / self.liabilities def __str__(self) -> str: name = "«Unspecified»" if self.token is not None: name = self.token.name return f"""« BalanceSheet [{name}]: Assets : {self.assets:>18,.8f} Settled Assets : {self.settled_assets:>18,.8f} Unsettled Assets : {self.unsettled_assets:>18,.8f} Liabilities : {self.liabilities:>18,.8f} Value : {self.value:>18,.8f} Collateral Ratio : {self.collateral_ratio:>18,.2%} » """ def __repr__(self) -> str: return f"{self}" class MarginAccount(AddressableAccount): def __init__(self, account_info: AccountInfo, version: Version, account_flags: MangoAccountFlags, mango_group: PublicKey, owner: PublicKey, deposits: typing.List[Decimal], borrows: typing.List[Decimal], open_orders: typing.List[PublicKey]): super().__init__(account_info) self.version: Version = version self.account_flags: MangoAccountFlags = account_flags self.mango_group: PublicKey = mango_group self.owner: PublicKey = owner self.deposits: typing.List[Decimal] = deposits self.borrows: typing.List[Decimal] = borrows self.open_orders: typing.List[PublicKey] = open_orders self.open_orders_accounts: typing.List[typing.Optional[OpenOrders]] = [None] * NUM_MARKETS @staticmethod def from_layout(layout: layouts.MARGIN_ACCOUNT, account_info: AccountInfo) -> "MarginAccount": account_flags: MangoAccountFlags = MangoAccountFlags.from_layout(layout.account_flags) deposits: typing.List[Decimal] = [] for index, deposit in enumerate(layout.deposits): deposits += [deposit] borrows: typing.List[Decimal] = [] for index, borrow in enumerate(layout.borrows): borrows += [borrow] return MarginAccount(account_info, Version.UNSPECIFIED, account_flags, layout.mango_group, layout.owner, deposits, borrows, list(layout.open_orders)) @staticmethod def parse(account_info: AccountInfo) -> "MarginAccount": data = account_info.data if len(data) != layouts.MARGIN_ACCOUNT.sizeof(): raise Exception(f"Data length ({len(data)}) does not match expected size ({layouts.MARGIN_ACCOUNT.sizeof()})") layout = layouts.MARGIN_ACCOUNT.parse(data) return MarginAccount.from_layout(layout, account_info) @staticmethod def load(context: Context, margin_account_address: PublicKey, group: typing.Optional[Group] = None) -> "MarginAccount": account_info = AccountInfo.load(context, margin_account_address) if account_info is None: raise Exception(f"MarginAccount account not found at address '{margin_account_address}'") margin_account = MarginAccount.parse(account_info) if group is None: group = Group.load(context) margin_account.load_open_orders_accounts(context, group) return margin_account @staticmethod def load_all_for_group(context: Context, program_id: PublicKey, group: Group) -> typing.List["MarginAccount"]: filters = [ MemcmpOpts( offset=layouts.MANGO_ACCOUNT_FLAGS.sizeof(), # mango_group is just after the MangoAccountFlags, which is the first entry bytes=encode_key(group.address) ) ] response = context.client.get_program_accounts(program_id, data_size=layouts.MARGIN_ACCOUNT.sizeof(), memcmp_opts=filters, commitment=Single, encoding="base64") margin_accounts = [] for margin_account_data in response["result"]: address = PublicKey(margin_account_data["pubkey"]) account = AccountInfo._from_response_values(margin_account_data["account"], address) margin_account = MarginAccount.parse(account) margin_accounts += [margin_account] return margin_accounts @staticmethod def load_all_for_group_with_open_orders(context: Context, program_id: PublicKey, group: Group) -> typing.List["MarginAccount"]: margin_accounts = MarginAccount.load_all_for_group(context, context.program_id, group) open_orders = OpenOrders.load_raw_open_orders_account_infos(context, group) for margin_account in margin_accounts: margin_account.install_open_orders_accounts(group, open_orders) return margin_accounts @staticmethod def load_all_for_owner(context: Context, owner: PublicKey, group: typing.Optional[Group] = None) -> typing.List["MarginAccount"]: if group is None: group = Group.load(context) mango_group_offset = layouts.MANGO_ACCOUNT_FLAGS.sizeof() # mango_group is just after the MangoAccountFlags, which is the first entry. owner_offset = mango_group_offset + 32 # owner is just after mango_group in the layout, and it's a PublicKey which is 32 bytes. filters = [ MemcmpOpts( offset=mango_group_offset, bytes=encode_key(group.address) ), MemcmpOpts( offset=owner_offset, bytes=encode_key(owner) ) ] response = context.client.get_program_accounts(context.program_id, data_size=layouts.MARGIN_ACCOUNT.sizeof(), memcmp_opts=filters, commitment=Single, encoding="base64") margin_accounts = [] for margin_account_data in response["result"]: address = PublicKey(margin_account_data["pubkey"]) account = AccountInfo._from_response_values(margin_account_data["account"], address) margin_account = MarginAccount.parse(account) margin_account.load_open_orders_accounts(context, group) margin_accounts += [margin_account] return margin_accounts @classmethod def load_all_ripe(cls, context: Context) -> typing.List["MarginAccount"]: logger: logging.Logger = logging.getLogger(cls.__name__) started_at = time.time() group = Group.load(context) margin_accounts = MarginAccount.load_all_for_group_with_open_orders(context, context.program_id, group) logger.info(f"Fetched {len(margin_accounts)} margin accounts to process.") prices = group.get_prices() nonzero: typing.List[MarginAccountMetadata] = [] for margin_account in margin_accounts: balance_sheet = margin_account.get_balance_sheet_totals(group, prices) if balance_sheet.collateral_ratio > 0: balances = margin_account.get_intrinsic_balances(group) nonzero += [MarginAccountMetadata(margin_account, balance_sheet, balances)] logger.info(f"Of those {len(margin_accounts)}, {len(nonzero)} have a nonzero collateral ratio.") ripe_metadata = filter(lambda mam: mam.balance_sheet.collateral_ratio <= group.init_coll_ratio, nonzero) ripe_accounts = list(map(lambda mam: mam.margin_account, ripe_metadata)) logger.info(f"Of those {len(nonzero)}, {len(ripe_accounts)} are ripe 🥭.") time_taken = time.time() - started_at logger.info(f"Loading ripe 🥭 accounts complete. Time taken: {time_taken:.2f} seconds.") return ripe_accounts def load_open_orders_accounts(self, context: Context, group: Group) -> None: for index, oo in enumerate(self.open_orders): key = oo if key != SYSTEM_PROGRAM_ADDRESS: self.open_orders_accounts[index] = OpenOrders.load(context, key, group.basket_tokens[index].token.decimals, group.shared_quote_token.token.decimals) def install_open_orders_accounts(self, group: Group, all_open_orders_by_address: typing.Dict[str, AccountInfo]) -> None: for index, oo in enumerate(self.open_orders): key = str(oo) if key in all_open_orders_by_address: open_orders_account_info = all_open_orders_by_address[key] open_orders = OpenOrders.parse(open_orders_account_info, group.basket_tokens[index].token.decimals, group.shared_quote_token.token.decimals) self.open_orders_accounts[index] = open_orders def get_intrinsic_balance_sheets(self, group: Group) -> typing.List[BalanceSheet]: settled_assets: typing.List[Decimal] = [Decimal(0)] * NUM_TOKENS liabilities: typing.List[Decimal] = [Decimal(0)] * NUM_TOKENS for index in range(NUM_TOKENS): settled_assets[index] = group.basket_tokens[index].index.deposit * self.deposits[index] liabilities[index] = group.basket_tokens[index].index.borrow * self.borrows[index] unsettled_assets: typing.List[Decimal] = [Decimal(0)] * NUM_TOKENS for index in range(NUM_MARKETS): open_orders_account = self.open_orders_accounts[index] if open_orders_account is not None: unsettled_assets[index] += open_orders_account.base_token_total unsettled_assets[NUM_TOKENS - 1] += open_orders_account.quote_token_total balance_sheets: typing.List[BalanceSheet] = [] for index in range(NUM_TOKENS): balance_sheets += [BalanceSheet(group.basket_tokens[index].token, liabilities[index], settled_assets[index], unsettled_assets[index])] return balance_sheets def get_priced_balance_sheets(self, group: Group, prices: typing.List[TokenValue]) -> typing.List[BalanceSheet]: priced: typing.List[BalanceSheet] = [] balance_sheets = self.get_intrinsic_balance_sheets(group) for balance_sheet in balance_sheets: price = TokenValue.find_by_token(prices, balance_sheet.token) liabilities = balance_sheet.liabilities * price.value settled_assets = balance_sheet.settled_assets * price.value unsettled_assets = balance_sheet.unsettled_assets * price.value priced += [BalanceSheet( price.token, price.token.round(liabilities), price.token.round(settled_assets), price.token.round(unsettled_assets) )] return priced def get_balance_sheet_totals(self, group: Group, prices: typing.List[TokenValue]) -> BalanceSheet: liabilities = Decimal(0) settled_assets = Decimal(0) unsettled_assets = Decimal(0) balance_sheets = self.get_priced_balance_sheets(group, prices) for balance_sheet in balance_sheets: if balance_sheet is not None: liabilities += balance_sheet.liabilities settled_assets += balance_sheet.settled_assets unsettled_assets += balance_sheet.unsettled_assets # A BalanceSheet must have a token - it's a pain to make it a typing.Optional[Token]. # So in this one case, we produce a 'fake' token whose symbol is a summary of all token # symbols that went into it. # # If this becomes more painful than typing.Optional[Token], we can go with making # Token optional. summary_name = "-".join([bal.token.name for bal in balance_sheets]) summary_token = Token(summary_name, SYSTEM_PROGRAM_ADDRESS, Decimal(0)) return BalanceSheet(summary_token, liabilities, settled_assets, unsettled_assets) def get_intrinsic_balances(self, group: Group) -> typing.List[TokenValue]: balance_sheets = self.get_intrinsic_balance_sheets(group) balances: typing.List[TokenValue] = [] for index, balance_sheet in enumerate(balance_sheets): if balance_sheet.token is None: raise Exception(f"Intrinsic balance sheet with index [{index}] has no token.") balances += [TokenValue(balance_sheet.token, balance_sheet.value)] return balances def __str__(self) -> str: deposits = ", ".join([f"{item:,.8f}" for item in self.deposits]) borrows = ", ".join([f"{item:,.8f}" for item in self.borrows]) if all(oo is None for oo in self.open_orders_accounts): open_orders = f"{self.open_orders}" else: open_orders_unindented = f"{self.open_orders_accounts}" open_orders = open_orders_unindented.replace("\n", "\n ") return f"""« MarginAccount: {self.address} Flags: {self.account_flags} Owner: {self.owner} Mango Group: {self.mango_group} Deposits: [{deposits}] Borrows: [{borrows}] Mango Open Orders: {open_orders} »""" class MarginAccountMetadata: def __init__(self, margin_account: MarginAccount, balance_sheet: BalanceSheet, balances: typing.List[TokenValue]): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.margin_account = margin_account self.balance_sheet = balance_sheet self.balances = balances @property def assets(self): return self.balance_sheet.assets @property def liabilities(self): return self.balance_sheet.liabilities @property def collateral_ratio(self): return self.balance_sheet.collateral_ratio class LiquidationEvent: def __init__(self, timestamp: datetime.datetime, signature: str, wallet_address: PublicKey, margin_account_address: PublicKey, balances_before: typing.List[TokenValue], balances_after: typing.List[TokenValue]): self.timestamp = timestamp self.signature = signature self.wallet_address = wallet_address self.margin_account_address = margin_account_address self.balances_before = balances_before self.balances_after = balances_after def __str__(self) -> str: changes = TokenValue.changes(self.balances_before, self.balances_after) changes_text = "\n ".join([f"{change.value:>15,.8f} {change.token.name}" for change in changes]) return f"""« 🥭 Liqudation Event 💧 at {self.timestamp} 📇 Signature: {self.signature} 👛 Wallet: {self.wallet_address} 💳 Margin Account: {self.margin_account_address} 💸 Changes: {changes_text} »""" def __repr__(self) -> str: return f"{self}" def _notebook_tests(): log_level = logging.getLogger().level try: logging.getLogger().setLevel(logging.CRITICAL) from Constants import SYSTEM_PROGRAM_ADDRESS from Context import default_context balances_before = [ TokenValue(TokenLookup.find_by_name(default_context, "ETH"), Decimal(1)), TokenValue(TokenLookup.find_by_name(default_context, "BTC"), Decimal("0.1")), TokenValue(TokenLookup.find_by_name(default_context, "USDT"), Decimal(1000)) ] balances_after = [ TokenValue(TokenLookup.find_by_name(default_context, "ETH"), Decimal(1)), TokenValue(TokenLookup.find_by_name(default_context, "BTC"), Decimal("0.05")), TokenValue(TokenLookup.find_by_name(default_context, "USDT"), Decimal(2000)) ] timestamp = datetime.datetime(2021, 5, 17, 12, 20, 56) event = LiquidationEvent(timestamp, "signature", SYSTEM_PROGRAM_ADDRESS, SYSTEM_PROGRAM_ADDRESS, balances_before, balances_after) assert(str(event) == """« 🥭 Liqudation Event 💧 at 2021-05-17 12:20:56 📇 Signature: signature 👛 Wallet: 11111111111111111111111111111111 💳 Margin Account: 11111111111111111111111111111111 💸 Changes: 0.00000000 ETH -0.05000000 BTC 1,000.00000000 USDT »""") finally: logging.getLogger().setLevel(log_level) _notebook_tests() del _notebook_tests if __name__ == "__main__": logging.getLogger().setLevel(logging.INFO) import base64 from Constants import SYSTEM_PROGRAM_ADDRESS from Context import default_context # Just use any public key here fake_public_key = SYSTEM_PROGRAM_ADDRESS encoded = "AwAAAAAAAACCaOmpoURMK6XHelGTaFawcuQ/78/15LAemWI8jrt3SRKLy2R9i60eclDjuDS8+p/ZhvTUd9G7uQVOYCsR6+BhmqGCiO6EPYP2PQkf/VRTvw7JjXvIjPFJy06QR1Cq1WfTonHl0OjCkyEf60SD07+MFJu5pVWNFGGEO/8AiAYfduaKdnFTaZEHPcK5Eq72WWHeHg2yIbBF09kyeOhlCJwOoG8O5SgpPV8QOA64ZNV4aKroFfADg6kEy/wWCdp3fv0O4GJgAAAAAPH6Ud6jtjwAAQAAAAAAAADiDkkCi9UOAAEAAAAAAAAADuBiYAAAAACNS5bSy7soAAEAAAAAAAAACMvgO+2jCwABAAAAAAAAAA7gYmAAAAAAZFeDUBNVhwABAAAAAAAAABtRNytozC8AAQAAAAAAAABIBGiCcyaEZdNhrTyeqUY692vOzzPdHaxAxguht3JQGlkzjtd05dX9LENHkl2z1XvUbTNKZlweypNRetmH0lmQ9VYQAHqylxZVK65gEg85g27YuSyvOBZAjJyRmYU9KdCO1D+4ehdPu9dQB1yI1uh75wShdAaFn2o4qrMYwq3SQQEAAAAAAAAAAiH1PPJKAuh6oGiE35aGhUQhFi/bxgKOudpFv8HEHNCFDy1uAqR6+CTQmradxC1wyyjL+iSft+5XudJWwSdi7wvphsxb96x7Obj/AgAAAAAKlV4LL5ow6r9LMhIAAAAADvsOtqcVFmChDPzPnwAAAE33lx1h8hPFD04AAAAAAAA8YRV3Oa309B2wGwAAAAAA+yPBZRlZz7b605n+AQAAAACgmZmZmZkZAQAAAAAAAAAAMDMzMzMzMwEAAAAAAAAA25D1XcAtRzSuuyx3U+X7aE9vM1EJySU9KprgL0LMJ/vat9+SEEUZuga7O5tTUrcMDYWDg+LYaAWhSQiN2fYk7aCGAQAAAAAAgIQeAAAAAAAA8gUqAQAAAAYGBgICAAAA" decoded = base64.b64decode(encoded) group_account_info = AccountInfo(fake_public_key, False, Decimal(0), fake_public_key, Decimal(0), decoded) group = Group.parse(default_context, group_account_info) print("\n\nThis is hard-coded, not live information!") print(group) print(TokenLookup.find_by_name(default_context, "ETH")) print(TokenLookup.find_by_name(default_context, "BTC")) # USDT print(TokenLookup.find_by_mint(default_context, PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"))) single_account_info = AccountInfo.load(default_context, default_context.dex_program_id) print("DEX account info", single_account_info) multiple_account_info = AccountInfo.load_multiple(default_context, [default_context.program_id, default_context.dex_program_id]) print("Mango program and DEX account info", multiple_account_info) balances_before = [ TokenValue(TokenLookup.find_by_name(default_context, "ETH"), Decimal(1)), TokenValue(TokenLookup.find_by_name(default_context, "BTC"), Decimal("0.1")), TokenValue(TokenLookup.find_by_name(default_context, "USDT"), Decimal(1000)) ] balances_after = [ TokenValue(TokenLookup.find_by_name(default_context, "ETH"), Decimal(1)), TokenValue(TokenLookup.find_by_name(default_context, "BTC"), Decimal("0.05")), TokenValue(TokenLookup.find_by_name(default_context, "USDT"), Decimal(2000)) ] timestamp = datetime.datetime(2021, 5, 17, 12, 20, 56) event = LiquidationEvent(timestamp, "signature", SYSTEM_PROGRAM_ADDRESS, SYSTEM_PROGRAM_ADDRESS, balances_before, balances_after) print(event)
[((1325, 14, 1325, 39), 'base64.b64decode', 'base64.b64decode', ({(1325, 31, 1325, 38): 'encoded'}, {}), '(encoded)', False, 'import base64\n'), ((1354, 16, 1354, 58), 'datetime.datetime', 'datetime.datetime', ({(1354, 34, 1354, 38): '2021', (1354, 40, 1354, 41): '5', (1354, 43, 1354, 45): '17', (1354, 47, 1354, 49): '12', (1354, 51, 1354, 53): '20', (1354, 55, 1354, 57): '56'}, {}), '(2021, 5, 17, 12, 20, 56)', False, 'import datetime\n'), ((58, 38, 58, 80), 'logging.getLogger', 'logging.getLogger', ({(58, 56, 58, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((67, 15, 67, 39), 'Decoder.encode_binary', 'encode_binary', ({(67, 29, 67, 38): 'self.data'}, {}), '(self.data)', False, 'from Decoder import decode_binary, encode_binary, encode_key\n'), ((101, 19, 101, 55), 'decimal.Decimal', 'Decimal', ({(101, 27, 101, 54): "response_values['lamports']"}, {}), "(response_values['lamports'])", False, 'from decimal import Decimal\n'), ((102, 16, 102, 51), 'solana.publickey.PublicKey', 'PublicKey', ({(102, 26, 102, 50): "response_values['owner']"}, {}), "(response_values['owner'])", False, 'from solana.publickey import PublicKey\n'), ((103, 21, 103, 58), 'decimal.Decimal', 'Decimal', ({(103, 29, 103, 57): "response_values['rentEpoch']"}, {}), "(response_values['rentEpoch'])", False, 'from decimal import Decimal\n'), ((104, 15, 104, 53), 'Decoder.decode_binary', 'decode_binary', ({(104, 29, 104, 52): "response_values['data']"}, {}), "(response_values['data'])", False, 'from Decoder import decode_binary, encode_binary, encode_key\n'), ((113, 38, 113, 80), 'logging.getLogger', 'logging.getLogger', ({(113, 56, 113, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((126, 38, 126, 80), 'logging.getLogger', 'logging.getLogger', ({(126, 56, 126, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((161, 38, 161, 80), 'logging.getLogger', 'logging.getLogger', ({(161, 56, 161, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((187, 38, 187, 80), 'logging.getLogger', 'logging.getLogger', ({(187, 56, 187, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((209, 38, 209, 80), 'logging.getLogger', 'logging.getLogger', ({(209, 56, 209, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((233, 38, 233, 80), 'logging.getLogger', 'logging.getLogger', ({(233, 56, 233, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((251, 38, 251, 80), 'logging.getLogger', 'logging.getLogger', ({(251, 56, 251, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((304, 17, 304, 47), 'Layout.AGGREGATOR.parse', 'layouts.AGGREGATOR.parse', ({(304, 42, 304, 46): 'data'}, {}), '(data)', True, 'import Layout as layouts\n'), ((329, 38, 329, 80), 'logging.getLogger', 'logging.getLogger', ({(329, 56, 329, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((336, 15, 336, 31), 'decimal.Decimal', 'Decimal', ({(336, 23, 336, 30): 'rounded'}, {}), '(rounded)', False, 'from decimal import Decimal\n'), ((398, 38, 398, 80), 'logging.getLogger', 'logging.getLogger', ({(398, 56, 398, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((451, 15, 451, 48), 'solana.rpc.types.TokenAccountOpts', 'TokenAccountOpts', (), '', False, 'from solana.rpc.types import MemcmpOpts, TokenAccountOpts, RPCMethod, RPCResponse\n'), ((458, 22, 458, 32), 'decimal.Decimal', 'Decimal', ({(458, 30, 458, 31): '0'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((558, 38, 558, 80), 'logging.getLogger', 'logging.getLogger', ({(558, 56, 558, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((656, 17, 656, 42), 'Layout.GROUP.parse', 'layouts.GROUP.parse', ({(656, 37, 656, 41): 'data'}, {}), '(data)', True, 'import Layout as layouts\n'), ((700, 21, 700, 32), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((791, 15, 791, 48), 'solana.rpc.types.TokenAccountOpts', 'TokenAccountOpts', (), '', False, 'from solana.rpc.types import MemcmpOpts, TokenAccountOpts, RPCMethod, RPCResponse\n'), ((838, 17, 838, 50), 'Layout.TOKEN_ACCOUNT.parse', 'layouts.TOKEN_ACCOUNT.parse', ({(838, 45, 838, 49): 'data'}, {}), '(data)', True, 'import Layout as layouts\n'), ((876, 15, 876, 81), 'pyserum.open_orders_account.OpenOrdersAccount.from_bytes', 'OpenOrdersAccount.from_bytes', ({(876, 44, 876, 56): 'self.address', (876, 58, 876, 80): 'self.account_info.data'}, {}), '(self.address, self.account_info.data)', False, 'from pyserum.open_orders_account import OpenOrdersAccount\n'), ((904, 17, 904, 48), 'Layout.OPEN_ORDERS.parse', 'layouts.OPEN_ORDERS.parse', ({(904, 43, 904, 47): 'data'}, {}), '(data)', True, 'import Layout as layouts\n'), ((966, 38, 966, 80), 'logging.getLogger', 'logging.getLogger', ({(966, 56, 966, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((1038, 17, 1038, 51), 'Layout.MARGIN_ACCOUNT.parse', 'layouts.MARGIN_ACCOUNT.parse', ({(1038, 46, 1038, 50): 'data'}, {}), '(data)', True, 'import Layout as layouts\n'), ((1083, 29, 1083, 65), 'Layout.MANGO_ACCOUNT_FLAGS.sizeof', 'layouts.MANGO_ACCOUNT_FLAGS.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((1108, 33, 1108, 64), 'logging.getLogger', 'logging.getLogger', ({(1108, 51, 1108, 63): 'cls.__name__'}, {}), '(cls.__name__)', False, 'import logging\n'), ((1110, 21, 1110, 32), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((1188, 22, 1188, 32), 'decimal.Decimal', 'Decimal', ({(1188, 30, 1188, 31): '0'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((1189, 25, 1189, 35), 'decimal.Decimal', 'Decimal', ({(1189, 33, 1189, 34): '0'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((1190, 27, 1190, 37), 'decimal.Decimal', 'Decimal', ({(1190, 35, 1190, 36): '0'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((1238, 38, 1238, 80), 'logging.getLogger', 'logging.getLogger', ({(1238, 56, 1238, 79): 'self.__class__.__name__'}, {}), '(self.__class__.__name__)', False, 'import logging\n'), ((1279, 16, 1279, 35), 'logging.getLogger', 'logging.getLogger', ({}, {}), '()', False, 'import logging\n'), ((1296, 20, 1296, 62), 'datetime.datetime', 'datetime.datetime', ({(1296, 38, 1296, 42): '2021', (1296, 44, 1296, 45): '5', (1296, 47, 1296, 49): '17', (1296, 51, 1296, 53): '12', (1296, 55, 1296, 57): '20', (1296, 59, 1296, 61): '56'}, {}), '(2021, 5, 17, 12, 20, 56)', False, 'import datetime\n'), ((1326, 61, 1326, 71), 'decimal.Decimal', 'Decimal', ({(1326, 69, 1326, 70): '0'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((1326, 90, 1326, 100), 'decimal.Decimal', 'Decimal', ({(1326, 98, 1326, 99): '0'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((195, 33, 195, 56), 'decimal.Decimal', 'Decimal', ({(195, 41, 195, 55): '(10 ** decimals)'}, {}), '(10 ** decimals)', False, 'from decimal import Decimal\n'), ((196, 35, 196, 58), 'decimal.Decimal', 'Decimal', ({(196, 43, 196, 57): '(10 ** decimals)'}, {}), '(10 ** decimals)', False, 'from decimal import Decimal\n'), ((300, 24, 300, 51), 'Layout.AGGREGATOR.sizeof', 'layouts.AGGREGATOR.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((385, 33, 385, 43), 'decimal.Decimal', 'Decimal', ({(385, 41, 385, 42): '(6)'}, {}), '(6)', False, 'from decimal import Decimal\n'), ((394, 33, 394, 43), 'decimal.Decimal', 'Decimal', ({(394, 41, 394, 42): '(6)'}, {}), '(6)', False, 'from decimal import Decimal\n'), ((461, 20, 461, 64), 'decimal.Decimal', 'Decimal', ({(461, 28, 461, 63): "result['result']['value']['amount']"}, {}), "(result['result']['value']['amount'])", False, 'from decimal import Decimal\n'), ((463, 22, 463, 51), 'decimal.Decimal', 'Decimal', ({(463, 30, 463, 50): '10 ** decimal_places'}, {}), '(10 ** decimal_places)', False, 'from decimal import Decimal\n'), ((643, 60, 643, 74), 'decimal.Decimal', 'Decimal', ({(643, 68, 643, 73): '""".01"""'}, {}), "('.01')", False, 'from decimal import Decimal\n'), ((644, 58, 644, 72), 'decimal.Decimal', 'Decimal', ({(644, 66, 644, 71): '""".01"""'}, {}), "('.01')", False, 'from decimal import Decimal\n'), ((653, 24, 653, 46), 'Layout.GROUP.sizeof', 'layouts.GROUP.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((717, 21, 717, 32), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((784, 26, 784, 89), 'spl.token.client.Token', 'SplToken', ({(784, 35, 784, 49): 'context.client', (784, 51, 784, 61): 'token.mint', (784, 63, 784, 79): 'TOKEN_PROGRAM_ID', (784, 81, 784, 88): 'account'}, {}), '(context.client, token.mint, TOKEN_PROGRAM_ID, account)', True, 'from spl.token.client import Token as SplToken\n'), ((835, 24, 835, 54), 'Layout.TOKEN_ACCOUNT.sizeof', 'layouts.TOKEN_ACCOUNT.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((901, 24, 901, 52), 'Layout.OPEN_ORDERS.sizeof', 'layouts.OPEN_ORDERS.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((982, 31, 982, 41), 'decimal.Decimal', 'Decimal', ({(982, 39, 982, 40): '(0)'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((983, 19, 983, 29), 'decimal.Decimal', 'Decimal', ({(983, 27, 983, 28): '(0)'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((1035, 24, 1035, 55), 'Layout.MARGIN_ACCOUNT.sizeof', 'layouts.MARGIN_ACCOUNT.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((1063, 22, 1063, 62), 'solana.publickey.PublicKey', 'PublicKey', ({(1063, 32, 1063, 61): "margin_account_data['pubkey']"}, {}), "(margin_account_data['pubkey'])", False, 'from solana.publickey import PublicKey\n'), ((1099, 22, 1099, 62), 'solana.publickey.PublicKey', 'PublicKey', ({(1099, 32, 1099, 61): "margin_account_data['pubkey']"}, {}), "(margin_account_data['pubkey'])", False, 'from solana.publickey import PublicKey\n'), ((1129, 21, 1129, 32), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((1206, 68, 1206, 78), 'decimal.Decimal', 'Decimal', ({(1206, 76, 1206, 77): '0'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((1316, 4, 1316, 23), 'logging.getLogger', 'logging.getLogger', ({}, {}), '()', False, 'import logging\n'), ((1336, 52, 1336, 109), 'solana.publickey.PublicKey', 'PublicKey', ({(1336, 62, 1336, 108): '"""Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"""'}, {}), "('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB')", False, 'from solana.publickey import PublicKey\n'), ((1345, 69, 1345, 79), 'decimal.Decimal', 'Decimal', ({(1345, 77, 1345, 78): '(1)'}, {}), '(1)', False, 'from decimal import Decimal\n'), ((1346, 69, 1346, 83), 'decimal.Decimal', 'Decimal', ({(1346, 77, 1346, 82): '"""0.1"""'}, {}), "('0.1')", False, 'from decimal import Decimal\n'), ((1347, 70, 1347, 83), 'decimal.Decimal', 'Decimal', ({(1347, 78, 1347, 82): '(1000)'}, {}), '(1000)', False, 'from decimal import Decimal\n'), ((1350, 69, 1350, 79), 'decimal.Decimal', 'Decimal', ({(1350, 77, 1350, 78): '(1)'}, {}), '(1)', False, 'from decimal import Decimal\n'), ((1351, 69, 1351, 84), 'decimal.Decimal', 'Decimal', ({(1351, 77, 1351, 83): '"""0.05"""'}, {}), "('0.05')", False, 'from decimal import Decimal\n'), ((1352, 70, 1352, 83), 'decimal.Decimal', 'Decimal', ({(1352, 78, 1352, 82): '(2000)'}, {}), '(2000)', False, 'from decimal import Decimal\n'), ((94, 63, 94, 95), 'solana.rpc.types.RPCMethod', 'RPCMethod', ({(94, 73, 94, 94): '"""getMultipleAccounts"""'}, {}), "('getMultipleAccounts')", False, 'from solana.rpc.types import MemcmpOpts, TokenAccountOpts, RPCMethod, RPCResponse\n'), ((472, 37, 472, 47), 'decimal.Decimal', 'Decimal', ({(472, 45, 472, 46): '(0)'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((570, 33, 570, 71), 'pyserum.market.Market.load', 'Market.load', ({(570, 45, 570, 59): 'context.client', (570, 61, 570, 70): 'self.spot'}, {}), '(context.client, self.spot)', False, 'from pyserum.market import Market\n'), ((712, 68, 712, 78), 'decimal.Decimal', 'Decimal', ({(712, 76, 712, 77): '(1)'}, {}), '(1)', False, 'from decimal import Decimal\n'), ((797, 96, 797, 139), 'solana.publickey.PublicKey', 'PublicKey', ({(797, 106, 797, 138): "token_account_response['pubkey']"}, {}), "(token_account_response['pubkey'])", False, 'from solana.publickey import PublicKey\n'), ((844, 62, 844, 92), 'Layout.TOKEN_ACCOUNT.sizeof', 'layouts.TOKEN_ACCOUNT.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((1060, 77, 1060, 108), 'Layout.MARGIN_ACCOUNT.sizeof', 'layouts.MARGIN_ACCOUNT.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((1096, 85, 1096, 116), 'Layout.MARGIN_ACCOUNT.sizeof', 'layouts.MARGIN_ACCOUNT.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((1150, 48, 1150, 58), 'decimal.Decimal', 'Decimal', ({(1150, 56, 1150, 57): '(0)'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((1151, 45, 1151, 55), 'decimal.Decimal', 'Decimal', ({(1151, 53, 1151, 54): '(0)'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((1156, 50, 1156, 60), 'decimal.Decimal', 'Decimal', ({(1156, 58, 1156, 59): '(0)'}, {}), '(0)', False, 'from decimal import Decimal\n'), ((1281, 8, 1281, 27), 'logging.getLogger', 'logging.getLogger', ({}, {}), '()', False, 'import logging\n'), ((1287, 73, 1287, 83), 'decimal.Decimal', 'Decimal', ({(1287, 81, 1287, 82): '(1)'}, {}), '(1)', False, 'from decimal import Decimal\n'), ((1288, 73, 1288, 87), 'decimal.Decimal', 'Decimal', ({(1288, 81, 1288, 86): '"""0.1"""'}, {}), "('0.1')", False, 'from decimal import Decimal\n'), ((1289, 74, 1289, 87), 'decimal.Decimal', 'Decimal', ({(1289, 82, 1289, 86): '(1000)'}, {}), '(1000)', False, 'from decimal import Decimal\n'), ((1292, 73, 1292, 83), 'decimal.Decimal', 'Decimal', ({(1292, 81, 1292, 82): '(1)'}, {}), '(1)', False, 'from decimal import Decimal\n'), ((1293, 73, 1293, 88), 'decimal.Decimal', 'Decimal', ({(1293, 81, 1293, 87): '"""0.05"""'}, {}), "('0.05')", False, 'from decimal import Decimal\n'), ((1294, 74, 1294, 87), 'decimal.Decimal', 'Decimal', ({(1294, 82, 1294, 86): '(2000)'}, {}), '(2000)', False, 'from decimal import Decimal\n'), ((1309, 8, 1309, 27), 'logging.getLogger', 'logging.getLogger', ({}, {}), '()', False, 'import logging\n'), ((912, 22, 912, 50), 'Decoder.encode_key', 'encode_key', ({(912, 33, 912, 49): 'group.signer_key'}, {}), '(group.signer_key)', False, 'from Decoder import decode_binary, encode_binary, encode_key\n'), ((916, 93, 916, 121), 'Layout.OPEN_ORDERS.sizeof', 'layouts.OPEN_ORDERS.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((933, 22, 933, 40), 'Decoder.encode_key', 'encode_key', ({(933, 33, 933, 39): 'market'}, {}), '(market)', False, 'from Decoder import decode_binary, encode_binary, encode_key\n'), ((937, 22, 937, 39), 'Decoder.encode_key', 'encode_key', ({(937, 33, 937, 38): 'owner'}, {}), '(owner)', False, 'from Decoder import decode_binary, encode_binary, encode_key\n'), ((941, 95, 941, 123), 'Layout.OPEN_ORDERS.sizeof', 'layouts.OPEN_ORDERS.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((1056, 23, 1056, 59), 'Layout.MANGO_ACCOUNT_FLAGS.sizeof', 'layouts.MANGO_ACCOUNT_FLAGS.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((1057, 22, 1057, 47), 'Decoder.encode_key', 'encode_key', ({(1057, 33, 1057, 46): 'group.address'}, {}), '(group.address)', False, 'from Decoder import decode_binary, encode_binary, encode_key\n'), ((1088, 22, 1088, 47), 'Decoder.encode_key', 'encode_key', ({(1088, 33, 1088, 46): 'group.address'}, {}), '(group.address)', False, 'from Decoder import decode_binary, encode_binary, encode_key\n'), ((1092, 22, 1092, 39), 'Decoder.encode_key', 'encode_key', ({(1092, 33, 1092, 38): 'owner'}, {}), '(owner)', False, 'from Decoder import decode_binary, encode_binary, encode_key\n'), ((301, 87, 301, 114), 'Layout.AGGREGATOR.sizeof', 'layouts.AGGREGATOR.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((654, 87, 654, 109), 'Layout.GROUP.sizeof', 'layouts.GROUP.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((836, 87, 836, 117), 'Layout.TOKEN_ACCOUNT.sizeof', 'layouts.TOKEN_ACCOUNT.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((902, 87, 902, 115), 'Layout.OPEN_ORDERS.sizeof', 'layouts.OPEN_ORDERS.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((911, 23, 911, 59), 'Layout.SERUM_ACCOUNT_FLAGS.sizeof', 'layouts.SERUM_ACCOUNT_FLAGS.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((917, 120, 917, 147), 'solana.publickey.PublicKey', 'PublicKey', ({(917, 130, 917, 146): "result['pubkey']"}, {}), "(result['pubkey'])", False, 'from solana.publickey import PublicKey\n'), ((932, 23, 932, 59), 'Layout.SERUM_ACCOUNT_FLAGS.sizeof', 'layouts.SERUM_ACCOUNT_FLAGS.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((936, 23, 936, 59), 'Layout.SERUM_ACCOUNT_FLAGS.sizeof', 'layouts.SERUM_ACCOUNT_FLAGS.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n'), ((942, 115, 942, 142), 'solana.publickey.PublicKey', 'PublicKey', ({(942, 125, 942, 141): "result['pubkey']"}, {}), "(result['pubkey'])", False, 'from solana.publickey import PublicKey\n'), ((1036, 87, 1036, 118), 'Layout.MARGIN_ACCOUNT.sizeof', 'layouts.MARGIN_ACCOUNT.sizeof', ({}, {}), '()', True, 'import Layout as layouts\n')]
afnmachado/univesp_pi_1
agendamentos/migrations/0011_alter_agendamentosfuncionarios_table.py
e6f2b545faaf53d14d17f751d2fb32e6618885b7
# Generated by Django 3.2.8 on 2021-11-29 05:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('agendamentos', '0010_agendamentosfuncionarios'), ] operations = [ migrations.AlterModelTable( name='agendamentosfuncionarios', table='agendamento_funcionario', ), ]
[((13, 8, 16, 9), 'django.db.migrations.AlterModelTable', 'migrations.AlterModelTable', (), '', False, 'from django.db import migrations\n')]
teresa-ho/stx-openstacksdk
openstack/tests/unit/metric/v1/test_capabilities.py
7d723da3ffe9861e6e9abcaeadc1991689f782c5
# 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 testtools from openstack.metric.v1 import capabilities BODY = { 'aggregation_methods': ['mean', 'max', 'avg'], } class TestCapabilites(testtools.TestCase): def test_basic(self): sot = capabilities.Capabilities() self.assertEqual('/capabilities', sot.base_path) self.assertEqual('metric', sot.service.service_type) self.assertFalse(sot.allow_create) self.assertTrue(sot.allow_get) self.assertFalse(sot.allow_update) self.assertFalse(sot.allow_delete) self.assertFalse(sot.allow_list) def test_make_it(self): sot = capabilities.Capabilities(**BODY) self.assertEqual(BODY['aggregation_methods'], sot.aggregation_methods)
[((24, 14, 24, 41), 'openstack.metric.v1.capabilities.Capabilities', 'capabilities.Capabilities', ({}, {}), '()', False, 'from openstack.metric.v1 import capabilities\n'), ((34, 14, 34, 47), 'openstack.metric.v1.capabilities.Capabilities', 'capabilities.Capabilities', ({}, {}), '(**BODY)', False, 'from openstack.metric.v1 import capabilities\n')]
yqliaohk/pyXDSM
pyxdsm/tests/test_xdsm.py
3bcfab710543d6624ba0698093c6522bc94601e8
import unittest import os from pyxdsm.XDSM import XDSM, __file__ from numpy.distutils.exec_command import find_executable def filter_lines(lns): # Empty lines are excluded. # Leading and trailing whitespaces are removed # Comments are removed. return [ln.strip() for ln in lns if ln.strip() and not ln.strip().startswith('%')] class TestXDSM(unittest.TestCase): def setUp(self): import os import tempfile self.startdir = os.getcwd() self.tempdir = tempfile.mkdtemp(prefix='testdir-') os.chdir(self.tempdir) def tearDown(self): import os import shutil os.chdir(self.startdir) try: shutil.rmtree(self.tempdir) except OSError: pass def test_examples(self): ''' This test just builds the three examples, and assert that the output files exist. Unlike the other tests, this one requires LaTeX to be available. ''' os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../examples')) filenames = ['kitchen_sink', 'mdf'] for f in filenames: os.system('python {}.py'.format(f)) self.assertTrue(os.path.isfile(f + '.tikz')) self.assertTrue(os.path.isfile(f + '.tex')) # look for the pdflatex executable pdflatex = find_executable('pdflatex') is not None # if no pdflatex, then do not assert that the pdf was compiled self.assertTrue(not pdflatex or os.path.isfile(f + '.pdf')) os.system('python mat_eqn.py') self.assertTrue(os.path.isfile('mat_eqn_example.pdf')) # change back to previous directory os.chdir(self.tempdir) def test_connect(self): x = XDSM(use_sfmath=False) x.add_system('D1', 'Function', 'D_1', label_width=2) x.add_system('D2', 'Function', 'D_2', stack=False) try: x.connect('D1', 'D2', r'\mathcal{R}(y_1)', 'foobar') except ValueError as err: self.assertEquals(str(err), 'label_width argument must be an integer') else: self.fail('Expected ValueError') def test_options(self): filename = 'xdsm_test_options' spec_dir = filename + '_specs' # Change `use_sfmath` to False to use computer modern x = XDSM(use_sfmath=False) x.add_system('opt', 'Optimization', r'\text{Optimizer}') x.add_system('solver', 'MDA', r'\text{Newton}') x.add_system('D1', 'Function', 'D_1', label_width=2) x.add_system('D2', 'Function', 'D_2', stack=False) x.add_system('F', 'Function', 'F', faded=True) x.add_system('G', 'Function', 'G', spec_name="G_spec") x.connect('opt', 'D1', 'x, z') x.connect('opt', 'D2', 'z') x.connect('opt', 'F', 'x, z') x.connect('solver', 'D1', 'y_2') x.connect('solver', 'D2', 'y_1') x.connect('D1', 'solver', r'\mathcal{R}(y_1)') x.connect('solver', 'F', 'y_1, y_2') x.connect('D2', 'solver', r'\mathcal{R}(y_2)') x.connect('solver', 'G', 'y_1, y_2') x.connect('F', 'opt', 'f') x.connect('G', 'opt', 'g') x.add_output('opt', 'x^*, z^*', side='right') x.add_output('D1', 'y_1^*', side='left', stack=True) x.add_output('D2', 'y_2^*', side='left') x.add_output('F', 'f^*', side='left') x.add_output('G', 'g^*') x.write(filename) x.write_sys_specs(spec_dir) # Test if files where created self.assertTrue(os.path.isfile(filename + '.tikz')) self.assertTrue(os.path.isfile(filename + '.tex')) self.assertTrue(os.path.isdir(spec_dir)) self.assertTrue(os.path.isfile(os.path.join(spec_dir, 'F.json'))) self.assertTrue(os.path.isfile(os.path.join(spec_dir, 'G_spec.json'))) def test_stacked_system(self): x = XDSM() x.add_system('test', 'Optimization', r'\text{test}', stack=True) file_name = "stacked_test" x.write(file_name) tikz_file = file_name + '.tikz' with open(tikz_file, "r") as f: tikz = f.read() self.assertIn(r"\node [Optimization,stack]", tikz) def test_tikz_content(self): # Check if TiKZ file was created. # Compare the content of the sample below and the newly created TiKZ file. sample_txt = r""" %%% Preamble Requirements %%% % \usepackage{geometry} % \usepackage{amsfonts} % \usepackage{amsmath} % \usepackage{amssymb} % \usepackage{tikz} % Optional packages such as sfmath set through python interface % \usepackage{sfmath} % \usetikzlibrary{arrows,chains,positioning,scopes,shapes.geometric,shapes.misc,shadows} %%% End Preamble Requirements %%% \input{"path/to/diagram_styles"} \begin{tikzpicture} \matrix[MatrixSetup]{ %Row 0 \node [DataIO] (left_output_opt) {$x^*, z^*$};& \node [Optimization] (opt) {$\text{Optimizer}$};& & \node [DataInter] (opt-D1) {$x, z$};& \node [DataInter] (opt-D2) {$z$};& \node [DataInter] (opt-F) {$x, z$};& \\ %Row 1 & & \node [MDA] (solver) {$\text{Newton}$};& \node [DataInter] (solver-D1) {$y_2$};& \node [DataInter] (solver-D2) {$y_1$};& \node [DataInter] (solver-F) {$y_1, y_2$};& \node [DataInter] (solver-G) {$y_1, y_2$};\\ %Row 2 \node [DataIO] (left_output_D1) {$y_1^*$};& & \node [DataInter] (D1-solver) {$\mathcal{R}(y_1)$};& \node [Function] (D1) {$D_1$};& & & \\ %Row 3 \node [DataIO] (left_output_D2) {$y_2^*$};& & \node [DataInter] (D2-solver) {$\mathcal{R}(y_2)$};& & \node [Function] (D2) {$D_2$};& & \\ %Row 4 \node [DataIO] (left_output_F) {$f^*$};& \node [DataInter] (F-opt) {$f$};& & & & \node [Function] (F) {$F$};& \\ %Row 5 \node [DataIO] (left_output_G) {$g^*$};& \node [DataInter] (G-opt) {$g$};& & & & & \node [Function] (G) {$G$};\\ %Row 6 & & & & & & \\ }; % XDSM process chains \begin{pgfonlayer}{data} \path % Horizontal edges (opt) edge [DataLine] (opt-D1) (opt) edge [DataLine] (opt-D2) (opt) edge [DataLine] (opt-F) (solver) edge [DataLine] (solver-D1) (solver) edge [DataLine] (solver-D2) (D1) edge [DataLine] (D1-solver) (solver) edge [DataLine] (solver-F) (D2) edge [DataLine] (D2-solver) (solver) edge [DataLine] (solver-G) (F) edge [DataLine] (F-opt) (G) edge [DataLine] (G-opt) (opt) edge [DataLine] (left_output_opt) (D1) edge [DataLine] (left_output_D1) (D2) edge [DataLine] (left_output_D2) (F) edge [DataLine] (left_output_F) (G) edge [DataLine] (left_output_G) % Vertical edges (opt-D1) edge [DataLine] (D1) (opt-D2) edge [DataLine] (D2) (opt-F) edge [DataLine] (F) (solver-D1) edge [DataLine] (D1) (solver-D2) edge [DataLine] (D2) (D1-solver) edge [DataLine] (solver) (solver-F) edge [DataLine] (F) (D2-solver) edge [DataLine] (solver) (solver-G) edge [DataLine] (G) (F-opt) edge [DataLine] (opt) (G-opt) edge [DataLine] (opt); \end{pgfonlayer} \end{tikzpicture}""" filename = 'xdsm_test_tikz' x = XDSM(use_sfmath=True) x.add_system('opt', 'Optimization', r'\text{Optimizer}') x.add_system('solver', 'MDA', r'\text{Newton}') x.add_system('D1', 'Function', 'D_1') x.add_system('D2', 'Function', 'D_2') x.add_system('F', 'Function', 'F') x.add_system('G', 'Function', 'G') x.connect('opt', 'D1', 'x, z') x.connect('opt', 'D2', 'z') x.connect('opt', 'F', 'x, z') x.connect('solver', 'D1', 'y_2') x.connect('solver', 'D2', 'y_1') x.connect('D1', 'solver', r'\mathcal{R}(y_1)') x.connect('solver', 'F', 'y_1, y_2') x.connect('D2', 'solver', r'\mathcal{R}(y_2)') x.connect('solver', 'G', 'y_1, y_2') x.connect('F', 'opt', 'f') x.connect('G', 'opt', 'g') x.add_output('opt', 'x^*, z^*', side='left') x.add_output('D1', 'y_1^*', side='left') x.add_output('D2', 'y_2^*', side='left') x.add_output('F', 'f^*', side='left') x.add_output('G', 'g^*', side='left') x.write(filename) # Check if file was created tikz_file = filename + '.tikz' self.assertTrue(os.path.isfile(tikz_file)) sample_lines = sample_txt.split('\n') sample_lines = filter_lines(sample_lines) with open(tikz_file, "r") as f: new_lines = filter_lines(f.readlines()) sample_no_match = [] # Sample text new_no_match = [] # New text for new_line, sample_line in zip(new_lines, sample_lines): if new_line.startswith(r'\input{'): continue if new_line != sample_line: # else everything is okay # This can be because of the different ordering of lines or because of an error. sample_no_match.append(new_line) new_no_match.append(sample_line) # Sort both sets of suspicious lines sample_no_match.sort() new_no_match.sort() for sample_line, new_line in zip(sample_no_match, new_no_match): # Now the lines should match, if only the ordering was different self.assertEqual(new_line, sample_line) # To be sure, check the length, otherwise a missing last line could get unnoticed because of using zip self.assertEqual(len(new_lines), len(sample_lines)) if __name__ == "__main__": unittest.main()
[((316, 4, 316, 19), 'unittest.main', 'unittest.main', ({}, {}), '()', False, 'import unittest\n'), ((19, 24, 19, 35), 'os.getcwd', 'os.getcwd', ({}, {}), '()', False, 'import os\n'), ((20, 23, 20, 58), 'tempfile.mkdtemp', 'tempfile.mkdtemp', (), '', False, 'import tempfile\n'), ((22, 8, 22, 30), 'os.chdir', 'os.chdir', ({(22, 17, 22, 29): 'self.tempdir'}, {}), '(self.tempdir)', False, 'import os\n'), ((28, 8, 28, 31), 'os.chdir', 'os.chdir', ({(28, 17, 28, 30): 'self.startdir'}, {}), '(self.startdir)', False, 'import os\n'), ((51, 8, 51, 38), 'os.system', 'os.system', ({(51, 18, 51, 37): '"""python mat_eqn.py"""'}, {}), "('python mat_eqn.py')", False, 'import os\n'), ((54, 8, 54, 30), 'os.chdir', 'os.chdir', ({(54, 17, 54, 29): 'self.tempdir'}, {}), '(self.tempdir)', False, 'import os\n'), ((58, 12, 58, 34), 'pyxdsm.XDSM.XDSM', 'XDSM', (), '', False, 'from pyxdsm.XDSM import XDSM, __file__\n'), ((75, 12, 75, 34), 'pyxdsm.XDSM.XDSM', 'XDSM', (), '', False, 'from pyxdsm.XDSM import XDSM, __file__\n'), ((115, 12, 115, 18), 'pyxdsm.XDSM.XDSM', 'XDSM', ({}, {}), '()', False, 'from pyxdsm.XDSM import XDSM, __file__\n'), ((252, 12, 252, 33), 'pyxdsm.XDSM.XDSM', 'XDSM', (), '', False, 'from pyxdsm.XDSM import XDSM, __file__\n'), ((31, 12, 31, 39), 'shutil.rmtree', 'shutil.rmtree', ({(31, 26, 31, 38): 'self.tempdir'}, {}), '(self.tempdir)', False, 'import shutil\n'), ((52, 24, 52, 61), 'os.path.isfile', 'os.path.isfile', ({(52, 39, 52, 60): '"""mat_eqn_example.pdf"""'}, {}), "('mat_eqn_example.pdf')", False, 'import os\n'), ((106, 24, 106, 58), 'os.path.isfile', 'os.path.isfile', ({(106, 39, 106, 57): "(filename + '.tikz')"}, {}), "(filename + '.tikz')", False, 'import os\n'), ((107, 24, 107, 57), 'os.path.isfile', 'os.path.isfile', ({(107, 39, 107, 56): "(filename + '.tex')"}, {}), "(filename + '.tex')", False, 'import os\n'), ((108, 24, 108, 47), 'os.path.isdir', 'os.path.isdir', ({(108, 38, 108, 46): 'spec_dir'}, {}), '(spec_dir)', False, 'import os\n'), ((284, 24, 284, 49), 'os.path.isfile', 'os.path.isfile', ({(284, 39, 284, 48): 'tikz_file'}, {}), '(tikz_file)', False, 'import os\n'), ((45, 28, 45, 55), 'os.path.isfile', 'os.path.isfile', ({(45, 43, 45, 54): "(f + '.tikz')"}, {}), "(f + '.tikz')", False, 'import os\n'), ((46, 28, 46, 54), 'os.path.isfile', 'os.path.isfile', ({(46, 43, 46, 53): "(f + '.tex')"}, {}), "(f + '.tex')", False, 'import os\n'), ((48, 23, 48, 50), 'numpy.distutils.exec_command.find_executable', 'find_executable', ({(48, 39, 48, 49): '"""pdflatex"""'}, {}), "('pdflatex')", False, 'from numpy.distutils.exec_command import find_executable\n'), ((109, 39, 109, 71), 'os.path.join', 'os.path.join', ({(109, 52, 109, 60): 'spec_dir', (109, 62, 109, 70): '"""F.json"""'}, {}), "(spec_dir, 'F.json')", False, 'import os\n'), ((110, 39, 110, 76), 'os.path.join', 'os.path.join', ({(110, 52, 110, 60): 'spec_dir', (110, 62, 110, 75): '"""G_spec.json"""'}, {}), "(spec_dir, 'G_spec.json')", False, 'import os\n'), ((40, 46, 40, 71), 'os.path.abspath', 'os.path.abspath', ({(40, 62, 40, 70): '__file__'}, {}), '(__file__)', False, 'import os\n'), ((50, 44, 50, 70), 'os.path.isfile', 'os.path.isfile', ({(50, 59, 50, 69): "(f + '.pdf')"}, {}), "(f + '.pdf')", False, 'import os\n')]
quanttide/wecom-sdk-py
wecom_sdk/base/callback.py
1c71909c08d885e52e4ec38a9ddac0938a059e5a
# -*- coding: utf-8 -*- from wecom_sdk.base.crypt import encrypt_msg, decrypt_msg class WeChatWorkCallbackSDK(object): """ 企业微信回调SDK基本类,用于实现内部系统和企业微信客户端的双向通信 详细说明:https://work.weixin.qq.com/api/doc/90000/90135/90930 """ def __init__(self, token, encoding_aes_key): self.token = token self.encoding_aes_key = encoding_aes_key def encrypt(self, data: dict) -> str: """ 服务端加密数据 :param data: :param timestamp: :param nonce: :return: """ return encrypt_msg(data, token=self.token, encoding_aes_key=self.encoding_aes_key) def decrypt(self, xml, sign, timestamp, nonce) -> dict: """ 验证并解密来自客户端的数据 :return: """ return decrypt_msg(xml_text=xml, encrypt_sign=sign, timestamp=timestamp, nonce=nonce, token=self.token, encoding_aes_key=self.encoding_aes_key)
[((23, 15, 23, 90), 'wecom_sdk.base.crypt.encrypt_msg', 'encrypt_msg', (), '', False, 'from wecom_sdk.base.crypt import encrypt_msg, decrypt_msg\n'), ((30, 15, 31, 84), 'wecom_sdk.base.crypt.decrypt_msg', 'decrypt_msg', (), '', False, 'from wecom_sdk.base.crypt import encrypt_msg, decrypt_msg\n')]
numankh/GRE-Vocab-Helper
scripts/get-table-schemas.py
c2858f3200f6d6673b1f316879e5ac482a6b7a83
import psycopg2 from decouple import config import pandas as pd import dbconnect cursor, connection = dbconnect.connect_to_db() sql = """ SELECT "table_name","column_name", "data_type", "table_schema" FROM INFORMATION_SCHEMA.COLUMNS WHERE "table_schema" = 'public' ORDER BY table_name """ df = pd.read_sql(sql, con=connection) print(df.to_string())
[((6, 21, 6, 46), 'dbconnect.connect_to_db', 'dbconnect.connect_to_db', ({}, {}), '()', False, 'import dbconnect\n'), ((13, 5, 13, 37), 'pandas.read_sql', 'pd.read_sql', (), '', True, 'import pandas as pd\n')]
andriyor/agate
tests/test_table/test_pivot.py
9b12d4bcc75bf3788e0774e23188f4409c3e7519
#!/usr/bin/env python # -*- coding: utf8 -*- import sys try: from cdecimal import Decimal except ImportError: # pragma: no cover from decimal import Decimal from agate import Table from agate.aggregations import Sum from agate.computations import Percent from agate.data_types import Number, Text from agate.testcase import AgateTestCase class TestPivot(AgateTestCase): def setUp(self): self.rows = ( ('joe', 'white', 'male', 20, 'blue'), ('jane', 'white', 'female', 20, 'blue'), ('josh', 'black', 'male', 20, 'blue'), ('jim', 'latino', 'male', 25, 'blue'), ('julia', 'white', 'female', 25, 'green'), ('joan', 'asian', 'female', 25, 'green') ) self.number_type = Number() self.text_type = Text() self.column_names = ['name', 'race', 'gender', 'age', 'color'] self.column_types = [self.text_type, self.text_type, self.text_type, self.number_type, self.text_type] def test_pivot(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot('race', 'gender') pivot_rows = ( ('white', 1, 2), ('black', 1, 0), ('latino', 1, 0), ('asian', 0, 1) ) self.assertColumnNames(pivot_table, ['race', 'male', 'female']) self.assertRowNames(pivot_table, ['white', 'black', 'latino', 'asian']) self.assertColumnTypes(pivot_table, [Text, Number, Number]) self.assertRows(pivot_table, pivot_rows) def test_pivot_by_lambda(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot(lambda r: r['gender']) pivot_rows = ( ('male', 3), ('female', 3) ) self.assertColumnNames(pivot_table, ['group', 'Count']) self.assertRowNames(pivot_table, ['male', 'female']) self.assertColumnTypes(pivot_table, [Text, Number]) self.assertRows(pivot_table, pivot_rows) def test_pivot_by_lambda_group_name(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot(lambda r: r['gender'], key_name='gender') pivot_rows = ( ('male', 3), ('female', 3) ) self.assertColumnNames(pivot_table, ['gender', 'Count']) self.assertRowNames(pivot_table, ['male', 'female']) self.assertColumnTypes(pivot_table, [Text, Number]) self.assertRows(pivot_table, pivot_rows) def test_pivot_by_lambda_group_name_sequence_invalid(self): table = Table(self.rows, self.column_names, self.column_types) with self.assertRaises(ValueError): table.pivot(['race', 'gender'], key_name='foo') def test_pivot_no_key(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot(pivot='gender') pivot_rows = ( (3, 3), ) self.assertColumnNames(pivot_table, ['male', 'female']) self.assertColumnTypes(pivot_table, [Number, Number]) self.assertRows(pivot_table, pivot_rows) def test_pivot_no_pivot(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot('race') pivot_rows = ( ('white', 3), ('black', 1), ('latino', 1), ('asian', 1) ) self.assertColumnNames(pivot_table, ['race', 'Count']) self.assertColumnTypes(pivot_table, [Text, Number]) self.assertRows(pivot_table, pivot_rows) def test_pivot_sum(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot('race', 'gender', Sum('age')) pivot_rows = ( ('white', 20, 45), ('black', 20, 0), ('latino', 25, 0), ('asian', 0, 25) ) self.assertColumnNames(pivot_table, ['race', 'male', 'female']) self.assertColumnTypes(pivot_table, [Text, Number, Number]) self.assertRows(pivot_table, pivot_rows) def test_pivot_multiple_keys(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot(['race', 'gender'], 'age') pivot_rows = ( ('white', 'male', 1, 0), ('white', 'female', 1, 1), ('black', 'male', 1, 0), ('latino', 'male', 0, 1), ('asian', 'female', 0, 1), ) self.assertRows(pivot_table, pivot_rows) self.assertColumnNames(pivot_table, ['race', 'gender', '20', '25']) self.assertRowNames(pivot_table, [ ('white', 'male'), ('white', 'female'), ('black', 'male'), ('latino', 'male'), ('asian', 'female'), ]) self.assertColumnTypes(pivot_table, [Text, Text, Number, Number]) def test_pivot_multiple_keys_no_pivot(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot(['race', 'gender']) pivot_rows = ( ('white', 'male', 1), ('white', 'female', 2), ('black', 'male', 1), ('latino', 'male', 1), ('asian', 'female', 1), ) self.assertRows(pivot_table, pivot_rows) self.assertColumnNames(pivot_table, ['race', 'gender', 'Count']) self.assertColumnTypes(pivot_table, [Text, Text, Number]) def test_pivot_default_value(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot('race', 'gender', default_value=None) pivot_rows = ( ('white', 1, 2), ('black', 1, None), ('latino', 1, None), ('asian', None, 1) ) self.assertColumnNames(pivot_table, ['race', 'male', 'female']) self.assertColumnTypes(pivot_table, [Text, Number, Number]) self.assertRows(pivot_table, pivot_rows) def test_pivot_compute(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot('gender', computation=Percent('Count')) pivot_table.print_table(output=sys.stdout) pivot_rows = ( ('male', Decimal(50)), ('female', Decimal(50)), ) self.assertColumnNames(pivot_table, ['gender', 'Percent']) self.assertColumnTypes(pivot_table, [Text, Number]) self.assertRows(pivot_table, pivot_rows) def test_pivot_compute_pivots(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot('gender', 'color', computation=Percent('Count')) pivot_table.print_table(output=sys.stdout) pivot_rows = ( ('male', Decimal(50), 0), ('female', Decimal(1) / Decimal(6) * Decimal(100), Decimal(1) / Decimal(3) * Decimal(100)), ) self.assertColumnNames(pivot_table, ['gender', 'blue', 'green']) self.assertColumnTypes(pivot_table, [Text, Number, Number]) self.assertRows(pivot_table, pivot_rows) def test_pivot_compute_kwargs(self): table = Table(self.rows, self.column_names, self.column_types) pivot_table = table.pivot('gender', 'color', computation=Percent('Count', total=8)) pivot_table.print_table(output=sys.stdout) pivot_rows = ( ('male', Decimal(3) / Decimal(8) * Decimal(100), 0), ('female', Decimal(1) / Decimal(8) * Decimal(100), Decimal(2) / Decimal(8) * Decimal(100)), ) self.assertColumnNames(pivot_table, ['gender', 'blue', 'green']) self.assertColumnTypes(pivot_table, [Text, Number, Number]) self.assertRows(pivot_table, pivot_rows)
[((29, 27, 29, 35), 'agate.data_types.Number', 'Number', ({}, {}), '()', False, 'from agate.data_types import Number, Text\n'), ((30, 25, 30, 31), 'agate.data_types.Text', 'Text', ({}, {}), '()', False, 'from agate.data_types import Number, Text\n'), ((36, 16, 36, 70), 'agate.Table', 'Table', ({(36, 22, 36, 31): 'self.rows', (36, 33, 36, 50): 'self.column_names', (36, 52, 36, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((53, 16, 53, 70), 'agate.Table', 'Table', ({(53, 22, 53, 31): 'self.rows', (53, 33, 53, 50): 'self.column_names', (53, 52, 53, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((68, 16, 68, 70), 'agate.Table', 'Table', ({(68, 22, 68, 31): 'self.rows', (68, 33, 68, 50): 'self.column_names', (68, 52, 68, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((83, 16, 83, 70), 'agate.Table', 'Table', ({(83, 22, 83, 31): 'self.rows', (83, 33, 83, 50): 'self.column_names', (83, 52, 83, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((89, 16, 89, 70), 'agate.Table', 'Table', ({(89, 22, 89, 31): 'self.rows', (89, 33, 89, 50): 'self.column_names', (89, 52, 89, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((102, 16, 102, 70), 'agate.Table', 'Table', ({(102, 22, 102, 31): 'self.rows', (102, 33, 102, 50): 'self.column_names', (102, 52, 102, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((118, 16, 118, 70), 'agate.Table', 'Table', ({(118, 22, 118, 31): 'self.rows', (118, 33, 118, 50): 'self.column_names', (118, 52, 118, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((134, 16, 134, 70), 'agate.Table', 'Table', ({(134, 22, 134, 31): 'self.rows', (134, 33, 134, 50): 'self.column_names', (134, 52, 134, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((158, 16, 158, 70), 'agate.Table', 'Table', ({(158, 22, 158, 31): 'self.rows', (158, 33, 158, 50): 'self.column_names', (158, 52, 158, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((175, 16, 175, 70), 'agate.Table', 'Table', ({(175, 22, 175, 31): 'self.rows', (175, 33, 175, 50): 'self.column_names', (175, 52, 175, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((191, 16, 191, 70), 'agate.Table', 'Table', ({(191, 22, 191, 31): 'self.rows', (191, 33, 191, 50): 'self.column_names', (191, 52, 191, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((207, 16, 207, 70), 'agate.Table', 'Table', ({(207, 22, 207, 31): 'self.rows', (207, 33, 207, 50): 'self.column_names', (207, 52, 207, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((223, 16, 223, 70), 'agate.Table', 'Table', ({(223, 22, 223, 31): 'self.rows', (223, 33, 223, 50): 'self.column_names', (223, 52, 223, 69): 'self.column_types'}, {}), '(self.rows, self.column_names, self.column_types)', False, 'from agate import Table\n'), ((120, 52, 120, 62), 'agate.aggregations.Sum', 'Sum', ({(120, 56, 120, 61): '"""age"""'}, {}), "('age')", False, 'from agate.aggregations import Sum\n'), ((193, 56, 193, 72), 'agate.computations.Percent', 'Percent', ({(193, 64, 193, 71): '"""Count"""'}, {}), "('Count')", False, 'from agate.computations import Percent\n'), ((198, 21, 198, 32), 'decimal.Decimal', 'Decimal', ({(198, 29, 198, 31): '(50)'}, {}), '(50)', False, 'from decimal import Decimal\n'), ((199, 23, 199, 34), 'decimal.Decimal', 'Decimal', ({(199, 31, 199, 33): '(50)'}, {}), '(50)', False, 'from decimal import Decimal\n'), ((209, 65, 209, 81), 'agate.computations.Percent', 'Percent', ({(209, 73, 209, 80): '"""Count"""'}, {}), "('Count')", False, 'from agate.computations import Percent\n'), ((214, 21, 214, 32), 'decimal.Decimal', 'Decimal', ({(214, 29, 214, 31): '(50)'}, {}), '(50)', False, 'from decimal import Decimal\n'), ((225, 65, 225, 90), 'agate.computations.Percent', 'Percent', (), '', False, 'from agate.computations import Percent\n'), ((215, 49, 215, 61), 'decimal.Decimal', 'Decimal', ({(215, 57, 215, 60): '(100)'}, {}), '(100)', False, 'from decimal import Decimal\n'), ((215, 89, 215, 101), 'decimal.Decimal', 'Decimal', ({(215, 97, 215, 100): '(100)'}, {}), '(100)', False, 'from decimal import Decimal\n'), ((230, 47, 230, 59), 'decimal.Decimal', 'Decimal', ({(230, 55, 230, 58): '(100)'}, {}), '(100)', False, 'from decimal import Decimal\n'), ((231, 49, 231, 61), 'decimal.Decimal', 'Decimal', ({(231, 57, 231, 60): '(100)'}, {}), '(100)', False, 'from decimal import Decimal\n'), ((231, 89, 231, 101), 'decimal.Decimal', 'Decimal', ({(231, 97, 231, 100): '(100)'}, {}), '(100)', False, 'from decimal import Decimal\n'), ((215, 23, 215, 33), 'decimal.Decimal', 'Decimal', ({(215, 31, 215, 32): '(1)'}, {}), '(1)', False, 'from decimal import Decimal\n'), ((215, 36, 215, 46), 'decimal.Decimal', 'Decimal', ({(215, 44, 215, 45): '(6)'}, {}), '(6)', False, 'from decimal import Decimal\n'), ((215, 63, 215, 73), 'decimal.Decimal', 'Decimal', ({(215, 71, 215, 72): '(1)'}, {}), '(1)', False, 'from decimal import Decimal\n'), ((215, 76, 215, 86), 'decimal.Decimal', 'Decimal', ({(215, 84, 215, 85): '(3)'}, {}), '(3)', False, 'from decimal import Decimal\n'), ((230, 21, 230, 31), 'decimal.Decimal', 'Decimal', ({(230, 29, 230, 30): '(3)'}, {}), '(3)', False, 'from decimal import Decimal\n'), ((230, 34, 230, 44), 'decimal.Decimal', 'Decimal', ({(230, 42, 230, 43): '(8)'}, {}), '(8)', False, 'from decimal import Decimal\n'), ((231, 23, 231, 33), 'decimal.Decimal', 'Decimal', ({(231, 31, 231, 32): '(1)'}, {}), '(1)', False, 'from decimal import Decimal\n'), ((231, 36, 231, 46), 'decimal.Decimal', 'Decimal', ({(231, 44, 231, 45): '(8)'}, {}), '(8)', False, 'from decimal import Decimal\n'), ((231, 63, 231, 73), 'decimal.Decimal', 'Decimal', ({(231, 71, 231, 72): '(2)'}, {}), '(2)', False, 'from decimal import Decimal\n'), ((231, 76, 231, 86), 'decimal.Decimal', 'Decimal', ({(231, 84, 231, 85): '(8)'}, {}), '(8)', False, 'from decimal import Decimal\n')]
chengzhag/DeepPanoContext
external/pyTorchChamferDistance/chamfer_distance/__init__.py
14f847e51ec2bd08e0fc178dd1640541752addb7
import os os.makedirs(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'build')), exist_ok=True) from .chamfer_distance import ChamferDistance
[((2, 41, 2, 66), 'os.path.dirname', 'os.path.dirname', ({(2, 57, 2, 65): '__file__'}, {}), '(__file__)', False, 'import os\n')]
georg-wolflein/impartial
test_impartial.py
a53819cefcb74a57e3c1148a6b8fa88aed9264d4
from functools import partial from impartial import impartial def f(x: int, y: int, z: int = 0) -> int: return x + 2*y + z def test_simple_call_args(): assert impartial(f, 1)(2) == f(1, 2) def test_simple_call_kwargs(): assert impartial(f, y=2)(x=1) == f(1, 2) def test_simple_call_empty(): assert impartial(f, 1, y=2)() == f(1, 2) def test_decorator(): @impartial def f(x, y): return x + 2*y assert f.with_y(2)(1) == 5 def test_func(): assert impartial(f, 1).func is f def test_with_kwargs(): assert impartial(f, 1).with_z(3)(2) == f(1, 2, 3) def test_multiple_with_kwargs(): assert impartial(f, 1).with_z(3).with_y(2)() == f(1, 2, 3) def test_with_kwargs_override(): assert impartial(f, 1, 2).with_z(3).with_z(4)() == f(1, 2, 4) def test_nested_impartial(): imp = impartial(f, x=1, y=2) imp = impartial(imp, x=2) imp = impartial(imp, x=3) assert imp() == f(3, 2) assert not isinstance(imp.func, impartial) assert imp.func is f def test_nested_partial(): imp = partial(f, x=1, y=2) imp = partial(imp, x=2) imp = impartial(imp, x=3) assert imp() == f(3, 2) assert not isinstance(imp.func, partial) assert imp.func is f def test_configure(): assert impartial(f, 1, z=2).configure(2, z=3)() == f(1, 2, 3)
[((46, 10, 46, 32), 'impartial.impartial', 'impartial', (), '', False, 'from impartial import impartial\n'), ((47, 10, 47, 29), 'impartial.impartial', 'impartial', (), '', False, 'from impartial import impartial\n'), ((48, 10, 48, 29), 'impartial.impartial', 'impartial', (), '', False, 'from impartial import impartial\n'), ((55, 10, 55, 30), 'functools.partial', 'partial', (), '', False, 'from functools import partial\n'), ((56, 10, 56, 27), 'functools.partial', 'partial', (), '', False, 'from functools import partial\n'), ((57, 10, 57, 29), 'impartial.impartial', 'impartial', (), '', False, 'from impartial import impartial\n'), ((11, 11, 11, 26), 'impartial.impartial', 'impartial', ({(11, 21, 11, 22): 'f', (11, 24, 11, 25): '(1)'}, {}), '(f, 1)', False, 'from impartial import impartial\n'), ((15, 11, 15, 28), 'impartial.impartial', 'impartial', (), '', False, 'from impartial import impartial\n'), ((19, 11, 19, 31), 'impartial.impartial', 'impartial', (), '', False, 'from impartial import impartial\n'), ((30, 11, 30, 26), 'impartial.impartial', 'impartial', ({(30, 21, 30, 22): 'f', (30, 24, 30, 25): '(1)'}, {}), '(f, 1)', False, 'from impartial import impartial\n'), ((34, 11, 34, 26), 'impartial.impartial', 'impartial', ({(34, 21, 34, 22): 'f', (34, 24, 34, 25): '(1)'}, {}), '(f, 1)', False, 'from impartial import impartial\n'), ((64, 11, 64, 31), 'impartial.impartial', 'impartial', (), '', False, 'from impartial import impartial\n'), ((38, 11, 38, 26), 'impartial.impartial', 'impartial', ({(38, 21, 38, 22): 'f', (38, 24, 38, 25): '(1)'}, {}), '(f, 1)', False, 'from impartial import impartial\n'), ((42, 11, 42, 29), 'impartial.impartial', 'impartial', ({(42, 21, 42, 22): 'f', (42, 24, 42, 25): '(1)', (42, 27, 42, 28): '(2)'}, {}), '(f, 1, 2)', False, 'from impartial import impartial\n')]
smilechaser/screeps-script-caddy
manager.py
11b6e809675dfd0a5a4ff917a492adc4a5a08bca
''' Python script for uploading/downloading scripts for use with the game Screeps. http://support.screeps.com/hc/en-us/articles/203022612-Commiting-scripts-using-direct-API-access Usage: # # general help/usage # python3 manager.py --help # # retrieve all scripts from the game and store them # in the folder "some_folder" # python3 manager.py from_game some_folder # # send all *.js files to the game # python3 manager.py to_game some_folder WARNING: Use at your own risk! Make backups of all your game content! ''' import sys import os import argparse import json import requests from requests.auth import HTTPBasicAuth SCREEPS_ENDPOINT = 'https://screeps.com/api/user/code' USER_ENV = 'SCREEPS_USER' PASSWORD_ENV = 'SCREEPS_PASSWORD' TO_SCREEPS = 'to_game' FROM_SCREEPS = 'from_game' def get_user_from_env(): user = os.environ.get('SCREEPS_USER') if not user: print('You must provide a username, i.e. export ' '{}=<your email address>'. format(USER_ENV)) sys.exit() return user def get_password_from_env(): password = os.environ.get('SCREEPS_PASSWORD') if not password: print('You must provide a password, i.e. export {}=<your password>'. format(PASSWORD_ENV)) sys.exit() return password def get_data(user, password): print('Retrieving data...') response = requests.get(SCREEPS_ENDPOINT, auth=HTTPBasicAuth(user, password)) response.raise_for_status() data = response.json() if data['ok'] != 1: raise Exception() return data def send_data(user, password, modules): auth = HTTPBasicAuth(user, password) headers = {'Content-Type': 'application/json; charset=utf-8'} data = {'modules': modules} resp = requests.post(SCREEPS_ENDPOINT, data=json.dumps(data), headers=headers, auth=auth) resp.raise_for_status() def check_for_collisions(target_folder, modules): for module in modules: target = os.path.join(target_folder, '{}.js'.format(module)) if os.path.exists(target): print('File {} exists.'.format(target)) print('Specify --force to overwrite. Aborting...') sys.exit() def main(): parser = argparse.ArgumentParser(description='') parser.add_argument('operation', choices=(TO_SCREEPS, FROM_SCREEPS), help='') parser.add_argument('destination', help='') parser.add_argument('--user', help='') parser.add_argument('--password', help='') parser.add_argument('--force', action='store_const', const=True, help='force overwrite of files in an existing folder') parser.add_argument('--merge', action='store_const', const=True, help='merge scripts into a single main.js module') args = parser.parse_args() user = args.user if args.user else get_user_from_env() password = args.password if args.password else get_password_from_env() target_folder = os.path.abspath(args.destination) if args.operation == FROM_SCREEPS: data = get_data(user, password) # does the folder exist? if not os.path.isdir(target_folder): # no - create it print('Creating new folder "{}"...'.format(target_folder)) os.makedirs(target_folder) else: # yes - check for collisions (unless --force was specified) if not args.force: print('Checking for collisions...') check_for_collisions(target_folder, data['modules']) print('Ok, no collisions.') # for each module, create a corresponding filename and put it in # the target folder for module in data['modules']: target = os.path.join(target_folder, '{}.js'.format(module)) with open(target, 'w') as fout: fout.write(data['modules'][module]) else: modules = {} for root, folders, files in os.walk(target_folder): folders[:] = [] for target_file in files: name, ext = os.path.splitext(target_file) if ext != '.js': continue with open(os.path.join(root, target_file), 'r') as fin: modules[name] = fin.read() if args.merge: merge_modules(modules) # upload modules send_data(user, password, modules) def generate_header(filename): return ''' // {border} // {name} // {border} '''.format(border='-' * 25, name=filename) def merge_modules(modules): keys = [x for x in modules.keys()] keys.sort() merged = '' for key in keys: merged = merged + generate_header(key) + modules[key] del(modules[key]) modules['main.js'] = merged if __name__ == '__main__': main()
[((50, 11, 50, 41), 'os.environ.get', 'os.environ.get', ({(50, 26, 50, 40): '"""SCREEPS_USER"""'}, {}), "('SCREEPS_USER')", False, 'import os\n'), ((63, 15, 63, 49), 'os.environ.get', 'os.environ.get', ({(63, 30, 63, 48): '"""SCREEPS_PASSWORD"""'}, {}), "('SCREEPS_PASSWORD')", False, 'import os\n'), ((92, 11, 92, 40), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', ({(92, 25, 92, 29): 'user', (92, 31, 92, 39): 'password'}, {}), '(user, password)', False, 'from requests.auth import HTTPBasicAuth\n'), ((120, 13, 120, 52), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (), '', False, 'import argparse\n'), ((137, 20, 137, 53), 'os.path.abspath', 'os.path.abspath', ({(137, 36, 137, 52): 'args.destination'}, {}), '(args.destination)', False, 'import os\n'), ((56, 8, 56, 18), 'sys.exit', 'sys.exit', ({}, {}), '()', False, 'import sys\n'), ((68, 8, 68, 18), 'sys.exit', 'sys.exit', ({}, {}), '()', False, 'import sys\n'), ((111, 11, 111, 33), 'os.path.exists', 'os.path.exists', ({(111, 26, 111, 32): 'target'}, {}), '(target)', False, 'import os\n'), ((176, 36, 176, 58), 'os.walk', 'os.walk', ({(176, 44, 176, 57): 'target_folder'}, {}), '(target_folder)', False, 'import os\n'), ((78, 33, 78, 62), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', ({(78, 47, 78, 51): 'user', (78, 53, 78, 61): 'password'}, {}), '(user, password)', False, 'from requests.auth import HTTPBasicAuth\n'), ((98, 30, 98, 46), 'json.dumps', 'json.dumps', ({(98, 41, 98, 45): 'data'}, {}), '(data)', False, 'import json\n'), ((115, 12, 115, 22), 'sys.exit', 'sys.exit', ({}, {}), '()', False, 'import sys\n'), ((144, 15, 144, 43), 'os.path.isdir', 'os.path.isdir', ({(144, 29, 144, 42): 'target_folder'}, {}), '(target_folder)', False, 'import os\n'), ((149, 12, 149, 38), 'os.makedirs', 'os.makedirs', ({(149, 24, 149, 37): 'target_folder'}, {}), '(target_folder)', False, 'import os\n'), ((182, 28, 182, 57), 'os.path.splitext', 'os.path.splitext', ({(182, 45, 182, 56): 'target_file'}, {}), '(target_file)', False, 'import os\n'), ((187, 26, 187, 57), 'os.path.join', 'os.path.join', ({(187, 39, 187, 43): 'root', (187, 45, 187, 56): 'target_file'}, {}), '(root, target_file)', False, 'import os\n')]
Nemfeto/python_training
contact.py
4d04f07700da4b0d5b50736ba197ad85fd2ee549
class Contact: def __init__(self, first_name, last_name, nickname, address, mobile, email): self.first_name = first_name self.last_name = last_name self.nickname = nickname self.address = address self.mobile = mobile self.email = email
[]
Integreat/cms-v2
integreat_cms/cms/views/dashboard/admin_dashboard_view.py
c79a54fd5abb792696420aa6427a5e5a356fa79c
import logging from django.views.generic import TemplateView from ...models import Feedback from ..chat.chat_context_mixin import ChatContextMixin logger = logging.getLogger(__name__) class AdminDashboardView(TemplateView, ChatContextMixin): """ View for the admin dashboard """ #: The template to render (see :class:`~django.views.generic.base.TemplateResponseMixin`) template_name = "dashboard/admin_dashboard.html" #: The context dict passed to the template (see :class:`~django.views.generic.base.ContextMixin`) extra_context = {"current_menu_item": "admin_dashboard"} def get_context_data(self, **kwargs): r""" Returns a dictionary representing the template context (see :meth:`~django.views.generic.base.ContextMixin.get_context_data`). :param \**kwargs: The given keyword arguments :type \**kwargs: dict :return: The template context :rtype: dict """ context = super().get_context_data(**kwargs) context["admin_feedback"] = Feedback.objects.filter( is_technical=True, read_by=None )[:5] return context
[((8, 9, 8, 36), 'logging.getLogger', 'logging.getLogger', ({(8, 27, 8, 35): '__name__'}, {}), '(__name__)', False, 'import logging\n')]
bhumikapahariapuresoftware/tangled-up-in-unicode
src/tangled_up_in_unicode/tangled_up_in_unicode_14_0_0.py
ee052e6f0fd4a0083178a163ec72dc37e2ad5d59
from typing import Optional import bisect from tangled_up_in_unicode.u14_0_0_data.prop_list_to_property import prop_list_to_property from tangled_up_in_unicode.u14_0_0_data.blocks_to_block_start import blocks_to_block_start from tangled_up_in_unicode.u14_0_0_data.blocks_to_block_end import blocks_to_block_end from tangled_up_in_unicode.u14_0_0_data.property_value_alias_age_short_to_long import property_value_alias_age_short_to_long from tangled_up_in_unicode.u14_0_0_data.property_value_alias_bc_short_to_long import property_value_alias_bc_short_to_long from tangled_up_in_unicode.u14_0_0_data.property_value_alias_blk_long_to_short import property_value_alias_blk_long_to_short from tangled_up_in_unicode.u14_0_0_data.property_value_alias_ccc_short_to_long import property_value_alias_ccc_short_to_long from tangled_up_in_unicode.u14_0_0_data.property_value_alias_ea_short_to_long import property_value_alias_ea_short_to_long from tangled_up_in_unicode.u14_0_0_data.property_value_alias_gc_short_to_long import property_value_alias_gc_short_to_long from tangled_up_in_unicode.u14_0_0_data.property_value_alias_sc_long_to_short import property_value_alias_sc_long_to_short from tangled_up_in_unicode.u14_0_0_data.scripts_to_script_start import scripts_to_script_start from tangled_up_in_unicode.u14_0_0_data.scripts_to_script_end import scripts_to_script_end from tangled_up_in_unicode.u14_0_0_data.east_asian_width_to_east_asian_width_start import east_asian_width_to_east_asian_width_start from tangled_up_in_unicode.u14_0_0_data.east_asian_width_to_east_asian_width_end import east_asian_width_to_east_asian_width_end from tangled_up_in_unicode.u14_0_0_data.derived_age_to_age_start import derived_age_to_age_start from tangled_up_in_unicode.u14_0_0_data.derived_age_to_age_end import derived_age_to_age_end from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_name_start import unicode_data_to_name_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_category_start import unicode_data_to_category_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_category_end import unicode_data_to_category_end from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_bidirectional_start import unicode_data_to_bidirectional_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_bidirectional_end import unicode_data_to_bidirectional_end from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_decimal_start import unicode_data_to_decimal_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_digit_start import unicode_data_to_digit_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_numeric_start import unicode_data_to_numeric_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_combining_start import unicode_data_to_combining_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_mirrored_start import unicode_data_to_mirrored_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_mirrored_end import unicode_data_to_mirrored_end from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_decomposition_start import unicode_data_to_decomposition_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_uppercase_start import unicode_data_to_uppercase_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_lowercase_start import unicode_data_to_lowercase_start from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_titlecase_start import unicode_data_to_titlecase_start unidata_version = "14.0.0" def name(chr: str, default=None) -> str: """Returns the name assigned to the character chr as a string. If no name is defined, default is returned, or, if not given, ValueError is raised.""" idx = ord(chr) try: return unicode_data_to_name_start[idx] except KeyError: if default is None: raise ValueError("no such name") else: return default def category(chr: str) -> str: """Returns the general category assigned to the character chr as string.""" idx = ord(chr) start_keys = sorted(unicode_data_to_category_start.keys()) insertion_point = bisect.bisect_left(start_keys, idx) if insertion_point == len(start_keys) or start_keys[insertion_point] != idx: insertion_point -= 1 key_start = start_keys[insertion_point] result_start = unicode_data_to_category_start[key_start] end_keys = sorted(unicode_data_to_category_end.keys()) insertion_point = bisect.bisect_left(end_keys, idx) try: key_end = end_keys[insertion_point] result_end = unicode_data_to_category_end[key_end] if result_end != key_start: result_end = result_start key_end = key_start else: result_end = unicode_data_to_category_start[result_end] if key_start <= idx <= key_end and result_start == result_end: return result_start else: return "Zzzz" except IndexError: return "Zzzz" def bidirectional(chr: str) -> str: """Returns the bidirectional class assigned to the character chr as string. If no such value is defined, an empty string is returned.""" idx = ord(chr) start_keys = sorted(unicode_data_to_bidirectional_start.keys()) insertion_point = bisect.bisect_left(start_keys, idx) if insertion_point == len(start_keys) or start_keys[insertion_point] != idx: insertion_point -= 1 key_start = start_keys[insertion_point] result_start = unicode_data_to_bidirectional_start[key_start] end_keys = sorted(unicode_data_to_bidirectional_end.keys()) insertion_point = bisect.bisect_left(end_keys, idx) try: key_end = end_keys[insertion_point] result_end = unicode_data_to_bidirectional_end[key_end] if result_end != key_start: result_end = result_start key_end = key_start else: result_end = unicode_data_to_bidirectional_start[result_end] if key_start <= idx <= key_end and result_start == result_end: return result_start else: return "" except IndexError: return "" def decimal(chr: str, default=None) -> int: """Returns the decimal value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.""" idx = ord(chr) try: return unicode_data_to_decimal_start[idx] except KeyError: if default is None: raise ValueError("not a decimal") else: return default def digit(chr: str, default=None) -> int: """Returns the digit value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.""" idx = ord(chr) try: return unicode_data_to_digit_start[idx] except KeyError: if default is None: raise ValueError("not a digit") else: return default def numeric(chr: str, default=None) -> float: """Returns the numeric value assigned to the character chr as float. If no such value is defined, default is returned, or, if not given, ValueError is raised.""" idx = ord(chr) try: return unicode_data_to_numeric_start[idx] except KeyError: if default is None: raise ValueError("not a numeric character") else: return default def combining(chr: str) -> int: """Returns the canonical combining class assigned to the character chr as integer. Returns 0 if no combining class is defined.""" idx = ord(chr) try: return unicode_data_to_combining_start[idx] except KeyError: return 0 def mirrored(chr: str) -> int: """Returns the mirrored property assigned to the character chr as integer. Returns 1 if the character has been identified as a "mirrored" character in bidirectional text, 0 otherwise.""" idx = ord(chr) start_keys = sorted(unicode_data_to_mirrored_start.keys()) insertion_point = bisect.bisect_left(start_keys, idx) if insertion_point == len(start_keys) or start_keys[insertion_point] != idx: insertion_point -= 1 key_start = start_keys[insertion_point] result_start = unicode_data_to_mirrored_start[key_start] end_keys = sorted(unicode_data_to_mirrored_end.keys()) insertion_point = bisect.bisect_left(end_keys, idx) try: key_end = end_keys[insertion_point] result_end = unicode_data_to_mirrored_end[key_end] if result_end != key_start: result_end = result_start key_end = key_start else: result_end = unicode_data_to_mirrored_start[result_end] if key_start <= idx <= key_end and result_start == result_end: return result_start else: return 0 except IndexError: return 0 def decomposition(chr: str) -> str: """Returns the character decomposition mapping assigned to the character chr as string. An empty string is returned in case no such mapping is defined.""" idx = ord(chr) try: return unicode_data_to_decomposition_start[idx] except KeyError: return "" def uppercase(chr: str) -> str: """""" idx = ord(chr) try: return unicode_data_to_uppercase_start[idx] except KeyError: return "" def lowercase(chr: str) -> str: """""" idx = ord(chr) try: return unicode_data_to_lowercase_start[idx] except KeyError: return "" def titlecase(chr: str) -> str: """""" idx = ord(chr) try: return unicode_data_to_titlecase_start[idx] except KeyError: return "" def east_asian_width(chr: str, default=None) -> str: """Returns the east asian width assigned to the character chr as string.""" idx = ord(chr) start_keys = sorted(east_asian_width_to_east_asian_width_start.keys()) insertion_point = bisect.bisect_left(start_keys, idx) if insertion_point == len(start_keys) or start_keys[insertion_point] != idx: insertion_point -= 1 key_start = start_keys[insertion_point] result_start = east_asian_width_to_east_asian_width_start[key_start] end_keys = sorted(east_asian_width_to_east_asian_width_end.keys()) insertion_point = bisect.bisect_left(end_keys, idx) key_end = end_keys[insertion_point] result_end = east_asian_width_to_east_asian_width_end[key_end] if result_end != key_start: result_end = result_start key_end = key_start else: result_end = east_asian_width_to_east_asian_width_start[result_end] if key_start <= idx <= key_end and result_start == result_end: return result_start else: if default is None: raise ValueError("no east asian width") else: return default def age(chr: str) -> str: """""" idx = ord(chr) start_keys = sorted(derived_age_to_age_start.keys()) insertion_point = bisect.bisect_left(start_keys, idx) if insertion_point == len(start_keys) or start_keys[insertion_point] != idx: insertion_point -= 1 key_start = start_keys[insertion_point] result_start = derived_age_to_age_start[key_start] end_keys = sorted(derived_age_to_age_end.keys()) insertion_point = bisect.bisect_left(end_keys, idx) try: key_end = end_keys[insertion_point] result_end = derived_age_to_age_end[key_end] if result_end != key_start: result_end = result_start key_end = key_start else: result_end = derived_age_to_age_start[result_end] if key_start <= idx <= key_end and result_start == result_end: return result_start else: return "1.0" except IndexError: return "1.0" def block(chr: str) -> str: """""" idx = ord(chr) start_keys = sorted(blocks_to_block_start.keys()) insertion_point = bisect.bisect_left(start_keys, idx) if insertion_point == len(start_keys) or start_keys[insertion_point] != idx: insertion_point -= 1 key_start = start_keys[insertion_point] result_start = blocks_to_block_start[key_start] end_keys = sorted(blocks_to_block_end.keys()) insertion_point = bisect.bisect_left(end_keys, idx) try: key_end = end_keys[insertion_point] result_end = blocks_to_block_end[key_end] if result_end != key_start: result_end = result_start key_end = key_start else: result_end = blocks_to_block_start[result_end] if key_start <= idx <= key_end and result_start == result_end: return result_start else: return "Unknown" except IndexError: return "Unknown" def script(chr: str) -> str: """""" idx = ord(chr) start_keys = sorted(scripts_to_script_start.keys()) insertion_point = bisect.bisect_left(start_keys, idx) if insertion_point == len(start_keys) or start_keys[insertion_point] != idx: insertion_point -= 1 key_start = start_keys[insertion_point] result_start = scripts_to_script_start[key_start] end_keys = sorted(scripts_to_script_end.keys()) insertion_point = bisect.bisect_left(end_keys, idx) try: key_end = end_keys[insertion_point] result_end = scripts_to_script_end[key_end] if result_end != key_start: result_end = result_start key_end = key_start else: result_end = scripts_to_script_start[result_end] if key_start <= idx <= key_end and result_start == result_end: return result_start else: return "Unknown" except IndexError: return "Unknown" def prop_list(chr: str) -> list: """""" idx = ord(chr) try: return prop_list_to_property[idx] except KeyError: return set() def age_long(value: str) -> Optional[str]: """""" try: return property_value_alias_age_short_to_long[value] except KeyError: return None def category_long(value: str) -> Optional[str]: """""" try: return property_value_alias_gc_short_to_long[value] except KeyError: return None def east_asian_width_long(value: str) -> Optional[str]: """""" try: return property_value_alias_ea_short_to_long[value] except KeyError: return None def bidirectional_long(value: str) -> Optional[str]: """""" try: return property_value_alias_bc_short_to_long[value] except KeyError: return None def combining_long(value: str) -> Optional[str]: """""" try: return property_value_alias_ccc_short_to_long[value] except KeyError: return None def block_abbr(value: str) -> Optional[str]: """""" try: return property_value_alias_blk_long_to_short[value] except KeyError: return None def script_abbr(value: str) -> Optional[str]: """""" try: return property_value_alias_sc_long_to_short[value] except KeyError: return None
[((57, 22, 57, 57), 'bisect.bisect_left', 'bisect.bisect_left', ({(57, 41, 57, 51): 'start_keys', (57, 53, 57, 56): 'idx'}, {}), '(start_keys, idx)', False, 'import bisect\n'), ((64, 22, 64, 55), 'bisect.bisect_left', 'bisect.bisect_left', ({(64, 41, 64, 49): 'end_keys', (64, 51, 64, 54): 'idx'}, {}), '(end_keys, idx)', False, 'import bisect\n'), ((88, 22, 88, 57), 'bisect.bisect_left', 'bisect.bisect_left', ({(88, 41, 88, 51): 'start_keys', (88, 53, 88, 56): 'idx'}, {}), '(start_keys, idx)', False, 'import bisect\n'), ((95, 22, 95, 55), 'bisect.bisect_left', 'bisect.bisect_left', ({(95, 41, 95, 49): 'end_keys', (95, 51, 95, 54): 'idx'}, {}), '(end_keys, idx)', False, 'import bisect\n'), ((168, 22, 168, 57), 'bisect.bisect_left', 'bisect.bisect_left', ({(168, 41, 168, 51): 'start_keys', (168, 53, 168, 56): 'idx'}, {}), '(start_keys, idx)', False, 'import bisect\n'), ((175, 22, 175, 55), 'bisect.bisect_left', 'bisect.bisect_left', ({(175, 41, 175, 49): 'end_keys', (175, 51, 175, 54): 'idx'}, {}), '(end_keys, idx)', False, 'import bisect\n'), ((235, 22, 235, 57), 'bisect.bisect_left', 'bisect.bisect_left', ({(235, 41, 235, 51): 'start_keys', (235, 53, 235, 56): 'idx'}, {}), '(start_keys, idx)', False, 'import bisect\n'), ((242, 22, 242, 55), 'bisect.bisect_left', 'bisect.bisect_left', ({(242, 41, 242, 49): 'end_keys', (242, 51, 242, 54): 'idx'}, {}), '(end_keys, idx)', False, 'import bisect\n'), ((265, 22, 265, 57), 'bisect.bisect_left', 'bisect.bisect_left', ({(265, 41, 265, 51): 'start_keys', (265, 53, 265, 56): 'idx'}, {}), '(start_keys, idx)', False, 'import bisect\n'), ((272, 22, 272, 55), 'bisect.bisect_left', 'bisect.bisect_left', ({(272, 41, 272, 49): 'end_keys', (272, 51, 272, 54): 'idx'}, {}), '(end_keys, idx)', False, 'import bisect\n'), ((295, 22, 295, 57), 'bisect.bisect_left', 'bisect.bisect_left', ({(295, 41, 295, 51): 'start_keys', (295, 53, 295, 56): 'idx'}, {}), '(start_keys, idx)', False, 'import bisect\n'), ((302, 22, 302, 55), 'bisect.bisect_left', 'bisect.bisect_left', ({(302, 41, 302, 49): 'end_keys', (302, 51, 302, 54): 'idx'}, {}), '(end_keys, idx)', False, 'import bisect\n'), ((325, 22, 325, 57), 'bisect.bisect_left', 'bisect.bisect_left', ({(325, 41, 325, 51): 'start_keys', (325, 53, 325, 56): 'idx'}, {}), '(start_keys, idx)', False, 'import bisect\n'), ((332, 22, 332, 55), 'bisect.bisect_left', 'bisect.bisect_left', ({(332, 41, 332, 49): 'end_keys', (332, 51, 332, 54): 'idx'}, {}), '(end_keys, idx)', False, 'import bisect\n'), ((56, 24, 56, 61), 'tangled_up_in_unicode.u14_0_0_data.unicode_data_to_category_start.unicode_data_to_category_start.keys', 'unicode_data_to_category_start.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_category_start import unicode_data_to_category_start\n'), ((63, 22, 63, 57), 'tangled_up_in_unicode.u14_0_0_data.unicode_data_to_category_end.unicode_data_to_category_end.keys', 'unicode_data_to_category_end.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_category_end import unicode_data_to_category_end\n'), ((87, 24, 87, 66), 'tangled_up_in_unicode.u14_0_0_data.unicode_data_to_bidirectional_start.unicode_data_to_bidirectional_start.keys', 'unicode_data_to_bidirectional_start.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_bidirectional_start import unicode_data_to_bidirectional_start\n'), ((94, 22, 94, 62), 'tangled_up_in_unicode.u14_0_0_data.unicode_data_to_bidirectional_end.unicode_data_to_bidirectional_end.keys', 'unicode_data_to_bidirectional_end.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_bidirectional_end import unicode_data_to_bidirectional_end\n'), ((167, 24, 167, 61), 'tangled_up_in_unicode.u14_0_0_data.unicode_data_to_mirrored_start.unicode_data_to_mirrored_start.keys', 'unicode_data_to_mirrored_start.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_mirrored_start import unicode_data_to_mirrored_start\n'), ((174, 22, 174, 57), 'tangled_up_in_unicode.u14_0_0_data.unicode_data_to_mirrored_end.unicode_data_to_mirrored_end.keys', 'unicode_data_to_mirrored_end.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.unicode_data_to_mirrored_end import unicode_data_to_mirrored_end\n'), ((234, 24, 234, 73), 'tangled_up_in_unicode.u14_0_0_data.east_asian_width_to_east_asian_width_start.east_asian_width_to_east_asian_width_start.keys', 'east_asian_width_to_east_asian_width_start.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.east_asian_width_to_east_asian_width_start import east_asian_width_to_east_asian_width_start\n'), ((241, 22, 241, 69), 'tangled_up_in_unicode.u14_0_0_data.east_asian_width_to_east_asian_width_end.east_asian_width_to_east_asian_width_end.keys', 'east_asian_width_to_east_asian_width_end.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.east_asian_width_to_east_asian_width_end import east_asian_width_to_east_asian_width_end\n'), ((264, 24, 264, 55), 'tangled_up_in_unicode.u14_0_0_data.derived_age_to_age_start.derived_age_to_age_start.keys', 'derived_age_to_age_start.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.derived_age_to_age_start import derived_age_to_age_start\n'), ((271, 22, 271, 51), 'tangled_up_in_unicode.u14_0_0_data.derived_age_to_age_end.derived_age_to_age_end.keys', 'derived_age_to_age_end.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.derived_age_to_age_end import derived_age_to_age_end\n'), ((294, 24, 294, 52), 'tangled_up_in_unicode.u14_0_0_data.blocks_to_block_start.blocks_to_block_start.keys', 'blocks_to_block_start.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.blocks_to_block_start import blocks_to_block_start\n'), ((301, 22, 301, 48), 'tangled_up_in_unicode.u14_0_0_data.blocks_to_block_end.blocks_to_block_end.keys', 'blocks_to_block_end.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.blocks_to_block_end import blocks_to_block_end\n'), ((324, 24, 324, 54), 'tangled_up_in_unicode.u14_0_0_data.scripts_to_script_start.scripts_to_script_start.keys', 'scripts_to_script_start.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.scripts_to_script_start import scripts_to_script_start\n'), ((331, 22, 331, 50), 'tangled_up_in_unicode.u14_0_0_data.scripts_to_script_end.scripts_to_script_end.keys', 'scripts_to_script_end.keys', ({}, {}), '()', False, 'from tangled_up_in_unicode.u14_0_0_data.scripts_to_script_end import scripts_to_script_end\n')]
namib-project/weatherstation-image
to_display.py
ae6a11943bfd21135bf0ce5d113865b69c58bbe2
from PIL import Image from PIL import ImageDraw from PIL import ImageFont import sys import ST7735 # Create ST7735 LCD display class object and set pin numbers and display hardware information. disp = ST7735.ST7735( dc=24, cs=ST7735.BG_SPI_CS_BACK, rst=25, port=0, width=122, height=160, rotation=270 ) # Initialize display. disp.begin() WIDTH = disp.width HEIGHT = disp.height img = Image.new('RGB', (WIDTH, HEIGHT), color=(0, 0, 0)) draw = ImageDraw.Draw(img) font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", 12) # Initialize a secondary text with the empty string text2 = "" # Print test-output on the display if n oargument is given if len(sys.argv) == 1: text = "Temperature:\nHumidity:\nUV:\nRain:\nLight:" text2 = "20°C\n50 %\n42\nyes\nOn" # Print the argument if only one is given elif len(sys.argv) == 2: text = sys.argv[1] # If 2 arguments are given use the second as the secondary text elif len(sys.argv) == 3: text = sys.argv[1] text2 = sys.argv[2] # For any other number of arguments draw them in one line each else: text = ''.join(i + "\n" for i in sys.argv[1:]) # Print both texts, with the secondary one starting with an 100 px offset draw.text((10, 10), text, font=font, fill=(255, 255, 255)) draw.text((110, 10), text2, font=font, fill=(255, 255, 255)) disp.display(img)
[((9, 7, 17, 1), 'ST7735.ST7735', 'ST7735.ST7735', (), '', False, 'import ST7735\n'), ((25, 6, 25, 56), 'PIL.Image.new', 'Image.new', (), '', False, 'from PIL import Image\n'), ((27, 7, 27, 26), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', ({(27, 22, 27, 25): 'img'}, {}), '(img)', False, 'from PIL import ImageDraw\n'), ((29, 7, 29, 96), 'PIL.ImageFont.truetype', 'ImageFont.truetype', ({(29, 26, 29, 91): '"""/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf"""', (29, 93, 29, 95): '12'}, {}), "(\n '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf', 12)", False, 'from PIL import ImageFont\n')]
saransh808/Projects
Smart User Targeted Advertising/MinorPro/FINALPROJECT/Resources/testInsert.py
7449ed6b53900ebb16a9084cff389cc50f3c9f6c
import sqlite3 conn=sqlite3.connect('Survey.db') fo=open('insertcommand.txt') str=fo.readline() while str: str="INSERT INTO data VALUES"+str conn.execute(str) #print(str) str=fo.readline() conn.commit() conn.close() fo.close()
[((3, 5, 3, 33), 'sqlite3.connect', 'sqlite3.connect', ({(3, 21, 3, 32): '"""Survey.db"""'}, {}), "('Survey.db')", False, 'import sqlite3\n')]
HyperionGray/python-chrome-devtools-protocol
cdp/headless_experimental.py
5463a5f3d20100255c932961b944e4b37dbb7e61
# DO NOT EDIT THIS FILE! # # This file is generated from the CDP specification. If you need to make # changes, edit the generator and regenerate all of the modules. # # CDP domain: HeadlessExperimental (experimental) from __future__ import annotations from cdp.util import event_class, T_JSON_DICT from dataclasses import dataclass import enum import typing @dataclass class ScreenshotParams: ''' Encoding options for a screenshot. ''' #: Image compression format (defaults to png). format_: typing.Optional[str] = None #: Compression quality from range [0..100] (jpeg only). quality: typing.Optional[int] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() if self.format_ is not None: json['format'] = self.format_ if self.quality is not None: json['quality'] = self.quality return json @classmethod def from_json(cls, json: T_JSON_DICT) -> ScreenshotParams: return cls( format_=str(json['format']) if 'format' in json else None, quality=int(json['quality']) if 'quality' in json else None, ) def begin_frame( frame_time_ticks: typing.Optional[float] = None, interval: typing.Optional[float] = None, no_display_updates: typing.Optional[bool] = None, screenshot: typing.Optional[ScreenshotParams] = None ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,typing.Tuple[bool, typing.Optional[str]]]: ''' Sends a BeginFrame to the target and returns when the frame was completed. Optionally captures a screenshot from the resulting frame. Requires that the target was created with enabled BeginFrameControl. Designed for use with --run-all-compositor-stages-before-draw, see also https://goo.gl/3zHXhB for more background. :param frame_time_ticks: *(Optional)* Timestamp of this BeginFrame in Renderer TimeTicks (milliseconds of uptime). If not set, the current time will be used. :param interval: *(Optional)* The interval between BeginFrames that is reported to the compositor, in milliseconds. Defaults to a 60 frames/second interval, i.e. about 16.666 milliseconds. :param no_display_updates: *(Optional)* Whether updates should not be committed and drawn onto the display. False by default. If true, only side effects of the BeginFrame will be run, such as layout and animations, but any visual updates may not be visible on the display or in screenshots. :param screenshot: *(Optional)* If set, a screenshot of the frame will be captured and returned in the response. Otherwise, no screenshot will be captured. Note that capturing a screenshot can fail, for example, during renderer initialization. In such a case, no screenshot data will be returned. :returns: A tuple with the following items: 0. **hasDamage** - Whether the BeginFrame resulted in damage and, thus, a new frame was committed to the display. Reported for diagnostic uses, may be removed in the future. 1. **screenshotData** - *(Optional)* Base64-encoded image data of the screenshot, if one was requested and successfully taken. ''' params: T_JSON_DICT = dict() if frame_time_ticks is not None: params['frameTimeTicks'] = frame_time_ticks if interval is not None: params['interval'] = interval if no_display_updates is not None: params['noDisplayUpdates'] = no_display_updates if screenshot is not None: params['screenshot'] = screenshot.to_json() cmd_dict: T_JSON_DICT = { 'method': 'HeadlessExperimental.beginFrame', 'params': params, } json = yield cmd_dict return ( bool(json['hasDamage']), str(json['screenshotData']) if 'screenshotData' in json else None ) def disable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: ''' Disables headless events for the target. ''' cmd_dict: T_JSON_DICT = { 'method': 'HeadlessExperimental.disable', } json = yield cmd_dict def enable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: ''' Enables headless events for the target. ''' cmd_dict: T_JSON_DICT = { 'method': 'HeadlessExperimental.enable', } json = yield cmd_dict @event_class('HeadlessExperimental.needsBeginFramesChanged') @dataclass class NeedsBeginFramesChanged: ''' Issued when the target starts or stops needing BeginFrames. ''' #: True if BeginFrames are needed, false otherwise. needs_begin_frames: bool @classmethod def from_json(cls, json: T_JSON_DICT) -> NeedsBeginFramesChanged: return cls( needs_begin_frames=bool(json['needsBeginFrames']) )
[((103, 1, 103, 60), 'cdp.util.event_class', 'event_class', ({(103, 13, 103, 59): '"""HeadlessExperimental.needsBeginFramesChanged"""'}, {}), "('HeadlessExperimental.needsBeginFramesChanged')", False, 'from cdp.util import event_class, T_JSON_DICT\n')]
resurtm/wvflib
tests/test_geometry.py
106f426cc2c63c8d21f3e0ec1b90b06450dfc547
import unittest from wvflib.geometry import Face class TestGeometry(unittest.TestCase): def test_constructor(self): f = Face() self.assertTrue(len(f.vertices) == 0) if __name__ == '__main__': unittest.main()
[((13, 4, 13, 19), 'unittest.main', 'unittest.main', ({}, {}), '()', False, 'import unittest\n'), ((8, 12, 8, 18), 'wvflib.geometry.Face', 'Face', ({}, {}), '()', False, 'from wvflib.geometry import Face\n')]
d066y/detectem
tests/test_core.py
648ddff159e17777e41b1dd266a759e9f0774ea8
import pytest from detectem.core import Detector, Result, ResultCollection from detectem.plugin import Plugin, PluginCollection from detectem.settings import INDICATOR_TYPE, HINT_TYPE, MAIN_ENTRY, GENERIC_TYPE from detectem.plugins.helpers import meta_generator class TestDetector(): HAR_ENTRY_1 = { 'request': { 'url': 'http://domain.tld/libA-1.4.2.js' }, 'response': { 'url': 'http://domain.tld/libA-1.4.2.js' }, } HAR_NO_URL_REDIRECT = [ { 'request': {'url': 'http://domain.tld/'}, 'response': {}, }, { 'request': {'url': 'http://domain.tld/js/script.js'}, 'response': {}, } ] HAR_URL_REDIRECT_PATH = [ { 'request': {'url': 'http://domain.tld/'}, 'response': {'headers': [ {'name': 'Location', 'value': '/new/default.html'} ]}, }, { 'request': {'url': 'http://domain.tld/new/default.html'}, 'response': {}, } ] HAR_URL_REDIRECT_ABS = [ { 'request': {'url': 'http://domain.tld/'}, 'response': {'headers': [ {'name': 'Location', 'value': 'http://other-domain.tld/'} ]}, }, { 'request': {'url': 'http://other-domain.tld/'}, 'response': {}, } ] URL = 'http://domain.tld/' FOO_PLUGIN = { 'name': 'foo', 'homepage': 'foo', 'matchers': { 'url': 'foo.*-(?P<version>[0-9\.]+)\.js', 'header': ('FooHeader', 'Foo.* v(?P<version>[0-9\.]+)'), 'body': 'Foo.* v(?P<version>[0-9\.]+)', 'xpath': (meta_generator('foo-min'), '(?P<version>[0-9\.]+)'), }, 'indicators': { 'url': 'foo.*\.js', 'header': ('FooHeader', 'Foo'), 'body': 'Foo', 'xpath': "//meta[@name='generator']", }, 'modular_matchers': { 'url': 'foo-(?P<name>\w+)-.*\.js', 'header': ('FooHeader', 'Foo-(?P<name>\w+)'), 'body': 'Foo-(?P<name>\w+)', 'xpath': (meta_generator('foo-min'), 'foo-(?P<name>\w+)'), }, } FOO_RESULTS = [ [{'name': 'foo', 'version': '1.1'}], [{'name': 'foo'}], [{'name': 'foo-min', 'version': '1.1'}], ] MATCHER_SOURCES = [ ['matchers'], ['indicators'], ['matchers', 'modular_matchers'], ] def test_detector_starts_with_empty_results(self): d = Detector({'har': None, 'softwares': None}, [], None) assert not d._results.get_results() @pytest.mark.parametrize("har,index", [ (HAR_NO_URL_REDIRECT, 0), (HAR_URL_REDIRECT_PATH, 1), (HAR_URL_REDIRECT_ABS, 1), ]) def test_mark_main_entry(self, har, index): d = self._create_detector(har, []) assert d.har[index]['detectem']['type'] == MAIN_ENTRY def test_convert_inline_script_to_har_entry(self): script = 'Inline script' d = Detector({'har': [], 'softwares': [], 'scripts': [script]}, None, self.URL) e = d.har[0] assert e['request']['url'] == self.URL assert e['response']['content']['text'] == script @pytest.mark.parametrize("scripts,n_entries", [ ([], 0), (['script1', 'script2'], 2), ]) def test_add_inline_scripts_to_har(self, scripts, n_entries): d = Detector({'har': [], 'softwares': [], 'scripts': scripts}, None, self.URL) assert len(d.har) == n_entries def _create_plugin(self, template, sources, matchers): class TestPlugin(Plugin): name = template['name'] homepage = template['homepage'] p = TestPlugin() for s in sources: g = [{m: template[s][m]} for m in matchers] setattr(p, s, g) return p def _create_detector(self, har, plugins): pc = PluginCollection() for p in plugins: pc.add(p) return Detector({'har': har, 'softwares': []}, pc, self.URL) @pytest.mark.parametrize('sources,result', zip(MATCHER_SOURCES, FOO_RESULTS)) def test_match_from_headers(self, sources, result): har = [ { 'request': {'url': self.URL}, 'response': { 'url': self.URL, 'headers': [ {'name': 'FooHeader', 'value': 'Foo-min v1.1'} ] }, }, ] p = self._create_plugin(self.FOO_PLUGIN, sources, ['header']) d = self._create_detector(har, [p]) assert d.get_results() == result @pytest.mark.parametrize('sources', MATCHER_SOURCES) def test_match_from_headers_ignores_resource_entries(self, sources): har = [ { 'request': {'url': self.URL}, 'response': { 'url': self.URL, 'headers': [], }, }, { 'request': {'url': 'http://foo.org/lib/foo.js'}, 'response': { 'url': 'http://foo.org/lib/foo.js', 'headers': [ {'name': 'FooHeader', 'value': 'Foo-min v1.1'} ] }, }, ] p = self._create_plugin(self.FOO_PLUGIN, sources, ['header']) d = self._create_detector(har, [p]) assert not d.get_results() @pytest.mark.parametrize('sources,result', zip(MATCHER_SOURCES, FOO_RESULTS)) def test_match_from_body(self, sources, result): har = [ { 'request': {'url': self.URL}, 'response': { 'url': self.URL, 'content': {'text': 'Main content'}, }, }, { 'request': {'url': 'http://foo.org/lib/foo.js'}, 'response': { 'url': 'http://foo.org/lib/foo.js', 'content': {'text': 'Plugin Foo-min v1.1'}, }, }, ] p = self._create_plugin(self.FOO_PLUGIN, sources, ['body']) d = self._create_detector(har, [p]) assert d.get_results() == result @pytest.mark.parametrize('sources', MATCHER_SOURCES) def test_match_from_body_excludes_main_entry(self, sources): har = [ { 'request': {'url': self.URL}, 'response': { 'url': self.URL, 'content': {'text': 'About Foo-min v1.1'}, }, }, ] p = self._create_plugin(self.FOO_PLUGIN, sources, ['body']) d = self._create_detector(har, [p]) assert not d.get_results() @pytest.mark.parametrize('sources,result', zip(MATCHER_SOURCES, FOO_RESULTS)) def test_match_from_url(self, sources, result): har = [ { 'request': {'url': self.URL}, 'response': {'url': self.URL}, }, { 'request': {'url': 'http://foo.org/lib/foo-min-1.1.js'}, 'response': { 'url': 'http://foo.org/lib/foo-min-1.1.js', }, }, ] p = self._create_plugin(self.FOO_PLUGIN, sources, ['url']) d = self._create_detector(har, [p]) assert d.get_results() == result @pytest.mark.parametrize('sources,result', zip(MATCHER_SOURCES, FOO_RESULTS)) def test_match_from_xpath(self, sources, result): har = [ { 'request': {'url': self.URL}, 'response': { 'url': self.URL, 'content': { 'text': '<meta name="generator" content="foo-min 1.1">' }, }, }, ] p = self._create_plugin(self.FOO_PLUGIN, sources, ['xpath']) d = self._create_detector(har, [p]) assert d.get_results() == result def test_get_hints_with_valid_hint(self): class TestPlugin(Plugin): name = 'test' homepage = 'test' class BlaPlugin(Plugin): name = 'bla' hints = ['test'] detector = self._create_detector(None, [TestPlugin()]) hints = detector.get_hints(BlaPlugin()) assert hints def test_get_hints_with_invalid_hint(self): class BlaPlugin(Plugin): name = 'bla' hints = ['test'] detector = self._create_detector(None, []) hints = detector.get_hints(BlaPlugin()) assert not hints class TestResultCollection(): @staticmethod def _assert_results(detected, results): c = ResultCollection() for d in detected: c.add_result(d) assert set(c.get_results()) == set(results) @pytest.mark.parametrize('detected,results', [ ( [Result('pluginA', '1.1'), Result('pluginB', '3.8.7'), Result('pluginC', '4.0')], [Result('pluginA', '1.1'), Result('pluginB', '3.8.7'), Result('pluginC', '4.0')] ), ( [Result('pluginA', '1.3'), Result('pluginA', '1.2'), Result('pluginA', '1.1')], [Result('pluginA', '1.1'), Result('pluginA', '1.2'), Result('pluginA', '1.3')], ), ( [ Result('pluginA', '1.1'), Result('pluginC', type=HINT_TYPE), Result('pluginB', type=INDICATOR_TYPE), Result('pluginD', type=GENERIC_TYPE), ], [ Result('pluginA', '1.1'), Result('pluginB', type=INDICATOR_TYPE), Result('pluginC', type=HINT_TYPE), Result('pluginD', type=GENERIC_TYPE), ] ), ]) def test_get_all_detected_plugins(self, detected, results): self._assert_results(detected, results) @pytest.mark.parametrize('detected,results', [ ( [Result('pluginA', '1.1'), Result('pluginA', '1.2'), Result('pluginA', '1.1')], [Result('pluginA', '1.1'), Result('pluginA', '1.2')] ), ( [ Result('pluginA', '1.1'), Result('pluginA', type=INDICATOR_TYPE), Result('pluginA', type=HINT_TYPE), ], [Result('pluginA', '1.1')] ), ( [Result('pluginB', type=HINT_TYPE), Result('pluginB', type=HINT_TYPE)], [Result('pluginB', type=HINT_TYPE)] ), ( [Result('pluginB', type=INDICATOR_TYPE), Result('pluginB', type=INDICATOR_TYPE)], [Result('pluginB', type=INDICATOR_TYPE)] ), ( [Result('pluginB', type=INDICATOR_TYPE), Result('pluginB', type=HINT_TYPE)], [Result('pluginB', type=INDICATOR_TYPE)] ), ( [Result('pluginB', type=INDICATOR_TYPE), Result('pluginB', type=GENERIC_TYPE)], [Result('pluginB', type=INDICATOR_TYPE)] ), ]) def test_remove_duplicated_results(self, detected, results): self._assert_results(detected, results)
[((95, 5, 99, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(95, 29, 95, 40): '"""har,index"""', (95, 42, 99, 5): '[(HAR_NO_URL_REDIRECT, 0), (HAR_URL_REDIRECT_PATH, 1), (\n HAR_URL_REDIRECT_ABS, 1)]'}, {}), "('har,index', [(HAR_NO_URL_REDIRECT, 0), (\n HAR_URL_REDIRECT_PATH, 1), (HAR_URL_REDIRECT_ABS, 1)])", False, 'import pytest\n'), ((113, 5, 116, 6), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(113, 29, 113, 48): '"""scripts,n_entries"""', (113, 50, 116, 5): "[([], 0), (['script1', 'script2'], 2)]"}, {}), "('scripts,n_entries', [([], 0), (['script1',\n 'script2'], 2)])", False, 'import pytest\n'), ((156, 5, 156, 56), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(156, 29, 156, 38): '"""sources"""', (156, 40, 156, 55): 'MATCHER_SOURCES'}, {}), "('sources', MATCHER_SOURCES)", False, 'import pytest\n'), ((204, 5, 204, 56), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(204, 29, 204, 38): '"""sources"""', (204, 40, 204, 55): 'MATCHER_SOURCES'}, {}), "('sources', MATCHER_SOURCES)", False, 'import pytest\n'), ((92, 12, 92, 64), 'detectem.core.Detector', 'Detector', ({(92, 21, 92, 53): "{'har': None, 'softwares': None}", (92, 55, 92, 57): '[]', (92, 59, 92, 63): 'None'}, {}), "({'har': None, 'softwares': None}, [], None)", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((107, 12, 107, 87), 'detectem.core.Detector', 'Detector', ({(107, 21, 107, 70): "{'har': [], 'softwares': [], 'scripts': [script]}", (107, 72, 107, 76): 'None', (107, 78, 107, 86): 'self.URL'}, {}), "({'har': [], 'softwares': [], 'scripts': [script]}, None, self.URL)", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((118, 12, 118, 86), 'detectem.core.Detector', 'Detector', ({(118, 21, 118, 69): "{'har': [], 'softwares': [], 'scripts': scripts}", (118, 71, 118, 75): 'None', (118, 77, 118, 85): 'self.URL'}, {}), "({'har': [], 'softwares': [], 'scripts': scripts}, None, self.URL)", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((133, 13, 133, 31), 'detectem.plugin.PluginCollection', 'PluginCollection', ({}, {}), '()', False, 'from detectem.plugin import Plugin, PluginCollection\n'), ((136, 15, 136, 68), 'detectem.core.Detector', 'Detector', ({(136, 24, 136, 53): "{'har': har, 'softwares': []}", (136, 55, 136, 57): 'pc', (136, 59, 136, 67): 'self.URL'}, {}), "({'har': har, 'softwares': []}, pc, self.URL)", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((285, 12, 285, 30), 'detectem.core.ResultCollection', 'ResultCollection', ({}, {}), '()', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((63, 22, 63, 47), 'detectem.plugins.helpers.meta_generator', 'meta_generator', ({(63, 37, 63, 46): '"""foo-min"""'}, {}), "('foo-min')", False, 'from detectem.plugins.helpers import meta_generator\n'), ((75, 22, 75, 47), 'detectem.plugins.helpers.meta_generator', 'meta_generator', ({(75, 37, 75, 46): '"""foo-min"""'}, {}), "('foo-min')", False, 'from detectem.plugins.helpers import meta_generator\n'), ((292, 13, 292, 37), 'detectem.core.Result', 'Result', ({(292, 20, 292, 29): '"""pluginA"""', (292, 31, 292, 36): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((292, 39, 292, 65), 'detectem.core.Result', 'Result', ({(292, 46, 292, 55): '"""pluginB"""', (292, 57, 292, 64): '"""3.8.7"""'}, {}), "('pluginB', '3.8.7')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((292, 67, 292, 91), 'detectem.core.Result', 'Result', ({(292, 74, 292, 83): '"""pluginC"""', (292, 85, 292, 90): '"""4.0"""'}, {}), "('pluginC', '4.0')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((293, 13, 293, 37), 'detectem.core.Result', 'Result', ({(293, 20, 293, 29): '"""pluginA"""', (293, 31, 293, 36): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((293, 39, 293, 65), 'detectem.core.Result', 'Result', ({(293, 46, 293, 55): '"""pluginB"""', (293, 57, 293, 64): '"""3.8.7"""'}, {}), "('pluginB', '3.8.7')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((293, 67, 293, 91), 'detectem.core.Result', 'Result', ({(293, 74, 293, 83): '"""pluginC"""', (293, 85, 293, 90): '"""4.0"""'}, {}), "('pluginC', '4.0')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((296, 13, 296, 37), 'detectem.core.Result', 'Result', ({(296, 20, 296, 29): '"""pluginA"""', (296, 31, 296, 36): '"""1.3"""'}, {}), "('pluginA', '1.3')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((296, 39, 296, 63), 'detectem.core.Result', 'Result', ({(296, 46, 296, 55): '"""pluginA"""', (296, 57, 296, 62): '"""1.2"""'}, {}), "('pluginA', '1.2')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((296, 65, 296, 89), 'detectem.core.Result', 'Result', ({(296, 72, 296, 81): '"""pluginA"""', (296, 83, 296, 88): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((297, 13, 297, 37), 'detectem.core.Result', 'Result', ({(297, 20, 297, 29): '"""pluginA"""', (297, 31, 297, 36): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((297, 39, 297, 63), 'detectem.core.Result', 'Result', ({(297, 46, 297, 55): '"""pluginA"""', (297, 57, 297, 62): '"""1.2"""'}, {}), "('pluginA', '1.2')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((297, 65, 297, 89), 'detectem.core.Result', 'Result', ({(297, 72, 297, 81): '"""pluginA"""', (297, 83, 297, 88): '"""1.3"""'}, {}), "('pluginA', '1.3')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((301, 16, 301, 40), 'detectem.core.Result', 'Result', ({(301, 23, 301, 32): '"""pluginA"""', (301, 34, 301, 39): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((302, 16, 302, 49), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((303, 16, 303, 54), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((304, 16, 304, 52), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((307, 16, 307, 40), 'detectem.core.Result', 'Result', ({(307, 23, 307, 32): '"""pluginA"""', (307, 34, 307, 39): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((308, 16, 308, 54), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((309, 16, 309, 49), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((310, 16, 310, 52), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((319, 13, 319, 37), 'detectem.core.Result', 'Result', ({(319, 20, 319, 29): '"""pluginA"""', (319, 31, 319, 36): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((319, 39, 319, 63), 'detectem.core.Result', 'Result', ({(319, 46, 319, 55): '"""pluginA"""', (319, 57, 319, 62): '"""1.2"""'}, {}), "('pluginA', '1.2')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((319, 65, 319, 89), 'detectem.core.Result', 'Result', ({(319, 72, 319, 81): '"""pluginA"""', (319, 83, 319, 88): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((320, 13, 320, 37), 'detectem.core.Result', 'Result', ({(320, 20, 320, 29): '"""pluginA"""', (320, 31, 320, 36): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((320, 39, 320, 63), 'detectem.core.Result', 'Result', ({(320, 46, 320, 55): '"""pluginA"""', (320, 57, 320, 62): '"""1.2"""'}, {}), "('pluginA', '1.2')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((324, 16, 324, 40), 'detectem.core.Result', 'Result', ({(324, 23, 324, 32): '"""pluginA"""', (324, 34, 324, 39): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((325, 16, 325, 54), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((326, 16, 326, 49), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((328, 13, 328, 37), 'detectem.core.Result', 'Result', ({(328, 20, 328, 29): '"""pluginA"""', (328, 31, 328, 36): '"""1.1"""'}, {}), "('pluginA', '1.1')", False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((331, 13, 331, 46), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((331, 48, 331, 81), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((332, 13, 332, 46), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((335, 13, 335, 51), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((335, 53, 335, 91), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((336, 13, 336, 51), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((339, 13, 339, 51), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((339, 53, 339, 86), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((340, 13, 340, 51), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((343, 13, 343, 51), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((343, 53, 343, 89), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n'), ((344, 13, 344, 51), 'detectem.core.Result', 'Result', (), '', False, 'from detectem.core import Detector, Result, ResultCollection\n')]
Mlitwin98/twitter-clone
twitter-clone/twitter/views.py
4fbe754a4693c39ac4e9623f51ca42a7facecd2e
from django.dispatch.dispatcher import receiver from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth.decorators import login_required from django.http.response import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login from django.contrib import messages from django.db.models import Count from django.template.loader import render_to_string from django.http import HttpResponseRedirect, JsonResponse from twitter.models import Tweet, Follow, Notification, Comment from twitter.myDecor import check_if_user_logged from twitter.forms import SignUpForm # Create your views here. @check_if_user_logged def index(request): return render(request, 'index.html') @check_if_user_logged def login(request): if request.method == 'POST': if 'login' in request.POST: mail = request.POST['email'] pwd = request.POST['password'] user = authenticate(request, username=mail, password=pwd) if user is not None: auth_login(request, user) return redirect('home') else: messages.error(request, 'Invalid credentials') return render(request, 'login.html') elif 'cancel' in request.POST: return redirect('index') else: return render(request, 'login.html') def logout(reqeuest): auth_logout(reqeuest) return redirect('index') @check_if_user_logged def register(request): if request.method == 'POST': if 'cancel' in request.POST: return redirect('index') elif 'register' in request.POST: form = SignUpForm(request.POST) if form.is_valid(): user = form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password') user.set_password(raw_password) user.save() user = authenticate(request, username=email, password = raw_password) auth_login(request, user) return redirect('home') else: form = SignUpForm() messages.error(request, 'Invalid form fill') return render(request, 'register.html', {'form':form}) else: form = SignUpForm() return render(request, 'register.html', {'form':form}) @login_required(redirect_field_name=None) def home(request): if request.method == 'POST': author = request.user content = request.POST['tweet'] tweet = Tweet(author=author, content=content) tweet.save() for follower in request.user.following.all().values_list('following_user_id', flat=True): Notification.objects.create(sender = request.user, receiver = User.objects.get(id=follower), target = tweet, type = 'L') return redirect('home') else: followedUsers = [request.user] for followed in request.user.followers.all(): followedUsers.append(User.objects.get(id=followed.user_id_id)) tweets = Tweet.objects.filter(author__in=followedUsers).order_by('-timeStamp') rec_profiles = User.objects.annotate(count=Count('followers')).order_by('followers').exclude(username=request.user.username).exclude(id__in=request.user.followers.all().values_list('user_id', flat=True))[:5] return render(request, 'home.html', {'tweets':tweets, 'rec_profiles':rec_profiles}) def profile(request, username): if request.method == 'POST': user = User.objects.get(username=username) user.profile.bio = request.POST['bio'] user.profile.profilePic = request.FILES['pic'] if 'pic' in request.FILES else user.profile.profilePic user.profile.backgroundPic = request.FILES['banner'] if 'banner' in request.FILES else user.profile.backgroundPic user.save() return redirect('profile', username=username) else: try: userProfile = User.objects.get(username=username) except User.DoesNotExist: return HttpResponse('User Not Found') tweets = Tweet.objects.filter(author__exact=userProfile).order_by('-timeStamp') is_following = False for follow in request.user.followers.all(): if userProfile.id == follow.user_id_id: is_following=True rec_profiles = User.objects.annotate(count=Count('followers')).order_by('followers').exclude(username=request.user.username).exclude(username=username).exclude(id__in=request.user.followers.all().values_list('user_id', flat=True))[:5] return render(request, 'profile.html', {'userProfile':userProfile, 'tweets':tweets, 'is_following':is_following, 'rec_profiles':rec_profiles}) @login_required(redirect_field_name=None) def delete_post(request, tweetID): if request.method == 'POST': tweet = Tweet.objects.get(id=tweetID) if tweet.author == request.user: tweet.delete() return redirect('profile', username=request.user.username) else: return redirect('home') @login_required(redirect_field_name=None) def like_post(request): tweet = get_object_or_404(Tweet, id=request.POST.get('id')) if tweet.likes.filter(id=request.user.id).exists(): tweet.likes.remove(request.user) is_liked = False else: tweet.likes.add(request.user) is_liked = True if(request.user != tweet.author): Notification.objects.create(sender = request.user, receiver = User.objects.get(username = tweet.author), target = tweet, type = 'L') context = { 'tweet': tweet, 'is_liked': is_liked, } if request.is_ajax(): html = render_to_string('tweet.html', context, request=request) return JsonResponse({'form':html}) @login_required(redirect_field_name=None) def change_mode(request): if request.method == 'POST': usr = User.objects.get(id=request.user.id) usr.profile.mode = request.POST['mode'] usr.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) @login_required(redirect_field_name=None) def follow_profile(request): followed_user = get_object_or_404(User, id=request.POST.get('id')) if Follow.objects.filter(user_id=followed_user.id, following_user_id = request.user.id).exists(): Follow.objects.filter(user_id=followed_user.id, following_user_id = request.user.id).delete() is_following = False else: Follow.objects.create(user_id=followed_user, following_user_id = request.user) Notification.objects.create(sender = request.user, receiver = followed_user, target = None, type = 'F') is_following = True context = { 'profile':followed_user, 'userProfile':followed_user, 'is_following':is_following } if request.is_ajax(): html = render_to_string('follow_button.html', context, request=request) return JsonResponse({'form':html}) def notifications(request): notifics = request.user.your_notifications.all() for notific in notifics: notific.seen = True notific.save() notifics = request.user.your_notifications.all().order_by('-id')[:10] return render(request, 'notifications.html', {'notifics':notifics}) def tweet_details(request, tweetID): tweet = Tweet.objects.get(id=tweetID) comments = tweet.main_tweet.all().order_by('-timeStamp') return render(request, 'tweet_details.html', {'tweet':tweet, 'comments':comments}) def comment(request, tweetID): if request.method == 'POST': author = request.user content = request.POST['comment'] tweet = Tweet.objects.get(id=tweetID) Comment.objects.create(author=author, main_tweet=tweet, content=content) if(request.user != tweet.author): Notification.objects.create(sender = request.user, receiver = tweet.author, target = tweet, type = 'C') return redirect(tweet_details, tweetID=tweetID) else: return redirect(home) #Notification on post comment
[((68, 1, 68, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((118, 1, 118, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((128, 1, 128, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((151, 1, 151, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((161, 1, 161, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((20, 11, 20, 40), 'django.shortcuts.render', 'render', ({(20, 18, 20, 25): 'request', (20, 27, 20, 39): '"""index.html"""'}, {}), "(request, 'index.html')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((41, 4, 41, 25), 'django.contrib.auth.logout', 'auth_logout', ({(41, 16, 41, 24): 'reqeuest'}, {}), '(reqeuest)', True, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((42, 11, 42, 28), 'django.shortcuts.redirect', 'redirect', ({(42, 20, 42, 27): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((190, 11, 190, 71), 'django.shortcuts.render', 'render', ({(190, 18, 190, 25): 'request', (190, 27, 190, 47): '"""notifications.html"""', (190, 49, 190, 70): "{'notifics': notifics}"}, {}), "(request, 'notifications.html', {'notifics': notifics})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((194, 12, 194, 41), 'twitter.models.Tweet.objects.get', 'Tweet.objects.get', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((197, 11, 197, 86), 'django.shortcuts.render', 'render', ({(197, 18, 197, 25): 'request', (197, 27, 197, 47): '"""tweet_details.html"""', (197, 49, 197, 85): "{'tweet': tweet, 'comments': comments}"}, {}), "(request, 'tweet_details.html', {'tweet': tweet, 'comments': comments})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((38, 15, 38, 44), 'django.shortcuts.render', 'render', ({(38, 22, 38, 29): 'request', (38, 31, 38, 43): '"""login.html"""'}, {}), "(request, 'login.html')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((65, 15, 65, 27), 'twitter.forms.SignUpForm', 'SignUpForm', ({}, {}), '()', False, 'from twitter.forms import SignUpForm\n'), ((66, 15, 66, 62), 'django.shortcuts.render', 'render', ({(66, 22, 66, 29): 'request', (66, 31, 66, 46): '"""register.html"""', (66, 48, 66, 61): "{'form': form}"}, {}), "(request, 'register.html', {'form': form})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((73, 16, 73, 53), 'twitter.models.Tweet', 'Tweet', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((79, 15, 79, 31), 'django.shortcuts.redirect', 'redirect', ({(79, 24, 79, 30): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((89, 15, 89, 91), 'django.shortcuts.render', 'render', ({(89, 22, 89, 29): 'request', (89, 31, 89, 42): '"""home.html"""', (89, 44, 89, 90): "{'tweets': tweets, 'rec_profiles': rec_profiles}"}, {}), "(request, 'home.html', {'tweets': tweets, 'rec_profiles': rec_profiles})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((93, 15, 93, 50), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((100, 15, 100, 53), 'django.shortcuts.redirect', 'redirect', (), '', False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((116, 15, 116, 150), 'django.shortcuts.render', 'render', ({(116, 22, 116, 29): 'request', (116, 31, 116, 45): '"""profile.html"""', (116, 47, 116, 149): "{'userProfile': userProfile, 'tweets': tweets, 'is_following': is_following,\n 'rec_profiles': rec_profiles}"}, {}), "(request, 'profile.html', {'userProfile': userProfile, 'tweets':\n tweets, 'is_following': is_following, 'rec_profiles': rec_profiles})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((121, 16, 121, 45), 'twitter.models.Tweet.objects.get', 'Tweet.objects.get', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((124, 15, 124, 66), 'django.shortcuts.redirect', 'redirect', (), '', False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((126, 15, 126, 31), 'django.shortcuts.redirect', 'redirect', ({(126, 24, 126, 30): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((148, 15, 148, 71), 'django.template.loader.render_to_string', 'render_to_string', (), '', False, 'from django.template.loader import render_to_string\n'), ((149, 15, 149, 42), 'django.http.JsonResponse', 'JsonResponse', ({(149, 28, 149, 41): "{'form': html}"}, {}), "({'form': html})", False, 'from django.http import HttpResponseRedirect, JsonResponse\n'), ((154, 14, 154, 50), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((169, 8, 169, 86), 'twitter.models.Follow.objects.create', 'Follow.objects.create', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((170, 8, 170, 111), 'twitter.models.Notification.objects.create', 'Notification.objects.create', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((180, 15, 180, 79), 'django.template.loader.render_to_string', 'render_to_string', (), '', False, 'from django.template.loader import render_to_string\n'), ((181, 15, 181, 42), 'django.http.JsonResponse', 'JsonResponse', ({(181, 28, 181, 41): "{'form': html}"}, {}), "({'form': html})", False, 'from django.http import HttpResponseRedirect, JsonResponse\n'), ((204, 16, 204, 45), 'twitter.models.Tweet.objects.get', 'Tweet.objects.get', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((205, 8, 205, 80), 'twitter.models.Comment.objects.create', 'Comment.objects.create', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((209, 15, 209, 55), 'django.shortcuts.redirect', 'redirect', (), '', False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((211, 15, 211, 29), 'django.shortcuts.redirect', 'redirect', ({(211, 24, 211, 28): 'home'}, {}), '(home)', False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((28, 19, 28, 69), 'django.contrib.auth.authenticate', 'authenticate', (), '', False, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((48, 19, 48, 36), 'django.shortcuts.redirect', 'redirect', ({(48, 28, 48, 35): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((103, 26, 103, 61), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((165, 7, 165, 91), 'twitter.models.Follow.objects.filter', 'Follow.objects.filter', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((208, 12, 208, 115), 'twitter.models.Notification.objects.create', 'Notification.objects.create', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((30, 16, 30, 41), 'django.contrib.auth.login', 'auth_login', ({(30, 27, 30, 34): 'request', (30, 36, 30, 40): 'user'}, {}), '(request, user)', True, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((31, 23, 31, 39), 'django.shortcuts.redirect', 'redirect', ({(31, 32, 31, 38): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((33, 16, 33, 62), 'django.contrib.messages.error', 'messages.error', ({(33, 31, 33, 38): 'request', (33, 40, 33, 61): '"""Invalid credentials"""'}, {}), "(request, 'Invalid credentials')", False, 'from django.contrib import messages\n'), ((34, 23, 34, 52), 'django.shortcuts.render', 'render', ({(34, 30, 34, 37): 'request', (34, 39, 34, 51): '"""login.html"""'}, {}), "(request, 'login.html')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((36, 19, 36, 36), 'django.shortcuts.redirect', 'redirect', ({(36, 28, 36, 35): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((50, 19, 50, 43), 'twitter.forms.SignUpForm', 'SignUpForm', ({(50, 30, 50, 42): 'request.POST'}, {}), '(request.POST)', False, 'from twitter.forms import SignUpForm\n'), ((83, 33, 83, 73), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((85, 17, 85, 63), 'twitter.models.Tweet.objects.filter', 'Tweet.objects.filter', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((105, 19, 105, 49), 'django.http.response.HttpResponse', 'HttpResponse', ({(105, 32, 105, 48): '"""User Not Found"""'}, {}), "('User Not Found')", False, 'from django.http.response import HttpResponse\n'), ((107, 17, 107, 64), 'twitter.models.Tweet.objects.filter', 'Tweet.objects.filter', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((166, 8, 166, 92), 'twitter.models.Follow.objects.filter', 'Follow.objects.filter', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((57, 23, 57, 85), 'django.contrib.auth.authenticate', 'authenticate', (), '', False, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((58, 16, 58, 41), 'django.contrib.auth.login', 'auth_login', ({(58, 27, 58, 34): 'request', (58, 36, 58, 40): 'user'}, {}), '(request, user)', True, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((59, 23, 59, 39), 'django.shortcuts.redirect', 'redirect', ({(59, 32, 59, 38): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((61, 23, 61, 35), 'twitter.forms.SignUpForm', 'SignUpForm', ({}, {}), '()', False, 'from twitter.forms import SignUpForm\n'), ((62, 16, 62, 60), 'django.contrib.messages.error', 'messages.error', ({(62, 31, 62, 38): 'request', (62, 40, 62, 59): '"""Invalid form fill"""'}, {}), "(request, 'Invalid form fill')", False, 'from django.contrib import messages\n'), ((63, 23, 63, 70), 'django.shortcuts.render', 'render', ({(63, 30, 63, 37): 'request', (63, 39, 63, 54): '"""register.html"""', (63, 56, 63, 69): "{'form': form}"}, {}), "(request, 'register.html', {'form': form})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((77, 74, 77, 103), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((140, 74, 140, 115), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((87, 51, 87, 69), 'django.db.models.Count', 'Count', ({(87, 57, 87, 68): '"""followers"""'}, {}), "('followers')", False, 'from django.db.models import Count\n'), ((114, 51, 114, 69), 'django.db.models.Count', 'Count', ({(114, 57, 114, 68): '"""followers"""'}, {}), "('followers')", False, 'from django.db.models import Count\n')]
Amruthaohm/custom_app
custom_app/custom_app/doctype/depart/test_depart.py
03bc3fc11c3627251796611caf33b7117c46d69b
# Copyright (c) 2022, momscode and Contributors # See license.txt # import frappe import unittest class Testdepart(unittest.TestCase): pass
[]
khdesai/cti-python-stix2
stix2/__init__.py
20a9bb316c43b7d9faaab686db8d51e5c89416da
"""Python APIs for STIX 2. .. autosummary:: :toctree: api confidence datastore environment equivalence exceptions markings parsing pattern_visitor patterns properties serialization utils v20 v21 versioning workbench """ # flake8: noqa DEFAULT_VERSION = '2.1' # Default version will always be the latest STIX 2.X version from .confidence import scales from .datastore import CompositeDataSource from .datastore.filesystem import ( FileSystemSink, FileSystemSource, FileSystemStore, ) from .datastore.filters import Filter from .datastore.memory import MemorySink, MemorySource, MemoryStore from .datastore.taxii import ( TAXIICollectionSink, TAXIICollectionSource, TAXIICollectionStore, ) from .environment import Environment, ObjectFactory from .markings import ( add_markings, clear_markings, get_markings, is_marked, remove_markings, set_markings, ) from .parsing import _collect_stix2_mappings, parse, parse_observable from .patterns import ( AndBooleanExpression, AndObservationExpression, BasicObjectPathComponent, BinaryConstant, BooleanConstant, EqualityComparisonExpression, FloatConstant, FollowedByObservationExpression, GreaterThanComparisonExpression, GreaterThanEqualComparisonExpression, HashConstant, HexConstant, InComparisonExpression, IntegerConstant, IsSubsetComparisonExpression, IsSupersetComparisonExpression, LessThanComparisonExpression, LessThanEqualComparisonExpression, LikeComparisonExpression, ListConstant, ListObjectPathComponent, MatchesComparisonExpression, ObjectPath, ObservationExpression, OrBooleanExpression, OrObservationExpression, ParentheticalExpression, QualifiedObservationExpression, ReferenceObjectPathComponent, RepeatQualifier, StartStopQualifier, StringConstant, TimestampConstant, WithinQualifier, ) from .v21 import * # This import will always be the latest STIX 2.X version from .version import __version__ from .versioning import new_version, revoke _collect_stix2_mappings()
[]
chr0m3/boj-codes
0/1/1436/1436.py
d71d0a22d0a3ae62c225f382442461275f56fe8f
count = int(input()) title = 0 while count > 0: title += 1 if '666' in str(title): count -= 1 print(title)
[]
jieatelement/quickstart-aws-industrial-machine-connectivity
functions/source/GreengrassLambda/idna/uts46data.py
ca6af4dcbf795ce4a91adcbec4b206147ab26bfa
# This file is automatically generated by tools/idna-data # vim: set fileencoding=utf-8 : """IDNA Mapping Table from UTS46.""" __version__ = "11.0.0" def _seg_0(): return [ (0x0, '3'), (0x1, '3'), (0x2, '3'), (0x3, '3'), (0x4, '3'), (0x5, '3'), (0x6, '3'), (0x7, '3'), (0x8, '3'), (0x9, '3'), (0xA, '3'), (0xB, '3'), (0xC, '3'), (0xD, '3'), (0xE, '3'), (0xF, '3'), (0x10, '3'), (0x11, '3'), (0x12, '3'), (0x13, '3'), (0x14, '3'), (0x15, '3'), (0x16, '3'), (0x17, '3'), (0x18, '3'), (0x19, '3'), (0x1A, '3'), (0x1B, '3'), (0x1C, '3'), (0x1D, '3'), (0x1E, '3'), (0x1F, '3'), (0x20, '3'), (0x21, '3'), (0x22, '3'), (0x23, '3'), (0x24, '3'), (0x25, '3'), (0x26, '3'), (0x27, '3'), (0x28, '3'), (0x29, '3'), (0x2A, '3'), (0x2B, '3'), (0x2C, '3'), (0x2D, 'V'), (0x2E, 'V'), (0x2F, '3'), (0x30, 'V'), (0x31, 'V'), (0x32, 'V'), (0x33, 'V'), (0x34, 'V'), (0x35, 'V'), (0x36, 'V'), (0x37, 'V'), (0x38, 'V'), (0x39, 'V'), (0x3A, '3'), (0x3B, '3'), (0x3C, '3'), (0x3D, '3'), (0x3E, '3'), (0x3F, '3'), (0x40, '3'), (0x41, 'M', u'a'), (0x42, 'M', u'b'), (0x43, 'M', u'c'), (0x44, 'M', u'd'), (0x45, 'M', u'e'), (0x46, 'M', u'f'), (0x47, 'M', u'g'), (0x48, 'M', u'h'), (0x49, 'M', u'i'), (0x4A, 'M', u'j'), (0x4B, 'M', u'k'), (0x4C, 'M', u'l'), (0x4D, 'M', u'm'), (0x4E, 'M', u'n'), (0x4F, 'M', u'o'), (0x50, 'M', u'p'), (0x51, 'M', u'q'), (0x52, 'M', u'r'), (0x53, 'M', u's'), (0x54, 'M', u't'), (0x55, 'M', u'u'), (0x56, 'M', u'v'), (0x57, 'M', u'w'), (0x58, 'M', u'x'), (0x59, 'M', u'y'), (0x5A, 'M', u'z'), (0x5B, '3'), (0x5C, '3'), (0x5D, '3'), (0x5E, '3'), (0x5F, '3'), (0x60, '3'), (0x61, 'V'), (0x62, 'V'), (0x63, 'V'), ] def _seg_1(): return [ (0x64, 'V'), (0x65, 'V'), (0x66, 'V'), (0x67, 'V'), (0x68, 'V'), (0x69, 'V'), (0x6A, 'V'), (0x6B, 'V'), (0x6C, 'V'), (0x6D, 'V'), (0x6E, 'V'), (0x6F, 'V'), (0x70, 'V'), (0x71, 'V'), (0x72, 'V'), (0x73, 'V'), (0x74, 'V'), (0x75, 'V'), (0x76, 'V'), (0x77, 'V'), (0x78, 'V'), (0x79, 'V'), (0x7A, 'V'), (0x7B, '3'), (0x7C, '3'), (0x7D, '3'), (0x7E, '3'), (0x7F, '3'), (0x80, 'X'), (0x81, 'X'), (0x82, 'X'), (0x83, 'X'), (0x84, 'X'), (0x85, 'X'), (0x86, 'X'), (0x87, 'X'), (0x88, 'X'), (0x89, 'X'), (0x8A, 'X'), (0x8B, 'X'), (0x8C, 'X'), (0x8D, 'X'), (0x8E, 'X'), (0x8F, 'X'), (0x90, 'X'), (0x91, 'X'), (0x92, 'X'), (0x93, 'X'), (0x94, 'X'), (0x95, 'X'), (0x96, 'X'), (0x97, 'X'), (0x98, 'X'), (0x99, 'X'), (0x9A, 'X'), (0x9B, 'X'), (0x9C, 'X'), (0x9D, 'X'), (0x9E, 'X'), (0x9F, 'X'), (0xA0, '3', u' '), (0xA1, 'V'), (0xA2, 'V'), (0xA3, 'V'), (0xA4, 'V'), (0xA5, 'V'), (0xA6, 'V'), (0xA7, 'V'), (0xA8, '3', u' ̈'), (0xA9, 'V'), (0xAA, 'M', u'a'), (0xAB, 'V'), (0xAC, 'V'), (0xAD, 'I'), (0xAE, 'V'), (0xAF, '3', u' ̄'), (0xB0, 'V'), (0xB1, 'V'), (0xB2, 'M', u'2'), (0xB3, 'M', u'3'), (0xB4, '3', u' ́'), (0xB5, 'M', u'μ'), (0xB6, 'V'), (0xB7, 'V'), (0xB8, '3', u' ̧'), (0xB9, 'M', u'1'), (0xBA, 'M', u'o'), (0xBB, 'V'), (0xBC, 'M', u'1⁄4'), (0xBD, 'M', u'1⁄2'), (0xBE, 'M', u'3⁄4'), (0xBF, 'V'), (0xC0, 'M', u'à'), (0xC1, 'M', u'á'), (0xC2, 'M', u'â'), (0xC3, 'M', u'ã'), (0xC4, 'M', u'ä'), (0xC5, 'M', u'å'), (0xC6, 'M', u'æ'), (0xC7, 'M', u'ç'), ] def _seg_2(): return [ (0xC8, 'M', u'è'), (0xC9, 'M', u'é'), (0xCA, 'M', u'ê'), (0xCB, 'M', u'ë'), (0xCC, 'M', u'ì'), (0xCD, 'M', u'í'), (0xCE, 'M', u'î'), (0xCF, 'M', u'ï'), (0xD0, 'M', u'ð'), (0xD1, 'M', u'ñ'), (0xD2, 'M', u'ò'), (0xD3, 'M', u'ó'), (0xD4, 'M', u'ô'), (0xD5, 'M', u'õ'), (0xD6, 'M', u'ö'), (0xD7, 'V'), (0xD8, 'M', u'ø'), (0xD9, 'M', u'ù'), (0xDA, 'M', u'ú'), (0xDB, 'M', u'û'), (0xDC, 'M', u'ü'), (0xDD, 'M', u'ý'), (0xDE, 'M', u'þ'), (0xDF, 'D', u'ss'), (0xE0, 'V'), (0xE1, 'V'), (0xE2, 'V'), (0xE3, 'V'), (0xE4, 'V'), (0xE5, 'V'), (0xE6, 'V'), (0xE7, 'V'), (0xE8, 'V'), (0xE9, 'V'), (0xEA, 'V'), (0xEB, 'V'), (0xEC, 'V'), (0xED, 'V'), (0xEE, 'V'), (0xEF, 'V'), (0xF0, 'V'), (0xF1, 'V'), (0xF2, 'V'), (0xF3, 'V'), (0xF4, 'V'), (0xF5, 'V'), (0xF6, 'V'), (0xF7, 'V'), (0xF8, 'V'), (0xF9, 'V'), (0xFA, 'V'), (0xFB, 'V'), (0xFC, 'V'), (0xFD, 'V'), (0xFE, 'V'), (0xFF, 'V'), (0x100, 'M', u'ā'), (0x101, 'V'), (0x102, 'M', u'ă'), (0x103, 'V'), (0x104, 'M', u'ą'), (0x105, 'V'), (0x106, 'M', u'ć'), (0x107, 'V'), (0x108, 'M', u'ĉ'), (0x109, 'V'), (0x10A, 'M', u'ċ'), (0x10B, 'V'), (0x10C, 'M', u'č'), (0x10D, 'V'), (0x10E, 'M', u'ď'), (0x10F, 'V'), (0x110, 'M', u'đ'), (0x111, 'V'), (0x112, 'M', u'ē'), (0x113, 'V'), (0x114, 'M', u'ĕ'), (0x115, 'V'), (0x116, 'M', u'ė'), (0x117, 'V'), (0x118, 'M', u'ę'), (0x119, 'V'), (0x11A, 'M', u'ě'), (0x11B, 'V'), (0x11C, 'M', u'ĝ'), (0x11D, 'V'), (0x11E, 'M', u'ğ'), (0x11F, 'V'), (0x120, 'M', u'ġ'), (0x121, 'V'), (0x122, 'M', u'ģ'), (0x123, 'V'), (0x124, 'M', u'ĥ'), (0x125, 'V'), (0x126, 'M', u'ħ'), (0x127, 'V'), (0x128, 'M', u'ĩ'), (0x129, 'V'), (0x12A, 'M', u'ī'), (0x12B, 'V'), ] def _seg_3(): return [ (0x12C, 'M', u'ĭ'), (0x12D, 'V'), (0x12E, 'M', u'į'), (0x12F, 'V'), (0x130, 'M', u'i̇'), (0x131, 'V'), (0x132, 'M', u'ij'), (0x134, 'M', u'ĵ'), (0x135, 'V'), (0x136, 'M', u'ķ'), (0x137, 'V'), (0x139, 'M', u'ĺ'), (0x13A, 'V'), (0x13B, 'M', u'ļ'), (0x13C, 'V'), (0x13D, 'M', u'ľ'), (0x13E, 'V'), (0x13F, 'M', u'l·'), (0x141, 'M', u'ł'), (0x142, 'V'), (0x143, 'M', u'ń'), (0x144, 'V'), (0x145, 'M', u'ņ'), (0x146, 'V'), (0x147, 'M', u'ň'), (0x148, 'V'), (0x149, 'M', u'ʼn'), (0x14A, 'M', u'ŋ'), (0x14B, 'V'), (0x14C, 'M', u'ō'), (0x14D, 'V'), (0x14E, 'M', u'ŏ'), (0x14F, 'V'), (0x150, 'M', u'ő'), (0x151, 'V'), (0x152, 'M', u'œ'), (0x153, 'V'), (0x154, 'M', u'ŕ'), (0x155, 'V'), (0x156, 'M', u'ŗ'), (0x157, 'V'), (0x158, 'M', u'ř'), (0x159, 'V'), (0x15A, 'M', u'ś'), (0x15B, 'V'), (0x15C, 'M', u'ŝ'), (0x15D, 'V'), (0x15E, 'M', u'ş'), (0x15F, 'V'), (0x160, 'M', u'š'), (0x161, 'V'), (0x162, 'M', u'ţ'), (0x163, 'V'), (0x164, 'M', u'ť'), (0x165, 'V'), (0x166, 'M', u'ŧ'), (0x167, 'V'), (0x168, 'M', u'ũ'), (0x169, 'V'), (0x16A, 'M', u'ū'), (0x16B, 'V'), (0x16C, 'M', u'ŭ'), (0x16D, 'V'), (0x16E, 'M', u'ů'), (0x16F, 'V'), (0x170, 'M', u'ű'), (0x171, 'V'), (0x172, 'M', u'ų'), (0x173, 'V'), (0x174, 'M', u'ŵ'), (0x175, 'V'), (0x176, 'M', u'ŷ'), (0x177, 'V'), (0x178, 'M', u'ÿ'), (0x179, 'M', u'ź'), (0x17A, 'V'), (0x17B, 'M', u'ż'), (0x17C, 'V'), (0x17D, 'M', u'ž'), (0x17E, 'V'), (0x17F, 'M', u's'), (0x180, 'V'), (0x181, 'M', u'ɓ'), (0x182, 'M', u'ƃ'), (0x183, 'V'), (0x184, 'M', u'ƅ'), (0x185, 'V'), (0x186, 'M', u'ɔ'), (0x187, 'M', u'ƈ'), (0x188, 'V'), (0x189, 'M', u'ɖ'), (0x18A, 'M', u'ɗ'), (0x18B, 'M', u'ƌ'), (0x18C, 'V'), (0x18E, 'M', u'ǝ'), (0x18F, 'M', u'ə'), (0x190, 'M', u'ɛ'), (0x191, 'M', u'ƒ'), (0x192, 'V'), (0x193, 'M', u'ɠ'), ] def _seg_4(): return [ (0x194, 'M', u'ɣ'), (0x195, 'V'), (0x196, 'M', u'ɩ'), (0x197, 'M', u'ɨ'), (0x198, 'M', u'ƙ'), (0x199, 'V'), (0x19C, 'M', u'ɯ'), (0x19D, 'M', u'ɲ'), (0x19E, 'V'), (0x19F, 'M', u'ɵ'), (0x1A0, 'M', u'ơ'), (0x1A1, 'V'), (0x1A2, 'M', u'ƣ'), (0x1A3, 'V'), (0x1A4, 'M', u'ƥ'), (0x1A5, 'V'), (0x1A6, 'M', u'ʀ'), (0x1A7, 'M', u'ƨ'), (0x1A8, 'V'), (0x1A9, 'M', u'ʃ'), (0x1AA, 'V'), (0x1AC, 'M', u'ƭ'), (0x1AD, 'V'), (0x1AE, 'M', u'ʈ'), (0x1AF, 'M', u'ư'), (0x1B0, 'V'), (0x1B1, 'M', u'ʊ'), (0x1B2, 'M', u'ʋ'), (0x1B3, 'M', u'ƴ'), (0x1B4, 'V'), (0x1B5, 'M', u'ƶ'), (0x1B6, 'V'), (0x1B7, 'M', u'ʒ'), (0x1B8, 'M', u'ƹ'), (0x1B9, 'V'), (0x1BC, 'M', u'ƽ'), (0x1BD, 'V'), (0x1C4, 'M', u'dž'), (0x1C7, 'M', u'lj'), (0x1CA, 'M', u'nj'), (0x1CD, 'M', u'ǎ'), (0x1CE, 'V'), (0x1CF, 'M', u'ǐ'), (0x1D0, 'V'), (0x1D1, 'M', u'ǒ'), (0x1D2, 'V'), (0x1D3, 'M', u'ǔ'), (0x1D4, 'V'), (0x1D5, 'M', u'ǖ'), (0x1D6, 'V'), (0x1D7, 'M', u'ǘ'), (0x1D8, 'V'), (0x1D9, 'M', u'ǚ'), (0x1DA, 'V'), (0x1DB, 'M', u'ǜ'), (0x1DC, 'V'), (0x1DE, 'M', u'ǟ'), (0x1DF, 'V'), (0x1E0, 'M', u'ǡ'), (0x1E1, 'V'), (0x1E2, 'M', u'ǣ'), (0x1E3, 'V'), (0x1E4, 'M', u'ǥ'), (0x1E5, 'V'), (0x1E6, 'M', u'ǧ'), (0x1E7, 'V'), (0x1E8, 'M', u'ǩ'), (0x1E9, 'V'), (0x1EA, 'M', u'ǫ'), (0x1EB, 'V'), (0x1EC, 'M', u'ǭ'), (0x1ED, 'V'), (0x1EE, 'M', u'ǯ'), (0x1EF, 'V'), (0x1F1, 'M', u'dz'), (0x1F4, 'M', u'ǵ'), (0x1F5, 'V'), (0x1F6, 'M', u'ƕ'), (0x1F7, 'M', u'ƿ'), (0x1F8, 'M', u'ǹ'), (0x1F9, 'V'), (0x1FA, 'M', u'ǻ'), (0x1FB, 'V'), (0x1FC, 'M', u'ǽ'), (0x1FD, 'V'), (0x1FE, 'M', u'ǿ'), (0x1FF, 'V'), (0x200, 'M', u'ȁ'), (0x201, 'V'), (0x202, 'M', u'ȃ'), (0x203, 'V'), (0x204, 'M', u'ȅ'), (0x205, 'V'), (0x206, 'M', u'ȇ'), (0x207, 'V'), (0x208, 'M', u'ȉ'), (0x209, 'V'), (0x20A, 'M', u'ȋ'), (0x20B, 'V'), (0x20C, 'M', u'ȍ'), ] def _seg_5(): return [ (0x20D, 'V'), (0x20E, 'M', u'ȏ'), (0x20F, 'V'), (0x210, 'M', u'ȑ'), (0x211, 'V'), (0x212, 'M', u'ȓ'), (0x213, 'V'), (0x214, 'M', u'ȕ'), (0x215, 'V'), (0x216, 'M', u'ȗ'), (0x217, 'V'), (0x218, 'M', u'ș'), (0x219, 'V'), (0x21A, 'M', u'ț'), (0x21B, 'V'), (0x21C, 'M', u'ȝ'), (0x21D, 'V'), (0x21E, 'M', u'ȟ'), (0x21F, 'V'), (0x220, 'M', u'ƞ'), (0x221, 'V'), (0x222, 'M', u'ȣ'), (0x223, 'V'), (0x224, 'M', u'ȥ'), (0x225, 'V'), (0x226, 'M', u'ȧ'), (0x227, 'V'), (0x228, 'M', u'ȩ'), (0x229, 'V'), (0x22A, 'M', u'ȫ'), (0x22B, 'V'), (0x22C, 'M', u'ȭ'), (0x22D, 'V'), (0x22E, 'M', u'ȯ'), (0x22F, 'V'), (0x230, 'M', u'ȱ'), (0x231, 'V'), (0x232, 'M', u'ȳ'), (0x233, 'V'), (0x23A, 'M', u'ⱥ'), (0x23B, 'M', u'ȼ'), (0x23C, 'V'), (0x23D, 'M', u'ƚ'), (0x23E, 'M', u'ⱦ'), (0x23F, 'V'), (0x241, 'M', u'ɂ'), (0x242, 'V'), (0x243, 'M', u'ƀ'), (0x244, 'M', u'ʉ'), (0x245, 'M', u'ʌ'), (0x246, 'M', u'ɇ'), (0x247, 'V'), (0x248, 'M', u'ɉ'), (0x249, 'V'), (0x24A, 'M', u'ɋ'), (0x24B, 'V'), (0x24C, 'M', u'ɍ'), (0x24D, 'V'), (0x24E, 'M', u'ɏ'), (0x24F, 'V'), (0x2B0, 'M', u'h'), (0x2B1, 'M', u'ɦ'), (0x2B2, 'M', u'j'), (0x2B3, 'M', u'r'), (0x2B4, 'M', u'ɹ'), (0x2B5, 'M', u'ɻ'), (0x2B6, 'M', u'ʁ'), (0x2B7, 'M', u'w'), (0x2B8, 'M', u'y'), (0x2B9, 'V'), (0x2D8, '3', u' ̆'), (0x2D9, '3', u' ̇'), (0x2DA, '3', u' ̊'), (0x2DB, '3', u' ̨'), (0x2DC, '3', u' ̃'), (0x2DD, '3', u' ̋'), (0x2DE, 'V'), (0x2E0, 'M', u'ɣ'), (0x2E1, 'M', u'l'), (0x2E2, 'M', u's'), (0x2E3, 'M', u'x'), (0x2E4, 'M', u'ʕ'), (0x2E5, 'V'), (0x340, 'M', u'̀'), (0x341, 'M', u'́'), (0x342, 'V'), (0x343, 'M', u'̓'), (0x344, 'M', u'̈́'), (0x345, 'M', u'ι'), (0x346, 'V'), (0x34F, 'I'), (0x350, 'V'), (0x370, 'M', u'ͱ'), (0x371, 'V'), (0x372, 'M', u'ͳ'), (0x373, 'V'), (0x374, 'M', u'ʹ'), (0x375, 'V'), (0x376, 'M', u'ͷ'), (0x377, 'V'), ] def _seg_6(): return [ (0x378, 'X'), (0x37A, '3', u' ι'), (0x37B, 'V'), (0x37E, '3', u';'), (0x37F, 'M', u'ϳ'), (0x380, 'X'), (0x384, '3', u' ́'), (0x385, '3', u' ̈́'), (0x386, 'M', u'ά'), (0x387, 'M', u'·'), (0x388, 'M', u'έ'), (0x389, 'M', u'ή'), (0x38A, 'M', u'ί'), (0x38B, 'X'), (0x38C, 'M', u'ό'), (0x38D, 'X'), (0x38E, 'M', u'ύ'), (0x38F, 'M', u'ώ'), (0x390, 'V'), (0x391, 'M', u'α'), (0x392, 'M', u'β'), (0x393, 'M', u'γ'), (0x394, 'M', u'δ'), (0x395, 'M', u'ε'), (0x396, 'M', u'ζ'), (0x397, 'M', u'η'), (0x398, 'M', u'θ'), (0x399, 'M', u'ι'), (0x39A, 'M', u'κ'), (0x39B, 'M', u'λ'), (0x39C, 'M', u'μ'), (0x39D, 'M', u'ν'), (0x39E, 'M', u'ξ'), (0x39F, 'M', u'ο'), (0x3A0, 'M', u'π'), (0x3A1, 'M', u'ρ'), (0x3A2, 'X'), (0x3A3, 'M', u'σ'), (0x3A4, 'M', u'τ'), (0x3A5, 'M', u'υ'), (0x3A6, 'M', u'φ'), (0x3A7, 'M', u'χ'), (0x3A8, 'M', u'ψ'), (0x3A9, 'M', u'ω'), (0x3AA, 'M', u'ϊ'), (0x3AB, 'M', u'ϋ'), (0x3AC, 'V'), (0x3C2, 'D', u'σ'), (0x3C3, 'V'), (0x3CF, 'M', u'ϗ'), (0x3D0, 'M', u'β'), (0x3D1, 'M', u'θ'), (0x3D2, 'M', u'υ'), (0x3D3, 'M', u'ύ'), (0x3D4, 'M', u'ϋ'), (0x3D5, 'M', u'φ'), (0x3D6, 'M', u'π'), (0x3D7, 'V'), (0x3D8, 'M', u'ϙ'), (0x3D9, 'V'), (0x3DA, 'M', u'ϛ'), (0x3DB, 'V'), (0x3DC, 'M', u'ϝ'), (0x3DD, 'V'), (0x3DE, 'M', u'ϟ'), (0x3DF, 'V'), (0x3E0, 'M', u'ϡ'), (0x3E1, 'V'), (0x3E2, 'M', u'ϣ'), (0x3E3, 'V'), (0x3E4, 'M', u'ϥ'), (0x3E5, 'V'), (0x3E6, 'M', u'ϧ'), (0x3E7, 'V'), (0x3E8, 'M', u'ϩ'), (0x3E9, 'V'), (0x3EA, 'M', u'ϫ'), (0x3EB, 'V'), (0x3EC, 'M', u'ϭ'), (0x3ED, 'V'), (0x3EE, 'M', u'ϯ'), (0x3EF, 'V'), (0x3F0, 'M', u'κ'), (0x3F1, 'M', u'ρ'), (0x3F2, 'M', u'σ'), (0x3F3, 'V'), (0x3F4, 'M', u'θ'), (0x3F5, 'M', u'ε'), (0x3F6, 'V'), (0x3F7, 'M', u'ϸ'), (0x3F8, 'V'), (0x3F9, 'M', u'σ'), (0x3FA, 'M', u'ϻ'), (0x3FB, 'V'), (0x3FD, 'M', u'ͻ'), (0x3FE, 'M', u'ͼ'), (0x3FF, 'M', u'ͽ'), (0x400, 'M', u'ѐ'), (0x401, 'M', u'ё'), (0x402, 'M', u'ђ'), ] def _seg_7(): return [ (0x403, 'M', u'ѓ'), (0x404, 'M', u'є'), (0x405, 'M', u'ѕ'), (0x406, 'M', u'і'), (0x407, 'M', u'ї'), (0x408, 'M', u'ј'), (0x409, 'M', u'љ'), (0x40A, 'M', u'њ'), (0x40B, 'M', u'ћ'), (0x40C, 'M', u'ќ'), (0x40D, 'M', u'ѝ'), (0x40E, 'M', u'ў'), (0x40F, 'M', u'џ'), (0x410, 'M', u'а'), (0x411, 'M', u'б'), (0x412, 'M', u'в'), (0x413, 'M', u'г'), (0x414, 'M', u'д'), (0x415, 'M', u'е'), (0x416, 'M', u'ж'), (0x417, 'M', u'з'), (0x418, 'M', u'и'), (0x419, 'M', u'й'), (0x41A, 'M', u'к'), (0x41B, 'M', u'л'), (0x41C, 'M', u'м'), (0x41D, 'M', u'н'), (0x41E, 'M', u'о'), (0x41F, 'M', u'п'), (0x420, 'M', u'р'), (0x421, 'M', u'с'), (0x422, 'M', u'т'), (0x423, 'M', u'у'), (0x424, 'M', u'ф'), (0x425, 'M', u'х'), (0x426, 'M', u'ц'), (0x427, 'M', u'ч'), (0x428, 'M', u'ш'), (0x429, 'M', u'щ'), (0x42A, 'M', u'ъ'), (0x42B, 'M', u'ы'), (0x42C, 'M', u'ь'), (0x42D, 'M', u'э'), (0x42E, 'M', u'ю'), (0x42F, 'M', u'я'), (0x430, 'V'), (0x460, 'M', u'ѡ'), (0x461, 'V'), (0x462, 'M', u'ѣ'), (0x463, 'V'), (0x464, 'M', u'ѥ'), (0x465, 'V'), (0x466, 'M', u'ѧ'), (0x467, 'V'), (0x468, 'M', u'ѩ'), (0x469, 'V'), (0x46A, 'M', u'ѫ'), (0x46B, 'V'), (0x46C, 'M', u'ѭ'), (0x46D, 'V'), (0x46E, 'M', u'ѯ'), (0x46F, 'V'), (0x470, 'M', u'ѱ'), (0x471, 'V'), (0x472, 'M', u'ѳ'), (0x473, 'V'), (0x474, 'M', u'ѵ'), (0x475, 'V'), (0x476, 'M', u'ѷ'), (0x477, 'V'), (0x478, 'M', u'ѹ'), (0x479, 'V'), (0x47A, 'M', u'ѻ'), (0x47B, 'V'), (0x47C, 'M', u'ѽ'), (0x47D, 'V'), (0x47E, 'M', u'ѿ'), (0x47F, 'V'), (0x480, 'M', u'ҁ'), (0x481, 'V'), (0x48A, 'M', u'ҋ'), (0x48B, 'V'), (0x48C, 'M', u'ҍ'), (0x48D, 'V'), (0x48E, 'M', u'ҏ'), (0x48F, 'V'), (0x490, 'M', u'ґ'), (0x491, 'V'), (0x492, 'M', u'ғ'), (0x493, 'V'), (0x494, 'M', u'ҕ'), (0x495, 'V'), (0x496, 'M', u'җ'), (0x497, 'V'), (0x498, 'M', u'ҙ'), (0x499, 'V'), (0x49A, 'M', u'қ'), (0x49B, 'V'), (0x49C, 'M', u'ҝ'), (0x49D, 'V'), ] def _seg_8(): return [ (0x49E, 'M', u'ҟ'), (0x49F, 'V'), (0x4A0, 'M', u'ҡ'), (0x4A1, 'V'), (0x4A2, 'M', u'ң'), (0x4A3, 'V'), (0x4A4, 'M', u'ҥ'), (0x4A5, 'V'), (0x4A6, 'M', u'ҧ'), (0x4A7, 'V'), (0x4A8, 'M', u'ҩ'), (0x4A9, 'V'), (0x4AA, 'M', u'ҫ'), (0x4AB, 'V'), (0x4AC, 'M', u'ҭ'), (0x4AD, 'V'), (0x4AE, 'M', u'ү'), (0x4AF, 'V'), (0x4B0, 'M', u'ұ'), (0x4B1, 'V'), (0x4B2, 'M', u'ҳ'), (0x4B3, 'V'), (0x4B4, 'M', u'ҵ'), (0x4B5, 'V'), (0x4B6, 'M', u'ҷ'), (0x4B7, 'V'), (0x4B8, 'M', u'ҹ'), (0x4B9, 'V'), (0x4BA, 'M', u'һ'), (0x4BB, 'V'), (0x4BC, 'M', u'ҽ'), (0x4BD, 'V'), (0x4BE, 'M', u'ҿ'), (0x4BF, 'V'), (0x4C0, 'X'), (0x4C1, 'M', u'ӂ'), (0x4C2, 'V'), (0x4C3, 'M', u'ӄ'), (0x4C4, 'V'), (0x4C5, 'M', u'ӆ'), (0x4C6, 'V'), (0x4C7, 'M', u'ӈ'), (0x4C8, 'V'), (0x4C9, 'M', u'ӊ'), (0x4CA, 'V'), (0x4CB, 'M', u'ӌ'), (0x4CC, 'V'), (0x4CD, 'M', u'ӎ'), (0x4CE, 'V'), (0x4D0, 'M', u'ӑ'), (0x4D1, 'V'), (0x4D2, 'M', u'ӓ'), (0x4D3, 'V'), (0x4D4, 'M', u'ӕ'), (0x4D5, 'V'), (0x4D6, 'M', u'ӗ'), (0x4D7, 'V'), (0x4D8, 'M', u'ә'), (0x4D9, 'V'), (0x4DA, 'M', u'ӛ'), (0x4DB, 'V'), (0x4DC, 'M', u'ӝ'), (0x4DD, 'V'), (0x4DE, 'M', u'ӟ'), (0x4DF, 'V'), (0x4E0, 'M', u'ӡ'), (0x4E1, 'V'), (0x4E2, 'M', u'ӣ'), (0x4E3, 'V'), (0x4E4, 'M', u'ӥ'), (0x4E5, 'V'), (0x4E6, 'M', u'ӧ'), (0x4E7, 'V'), (0x4E8, 'M', u'ө'), (0x4E9, 'V'), (0x4EA, 'M', u'ӫ'), (0x4EB, 'V'), (0x4EC, 'M', u'ӭ'), (0x4ED, 'V'), (0x4EE, 'M', u'ӯ'), (0x4EF, 'V'), (0x4F0, 'M', u'ӱ'), (0x4F1, 'V'), (0x4F2, 'M', u'ӳ'), (0x4F3, 'V'), (0x4F4, 'M', u'ӵ'), (0x4F5, 'V'), (0x4F6, 'M', u'ӷ'), (0x4F7, 'V'), (0x4F8, 'M', u'ӹ'), (0x4F9, 'V'), (0x4FA, 'M', u'ӻ'), (0x4FB, 'V'), (0x4FC, 'M', u'ӽ'), (0x4FD, 'V'), (0x4FE, 'M', u'ӿ'), (0x4FF, 'V'), (0x500, 'M', u'ԁ'), (0x501, 'V'), (0x502, 'M', u'ԃ'), ] def _seg_9(): return [ (0x503, 'V'), (0x504, 'M', u'ԅ'), (0x505, 'V'), (0x506, 'M', u'ԇ'), (0x507, 'V'), (0x508, 'M', u'ԉ'), (0x509, 'V'), (0x50A, 'M', u'ԋ'), (0x50B, 'V'), (0x50C, 'M', u'ԍ'), (0x50D, 'V'), (0x50E, 'M', u'ԏ'), (0x50F, 'V'), (0x510, 'M', u'ԑ'), (0x511, 'V'), (0x512, 'M', u'ԓ'), (0x513, 'V'), (0x514, 'M', u'ԕ'), (0x515, 'V'), (0x516, 'M', u'ԗ'), (0x517, 'V'), (0x518, 'M', u'ԙ'), (0x519, 'V'), (0x51A, 'M', u'ԛ'), (0x51B, 'V'), (0x51C, 'M', u'ԝ'), (0x51D, 'V'), (0x51E, 'M', u'ԟ'), (0x51F, 'V'), (0x520, 'M', u'ԡ'), (0x521, 'V'), (0x522, 'M', u'ԣ'), (0x523, 'V'), (0x524, 'M', u'ԥ'), (0x525, 'V'), (0x526, 'M', u'ԧ'), (0x527, 'V'), (0x528, 'M', u'ԩ'), (0x529, 'V'), (0x52A, 'M', u'ԫ'), (0x52B, 'V'), (0x52C, 'M', u'ԭ'), (0x52D, 'V'), (0x52E, 'M', u'ԯ'), (0x52F, 'V'), (0x530, 'X'), (0x531, 'M', u'ա'), (0x532, 'M', u'բ'), (0x533, 'M', u'գ'), (0x534, 'M', u'դ'), (0x535, 'M', u'ե'), (0x536, 'M', u'զ'), (0x537, 'M', u'է'), (0x538, 'M', u'ը'), (0x539, 'M', u'թ'), (0x53A, 'M', u'ժ'), (0x53B, 'M', u'ի'), (0x53C, 'M', u'լ'), (0x53D, 'M', u'խ'), (0x53E, 'M', u'ծ'), (0x53F, 'M', u'կ'), (0x540, 'M', u'հ'), (0x541, 'M', u'ձ'), (0x542, 'M', u'ղ'), (0x543, 'M', u'ճ'), (0x544, 'M', u'մ'), (0x545, 'M', u'յ'), (0x546, 'M', u'ն'), (0x547, 'M', u'շ'), (0x548, 'M', u'ո'), (0x549, 'M', u'չ'), (0x54A, 'M', u'պ'), (0x54B, 'M', u'ջ'), (0x54C, 'M', u'ռ'), (0x54D, 'M', u'ս'), (0x54E, 'M', u'վ'), (0x54F, 'M', u'տ'), (0x550, 'M', u'ր'), (0x551, 'M', u'ց'), (0x552, 'M', u'ւ'), (0x553, 'M', u'փ'), (0x554, 'M', u'ք'), (0x555, 'M', u'օ'), (0x556, 'M', u'ֆ'), (0x557, 'X'), (0x559, 'V'), (0x587, 'M', u'եւ'), (0x588, 'V'), (0x58B, 'X'), (0x58D, 'V'), (0x590, 'X'), (0x591, 'V'), (0x5C8, 'X'), (0x5D0, 'V'), (0x5EB, 'X'), (0x5EF, 'V'), (0x5F5, 'X'), (0x606, 'V'), (0x61C, 'X'), (0x61E, 'V'), ] def _seg_10(): return [ (0x675, 'M', u'اٴ'), (0x676, 'M', u'وٴ'), (0x677, 'M', u'ۇٴ'), (0x678, 'M', u'يٴ'), (0x679, 'V'), (0x6DD, 'X'), (0x6DE, 'V'), (0x70E, 'X'), (0x710, 'V'), (0x74B, 'X'), (0x74D, 'V'), (0x7B2, 'X'), (0x7C0, 'V'), (0x7FB, 'X'), (0x7FD, 'V'), (0x82E, 'X'), (0x830, 'V'), (0x83F, 'X'), (0x840, 'V'), (0x85C, 'X'), (0x85E, 'V'), (0x85F, 'X'), (0x860, 'V'), (0x86B, 'X'), (0x8A0, 'V'), (0x8B5, 'X'), (0x8B6, 'V'), (0x8BE, 'X'), (0x8D3, 'V'), (0x8E2, 'X'), (0x8E3, 'V'), (0x958, 'M', u'क़'), (0x959, 'M', u'ख़'), (0x95A, 'M', u'ग़'), (0x95B, 'M', u'ज़'), (0x95C, 'M', u'ड़'), (0x95D, 'M', u'ढ़'), (0x95E, 'M', u'फ़'), (0x95F, 'M', u'य़'), (0x960, 'V'), (0x984, 'X'), (0x985, 'V'), (0x98D, 'X'), (0x98F, 'V'), (0x991, 'X'), (0x993, 'V'), (0x9A9, 'X'), (0x9AA, 'V'), (0x9B1, 'X'), (0x9B2, 'V'), (0x9B3, 'X'), (0x9B6, 'V'), (0x9BA, 'X'), (0x9BC, 'V'), (0x9C5, 'X'), (0x9C7, 'V'), (0x9C9, 'X'), (0x9CB, 'V'), (0x9CF, 'X'), (0x9D7, 'V'), (0x9D8, 'X'), (0x9DC, 'M', u'ড়'), (0x9DD, 'M', u'ঢ়'), (0x9DE, 'X'), (0x9DF, 'M', u'য়'), (0x9E0, 'V'), (0x9E4, 'X'), (0x9E6, 'V'), (0x9FF, 'X'), (0xA01, 'V'), (0xA04, 'X'), (0xA05, 'V'), (0xA0B, 'X'), (0xA0F, 'V'), (0xA11, 'X'), (0xA13, 'V'), (0xA29, 'X'), (0xA2A, 'V'), (0xA31, 'X'), (0xA32, 'V'), (0xA33, 'M', u'ਲ਼'), (0xA34, 'X'), (0xA35, 'V'), (0xA36, 'M', u'ਸ਼'), (0xA37, 'X'), (0xA38, 'V'), (0xA3A, 'X'), (0xA3C, 'V'), (0xA3D, 'X'), (0xA3E, 'V'), (0xA43, 'X'), (0xA47, 'V'), (0xA49, 'X'), (0xA4B, 'V'), (0xA4E, 'X'), (0xA51, 'V'), (0xA52, 'X'), (0xA59, 'M', u'ਖ਼'), (0xA5A, 'M', u'ਗ਼'), (0xA5B, 'M', u'ਜ਼'), ] def _seg_11(): return [ (0xA5C, 'V'), (0xA5D, 'X'), (0xA5E, 'M', u'ਫ਼'), (0xA5F, 'X'), (0xA66, 'V'), (0xA77, 'X'), (0xA81, 'V'), (0xA84, 'X'), (0xA85, 'V'), (0xA8E, 'X'), (0xA8F, 'V'), (0xA92, 'X'), (0xA93, 'V'), (0xAA9, 'X'), (0xAAA, 'V'), (0xAB1, 'X'), (0xAB2, 'V'), (0xAB4, 'X'), (0xAB5, 'V'), (0xABA, 'X'), (0xABC, 'V'), (0xAC6, 'X'), (0xAC7, 'V'), (0xACA, 'X'), (0xACB, 'V'), (0xACE, 'X'), (0xAD0, 'V'), (0xAD1, 'X'), (0xAE0, 'V'), (0xAE4, 'X'), (0xAE6, 'V'), (0xAF2, 'X'), (0xAF9, 'V'), (0xB00, 'X'), (0xB01, 'V'), (0xB04, 'X'), (0xB05, 'V'), (0xB0D, 'X'), (0xB0F, 'V'), (0xB11, 'X'), (0xB13, 'V'), (0xB29, 'X'), (0xB2A, 'V'), (0xB31, 'X'), (0xB32, 'V'), (0xB34, 'X'), (0xB35, 'V'), (0xB3A, 'X'), (0xB3C, 'V'), (0xB45, 'X'), (0xB47, 'V'), (0xB49, 'X'), (0xB4B, 'V'), (0xB4E, 'X'), (0xB56, 'V'), (0xB58, 'X'), (0xB5C, 'M', u'ଡ଼'), (0xB5D, 'M', u'ଢ଼'), (0xB5E, 'X'), (0xB5F, 'V'), (0xB64, 'X'), (0xB66, 'V'), (0xB78, 'X'), (0xB82, 'V'), (0xB84, 'X'), (0xB85, 'V'), (0xB8B, 'X'), (0xB8E, 'V'), (0xB91, 'X'), (0xB92, 'V'), (0xB96, 'X'), (0xB99, 'V'), (0xB9B, 'X'), (0xB9C, 'V'), (0xB9D, 'X'), (0xB9E, 'V'), (0xBA0, 'X'), (0xBA3, 'V'), (0xBA5, 'X'), (0xBA8, 'V'), (0xBAB, 'X'), (0xBAE, 'V'), (0xBBA, 'X'), (0xBBE, 'V'), (0xBC3, 'X'), (0xBC6, 'V'), (0xBC9, 'X'), (0xBCA, 'V'), (0xBCE, 'X'), (0xBD0, 'V'), (0xBD1, 'X'), (0xBD7, 'V'), (0xBD8, 'X'), (0xBE6, 'V'), (0xBFB, 'X'), (0xC00, 'V'), (0xC0D, 'X'), (0xC0E, 'V'), (0xC11, 'X'), (0xC12, 'V'), ] def _seg_12(): return [ (0xC29, 'X'), (0xC2A, 'V'), (0xC3A, 'X'), (0xC3D, 'V'), (0xC45, 'X'), (0xC46, 'V'), (0xC49, 'X'), (0xC4A, 'V'), (0xC4E, 'X'), (0xC55, 'V'), (0xC57, 'X'), (0xC58, 'V'), (0xC5B, 'X'), (0xC60, 'V'), (0xC64, 'X'), (0xC66, 'V'), (0xC70, 'X'), (0xC78, 'V'), (0xC8D, 'X'), (0xC8E, 'V'), (0xC91, 'X'), (0xC92, 'V'), (0xCA9, 'X'), (0xCAA, 'V'), (0xCB4, 'X'), (0xCB5, 'V'), (0xCBA, 'X'), (0xCBC, 'V'), (0xCC5, 'X'), (0xCC6, 'V'), (0xCC9, 'X'), (0xCCA, 'V'), (0xCCE, 'X'), (0xCD5, 'V'), (0xCD7, 'X'), (0xCDE, 'V'), (0xCDF, 'X'), (0xCE0, 'V'), (0xCE4, 'X'), (0xCE6, 'V'), (0xCF0, 'X'), (0xCF1, 'V'), (0xCF3, 'X'), (0xD00, 'V'), (0xD04, 'X'), (0xD05, 'V'), (0xD0D, 'X'), (0xD0E, 'V'), (0xD11, 'X'), (0xD12, 'V'), (0xD45, 'X'), (0xD46, 'V'), (0xD49, 'X'), (0xD4A, 'V'), (0xD50, 'X'), (0xD54, 'V'), (0xD64, 'X'), (0xD66, 'V'), (0xD80, 'X'), (0xD82, 'V'), (0xD84, 'X'), (0xD85, 'V'), (0xD97, 'X'), (0xD9A, 'V'), (0xDB2, 'X'), (0xDB3, 'V'), (0xDBC, 'X'), (0xDBD, 'V'), (0xDBE, 'X'), (0xDC0, 'V'), (0xDC7, 'X'), (0xDCA, 'V'), (0xDCB, 'X'), (0xDCF, 'V'), (0xDD5, 'X'), (0xDD6, 'V'), (0xDD7, 'X'), (0xDD8, 'V'), (0xDE0, 'X'), (0xDE6, 'V'), (0xDF0, 'X'), (0xDF2, 'V'), (0xDF5, 'X'), (0xE01, 'V'), (0xE33, 'M', u'ํา'), (0xE34, 'V'), (0xE3B, 'X'), (0xE3F, 'V'), (0xE5C, 'X'), (0xE81, 'V'), (0xE83, 'X'), (0xE84, 'V'), (0xE85, 'X'), (0xE87, 'V'), (0xE89, 'X'), (0xE8A, 'V'), (0xE8B, 'X'), (0xE8D, 'V'), (0xE8E, 'X'), (0xE94, 'V'), ] def _seg_13(): return [ (0xE98, 'X'), (0xE99, 'V'), (0xEA0, 'X'), (0xEA1, 'V'), (0xEA4, 'X'), (0xEA5, 'V'), (0xEA6, 'X'), (0xEA7, 'V'), (0xEA8, 'X'), (0xEAA, 'V'), (0xEAC, 'X'), (0xEAD, 'V'), (0xEB3, 'M', u'ໍາ'), (0xEB4, 'V'), (0xEBA, 'X'), (0xEBB, 'V'), (0xEBE, 'X'), (0xEC0, 'V'), (0xEC5, 'X'), (0xEC6, 'V'), (0xEC7, 'X'), (0xEC8, 'V'), (0xECE, 'X'), (0xED0, 'V'), (0xEDA, 'X'), (0xEDC, 'M', u'ຫນ'), (0xEDD, 'M', u'ຫມ'), (0xEDE, 'V'), (0xEE0, 'X'), (0xF00, 'V'), (0xF0C, 'M', u'་'), (0xF0D, 'V'), (0xF43, 'M', u'གྷ'), (0xF44, 'V'), (0xF48, 'X'), (0xF49, 'V'), (0xF4D, 'M', u'ཌྷ'), (0xF4E, 'V'), (0xF52, 'M', u'དྷ'), (0xF53, 'V'), (0xF57, 'M', u'བྷ'), (0xF58, 'V'), (0xF5C, 'M', u'ཛྷ'), (0xF5D, 'V'), (0xF69, 'M', u'ཀྵ'), (0xF6A, 'V'), (0xF6D, 'X'), (0xF71, 'V'), (0xF73, 'M', u'ཱི'), (0xF74, 'V'), (0xF75, 'M', u'ཱུ'), (0xF76, 'M', u'ྲྀ'), (0xF77, 'M', u'ྲཱྀ'), (0xF78, 'M', u'ླྀ'), (0xF79, 'M', u'ླཱྀ'), (0xF7A, 'V'), (0xF81, 'M', u'ཱྀ'), (0xF82, 'V'), (0xF93, 'M', u'ྒྷ'), (0xF94, 'V'), (0xF98, 'X'), (0xF99, 'V'), (0xF9D, 'M', u'ྜྷ'), (0xF9E, 'V'), (0xFA2, 'M', u'ྡྷ'), (0xFA3, 'V'), (0xFA7, 'M', u'ྦྷ'), (0xFA8, 'V'), (0xFAC, 'M', u'ྫྷ'), (0xFAD, 'V'), (0xFB9, 'M', u'ྐྵ'), (0xFBA, 'V'), (0xFBD, 'X'), (0xFBE, 'V'), (0xFCD, 'X'), (0xFCE, 'V'), (0xFDB, 'X'), (0x1000, 'V'), (0x10A0, 'X'), (0x10C7, 'M', u'ⴧ'), (0x10C8, 'X'), (0x10CD, 'M', u'ⴭ'), (0x10CE, 'X'), (0x10D0, 'V'), (0x10FC, 'M', u'ნ'), (0x10FD, 'V'), (0x115F, 'X'), (0x1161, 'V'), (0x1249, 'X'), (0x124A, 'V'), (0x124E, 'X'), (0x1250, 'V'), (0x1257, 'X'), (0x1258, 'V'), (0x1259, 'X'), (0x125A, 'V'), (0x125E, 'X'), (0x1260, 'V'), (0x1289, 'X'), (0x128A, 'V'), ] def _seg_14(): return [ (0x128E, 'X'), (0x1290, 'V'), (0x12B1, 'X'), (0x12B2, 'V'), (0x12B6, 'X'), (0x12B8, 'V'), (0x12BF, 'X'), (0x12C0, 'V'), (0x12C1, 'X'), (0x12C2, 'V'), (0x12C6, 'X'), (0x12C8, 'V'), (0x12D7, 'X'), (0x12D8, 'V'), (0x1311, 'X'), (0x1312, 'V'), (0x1316, 'X'), (0x1318, 'V'), (0x135B, 'X'), (0x135D, 'V'), (0x137D, 'X'), (0x1380, 'V'), (0x139A, 'X'), (0x13A0, 'V'), (0x13F6, 'X'), (0x13F8, 'M', u'Ᏸ'), (0x13F9, 'M', u'Ᏹ'), (0x13FA, 'M', u'Ᏺ'), (0x13FB, 'M', u'Ᏻ'), (0x13FC, 'M', u'Ᏼ'), (0x13FD, 'M', u'Ᏽ'), (0x13FE, 'X'), (0x1400, 'V'), (0x1680, 'X'), (0x1681, 'V'), (0x169D, 'X'), (0x16A0, 'V'), (0x16F9, 'X'), (0x1700, 'V'), (0x170D, 'X'), (0x170E, 'V'), (0x1715, 'X'), (0x1720, 'V'), (0x1737, 'X'), (0x1740, 'V'), (0x1754, 'X'), (0x1760, 'V'), (0x176D, 'X'), (0x176E, 'V'), (0x1771, 'X'), (0x1772, 'V'), (0x1774, 'X'), (0x1780, 'V'), (0x17B4, 'X'), (0x17B6, 'V'), (0x17DE, 'X'), (0x17E0, 'V'), (0x17EA, 'X'), (0x17F0, 'V'), (0x17FA, 'X'), (0x1800, 'V'), (0x1806, 'X'), (0x1807, 'V'), (0x180B, 'I'), (0x180E, 'X'), (0x1810, 'V'), (0x181A, 'X'), (0x1820, 'V'), (0x1879, 'X'), (0x1880, 'V'), (0x18AB, 'X'), (0x18B0, 'V'), (0x18F6, 'X'), (0x1900, 'V'), (0x191F, 'X'), (0x1920, 'V'), (0x192C, 'X'), (0x1930, 'V'), (0x193C, 'X'), (0x1940, 'V'), (0x1941, 'X'), (0x1944, 'V'), (0x196E, 'X'), (0x1970, 'V'), (0x1975, 'X'), (0x1980, 'V'), (0x19AC, 'X'), (0x19B0, 'V'), (0x19CA, 'X'), (0x19D0, 'V'), (0x19DB, 'X'), (0x19DE, 'V'), (0x1A1C, 'X'), (0x1A1E, 'V'), (0x1A5F, 'X'), (0x1A60, 'V'), (0x1A7D, 'X'), (0x1A7F, 'V'), (0x1A8A, 'X'), (0x1A90, 'V'), ] def _seg_15(): return [ (0x1A9A, 'X'), (0x1AA0, 'V'), (0x1AAE, 'X'), (0x1AB0, 'V'), (0x1ABF, 'X'), (0x1B00, 'V'), (0x1B4C, 'X'), (0x1B50, 'V'), (0x1B7D, 'X'), (0x1B80, 'V'), (0x1BF4, 'X'), (0x1BFC, 'V'), (0x1C38, 'X'), (0x1C3B, 'V'), (0x1C4A, 'X'), (0x1C4D, 'V'), (0x1C80, 'M', u'в'), (0x1C81, 'M', u'д'), (0x1C82, 'M', u'о'), (0x1C83, 'M', u'с'), (0x1C84, 'M', u'т'), (0x1C86, 'M', u'ъ'), (0x1C87, 'M', u'ѣ'), (0x1C88, 'M', u'ꙋ'), (0x1C89, 'X'), (0x1CC0, 'V'), (0x1CC8, 'X'), (0x1CD0, 'V'), (0x1CFA, 'X'), (0x1D00, 'V'), (0x1D2C, 'M', u'a'), (0x1D2D, 'M', u'æ'), (0x1D2E, 'M', u'b'), (0x1D2F, 'V'), (0x1D30, 'M', u'd'), (0x1D31, 'M', u'e'), (0x1D32, 'M', u'ǝ'), (0x1D33, 'M', u'g'), (0x1D34, 'M', u'h'), (0x1D35, 'M', u'i'), (0x1D36, 'M', u'j'), (0x1D37, 'M', u'k'), (0x1D38, 'M', u'l'), (0x1D39, 'M', u'm'), (0x1D3A, 'M', u'n'), (0x1D3B, 'V'), (0x1D3C, 'M', u'o'), (0x1D3D, 'M', u'ȣ'), (0x1D3E, 'M', u'p'), (0x1D3F, 'M', u'r'), (0x1D40, 'M', u't'), (0x1D41, 'M', u'u'), (0x1D42, 'M', u'w'), (0x1D43, 'M', u'a'), (0x1D44, 'M', u'ɐ'), (0x1D45, 'M', u'ɑ'), (0x1D46, 'M', u'ᴂ'), (0x1D47, 'M', u'b'), (0x1D48, 'M', u'd'), (0x1D49, 'M', u'e'), (0x1D4A, 'M', u'ə'), (0x1D4B, 'M', u'ɛ'), (0x1D4C, 'M', u'ɜ'), (0x1D4D, 'M', u'g'), (0x1D4E, 'V'), (0x1D4F, 'M', u'k'), (0x1D50, 'M', u'm'), (0x1D51, 'M', u'ŋ'), (0x1D52, 'M', u'o'), (0x1D53, 'M', u'ɔ'), (0x1D54, 'M', u'ᴖ'), (0x1D55, 'M', u'ᴗ'), (0x1D56, 'M', u'p'), (0x1D57, 'M', u't'), (0x1D58, 'M', u'u'), (0x1D59, 'M', u'ᴝ'), (0x1D5A, 'M', u'ɯ'), (0x1D5B, 'M', u'v'), (0x1D5C, 'M', u'ᴥ'), (0x1D5D, 'M', u'β'), (0x1D5E, 'M', u'γ'), (0x1D5F, 'M', u'δ'), (0x1D60, 'M', u'φ'), (0x1D61, 'M', u'χ'), (0x1D62, 'M', u'i'), (0x1D63, 'M', u'r'), (0x1D64, 'M', u'u'), (0x1D65, 'M', u'v'), (0x1D66, 'M', u'β'), (0x1D67, 'M', u'γ'), (0x1D68, 'M', u'ρ'), (0x1D69, 'M', u'φ'), (0x1D6A, 'M', u'χ'), (0x1D6B, 'V'), (0x1D78, 'M', u'н'), (0x1D79, 'V'), (0x1D9B, 'M', u'ɒ'), (0x1D9C, 'M', u'c'), (0x1D9D, 'M', u'ɕ'), (0x1D9E, 'M', u'ð'), ] def _seg_16(): return [ (0x1D9F, 'M', u'ɜ'), (0x1DA0, 'M', u'f'), (0x1DA1, 'M', u'ɟ'), (0x1DA2, 'M', u'ɡ'), (0x1DA3, 'M', u'ɥ'), (0x1DA4, 'M', u'ɨ'), (0x1DA5, 'M', u'ɩ'), (0x1DA6, 'M', u'ɪ'), (0x1DA7, 'M', u'ᵻ'), (0x1DA8, 'M', u'ʝ'), (0x1DA9, 'M', u'ɭ'), (0x1DAA, 'M', u'ᶅ'), (0x1DAB, 'M', u'ʟ'), (0x1DAC, 'M', u'ɱ'), (0x1DAD, 'M', u'ɰ'), (0x1DAE, 'M', u'ɲ'), (0x1DAF, 'M', u'ɳ'), (0x1DB0, 'M', u'ɴ'), (0x1DB1, 'M', u'ɵ'), (0x1DB2, 'M', u'ɸ'), (0x1DB3, 'M', u'ʂ'), (0x1DB4, 'M', u'ʃ'), (0x1DB5, 'M', u'ƫ'), (0x1DB6, 'M', u'ʉ'), (0x1DB7, 'M', u'ʊ'), (0x1DB8, 'M', u'ᴜ'), (0x1DB9, 'M', u'ʋ'), (0x1DBA, 'M', u'ʌ'), (0x1DBB, 'M', u'z'), (0x1DBC, 'M', u'ʐ'), (0x1DBD, 'M', u'ʑ'), (0x1DBE, 'M', u'ʒ'), (0x1DBF, 'M', u'θ'), (0x1DC0, 'V'), (0x1DFA, 'X'), (0x1DFB, 'V'), (0x1E00, 'M', u'ḁ'), (0x1E01, 'V'), (0x1E02, 'M', u'ḃ'), (0x1E03, 'V'), (0x1E04, 'M', u'ḅ'), (0x1E05, 'V'), (0x1E06, 'M', u'ḇ'), (0x1E07, 'V'), (0x1E08, 'M', u'ḉ'), (0x1E09, 'V'), (0x1E0A, 'M', u'ḋ'), (0x1E0B, 'V'), (0x1E0C, 'M', u'ḍ'), (0x1E0D, 'V'), (0x1E0E, 'M', u'ḏ'), (0x1E0F, 'V'), (0x1E10, 'M', u'ḑ'), (0x1E11, 'V'), (0x1E12, 'M', u'ḓ'), (0x1E13, 'V'), (0x1E14, 'M', u'ḕ'), (0x1E15, 'V'), (0x1E16, 'M', u'ḗ'), (0x1E17, 'V'), (0x1E18, 'M', u'ḙ'), (0x1E19, 'V'), (0x1E1A, 'M', u'ḛ'), (0x1E1B, 'V'), (0x1E1C, 'M', u'ḝ'), (0x1E1D, 'V'), (0x1E1E, 'M', u'ḟ'), (0x1E1F, 'V'), (0x1E20, 'M', u'ḡ'), (0x1E21, 'V'), (0x1E22, 'M', u'ḣ'), (0x1E23, 'V'), (0x1E24, 'M', u'ḥ'), (0x1E25, 'V'), (0x1E26, 'M', u'ḧ'), (0x1E27, 'V'), (0x1E28, 'M', u'ḩ'), (0x1E29, 'V'), (0x1E2A, 'M', u'ḫ'), (0x1E2B, 'V'), (0x1E2C, 'M', u'ḭ'), (0x1E2D, 'V'), (0x1E2E, 'M', u'ḯ'), (0x1E2F, 'V'), (0x1E30, 'M', u'ḱ'), (0x1E31, 'V'), (0x1E32, 'M', u'ḳ'), (0x1E33, 'V'), (0x1E34, 'M', u'ḵ'), (0x1E35, 'V'), (0x1E36, 'M', u'ḷ'), (0x1E37, 'V'), (0x1E38, 'M', u'ḹ'), (0x1E39, 'V'), (0x1E3A, 'M', u'ḻ'), (0x1E3B, 'V'), (0x1E3C, 'M', u'ḽ'), (0x1E3D, 'V'), (0x1E3E, 'M', u'ḿ'), (0x1E3F, 'V'), ] def _seg_17(): return [ (0x1E40, 'M', u'ṁ'), (0x1E41, 'V'), (0x1E42, 'M', u'ṃ'), (0x1E43, 'V'), (0x1E44, 'M', u'ṅ'), (0x1E45, 'V'), (0x1E46, 'M', u'ṇ'), (0x1E47, 'V'), (0x1E48, 'M', u'ṉ'), (0x1E49, 'V'), (0x1E4A, 'M', u'ṋ'), (0x1E4B, 'V'), (0x1E4C, 'M', u'ṍ'), (0x1E4D, 'V'), (0x1E4E, 'M', u'ṏ'), (0x1E4F, 'V'), (0x1E50, 'M', u'ṑ'), (0x1E51, 'V'), (0x1E52, 'M', u'ṓ'), (0x1E53, 'V'), (0x1E54, 'M', u'ṕ'), (0x1E55, 'V'), (0x1E56, 'M', u'ṗ'), (0x1E57, 'V'), (0x1E58, 'M', u'ṙ'), (0x1E59, 'V'), (0x1E5A, 'M', u'ṛ'), (0x1E5B, 'V'), (0x1E5C, 'M', u'ṝ'), (0x1E5D, 'V'), (0x1E5E, 'M', u'ṟ'), (0x1E5F, 'V'), (0x1E60, 'M', u'ṡ'), (0x1E61, 'V'), (0x1E62, 'M', u'ṣ'), (0x1E63, 'V'), (0x1E64, 'M', u'ṥ'), (0x1E65, 'V'), (0x1E66, 'M', u'ṧ'), (0x1E67, 'V'), (0x1E68, 'M', u'ṩ'), (0x1E69, 'V'), (0x1E6A, 'M', u'ṫ'), (0x1E6B, 'V'), (0x1E6C, 'M', u'ṭ'), (0x1E6D, 'V'), (0x1E6E, 'M', u'ṯ'), (0x1E6F, 'V'), (0x1E70, 'M', u'ṱ'), (0x1E71, 'V'), (0x1E72, 'M', u'ṳ'), (0x1E73, 'V'), (0x1E74, 'M', u'ṵ'), (0x1E75, 'V'), (0x1E76, 'M', u'ṷ'), (0x1E77, 'V'), (0x1E78, 'M', u'ṹ'), (0x1E79, 'V'), (0x1E7A, 'M', u'ṻ'), (0x1E7B, 'V'), (0x1E7C, 'M', u'ṽ'), (0x1E7D, 'V'), (0x1E7E, 'M', u'ṿ'), (0x1E7F, 'V'), (0x1E80, 'M', u'ẁ'), (0x1E81, 'V'), (0x1E82, 'M', u'ẃ'), (0x1E83, 'V'), (0x1E84, 'M', u'ẅ'), (0x1E85, 'V'), (0x1E86, 'M', u'ẇ'), (0x1E87, 'V'), (0x1E88, 'M', u'ẉ'), (0x1E89, 'V'), (0x1E8A, 'M', u'ẋ'), (0x1E8B, 'V'), (0x1E8C, 'M', u'ẍ'), (0x1E8D, 'V'), (0x1E8E, 'M', u'ẏ'), (0x1E8F, 'V'), (0x1E90, 'M', u'ẑ'), (0x1E91, 'V'), (0x1E92, 'M', u'ẓ'), (0x1E93, 'V'), (0x1E94, 'M', u'ẕ'), (0x1E95, 'V'), (0x1E9A, 'M', u'aʾ'), (0x1E9B, 'M', u'ṡ'), (0x1E9C, 'V'), (0x1E9E, 'M', u'ss'), (0x1E9F, 'V'), (0x1EA0, 'M', u'ạ'), (0x1EA1, 'V'), (0x1EA2, 'M', u'ả'), (0x1EA3, 'V'), (0x1EA4, 'M', u'ấ'), (0x1EA5, 'V'), (0x1EA6, 'M', u'ầ'), (0x1EA7, 'V'), (0x1EA8, 'M', u'ẩ'), ] def _seg_18(): return [ (0x1EA9, 'V'), (0x1EAA, 'M', u'ẫ'), (0x1EAB, 'V'), (0x1EAC, 'M', u'ậ'), (0x1EAD, 'V'), (0x1EAE, 'M', u'ắ'), (0x1EAF, 'V'), (0x1EB0, 'M', u'ằ'), (0x1EB1, 'V'), (0x1EB2, 'M', u'ẳ'), (0x1EB3, 'V'), (0x1EB4, 'M', u'ẵ'), (0x1EB5, 'V'), (0x1EB6, 'M', u'ặ'), (0x1EB7, 'V'), (0x1EB8, 'M', u'ẹ'), (0x1EB9, 'V'), (0x1EBA, 'M', u'ẻ'), (0x1EBB, 'V'), (0x1EBC, 'M', u'ẽ'), (0x1EBD, 'V'), (0x1EBE, 'M', u'ế'), (0x1EBF, 'V'), (0x1EC0, 'M', u'ề'), (0x1EC1, 'V'), (0x1EC2, 'M', u'ể'), (0x1EC3, 'V'), (0x1EC4, 'M', u'ễ'), (0x1EC5, 'V'), (0x1EC6, 'M', u'ệ'), (0x1EC7, 'V'), (0x1EC8, 'M', u'ỉ'), (0x1EC9, 'V'), (0x1ECA, 'M', u'ị'), (0x1ECB, 'V'), (0x1ECC, 'M', u'ọ'), (0x1ECD, 'V'), (0x1ECE, 'M', u'ỏ'), (0x1ECF, 'V'), (0x1ED0, 'M', u'ố'), (0x1ED1, 'V'), (0x1ED2, 'M', u'ồ'), (0x1ED3, 'V'), (0x1ED4, 'M', u'ổ'), (0x1ED5, 'V'), (0x1ED6, 'M', u'ỗ'), (0x1ED7, 'V'), (0x1ED8, 'M', u'ộ'), (0x1ED9, 'V'), (0x1EDA, 'M', u'ớ'), (0x1EDB, 'V'), (0x1EDC, 'M', u'ờ'), (0x1EDD, 'V'), (0x1EDE, 'M', u'ở'), (0x1EDF, 'V'), (0x1EE0, 'M', u'ỡ'), (0x1EE1, 'V'), (0x1EE2, 'M', u'ợ'), (0x1EE3, 'V'), (0x1EE4, 'M', u'ụ'), (0x1EE5, 'V'), (0x1EE6, 'M', u'ủ'), (0x1EE7, 'V'), (0x1EE8, 'M', u'ứ'), (0x1EE9, 'V'), (0x1EEA, 'M', u'ừ'), (0x1EEB, 'V'), (0x1EEC, 'M', u'ử'), (0x1EED, 'V'), (0x1EEE, 'M', u'ữ'), (0x1EEF, 'V'), (0x1EF0, 'M', u'ự'), (0x1EF1, 'V'), (0x1EF2, 'M', u'ỳ'), (0x1EF3, 'V'), (0x1EF4, 'M', u'ỵ'), (0x1EF5, 'V'), (0x1EF6, 'M', u'ỷ'), (0x1EF7, 'V'), (0x1EF8, 'M', u'ỹ'), (0x1EF9, 'V'), (0x1EFA, 'M', u'ỻ'), (0x1EFB, 'V'), (0x1EFC, 'M', u'ỽ'), (0x1EFD, 'V'), (0x1EFE, 'M', u'ỿ'), (0x1EFF, 'V'), (0x1F08, 'M', u'ἀ'), (0x1F09, 'M', u'ἁ'), (0x1F0A, 'M', u'ἂ'), (0x1F0B, 'M', u'ἃ'), (0x1F0C, 'M', u'ἄ'), (0x1F0D, 'M', u'ἅ'), (0x1F0E, 'M', u'ἆ'), (0x1F0F, 'M', u'ἇ'), (0x1F10, 'V'), (0x1F16, 'X'), (0x1F18, 'M', u'ἐ'), (0x1F19, 'M', u'ἑ'), (0x1F1A, 'M', u'ἒ'), ] def _seg_19(): return [ (0x1F1B, 'M', u'ἓ'), (0x1F1C, 'M', u'ἔ'), (0x1F1D, 'M', u'ἕ'), (0x1F1E, 'X'), (0x1F20, 'V'), (0x1F28, 'M', u'ἠ'), (0x1F29, 'M', u'ἡ'), (0x1F2A, 'M', u'ἢ'), (0x1F2B, 'M', u'ἣ'), (0x1F2C, 'M', u'ἤ'), (0x1F2D, 'M', u'ἥ'), (0x1F2E, 'M', u'ἦ'), (0x1F2F, 'M', u'ἧ'), (0x1F30, 'V'), (0x1F38, 'M', u'ἰ'), (0x1F39, 'M', u'ἱ'), (0x1F3A, 'M', u'ἲ'), (0x1F3B, 'M', u'ἳ'), (0x1F3C, 'M', u'ἴ'), (0x1F3D, 'M', u'ἵ'), (0x1F3E, 'M', u'ἶ'), (0x1F3F, 'M', u'ἷ'), (0x1F40, 'V'), (0x1F46, 'X'), (0x1F48, 'M', u'ὀ'), (0x1F49, 'M', u'ὁ'), (0x1F4A, 'M', u'ὂ'), (0x1F4B, 'M', u'ὃ'), (0x1F4C, 'M', u'ὄ'), (0x1F4D, 'M', u'ὅ'), (0x1F4E, 'X'), (0x1F50, 'V'), (0x1F58, 'X'), (0x1F59, 'M', u'ὑ'), (0x1F5A, 'X'), (0x1F5B, 'M', u'ὓ'), (0x1F5C, 'X'), (0x1F5D, 'M', u'ὕ'), (0x1F5E, 'X'), (0x1F5F, 'M', u'ὗ'), (0x1F60, 'V'), (0x1F68, 'M', u'ὠ'), (0x1F69, 'M', u'ὡ'), (0x1F6A, 'M', u'ὢ'), (0x1F6B, 'M', u'ὣ'), (0x1F6C, 'M', u'ὤ'), (0x1F6D, 'M', u'ὥ'), (0x1F6E, 'M', u'ὦ'), (0x1F6F, 'M', u'ὧ'), (0x1F70, 'V'), (0x1F71, 'M', u'ά'), (0x1F72, 'V'), (0x1F73, 'M', u'έ'), (0x1F74, 'V'), (0x1F75, 'M', u'ή'), (0x1F76, 'V'), (0x1F77, 'M', u'ί'), (0x1F78, 'V'), (0x1F79, 'M', u'ό'), (0x1F7A, 'V'), (0x1F7B, 'M', u'ύ'), (0x1F7C, 'V'), (0x1F7D, 'M', u'ώ'), (0x1F7E, 'X'), (0x1F80, 'M', u'ἀι'), (0x1F81, 'M', u'ἁι'), (0x1F82, 'M', u'ἂι'), (0x1F83, 'M', u'ἃι'), (0x1F84, 'M', u'ἄι'), (0x1F85, 'M', u'ἅι'), (0x1F86, 'M', u'ἆι'), (0x1F87, 'M', u'ἇι'), (0x1F88, 'M', u'ἀι'), (0x1F89, 'M', u'ἁι'), (0x1F8A, 'M', u'ἂι'), (0x1F8B, 'M', u'ἃι'), (0x1F8C, 'M', u'ἄι'), (0x1F8D, 'M', u'ἅι'), (0x1F8E, 'M', u'ἆι'), (0x1F8F, 'M', u'ἇι'), (0x1F90, 'M', u'ἠι'), (0x1F91, 'M', u'ἡι'), (0x1F92, 'M', u'ἢι'), (0x1F93, 'M', u'ἣι'), (0x1F94, 'M', u'ἤι'), (0x1F95, 'M', u'ἥι'), (0x1F96, 'M', u'ἦι'), (0x1F97, 'M', u'ἧι'), (0x1F98, 'M', u'ἠι'), (0x1F99, 'M', u'ἡι'), (0x1F9A, 'M', u'ἢι'), (0x1F9B, 'M', u'ἣι'), (0x1F9C, 'M', u'ἤι'), (0x1F9D, 'M', u'ἥι'), (0x1F9E, 'M', u'ἦι'), (0x1F9F, 'M', u'ἧι'), (0x1FA0, 'M', u'ὠι'), (0x1FA1, 'M', u'ὡι'), (0x1FA2, 'M', u'ὢι'), (0x1FA3, 'M', u'ὣι'), ] def _seg_20(): return [ (0x1FA4, 'M', u'ὤι'), (0x1FA5, 'M', u'ὥι'), (0x1FA6, 'M', u'ὦι'), (0x1FA7, 'M', u'ὧι'), (0x1FA8, 'M', u'ὠι'), (0x1FA9, 'M', u'ὡι'), (0x1FAA, 'M', u'ὢι'), (0x1FAB, 'M', u'ὣι'), (0x1FAC, 'M', u'ὤι'), (0x1FAD, 'M', u'ὥι'), (0x1FAE, 'M', u'ὦι'), (0x1FAF, 'M', u'ὧι'), (0x1FB0, 'V'), (0x1FB2, 'M', u'ὰι'), (0x1FB3, 'M', u'αι'), (0x1FB4, 'M', u'άι'), (0x1FB5, 'X'), (0x1FB6, 'V'), (0x1FB7, 'M', u'ᾶι'), (0x1FB8, 'M', u'ᾰ'), (0x1FB9, 'M', u'ᾱ'), (0x1FBA, 'M', u'ὰ'), (0x1FBB, 'M', u'ά'), (0x1FBC, 'M', u'αι'), (0x1FBD, '3', u' ̓'), (0x1FBE, 'M', u'ι'), (0x1FBF, '3', u' ̓'), (0x1FC0, '3', u' ͂'), (0x1FC1, '3', u' ̈͂'), (0x1FC2, 'M', u'ὴι'), (0x1FC3, 'M', u'ηι'), (0x1FC4, 'M', u'ήι'), (0x1FC5, 'X'), (0x1FC6, 'V'), (0x1FC7, 'M', u'ῆι'), (0x1FC8, 'M', u'ὲ'), (0x1FC9, 'M', u'έ'), (0x1FCA, 'M', u'ὴ'), (0x1FCB, 'M', u'ή'), (0x1FCC, 'M', u'ηι'), (0x1FCD, '3', u' ̓̀'), (0x1FCE, '3', u' ̓́'), (0x1FCF, '3', u' ̓͂'), (0x1FD0, 'V'), (0x1FD3, 'M', u'ΐ'), (0x1FD4, 'X'), (0x1FD6, 'V'), (0x1FD8, 'M', u'ῐ'), (0x1FD9, 'M', u'ῑ'), (0x1FDA, 'M', u'ὶ'), (0x1FDB, 'M', u'ί'), (0x1FDC, 'X'), (0x1FDD, '3', u' ̔̀'), (0x1FDE, '3', u' ̔́'), (0x1FDF, '3', u' ̔͂'), (0x1FE0, 'V'), (0x1FE3, 'M', u'ΰ'), (0x1FE4, 'V'), (0x1FE8, 'M', u'ῠ'), (0x1FE9, 'M', u'ῡ'), (0x1FEA, 'M', u'ὺ'), (0x1FEB, 'M', u'ύ'), (0x1FEC, 'M', u'ῥ'), (0x1FED, '3', u' ̈̀'), (0x1FEE, '3', u' ̈́'), (0x1FEF, '3', u'`'), (0x1FF0, 'X'), (0x1FF2, 'M', u'ὼι'), (0x1FF3, 'M', u'ωι'), (0x1FF4, 'M', u'ώι'), (0x1FF5, 'X'), (0x1FF6, 'V'), (0x1FF7, 'M', u'ῶι'), (0x1FF8, 'M', u'ὸ'), (0x1FF9, 'M', u'ό'), (0x1FFA, 'M', u'ὼ'), (0x1FFB, 'M', u'ώ'), (0x1FFC, 'M', u'ωι'), (0x1FFD, '3', u' ́'), (0x1FFE, '3', u' ̔'), (0x1FFF, 'X'), (0x2000, '3', u' '), (0x200B, 'I'), (0x200C, 'D', u''), (0x200E, 'X'), (0x2010, 'V'), (0x2011, 'M', u'‐'), (0x2012, 'V'), (0x2017, '3', u' ̳'), (0x2018, 'V'), (0x2024, 'X'), (0x2027, 'V'), (0x2028, 'X'), (0x202F, '3', u' '), (0x2030, 'V'), (0x2033, 'M', u'′′'), (0x2034, 'M', u'′′′'), (0x2035, 'V'), (0x2036, 'M', u'‵‵'), (0x2037, 'M', u'‵‵‵'), ] def _seg_21(): return [ (0x2038, 'V'), (0x203C, '3', u'!!'), (0x203D, 'V'), (0x203E, '3', u' ̅'), (0x203F, 'V'), (0x2047, '3', u'??'), (0x2048, '3', u'?!'), (0x2049, '3', u'!?'), (0x204A, 'V'), (0x2057, 'M', u'′′′′'), (0x2058, 'V'), (0x205F, '3', u' '), (0x2060, 'I'), (0x2061, 'X'), (0x2064, 'I'), (0x2065, 'X'), (0x2070, 'M', u'0'), (0x2071, 'M', u'i'), (0x2072, 'X'), (0x2074, 'M', u'4'), (0x2075, 'M', u'5'), (0x2076, 'M', u'6'), (0x2077, 'M', u'7'), (0x2078, 'M', u'8'), (0x2079, 'M', u'9'), (0x207A, '3', u'+'), (0x207B, 'M', u'−'), (0x207C, '3', u'='), (0x207D, '3', u'('), (0x207E, '3', u')'), (0x207F, 'M', u'n'), (0x2080, 'M', u'0'), (0x2081, 'M', u'1'), (0x2082, 'M', u'2'), (0x2083, 'M', u'3'), (0x2084, 'M', u'4'), (0x2085, 'M', u'5'), (0x2086, 'M', u'6'), (0x2087, 'M', u'7'), (0x2088, 'M', u'8'), (0x2089, 'M', u'9'), (0x208A, '3', u'+'), (0x208B, 'M', u'−'), (0x208C, '3', u'='), (0x208D, '3', u'('), (0x208E, '3', u')'), (0x208F, 'X'), (0x2090, 'M', u'a'), (0x2091, 'M', u'e'), (0x2092, 'M', u'o'), (0x2093, 'M', u'x'), (0x2094, 'M', u'ə'), (0x2095, 'M', u'h'), (0x2096, 'M', u'k'), (0x2097, 'M', u'l'), (0x2098, 'M', u'm'), (0x2099, 'M', u'n'), (0x209A, 'M', u'p'), (0x209B, 'M', u's'), (0x209C, 'M', u't'), (0x209D, 'X'), (0x20A0, 'V'), (0x20A8, 'M', u'rs'), (0x20A9, 'V'), (0x20C0, 'X'), (0x20D0, 'V'), (0x20F1, 'X'), (0x2100, '3', u'a/c'), (0x2101, '3', u'a/s'), (0x2102, 'M', u'c'), (0x2103, 'M', u'°c'), (0x2104, 'V'), (0x2105, '3', u'c/o'), (0x2106, '3', u'c/u'), (0x2107, 'M', u'ɛ'), (0x2108, 'V'), (0x2109, 'M', u'°f'), (0x210A, 'M', u'g'), (0x210B, 'M', u'h'), (0x210F, 'M', u'ħ'), (0x2110, 'M', u'i'), (0x2112, 'M', u'l'), (0x2114, 'V'), (0x2115, 'M', u'n'), (0x2116, 'M', u'no'), (0x2117, 'V'), (0x2119, 'M', u'p'), (0x211A, 'M', u'q'), (0x211B, 'M', u'r'), (0x211E, 'V'), (0x2120, 'M', u'sm'), (0x2121, 'M', u'tel'), (0x2122, 'M', u'tm'), (0x2123, 'V'), (0x2124, 'M', u'z'), (0x2125, 'V'), (0x2126, 'M', u'ω'), (0x2127, 'V'), (0x2128, 'M', u'z'), (0x2129, 'V'), ] def _seg_22(): return [ (0x212A, 'M', u'k'), (0x212B, 'M', u'å'), (0x212C, 'M', u'b'), (0x212D, 'M', u'c'), (0x212E, 'V'), (0x212F, 'M', u'e'), (0x2131, 'M', u'f'), (0x2132, 'X'), (0x2133, 'M', u'm'), (0x2134, 'M', u'o'), (0x2135, 'M', u'א'), (0x2136, 'M', u'ב'), (0x2137, 'M', u'ג'), (0x2138, 'M', u'ד'), (0x2139, 'M', u'i'), (0x213A, 'V'), (0x213B, 'M', u'fax'), (0x213C, 'M', u'π'), (0x213D, 'M', u'γ'), (0x213F, 'M', u'π'), (0x2140, 'M', u'∑'), (0x2141, 'V'), (0x2145, 'M', u'd'), (0x2147, 'M', u'e'), (0x2148, 'M', u'i'), (0x2149, 'M', u'j'), (0x214A, 'V'), (0x2150, 'M', u'1⁄7'), (0x2151, 'M', u'1⁄9'), (0x2152, 'M', u'1⁄10'), (0x2153, 'M', u'1⁄3'), (0x2154, 'M', u'2⁄3'), (0x2155, 'M', u'1⁄5'), (0x2156, 'M', u'2⁄5'), (0x2157, 'M', u'3⁄5'), (0x2158, 'M', u'4⁄5'), (0x2159, 'M', u'1⁄6'), (0x215A, 'M', u'5⁄6'), (0x215B, 'M', u'1⁄8'), (0x215C, 'M', u'3⁄8'), (0x215D, 'M', u'5⁄8'), (0x215E, 'M', u'7⁄8'), (0x215F, 'M', u'1⁄'), (0x2160, 'M', u'i'), (0x2161, 'M', u'ii'), (0x2162, 'M', u'iii'), (0x2163, 'M', u'iv'), (0x2164, 'M', u'v'), (0x2165, 'M', u'vi'), (0x2166, 'M', u'vii'), (0x2167, 'M', u'viii'), (0x2168, 'M', u'ix'), (0x2169, 'M', u'x'), (0x216A, 'M', u'xi'), (0x216B, 'M', u'xii'), (0x216C, 'M', u'l'), (0x216D, 'M', u'c'), (0x216E, 'M', u'd'), (0x216F, 'M', u'm'), (0x2170, 'M', u'i'), (0x2171, 'M', u'ii'), (0x2172, 'M', u'iii'), (0x2173, 'M', u'iv'), (0x2174, 'M', u'v'), (0x2175, 'M', u'vi'), (0x2176, 'M', u'vii'), (0x2177, 'M', u'viii'), (0x2178, 'M', u'ix'), (0x2179, 'M', u'x'), (0x217A, 'M', u'xi'), (0x217B, 'M', u'xii'), (0x217C, 'M', u'l'), (0x217D, 'M', u'c'), (0x217E, 'M', u'd'), (0x217F, 'M', u'm'), (0x2180, 'V'), (0x2183, 'X'), (0x2184, 'V'), (0x2189, 'M', u'0⁄3'), (0x218A, 'V'), (0x218C, 'X'), (0x2190, 'V'), (0x222C, 'M', u'∫∫'), (0x222D, 'M', u'∫∫∫'), (0x222E, 'V'), (0x222F, 'M', u'∮∮'), (0x2230, 'M', u'∮∮∮'), (0x2231, 'V'), (0x2260, '3'), (0x2261, 'V'), (0x226E, '3'), (0x2270, 'V'), (0x2329, 'M', u'〈'), (0x232A, 'M', u'〉'), (0x232B, 'V'), (0x2427, 'X'), (0x2440, 'V'), (0x244B, 'X'), (0x2460, 'M', u'1'), (0x2461, 'M', u'2'), ] def _seg_23(): return [ (0x2462, 'M', u'3'), (0x2463, 'M', u'4'), (0x2464, 'M', u'5'), (0x2465, 'M', u'6'), (0x2466, 'M', u'7'), (0x2467, 'M', u'8'), (0x2468, 'M', u'9'), (0x2469, 'M', u'10'), (0x246A, 'M', u'11'), (0x246B, 'M', u'12'), (0x246C, 'M', u'13'), (0x246D, 'M', u'14'), (0x246E, 'M', u'15'), (0x246F, 'M', u'16'), (0x2470, 'M', u'17'), (0x2471, 'M', u'18'), (0x2472, 'M', u'19'), (0x2473, 'M', u'20'), (0x2474, '3', u'(1)'), (0x2475, '3', u'(2)'), (0x2476, '3', u'(3)'), (0x2477, '3', u'(4)'), (0x2478, '3', u'(5)'), (0x2479, '3', u'(6)'), (0x247A, '3', u'(7)'), (0x247B, '3', u'(8)'), (0x247C, '3', u'(9)'), (0x247D, '3', u'(10)'), (0x247E, '3', u'(11)'), (0x247F, '3', u'(12)'), (0x2480, '3', u'(13)'), (0x2481, '3', u'(14)'), (0x2482, '3', u'(15)'), (0x2483, '3', u'(16)'), (0x2484, '3', u'(17)'), (0x2485, '3', u'(18)'), (0x2486, '3', u'(19)'), (0x2487, '3', u'(20)'), (0x2488, 'X'), (0x249C, '3', u'(a)'), (0x249D, '3', u'(b)'), (0x249E, '3', u'(c)'), (0x249F, '3', u'(d)'), (0x24A0, '3', u'(e)'), (0x24A1, '3', u'(f)'), (0x24A2, '3', u'(g)'), (0x24A3, '3', u'(h)'), (0x24A4, '3', u'(i)'), (0x24A5, '3', u'(j)'), (0x24A6, '3', u'(k)'), (0x24A7, '3', u'(l)'), (0x24A8, '3', u'(m)'), (0x24A9, '3', u'(n)'), (0x24AA, '3', u'(o)'), (0x24AB, '3', u'(p)'), (0x24AC, '3', u'(q)'), (0x24AD, '3', u'(r)'), (0x24AE, '3', u'(s)'), (0x24AF, '3', u'(t)'), (0x24B0, '3', u'(u)'), (0x24B1, '3', u'(v)'), (0x24B2, '3', u'(w)'), (0x24B3, '3', u'(x)'), (0x24B4, '3', u'(y)'), (0x24B5, '3', u'(z)'), (0x24B6, 'M', u'a'), (0x24B7, 'M', u'b'), (0x24B8, 'M', u'c'), (0x24B9, 'M', u'd'), (0x24BA, 'M', u'e'), (0x24BB, 'M', u'f'), (0x24BC, 'M', u'g'), (0x24BD, 'M', u'h'), (0x24BE, 'M', u'i'), (0x24BF, 'M', u'j'), (0x24C0, 'M', u'k'), (0x24C1, 'M', u'l'), (0x24C2, 'M', u'm'), (0x24C3, 'M', u'n'), (0x24C4, 'M', u'o'), (0x24C5, 'M', u'p'), (0x24C6, 'M', u'q'), (0x24C7, 'M', u'r'), (0x24C8, 'M', u's'), (0x24C9, 'M', u't'), (0x24CA, 'M', u'u'), (0x24CB, 'M', u'v'), (0x24CC, 'M', u'w'), (0x24CD, 'M', u'x'), (0x24CE, 'M', u'y'), (0x24CF, 'M', u'z'), (0x24D0, 'M', u'a'), (0x24D1, 'M', u'b'), (0x24D2, 'M', u'c'), (0x24D3, 'M', u'd'), (0x24D4, 'M', u'e'), (0x24D5, 'M', u'f'), (0x24D6, 'M', u'g'), (0x24D7, 'M', u'h'), (0x24D8, 'M', u'i'), ] def _seg_24(): return [ (0x24D9, 'M', u'j'), (0x24DA, 'M', u'k'), (0x24DB, 'M', u'l'), (0x24DC, 'M', u'm'), (0x24DD, 'M', u'n'), (0x24DE, 'M', u'o'), (0x24DF, 'M', u'p'), (0x24E0, 'M', u'q'), (0x24E1, 'M', u'r'), (0x24E2, 'M', u's'), (0x24E3, 'M', u't'), (0x24E4, 'M', u'u'), (0x24E5, 'M', u'v'), (0x24E6, 'M', u'w'), (0x24E7, 'M', u'x'), (0x24E8, 'M', u'y'), (0x24E9, 'M', u'z'), (0x24EA, 'M', u'0'), (0x24EB, 'V'), (0x2A0C, 'M', u'∫∫∫∫'), (0x2A0D, 'V'), (0x2A74, '3', u'::='), (0x2A75, '3', u'=='), (0x2A76, '3', u'==='), (0x2A77, 'V'), (0x2ADC, 'M', u'⫝̸'), (0x2ADD, 'V'), (0x2B74, 'X'), (0x2B76, 'V'), (0x2B96, 'X'), (0x2B98, 'V'), (0x2BC9, 'X'), (0x2BCA, 'V'), (0x2BFF, 'X'), (0x2C00, 'M', u'ⰰ'), (0x2C01, 'M', u'ⰱ'), (0x2C02, 'M', u'ⰲ'), (0x2C03, 'M', u'ⰳ'), (0x2C04, 'M', u'ⰴ'), (0x2C05, 'M', u'ⰵ'), (0x2C06, 'M', u'ⰶ'), (0x2C07, 'M', u'ⰷ'), (0x2C08, 'M', u'ⰸ'), (0x2C09, 'M', u'ⰹ'), (0x2C0A, 'M', u'ⰺ'), (0x2C0B, 'M', u'ⰻ'), (0x2C0C, 'M', u'ⰼ'), (0x2C0D, 'M', u'ⰽ'), (0x2C0E, 'M', u'ⰾ'), (0x2C0F, 'M', u'ⰿ'), (0x2C10, 'M', u'ⱀ'), (0x2C11, 'M', u'ⱁ'), (0x2C12, 'M', u'ⱂ'), (0x2C13, 'M', u'ⱃ'), (0x2C14, 'M', u'ⱄ'), (0x2C15, 'M', u'ⱅ'), (0x2C16, 'M', u'ⱆ'), (0x2C17, 'M', u'ⱇ'), (0x2C18, 'M', u'ⱈ'), (0x2C19, 'M', u'ⱉ'), (0x2C1A, 'M', u'ⱊ'), (0x2C1B, 'M', u'ⱋ'), (0x2C1C, 'M', u'ⱌ'), (0x2C1D, 'M', u'ⱍ'), (0x2C1E, 'M', u'ⱎ'), (0x2C1F, 'M', u'ⱏ'), (0x2C20, 'M', u'ⱐ'), (0x2C21, 'M', u'ⱑ'), (0x2C22, 'M', u'ⱒ'), (0x2C23, 'M', u'ⱓ'), (0x2C24, 'M', u'ⱔ'), (0x2C25, 'M', u'ⱕ'), (0x2C26, 'M', u'ⱖ'), (0x2C27, 'M', u'ⱗ'), (0x2C28, 'M', u'ⱘ'), (0x2C29, 'M', u'ⱙ'), (0x2C2A, 'M', u'ⱚ'), (0x2C2B, 'M', u'ⱛ'), (0x2C2C, 'M', u'ⱜ'), (0x2C2D, 'M', u'ⱝ'), (0x2C2E, 'M', u'ⱞ'), (0x2C2F, 'X'), (0x2C30, 'V'), (0x2C5F, 'X'), (0x2C60, 'M', u'ⱡ'), (0x2C61, 'V'), (0x2C62, 'M', u'ɫ'), (0x2C63, 'M', u'ᵽ'), (0x2C64, 'M', u'ɽ'), (0x2C65, 'V'), (0x2C67, 'M', u'ⱨ'), (0x2C68, 'V'), (0x2C69, 'M', u'ⱪ'), (0x2C6A, 'V'), (0x2C6B, 'M', u'ⱬ'), (0x2C6C, 'V'), (0x2C6D, 'M', u'ɑ'), (0x2C6E, 'M', u'ɱ'), (0x2C6F, 'M', u'ɐ'), (0x2C70, 'M', u'ɒ'), ] def _seg_25(): return [ (0x2C71, 'V'), (0x2C72, 'M', u'ⱳ'), (0x2C73, 'V'), (0x2C75, 'M', u'ⱶ'), (0x2C76, 'V'), (0x2C7C, 'M', u'j'), (0x2C7D, 'M', u'v'), (0x2C7E, 'M', u'ȿ'), (0x2C7F, 'M', u'ɀ'), (0x2C80, 'M', u'ⲁ'), (0x2C81, 'V'), (0x2C82, 'M', u'ⲃ'), (0x2C83, 'V'), (0x2C84, 'M', u'ⲅ'), (0x2C85, 'V'), (0x2C86, 'M', u'ⲇ'), (0x2C87, 'V'), (0x2C88, 'M', u'ⲉ'), (0x2C89, 'V'), (0x2C8A, 'M', u'ⲋ'), (0x2C8B, 'V'), (0x2C8C, 'M', u'ⲍ'), (0x2C8D, 'V'), (0x2C8E, 'M', u'ⲏ'), (0x2C8F, 'V'), (0x2C90, 'M', u'ⲑ'), (0x2C91, 'V'), (0x2C92, 'M', u'ⲓ'), (0x2C93, 'V'), (0x2C94, 'M', u'ⲕ'), (0x2C95, 'V'), (0x2C96, 'M', u'ⲗ'), (0x2C97, 'V'), (0x2C98, 'M', u'ⲙ'), (0x2C99, 'V'), (0x2C9A, 'M', u'ⲛ'), (0x2C9B, 'V'), (0x2C9C, 'M', u'ⲝ'), (0x2C9D, 'V'), (0x2C9E, 'M', u'ⲟ'), (0x2C9F, 'V'), (0x2CA0, 'M', u'ⲡ'), (0x2CA1, 'V'), (0x2CA2, 'M', u'ⲣ'), (0x2CA3, 'V'), (0x2CA4, 'M', u'ⲥ'), (0x2CA5, 'V'), (0x2CA6, 'M', u'ⲧ'), (0x2CA7, 'V'), (0x2CA8, 'M', u'ⲩ'), (0x2CA9, 'V'), (0x2CAA, 'M', u'ⲫ'), (0x2CAB, 'V'), (0x2CAC, 'M', u'ⲭ'), (0x2CAD, 'V'), (0x2CAE, 'M', u'ⲯ'), (0x2CAF, 'V'), (0x2CB0, 'M', u'ⲱ'), (0x2CB1, 'V'), (0x2CB2, 'M', u'ⲳ'), (0x2CB3, 'V'), (0x2CB4, 'M', u'ⲵ'), (0x2CB5, 'V'), (0x2CB6, 'M', u'ⲷ'), (0x2CB7, 'V'), (0x2CB8, 'M', u'ⲹ'), (0x2CB9, 'V'), (0x2CBA, 'M', u'ⲻ'), (0x2CBB, 'V'), (0x2CBC, 'M', u'ⲽ'), (0x2CBD, 'V'), (0x2CBE, 'M', u'ⲿ'), (0x2CBF, 'V'), (0x2CC0, 'M', u'ⳁ'), (0x2CC1, 'V'), (0x2CC2, 'M', u'ⳃ'), (0x2CC3, 'V'), (0x2CC4, 'M', u'ⳅ'), (0x2CC5, 'V'), (0x2CC6, 'M', u'ⳇ'), (0x2CC7, 'V'), (0x2CC8, 'M', u'ⳉ'), (0x2CC9, 'V'), (0x2CCA, 'M', u'ⳋ'), (0x2CCB, 'V'), (0x2CCC, 'M', u'ⳍ'), (0x2CCD, 'V'), (0x2CCE, 'M', u'ⳏ'), (0x2CCF, 'V'), (0x2CD0, 'M', u'ⳑ'), (0x2CD1, 'V'), (0x2CD2, 'M', u'ⳓ'), (0x2CD3, 'V'), (0x2CD4, 'M', u'ⳕ'), (0x2CD5, 'V'), (0x2CD6, 'M', u'ⳗ'), (0x2CD7, 'V'), (0x2CD8, 'M', u'ⳙ'), (0x2CD9, 'V'), (0x2CDA, 'M', u'ⳛ'), ] def _seg_26(): return [ (0x2CDB, 'V'), (0x2CDC, 'M', u'ⳝ'), (0x2CDD, 'V'), (0x2CDE, 'M', u'ⳟ'), (0x2CDF, 'V'), (0x2CE0, 'M', u'ⳡ'), (0x2CE1, 'V'), (0x2CE2, 'M', u'ⳣ'), (0x2CE3, 'V'), (0x2CEB, 'M', u'ⳬ'), (0x2CEC, 'V'), (0x2CED, 'M', u'ⳮ'), (0x2CEE, 'V'), (0x2CF2, 'M', u'ⳳ'), (0x2CF3, 'V'), (0x2CF4, 'X'), (0x2CF9, 'V'), (0x2D26, 'X'), (0x2D27, 'V'), (0x2D28, 'X'), (0x2D2D, 'V'), (0x2D2E, 'X'), (0x2D30, 'V'), (0x2D68, 'X'), (0x2D6F, 'M', u'ⵡ'), (0x2D70, 'V'), (0x2D71, 'X'), (0x2D7F, 'V'), (0x2D97, 'X'), (0x2DA0, 'V'), (0x2DA7, 'X'), (0x2DA8, 'V'), (0x2DAF, 'X'), (0x2DB0, 'V'), (0x2DB7, 'X'), (0x2DB8, 'V'), (0x2DBF, 'X'), (0x2DC0, 'V'), (0x2DC7, 'X'), (0x2DC8, 'V'), (0x2DCF, 'X'), (0x2DD0, 'V'), (0x2DD7, 'X'), (0x2DD8, 'V'), (0x2DDF, 'X'), (0x2DE0, 'V'), (0x2E4F, 'X'), (0x2E80, 'V'), (0x2E9A, 'X'), (0x2E9B, 'V'), (0x2E9F, 'M', u'母'), (0x2EA0, 'V'), (0x2EF3, 'M', u'龟'), (0x2EF4, 'X'), (0x2F00, 'M', u'一'), (0x2F01, 'M', u'丨'), (0x2F02, 'M', u'丶'), (0x2F03, 'M', u'丿'), (0x2F04, 'M', u'乙'), (0x2F05, 'M', u'亅'), (0x2F06, 'M', u'二'), (0x2F07, 'M', u'亠'), (0x2F08, 'M', u'人'), (0x2F09, 'M', u'儿'), (0x2F0A, 'M', u'入'), (0x2F0B, 'M', u'八'), (0x2F0C, 'M', u'冂'), (0x2F0D, 'M', u'冖'), (0x2F0E, 'M', u'冫'), (0x2F0F, 'M', u'几'), (0x2F10, 'M', u'凵'), (0x2F11, 'M', u'刀'), (0x2F12, 'M', u'力'), (0x2F13, 'M', u'勹'), (0x2F14, 'M', u'匕'), (0x2F15, 'M', u'匚'), (0x2F16, 'M', u'匸'), (0x2F17, 'M', u'十'), (0x2F18, 'M', u'卜'), (0x2F19, 'M', u'卩'), (0x2F1A, 'M', u'厂'), (0x2F1B, 'M', u'厶'), (0x2F1C, 'M', u'又'), (0x2F1D, 'M', u'口'), (0x2F1E, 'M', u'囗'), (0x2F1F, 'M', u'土'), (0x2F20, 'M', u'士'), (0x2F21, 'M', u'夂'), (0x2F22, 'M', u'夊'), (0x2F23, 'M', u'夕'), (0x2F24, 'M', u'大'), (0x2F25, 'M', u'女'), (0x2F26, 'M', u'子'), (0x2F27, 'M', u'宀'), (0x2F28, 'M', u'寸'), (0x2F29, 'M', u'小'), (0x2F2A, 'M', u'尢'), (0x2F2B, 'M', u'尸'), (0x2F2C, 'M', u'屮'), (0x2F2D, 'M', u'山'), ] def _seg_27(): return [ (0x2F2E, 'M', u'巛'), (0x2F2F, 'M', u'工'), (0x2F30, 'M', u'己'), (0x2F31, 'M', u'巾'), (0x2F32, 'M', u'干'), (0x2F33, 'M', u'幺'), (0x2F34, 'M', u'广'), (0x2F35, 'M', u'廴'), (0x2F36, 'M', u'廾'), (0x2F37, 'M', u'弋'), (0x2F38, 'M', u'弓'), (0x2F39, 'M', u'彐'), (0x2F3A, 'M', u'彡'), (0x2F3B, 'M', u'彳'), (0x2F3C, 'M', u'心'), (0x2F3D, 'M', u'戈'), (0x2F3E, 'M', u'戶'), (0x2F3F, 'M', u'手'), (0x2F40, 'M', u'支'), (0x2F41, 'M', u'攴'), (0x2F42, 'M', u'文'), (0x2F43, 'M', u'斗'), (0x2F44, 'M', u'斤'), (0x2F45, 'M', u'方'), (0x2F46, 'M', u'无'), (0x2F47, 'M', u'日'), (0x2F48, 'M', u'曰'), (0x2F49, 'M', u'月'), (0x2F4A, 'M', u'木'), (0x2F4B, 'M', u'欠'), (0x2F4C, 'M', u'止'), (0x2F4D, 'M', u'歹'), (0x2F4E, 'M', u'殳'), (0x2F4F, 'M', u'毋'), (0x2F50, 'M', u'比'), (0x2F51, 'M', u'毛'), (0x2F52, 'M', u'氏'), (0x2F53, 'M', u'气'), (0x2F54, 'M', u'水'), (0x2F55, 'M', u'火'), (0x2F56, 'M', u'爪'), (0x2F57, 'M', u'父'), (0x2F58, 'M', u'爻'), (0x2F59, 'M', u'爿'), (0x2F5A, 'M', u'片'), (0x2F5B, 'M', u'牙'), (0x2F5C, 'M', u'牛'), (0x2F5D, 'M', u'犬'), (0x2F5E, 'M', u'玄'), (0x2F5F, 'M', u'玉'), (0x2F60, 'M', u'瓜'), (0x2F61, 'M', u'瓦'), (0x2F62, 'M', u'甘'), (0x2F63, 'M', u'生'), (0x2F64, 'M', u'用'), (0x2F65, 'M', u'田'), (0x2F66, 'M', u'疋'), (0x2F67, 'M', u'疒'), (0x2F68, 'M', u'癶'), (0x2F69, 'M', u'白'), (0x2F6A, 'M', u'皮'), (0x2F6B, 'M', u'皿'), (0x2F6C, 'M', u'目'), (0x2F6D, 'M', u'矛'), (0x2F6E, 'M', u'矢'), (0x2F6F, 'M', u'石'), (0x2F70, 'M', u'示'), (0x2F71, 'M', u'禸'), (0x2F72, 'M', u'禾'), (0x2F73, 'M', u'穴'), (0x2F74, 'M', u'立'), (0x2F75, 'M', u'竹'), (0x2F76, 'M', u'米'), (0x2F77, 'M', u'糸'), (0x2F78, 'M', u'缶'), (0x2F79, 'M', u'网'), (0x2F7A, 'M', u'羊'), (0x2F7B, 'M', u'羽'), (0x2F7C, 'M', u'老'), (0x2F7D, 'M', u'而'), (0x2F7E, 'M', u'耒'), (0x2F7F, 'M', u'耳'), (0x2F80, 'M', u'聿'), (0x2F81, 'M', u'肉'), (0x2F82, 'M', u'臣'), (0x2F83, 'M', u'自'), (0x2F84, 'M', u'至'), (0x2F85, 'M', u'臼'), (0x2F86, 'M', u'舌'), (0x2F87, 'M', u'舛'), (0x2F88, 'M', u'舟'), (0x2F89, 'M', u'艮'), (0x2F8A, 'M', u'色'), (0x2F8B, 'M', u'艸'), (0x2F8C, 'M', u'虍'), (0x2F8D, 'M', u'虫'), (0x2F8E, 'M', u'血'), (0x2F8F, 'M', u'行'), (0x2F90, 'M', u'衣'), (0x2F91, 'M', u'襾'), ] def _seg_28(): return [ (0x2F92, 'M', u'見'), (0x2F93, 'M', u'角'), (0x2F94, 'M', u'言'), (0x2F95, 'M', u'谷'), (0x2F96, 'M', u'豆'), (0x2F97, 'M', u'豕'), (0x2F98, 'M', u'豸'), (0x2F99, 'M', u'貝'), (0x2F9A, 'M', u'赤'), (0x2F9B, 'M', u'走'), (0x2F9C, 'M', u'足'), (0x2F9D, 'M', u'身'), (0x2F9E, 'M', u'車'), (0x2F9F, 'M', u'辛'), (0x2FA0, 'M', u'辰'), (0x2FA1, 'M', u'辵'), (0x2FA2, 'M', u'邑'), (0x2FA3, 'M', u'酉'), (0x2FA4, 'M', u'釆'), (0x2FA5, 'M', u'里'), (0x2FA6, 'M', u'金'), (0x2FA7, 'M', u'長'), (0x2FA8, 'M', u'門'), (0x2FA9, 'M', u'阜'), (0x2FAA, 'M', u'隶'), (0x2FAB, 'M', u'隹'), (0x2FAC, 'M', u'雨'), (0x2FAD, 'M', u'靑'), (0x2FAE, 'M', u'非'), (0x2FAF, 'M', u'面'), (0x2FB0, 'M', u'革'), (0x2FB1, 'M', u'韋'), (0x2FB2, 'M', u'韭'), (0x2FB3, 'M', u'音'), (0x2FB4, 'M', u'頁'), (0x2FB5, 'M', u'風'), (0x2FB6, 'M', u'飛'), (0x2FB7, 'M', u'食'), (0x2FB8, 'M', u'首'), (0x2FB9, 'M', u'香'), (0x2FBA, 'M', u'馬'), (0x2FBB, 'M', u'骨'), (0x2FBC, 'M', u'高'), (0x2FBD, 'M', u'髟'), (0x2FBE, 'M', u'鬥'), (0x2FBF, 'M', u'鬯'), (0x2FC0, 'M', u'鬲'), (0x2FC1, 'M', u'鬼'), (0x2FC2, 'M', u'魚'), (0x2FC3, 'M', u'鳥'), (0x2FC4, 'M', u'鹵'), (0x2FC5, 'M', u'鹿'), (0x2FC6, 'M', u'麥'), (0x2FC7, 'M', u'麻'), (0x2FC8, 'M', u'黃'), (0x2FC9, 'M', u'黍'), (0x2FCA, 'M', u'黑'), (0x2FCB, 'M', u'黹'), (0x2FCC, 'M', u'黽'), (0x2FCD, 'M', u'鼎'), (0x2FCE, 'M', u'鼓'), (0x2FCF, 'M', u'鼠'), (0x2FD0, 'M', u'鼻'), (0x2FD1, 'M', u'齊'), (0x2FD2, 'M', u'齒'), (0x2FD3, 'M', u'龍'), (0x2FD4, 'M', u'龜'), (0x2FD5, 'M', u'龠'), (0x2FD6, 'X'), (0x3000, '3', u' '), (0x3001, 'V'), (0x3002, 'M', u'.'), (0x3003, 'V'), (0x3036, 'M', u'〒'), (0x3037, 'V'), (0x3038, 'M', u'十'), (0x3039, 'M', u'卄'), (0x303A, 'M', u'卅'), (0x303B, 'V'), (0x3040, 'X'), (0x3041, 'V'), (0x3097, 'X'), (0x3099, 'V'), (0x309B, '3', u' ゙'), (0x309C, '3', u' ゚'), (0x309D, 'V'), (0x309F, 'M', u'より'), (0x30A0, 'V'), (0x30FF, 'M', u'コト'), (0x3100, 'X'), (0x3105, 'V'), (0x3130, 'X'), (0x3131, 'M', u'ᄀ'), (0x3132, 'M', u'ᄁ'), (0x3133, 'M', u'ᆪ'), (0x3134, 'M', u'ᄂ'), (0x3135, 'M', u'ᆬ'), (0x3136, 'M', u'ᆭ'), (0x3137, 'M', u'ᄃ'), (0x3138, 'M', u'ᄄ'), ] def _seg_29(): return [ (0x3139, 'M', u'ᄅ'), (0x313A, 'M', u'ᆰ'), (0x313B, 'M', u'ᆱ'), (0x313C, 'M', u'ᆲ'), (0x313D, 'M', u'ᆳ'), (0x313E, 'M', u'ᆴ'), (0x313F, 'M', u'ᆵ'), (0x3140, 'M', u'ᄚ'), (0x3141, 'M', u'ᄆ'), (0x3142, 'M', u'ᄇ'), (0x3143, 'M', u'ᄈ'), (0x3144, 'M', u'ᄡ'), (0x3145, 'M', u'ᄉ'), (0x3146, 'M', u'ᄊ'), (0x3147, 'M', u'ᄋ'), (0x3148, 'M', u'ᄌ'), (0x3149, 'M', u'ᄍ'), (0x314A, 'M', u'ᄎ'), (0x314B, 'M', u'ᄏ'), (0x314C, 'M', u'ᄐ'), (0x314D, 'M', u'ᄑ'), (0x314E, 'M', u'ᄒ'), (0x314F, 'M', u'ᅡ'), (0x3150, 'M', u'ᅢ'), (0x3151, 'M', u'ᅣ'), (0x3152, 'M', u'ᅤ'), (0x3153, 'M', u'ᅥ'), (0x3154, 'M', u'ᅦ'), (0x3155, 'M', u'ᅧ'), (0x3156, 'M', u'ᅨ'), (0x3157, 'M', u'ᅩ'), (0x3158, 'M', u'ᅪ'), (0x3159, 'M', u'ᅫ'), (0x315A, 'M', u'ᅬ'), (0x315B, 'M', u'ᅭ'), (0x315C, 'M', u'ᅮ'), (0x315D, 'M', u'ᅯ'), (0x315E, 'M', u'ᅰ'), (0x315F, 'M', u'ᅱ'), (0x3160, 'M', u'ᅲ'), (0x3161, 'M', u'ᅳ'), (0x3162, 'M', u'ᅴ'), (0x3163, 'M', u'ᅵ'), (0x3164, 'X'), (0x3165, 'M', u'ᄔ'), (0x3166, 'M', u'ᄕ'), (0x3167, 'M', u'ᇇ'), (0x3168, 'M', u'ᇈ'), (0x3169, 'M', u'ᇌ'), (0x316A, 'M', u'ᇎ'), (0x316B, 'M', u'ᇓ'), (0x316C, 'M', u'ᇗ'), (0x316D, 'M', u'ᇙ'), (0x316E, 'M', u'ᄜ'), (0x316F, 'M', u'ᇝ'), (0x3170, 'M', u'ᇟ'), (0x3171, 'M', u'ᄝ'), (0x3172, 'M', u'ᄞ'), (0x3173, 'M', u'ᄠ'), (0x3174, 'M', u'ᄢ'), (0x3175, 'M', u'ᄣ'), (0x3176, 'M', u'ᄧ'), (0x3177, 'M', u'ᄩ'), (0x3178, 'M', u'ᄫ'), (0x3179, 'M', u'ᄬ'), (0x317A, 'M', u'ᄭ'), (0x317B, 'M', u'ᄮ'), (0x317C, 'M', u'ᄯ'), (0x317D, 'M', u'ᄲ'), (0x317E, 'M', u'ᄶ'), (0x317F, 'M', u'ᅀ'), (0x3180, 'M', u'ᅇ'), (0x3181, 'M', u'ᅌ'), (0x3182, 'M', u'ᇱ'), (0x3183, 'M', u'ᇲ'), (0x3184, 'M', u'ᅗ'), (0x3185, 'M', u'ᅘ'), (0x3186, 'M', u'ᅙ'), (0x3187, 'M', u'ᆄ'), (0x3188, 'M', u'ᆅ'), (0x3189, 'M', u'ᆈ'), (0x318A, 'M', u'ᆑ'), (0x318B, 'M', u'ᆒ'), (0x318C, 'M', u'ᆔ'), (0x318D, 'M', u'ᆞ'), (0x318E, 'M', u'ᆡ'), (0x318F, 'X'), (0x3190, 'V'), (0x3192, 'M', u'一'), (0x3193, 'M', u'二'), (0x3194, 'M', u'三'), (0x3195, 'M', u'四'), (0x3196, 'M', u'上'), (0x3197, 'M', u'中'), (0x3198, 'M', u'下'), (0x3199, 'M', u'甲'), (0x319A, 'M', u'乙'), (0x319B, 'M', u'丙'), (0x319C, 'M', u'丁'), (0x319D, 'M', u'天'), ] def _seg_30(): return [ (0x319E, 'M', u'地'), (0x319F, 'M', u'人'), (0x31A0, 'V'), (0x31BB, 'X'), (0x31C0, 'V'), (0x31E4, 'X'), (0x31F0, 'V'), (0x3200, '3', u'(ᄀ)'), (0x3201, '3', u'(ᄂ)'), (0x3202, '3', u'(ᄃ)'), (0x3203, '3', u'(ᄅ)'), (0x3204, '3', u'(ᄆ)'), (0x3205, '3', u'(ᄇ)'), (0x3206, '3', u'(ᄉ)'), (0x3207, '3', u'(ᄋ)'), (0x3208, '3', u'(ᄌ)'), (0x3209, '3', u'(ᄎ)'), (0x320A, '3', u'(ᄏ)'), (0x320B, '3', u'(ᄐ)'), (0x320C, '3', u'(ᄑ)'), (0x320D, '3', u'(ᄒ)'), (0x320E, '3', u'(가)'), (0x320F, '3', u'(나)'), (0x3210, '3', u'(다)'), (0x3211, '3', u'(라)'), (0x3212, '3', u'(마)'), (0x3213, '3', u'(바)'), (0x3214, '3', u'(사)'), (0x3215, '3', u'(아)'), (0x3216, '3', u'(자)'), (0x3217, '3', u'(차)'), (0x3218, '3', u'(카)'), (0x3219, '3', u'(타)'), (0x321A, '3', u'(파)'), (0x321B, '3', u'(하)'), (0x321C, '3', u'(주)'), (0x321D, '3', u'(오전)'), (0x321E, '3', u'(오후)'), (0x321F, 'X'), (0x3220, '3', u'(一)'), (0x3221, '3', u'(二)'), (0x3222, '3', u'(三)'), (0x3223, '3', u'(四)'), (0x3224, '3', u'(五)'), (0x3225, '3', u'(六)'), (0x3226, '3', u'(七)'), (0x3227, '3', u'(八)'), (0x3228, '3', u'(九)'), (0x3229, '3', u'(十)'), (0x322A, '3', u'(月)'), (0x322B, '3', u'(火)'), (0x322C, '3', u'(水)'), (0x322D, '3', u'(木)'), (0x322E, '3', u'(金)'), (0x322F, '3', u'(土)'), (0x3230, '3', u'(日)'), (0x3231, '3', u'(株)'), (0x3232, '3', u'(有)'), (0x3233, '3', u'(社)'), (0x3234, '3', u'(名)'), (0x3235, '3', u'(特)'), (0x3236, '3', u'(財)'), (0x3237, '3', u'(祝)'), (0x3238, '3', u'(労)'), (0x3239, '3', u'(代)'), (0x323A, '3', u'(呼)'), (0x323B, '3', u'(学)'), (0x323C, '3', u'(監)'), (0x323D, '3', u'(企)'), (0x323E, '3', u'(資)'), (0x323F, '3', u'(協)'), (0x3240, '3', u'(祭)'), (0x3241, '3', u'(休)'), (0x3242, '3', u'(自)'), (0x3243, '3', u'(至)'), (0x3244, 'M', u'問'), (0x3245, 'M', u'幼'), (0x3246, 'M', u'文'), (0x3247, 'M', u'箏'), (0x3248, 'V'), (0x3250, 'M', u'pte'), (0x3251, 'M', u'21'), (0x3252, 'M', u'22'), (0x3253, 'M', u'23'), (0x3254, 'M', u'24'), (0x3255, 'M', u'25'), (0x3256, 'M', u'26'), (0x3257, 'M', u'27'), (0x3258, 'M', u'28'), (0x3259, 'M', u'29'), (0x325A, 'M', u'30'), (0x325B, 'M', u'31'), (0x325C, 'M', u'32'), (0x325D, 'M', u'33'), (0x325E, 'M', u'34'), (0x325F, 'M', u'35'), (0x3260, 'M', u'ᄀ'), (0x3261, 'M', u'ᄂ'), (0x3262, 'M', u'ᄃ'), (0x3263, 'M', u'ᄅ'), ] def _seg_31(): return [ (0x3264, 'M', u'ᄆ'), (0x3265, 'M', u'ᄇ'), (0x3266, 'M', u'ᄉ'), (0x3267, 'M', u'ᄋ'), (0x3268, 'M', u'ᄌ'), (0x3269, 'M', u'ᄎ'), (0x326A, 'M', u'ᄏ'), (0x326B, 'M', u'ᄐ'), (0x326C, 'M', u'ᄑ'), (0x326D, 'M', u'ᄒ'), (0x326E, 'M', u'가'), (0x326F, 'M', u'나'), (0x3270, 'M', u'다'), (0x3271, 'M', u'라'), (0x3272, 'M', u'마'), (0x3273, 'M', u'바'), (0x3274, 'M', u'사'), (0x3275, 'M', u'아'), (0x3276, 'M', u'자'), (0x3277, 'M', u'차'), (0x3278, 'M', u'카'), (0x3279, 'M', u'타'), (0x327A, 'M', u'파'), (0x327B, 'M', u'하'), (0x327C, 'M', u'참고'), (0x327D, 'M', u'주의'), (0x327E, 'M', u'우'), (0x327F, 'V'), (0x3280, 'M', u'一'), (0x3281, 'M', u'二'), (0x3282, 'M', u'三'), (0x3283, 'M', u'四'), (0x3284, 'M', u'五'), (0x3285, 'M', u'六'), (0x3286, 'M', u'七'), (0x3287, 'M', u'八'), (0x3288, 'M', u'九'), (0x3289, 'M', u'十'), (0x328A, 'M', u'月'), (0x328B, 'M', u'火'), (0x328C, 'M', u'水'), (0x328D, 'M', u'木'), (0x328E, 'M', u'金'), (0x328F, 'M', u'土'), (0x3290, 'M', u'日'), (0x3291, 'M', u'株'), (0x3292, 'M', u'有'), (0x3293, 'M', u'社'), (0x3294, 'M', u'名'), (0x3295, 'M', u'特'), (0x3296, 'M', u'財'), (0x3297, 'M', u'祝'), (0x3298, 'M', u'労'), (0x3299, 'M', u'秘'), (0x329A, 'M', u'男'), (0x329B, 'M', u'女'), (0x329C, 'M', u'適'), (0x329D, 'M', u'優'), (0x329E, 'M', u'印'), (0x329F, 'M', u'注'), (0x32A0, 'M', u'項'), (0x32A1, 'M', u'休'), (0x32A2, 'M', u'写'), (0x32A3, 'M', u'正'), (0x32A4, 'M', u'上'), (0x32A5, 'M', u'中'), (0x32A6, 'M', u'下'), (0x32A7, 'M', u'左'), (0x32A8, 'M', u'右'), (0x32A9, 'M', u'医'), (0x32AA, 'M', u'宗'), (0x32AB, 'M', u'学'), (0x32AC, 'M', u'監'), (0x32AD, 'M', u'企'), (0x32AE, 'M', u'資'), (0x32AF, 'M', u'協'), (0x32B0, 'M', u'夜'), (0x32B1, 'M', u'36'), (0x32B2, 'M', u'37'), (0x32B3, 'M', u'38'), (0x32B4, 'M', u'39'), (0x32B5, 'M', u'40'), (0x32B6, 'M', u'41'), (0x32B7, 'M', u'42'), (0x32B8, 'M', u'43'), (0x32B9, 'M', u'44'), (0x32BA, 'M', u'45'), (0x32BB, 'M', u'46'), (0x32BC, 'M', u'47'), (0x32BD, 'M', u'48'), (0x32BE, 'M', u'49'), (0x32BF, 'M', u'50'), (0x32C0, 'M', u'1月'), (0x32C1, 'M', u'2月'), (0x32C2, 'M', u'3月'), (0x32C3, 'M', u'4月'), (0x32C4, 'M', u'5月'), (0x32C5, 'M', u'6月'), (0x32C6, 'M', u'7月'), (0x32C7, 'M', u'8月'), ] def _seg_32(): return [ (0x32C8, 'M', u'9月'), (0x32C9, 'M', u'10月'), (0x32CA, 'M', u'11月'), (0x32CB, 'M', u'12月'), (0x32CC, 'M', u'hg'), (0x32CD, 'M', u'erg'), (0x32CE, 'M', u'ev'), (0x32CF, 'M', u'ltd'), (0x32D0, 'M', u'ア'), (0x32D1, 'M', u'イ'), (0x32D2, 'M', u'ウ'), (0x32D3, 'M', u'エ'), (0x32D4, 'M', u'オ'), (0x32D5, 'M', u'カ'), (0x32D6, 'M', u'キ'), (0x32D7, 'M', u'ク'), (0x32D8, 'M', u'ケ'), (0x32D9, 'M', u'コ'), (0x32DA, 'M', u'サ'), (0x32DB, 'M', u'シ'), (0x32DC, 'M', u'ス'), (0x32DD, 'M', u'セ'), (0x32DE, 'M', u'ソ'), (0x32DF, 'M', u'タ'), (0x32E0, 'M', u'チ'), (0x32E1, 'M', u'ツ'), (0x32E2, 'M', u'テ'), (0x32E3, 'M', u'ト'), (0x32E4, 'M', u'ナ'), (0x32E5, 'M', u'ニ'), (0x32E6, 'M', u'ヌ'), (0x32E7, 'M', u'ネ'), (0x32E8, 'M', u'ノ'), (0x32E9, 'M', u'ハ'), (0x32EA, 'M', u'ヒ'), (0x32EB, 'M', u'フ'), (0x32EC, 'M', u'ヘ'), (0x32ED, 'M', u'ホ'), (0x32EE, 'M', u'マ'), (0x32EF, 'M', u'ミ'), (0x32F0, 'M', u'ム'), (0x32F1, 'M', u'メ'), (0x32F2, 'M', u'モ'), (0x32F3, 'M', u'ヤ'), (0x32F4, 'M', u'ユ'), (0x32F5, 'M', u'ヨ'), (0x32F6, 'M', u'ラ'), (0x32F7, 'M', u'リ'), (0x32F8, 'M', u'ル'), (0x32F9, 'M', u'レ'), (0x32FA, 'M', u'ロ'), (0x32FB, 'M', u'ワ'), (0x32FC, 'M', u'ヰ'), (0x32FD, 'M', u'ヱ'), (0x32FE, 'M', u'ヲ'), (0x32FF, 'X'), (0x3300, 'M', u'アパート'), (0x3301, 'M', u'アルファ'), (0x3302, 'M', u'アンペア'), (0x3303, 'M', u'アール'), (0x3304, 'M', u'イニング'), (0x3305, 'M', u'インチ'), (0x3306, 'M', u'ウォン'), (0x3307, 'M', u'エスクード'), (0x3308, 'M', u'エーカー'), (0x3309, 'M', u'オンス'), (0x330A, 'M', u'オーム'), (0x330B, 'M', u'カイリ'), (0x330C, 'M', u'カラット'), (0x330D, 'M', u'カロリー'), (0x330E, 'M', u'ガロン'), (0x330F, 'M', u'ガンマ'), (0x3310, 'M', u'ギガ'), (0x3311, 'M', u'ギニー'), (0x3312, 'M', u'キュリー'), (0x3313, 'M', u'ギルダー'), (0x3314, 'M', u'キロ'), (0x3315, 'M', u'キログラム'), (0x3316, 'M', u'キロメートル'), (0x3317, 'M', u'キロワット'), (0x3318, 'M', u'グラム'), (0x3319, 'M', u'グラムトン'), (0x331A, 'M', u'クルゼイロ'), (0x331B, 'M', u'クローネ'), (0x331C, 'M', u'ケース'), (0x331D, 'M', u'コルナ'), (0x331E, 'M', u'コーポ'), (0x331F, 'M', u'サイクル'), (0x3320, 'M', u'サンチーム'), (0x3321, 'M', u'シリング'), (0x3322, 'M', u'センチ'), (0x3323, 'M', u'セント'), (0x3324, 'M', u'ダース'), (0x3325, 'M', u'デシ'), (0x3326, 'M', u'ドル'), (0x3327, 'M', u'トン'), (0x3328, 'M', u'ナノ'), (0x3329, 'M', u'ノット'), (0x332A, 'M', u'ハイツ'), (0x332B, 'M', u'パーセント'), ] def _seg_33(): return [ (0x332C, 'M', u'パーツ'), (0x332D, 'M', u'バーレル'), (0x332E, 'M', u'ピアストル'), (0x332F, 'M', u'ピクル'), (0x3330, 'M', u'ピコ'), (0x3331, 'M', u'ビル'), (0x3332, 'M', u'ファラッド'), (0x3333, 'M', u'フィート'), (0x3334, 'M', u'ブッシェル'), (0x3335, 'M', u'フラン'), (0x3336, 'M', u'ヘクタール'), (0x3337, 'M', u'ペソ'), (0x3338, 'M', u'ペニヒ'), (0x3339, 'M', u'ヘルツ'), (0x333A, 'M', u'ペンス'), (0x333B, 'M', u'ページ'), (0x333C, 'M', u'ベータ'), (0x333D, 'M', u'ポイント'), (0x333E, 'M', u'ボルト'), (0x333F, 'M', u'ホン'), (0x3340, 'M', u'ポンド'), (0x3341, 'M', u'ホール'), (0x3342, 'M', u'ホーン'), (0x3343, 'M', u'マイクロ'), (0x3344, 'M', u'マイル'), (0x3345, 'M', u'マッハ'), (0x3346, 'M', u'マルク'), (0x3347, 'M', u'マンション'), (0x3348, 'M', u'ミクロン'), (0x3349, 'M', u'ミリ'), (0x334A, 'M', u'ミリバール'), (0x334B, 'M', u'メガ'), (0x334C, 'M', u'メガトン'), (0x334D, 'M', u'メートル'), (0x334E, 'M', u'ヤード'), (0x334F, 'M', u'ヤール'), (0x3350, 'M', u'ユアン'), (0x3351, 'M', u'リットル'), (0x3352, 'M', u'リラ'), (0x3353, 'M', u'ルピー'), (0x3354, 'M', u'ルーブル'), (0x3355, 'M', u'レム'), (0x3356, 'M', u'レントゲン'), (0x3357, 'M', u'ワット'), (0x3358, 'M', u'0点'), (0x3359, 'M', u'1点'), (0x335A, 'M', u'2点'), (0x335B, 'M', u'3点'), (0x335C, 'M', u'4点'), (0x335D, 'M', u'5点'), (0x335E, 'M', u'6点'), (0x335F, 'M', u'7点'), (0x3360, 'M', u'8点'), (0x3361, 'M', u'9点'), (0x3362, 'M', u'10点'), (0x3363, 'M', u'11点'), (0x3364, 'M', u'12点'), (0x3365, 'M', u'13点'), (0x3366, 'M', u'14点'), (0x3367, 'M', u'15点'), (0x3368, 'M', u'16点'), (0x3369, 'M', u'17点'), (0x336A, 'M', u'18点'), (0x336B, 'M', u'19点'), (0x336C, 'M', u'20点'), (0x336D, 'M', u'21点'), (0x336E, 'M', u'22点'), (0x336F, 'M', u'23点'), (0x3370, 'M', u'24点'), (0x3371, 'M', u'hpa'), (0x3372, 'M', u'da'), (0x3373, 'M', u'au'), (0x3374, 'M', u'bar'), (0x3375, 'M', u'ov'), (0x3376, 'M', u'pc'), (0x3377, 'M', u'dm'), (0x3378, 'M', u'dm2'), (0x3379, 'M', u'dm3'), (0x337A, 'M', u'iu'), (0x337B, 'M', u'平成'), (0x337C, 'M', u'昭和'), (0x337D, 'M', u'大正'), (0x337E, 'M', u'明治'), (0x337F, 'M', u'株式会社'), (0x3380, 'M', u'pa'), (0x3381, 'M', u'na'), (0x3382, 'M', u'μa'), (0x3383, 'M', u'ma'), (0x3384, 'M', u'ka'), (0x3385, 'M', u'kb'), (0x3386, 'M', u'mb'), (0x3387, 'M', u'gb'), (0x3388, 'M', u'cal'), (0x3389, 'M', u'kcal'), (0x338A, 'M', u'pf'), (0x338B, 'M', u'nf'), (0x338C, 'M', u'μf'), (0x338D, 'M', u'μg'), (0x338E, 'M', u'mg'), (0x338F, 'M', u'kg'), ] def _seg_34(): return [ (0x3390, 'M', u'hz'), (0x3391, 'M', u'khz'), (0x3392, 'M', u'mhz'), (0x3393, 'M', u'ghz'), (0x3394, 'M', u'thz'), (0x3395, 'M', u'μl'), (0x3396, 'M', u'ml'), (0x3397, 'M', u'dl'), (0x3398, 'M', u'kl'), (0x3399, 'M', u'fm'), (0x339A, 'M', u'nm'), (0x339B, 'M', u'μm'), (0x339C, 'M', u'mm'), (0x339D, 'M', u'cm'), (0x339E, 'M', u'km'), (0x339F, 'M', u'mm2'), (0x33A0, 'M', u'cm2'), (0x33A1, 'M', u'm2'), (0x33A2, 'M', u'km2'), (0x33A3, 'M', u'mm3'), (0x33A4, 'M', u'cm3'), (0x33A5, 'M', u'm3'), (0x33A6, 'M', u'km3'), (0x33A7, 'M', u'm∕s'), (0x33A8, 'M', u'm∕s2'), (0x33A9, 'M', u'pa'), (0x33AA, 'M', u'kpa'), (0x33AB, 'M', u'mpa'), (0x33AC, 'M', u'gpa'), (0x33AD, 'M', u'rad'), (0x33AE, 'M', u'rad∕s'), (0x33AF, 'M', u'rad∕s2'), (0x33B0, 'M', u'ps'), (0x33B1, 'M', u'ns'), (0x33B2, 'M', u'μs'), (0x33B3, 'M', u'ms'), (0x33B4, 'M', u'pv'), (0x33B5, 'M', u'nv'), (0x33B6, 'M', u'μv'), (0x33B7, 'M', u'mv'), (0x33B8, 'M', u'kv'), (0x33B9, 'M', u'mv'), (0x33BA, 'M', u'pw'), (0x33BB, 'M', u'nw'), (0x33BC, 'M', u'μw'), (0x33BD, 'M', u'mw'), (0x33BE, 'M', u'kw'), (0x33BF, 'M', u'mw'), (0x33C0, 'M', u'kω'), (0x33C1, 'M', u'mω'), (0x33C2, 'X'), (0x33C3, 'M', u'bq'), (0x33C4, 'M', u'cc'), (0x33C5, 'M', u'cd'), (0x33C6, 'M', u'c∕kg'), (0x33C7, 'X'), (0x33C8, 'M', u'db'), (0x33C9, 'M', u'gy'), (0x33CA, 'M', u'ha'), (0x33CB, 'M', u'hp'), (0x33CC, 'M', u'in'), (0x33CD, 'M', u'kk'), (0x33CE, 'M', u'km'), (0x33CF, 'M', u'kt'), (0x33D0, 'M', u'lm'), (0x33D1, 'M', u'ln'), (0x33D2, 'M', u'log'), (0x33D3, 'M', u'lx'), (0x33D4, 'M', u'mb'), (0x33D5, 'M', u'mil'), (0x33D6, 'M', u'mol'), (0x33D7, 'M', u'ph'), (0x33D8, 'X'), (0x33D9, 'M', u'ppm'), (0x33DA, 'M', u'pr'), (0x33DB, 'M', u'sr'), (0x33DC, 'M', u'sv'), (0x33DD, 'M', u'wb'), (0x33DE, 'M', u'v∕m'), (0x33DF, 'M', u'a∕m'), (0x33E0, 'M', u'1日'), (0x33E1, 'M', u'2日'), (0x33E2, 'M', u'3日'), (0x33E3, 'M', u'4日'), (0x33E4, 'M', u'5日'), (0x33E5, 'M', u'6日'), (0x33E6, 'M', u'7日'), (0x33E7, 'M', u'8日'), (0x33E8, 'M', u'9日'), (0x33E9, 'M', u'10日'), (0x33EA, 'M', u'11日'), (0x33EB, 'M', u'12日'), (0x33EC, 'M', u'13日'), (0x33ED, 'M', u'14日'), (0x33EE, 'M', u'15日'), (0x33EF, 'M', u'16日'), (0x33F0, 'M', u'17日'), (0x33F1, 'M', u'18日'), (0x33F2, 'M', u'19日'), (0x33F3, 'M', u'20日'), ] def _seg_35(): return [ (0x33F4, 'M', u'21日'), (0x33F5, 'M', u'22日'), (0x33F6, 'M', u'23日'), (0x33F7, 'M', u'24日'), (0x33F8, 'M', u'25日'), (0x33F9, 'M', u'26日'), (0x33FA, 'M', u'27日'), (0x33FB, 'M', u'28日'), (0x33FC, 'M', u'29日'), (0x33FD, 'M', u'30日'), (0x33FE, 'M', u'31日'), (0x33FF, 'M', u'gal'), (0x3400, 'V'), (0x4DB6, 'X'), (0x4DC0, 'V'), (0x9FF0, 'X'), (0xA000, 'V'), (0xA48D, 'X'), (0xA490, 'V'), (0xA4C7, 'X'), (0xA4D0, 'V'), (0xA62C, 'X'), (0xA640, 'M', u'ꙁ'), (0xA641, 'V'), (0xA642, 'M', u'ꙃ'), (0xA643, 'V'), (0xA644, 'M', u'ꙅ'), (0xA645, 'V'), (0xA646, 'M', u'ꙇ'), (0xA647, 'V'), (0xA648, 'M', u'ꙉ'), (0xA649, 'V'), (0xA64A, 'M', u'ꙋ'), (0xA64B, 'V'), (0xA64C, 'M', u'ꙍ'), (0xA64D, 'V'), (0xA64E, 'M', u'ꙏ'), (0xA64F, 'V'), (0xA650, 'M', u'ꙑ'), (0xA651, 'V'), (0xA652, 'M', u'ꙓ'), (0xA653, 'V'), (0xA654, 'M', u'ꙕ'), (0xA655, 'V'), (0xA656, 'M', u'ꙗ'), (0xA657, 'V'), (0xA658, 'M', u'ꙙ'), (0xA659, 'V'), (0xA65A, 'M', u'ꙛ'), (0xA65B, 'V'), (0xA65C, 'M', u'ꙝ'), (0xA65D, 'V'), (0xA65E, 'M', u'ꙟ'), (0xA65F, 'V'), (0xA660, 'M', u'ꙡ'), (0xA661, 'V'), (0xA662, 'M', u'ꙣ'), (0xA663, 'V'), (0xA664, 'M', u'ꙥ'), (0xA665, 'V'), (0xA666, 'M', u'ꙧ'), (0xA667, 'V'), (0xA668, 'M', u'ꙩ'), (0xA669, 'V'), (0xA66A, 'M', u'ꙫ'), (0xA66B, 'V'), (0xA66C, 'M', u'ꙭ'), (0xA66D, 'V'), (0xA680, 'M', u'ꚁ'), (0xA681, 'V'), (0xA682, 'M', u'ꚃ'), (0xA683, 'V'), (0xA684, 'M', u'ꚅ'), (0xA685, 'V'), (0xA686, 'M', u'ꚇ'), (0xA687, 'V'), (0xA688, 'M', u'ꚉ'), (0xA689, 'V'), (0xA68A, 'M', u'ꚋ'), (0xA68B, 'V'), (0xA68C, 'M', u'ꚍ'), (0xA68D, 'V'), (0xA68E, 'M', u'ꚏ'), (0xA68F, 'V'), (0xA690, 'M', u'ꚑ'), (0xA691, 'V'), (0xA692, 'M', u'ꚓ'), (0xA693, 'V'), (0xA694, 'M', u'ꚕ'), (0xA695, 'V'), (0xA696, 'M', u'ꚗ'), (0xA697, 'V'), (0xA698, 'M', u'ꚙ'), (0xA699, 'V'), (0xA69A, 'M', u'ꚛ'), (0xA69B, 'V'), (0xA69C, 'M', u'ъ'), (0xA69D, 'M', u'ь'), (0xA69E, 'V'), (0xA6F8, 'X'), ] def _seg_36(): return [ (0xA700, 'V'), (0xA722, 'M', u'ꜣ'), (0xA723, 'V'), (0xA724, 'M', u'ꜥ'), (0xA725, 'V'), (0xA726, 'M', u'ꜧ'), (0xA727, 'V'), (0xA728, 'M', u'ꜩ'), (0xA729, 'V'), (0xA72A, 'M', u'ꜫ'), (0xA72B, 'V'), (0xA72C, 'M', u'ꜭ'), (0xA72D, 'V'), (0xA72E, 'M', u'ꜯ'), (0xA72F, 'V'), (0xA732, 'M', u'ꜳ'), (0xA733, 'V'), (0xA734, 'M', u'ꜵ'), (0xA735, 'V'), (0xA736, 'M', u'ꜷ'), (0xA737, 'V'), (0xA738, 'M', u'ꜹ'), (0xA739, 'V'), (0xA73A, 'M', u'ꜻ'), (0xA73B, 'V'), (0xA73C, 'M', u'ꜽ'), (0xA73D, 'V'), (0xA73E, 'M', u'ꜿ'), (0xA73F, 'V'), (0xA740, 'M', u'ꝁ'), (0xA741, 'V'), (0xA742, 'M', u'ꝃ'), (0xA743, 'V'), (0xA744, 'M', u'ꝅ'), (0xA745, 'V'), (0xA746, 'M', u'ꝇ'), (0xA747, 'V'), (0xA748, 'M', u'ꝉ'), (0xA749, 'V'), (0xA74A, 'M', u'ꝋ'), (0xA74B, 'V'), (0xA74C, 'M', u'ꝍ'), (0xA74D, 'V'), (0xA74E, 'M', u'ꝏ'), (0xA74F, 'V'), (0xA750, 'M', u'ꝑ'), (0xA751, 'V'), (0xA752, 'M', u'ꝓ'), (0xA753, 'V'), (0xA754, 'M', u'ꝕ'), (0xA755, 'V'), (0xA756, 'M', u'ꝗ'), (0xA757, 'V'), (0xA758, 'M', u'ꝙ'), (0xA759, 'V'), (0xA75A, 'M', u'ꝛ'), (0xA75B, 'V'), (0xA75C, 'M', u'ꝝ'), (0xA75D, 'V'), (0xA75E, 'M', u'ꝟ'), (0xA75F, 'V'), (0xA760, 'M', u'ꝡ'), (0xA761, 'V'), (0xA762, 'M', u'ꝣ'), (0xA763, 'V'), (0xA764, 'M', u'ꝥ'), (0xA765, 'V'), (0xA766, 'M', u'ꝧ'), (0xA767, 'V'), (0xA768, 'M', u'ꝩ'), (0xA769, 'V'), (0xA76A, 'M', u'ꝫ'), (0xA76B, 'V'), (0xA76C, 'M', u'ꝭ'), (0xA76D, 'V'), (0xA76E, 'M', u'ꝯ'), (0xA76F, 'V'), (0xA770, 'M', u'ꝯ'), (0xA771, 'V'), (0xA779, 'M', u'ꝺ'), (0xA77A, 'V'), (0xA77B, 'M', u'ꝼ'), (0xA77C, 'V'), (0xA77D, 'M', u'ᵹ'), (0xA77E, 'M', u'ꝿ'), (0xA77F, 'V'), (0xA780, 'M', u'ꞁ'), (0xA781, 'V'), (0xA782, 'M', u'ꞃ'), (0xA783, 'V'), (0xA784, 'M', u'ꞅ'), (0xA785, 'V'), (0xA786, 'M', u'ꞇ'), (0xA787, 'V'), (0xA78B, 'M', u'ꞌ'), (0xA78C, 'V'), (0xA78D, 'M', u'ɥ'), (0xA78E, 'V'), (0xA790, 'M', u'ꞑ'), (0xA791, 'V'), ] def _seg_37(): return [ (0xA792, 'M', u'ꞓ'), (0xA793, 'V'), (0xA796, 'M', u'ꞗ'), (0xA797, 'V'), (0xA798, 'M', u'ꞙ'), (0xA799, 'V'), (0xA79A, 'M', u'ꞛ'), (0xA79B, 'V'), (0xA79C, 'M', u'ꞝ'), (0xA79D, 'V'), (0xA79E, 'M', u'ꞟ'), (0xA79F, 'V'), (0xA7A0, 'M', u'ꞡ'), (0xA7A1, 'V'), (0xA7A2, 'M', u'ꞣ'), (0xA7A3, 'V'), (0xA7A4, 'M', u'ꞥ'), (0xA7A5, 'V'), (0xA7A6, 'M', u'ꞧ'), (0xA7A7, 'V'), (0xA7A8, 'M', u'ꞩ'), (0xA7A9, 'V'), (0xA7AA, 'M', u'ɦ'), (0xA7AB, 'M', u'ɜ'), (0xA7AC, 'M', u'ɡ'), (0xA7AD, 'M', u'ɬ'), (0xA7AE, 'M', u'ɪ'), (0xA7AF, 'V'), (0xA7B0, 'M', u'ʞ'), (0xA7B1, 'M', u'ʇ'), (0xA7B2, 'M', u'ʝ'), (0xA7B3, 'M', u'ꭓ'), (0xA7B4, 'M', u'ꞵ'), (0xA7B5, 'V'), (0xA7B6, 'M', u'ꞷ'), (0xA7B7, 'V'), (0xA7B8, 'X'), (0xA7B9, 'V'), (0xA7BA, 'X'), (0xA7F7, 'V'), (0xA7F8, 'M', u'ħ'), (0xA7F9, 'M', u'œ'), (0xA7FA, 'V'), (0xA82C, 'X'), (0xA830, 'V'), (0xA83A, 'X'), (0xA840, 'V'), (0xA878, 'X'), (0xA880, 'V'), (0xA8C6, 'X'), (0xA8CE, 'V'), (0xA8DA, 'X'), (0xA8E0, 'V'), (0xA954, 'X'), (0xA95F, 'V'), (0xA97D, 'X'), (0xA980, 'V'), (0xA9CE, 'X'), (0xA9CF, 'V'), (0xA9DA, 'X'), (0xA9DE, 'V'), (0xA9FF, 'X'), (0xAA00, 'V'), (0xAA37, 'X'), (0xAA40, 'V'), (0xAA4E, 'X'), (0xAA50, 'V'), (0xAA5A, 'X'), (0xAA5C, 'V'), (0xAAC3, 'X'), (0xAADB, 'V'), (0xAAF7, 'X'), (0xAB01, 'V'), (0xAB07, 'X'), (0xAB09, 'V'), (0xAB0F, 'X'), (0xAB11, 'V'), (0xAB17, 'X'), (0xAB20, 'V'), (0xAB27, 'X'), (0xAB28, 'V'), (0xAB2F, 'X'), (0xAB30, 'V'), (0xAB5C, 'M', u'ꜧ'), (0xAB5D, 'M', u'ꬷ'), (0xAB5E, 'M', u'ɫ'), (0xAB5F, 'M', u'ꭒ'), (0xAB60, 'V'), (0xAB66, 'X'), (0xAB70, 'M', u'Ꭰ'), (0xAB71, 'M', u'Ꭱ'), (0xAB72, 'M', u'Ꭲ'), (0xAB73, 'M', u'Ꭳ'), (0xAB74, 'M', u'Ꭴ'), (0xAB75, 'M', u'Ꭵ'), (0xAB76, 'M', u'Ꭶ'), (0xAB77, 'M', u'Ꭷ'), (0xAB78, 'M', u'Ꭸ'), (0xAB79, 'M', u'Ꭹ'), (0xAB7A, 'M', u'Ꭺ'), ] def _seg_38(): return [ (0xAB7B, 'M', u'Ꭻ'), (0xAB7C, 'M', u'Ꭼ'), (0xAB7D, 'M', u'Ꭽ'), (0xAB7E, 'M', u'Ꭾ'), (0xAB7F, 'M', u'Ꭿ'), (0xAB80, 'M', u'Ꮀ'), (0xAB81, 'M', u'Ꮁ'), (0xAB82, 'M', u'Ꮂ'), (0xAB83, 'M', u'Ꮃ'), (0xAB84, 'M', u'Ꮄ'), (0xAB85, 'M', u'Ꮅ'), (0xAB86, 'M', u'Ꮆ'), (0xAB87, 'M', u'Ꮇ'), (0xAB88, 'M', u'Ꮈ'), (0xAB89, 'M', u'Ꮉ'), (0xAB8A, 'M', u'Ꮊ'), (0xAB8B, 'M', u'Ꮋ'), (0xAB8C, 'M', u'Ꮌ'), (0xAB8D, 'M', u'Ꮍ'), (0xAB8E, 'M', u'Ꮎ'), (0xAB8F, 'M', u'Ꮏ'), (0xAB90, 'M', u'Ꮐ'), (0xAB91, 'M', u'Ꮑ'), (0xAB92, 'M', u'Ꮒ'), (0xAB93, 'M', u'Ꮓ'), (0xAB94, 'M', u'Ꮔ'), (0xAB95, 'M', u'Ꮕ'), (0xAB96, 'M', u'Ꮖ'), (0xAB97, 'M', u'Ꮗ'), (0xAB98, 'M', u'Ꮘ'), (0xAB99, 'M', u'Ꮙ'), (0xAB9A, 'M', u'Ꮚ'), (0xAB9B, 'M', u'Ꮛ'), (0xAB9C, 'M', u'Ꮜ'), (0xAB9D, 'M', u'Ꮝ'), (0xAB9E, 'M', u'Ꮞ'), (0xAB9F, 'M', u'Ꮟ'), (0xABA0, 'M', u'Ꮠ'), (0xABA1, 'M', u'Ꮡ'), (0xABA2, 'M', u'Ꮢ'), (0xABA3, 'M', u'Ꮣ'), (0xABA4, 'M', u'Ꮤ'), (0xABA5, 'M', u'Ꮥ'), (0xABA6, 'M', u'Ꮦ'), (0xABA7, 'M', u'Ꮧ'), (0xABA8, 'M', u'Ꮨ'), (0xABA9, 'M', u'Ꮩ'), (0xABAA, 'M', u'Ꮪ'), (0xABAB, 'M', u'Ꮫ'), (0xABAC, 'M', u'Ꮬ'), (0xABAD, 'M', u'Ꮭ'), (0xABAE, 'M', u'Ꮮ'), (0xABAF, 'M', u'Ꮯ'), (0xABB0, 'M', u'Ꮰ'), (0xABB1, 'M', u'Ꮱ'), (0xABB2, 'M', u'Ꮲ'), (0xABB3, 'M', u'Ꮳ'), (0xABB4, 'M', u'Ꮴ'), (0xABB5, 'M', u'Ꮵ'), (0xABB6, 'M', u'Ꮶ'), (0xABB7, 'M', u'Ꮷ'), (0xABB8, 'M', u'Ꮸ'), (0xABB9, 'M', u'Ꮹ'), (0xABBA, 'M', u'Ꮺ'), (0xABBB, 'M', u'Ꮻ'), (0xABBC, 'M', u'Ꮼ'), (0xABBD, 'M', u'Ꮽ'), (0xABBE, 'M', u'Ꮾ'), (0xABBF, 'M', u'Ꮿ'), (0xABC0, 'V'), (0xABEE, 'X'), (0xABF0, 'V'), (0xABFA, 'X'), (0xAC00, 'V'), (0xD7A4, 'X'), (0xD7B0, 'V'), (0xD7C7, 'X'), (0xD7CB, 'V'), (0xD7FC, 'X'), (0xF900, 'M', u'豈'), (0xF901, 'M', u'更'), (0xF902, 'M', u'車'), (0xF903, 'M', u'賈'), (0xF904, 'M', u'滑'), (0xF905, 'M', u'串'), (0xF906, 'M', u'句'), (0xF907, 'M', u'龜'), (0xF909, 'M', u'契'), (0xF90A, 'M', u'金'), (0xF90B, 'M', u'喇'), (0xF90C, 'M', u'奈'), (0xF90D, 'M', u'懶'), (0xF90E, 'M', u'癩'), (0xF90F, 'M', u'羅'), (0xF910, 'M', u'蘿'), (0xF911, 'M', u'螺'), (0xF912, 'M', u'裸'), (0xF913, 'M', u'邏'), (0xF914, 'M', u'樂'), (0xF915, 'M', u'洛'), ] def _seg_39(): return [ (0xF916, 'M', u'烙'), (0xF917, 'M', u'珞'), (0xF918, 'M', u'落'), (0xF919, 'M', u'酪'), (0xF91A, 'M', u'駱'), (0xF91B, 'M', u'亂'), (0xF91C, 'M', u'卵'), (0xF91D, 'M', u'欄'), (0xF91E, 'M', u'爛'), (0xF91F, 'M', u'蘭'), (0xF920, 'M', u'鸞'), (0xF921, 'M', u'嵐'), (0xF922, 'M', u'濫'), (0xF923, 'M', u'藍'), (0xF924, 'M', u'襤'), (0xF925, 'M', u'拉'), (0xF926, 'M', u'臘'), (0xF927, 'M', u'蠟'), (0xF928, 'M', u'廊'), (0xF929, 'M', u'朗'), (0xF92A, 'M', u'浪'), (0xF92B, 'M', u'狼'), (0xF92C, 'M', u'郎'), (0xF92D, 'M', u'來'), (0xF92E, 'M', u'冷'), (0xF92F, 'M', u'勞'), (0xF930, 'M', u'擄'), (0xF931, 'M', u'櫓'), (0xF932, 'M', u'爐'), (0xF933, 'M', u'盧'), (0xF934, 'M', u'老'), (0xF935, 'M', u'蘆'), (0xF936, 'M', u'虜'), (0xF937, 'M', u'路'), (0xF938, 'M', u'露'), (0xF939, 'M', u'魯'), (0xF93A, 'M', u'鷺'), (0xF93B, 'M', u'碌'), (0xF93C, 'M', u'祿'), (0xF93D, 'M', u'綠'), (0xF93E, 'M', u'菉'), (0xF93F, 'M', u'錄'), (0xF940, 'M', u'鹿'), (0xF941, 'M', u'論'), (0xF942, 'M', u'壟'), (0xF943, 'M', u'弄'), (0xF944, 'M', u'籠'), (0xF945, 'M', u'聾'), (0xF946, 'M', u'牢'), (0xF947, 'M', u'磊'), (0xF948, 'M', u'賂'), (0xF949, 'M', u'雷'), (0xF94A, 'M', u'壘'), (0xF94B, 'M', u'屢'), (0xF94C, 'M', u'樓'), (0xF94D, 'M', u'淚'), (0xF94E, 'M', u'漏'), (0xF94F, 'M', u'累'), (0xF950, 'M', u'縷'), (0xF951, 'M', u'陋'), (0xF952, 'M', u'勒'), (0xF953, 'M', u'肋'), (0xF954, 'M', u'凜'), (0xF955, 'M', u'凌'), (0xF956, 'M', u'稜'), (0xF957, 'M', u'綾'), (0xF958, 'M', u'菱'), (0xF959, 'M', u'陵'), (0xF95A, 'M', u'讀'), (0xF95B, 'M', u'拏'), (0xF95C, 'M', u'樂'), (0xF95D, 'M', u'諾'), (0xF95E, 'M', u'丹'), (0xF95F, 'M', u'寧'), (0xF960, 'M', u'怒'), (0xF961, 'M', u'率'), (0xF962, 'M', u'異'), (0xF963, 'M', u'北'), (0xF964, 'M', u'磻'), (0xF965, 'M', u'便'), (0xF966, 'M', u'復'), (0xF967, 'M', u'不'), (0xF968, 'M', u'泌'), (0xF969, 'M', u'數'), (0xF96A, 'M', u'索'), (0xF96B, 'M', u'參'), (0xF96C, 'M', u'塞'), (0xF96D, 'M', u'省'), (0xF96E, 'M', u'葉'), (0xF96F, 'M', u'說'), (0xF970, 'M', u'殺'), (0xF971, 'M', u'辰'), (0xF972, 'M', u'沈'), (0xF973, 'M', u'拾'), (0xF974, 'M', u'若'), (0xF975, 'M', u'掠'), (0xF976, 'M', u'略'), (0xF977, 'M', u'亮'), (0xF978, 'M', u'兩'), (0xF979, 'M', u'凉'), ] def _seg_40(): return [ (0xF97A, 'M', u'梁'), (0xF97B, 'M', u'糧'), (0xF97C, 'M', u'良'), (0xF97D, 'M', u'諒'), (0xF97E, 'M', u'量'), (0xF97F, 'M', u'勵'), (0xF980, 'M', u'呂'), (0xF981, 'M', u'女'), (0xF982, 'M', u'廬'), (0xF983, 'M', u'旅'), (0xF984, 'M', u'濾'), (0xF985, 'M', u'礪'), (0xF986, 'M', u'閭'), (0xF987, 'M', u'驪'), (0xF988, 'M', u'麗'), (0xF989, 'M', u'黎'), (0xF98A, 'M', u'力'), (0xF98B, 'M', u'曆'), (0xF98C, 'M', u'歷'), (0xF98D, 'M', u'轢'), (0xF98E, 'M', u'年'), (0xF98F, 'M', u'憐'), (0xF990, 'M', u'戀'), (0xF991, 'M', u'撚'), (0xF992, 'M', u'漣'), (0xF993, 'M', u'煉'), (0xF994, 'M', u'璉'), (0xF995, 'M', u'秊'), (0xF996, 'M', u'練'), (0xF997, 'M', u'聯'), (0xF998, 'M', u'輦'), (0xF999, 'M', u'蓮'), (0xF99A, 'M', u'連'), (0xF99B, 'M', u'鍊'), (0xF99C, 'M', u'列'), (0xF99D, 'M', u'劣'), (0xF99E, 'M', u'咽'), (0xF99F, 'M', u'烈'), (0xF9A0, 'M', u'裂'), (0xF9A1, 'M', u'說'), (0xF9A2, 'M', u'廉'), (0xF9A3, 'M', u'念'), (0xF9A4, 'M', u'捻'), (0xF9A5, 'M', u'殮'), (0xF9A6, 'M', u'簾'), (0xF9A7, 'M', u'獵'), (0xF9A8, 'M', u'令'), (0xF9A9, 'M', u'囹'), (0xF9AA, 'M', u'寧'), (0xF9AB, 'M', u'嶺'), (0xF9AC, 'M', u'怜'), (0xF9AD, 'M', u'玲'), (0xF9AE, 'M', u'瑩'), (0xF9AF, 'M', u'羚'), (0xF9B0, 'M', u'聆'), (0xF9B1, 'M', u'鈴'), (0xF9B2, 'M', u'零'), (0xF9B3, 'M', u'靈'), (0xF9B4, 'M', u'領'), (0xF9B5, 'M', u'例'), (0xF9B6, 'M', u'禮'), (0xF9B7, 'M', u'醴'), (0xF9B8, 'M', u'隸'), (0xF9B9, 'M', u'惡'), (0xF9BA, 'M', u'了'), (0xF9BB, 'M', u'僚'), (0xF9BC, 'M', u'寮'), (0xF9BD, 'M', u'尿'), (0xF9BE, 'M', u'料'), (0xF9BF, 'M', u'樂'), (0xF9C0, 'M', u'燎'), (0xF9C1, 'M', u'療'), (0xF9C2, 'M', u'蓼'), (0xF9C3, 'M', u'遼'), (0xF9C4, 'M', u'龍'), (0xF9C5, 'M', u'暈'), (0xF9C6, 'M', u'阮'), (0xF9C7, 'M', u'劉'), (0xF9C8, 'M', u'杻'), (0xF9C9, 'M', u'柳'), (0xF9CA, 'M', u'流'), (0xF9CB, 'M', u'溜'), (0xF9CC, 'M', u'琉'), (0xF9CD, 'M', u'留'), (0xF9CE, 'M', u'硫'), (0xF9CF, 'M', u'紐'), (0xF9D0, 'M', u'類'), (0xF9D1, 'M', u'六'), (0xF9D2, 'M', u'戮'), (0xF9D3, 'M', u'陸'), (0xF9D4, 'M', u'倫'), (0xF9D5, 'M', u'崙'), (0xF9D6, 'M', u'淪'), (0xF9D7, 'M', u'輪'), (0xF9D8, 'M', u'律'), (0xF9D9, 'M', u'慄'), (0xF9DA, 'M', u'栗'), (0xF9DB, 'M', u'率'), (0xF9DC, 'M', u'隆'), (0xF9DD, 'M', u'利'), ] def _seg_41(): return [ (0xF9DE, 'M', u'吏'), (0xF9DF, 'M', u'履'), (0xF9E0, 'M', u'易'), (0xF9E1, 'M', u'李'), (0xF9E2, 'M', u'梨'), (0xF9E3, 'M', u'泥'), (0xF9E4, 'M', u'理'), (0xF9E5, 'M', u'痢'), (0xF9E6, 'M', u'罹'), (0xF9E7, 'M', u'裏'), (0xF9E8, 'M', u'裡'), (0xF9E9, 'M', u'里'), (0xF9EA, 'M', u'離'), (0xF9EB, 'M', u'匿'), (0xF9EC, 'M', u'溺'), (0xF9ED, 'M', u'吝'), (0xF9EE, 'M', u'燐'), (0xF9EF, 'M', u'璘'), (0xF9F0, 'M', u'藺'), (0xF9F1, 'M', u'隣'), (0xF9F2, 'M', u'鱗'), (0xF9F3, 'M', u'麟'), (0xF9F4, 'M', u'林'), (0xF9F5, 'M', u'淋'), (0xF9F6, 'M', u'臨'), (0xF9F7, 'M', u'立'), (0xF9F8, 'M', u'笠'), (0xF9F9, 'M', u'粒'), (0xF9FA, 'M', u'狀'), (0xF9FB, 'M', u'炙'), (0xF9FC, 'M', u'識'), (0xF9FD, 'M', u'什'), (0xF9FE, 'M', u'茶'), (0xF9FF, 'M', u'刺'), (0xFA00, 'M', u'切'), (0xFA01, 'M', u'度'), (0xFA02, 'M', u'拓'), (0xFA03, 'M', u'糖'), (0xFA04, 'M', u'宅'), (0xFA05, 'M', u'洞'), (0xFA06, 'M', u'暴'), (0xFA07, 'M', u'輻'), (0xFA08, 'M', u'行'), (0xFA09, 'M', u'降'), (0xFA0A, 'M', u'見'), (0xFA0B, 'M', u'廓'), (0xFA0C, 'M', u'兀'), (0xFA0D, 'M', u'嗀'), (0xFA0E, 'V'), (0xFA10, 'M', u'塚'), (0xFA11, 'V'), (0xFA12, 'M', u'晴'), (0xFA13, 'V'), (0xFA15, 'M', u'凞'), (0xFA16, 'M', u'猪'), (0xFA17, 'M', u'益'), (0xFA18, 'M', u'礼'), (0xFA19, 'M', u'神'), (0xFA1A, 'M', u'祥'), (0xFA1B, 'M', u'福'), (0xFA1C, 'M', u'靖'), (0xFA1D, 'M', u'精'), (0xFA1E, 'M', u'羽'), (0xFA1F, 'V'), (0xFA20, 'M', u'蘒'), (0xFA21, 'V'), (0xFA22, 'M', u'諸'), (0xFA23, 'V'), (0xFA25, 'M', u'逸'), (0xFA26, 'M', u'都'), (0xFA27, 'V'), (0xFA2A, 'M', u'飯'), (0xFA2B, 'M', u'飼'), (0xFA2C, 'M', u'館'), (0xFA2D, 'M', u'鶴'), (0xFA2E, 'M', u'郞'), (0xFA2F, 'M', u'隷'), (0xFA30, 'M', u'侮'), (0xFA31, 'M', u'僧'), (0xFA32, 'M', u'免'), (0xFA33, 'M', u'勉'), (0xFA34, 'M', u'勤'), (0xFA35, 'M', u'卑'), (0xFA36, 'M', u'喝'), (0xFA37, 'M', u'嘆'), (0xFA38, 'M', u'器'), (0xFA39, 'M', u'塀'), (0xFA3A, 'M', u'墨'), (0xFA3B, 'M', u'層'), (0xFA3C, 'M', u'屮'), (0xFA3D, 'M', u'悔'), (0xFA3E, 'M', u'慨'), (0xFA3F, 'M', u'憎'), (0xFA40, 'M', u'懲'), (0xFA41, 'M', u'敏'), (0xFA42, 'M', u'既'), (0xFA43, 'M', u'暑'), (0xFA44, 'M', u'梅'), (0xFA45, 'M', u'海'), (0xFA46, 'M', u'渚'), ] def _seg_42(): return [ (0xFA47, 'M', u'漢'), (0xFA48, 'M', u'煮'), (0xFA49, 'M', u'爫'), (0xFA4A, 'M', u'琢'), (0xFA4B, 'M', u'碑'), (0xFA4C, 'M', u'社'), (0xFA4D, 'M', u'祉'), (0xFA4E, 'M', u'祈'), (0xFA4F, 'M', u'祐'), (0xFA50, 'M', u'祖'), (0xFA51, 'M', u'祝'), (0xFA52, 'M', u'禍'), (0xFA53, 'M', u'禎'), (0xFA54, 'M', u'穀'), (0xFA55, 'M', u'突'), (0xFA56, 'M', u'節'), (0xFA57, 'M', u'練'), (0xFA58, 'M', u'縉'), (0xFA59, 'M', u'繁'), (0xFA5A, 'M', u'署'), (0xFA5B, 'M', u'者'), (0xFA5C, 'M', u'臭'), (0xFA5D, 'M', u'艹'), (0xFA5F, 'M', u'著'), (0xFA60, 'M', u'褐'), (0xFA61, 'M', u'視'), (0xFA62, 'M', u'謁'), (0xFA63, 'M', u'謹'), (0xFA64, 'M', u'賓'), (0xFA65, 'M', u'贈'), (0xFA66, 'M', u'辶'), (0xFA67, 'M', u'逸'), (0xFA68, 'M', u'難'), (0xFA69, 'M', u'響'), (0xFA6A, 'M', u'頻'), (0xFA6B, 'M', u'恵'), (0xFA6C, 'M', u'𤋮'), (0xFA6D, 'M', u'舘'), (0xFA6E, 'X'), (0xFA70, 'M', u'並'), (0xFA71, 'M', u'况'), (0xFA72, 'M', u'全'), (0xFA73, 'M', u'侀'), (0xFA74, 'M', u'充'), (0xFA75, 'M', u'冀'), (0xFA76, 'M', u'勇'), (0xFA77, 'M', u'勺'), (0xFA78, 'M', u'喝'), (0xFA79, 'M', u'啕'), (0xFA7A, 'M', u'喙'), (0xFA7B, 'M', u'嗢'), (0xFA7C, 'M', u'塚'), (0xFA7D, 'M', u'墳'), (0xFA7E, 'M', u'奄'), (0xFA7F, 'M', u'奔'), (0xFA80, 'M', u'婢'), (0xFA81, 'M', u'嬨'), (0xFA82, 'M', u'廒'), (0xFA83, 'M', u'廙'), (0xFA84, 'M', u'彩'), (0xFA85, 'M', u'徭'), (0xFA86, 'M', u'惘'), (0xFA87, 'M', u'慎'), (0xFA88, 'M', u'愈'), (0xFA89, 'M', u'憎'), (0xFA8A, 'M', u'慠'), (0xFA8B, 'M', u'懲'), (0xFA8C, 'M', u'戴'), (0xFA8D, 'M', u'揄'), (0xFA8E, 'M', u'搜'), (0xFA8F, 'M', u'摒'), (0xFA90, 'M', u'敖'), (0xFA91, 'M', u'晴'), (0xFA92, 'M', u'朗'), (0xFA93, 'M', u'望'), (0xFA94, 'M', u'杖'), (0xFA95, 'M', u'歹'), (0xFA96, 'M', u'殺'), (0xFA97, 'M', u'流'), (0xFA98, 'M', u'滛'), (0xFA99, 'M', u'滋'), (0xFA9A, 'M', u'漢'), (0xFA9B, 'M', u'瀞'), (0xFA9C, 'M', u'煮'), (0xFA9D, 'M', u'瞧'), (0xFA9E, 'M', u'爵'), (0xFA9F, 'M', u'犯'), (0xFAA0, 'M', u'猪'), (0xFAA1, 'M', u'瑱'), (0xFAA2, 'M', u'甆'), (0xFAA3, 'M', u'画'), (0xFAA4, 'M', u'瘝'), (0xFAA5, 'M', u'瘟'), (0xFAA6, 'M', u'益'), (0xFAA7, 'M', u'盛'), (0xFAA8, 'M', u'直'), (0xFAA9, 'M', u'睊'), (0xFAAA, 'M', u'着'), (0xFAAB, 'M', u'磌'), (0xFAAC, 'M', u'窱'), ] def _seg_43(): return [ (0xFAAD, 'M', u'節'), (0xFAAE, 'M', u'类'), (0xFAAF, 'M', u'絛'), (0xFAB0, 'M', u'練'), (0xFAB1, 'M', u'缾'), (0xFAB2, 'M', u'者'), (0xFAB3, 'M', u'荒'), (0xFAB4, 'M', u'華'), (0xFAB5, 'M', u'蝹'), (0xFAB6, 'M', u'襁'), (0xFAB7, 'M', u'覆'), (0xFAB8, 'M', u'視'), (0xFAB9, 'M', u'調'), (0xFABA, 'M', u'諸'), (0xFABB, 'M', u'請'), (0xFABC, 'M', u'謁'), (0xFABD, 'M', u'諾'), (0xFABE, 'M', u'諭'), (0xFABF, 'M', u'謹'), (0xFAC0, 'M', u'變'), (0xFAC1, 'M', u'贈'), (0xFAC2, 'M', u'輸'), (0xFAC3, 'M', u'遲'), (0xFAC4, 'M', u'醙'), (0xFAC5, 'M', u'鉶'), (0xFAC6, 'M', u'陼'), (0xFAC7, 'M', u'難'), (0xFAC8, 'M', u'靖'), (0xFAC9, 'M', u'韛'), (0xFACA, 'M', u'響'), (0xFACB, 'M', u'頋'), (0xFACC, 'M', u'頻'), (0xFACD, 'M', u'鬒'), (0xFACE, 'M', u'龜'), (0xFACF, 'M', u'𢡊'), (0xFAD0, 'M', u'𢡄'), (0xFAD1, 'M', u'𣏕'), (0xFAD2, 'M', u'㮝'), (0xFAD3, 'M', u'䀘'), (0xFAD4, 'M', u'䀹'), (0xFAD5, 'M', u'𥉉'), (0xFAD6, 'M', u'𥳐'), (0xFAD7, 'M', u'𧻓'), (0xFAD8, 'M', u'齃'), (0xFAD9, 'M', u'龎'), (0xFADA, 'X'), (0xFB00, 'M', u'ff'), (0xFB01, 'M', u'fi'), (0xFB02, 'M', u'fl'), (0xFB03, 'M', u'ffi'), (0xFB04, 'M', u'ffl'), (0xFB05, 'M', u'st'), (0xFB07, 'X'), (0xFB13, 'M', u'մն'), (0xFB14, 'M', u'մե'), (0xFB15, 'M', u'մի'), (0xFB16, 'M', u'վն'), (0xFB17, 'M', u'մխ'), (0xFB18, 'X'), (0xFB1D, 'M', u'יִ'), (0xFB1E, 'V'), (0xFB1F, 'M', u'ײַ'), (0xFB20, 'M', u'ע'), (0xFB21, 'M', u'א'), (0xFB22, 'M', u'ד'), (0xFB23, 'M', u'ה'), (0xFB24, 'M', u'כ'), (0xFB25, 'M', u'ל'), (0xFB26, 'M', u'ם'), (0xFB27, 'M', u'ר'), (0xFB28, 'M', u'ת'), (0xFB29, '3', u'+'), (0xFB2A, 'M', u'שׁ'), (0xFB2B, 'M', u'שׂ'), (0xFB2C, 'M', u'שּׁ'), (0xFB2D, 'M', u'שּׂ'), (0xFB2E, 'M', u'אַ'), (0xFB2F, 'M', u'אָ'), (0xFB30, 'M', u'אּ'), (0xFB31, 'M', u'בּ'), (0xFB32, 'M', u'גּ'), (0xFB33, 'M', u'דּ'), (0xFB34, 'M', u'הּ'), (0xFB35, 'M', u'וּ'), (0xFB36, 'M', u'זּ'), (0xFB37, 'X'), (0xFB38, 'M', u'טּ'), (0xFB39, 'M', u'יּ'), (0xFB3A, 'M', u'ךּ'), (0xFB3B, 'M', u'כּ'), (0xFB3C, 'M', u'לּ'), (0xFB3D, 'X'), (0xFB3E, 'M', u'מּ'), (0xFB3F, 'X'), (0xFB40, 'M', u'נּ'), (0xFB41, 'M', u'סּ'), (0xFB42, 'X'), (0xFB43, 'M', u'ףּ'), (0xFB44, 'M', u'פּ'), (0xFB45, 'X'), ] def _seg_44(): return [ (0xFB46, 'M', u'צּ'), (0xFB47, 'M', u'קּ'), (0xFB48, 'M', u'רּ'), (0xFB49, 'M', u'שּ'), (0xFB4A, 'M', u'תּ'), (0xFB4B, 'M', u'וֹ'), (0xFB4C, 'M', u'בֿ'), (0xFB4D, 'M', u'כֿ'), (0xFB4E, 'M', u'פֿ'), (0xFB4F, 'M', u'אל'), (0xFB50, 'M', u'ٱ'), (0xFB52, 'M', u'ٻ'), (0xFB56, 'M', u'پ'), (0xFB5A, 'M', u'ڀ'), (0xFB5E, 'M', u'ٺ'), (0xFB62, 'M', u'ٿ'), (0xFB66, 'M', u'ٹ'), (0xFB6A, 'M', u'ڤ'), (0xFB6E, 'M', u'ڦ'), (0xFB72, 'M', u'ڄ'), (0xFB76, 'M', u'ڃ'), (0xFB7A, 'M', u'چ'), (0xFB7E, 'M', u'ڇ'), (0xFB82, 'M', u'ڍ'), (0xFB84, 'M', u'ڌ'), (0xFB86, 'M', u'ڎ'), (0xFB88, 'M', u'ڈ'), (0xFB8A, 'M', u'ژ'), (0xFB8C, 'M', u'ڑ'), (0xFB8E, 'M', u'ک'), (0xFB92, 'M', u'گ'), (0xFB96, 'M', u'ڳ'), (0xFB9A, 'M', u'ڱ'), (0xFB9E, 'M', u'ں'), (0xFBA0, 'M', u'ڻ'), (0xFBA4, 'M', u'ۀ'), (0xFBA6, 'M', u'ہ'), (0xFBAA, 'M', u'ھ'), (0xFBAE, 'M', u'ے'), (0xFBB0, 'M', u'ۓ'), (0xFBB2, 'V'), (0xFBC2, 'X'), (0xFBD3, 'M', u'ڭ'), (0xFBD7, 'M', u'ۇ'), (0xFBD9, 'M', u'ۆ'), (0xFBDB, 'M', u'ۈ'), (0xFBDD, 'M', u'ۇٴ'), (0xFBDE, 'M', u'ۋ'), (0xFBE0, 'M', u'ۅ'), (0xFBE2, 'M', u'ۉ'), (0xFBE4, 'M', u'ې'), (0xFBE8, 'M', u'ى'), (0xFBEA, 'M', u'ئا'), (0xFBEC, 'M', u'ئە'), (0xFBEE, 'M', u'ئو'), (0xFBF0, 'M', u'ئۇ'), (0xFBF2, 'M', u'ئۆ'), (0xFBF4, 'M', u'ئۈ'), (0xFBF6, 'M', u'ئې'), (0xFBF9, 'M', u'ئى'), (0xFBFC, 'M', u'ی'), (0xFC00, 'M', u'ئج'), (0xFC01, 'M', u'ئح'), (0xFC02, 'M', u'ئم'), (0xFC03, 'M', u'ئى'), (0xFC04, 'M', u'ئي'), (0xFC05, 'M', u'بج'), (0xFC06, 'M', u'بح'), (0xFC07, 'M', u'بخ'), (0xFC08, 'M', u'بم'), (0xFC09, 'M', u'بى'), (0xFC0A, 'M', u'بي'), (0xFC0B, 'M', u'تج'), (0xFC0C, 'M', u'تح'), (0xFC0D, 'M', u'تخ'), (0xFC0E, 'M', u'تم'), (0xFC0F, 'M', u'تى'), (0xFC10, 'M', u'تي'), (0xFC11, 'M', u'ثج'), (0xFC12, 'M', u'ثم'), (0xFC13, 'M', u'ثى'), (0xFC14, 'M', u'ثي'), (0xFC15, 'M', u'جح'), (0xFC16, 'M', u'جم'), (0xFC17, 'M', u'حج'), (0xFC18, 'M', u'حم'), (0xFC19, 'M', u'خج'), (0xFC1A, 'M', u'خح'), (0xFC1B, 'M', u'خم'), (0xFC1C, 'M', u'سج'), (0xFC1D, 'M', u'سح'), (0xFC1E, 'M', u'سخ'), (0xFC1F, 'M', u'سم'), (0xFC20, 'M', u'صح'), (0xFC21, 'M', u'صم'), (0xFC22, 'M', u'ضج'), (0xFC23, 'M', u'ضح'), (0xFC24, 'M', u'ضخ'), (0xFC25, 'M', u'ضم'), (0xFC26, 'M', u'طح'), ] def _seg_45(): return [ (0xFC27, 'M', u'طم'), (0xFC28, 'M', u'ظم'), (0xFC29, 'M', u'عج'), (0xFC2A, 'M', u'عم'), (0xFC2B, 'M', u'غج'), (0xFC2C, 'M', u'غم'), (0xFC2D, 'M', u'فج'), (0xFC2E, 'M', u'فح'), (0xFC2F, 'M', u'فخ'), (0xFC30, 'M', u'فم'), (0xFC31, 'M', u'فى'), (0xFC32, 'M', u'في'), (0xFC33, 'M', u'قح'), (0xFC34, 'M', u'قم'), (0xFC35, 'M', u'قى'), (0xFC36, 'M', u'قي'), (0xFC37, 'M', u'كا'), (0xFC38, 'M', u'كج'), (0xFC39, 'M', u'كح'), (0xFC3A, 'M', u'كخ'), (0xFC3B, 'M', u'كل'), (0xFC3C, 'M', u'كم'), (0xFC3D, 'M', u'كى'), (0xFC3E, 'M', u'كي'), (0xFC3F, 'M', u'لج'), (0xFC40, 'M', u'لح'), (0xFC41, 'M', u'لخ'), (0xFC42, 'M', u'لم'), (0xFC43, 'M', u'لى'), (0xFC44, 'M', u'لي'), (0xFC45, 'M', u'مج'), (0xFC46, 'M', u'مح'), (0xFC47, 'M', u'مخ'), (0xFC48, 'M', u'مم'), (0xFC49, 'M', u'مى'), (0xFC4A, 'M', u'مي'), (0xFC4B, 'M', u'نج'), (0xFC4C, 'M', u'نح'), (0xFC4D, 'M', u'نخ'), (0xFC4E, 'M', u'نم'), (0xFC4F, 'M', u'نى'), (0xFC50, 'M', u'ني'), (0xFC51, 'M', u'هج'), (0xFC52, 'M', u'هم'), (0xFC53, 'M', u'هى'), (0xFC54, 'M', u'هي'), (0xFC55, 'M', u'يج'), (0xFC56, 'M', u'يح'), (0xFC57, 'M', u'يخ'), (0xFC58, 'M', u'يم'), (0xFC59, 'M', u'يى'), (0xFC5A, 'M', u'يي'), (0xFC5B, 'M', u'ذٰ'), (0xFC5C, 'M', u'رٰ'), (0xFC5D, 'M', u'ىٰ'), (0xFC5E, '3', u' ٌّ'), (0xFC5F, '3', u' ٍّ'), (0xFC60, '3', u' َّ'), (0xFC61, '3', u' ُّ'), (0xFC62, '3', u' ِّ'), (0xFC63, '3', u' ّٰ'), (0xFC64, 'M', u'ئر'), (0xFC65, 'M', u'ئز'), (0xFC66, 'M', u'ئم'), (0xFC67, 'M', u'ئن'), (0xFC68, 'M', u'ئى'), (0xFC69, 'M', u'ئي'), (0xFC6A, 'M', u'بر'), (0xFC6B, 'M', u'بز'), (0xFC6C, 'M', u'بم'), (0xFC6D, 'M', u'بن'), (0xFC6E, 'M', u'بى'), (0xFC6F, 'M', u'بي'), (0xFC70, 'M', u'تر'), (0xFC71, 'M', u'تز'), (0xFC72, 'M', u'تم'), (0xFC73, 'M', u'تن'), (0xFC74, 'M', u'تى'), (0xFC75, 'M', u'تي'), (0xFC76, 'M', u'ثر'), (0xFC77, 'M', u'ثز'), (0xFC78, 'M', u'ثم'), (0xFC79, 'M', u'ثن'), (0xFC7A, 'M', u'ثى'), (0xFC7B, 'M', u'ثي'), (0xFC7C, 'M', u'فى'), (0xFC7D, 'M', u'في'), (0xFC7E, 'M', u'قى'), (0xFC7F, 'M', u'قي'), (0xFC80, 'M', u'كا'), (0xFC81, 'M', u'كل'), (0xFC82, 'M', u'كم'), (0xFC83, 'M', u'كى'), (0xFC84, 'M', u'كي'), (0xFC85, 'M', u'لم'), (0xFC86, 'M', u'لى'), (0xFC87, 'M', u'لي'), (0xFC88, 'M', u'ما'), (0xFC89, 'M', u'مم'), (0xFC8A, 'M', u'نر'), ] def _seg_46(): return [ (0xFC8B, 'M', u'نز'), (0xFC8C, 'M', u'نم'), (0xFC8D, 'M', u'نن'), (0xFC8E, 'M', u'نى'), (0xFC8F, 'M', u'ني'), (0xFC90, 'M', u'ىٰ'), (0xFC91, 'M', u'ير'), (0xFC92, 'M', u'يز'), (0xFC93, 'M', u'يم'), (0xFC94, 'M', u'ين'), (0xFC95, 'M', u'يى'), (0xFC96, 'M', u'يي'), (0xFC97, 'M', u'ئج'), (0xFC98, 'M', u'ئح'), (0xFC99, 'M', u'ئخ'), (0xFC9A, 'M', u'ئم'), (0xFC9B, 'M', u'ئه'), (0xFC9C, 'M', u'بج'), (0xFC9D, 'M', u'بح'), (0xFC9E, 'M', u'بخ'), (0xFC9F, 'M', u'بم'), (0xFCA0, 'M', u'به'), (0xFCA1, 'M', u'تج'), (0xFCA2, 'M', u'تح'), (0xFCA3, 'M', u'تخ'), (0xFCA4, 'M', u'تم'), (0xFCA5, 'M', u'ته'), (0xFCA6, 'M', u'ثم'), (0xFCA7, 'M', u'جح'), (0xFCA8, 'M', u'جم'), (0xFCA9, 'M', u'حج'), (0xFCAA, 'M', u'حم'), (0xFCAB, 'M', u'خج'), (0xFCAC, 'M', u'خم'), (0xFCAD, 'M', u'سج'), (0xFCAE, 'M', u'سح'), (0xFCAF, 'M', u'سخ'), (0xFCB0, 'M', u'سم'), (0xFCB1, 'M', u'صح'), (0xFCB2, 'M', u'صخ'), (0xFCB3, 'M', u'صم'), (0xFCB4, 'M', u'ضج'), (0xFCB5, 'M', u'ضح'), (0xFCB6, 'M', u'ضخ'), (0xFCB7, 'M', u'ضم'), (0xFCB8, 'M', u'طح'), (0xFCB9, 'M', u'ظم'), (0xFCBA, 'M', u'عج'), (0xFCBB, 'M', u'عم'), (0xFCBC, 'M', u'غج'), (0xFCBD, 'M', u'غم'), (0xFCBE, 'M', u'فج'), (0xFCBF, 'M', u'فح'), (0xFCC0, 'M', u'فخ'), (0xFCC1, 'M', u'فم'), (0xFCC2, 'M', u'قح'), (0xFCC3, 'M', u'قم'), (0xFCC4, 'M', u'كج'), (0xFCC5, 'M', u'كح'), (0xFCC6, 'M', u'كخ'), (0xFCC7, 'M', u'كل'), (0xFCC8, 'M', u'كم'), (0xFCC9, 'M', u'لج'), (0xFCCA, 'M', u'لح'), (0xFCCB, 'M', u'لخ'), (0xFCCC, 'M', u'لم'), (0xFCCD, 'M', u'له'), (0xFCCE, 'M', u'مج'), (0xFCCF, 'M', u'مح'), (0xFCD0, 'M', u'مخ'), (0xFCD1, 'M', u'مم'), (0xFCD2, 'M', u'نج'), (0xFCD3, 'M', u'نح'), (0xFCD4, 'M', u'نخ'), (0xFCD5, 'M', u'نم'), (0xFCD6, 'M', u'نه'), (0xFCD7, 'M', u'هج'), (0xFCD8, 'M', u'هم'), (0xFCD9, 'M', u'هٰ'), (0xFCDA, 'M', u'يج'), (0xFCDB, 'M', u'يح'), (0xFCDC, 'M', u'يخ'), (0xFCDD, 'M', u'يم'), (0xFCDE, 'M', u'يه'), (0xFCDF, 'M', u'ئم'), (0xFCE0, 'M', u'ئه'), (0xFCE1, 'M', u'بم'), (0xFCE2, 'M', u'به'), (0xFCE3, 'M', u'تم'), (0xFCE4, 'M', u'ته'), (0xFCE5, 'M', u'ثم'), (0xFCE6, 'M', u'ثه'), (0xFCE7, 'M', u'سم'), (0xFCE8, 'M', u'سه'), (0xFCE9, 'M', u'شم'), (0xFCEA, 'M', u'شه'), (0xFCEB, 'M', u'كل'), (0xFCEC, 'M', u'كم'), (0xFCED, 'M', u'لم'), (0xFCEE, 'M', u'نم'), ] def _seg_47(): return [ (0xFCEF, 'M', u'نه'), (0xFCF0, 'M', u'يم'), (0xFCF1, 'M', u'يه'), (0xFCF2, 'M', u'ـَّ'), (0xFCF3, 'M', u'ـُّ'), (0xFCF4, 'M', u'ـِّ'), (0xFCF5, 'M', u'طى'), (0xFCF6, 'M', u'طي'), (0xFCF7, 'M', u'عى'), (0xFCF8, 'M', u'عي'), (0xFCF9, 'M', u'غى'), (0xFCFA, 'M', u'غي'), (0xFCFB, 'M', u'سى'), (0xFCFC, 'M', u'سي'), (0xFCFD, 'M', u'شى'), (0xFCFE, 'M', u'شي'), (0xFCFF, 'M', u'حى'), (0xFD00, 'M', u'حي'), (0xFD01, 'M', u'جى'), (0xFD02, 'M', u'جي'), (0xFD03, 'M', u'خى'), (0xFD04, 'M', u'خي'), (0xFD05, 'M', u'صى'), (0xFD06, 'M', u'صي'), (0xFD07, 'M', u'ضى'), (0xFD08, 'M', u'ضي'), (0xFD09, 'M', u'شج'), (0xFD0A, 'M', u'شح'), (0xFD0B, 'M', u'شخ'), (0xFD0C, 'M', u'شم'), (0xFD0D, 'M', u'شر'), (0xFD0E, 'M', u'سر'), (0xFD0F, 'M', u'صر'), (0xFD10, 'M', u'ضر'), (0xFD11, 'M', u'طى'), (0xFD12, 'M', u'طي'), (0xFD13, 'M', u'عى'), (0xFD14, 'M', u'عي'), (0xFD15, 'M', u'غى'), (0xFD16, 'M', u'غي'), (0xFD17, 'M', u'سى'), (0xFD18, 'M', u'سي'), (0xFD19, 'M', u'شى'), (0xFD1A, 'M', u'شي'), (0xFD1B, 'M', u'حى'), (0xFD1C, 'M', u'حي'), (0xFD1D, 'M', u'جى'), (0xFD1E, 'M', u'جي'), (0xFD1F, 'M', u'خى'), (0xFD20, 'M', u'خي'), (0xFD21, 'M', u'صى'), (0xFD22, 'M', u'صي'), (0xFD23, 'M', u'ضى'), (0xFD24, 'M', u'ضي'), (0xFD25, 'M', u'شج'), (0xFD26, 'M', u'شح'), (0xFD27, 'M', u'شخ'), (0xFD28, 'M', u'شم'), (0xFD29, 'M', u'شر'), (0xFD2A, 'M', u'سر'), (0xFD2B, 'M', u'صر'), (0xFD2C, 'M', u'ضر'), (0xFD2D, 'M', u'شج'), (0xFD2E, 'M', u'شح'), (0xFD2F, 'M', u'شخ'), (0xFD30, 'M', u'شم'), (0xFD31, 'M', u'سه'), (0xFD32, 'M', u'شه'), (0xFD33, 'M', u'طم'), (0xFD34, 'M', u'سج'), (0xFD35, 'M', u'سح'), (0xFD36, 'M', u'سخ'), (0xFD37, 'M', u'شج'), (0xFD38, 'M', u'شح'), (0xFD39, 'M', u'شخ'), (0xFD3A, 'M', u'طم'), (0xFD3B, 'M', u'ظم'), (0xFD3C, 'M', u'اً'), (0xFD3E, 'V'), (0xFD40, 'X'), (0xFD50, 'M', u'تجم'), (0xFD51, 'M', u'تحج'), (0xFD53, 'M', u'تحم'), (0xFD54, 'M', u'تخم'), (0xFD55, 'M', u'تمج'), (0xFD56, 'M', u'تمح'), (0xFD57, 'M', u'تمخ'), (0xFD58, 'M', u'جمح'), (0xFD5A, 'M', u'حمي'), (0xFD5B, 'M', u'حمى'), (0xFD5C, 'M', u'سحج'), (0xFD5D, 'M', u'سجح'), (0xFD5E, 'M', u'سجى'), (0xFD5F, 'M', u'سمح'), (0xFD61, 'M', u'سمج'), (0xFD62, 'M', u'سمم'), (0xFD64, 'M', u'صحح'), (0xFD66, 'M', u'صمم'), (0xFD67, 'M', u'شحم'), (0xFD69, 'M', u'شجي'), ] def _seg_48(): return [ (0xFD6A, 'M', u'شمخ'), (0xFD6C, 'M', u'شمم'), (0xFD6E, 'M', u'ضحى'), (0xFD6F, 'M', u'ضخم'), (0xFD71, 'M', u'طمح'), (0xFD73, 'M', u'طمم'), (0xFD74, 'M', u'طمي'), (0xFD75, 'M', u'عجم'), (0xFD76, 'M', u'عمم'), (0xFD78, 'M', u'عمى'), (0xFD79, 'M', u'غمم'), (0xFD7A, 'M', u'غمي'), (0xFD7B, 'M', u'غمى'), (0xFD7C, 'M', u'فخم'), (0xFD7E, 'M', u'قمح'), (0xFD7F, 'M', u'قمم'), (0xFD80, 'M', u'لحم'), (0xFD81, 'M', u'لحي'), (0xFD82, 'M', u'لحى'), (0xFD83, 'M', u'لجج'), (0xFD85, 'M', u'لخم'), (0xFD87, 'M', u'لمح'), (0xFD89, 'M', u'محج'), (0xFD8A, 'M', u'محم'), (0xFD8B, 'M', u'محي'), (0xFD8C, 'M', u'مجح'), (0xFD8D, 'M', u'مجم'), (0xFD8E, 'M', u'مخج'), (0xFD8F, 'M', u'مخم'), (0xFD90, 'X'), (0xFD92, 'M', u'مجخ'), (0xFD93, 'M', u'همج'), (0xFD94, 'M', u'همم'), (0xFD95, 'M', u'نحم'), (0xFD96, 'M', u'نحى'), (0xFD97, 'M', u'نجم'), (0xFD99, 'M', u'نجى'), (0xFD9A, 'M', u'نمي'), (0xFD9B, 'M', u'نمى'), (0xFD9C, 'M', u'يمم'), (0xFD9E, 'M', u'بخي'), (0xFD9F, 'M', u'تجي'), (0xFDA0, 'M', u'تجى'), (0xFDA1, 'M', u'تخي'), (0xFDA2, 'M', u'تخى'), (0xFDA3, 'M', u'تمي'), (0xFDA4, 'M', u'تمى'), (0xFDA5, 'M', u'جمي'), (0xFDA6, 'M', u'جحى'), (0xFDA7, 'M', u'جمى'), (0xFDA8, 'M', u'سخى'), (0xFDA9, 'M', u'صحي'), (0xFDAA, 'M', u'شحي'), (0xFDAB, 'M', u'ضحي'), (0xFDAC, 'M', u'لجي'), (0xFDAD, 'M', u'لمي'), (0xFDAE, 'M', u'يحي'), (0xFDAF, 'M', u'يجي'), (0xFDB0, 'M', u'يمي'), (0xFDB1, 'M', u'ممي'), (0xFDB2, 'M', u'قمي'), (0xFDB3, 'M', u'نحي'), (0xFDB4, 'M', u'قمح'), (0xFDB5, 'M', u'لحم'), (0xFDB6, 'M', u'عمي'), (0xFDB7, 'M', u'كمي'), (0xFDB8, 'M', u'نجح'), (0xFDB9, 'M', u'مخي'), (0xFDBA, 'M', u'لجم'), (0xFDBB, 'M', u'كمم'), (0xFDBC, 'M', u'لجم'), (0xFDBD, 'M', u'نجح'), (0xFDBE, 'M', u'جحي'), (0xFDBF, 'M', u'حجي'), (0xFDC0, 'M', u'مجي'), (0xFDC1, 'M', u'فمي'), (0xFDC2, 'M', u'بحي'), (0xFDC3, 'M', u'كمم'), (0xFDC4, 'M', u'عجم'), (0xFDC5, 'M', u'صمم'), (0xFDC6, 'M', u'سخي'), (0xFDC7, 'M', u'نجي'), (0xFDC8, 'X'), (0xFDF0, 'M', u'صلے'), (0xFDF1, 'M', u'قلے'), (0xFDF2, 'M', u'الله'), (0xFDF3, 'M', u'اكبر'), (0xFDF4, 'M', u'محمد'), (0xFDF5, 'M', u'صلعم'), (0xFDF6, 'M', u'رسول'), (0xFDF7, 'M', u'عليه'), (0xFDF8, 'M', u'وسلم'), (0xFDF9, 'M', u'صلى'), (0xFDFA, '3', u'صلى الله عليه وسلم'), (0xFDFB, '3', u'جل جلاله'), (0xFDFC, 'M', u'ریال'), (0xFDFD, 'V'), (0xFDFE, 'X'), (0xFE00, 'I'), (0xFE10, '3', u','), ] def _seg_49(): return [ (0xFE11, 'M', u'、'), (0xFE12, 'X'), (0xFE13, '3', u':'), (0xFE14, '3', u';'), (0xFE15, '3', u'!'), (0xFE16, '3', u'?'), (0xFE17, 'M', u'〖'), (0xFE18, 'M', u'〗'), (0xFE19, 'X'), (0xFE20, 'V'), (0xFE30, 'X'), (0xFE31, 'M', u'—'), (0xFE32, 'M', u'–'), (0xFE33, '3', u'_'), (0xFE35, '3', u'('), (0xFE36, '3', u')'), (0xFE37, '3', u'{'), (0xFE38, '3', u'}'), (0xFE39, 'M', u'〔'), (0xFE3A, 'M', u'〕'), (0xFE3B, 'M', u'【'), (0xFE3C, 'M', u'】'), (0xFE3D, 'M', u'《'), (0xFE3E, 'M', u'》'), (0xFE3F, 'M', u'〈'), (0xFE40, 'M', u'〉'), (0xFE41, 'M', u'「'), (0xFE42, 'M', u'」'), (0xFE43, 'M', u'『'), (0xFE44, 'M', u'』'), (0xFE45, 'V'), (0xFE47, '3', u'['), (0xFE48, '3', u']'), (0xFE49, '3', u' ̅'), (0xFE4D, '3', u'_'), (0xFE50, '3', u','), (0xFE51, 'M', u'、'), (0xFE52, 'X'), (0xFE54, '3', u';'), (0xFE55, '3', u':'), (0xFE56, '3', u'?'), (0xFE57, '3', u'!'), (0xFE58, 'M', u'—'), (0xFE59, '3', u'('), (0xFE5A, '3', u')'), (0xFE5B, '3', u'{'), (0xFE5C, '3', u'}'), (0xFE5D, 'M', u'〔'), (0xFE5E, 'M', u'〕'), (0xFE5F, '3', u'#'), (0xFE60, '3', u'&'), (0xFE61, '3', u'*'), (0xFE62, '3', u'+'), (0xFE63, 'M', u'-'), (0xFE64, '3', u'<'), (0xFE65, '3', u'>'), (0xFE66, '3', u'='), (0xFE67, 'X'), (0xFE68, '3', u'\\'), (0xFE69, '3', u'$'), (0xFE6A, '3', u'%'), (0xFE6B, '3', u'@'), (0xFE6C, 'X'), (0xFE70, '3', u' ً'), (0xFE71, 'M', u'ـً'), (0xFE72, '3', u' ٌ'), (0xFE73, 'V'), (0xFE74, '3', u' ٍ'), (0xFE75, 'X'), (0xFE76, '3', u' َ'), (0xFE77, 'M', u'ـَ'), (0xFE78, '3', u' ُ'), (0xFE79, 'M', u'ـُ'), (0xFE7A, '3', u' ِ'), (0xFE7B, 'M', u'ـِ'), (0xFE7C, '3', u' ّ'), (0xFE7D, 'M', u'ـّ'), (0xFE7E, '3', u' ْ'), (0xFE7F, 'M', u'ـْ'), (0xFE80, 'M', u'ء'), (0xFE81, 'M', u'آ'), (0xFE83, 'M', u'أ'), (0xFE85, 'M', u'ؤ'), (0xFE87, 'M', u'إ'), (0xFE89, 'M', u'ئ'), (0xFE8D, 'M', u'ا'), (0xFE8F, 'M', u'ب'), (0xFE93, 'M', u'ة'), (0xFE95, 'M', u'ت'), (0xFE99, 'M', u'ث'), (0xFE9D, 'M', u'ج'), (0xFEA1, 'M', u'ح'), (0xFEA5, 'M', u'خ'), (0xFEA9, 'M', u'د'), (0xFEAB, 'M', u'ذ'), (0xFEAD, 'M', u'ر'), (0xFEAF, 'M', u'ز'), (0xFEB1, 'M', u'س'), (0xFEB5, 'M', u'ش'), (0xFEB9, 'M', u'ص'), ] def _seg_50(): return [ (0xFEBD, 'M', u'ض'), (0xFEC1, 'M', u'ط'), (0xFEC5, 'M', u'ظ'), (0xFEC9, 'M', u'ع'), (0xFECD, 'M', u'غ'), (0xFED1, 'M', u'ف'), (0xFED5, 'M', u'ق'), (0xFED9, 'M', u'ك'), (0xFEDD, 'M', u'ل'), (0xFEE1, 'M', u'م'), (0xFEE5, 'M', u'ن'), (0xFEE9, 'M', u'ه'), (0xFEED, 'M', u'و'), (0xFEEF, 'M', u'ى'), (0xFEF1, 'M', u'ي'), (0xFEF5, 'M', u'لآ'), (0xFEF7, 'M', u'لأ'), (0xFEF9, 'M', u'لإ'), (0xFEFB, 'M', u'لا'), (0xFEFD, 'X'), (0xFEFF, 'I'), (0xFF00, 'X'), (0xFF01, '3', u'!'), (0xFF02, '3', u'"'), (0xFF03, '3', u'#'), (0xFF04, '3', u'$'), (0xFF05, '3', u'%'), (0xFF06, '3', u'&'), (0xFF07, '3', u'\''), (0xFF08, '3', u'('), (0xFF09, '3', u')'), (0xFF0A, '3', u'*'), (0xFF0B, '3', u'+'), (0xFF0C, '3', u','), (0xFF0D, 'M', u'-'), (0xFF0E, 'M', u'.'), (0xFF0F, '3', u'/'), (0xFF10, 'M', u'0'), (0xFF11, 'M', u'1'), (0xFF12, 'M', u'2'), (0xFF13, 'M', u'3'), (0xFF14, 'M', u'4'), (0xFF15, 'M', u'5'), (0xFF16, 'M', u'6'), (0xFF17, 'M', u'7'), (0xFF18, 'M', u'8'), (0xFF19, 'M', u'9'), (0xFF1A, '3', u':'), (0xFF1B, '3', u';'), (0xFF1C, '3', u'<'), (0xFF1D, '3', u'='), (0xFF1E, '3', u'>'), (0xFF1F, '3', u'?'), (0xFF20, '3', u'@'), (0xFF21, 'M', u'a'), (0xFF22, 'M', u'b'), (0xFF23, 'M', u'c'), (0xFF24, 'M', u'd'), (0xFF25, 'M', u'e'), (0xFF26, 'M', u'f'), (0xFF27, 'M', u'g'), (0xFF28, 'M', u'h'), (0xFF29, 'M', u'i'), (0xFF2A, 'M', u'j'), (0xFF2B, 'M', u'k'), (0xFF2C, 'M', u'l'), (0xFF2D, 'M', u'm'), (0xFF2E, 'M', u'n'), (0xFF2F, 'M', u'o'), (0xFF30, 'M', u'p'), (0xFF31, 'M', u'q'), (0xFF32, 'M', u'r'), (0xFF33, 'M', u's'), (0xFF34, 'M', u't'), (0xFF35, 'M', u'u'), (0xFF36, 'M', u'v'), (0xFF37, 'M', u'w'), (0xFF38, 'M', u'x'), (0xFF39, 'M', u'y'), (0xFF3A, 'M', u'z'), (0xFF3B, '3', u'['), (0xFF3C, '3', u'\\'), (0xFF3D, '3', u']'), (0xFF3E, '3', u'^'), (0xFF3F, '3', u'_'), (0xFF40, '3', u'`'), (0xFF41, 'M', u'a'), (0xFF42, 'M', u'b'), (0xFF43, 'M', u'c'), (0xFF44, 'M', u'd'), (0xFF45, 'M', u'e'), (0xFF46, 'M', u'f'), (0xFF47, 'M', u'g'), (0xFF48, 'M', u'h'), (0xFF49, 'M', u'i'), (0xFF4A, 'M', u'j'), (0xFF4B, 'M', u'k'), (0xFF4C, 'M', u'l'), (0xFF4D, 'M', u'm'), (0xFF4E, 'M', u'n'), ] def _seg_51(): return [ (0xFF4F, 'M', u'o'), (0xFF50, 'M', u'p'), (0xFF51, 'M', u'q'), (0xFF52, 'M', u'r'), (0xFF53, 'M', u's'), (0xFF54, 'M', u't'), (0xFF55, 'M', u'u'), (0xFF56, 'M', u'v'), (0xFF57, 'M', u'w'), (0xFF58, 'M', u'x'), (0xFF59, 'M', u'y'), (0xFF5A, 'M', u'z'), (0xFF5B, '3', u'{'), (0xFF5C, '3', u'|'), (0xFF5D, '3', u'}'), (0xFF5E, '3', u'~'), (0xFF5F, 'M', u'⦅'), (0xFF60, 'M', u'⦆'), (0xFF61, 'M', u'.'), (0xFF62, 'M', u'「'), (0xFF63, 'M', u'」'), (0xFF64, 'M', u'、'), (0xFF65, 'M', u'・'), (0xFF66, 'M', u'ヲ'), (0xFF67, 'M', u'ァ'), (0xFF68, 'M', u'ィ'), (0xFF69, 'M', u'ゥ'), (0xFF6A, 'M', u'ェ'), (0xFF6B, 'M', u'ォ'), (0xFF6C, 'M', u'ャ'), (0xFF6D, 'M', u'ュ'), (0xFF6E, 'M', u'ョ'), (0xFF6F, 'M', u'ッ'), (0xFF70, 'M', u'ー'), (0xFF71, 'M', u'ア'), (0xFF72, 'M', u'イ'), (0xFF73, 'M', u'ウ'), (0xFF74, 'M', u'エ'), (0xFF75, 'M', u'オ'), (0xFF76, 'M', u'カ'), (0xFF77, 'M', u'キ'), (0xFF78, 'M', u'ク'), (0xFF79, 'M', u'ケ'), (0xFF7A, 'M', u'コ'), (0xFF7B, 'M', u'サ'), (0xFF7C, 'M', u'シ'), (0xFF7D, 'M', u'ス'), (0xFF7E, 'M', u'セ'), (0xFF7F, 'M', u'ソ'), (0xFF80, 'M', u'タ'), (0xFF81, 'M', u'チ'), (0xFF82, 'M', u'ツ'), (0xFF83, 'M', u'テ'), (0xFF84, 'M', u'ト'), (0xFF85, 'M', u'ナ'), (0xFF86, 'M', u'ニ'), (0xFF87, 'M', u'ヌ'), (0xFF88, 'M', u'ネ'), (0xFF89, 'M', u'ノ'), (0xFF8A, 'M', u'ハ'), (0xFF8B, 'M', u'ヒ'), (0xFF8C, 'M', u'フ'), (0xFF8D, 'M', u'ヘ'), (0xFF8E, 'M', u'ホ'), (0xFF8F, 'M', u'マ'), (0xFF90, 'M', u'ミ'), (0xFF91, 'M', u'ム'), (0xFF92, 'M', u'メ'), (0xFF93, 'M', u'モ'), (0xFF94, 'M', u'ヤ'), (0xFF95, 'M', u'ユ'), (0xFF96, 'M', u'ヨ'), (0xFF97, 'M', u'ラ'), (0xFF98, 'M', u'リ'), (0xFF99, 'M', u'ル'), (0xFF9A, 'M', u'レ'), (0xFF9B, 'M', u'ロ'), (0xFF9C, 'M', u'ワ'), (0xFF9D, 'M', u'ン'), (0xFF9E, 'M', u'゙'), (0xFF9F, 'M', u'゚'), (0xFFA0, 'X'), (0xFFA1, 'M', u'ᄀ'), (0xFFA2, 'M', u'ᄁ'), (0xFFA3, 'M', u'ᆪ'), (0xFFA4, 'M', u'ᄂ'), (0xFFA5, 'M', u'ᆬ'), (0xFFA6, 'M', u'ᆭ'), (0xFFA7, 'M', u'ᄃ'), (0xFFA8, 'M', u'ᄄ'), (0xFFA9, 'M', u'ᄅ'), (0xFFAA, 'M', u'ᆰ'), (0xFFAB, 'M', u'ᆱ'), (0xFFAC, 'M', u'ᆲ'), (0xFFAD, 'M', u'ᆳ'), (0xFFAE, 'M', u'ᆴ'), (0xFFAF, 'M', u'ᆵ'), (0xFFB0, 'M', u'ᄚ'), (0xFFB1, 'M', u'ᄆ'), (0xFFB2, 'M', u'ᄇ'), ] def _seg_52(): return [ (0xFFB3, 'M', u'ᄈ'), (0xFFB4, 'M', u'ᄡ'), (0xFFB5, 'M', u'ᄉ'), (0xFFB6, 'M', u'ᄊ'), (0xFFB7, 'M', u'ᄋ'), (0xFFB8, 'M', u'ᄌ'), (0xFFB9, 'M', u'ᄍ'), (0xFFBA, 'M', u'ᄎ'), (0xFFBB, 'M', u'ᄏ'), (0xFFBC, 'M', u'ᄐ'), (0xFFBD, 'M', u'ᄑ'), (0xFFBE, 'M', u'ᄒ'), (0xFFBF, 'X'), (0xFFC2, 'M', u'ᅡ'), (0xFFC3, 'M', u'ᅢ'), (0xFFC4, 'M', u'ᅣ'), (0xFFC5, 'M', u'ᅤ'), (0xFFC6, 'M', u'ᅥ'), (0xFFC7, 'M', u'ᅦ'), (0xFFC8, 'X'), (0xFFCA, 'M', u'ᅧ'), (0xFFCB, 'M', u'ᅨ'), (0xFFCC, 'M', u'ᅩ'), (0xFFCD, 'M', u'ᅪ'), (0xFFCE, 'M', u'ᅫ'), (0xFFCF, 'M', u'ᅬ'), (0xFFD0, 'X'), (0xFFD2, 'M', u'ᅭ'), (0xFFD3, 'M', u'ᅮ'), (0xFFD4, 'M', u'ᅯ'), (0xFFD5, 'M', u'ᅰ'), (0xFFD6, 'M', u'ᅱ'), (0xFFD7, 'M', u'ᅲ'), (0xFFD8, 'X'), (0xFFDA, 'M', u'ᅳ'), (0xFFDB, 'M', u'ᅴ'), (0xFFDC, 'M', u'ᅵ'), (0xFFDD, 'X'), (0xFFE0, 'M', u'¢'), (0xFFE1, 'M', u'£'), (0xFFE2, 'M', u'¬'), (0xFFE3, '3', u' ̄'), (0xFFE4, 'M', u'¦'), (0xFFE5, 'M', u'¥'), (0xFFE6, 'M', u'₩'), (0xFFE7, 'X'), (0xFFE8, 'M', u'│'), (0xFFE9, 'M', u'←'), (0xFFEA, 'M', u'↑'), (0xFFEB, 'M', u'→'), (0xFFEC, 'M', u'↓'), (0xFFED, 'M', u'■'), (0xFFEE, 'M', u'○'), (0xFFEF, 'X'), (0x10000, 'V'), (0x1000C, 'X'), (0x1000D, 'V'), (0x10027, 'X'), (0x10028, 'V'), (0x1003B, 'X'), (0x1003C, 'V'), (0x1003E, 'X'), (0x1003F, 'V'), (0x1004E, 'X'), (0x10050, 'V'), (0x1005E, 'X'), (0x10080, 'V'), (0x100FB, 'X'), (0x10100, 'V'), (0x10103, 'X'), (0x10107, 'V'), (0x10134, 'X'), (0x10137, 'V'), (0x1018F, 'X'), (0x10190, 'V'), (0x1019C, 'X'), (0x101A0, 'V'), (0x101A1, 'X'), (0x101D0, 'V'), (0x101FE, 'X'), (0x10280, 'V'), (0x1029D, 'X'), (0x102A0, 'V'), (0x102D1, 'X'), (0x102E0, 'V'), (0x102FC, 'X'), (0x10300, 'V'), (0x10324, 'X'), (0x1032D, 'V'), (0x1034B, 'X'), (0x10350, 'V'), (0x1037B, 'X'), (0x10380, 'V'), (0x1039E, 'X'), (0x1039F, 'V'), (0x103C4, 'X'), (0x103C8, 'V'), (0x103D6, 'X'), (0x10400, 'M', u'𐐨'), (0x10401, 'M', u'𐐩'), ] def _seg_53(): return [ (0x10402, 'M', u'𐐪'), (0x10403, 'M', u'𐐫'), (0x10404, 'M', u'𐐬'), (0x10405, 'M', u'𐐭'), (0x10406, 'M', u'𐐮'), (0x10407, 'M', u'𐐯'), (0x10408, 'M', u'𐐰'), (0x10409, 'M', u'𐐱'), (0x1040A, 'M', u'𐐲'), (0x1040B, 'M', u'𐐳'), (0x1040C, 'M', u'𐐴'), (0x1040D, 'M', u'𐐵'), (0x1040E, 'M', u'𐐶'), (0x1040F, 'M', u'𐐷'), (0x10410, 'M', u'𐐸'), (0x10411, 'M', u'𐐹'), (0x10412, 'M', u'𐐺'), (0x10413, 'M', u'𐐻'), (0x10414, 'M', u'𐐼'), (0x10415, 'M', u'𐐽'), (0x10416, 'M', u'𐐾'), (0x10417, 'M', u'𐐿'), (0x10418, 'M', u'𐑀'), (0x10419, 'M', u'𐑁'), (0x1041A, 'M', u'𐑂'), (0x1041B, 'M', u'𐑃'), (0x1041C, 'M', u'𐑄'), (0x1041D, 'M', u'𐑅'), (0x1041E, 'M', u'𐑆'), (0x1041F, 'M', u'𐑇'), (0x10420, 'M', u'𐑈'), (0x10421, 'M', u'𐑉'), (0x10422, 'M', u'𐑊'), (0x10423, 'M', u'𐑋'), (0x10424, 'M', u'𐑌'), (0x10425, 'M', u'𐑍'), (0x10426, 'M', u'𐑎'), (0x10427, 'M', u'𐑏'), (0x10428, 'V'), (0x1049E, 'X'), (0x104A0, 'V'), (0x104AA, 'X'), (0x104B0, 'M', u'𐓘'), (0x104B1, 'M', u'𐓙'), (0x104B2, 'M', u'𐓚'), (0x104B3, 'M', u'𐓛'), (0x104B4, 'M', u'𐓜'), (0x104B5, 'M', u'𐓝'), (0x104B6, 'M', u'𐓞'), (0x104B7, 'M', u'𐓟'), (0x104B8, 'M', u'𐓠'), (0x104B9, 'M', u'𐓡'), (0x104BA, 'M', u'𐓢'), (0x104BB, 'M', u'𐓣'), (0x104BC, 'M', u'𐓤'), (0x104BD, 'M', u'𐓥'), (0x104BE, 'M', u'𐓦'), (0x104BF, 'M', u'𐓧'), (0x104C0, 'M', u'𐓨'), (0x104C1, 'M', u'𐓩'), (0x104C2, 'M', u'𐓪'), (0x104C3, 'M', u'𐓫'), (0x104C4, 'M', u'𐓬'), (0x104C5, 'M', u'𐓭'), (0x104C6, 'M', u'𐓮'), (0x104C7, 'M', u'𐓯'), (0x104C8, 'M', u'𐓰'), (0x104C9, 'M', u'𐓱'), (0x104CA, 'M', u'𐓲'), (0x104CB, 'M', u'𐓳'), (0x104CC, 'M', u'𐓴'), (0x104CD, 'M', u'𐓵'), (0x104CE, 'M', u'𐓶'), (0x104CF, 'M', u'𐓷'), (0x104D0, 'M', u'𐓸'), (0x104D1, 'M', u'𐓹'), (0x104D2, 'M', u'𐓺'), (0x104D3, 'M', u'𐓻'), (0x104D4, 'X'), (0x104D8, 'V'), (0x104FC, 'X'), (0x10500, 'V'), (0x10528, 'X'), (0x10530, 'V'), (0x10564, 'X'), (0x1056F, 'V'), (0x10570, 'X'), (0x10600, 'V'), (0x10737, 'X'), (0x10740, 'V'), (0x10756, 'X'), (0x10760, 'V'), (0x10768, 'X'), (0x10800, 'V'), (0x10806, 'X'), (0x10808, 'V'), (0x10809, 'X'), (0x1080A, 'V'), (0x10836, 'X'), (0x10837, 'V'), ] def _seg_54(): return [ (0x10839, 'X'), (0x1083C, 'V'), (0x1083D, 'X'), (0x1083F, 'V'), (0x10856, 'X'), (0x10857, 'V'), (0x1089F, 'X'), (0x108A7, 'V'), (0x108B0, 'X'), (0x108E0, 'V'), (0x108F3, 'X'), (0x108F4, 'V'), (0x108F6, 'X'), (0x108FB, 'V'), (0x1091C, 'X'), (0x1091F, 'V'), (0x1093A, 'X'), (0x1093F, 'V'), (0x10940, 'X'), (0x10980, 'V'), (0x109B8, 'X'), (0x109BC, 'V'), (0x109D0, 'X'), (0x109D2, 'V'), (0x10A04, 'X'), (0x10A05, 'V'), (0x10A07, 'X'), (0x10A0C, 'V'), (0x10A14, 'X'), (0x10A15, 'V'), (0x10A18, 'X'), (0x10A19, 'V'), (0x10A36, 'X'), (0x10A38, 'V'), (0x10A3B, 'X'), (0x10A3F, 'V'), (0x10A49, 'X'), (0x10A50, 'V'), (0x10A59, 'X'), (0x10A60, 'V'), (0x10AA0, 'X'), (0x10AC0, 'V'), (0x10AE7, 'X'), (0x10AEB, 'V'), (0x10AF7, 'X'), (0x10B00, 'V'), (0x10B36, 'X'), (0x10B39, 'V'), (0x10B56, 'X'), (0x10B58, 'V'), (0x10B73, 'X'), (0x10B78, 'V'), (0x10B92, 'X'), (0x10B99, 'V'), (0x10B9D, 'X'), (0x10BA9, 'V'), (0x10BB0, 'X'), (0x10C00, 'V'), (0x10C49, 'X'), (0x10C80, 'M', u'𐳀'), (0x10C81, 'M', u'𐳁'), (0x10C82, 'M', u'𐳂'), (0x10C83, 'M', u'𐳃'), (0x10C84, 'M', u'𐳄'), (0x10C85, 'M', u'𐳅'), (0x10C86, 'M', u'𐳆'), (0x10C87, 'M', u'𐳇'), (0x10C88, 'M', u'𐳈'), (0x10C89, 'M', u'𐳉'), (0x10C8A, 'M', u'𐳊'), (0x10C8B, 'M', u'𐳋'), (0x10C8C, 'M', u'𐳌'), (0x10C8D, 'M', u'𐳍'), (0x10C8E, 'M', u'𐳎'), (0x10C8F, 'M', u'𐳏'), (0x10C90, 'M', u'𐳐'), (0x10C91, 'M', u'𐳑'), (0x10C92, 'M', u'𐳒'), (0x10C93, 'M', u'𐳓'), (0x10C94, 'M', u'𐳔'), (0x10C95, 'M', u'𐳕'), (0x10C96, 'M', u'𐳖'), (0x10C97, 'M', u'𐳗'), (0x10C98, 'M', u'𐳘'), (0x10C99, 'M', u'𐳙'), (0x10C9A, 'M', u'𐳚'), (0x10C9B, 'M', u'𐳛'), (0x10C9C, 'M', u'𐳜'), (0x10C9D, 'M', u'𐳝'), (0x10C9E, 'M', u'𐳞'), (0x10C9F, 'M', u'𐳟'), (0x10CA0, 'M', u'𐳠'), (0x10CA1, 'M', u'𐳡'), (0x10CA2, 'M', u'𐳢'), (0x10CA3, 'M', u'𐳣'), (0x10CA4, 'M', u'𐳤'), (0x10CA5, 'M', u'𐳥'), (0x10CA6, 'M', u'𐳦'), (0x10CA7, 'M', u'𐳧'), (0x10CA8, 'M', u'𐳨'), ] def _seg_55(): return [ (0x10CA9, 'M', u'𐳩'), (0x10CAA, 'M', u'𐳪'), (0x10CAB, 'M', u'𐳫'), (0x10CAC, 'M', u'𐳬'), (0x10CAD, 'M', u'𐳭'), (0x10CAE, 'M', u'𐳮'), (0x10CAF, 'M', u'𐳯'), (0x10CB0, 'M', u'𐳰'), (0x10CB1, 'M', u'𐳱'), (0x10CB2, 'M', u'𐳲'), (0x10CB3, 'X'), (0x10CC0, 'V'), (0x10CF3, 'X'), (0x10CFA, 'V'), (0x10D28, 'X'), (0x10D30, 'V'), (0x10D3A, 'X'), (0x10E60, 'V'), (0x10E7F, 'X'), (0x10F00, 'V'), (0x10F28, 'X'), (0x10F30, 'V'), (0x10F5A, 'X'), (0x11000, 'V'), (0x1104E, 'X'), (0x11052, 'V'), (0x11070, 'X'), (0x1107F, 'V'), (0x110BD, 'X'), (0x110BE, 'V'), (0x110C2, 'X'), (0x110D0, 'V'), (0x110E9, 'X'), (0x110F0, 'V'), (0x110FA, 'X'), (0x11100, 'V'), (0x11135, 'X'), (0x11136, 'V'), (0x11147, 'X'), (0x11150, 'V'), (0x11177, 'X'), (0x11180, 'V'), (0x111CE, 'X'), (0x111D0, 'V'), (0x111E0, 'X'), (0x111E1, 'V'), (0x111F5, 'X'), (0x11200, 'V'), (0x11212, 'X'), (0x11213, 'V'), (0x1123F, 'X'), (0x11280, 'V'), (0x11287, 'X'), (0x11288, 'V'), (0x11289, 'X'), (0x1128A, 'V'), (0x1128E, 'X'), (0x1128F, 'V'), (0x1129E, 'X'), (0x1129F, 'V'), (0x112AA, 'X'), (0x112B0, 'V'), (0x112EB, 'X'), (0x112F0, 'V'), (0x112FA, 'X'), (0x11300, 'V'), (0x11304, 'X'), (0x11305, 'V'), (0x1130D, 'X'), (0x1130F, 'V'), (0x11311, 'X'), (0x11313, 'V'), (0x11329, 'X'), (0x1132A, 'V'), (0x11331, 'X'), (0x11332, 'V'), (0x11334, 'X'), (0x11335, 'V'), (0x1133A, 'X'), (0x1133B, 'V'), (0x11345, 'X'), (0x11347, 'V'), (0x11349, 'X'), (0x1134B, 'V'), (0x1134E, 'X'), (0x11350, 'V'), (0x11351, 'X'), (0x11357, 'V'), (0x11358, 'X'), (0x1135D, 'V'), (0x11364, 'X'), (0x11366, 'V'), (0x1136D, 'X'), (0x11370, 'V'), (0x11375, 'X'), (0x11400, 'V'), (0x1145A, 'X'), (0x1145B, 'V'), (0x1145C, 'X'), (0x1145D, 'V'), ] def _seg_56(): return [ (0x1145F, 'X'), (0x11480, 'V'), (0x114C8, 'X'), (0x114D0, 'V'), (0x114DA, 'X'), (0x11580, 'V'), (0x115B6, 'X'), (0x115B8, 'V'), (0x115DE, 'X'), (0x11600, 'V'), (0x11645, 'X'), (0x11650, 'V'), (0x1165A, 'X'), (0x11660, 'V'), (0x1166D, 'X'), (0x11680, 'V'), (0x116B8, 'X'), (0x116C0, 'V'), (0x116CA, 'X'), (0x11700, 'V'), (0x1171B, 'X'), (0x1171D, 'V'), (0x1172C, 'X'), (0x11730, 'V'), (0x11740, 'X'), (0x11800, 'V'), (0x1183C, 'X'), (0x118A0, 'M', u'𑣀'), (0x118A1, 'M', u'𑣁'), (0x118A2, 'M', u'𑣂'), (0x118A3, 'M', u'𑣃'), (0x118A4, 'M', u'𑣄'), (0x118A5, 'M', u'𑣅'), (0x118A6, 'M', u'𑣆'), (0x118A7, 'M', u'𑣇'), (0x118A8, 'M', u'𑣈'), (0x118A9, 'M', u'𑣉'), (0x118AA, 'M', u'𑣊'), (0x118AB, 'M', u'𑣋'), (0x118AC, 'M', u'𑣌'), (0x118AD, 'M', u'𑣍'), (0x118AE, 'M', u'𑣎'), (0x118AF, 'M', u'𑣏'), (0x118B0, 'M', u'𑣐'), (0x118B1, 'M', u'𑣑'), (0x118B2, 'M', u'𑣒'), (0x118B3, 'M', u'𑣓'), (0x118B4, 'M', u'𑣔'), (0x118B5, 'M', u'𑣕'), (0x118B6, 'M', u'𑣖'), (0x118B7, 'M', u'𑣗'), (0x118B8, 'M', u'𑣘'), (0x118B9, 'M', u'𑣙'), (0x118BA, 'M', u'𑣚'), (0x118BB, 'M', u'𑣛'), (0x118BC, 'M', u'𑣜'), (0x118BD, 'M', u'𑣝'), (0x118BE, 'M', u'𑣞'), (0x118BF, 'M', u'𑣟'), (0x118C0, 'V'), (0x118F3, 'X'), (0x118FF, 'V'), (0x11900, 'X'), (0x11A00, 'V'), (0x11A48, 'X'), (0x11A50, 'V'), (0x11A84, 'X'), (0x11A86, 'V'), (0x11AA3, 'X'), (0x11AC0, 'V'), (0x11AF9, 'X'), (0x11C00, 'V'), (0x11C09, 'X'), (0x11C0A, 'V'), (0x11C37, 'X'), (0x11C38, 'V'), (0x11C46, 'X'), (0x11C50, 'V'), (0x11C6D, 'X'), (0x11C70, 'V'), (0x11C90, 'X'), (0x11C92, 'V'), (0x11CA8, 'X'), (0x11CA9, 'V'), (0x11CB7, 'X'), (0x11D00, 'V'), (0x11D07, 'X'), (0x11D08, 'V'), (0x11D0A, 'X'), (0x11D0B, 'V'), (0x11D37, 'X'), (0x11D3A, 'V'), (0x11D3B, 'X'), (0x11D3C, 'V'), (0x11D3E, 'X'), (0x11D3F, 'V'), (0x11D48, 'X'), (0x11D50, 'V'), (0x11D5A, 'X'), (0x11D60, 'V'), ] def _seg_57(): return [ (0x11D66, 'X'), (0x11D67, 'V'), (0x11D69, 'X'), (0x11D6A, 'V'), (0x11D8F, 'X'), (0x11D90, 'V'), (0x11D92, 'X'), (0x11D93, 'V'), (0x11D99, 'X'), (0x11DA0, 'V'), (0x11DAA, 'X'), (0x11EE0, 'V'), (0x11EF9, 'X'), (0x12000, 'V'), (0x1239A, 'X'), (0x12400, 'V'), (0x1246F, 'X'), (0x12470, 'V'), (0x12475, 'X'), (0x12480, 'V'), (0x12544, 'X'), (0x13000, 'V'), (0x1342F, 'X'), (0x14400, 'V'), (0x14647, 'X'), (0x16800, 'V'), (0x16A39, 'X'), (0x16A40, 'V'), (0x16A5F, 'X'), (0x16A60, 'V'), (0x16A6A, 'X'), (0x16A6E, 'V'), (0x16A70, 'X'), (0x16AD0, 'V'), (0x16AEE, 'X'), (0x16AF0, 'V'), (0x16AF6, 'X'), (0x16B00, 'V'), (0x16B46, 'X'), (0x16B50, 'V'), (0x16B5A, 'X'), (0x16B5B, 'V'), (0x16B62, 'X'), (0x16B63, 'V'), (0x16B78, 'X'), (0x16B7D, 'V'), (0x16B90, 'X'), (0x16E60, 'V'), (0x16E9B, 'X'), (0x16F00, 'V'), (0x16F45, 'X'), (0x16F50, 'V'), (0x16F7F, 'X'), (0x16F8F, 'V'), (0x16FA0, 'X'), (0x16FE0, 'V'), (0x16FE2, 'X'), (0x17000, 'V'), (0x187F2, 'X'), (0x18800, 'V'), (0x18AF3, 'X'), (0x1B000, 'V'), (0x1B11F, 'X'), (0x1B170, 'V'), (0x1B2FC, 'X'), (0x1BC00, 'V'), (0x1BC6B, 'X'), (0x1BC70, 'V'), (0x1BC7D, 'X'), (0x1BC80, 'V'), (0x1BC89, 'X'), (0x1BC90, 'V'), (0x1BC9A, 'X'), (0x1BC9C, 'V'), (0x1BCA0, 'I'), (0x1BCA4, 'X'), (0x1D000, 'V'), (0x1D0F6, 'X'), (0x1D100, 'V'), (0x1D127, 'X'), (0x1D129, 'V'), (0x1D15E, 'M', u'𝅗𝅥'), (0x1D15F, 'M', u'𝅘𝅥'), (0x1D160, 'M', u'𝅘𝅥𝅮'), (0x1D161, 'M', u'𝅘𝅥𝅯'), (0x1D162, 'M', u'𝅘𝅥𝅰'), (0x1D163, 'M', u'𝅘𝅥𝅱'), (0x1D164, 'M', u'𝅘𝅥𝅲'), (0x1D165, 'V'), (0x1D173, 'X'), (0x1D17B, 'V'), (0x1D1BB, 'M', u'𝆹𝅥'), (0x1D1BC, 'M', u'𝆺𝅥'), (0x1D1BD, 'M', u'𝆹𝅥𝅮'), (0x1D1BE, 'M', u'𝆺𝅥𝅮'), (0x1D1BF, 'M', u'𝆹𝅥𝅯'), (0x1D1C0, 'M', u'𝆺𝅥𝅯'), (0x1D1C1, 'V'), (0x1D1E9, 'X'), (0x1D200, 'V'), ] def _seg_58(): return [ (0x1D246, 'X'), (0x1D2E0, 'V'), (0x1D2F4, 'X'), (0x1D300, 'V'), (0x1D357, 'X'), (0x1D360, 'V'), (0x1D379, 'X'), (0x1D400, 'M', u'a'), (0x1D401, 'M', u'b'), (0x1D402, 'M', u'c'), (0x1D403, 'M', u'd'), (0x1D404, 'M', u'e'), (0x1D405, 'M', u'f'), (0x1D406, 'M', u'g'), (0x1D407, 'M', u'h'), (0x1D408, 'M', u'i'), (0x1D409, 'M', u'j'), (0x1D40A, 'M', u'k'), (0x1D40B, 'M', u'l'), (0x1D40C, 'M', u'm'), (0x1D40D, 'M', u'n'), (0x1D40E, 'M', u'o'), (0x1D40F, 'M', u'p'), (0x1D410, 'M', u'q'), (0x1D411, 'M', u'r'), (0x1D412, 'M', u's'), (0x1D413, 'M', u't'), (0x1D414, 'M', u'u'), (0x1D415, 'M', u'v'), (0x1D416, 'M', u'w'), (0x1D417, 'M', u'x'), (0x1D418, 'M', u'y'), (0x1D419, 'M', u'z'), (0x1D41A, 'M', u'a'), (0x1D41B, 'M', u'b'), (0x1D41C, 'M', u'c'), (0x1D41D, 'M', u'd'), (0x1D41E, 'M', u'e'), (0x1D41F, 'M', u'f'), (0x1D420, 'M', u'g'), (0x1D421, 'M', u'h'), (0x1D422, 'M', u'i'), (0x1D423, 'M', u'j'), (0x1D424, 'M', u'k'), (0x1D425, 'M', u'l'), (0x1D426, 'M', u'm'), (0x1D427, 'M', u'n'), (0x1D428, 'M', u'o'), (0x1D429, 'M', u'p'), (0x1D42A, 'M', u'q'), (0x1D42B, 'M', u'r'), (0x1D42C, 'M', u's'), (0x1D42D, 'M', u't'), (0x1D42E, 'M', u'u'), (0x1D42F, 'M', u'v'), (0x1D430, 'M', u'w'), (0x1D431, 'M', u'x'), (0x1D432, 'M', u'y'), (0x1D433, 'M', u'z'), (0x1D434, 'M', u'a'), (0x1D435, 'M', u'b'), (0x1D436, 'M', u'c'), (0x1D437, 'M', u'd'), (0x1D438, 'M', u'e'), (0x1D439, 'M', u'f'), (0x1D43A, 'M', u'g'), (0x1D43B, 'M', u'h'), (0x1D43C, 'M', u'i'), (0x1D43D, 'M', u'j'), (0x1D43E, 'M', u'k'), (0x1D43F, 'M', u'l'), (0x1D440, 'M', u'm'), (0x1D441, 'M', u'n'), (0x1D442, 'M', u'o'), (0x1D443, 'M', u'p'), (0x1D444, 'M', u'q'), (0x1D445, 'M', u'r'), (0x1D446, 'M', u's'), (0x1D447, 'M', u't'), (0x1D448, 'M', u'u'), (0x1D449, 'M', u'v'), (0x1D44A, 'M', u'w'), (0x1D44B, 'M', u'x'), (0x1D44C, 'M', u'y'), (0x1D44D, 'M', u'z'), (0x1D44E, 'M', u'a'), (0x1D44F, 'M', u'b'), (0x1D450, 'M', u'c'), (0x1D451, 'M', u'd'), (0x1D452, 'M', u'e'), (0x1D453, 'M', u'f'), (0x1D454, 'M', u'g'), (0x1D455, 'X'), (0x1D456, 'M', u'i'), (0x1D457, 'M', u'j'), (0x1D458, 'M', u'k'), (0x1D459, 'M', u'l'), (0x1D45A, 'M', u'm'), (0x1D45B, 'M', u'n'), (0x1D45C, 'M', u'o'), ] def _seg_59(): return [ (0x1D45D, 'M', u'p'), (0x1D45E, 'M', u'q'), (0x1D45F, 'M', u'r'), (0x1D460, 'M', u's'), (0x1D461, 'M', u't'), (0x1D462, 'M', u'u'), (0x1D463, 'M', u'v'), (0x1D464, 'M', u'w'), (0x1D465, 'M', u'x'), (0x1D466, 'M', u'y'), (0x1D467, 'M', u'z'), (0x1D468, 'M', u'a'), (0x1D469, 'M', u'b'), (0x1D46A, 'M', u'c'), (0x1D46B, 'M', u'd'), (0x1D46C, 'M', u'e'), (0x1D46D, 'M', u'f'), (0x1D46E, 'M', u'g'), (0x1D46F, 'M', u'h'), (0x1D470, 'M', u'i'), (0x1D471, 'M', u'j'), (0x1D472, 'M', u'k'), (0x1D473, 'M', u'l'), (0x1D474, 'M', u'm'), (0x1D475, 'M', u'n'), (0x1D476, 'M', u'o'), (0x1D477, 'M', u'p'), (0x1D478, 'M', u'q'), (0x1D479, 'M', u'r'), (0x1D47A, 'M', u's'), (0x1D47B, 'M', u't'), (0x1D47C, 'M', u'u'), (0x1D47D, 'M', u'v'), (0x1D47E, 'M', u'w'), (0x1D47F, 'M', u'x'), (0x1D480, 'M', u'y'), (0x1D481, 'M', u'z'), (0x1D482, 'M', u'a'), (0x1D483, 'M', u'b'), (0x1D484, 'M', u'c'), (0x1D485, 'M', u'd'), (0x1D486, 'M', u'e'), (0x1D487, 'M', u'f'), (0x1D488, 'M', u'g'), (0x1D489, 'M', u'h'), (0x1D48A, 'M', u'i'), (0x1D48B, 'M', u'j'), (0x1D48C, 'M', u'k'), (0x1D48D, 'M', u'l'), (0x1D48E, 'M', u'm'), (0x1D48F, 'M', u'n'), (0x1D490, 'M', u'o'), (0x1D491, 'M', u'p'), (0x1D492, 'M', u'q'), (0x1D493, 'M', u'r'), (0x1D494, 'M', u's'), (0x1D495, 'M', u't'), (0x1D496, 'M', u'u'), (0x1D497, 'M', u'v'), (0x1D498, 'M', u'w'), (0x1D499, 'M', u'x'), (0x1D49A, 'M', u'y'), (0x1D49B, 'M', u'z'), (0x1D49C, 'M', u'a'), (0x1D49D, 'X'), (0x1D49E, 'M', u'c'), (0x1D49F, 'M', u'd'), (0x1D4A0, 'X'), (0x1D4A2, 'M', u'g'), (0x1D4A3, 'X'), (0x1D4A5, 'M', u'j'), (0x1D4A6, 'M', u'k'), (0x1D4A7, 'X'), (0x1D4A9, 'M', u'n'), (0x1D4AA, 'M', u'o'), (0x1D4AB, 'M', u'p'), (0x1D4AC, 'M', u'q'), (0x1D4AD, 'X'), (0x1D4AE, 'M', u's'), (0x1D4AF, 'M', u't'), (0x1D4B0, 'M', u'u'), (0x1D4B1, 'M', u'v'), (0x1D4B2, 'M', u'w'), (0x1D4B3, 'M', u'x'), (0x1D4B4, 'M', u'y'), (0x1D4B5, 'M', u'z'), (0x1D4B6, 'M', u'a'), (0x1D4B7, 'M', u'b'), (0x1D4B8, 'M', u'c'), (0x1D4B9, 'M', u'd'), (0x1D4BA, 'X'), (0x1D4BB, 'M', u'f'), (0x1D4BC, 'X'), (0x1D4BD, 'M', u'h'), (0x1D4BE, 'M', u'i'), (0x1D4BF, 'M', u'j'), (0x1D4C0, 'M', u'k'), (0x1D4C1, 'M', u'l'), (0x1D4C2, 'M', u'm'), (0x1D4C3, 'M', u'n'), ] def _seg_60(): return [ (0x1D4C4, 'X'), (0x1D4C5, 'M', u'p'), (0x1D4C6, 'M', u'q'), (0x1D4C7, 'M', u'r'), (0x1D4C8, 'M', u's'), (0x1D4C9, 'M', u't'), (0x1D4CA, 'M', u'u'), (0x1D4CB, 'M', u'v'), (0x1D4CC, 'M', u'w'), (0x1D4CD, 'M', u'x'), (0x1D4CE, 'M', u'y'), (0x1D4CF, 'M', u'z'), (0x1D4D0, 'M', u'a'), (0x1D4D1, 'M', u'b'), (0x1D4D2, 'M', u'c'), (0x1D4D3, 'M', u'd'), (0x1D4D4, 'M', u'e'), (0x1D4D5, 'M', u'f'), (0x1D4D6, 'M', u'g'), (0x1D4D7, 'M', u'h'), (0x1D4D8, 'M', u'i'), (0x1D4D9, 'M', u'j'), (0x1D4DA, 'M', u'k'), (0x1D4DB, 'M', u'l'), (0x1D4DC, 'M', u'm'), (0x1D4DD, 'M', u'n'), (0x1D4DE, 'M', u'o'), (0x1D4DF, 'M', u'p'), (0x1D4E0, 'M', u'q'), (0x1D4E1, 'M', u'r'), (0x1D4E2, 'M', u's'), (0x1D4E3, 'M', u't'), (0x1D4E4, 'M', u'u'), (0x1D4E5, 'M', u'v'), (0x1D4E6, 'M', u'w'), (0x1D4E7, 'M', u'x'), (0x1D4E8, 'M', u'y'), (0x1D4E9, 'M', u'z'), (0x1D4EA, 'M', u'a'), (0x1D4EB, 'M', u'b'), (0x1D4EC, 'M', u'c'), (0x1D4ED, 'M', u'd'), (0x1D4EE, 'M', u'e'), (0x1D4EF, 'M', u'f'), (0x1D4F0, 'M', u'g'), (0x1D4F1, 'M', u'h'), (0x1D4F2, 'M', u'i'), (0x1D4F3, 'M', u'j'), (0x1D4F4, 'M', u'k'), (0x1D4F5, 'M', u'l'), (0x1D4F6, 'M', u'm'), (0x1D4F7, 'M', u'n'), (0x1D4F8, 'M', u'o'), (0x1D4F9, 'M', u'p'), (0x1D4FA, 'M', u'q'), (0x1D4FB, 'M', u'r'), (0x1D4FC, 'M', u's'), (0x1D4FD, 'M', u't'), (0x1D4FE, 'M', u'u'), (0x1D4FF, 'M', u'v'), (0x1D500, 'M', u'w'), (0x1D501, 'M', u'x'), (0x1D502, 'M', u'y'), (0x1D503, 'M', u'z'), (0x1D504, 'M', u'a'), (0x1D505, 'M', u'b'), (0x1D506, 'X'), (0x1D507, 'M', u'd'), (0x1D508, 'M', u'e'), (0x1D509, 'M', u'f'), (0x1D50A, 'M', u'g'), (0x1D50B, 'X'), (0x1D50D, 'M', u'j'), (0x1D50E, 'M', u'k'), (0x1D50F, 'M', u'l'), (0x1D510, 'M', u'm'), (0x1D511, 'M', u'n'), (0x1D512, 'M', u'o'), (0x1D513, 'M', u'p'), (0x1D514, 'M', u'q'), (0x1D515, 'X'), (0x1D516, 'M', u's'), (0x1D517, 'M', u't'), (0x1D518, 'M', u'u'), (0x1D519, 'M', u'v'), (0x1D51A, 'M', u'w'), (0x1D51B, 'M', u'x'), (0x1D51C, 'M', u'y'), (0x1D51D, 'X'), (0x1D51E, 'M', u'a'), (0x1D51F, 'M', u'b'), (0x1D520, 'M', u'c'), (0x1D521, 'M', u'd'), (0x1D522, 'M', u'e'), (0x1D523, 'M', u'f'), (0x1D524, 'M', u'g'), (0x1D525, 'M', u'h'), (0x1D526, 'M', u'i'), (0x1D527, 'M', u'j'), (0x1D528, 'M', u'k'), ] def _seg_61(): return [ (0x1D529, 'M', u'l'), (0x1D52A, 'M', u'm'), (0x1D52B, 'M', u'n'), (0x1D52C, 'M', u'o'), (0x1D52D, 'M', u'p'), (0x1D52E, 'M', u'q'), (0x1D52F, 'M', u'r'), (0x1D530, 'M', u's'), (0x1D531, 'M', u't'), (0x1D532, 'M', u'u'), (0x1D533, 'M', u'v'), (0x1D534, 'M', u'w'), (0x1D535, 'M', u'x'), (0x1D536, 'M', u'y'), (0x1D537, 'M', u'z'), (0x1D538, 'M', u'a'), (0x1D539, 'M', u'b'), (0x1D53A, 'X'), (0x1D53B, 'M', u'd'), (0x1D53C, 'M', u'e'), (0x1D53D, 'M', u'f'), (0x1D53E, 'M', u'g'), (0x1D53F, 'X'), (0x1D540, 'M', u'i'), (0x1D541, 'M', u'j'), (0x1D542, 'M', u'k'), (0x1D543, 'M', u'l'), (0x1D544, 'M', u'm'), (0x1D545, 'X'), (0x1D546, 'M', u'o'), (0x1D547, 'X'), (0x1D54A, 'M', u's'), (0x1D54B, 'M', u't'), (0x1D54C, 'M', u'u'), (0x1D54D, 'M', u'v'), (0x1D54E, 'M', u'w'), (0x1D54F, 'M', u'x'), (0x1D550, 'M', u'y'), (0x1D551, 'X'), (0x1D552, 'M', u'a'), (0x1D553, 'M', u'b'), (0x1D554, 'M', u'c'), (0x1D555, 'M', u'd'), (0x1D556, 'M', u'e'), (0x1D557, 'M', u'f'), (0x1D558, 'M', u'g'), (0x1D559, 'M', u'h'), (0x1D55A, 'M', u'i'), (0x1D55B, 'M', u'j'), (0x1D55C, 'M', u'k'), (0x1D55D, 'M', u'l'), (0x1D55E, 'M', u'm'), (0x1D55F, 'M', u'n'), (0x1D560, 'M', u'o'), (0x1D561, 'M', u'p'), (0x1D562, 'M', u'q'), (0x1D563, 'M', u'r'), (0x1D564, 'M', u's'), (0x1D565, 'M', u't'), (0x1D566, 'M', u'u'), (0x1D567, 'M', u'v'), (0x1D568, 'M', u'w'), (0x1D569, 'M', u'x'), (0x1D56A, 'M', u'y'), (0x1D56B, 'M', u'z'), (0x1D56C, 'M', u'a'), (0x1D56D, 'M', u'b'), (0x1D56E, 'M', u'c'), (0x1D56F, 'M', u'd'), (0x1D570, 'M', u'e'), (0x1D571, 'M', u'f'), (0x1D572, 'M', u'g'), (0x1D573, 'M', u'h'), (0x1D574, 'M', u'i'), (0x1D575, 'M', u'j'), (0x1D576, 'M', u'k'), (0x1D577, 'M', u'l'), (0x1D578, 'M', u'm'), (0x1D579, 'M', u'n'), (0x1D57A, 'M', u'o'), (0x1D57B, 'M', u'p'), (0x1D57C, 'M', u'q'), (0x1D57D, 'M', u'r'), (0x1D57E, 'M', u's'), (0x1D57F, 'M', u't'), (0x1D580, 'M', u'u'), (0x1D581, 'M', u'v'), (0x1D582, 'M', u'w'), (0x1D583, 'M', u'x'), (0x1D584, 'M', u'y'), (0x1D585, 'M', u'z'), (0x1D586, 'M', u'a'), (0x1D587, 'M', u'b'), (0x1D588, 'M', u'c'), (0x1D589, 'M', u'd'), (0x1D58A, 'M', u'e'), (0x1D58B, 'M', u'f'), (0x1D58C, 'M', u'g'), (0x1D58D, 'M', u'h'), (0x1D58E, 'M', u'i'), ] def _seg_62(): return [ (0x1D58F, 'M', u'j'), (0x1D590, 'M', u'k'), (0x1D591, 'M', u'l'), (0x1D592, 'M', u'm'), (0x1D593, 'M', u'n'), (0x1D594, 'M', u'o'), (0x1D595, 'M', u'p'), (0x1D596, 'M', u'q'), (0x1D597, 'M', u'r'), (0x1D598, 'M', u's'), (0x1D599, 'M', u't'), (0x1D59A, 'M', u'u'), (0x1D59B, 'M', u'v'), (0x1D59C, 'M', u'w'), (0x1D59D, 'M', u'x'), (0x1D59E, 'M', u'y'), (0x1D59F, 'M', u'z'), (0x1D5A0, 'M', u'a'), (0x1D5A1, 'M', u'b'), (0x1D5A2, 'M', u'c'), (0x1D5A3, 'M', u'd'), (0x1D5A4, 'M', u'e'), (0x1D5A5, 'M', u'f'), (0x1D5A6, 'M', u'g'), (0x1D5A7, 'M', u'h'), (0x1D5A8, 'M', u'i'), (0x1D5A9, 'M', u'j'), (0x1D5AA, 'M', u'k'), (0x1D5AB, 'M', u'l'), (0x1D5AC, 'M', u'm'), (0x1D5AD, 'M', u'n'), (0x1D5AE, 'M', u'o'), (0x1D5AF, 'M', u'p'), (0x1D5B0, 'M', u'q'), (0x1D5B1, 'M', u'r'), (0x1D5B2, 'M', u's'), (0x1D5B3, 'M', u't'), (0x1D5B4, 'M', u'u'), (0x1D5B5, 'M', u'v'), (0x1D5B6, 'M', u'w'), (0x1D5B7, 'M', u'x'), (0x1D5B8, 'M', u'y'), (0x1D5B9, 'M', u'z'), (0x1D5BA, 'M', u'a'), (0x1D5BB, 'M', u'b'), (0x1D5BC, 'M', u'c'), (0x1D5BD, 'M', u'd'), (0x1D5BE, 'M', u'e'), (0x1D5BF, 'M', u'f'), (0x1D5C0, 'M', u'g'), (0x1D5C1, 'M', u'h'), (0x1D5C2, 'M', u'i'), (0x1D5C3, 'M', u'j'), (0x1D5C4, 'M', u'k'), (0x1D5C5, 'M', u'l'), (0x1D5C6, 'M', u'm'), (0x1D5C7, 'M', u'n'), (0x1D5C8, 'M', u'o'), (0x1D5C9, 'M', u'p'), (0x1D5CA, 'M', u'q'), (0x1D5CB, 'M', u'r'), (0x1D5CC, 'M', u's'), (0x1D5CD, 'M', u't'), (0x1D5CE, 'M', u'u'), (0x1D5CF, 'M', u'v'), (0x1D5D0, 'M', u'w'), (0x1D5D1, 'M', u'x'), (0x1D5D2, 'M', u'y'), (0x1D5D3, 'M', u'z'), (0x1D5D4, 'M', u'a'), (0x1D5D5, 'M', u'b'), (0x1D5D6, 'M', u'c'), (0x1D5D7, 'M', u'd'), (0x1D5D8, 'M', u'e'), (0x1D5D9, 'M', u'f'), (0x1D5DA, 'M', u'g'), (0x1D5DB, 'M', u'h'), (0x1D5DC, 'M', u'i'), (0x1D5DD, 'M', u'j'), (0x1D5DE, 'M', u'k'), (0x1D5DF, 'M', u'l'), (0x1D5E0, 'M', u'm'), (0x1D5E1, 'M', u'n'), (0x1D5E2, 'M', u'o'), (0x1D5E3, 'M', u'p'), (0x1D5E4, 'M', u'q'), (0x1D5E5, 'M', u'r'), (0x1D5E6, 'M', u's'), (0x1D5E7, 'M', u't'), (0x1D5E8, 'M', u'u'), (0x1D5E9, 'M', u'v'), (0x1D5EA, 'M', u'w'), (0x1D5EB, 'M', u'x'), (0x1D5EC, 'M', u'y'), (0x1D5ED, 'M', u'z'), (0x1D5EE, 'M', u'a'), (0x1D5EF, 'M', u'b'), (0x1D5F0, 'M', u'c'), (0x1D5F1, 'M', u'd'), (0x1D5F2, 'M', u'e'), ] def _seg_63(): return [ (0x1D5F3, 'M', u'f'), (0x1D5F4, 'M', u'g'), (0x1D5F5, 'M', u'h'), (0x1D5F6, 'M', u'i'), (0x1D5F7, 'M', u'j'), (0x1D5F8, 'M', u'k'), (0x1D5F9, 'M', u'l'), (0x1D5FA, 'M', u'm'), (0x1D5FB, 'M', u'n'), (0x1D5FC, 'M', u'o'), (0x1D5FD, 'M', u'p'), (0x1D5FE, 'M', u'q'), (0x1D5FF, 'M', u'r'), (0x1D600, 'M', u's'), (0x1D601, 'M', u't'), (0x1D602, 'M', u'u'), (0x1D603, 'M', u'v'), (0x1D604, 'M', u'w'), (0x1D605, 'M', u'x'), (0x1D606, 'M', u'y'), (0x1D607, 'M', u'z'), (0x1D608, 'M', u'a'), (0x1D609, 'M', u'b'), (0x1D60A, 'M', u'c'), (0x1D60B, 'M', u'd'), (0x1D60C, 'M', u'e'), (0x1D60D, 'M', u'f'), (0x1D60E, 'M', u'g'), (0x1D60F, 'M', u'h'), (0x1D610, 'M', u'i'), (0x1D611, 'M', u'j'), (0x1D612, 'M', u'k'), (0x1D613, 'M', u'l'), (0x1D614, 'M', u'm'), (0x1D615, 'M', u'n'), (0x1D616, 'M', u'o'), (0x1D617, 'M', u'p'), (0x1D618, 'M', u'q'), (0x1D619, 'M', u'r'), (0x1D61A, 'M', u's'), (0x1D61B, 'M', u't'), (0x1D61C, 'M', u'u'), (0x1D61D, 'M', u'v'), (0x1D61E, 'M', u'w'), (0x1D61F, 'M', u'x'), (0x1D620, 'M', u'y'), (0x1D621, 'M', u'z'), (0x1D622, 'M', u'a'), (0x1D623, 'M', u'b'), (0x1D624, 'M', u'c'), (0x1D625, 'M', u'd'), (0x1D626, 'M', u'e'), (0x1D627, 'M', u'f'), (0x1D628, 'M', u'g'), (0x1D629, 'M', u'h'), (0x1D62A, 'M', u'i'), (0x1D62B, 'M', u'j'), (0x1D62C, 'M', u'k'), (0x1D62D, 'M', u'l'), (0x1D62E, 'M', u'm'), (0x1D62F, 'M', u'n'), (0x1D630, 'M', u'o'), (0x1D631, 'M', u'p'), (0x1D632, 'M', u'q'), (0x1D633, 'M', u'r'), (0x1D634, 'M', u's'), (0x1D635, 'M', u't'), (0x1D636, 'M', u'u'), (0x1D637, 'M', u'v'), (0x1D638, 'M', u'w'), (0x1D639, 'M', u'x'), (0x1D63A, 'M', u'y'), (0x1D63B, 'M', u'z'), (0x1D63C, 'M', u'a'), (0x1D63D, 'M', u'b'), (0x1D63E, 'M', u'c'), (0x1D63F, 'M', u'd'), (0x1D640, 'M', u'e'), (0x1D641, 'M', u'f'), (0x1D642, 'M', u'g'), (0x1D643, 'M', u'h'), (0x1D644, 'M', u'i'), (0x1D645, 'M', u'j'), (0x1D646, 'M', u'k'), (0x1D647, 'M', u'l'), (0x1D648, 'M', u'm'), (0x1D649, 'M', u'n'), (0x1D64A, 'M', u'o'), (0x1D64B, 'M', u'p'), (0x1D64C, 'M', u'q'), (0x1D64D, 'M', u'r'), (0x1D64E, 'M', u's'), (0x1D64F, 'M', u't'), (0x1D650, 'M', u'u'), (0x1D651, 'M', u'v'), (0x1D652, 'M', u'w'), (0x1D653, 'M', u'x'), (0x1D654, 'M', u'y'), (0x1D655, 'M', u'z'), (0x1D656, 'M', u'a'), ] def _seg_64(): return [ (0x1D657, 'M', u'b'), (0x1D658, 'M', u'c'), (0x1D659, 'M', u'd'), (0x1D65A, 'M', u'e'), (0x1D65B, 'M', u'f'), (0x1D65C, 'M', u'g'), (0x1D65D, 'M', u'h'), (0x1D65E, 'M', u'i'), (0x1D65F, 'M', u'j'), (0x1D660, 'M', u'k'), (0x1D661, 'M', u'l'), (0x1D662, 'M', u'm'), (0x1D663, 'M', u'n'), (0x1D664, 'M', u'o'), (0x1D665, 'M', u'p'), (0x1D666, 'M', u'q'), (0x1D667, 'M', u'r'), (0x1D668, 'M', u's'), (0x1D669, 'M', u't'), (0x1D66A, 'M', u'u'), (0x1D66B, 'M', u'v'), (0x1D66C, 'M', u'w'), (0x1D66D, 'M', u'x'), (0x1D66E, 'M', u'y'), (0x1D66F, 'M', u'z'), (0x1D670, 'M', u'a'), (0x1D671, 'M', u'b'), (0x1D672, 'M', u'c'), (0x1D673, 'M', u'd'), (0x1D674, 'M', u'e'), (0x1D675, 'M', u'f'), (0x1D676, 'M', u'g'), (0x1D677, 'M', u'h'), (0x1D678, 'M', u'i'), (0x1D679, 'M', u'j'), (0x1D67A, 'M', u'k'), (0x1D67B, 'M', u'l'), (0x1D67C, 'M', u'm'), (0x1D67D, 'M', u'n'), (0x1D67E, 'M', u'o'), (0x1D67F, 'M', u'p'), (0x1D680, 'M', u'q'), (0x1D681, 'M', u'r'), (0x1D682, 'M', u's'), (0x1D683, 'M', u't'), (0x1D684, 'M', u'u'), (0x1D685, 'M', u'v'), (0x1D686, 'M', u'w'), (0x1D687, 'M', u'x'), (0x1D688, 'M', u'y'), (0x1D689, 'M', u'z'), (0x1D68A, 'M', u'a'), (0x1D68B, 'M', u'b'), (0x1D68C, 'M', u'c'), (0x1D68D, 'M', u'd'), (0x1D68E, 'M', u'e'), (0x1D68F, 'M', u'f'), (0x1D690, 'M', u'g'), (0x1D691, 'M', u'h'), (0x1D692, 'M', u'i'), (0x1D693, 'M', u'j'), (0x1D694, 'M', u'k'), (0x1D695, 'M', u'l'), (0x1D696, 'M', u'm'), (0x1D697, 'M', u'n'), (0x1D698, 'M', u'o'), (0x1D699, 'M', u'p'), (0x1D69A, 'M', u'q'), (0x1D69B, 'M', u'r'), (0x1D69C, 'M', u's'), (0x1D69D, 'M', u't'), (0x1D69E, 'M', u'u'), (0x1D69F, 'M', u'v'), (0x1D6A0, 'M', u'w'), (0x1D6A1, 'M', u'x'), (0x1D6A2, 'M', u'y'), (0x1D6A3, 'M', u'z'), (0x1D6A4, 'M', u'ı'), (0x1D6A5, 'M', u'ȷ'), (0x1D6A6, 'X'), (0x1D6A8, 'M', u'α'), (0x1D6A9, 'M', u'β'), (0x1D6AA, 'M', u'γ'), (0x1D6AB, 'M', u'δ'), (0x1D6AC, 'M', u'ε'), (0x1D6AD, 'M', u'ζ'), (0x1D6AE, 'M', u'η'), (0x1D6AF, 'M', u'θ'), (0x1D6B0, 'M', u'ι'), (0x1D6B1, 'M', u'κ'), (0x1D6B2, 'M', u'λ'), (0x1D6B3, 'M', u'μ'), (0x1D6B4, 'M', u'ν'), (0x1D6B5, 'M', u'ξ'), (0x1D6B6, 'M', u'ο'), (0x1D6B7, 'M', u'π'), (0x1D6B8, 'M', u'ρ'), (0x1D6B9, 'M', u'θ'), (0x1D6BA, 'M', u'σ'), (0x1D6BB, 'M', u'τ'), ] def _seg_65(): return [ (0x1D6BC, 'M', u'υ'), (0x1D6BD, 'M', u'φ'), (0x1D6BE, 'M', u'χ'), (0x1D6BF, 'M', u'ψ'), (0x1D6C0, 'M', u'ω'), (0x1D6C1, 'M', u'∇'), (0x1D6C2, 'M', u'α'), (0x1D6C3, 'M', u'β'), (0x1D6C4, 'M', u'γ'), (0x1D6C5, 'M', u'δ'), (0x1D6C6, 'M', u'ε'), (0x1D6C7, 'M', u'ζ'), (0x1D6C8, 'M', u'η'), (0x1D6C9, 'M', u'θ'), (0x1D6CA, 'M', u'ι'), (0x1D6CB, 'M', u'κ'), (0x1D6CC, 'M', u'λ'), (0x1D6CD, 'M', u'μ'), (0x1D6CE, 'M', u'ν'), (0x1D6CF, 'M', u'ξ'), (0x1D6D0, 'M', u'ο'), (0x1D6D1, 'M', u'π'), (0x1D6D2, 'M', u'ρ'), (0x1D6D3, 'M', u'σ'), (0x1D6D5, 'M', u'τ'), (0x1D6D6, 'M', u'υ'), (0x1D6D7, 'M', u'φ'), (0x1D6D8, 'M', u'χ'), (0x1D6D9, 'M', u'ψ'), (0x1D6DA, 'M', u'ω'), (0x1D6DB, 'M', u'∂'), (0x1D6DC, 'M', u'ε'), (0x1D6DD, 'M', u'θ'), (0x1D6DE, 'M', u'κ'), (0x1D6DF, 'M', u'φ'), (0x1D6E0, 'M', u'ρ'), (0x1D6E1, 'M', u'π'), (0x1D6E2, 'M', u'α'), (0x1D6E3, 'M', u'β'), (0x1D6E4, 'M', u'γ'), (0x1D6E5, 'M', u'δ'), (0x1D6E6, 'M', u'ε'), (0x1D6E7, 'M', u'ζ'), (0x1D6E8, 'M', u'η'), (0x1D6E9, 'M', u'θ'), (0x1D6EA, 'M', u'ι'), (0x1D6EB, 'M', u'κ'), (0x1D6EC, 'M', u'λ'), (0x1D6ED, 'M', u'μ'), (0x1D6EE, 'M', u'ν'), (0x1D6EF, 'M', u'ξ'), (0x1D6F0, 'M', u'ο'), (0x1D6F1, 'M', u'π'), (0x1D6F2, 'M', u'ρ'), (0x1D6F3, 'M', u'θ'), (0x1D6F4, 'M', u'σ'), (0x1D6F5, 'M', u'τ'), (0x1D6F6, 'M', u'υ'), (0x1D6F7, 'M', u'φ'), (0x1D6F8, 'M', u'χ'), (0x1D6F9, 'M', u'ψ'), (0x1D6FA, 'M', u'ω'), (0x1D6FB, 'M', u'∇'), (0x1D6FC, 'M', u'α'), (0x1D6FD, 'M', u'β'), (0x1D6FE, 'M', u'γ'), (0x1D6FF, 'M', u'δ'), (0x1D700, 'M', u'ε'), (0x1D701, 'M', u'ζ'), (0x1D702, 'M', u'η'), (0x1D703, 'M', u'θ'), (0x1D704, 'M', u'ι'), (0x1D705, 'M', u'κ'), (0x1D706, 'M', u'λ'), (0x1D707, 'M', u'μ'), (0x1D708, 'M', u'ν'), (0x1D709, 'M', u'ξ'), (0x1D70A, 'M', u'ο'), (0x1D70B, 'M', u'π'), (0x1D70C, 'M', u'ρ'), (0x1D70D, 'M', u'σ'), (0x1D70F, 'M', u'τ'), (0x1D710, 'M', u'υ'), (0x1D711, 'M', u'φ'), (0x1D712, 'M', u'χ'), (0x1D713, 'M', u'ψ'), (0x1D714, 'M', u'ω'), (0x1D715, 'M', u'∂'), (0x1D716, 'M', u'ε'), (0x1D717, 'M', u'θ'), (0x1D718, 'M', u'κ'), (0x1D719, 'M', u'φ'), (0x1D71A, 'M', u'ρ'), (0x1D71B, 'M', u'π'), (0x1D71C, 'M', u'α'), (0x1D71D, 'M', u'β'), (0x1D71E, 'M', u'γ'), (0x1D71F, 'M', u'δ'), (0x1D720, 'M', u'ε'), (0x1D721, 'M', u'ζ'), ] def _seg_66(): return [ (0x1D722, 'M', u'η'), (0x1D723, 'M', u'θ'), (0x1D724, 'M', u'ι'), (0x1D725, 'M', u'κ'), (0x1D726, 'M', u'λ'), (0x1D727, 'M', u'μ'), (0x1D728, 'M', u'ν'), (0x1D729, 'M', u'ξ'), (0x1D72A, 'M', u'ο'), (0x1D72B, 'M', u'π'), (0x1D72C, 'M', u'ρ'), (0x1D72D, 'M', u'θ'), (0x1D72E, 'M', u'σ'), (0x1D72F, 'M', u'τ'), (0x1D730, 'M', u'υ'), (0x1D731, 'M', u'φ'), (0x1D732, 'M', u'χ'), (0x1D733, 'M', u'ψ'), (0x1D734, 'M', u'ω'), (0x1D735, 'M', u'∇'), (0x1D736, 'M', u'α'), (0x1D737, 'M', u'β'), (0x1D738, 'M', u'γ'), (0x1D739, 'M', u'δ'), (0x1D73A, 'M', u'ε'), (0x1D73B, 'M', u'ζ'), (0x1D73C, 'M', u'η'), (0x1D73D, 'M', u'θ'), (0x1D73E, 'M', u'ι'), (0x1D73F, 'M', u'κ'), (0x1D740, 'M', u'λ'), (0x1D741, 'M', u'μ'), (0x1D742, 'M', u'ν'), (0x1D743, 'M', u'ξ'), (0x1D744, 'M', u'ο'), (0x1D745, 'M', u'π'), (0x1D746, 'M', u'ρ'), (0x1D747, 'M', u'σ'), (0x1D749, 'M', u'τ'), (0x1D74A, 'M', u'υ'), (0x1D74B, 'M', u'φ'), (0x1D74C, 'M', u'χ'), (0x1D74D, 'M', u'ψ'), (0x1D74E, 'M', u'ω'), (0x1D74F, 'M', u'∂'), (0x1D750, 'M', u'ε'), (0x1D751, 'M', u'θ'), (0x1D752, 'M', u'κ'), (0x1D753, 'M', u'φ'), (0x1D754, 'M', u'ρ'), (0x1D755, 'M', u'π'), (0x1D756, 'M', u'α'), (0x1D757, 'M', u'β'), (0x1D758, 'M', u'γ'), (0x1D759, 'M', u'δ'), (0x1D75A, 'M', u'ε'), (0x1D75B, 'M', u'ζ'), (0x1D75C, 'M', u'η'), (0x1D75D, 'M', u'θ'), (0x1D75E, 'M', u'ι'), (0x1D75F, 'M', u'κ'), (0x1D760, 'M', u'λ'), (0x1D761, 'M', u'μ'), (0x1D762, 'M', u'ν'), (0x1D763, 'M', u'ξ'), (0x1D764, 'M', u'ο'), (0x1D765, 'M', u'π'), (0x1D766, 'M', u'ρ'), (0x1D767, 'M', u'θ'), (0x1D768, 'M', u'σ'), (0x1D769, 'M', u'τ'), (0x1D76A, 'M', u'υ'), (0x1D76B, 'M', u'φ'), (0x1D76C, 'M', u'χ'), (0x1D76D, 'M', u'ψ'), (0x1D76E, 'M', u'ω'), (0x1D76F, 'M', u'∇'), (0x1D770, 'M', u'α'), (0x1D771, 'M', u'β'), (0x1D772, 'M', u'γ'), (0x1D773, 'M', u'δ'), (0x1D774, 'M', u'ε'), (0x1D775, 'M', u'ζ'), (0x1D776, 'M', u'η'), (0x1D777, 'M', u'θ'), (0x1D778, 'M', u'ι'), (0x1D779, 'M', u'κ'), (0x1D77A, 'M', u'λ'), (0x1D77B, 'M', u'μ'), (0x1D77C, 'M', u'ν'), (0x1D77D, 'M', u'ξ'), (0x1D77E, 'M', u'ο'), (0x1D77F, 'M', u'π'), (0x1D780, 'M', u'ρ'), (0x1D781, 'M', u'σ'), (0x1D783, 'M', u'τ'), (0x1D784, 'M', u'υ'), (0x1D785, 'M', u'φ'), (0x1D786, 'M', u'χ'), (0x1D787, 'M', u'ψ'), ] def _seg_67(): return [ (0x1D788, 'M', u'ω'), (0x1D789, 'M', u'∂'), (0x1D78A, 'M', u'ε'), (0x1D78B, 'M', u'θ'), (0x1D78C, 'M', u'κ'), (0x1D78D, 'M', u'φ'), (0x1D78E, 'M', u'ρ'), (0x1D78F, 'M', u'π'), (0x1D790, 'M', u'α'), (0x1D791, 'M', u'β'), (0x1D792, 'M', u'γ'), (0x1D793, 'M', u'δ'), (0x1D794, 'M', u'ε'), (0x1D795, 'M', u'ζ'), (0x1D796, 'M', u'η'), (0x1D797, 'M', u'θ'), (0x1D798, 'M', u'ι'), (0x1D799, 'M', u'κ'), (0x1D79A, 'M', u'λ'), (0x1D79B, 'M', u'μ'), (0x1D79C, 'M', u'ν'), (0x1D79D, 'M', u'ξ'), (0x1D79E, 'M', u'ο'), (0x1D79F, 'M', u'π'), (0x1D7A0, 'M', u'ρ'), (0x1D7A1, 'M', u'θ'), (0x1D7A2, 'M', u'σ'), (0x1D7A3, 'M', u'τ'), (0x1D7A4, 'M', u'υ'), (0x1D7A5, 'M', u'φ'), (0x1D7A6, 'M', u'χ'), (0x1D7A7, 'M', u'ψ'), (0x1D7A8, 'M', u'ω'), (0x1D7A9, 'M', u'∇'), (0x1D7AA, 'M', u'α'), (0x1D7AB, 'M', u'β'), (0x1D7AC, 'M', u'γ'), (0x1D7AD, 'M', u'δ'), (0x1D7AE, 'M', u'ε'), (0x1D7AF, 'M', u'ζ'), (0x1D7B0, 'M', u'η'), (0x1D7B1, 'M', u'θ'), (0x1D7B2, 'M', u'ι'), (0x1D7B3, 'M', u'κ'), (0x1D7B4, 'M', u'λ'), (0x1D7B5, 'M', u'μ'), (0x1D7B6, 'M', u'ν'), (0x1D7B7, 'M', u'ξ'), (0x1D7B8, 'M', u'ο'), (0x1D7B9, 'M', u'π'), (0x1D7BA, 'M', u'ρ'), (0x1D7BB, 'M', u'σ'), (0x1D7BD, 'M', u'τ'), (0x1D7BE, 'M', u'υ'), (0x1D7BF, 'M', u'φ'), (0x1D7C0, 'M', u'χ'), (0x1D7C1, 'M', u'ψ'), (0x1D7C2, 'M', u'ω'), (0x1D7C3, 'M', u'∂'), (0x1D7C4, 'M', u'ε'), (0x1D7C5, 'M', u'θ'), (0x1D7C6, 'M', u'κ'), (0x1D7C7, 'M', u'φ'), (0x1D7C8, 'M', u'ρ'), (0x1D7C9, 'M', u'π'), (0x1D7CA, 'M', u'ϝ'), (0x1D7CC, 'X'), (0x1D7CE, 'M', u'0'), (0x1D7CF, 'M', u'1'), (0x1D7D0, 'M', u'2'), (0x1D7D1, 'M', u'3'), (0x1D7D2, 'M', u'4'), (0x1D7D3, 'M', u'5'), (0x1D7D4, 'M', u'6'), (0x1D7D5, 'M', u'7'), (0x1D7D6, 'M', u'8'), (0x1D7D7, 'M', u'9'), (0x1D7D8, 'M', u'0'), (0x1D7D9, 'M', u'1'), (0x1D7DA, 'M', u'2'), (0x1D7DB, 'M', u'3'), (0x1D7DC, 'M', u'4'), (0x1D7DD, 'M', u'5'), (0x1D7DE, 'M', u'6'), (0x1D7DF, 'M', u'7'), (0x1D7E0, 'M', u'8'), (0x1D7E1, 'M', u'9'), (0x1D7E2, 'M', u'0'), (0x1D7E3, 'M', u'1'), (0x1D7E4, 'M', u'2'), (0x1D7E5, 'M', u'3'), (0x1D7E6, 'M', u'4'), (0x1D7E7, 'M', u'5'), (0x1D7E8, 'M', u'6'), (0x1D7E9, 'M', u'7'), (0x1D7EA, 'M', u'8'), (0x1D7EB, 'M', u'9'), (0x1D7EC, 'M', u'0'), (0x1D7ED, 'M', u'1'), (0x1D7EE, 'M', u'2'), ] def _seg_68(): return [ (0x1D7EF, 'M', u'3'), (0x1D7F0, 'M', u'4'), (0x1D7F1, 'M', u'5'), (0x1D7F2, 'M', u'6'), (0x1D7F3, 'M', u'7'), (0x1D7F4, 'M', u'8'), (0x1D7F5, 'M', u'9'), (0x1D7F6, 'M', u'0'), (0x1D7F7, 'M', u'1'), (0x1D7F8, 'M', u'2'), (0x1D7F9, 'M', u'3'), (0x1D7FA, 'M', u'4'), (0x1D7FB, 'M', u'5'), (0x1D7FC, 'M', u'6'), (0x1D7FD, 'M', u'7'), (0x1D7FE, 'M', u'8'), (0x1D7FF, 'M', u'9'), (0x1D800, 'V'), (0x1DA8C, 'X'), (0x1DA9B, 'V'), (0x1DAA0, 'X'), (0x1DAA1, 'V'), (0x1DAB0, 'X'), (0x1E000, 'V'), (0x1E007, 'X'), (0x1E008, 'V'), (0x1E019, 'X'), (0x1E01B, 'V'), (0x1E022, 'X'), (0x1E023, 'V'), (0x1E025, 'X'), (0x1E026, 'V'), (0x1E02B, 'X'), (0x1E800, 'V'), (0x1E8C5, 'X'), (0x1E8C7, 'V'), (0x1E8D7, 'X'), (0x1E900, 'M', u'𞤢'), (0x1E901, 'M', u'𞤣'), (0x1E902, 'M', u'𞤤'), (0x1E903, 'M', u'𞤥'), (0x1E904, 'M', u'𞤦'), (0x1E905, 'M', u'𞤧'), (0x1E906, 'M', u'𞤨'), (0x1E907, 'M', u'𞤩'), (0x1E908, 'M', u'𞤪'), (0x1E909, 'M', u'𞤫'), (0x1E90A, 'M', u'𞤬'), (0x1E90B, 'M', u'𞤭'), (0x1E90C, 'M', u'𞤮'), (0x1E90D, 'M', u'𞤯'), (0x1E90E, 'M', u'𞤰'), (0x1E90F, 'M', u'𞤱'), (0x1E910, 'M', u'𞤲'), (0x1E911, 'M', u'𞤳'), (0x1E912, 'M', u'𞤴'), (0x1E913, 'M', u'𞤵'), (0x1E914, 'M', u'𞤶'), (0x1E915, 'M', u'𞤷'), (0x1E916, 'M', u'𞤸'), (0x1E917, 'M', u'𞤹'), (0x1E918, 'M', u'𞤺'), (0x1E919, 'M', u'𞤻'), (0x1E91A, 'M', u'𞤼'), (0x1E91B, 'M', u'𞤽'), (0x1E91C, 'M', u'𞤾'), (0x1E91D, 'M', u'𞤿'), (0x1E91E, 'M', u'𞥀'), (0x1E91F, 'M', u'𞥁'), (0x1E920, 'M', u'𞥂'), (0x1E921, 'M', u'𞥃'), (0x1E922, 'V'), (0x1E94B, 'X'), (0x1E950, 'V'), (0x1E95A, 'X'), (0x1E95E, 'V'), (0x1E960, 'X'), (0x1EC71, 'V'), (0x1ECB5, 'X'), (0x1EE00, 'M', u'ا'), (0x1EE01, 'M', u'ب'), (0x1EE02, 'M', u'ج'), (0x1EE03, 'M', u'د'), (0x1EE04, 'X'), (0x1EE05, 'M', u'و'), (0x1EE06, 'M', u'ز'), (0x1EE07, 'M', u'ح'), (0x1EE08, 'M', u'ط'), (0x1EE09, 'M', u'ي'), (0x1EE0A, 'M', u'ك'), (0x1EE0B, 'M', u'ل'), (0x1EE0C, 'M', u'م'), (0x1EE0D, 'M', u'ن'), (0x1EE0E, 'M', u'س'), (0x1EE0F, 'M', u'ع'), (0x1EE10, 'M', u'ف'), (0x1EE11, 'M', u'ص'), (0x1EE12, 'M', u'ق'), (0x1EE13, 'M', u'ر'), (0x1EE14, 'M', u'ش'), ] def _seg_69(): return [ (0x1EE15, 'M', u'ت'), (0x1EE16, 'M', u'ث'), (0x1EE17, 'M', u'خ'), (0x1EE18, 'M', u'ذ'), (0x1EE19, 'M', u'ض'), (0x1EE1A, 'M', u'ظ'), (0x1EE1B, 'M', u'غ'), (0x1EE1C, 'M', u'ٮ'), (0x1EE1D, 'M', u'ں'), (0x1EE1E, 'M', u'ڡ'), (0x1EE1F, 'M', u'ٯ'), (0x1EE20, 'X'), (0x1EE21, 'M', u'ب'), (0x1EE22, 'M', u'ج'), (0x1EE23, 'X'), (0x1EE24, 'M', u'ه'), (0x1EE25, 'X'), (0x1EE27, 'M', u'ح'), (0x1EE28, 'X'), (0x1EE29, 'M', u'ي'), (0x1EE2A, 'M', u'ك'), (0x1EE2B, 'M', u'ل'), (0x1EE2C, 'M', u'م'), (0x1EE2D, 'M', u'ن'), (0x1EE2E, 'M', u'س'), (0x1EE2F, 'M', u'ع'), (0x1EE30, 'M', u'ف'), (0x1EE31, 'M', u'ص'), (0x1EE32, 'M', u'ق'), (0x1EE33, 'X'), (0x1EE34, 'M', u'ش'), (0x1EE35, 'M', u'ت'), (0x1EE36, 'M', u'ث'), (0x1EE37, 'M', u'خ'), (0x1EE38, 'X'), (0x1EE39, 'M', u'ض'), (0x1EE3A, 'X'), (0x1EE3B, 'M', u'غ'), (0x1EE3C, 'X'), (0x1EE42, 'M', u'ج'), (0x1EE43, 'X'), (0x1EE47, 'M', u'ح'), (0x1EE48, 'X'), (0x1EE49, 'M', u'ي'), (0x1EE4A, 'X'), (0x1EE4B, 'M', u'ل'), (0x1EE4C, 'X'), (0x1EE4D, 'M', u'ن'), (0x1EE4E, 'M', u'س'), (0x1EE4F, 'M', u'ع'), (0x1EE50, 'X'), (0x1EE51, 'M', u'ص'), (0x1EE52, 'M', u'ق'), (0x1EE53, 'X'), (0x1EE54, 'M', u'ش'), (0x1EE55, 'X'), (0x1EE57, 'M', u'خ'), (0x1EE58, 'X'), (0x1EE59, 'M', u'ض'), (0x1EE5A, 'X'), (0x1EE5B, 'M', u'غ'), (0x1EE5C, 'X'), (0x1EE5D, 'M', u'ں'), (0x1EE5E, 'X'), (0x1EE5F, 'M', u'ٯ'), (0x1EE60, 'X'), (0x1EE61, 'M', u'ب'), (0x1EE62, 'M', u'ج'), (0x1EE63, 'X'), (0x1EE64, 'M', u'ه'), (0x1EE65, 'X'), (0x1EE67, 'M', u'ح'), (0x1EE68, 'M', u'ط'), (0x1EE69, 'M', u'ي'), (0x1EE6A, 'M', u'ك'), (0x1EE6B, 'X'), (0x1EE6C, 'M', u'م'), (0x1EE6D, 'M', u'ن'), (0x1EE6E, 'M', u'س'), (0x1EE6F, 'M', u'ع'), (0x1EE70, 'M', u'ف'), (0x1EE71, 'M', u'ص'), (0x1EE72, 'M', u'ق'), (0x1EE73, 'X'), (0x1EE74, 'M', u'ش'), (0x1EE75, 'M', u'ت'), (0x1EE76, 'M', u'ث'), (0x1EE77, 'M', u'خ'), (0x1EE78, 'X'), (0x1EE79, 'M', u'ض'), (0x1EE7A, 'M', u'ظ'), (0x1EE7B, 'M', u'غ'), (0x1EE7C, 'M', u'ٮ'), (0x1EE7D, 'X'), (0x1EE7E, 'M', u'ڡ'), (0x1EE7F, 'X'), (0x1EE80, 'M', u'ا'), (0x1EE81, 'M', u'ب'), (0x1EE82, 'M', u'ج'), (0x1EE83, 'M', u'د'), ] def _seg_70(): return [ (0x1EE84, 'M', u'ه'), (0x1EE85, 'M', u'و'), (0x1EE86, 'M', u'ز'), (0x1EE87, 'M', u'ح'), (0x1EE88, 'M', u'ط'), (0x1EE89, 'M', u'ي'), (0x1EE8A, 'X'), (0x1EE8B, 'M', u'ل'), (0x1EE8C, 'M', u'م'), (0x1EE8D, 'M', u'ن'), (0x1EE8E, 'M', u'س'), (0x1EE8F, 'M', u'ع'), (0x1EE90, 'M', u'ف'), (0x1EE91, 'M', u'ص'), (0x1EE92, 'M', u'ق'), (0x1EE93, 'M', u'ر'), (0x1EE94, 'M', u'ش'), (0x1EE95, 'M', u'ت'), (0x1EE96, 'M', u'ث'), (0x1EE97, 'M', u'خ'), (0x1EE98, 'M', u'ذ'), (0x1EE99, 'M', u'ض'), (0x1EE9A, 'M', u'ظ'), (0x1EE9B, 'M', u'غ'), (0x1EE9C, 'X'), (0x1EEA1, 'M', u'ب'), (0x1EEA2, 'M', u'ج'), (0x1EEA3, 'M', u'د'), (0x1EEA4, 'X'), (0x1EEA5, 'M', u'و'), (0x1EEA6, 'M', u'ز'), (0x1EEA7, 'M', u'ح'), (0x1EEA8, 'M', u'ط'), (0x1EEA9, 'M', u'ي'), (0x1EEAA, 'X'), (0x1EEAB, 'M', u'ل'), (0x1EEAC, 'M', u'م'), (0x1EEAD, 'M', u'ن'), (0x1EEAE, 'M', u'س'), (0x1EEAF, 'M', u'ع'), (0x1EEB0, 'M', u'ف'), (0x1EEB1, 'M', u'ص'), (0x1EEB2, 'M', u'ق'), (0x1EEB3, 'M', u'ر'), (0x1EEB4, 'M', u'ش'), (0x1EEB5, 'M', u'ت'), (0x1EEB6, 'M', u'ث'), (0x1EEB7, 'M', u'خ'), (0x1EEB8, 'M', u'ذ'), (0x1EEB9, 'M', u'ض'), (0x1EEBA, 'M', u'ظ'), (0x1EEBB, 'M', u'غ'), (0x1EEBC, 'X'), (0x1EEF0, 'V'), (0x1EEF2, 'X'), (0x1F000, 'V'), (0x1F02C, 'X'), (0x1F030, 'V'), (0x1F094, 'X'), (0x1F0A0, 'V'), (0x1F0AF, 'X'), (0x1F0B1, 'V'), (0x1F0C0, 'X'), (0x1F0C1, 'V'), (0x1F0D0, 'X'), (0x1F0D1, 'V'), (0x1F0F6, 'X'), (0x1F101, '3', u'0,'), (0x1F102, '3', u'1,'), (0x1F103, '3', u'2,'), (0x1F104, '3', u'3,'), (0x1F105, '3', u'4,'), (0x1F106, '3', u'5,'), (0x1F107, '3', u'6,'), (0x1F108, '3', u'7,'), (0x1F109, '3', u'8,'), (0x1F10A, '3', u'9,'), (0x1F10B, 'V'), (0x1F10D, 'X'), (0x1F110, '3', u'(a)'), (0x1F111, '3', u'(b)'), (0x1F112, '3', u'(c)'), (0x1F113, '3', u'(d)'), (0x1F114, '3', u'(e)'), (0x1F115, '3', u'(f)'), (0x1F116, '3', u'(g)'), (0x1F117, '3', u'(h)'), (0x1F118, '3', u'(i)'), (0x1F119, '3', u'(j)'), (0x1F11A, '3', u'(k)'), (0x1F11B, '3', u'(l)'), (0x1F11C, '3', u'(m)'), (0x1F11D, '3', u'(n)'), (0x1F11E, '3', u'(o)'), (0x1F11F, '3', u'(p)'), (0x1F120, '3', u'(q)'), (0x1F121, '3', u'(r)'), (0x1F122, '3', u'(s)'), (0x1F123, '3', u'(t)'), (0x1F124, '3', u'(u)'), ] def _seg_71(): return [ (0x1F125, '3', u'(v)'), (0x1F126, '3', u'(w)'), (0x1F127, '3', u'(x)'), (0x1F128, '3', u'(y)'), (0x1F129, '3', u'(z)'), (0x1F12A, 'M', u'〔s〕'), (0x1F12B, 'M', u'c'), (0x1F12C, 'M', u'r'), (0x1F12D, 'M', u'cd'), (0x1F12E, 'M', u'wz'), (0x1F12F, 'V'), (0x1F130, 'M', u'a'), (0x1F131, 'M', u'b'), (0x1F132, 'M', u'c'), (0x1F133, 'M', u'd'), (0x1F134, 'M', u'e'), (0x1F135, 'M', u'f'), (0x1F136, 'M', u'g'), (0x1F137, 'M', u'h'), (0x1F138, 'M', u'i'), (0x1F139, 'M', u'j'), (0x1F13A, 'M', u'k'), (0x1F13B, 'M', u'l'), (0x1F13C, 'M', u'm'), (0x1F13D, 'M', u'n'), (0x1F13E, 'M', u'o'), (0x1F13F, 'M', u'p'), (0x1F140, 'M', u'q'), (0x1F141, 'M', u'r'), (0x1F142, 'M', u's'), (0x1F143, 'M', u't'), (0x1F144, 'M', u'u'), (0x1F145, 'M', u'v'), (0x1F146, 'M', u'w'), (0x1F147, 'M', u'x'), (0x1F148, 'M', u'y'), (0x1F149, 'M', u'z'), (0x1F14A, 'M', u'hv'), (0x1F14B, 'M', u'mv'), (0x1F14C, 'M', u'sd'), (0x1F14D, 'M', u'ss'), (0x1F14E, 'M', u'ppv'), (0x1F14F, 'M', u'wc'), (0x1F150, 'V'), (0x1F16A, 'M', u'mc'), (0x1F16B, 'M', u'md'), (0x1F16C, 'X'), (0x1F170, 'V'), (0x1F190, 'M', u'dj'), (0x1F191, 'V'), (0x1F1AD, 'X'), (0x1F1E6, 'V'), (0x1F200, 'M', u'ほか'), (0x1F201, 'M', u'ココ'), (0x1F202, 'M', u'サ'), (0x1F203, 'X'), (0x1F210, 'M', u'手'), (0x1F211, 'M', u'字'), (0x1F212, 'M', u'双'), (0x1F213, 'M', u'デ'), (0x1F214, 'M', u'二'), (0x1F215, 'M', u'多'), (0x1F216, 'M', u'解'), (0x1F217, 'M', u'天'), (0x1F218, 'M', u'交'), (0x1F219, 'M', u'映'), (0x1F21A, 'M', u'無'), (0x1F21B, 'M', u'料'), (0x1F21C, 'M', u'前'), (0x1F21D, 'M', u'後'), (0x1F21E, 'M', u'再'), (0x1F21F, 'M', u'新'), (0x1F220, 'M', u'初'), (0x1F221, 'M', u'終'), (0x1F222, 'M', u'生'), (0x1F223, 'M', u'販'), (0x1F224, 'M', u'声'), (0x1F225, 'M', u'吹'), (0x1F226, 'M', u'演'), (0x1F227, 'M', u'投'), (0x1F228, 'M', u'捕'), (0x1F229, 'M', u'一'), (0x1F22A, 'M', u'三'), (0x1F22B, 'M', u'遊'), (0x1F22C, 'M', u'左'), (0x1F22D, 'M', u'中'), (0x1F22E, 'M', u'右'), (0x1F22F, 'M', u'指'), (0x1F230, 'M', u'走'), (0x1F231, 'M', u'打'), (0x1F232, 'M', u'禁'), (0x1F233, 'M', u'空'), (0x1F234, 'M', u'合'), (0x1F235, 'M', u'満'), (0x1F236, 'M', u'有'), (0x1F237, 'M', u'月'), (0x1F238, 'M', u'申'), (0x1F239, 'M', u'割'), (0x1F23A, 'M', u'営'), (0x1F23B, 'M', u'配'), ] def _seg_72(): return [ (0x1F23C, 'X'), (0x1F240, 'M', u'〔本〕'), (0x1F241, 'M', u'〔三〕'), (0x1F242, 'M', u'〔二〕'), (0x1F243, 'M', u'〔安〕'), (0x1F244, 'M', u'〔点〕'), (0x1F245, 'M', u'〔打〕'), (0x1F246, 'M', u'〔盗〕'), (0x1F247, 'M', u'〔勝〕'), (0x1F248, 'M', u'〔敗〕'), (0x1F249, 'X'), (0x1F250, 'M', u'得'), (0x1F251, 'M', u'可'), (0x1F252, 'X'), (0x1F260, 'V'), (0x1F266, 'X'), (0x1F300, 'V'), (0x1F6D5, 'X'), (0x1F6E0, 'V'), (0x1F6ED, 'X'), (0x1F6F0, 'V'), (0x1F6FA, 'X'), (0x1F700, 'V'), (0x1F774, 'X'), (0x1F780, 'V'), (0x1F7D9, 'X'), (0x1F800, 'V'), (0x1F80C, 'X'), (0x1F810, 'V'), (0x1F848, 'X'), (0x1F850, 'V'), (0x1F85A, 'X'), (0x1F860, 'V'), (0x1F888, 'X'), (0x1F890, 'V'), (0x1F8AE, 'X'), (0x1F900, 'V'), (0x1F90C, 'X'), (0x1F910, 'V'), (0x1F93F, 'X'), (0x1F940, 'V'), (0x1F971, 'X'), (0x1F973, 'V'), (0x1F977, 'X'), (0x1F97A, 'V'), (0x1F97B, 'X'), (0x1F97C, 'V'), (0x1F9A3, 'X'), (0x1F9B0, 'V'), (0x1F9BA, 'X'), (0x1F9C0, 'V'), (0x1F9C3, 'X'), (0x1F9D0, 'V'), (0x1FA00, 'X'), (0x1FA60, 'V'), (0x1FA6E, 'X'), (0x20000, 'V'), (0x2A6D7, 'X'), (0x2A700, 'V'), (0x2B735, 'X'), (0x2B740, 'V'), (0x2B81E, 'X'), (0x2B820, 'V'), (0x2CEA2, 'X'), (0x2CEB0, 'V'), (0x2EBE1, 'X'), (0x2F800, 'M', u'丽'), (0x2F801, 'M', u'丸'), (0x2F802, 'M', u'乁'), (0x2F803, 'M', u'𠄢'), (0x2F804, 'M', u'你'), (0x2F805, 'M', u'侮'), (0x2F806, 'M', u'侻'), (0x2F807, 'M', u'倂'), (0x2F808, 'M', u'偺'), (0x2F809, 'M', u'備'), (0x2F80A, 'M', u'僧'), (0x2F80B, 'M', u'像'), (0x2F80C, 'M', u'㒞'), (0x2F80D, 'M', u'𠘺'), (0x2F80E, 'M', u'免'), (0x2F80F, 'M', u'兔'), (0x2F810, 'M', u'兤'), (0x2F811, 'M', u'具'), (0x2F812, 'M', u'𠔜'), (0x2F813, 'M', u'㒹'), (0x2F814, 'M', u'內'), (0x2F815, 'M', u'再'), (0x2F816, 'M', u'𠕋'), (0x2F817, 'M', u'冗'), (0x2F818, 'M', u'冤'), (0x2F819, 'M', u'仌'), (0x2F81A, 'M', u'冬'), (0x2F81B, 'M', u'况'), (0x2F81C, 'M', u'𩇟'), (0x2F81D, 'M', u'凵'), (0x2F81E, 'M', u'刃'), (0x2F81F, 'M', u'㓟'), (0x2F820, 'M', u'刻'), (0x2F821, 'M', u'剆'), ] def _seg_73(): return [ (0x2F822, 'M', u'割'), (0x2F823, 'M', u'剷'), (0x2F824, 'M', u'㔕'), (0x2F825, 'M', u'勇'), (0x2F826, 'M', u'勉'), (0x2F827, 'M', u'勤'), (0x2F828, 'M', u'勺'), (0x2F829, 'M', u'包'), (0x2F82A, 'M', u'匆'), (0x2F82B, 'M', u'北'), (0x2F82C, 'M', u'卉'), (0x2F82D, 'M', u'卑'), (0x2F82E, 'M', u'博'), (0x2F82F, 'M', u'即'), (0x2F830, 'M', u'卽'), (0x2F831, 'M', u'卿'), (0x2F834, 'M', u'𠨬'), (0x2F835, 'M', u'灰'), (0x2F836, 'M', u'及'), (0x2F837, 'M', u'叟'), (0x2F838, 'M', u'𠭣'), (0x2F839, 'M', u'叫'), (0x2F83A, 'M', u'叱'), (0x2F83B, 'M', u'吆'), (0x2F83C, 'M', u'咞'), (0x2F83D, 'M', u'吸'), (0x2F83E, 'M', u'呈'), (0x2F83F, 'M', u'周'), (0x2F840, 'M', u'咢'), (0x2F841, 'M', u'哶'), (0x2F842, 'M', u'唐'), (0x2F843, 'M', u'啓'), (0x2F844, 'M', u'啣'), (0x2F845, 'M', u'善'), (0x2F847, 'M', u'喙'), (0x2F848, 'M', u'喫'), (0x2F849, 'M', u'喳'), (0x2F84A, 'M', u'嗂'), (0x2F84B, 'M', u'圖'), (0x2F84C, 'M', u'嘆'), (0x2F84D, 'M', u'圗'), (0x2F84E, 'M', u'噑'), (0x2F84F, 'M', u'噴'), (0x2F850, 'M', u'切'), (0x2F851, 'M', u'壮'), (0x2F852, 'M', u'城'), (0x2F853, 'M', u'埴'), (0x2F854, 'M', u'堍'), (0x2F855, 'M', u'型'), (0x2F856, 'M', u'堲'), (0x2F857, 'M', u'報'), (0x2F858, 'M', u'墬'), (0x2F859, 'M', u'𡓤'), (0x2F85A, 'M', u'売'), (0x2F85B, 'M', u'壷'), (0x2F85C, 'M', u'夆'), (0x2F85D, 'M', u'多'), (0x2F85E, 'M', u'夢'), (0x2F85F, 'M', u'奢'), (0x2F860, 'M', u'𡚨'), (0x2F861, 'M', u'𡛪'), (0x2F862, 'M', u'姬'), (0x2F863, 'M', u'娛'), (0x2F864, 'M', u'娧'), (0x2F865, 'M', u'姘'), (0x2F866, 'M', u'婦'), (0x2F867, 'M', u'㛮'), (0x2F868, 'X'), (0x2F869, 'M', u'嬈'), (0x2F86A, 'M', u'嬾'), (0x2F86C, 'M', u'𡧈'), (0x2F86D, 'M', u'寃'), (0x2F86E, 'M', u'寘'), (0x2F86F, 'M', u'寧'), (0x2F870, 'M', u'寳'), (0x2F871, 'M', u'𡬘'), (0x2F872, 'M', u'寿'), (0x2F873, 'M', u'将'), (0x2F874, 'X'), (0x2F875, 'M', u'尢'), (0x2F876, 'M', u'㞁'), (0x2F877, 'M', u'屠'), (0x2F878, 'M', u'屮'), (0x2F879, 'M', u'峀'), (0x2F87A, 'M', u'岍'), (0x2F87B, 'M', u'𡷤'), (0x2F87C, 'M', u'嵃'), (0x2F87D, 'M', u'𡷦'), (0x2F87E, 'M', u'嵮'), (0x2F87F, 'M', u'嵫'), (0x2F880, 'M', u'嵼'), (0x2F881, 'M', u'巡'), (0x2F882, 'M', u'巢'), (0x2F883, 'M', u'㠯'), (0x2F884, 'M', u'巽'), (0x2F885, 'M', u'帨'), (0x2F886, 'M', u'帽'), (0x2F887, 'M', u'幩'), (0x2F888, 'M', u'㡢'), (0x2F889, 'M', u'𢆃'), ] def _seg_74(): return [ (0x2F88A, 'M', u'㡼'), (0x2F88B, 'M', u'庰'), (0x2F88C, 'M', u'庳'), (0x2F88D, 'M', u'庶'), (0x2F88E, 'M', u'廊'), (0x2F88F, 'M', u'𪎒'), (0x2F890, 'M', u'廾'), (0x2F891, 'M', u'𢌱'), (0x2F893, 'M', u'舁'), (0x2F894, 'M', u'弢'), (0x2F896, 'M', u'㣇'), (0x2F897, 'M', u'𣊸'), (0x2F898, 'M', u'𦇚'), (0x2F899, 'M', u'形'), (0x2F89A, 'M', u'彫'), (0x2F89B, 'M', u'㣣'), (0x2F89C, 'M', u'徚'), (0x2F89D, 'M', u'忍'), (0x2F89E, 'M', u'志'), (0x2F89F, 'M', u'忹'), (0x2F8A0, 'M', u'悁'), (0x2F8A1, 'M', u'㤺'), (0x2F8A2, 'M', u'㤜'), (0x2F8A3, 'M', u'悔'), (0x2F8A4, 'M', u'𢛔'), (0x2F8A5, 'M', u'惇'), (0x2F8A6, 'M', u'慈'), (0x2F8A7, 'M', u'慌'), (0x2F8A8, 'M', u'慎'), (0x2F8A9, 'M', u'慌'), (0x2F8AA, 'M', u'慺'), (0x2F8AB, 'M', u'憎'), (0x2F8AC, 'M', u'憲'), (0x2F8AD, 'M', u'憤'), (0x2F8AE, 'M', u'憯'), (0x2F8AF, 'M', u'懞'), (0x2F8B0, 'M', u'懲'), (0x2F8B1, 'M', u'懶'), (0x2F8B2, 'M', u'成'), (0x2F8B3, 'M', u'戛'), (0x2F8B4, 'M', u'扝'), (0x2F8B5, 'M', u'抱'), (0x2F8B6, 'M', u'拔'), (0x2F8B7, 'M', u'捐'), (0x2F8B8, 'M', u'𢬌'), (0x2F8B9, 'M', u'挽'), (0x2F8BA, 'M', u'拼'), (0x2F8BB, 'M', u'捨'), (0x2F8BC, 'M', u'掃'), (0x2F8BD, 'M', u'揤'), (0x2F8BE, 'M', u'𢯱'), (0x2F8BF, 'M', u'搢'), (0x2F8C0, 'M', u'揅'), (0x2F8C1, 'M', u'掩'), (0x2F8C2, 'M', u'㨮'), (0x2F8C3, 'M', u'摩'), (0x2F8C4, 'M', u'摾'), (0x2F8C5, 'M', u'撝'), (0x2F8C6, 'M', u'摷'), (0x2F8C7, 'M', u'㩬'), (0x2F8C8, 'M', u'敏'), (0x2F8C9, 'M', u'敬'), (0x2F8CA, 'M', u'𣀊'), (0x2F8CB, 'M', u'旣'), (0x2F8CC, 'M', u'書'), (0x2F8CD, 'M', u'晉'), (0x2F8CE, 'M', u'㬙'), (0x2F8CF, 'M', u'暑'), (0x2F8D0, 'M', u'㬈'), (0x2F8D1, 'M', u'㫤'), (0x2F8D2, 'M', u'冒'), (0x2F8D3, 'M', u'冕'), (0x2F8D4, 'M', u'最'), (0x2F8D5, 'M', u'暜'), (0x2F8D6, 'M', u'肭'), (0x2F8D7, 'M', u'䏙'), (0x2F8D8, 'M', u'朗'), (0x2F8D9, 'M', u'望'), (0x2F8DA, 'M', u'朡'), (0x2F8DB, 'M', u'杞'), (0x2F8DC, 'M', u'杓'), (0x2F8DD, 'M', u'𣏃'), (0x2F8DE, 'M', u'㭉'), (0x2F8DF, 'M', u'柺'), (0x2F8E0, 'M', u'枅'), (0x2F8E1, 'M', u'桒'), (0x2F8E2, 'M', u'梅'), (0x2F8E3, 'M', u'𣑭'), (0x2F8E4, 'M', u'梎'), (0x2F8E5, 'M', u'栟'), (0x2F8E6, 'M', u'椔'), (0x2F8E7, 'M', u'㮝'), (0x2F8E8, 'M', u'楂'), (0x2F8E9, 'M', u'榣'), (0x2F8EA, 'M', u'槪'), (0x2F8EB, 'M', u'檨'), (0x2F8EC, 'M', u'𣚣'), (0x2F8ED, 'M', u'櫛'), (0x2F8EE, 'M', u'㰘'), (0x2F8EF, 'M', u'次'), ] def _seg_75(): return [ (0x2F8F0, 'M', u'𣢧'), (0x2F8F1, 'M', u'歔'), (0x2F8F2, 'M', u'㱎'), (0x2F8F3, 'M', u'歲'), (0x2F8F4, 'M', u'殟'), (0x2F8F5, 'M', u'殺'), (0x2F8F6, 'M', u'殻'), (0x2F8F7, 'M', u'𣪍'), (0x2F8F8, 'M', u'𡴋'), (0x2F8F9, 'M', u'𣫺'), (0x2F8FA, 'M', u'汎'), (0x2F8FB, 'M', u'𣲼'), (0x2F8FC, 'M', u'沿'), (0x2F8FD, 'M', u'泍'), (0x2F8FE, 'M', u'汧'), (0x2F8FF, 'M', u'洖'), (0x2F900, 'M', u'派'), (0x2F901, 'M', u'海'), (0x2F902, 'M', u'流'), (0x2F903, 'M', u'浩'), (0x2F904, 'M', u'浸'), (0x2F905, 'M', u'涅'), (0x2F906, 'M', u'𣴞'), (0x2F907, 'M', u'洴'), (0x2F908, 'M', u'港'), (0x2F909, 'M', u'湮'), (0x2F90A, 'M', u'㴳'), (0x2F90B, 'M', u'滋'), (0x2F90C, 'M', u'滇'), (0x2F90D, 'M', u'𣻑'), (0x2F90E, 'M', u'淹'), (0x2F90F, 'M', u'潮'), (0x2F910, 'M', u'𣽞'), (0x2F911, 'M', u'𣾎'), (0x2F912, 'M', u'濆'), (0x2F913, 'M', u'瀹'), (0x2F914, 'M', u'瀞'), (0x2F915, 'M', u'瀛'), (0x2F916, 'M', u'㶖'), (0x2F917, 'M', u'灊'), (0x2F918, 'M', u'災'), (0x2F919, 'M', u'灷'), (0x2F91A, 'M', u'炭'), (0x2F91B, 'M', u'𠔥'), (0x2F91C, 'M', u'煅'), (0x2F91D, 'M', u'𤉣'), (0x2F91E, 'M', u'熜'), (0x2F91F, 'X'), (0x2F920, 'M', u'爨'), (0x2F921, 'M', u'爵'), (0x2F922, 'M', u'牐'), (0x2F923, 'M', u'𤘈'), (0x2F924, 'M', u'犀'), (0x2F925, 'M', u'犕'), (0x2F926, 'M', u'𤜵'), (0x2F927, 'M', u'𤠔'), (0x2F928, 'M', u'獺'), (0x2F929, 'M', u'王'), (0x2F92A, 'M', u'㺬'), (0x2F92B, 'M', u'玥'), (0x2F92C, 'M', u'㺸'), (0x2F92E, 'M', u'瑇'), (0x2F92F, 'M', u'瑜'), (0x2F930, 'M', u'瑱'), (0x2F931, 'M', u'璅'), (0x2F932, 'M', u'瓊'), (0x2F933, 'M', u'㼛'), (0x2F934, 'M', u'甤'), (0x2F935, 'M', u'𤰶'), (0x2F936, 'M', u'甾'), (0x2F937, 'M', u'𤲒'), (0x2F938, 'M', u'異'), (0x2F939, 'M', u'𢆟'), (0x2F93A, 'M', u'瘐'), (0x2F93B, 'M', u'𤾡'), (0x2F93C, 'M', u'𤾸'), (0x2F93D, 'M', u'𥁄'), (0x2F93E, 'M', u'㿼'), (0x2F93F, 'M', u'䀈'), (0x2F940, 'M', u'直'), (0x2F941, 'M', u'𥃳'), (0x2F942, 'M', u'𥃲'), (0x2F943, 'M', u'𥄙'), (0x2F944, 'M', u'𥄳'), (0x2F945, 'M', u'眞'), (0x2F946, 'M', u'真'), (0x2F948, 'M', u'睊'), (0x2F949, 'M', u'䀹'), (0x2F94A, 'M', u'瞋'), (0x2F94B, 'M', u'䁆'), (0x2F94C, 'M', u'䂖'), (0x2F94D, 'M', u'𥐝'), (0x2F94E, 'M', u'硎'), (0x2F94F, 'M', u'碌'), (0x2F950, 'M', u'磌'), (0x2F951, 'M', u'䃣'), (0x2F952, 'M', u'𥘦'), (0x2F953, 'M', u'祖'), (0x2F954, 'M', u'𥚚'), (0x2F955, 'M', u'𥛅'), ] def _seg_76(): return [ (0x2F956, 'M', u'福'), (0x2F957, 'M', u'秫'), (0x2F958, 'M', u'䄯'), (0x2F959, 'M', u'穀'), (0x2F95A, 'M', u'穊'), (0x2F95B, 'M', u'穏'), (0x2F95C, 'M', u'𥥼'), (0x2F95D, 'M', u'𥪧'), (0x2F95F, 'X'), (0x2F960, 'M', u'䈂'), (0x2F961, 'M', u'𥮫'), (0x2F962, 'M', u'篆'), (0x2F963, 'M', u'築'), (0x2F964, 'M', u'䈧'), (0x2F965, 'M', u'𥲀'), (0x2F966, 'M', u'糒'), (0x2F967, 'M', u'䊠'), (0x2F968, 'M', u'糨'), (0x2F969, 'M', u'糣'), (0x2F96A, 'M', u'紀'), (0x2F96B, 'M', u'𥾆'), (0x2F96C, 'M', u'絣'), (0x2F96D, 'M', u'䌁'), (0x2F96E, 'M', u'緇'), (0x2F96F, 'M', u'縂'), (0x2F970, 'M', u'繅'), (0x2F971, 'M', u'䌴'), (0x2F972, 'M', u'𦈨'), (0x2F973, 'M', u'𦉇'), (0x2F974, 'M', u'䍙'), (0x2F975, 'M', u'𦋙'), (0x2F976, 'M', u'罺'), (0x2F977, 'M', u'𦌾'), (0x2F978, 'M', u'羕'), (0x2F979, 'M', u'翺'), (0x2F97A, 'M', u'者'), (0x2F97B, 'M', u'𦓚'), (0x2F97C, 'M', u'𦔣'), (0x2F97D, 'M', u'聠'), (0x2F97E, 'M', u'𦖨'), (0x2F97F, 'M', u'聰'), (0x2F980, 'M', u'𣍟'), (0x2F981, 'M', u'䏕'), (0x2F982, 'M', u'育'), (0x2F983, 'M', u'脃'), (0x2F984, 'M', u'䐋'), (0x2F985, 'M', u'脾'), (0x2F986, 'M', u'媵'), (0x2F987, 'M', u'𦞧'), (0x2F988, 'M', u'𦞵'), (0x2F989, 'M', u'𣎓'), (0x2F98A, 'M', u'𣎜'), (0x2F98B, 'M', u'舁'), (0x2F98C, 'M', u'舄'), (0x2F98D, 'M', u'辞'), (0x2F98E, 'M', u'䑫'), (0x2F98F, 'M', u'芑'), (0x2F990, 'M', u'芋'), (0x2F991, 'M', u'芝'), (0x2F992, 'M', u'劳'), (0x2F993, 'M', u'花'), (0x2F994, 'M', u'芳'), (0x2F995, 'M', u'芽'), (0x2F996, 'M', u'苦'), (0x2F997, 'M', u'𦬼'), (0x2F998, 'M', u'若'), (0x2F999, 'M', u'茝'), (0x2F99A, 'M', u'荣'), (0x2F99B, 'M', u'莭'), (0x2F99C, 'M', u'茣'), (0x2F99D, 'M', u'莽'), (0x2F99E, 'M', u'菧'), (0x2F99F, 'M', u'著'), (0x2F9A0, 'M', u'荓'), (0x2F9A1, 'M', u'菊'), (0x2F9A2, 'M', u'菌'), (0x2F9A3, 'M', u'菜'), (0x2F9A4, 'M', u'𦰶'), (0x2F9A5, 'M', u'𦵫'), (0x2F9A6, 'M', u'𦳕'), (0x2F9A7, 'M', u'䔫'), (0x2F9A8, 'M', u'蓱'), (0x2F9A9, 'M', u'蓳'), (0x2F9AA, 'M', u'蔖'), (0x2F9AB, 'M', u'𧏊'), (0x2F9AC, 'M', u'蕤'), (0x2F9AD, 'M', u'𦼬'), (0x2F9AE, 'M', u'䕝'), (0x2F9AF, 'M', u'䕡'), (0x2F9B0, 'M', u'𦾱'), (0x2F9B1, 'M', u'𧃒'), (0x2F9B2, 'M', u'䕫'), (0x2F9B3, 'M', u'虐'), (0x2F9B4, 'M', u'虜'), (0x2F9B5, 'M', u'虧'), (0x2F9B6, 'M', u'虩'), (0x2F9B7, 'M', u'蚩'), (0x2F9B8, 'M', u'蚈'), (0x2F9B9, 'M', u'蜎'), (0x2F9BA, 'M', u'蛢'), ] def _seg_77(): return [ (0x2F9BB, 'M', u'蝹'), (0x2F9BC, 'M', u'蜨'), (0x2F9BD, 'M', u'蝫'), (0x2F9BE, 'M', u'螆'), (0x2F9BF, 'X'), (0x2F9C0, 'M', u'蟡'), (0x2F9C1, 'M', u'蠁'), (0x2F9C2, 'M', u'䗹'), (0x2F9C3, 'M', u'衠'), (0x2F9C4, 'M', u'衣'), (0x2F9C5, 'M', u'𧙧'), (0x2F9C6, 'M', u'裗'), (0x2F9C7, 'M', u'裞'), (0x2F9C8, 'M', u'䘵'), (0x2F9C9, 'M', u'裺'), (0x2F9CA, 'M', u'㒻'), (0x2F9CB, 'M', u'𧢮'), (0x2F9CC, 'M', u'𧥦'), (0x2F9CD, 'M', u'䚾'), (0x2F9CE, 'M', u'䛇'), (0x2F9CF, 'M', u'誠'), (0x2F9D0, 'M', u'諭'), (0x2F9D1, 'M', u'變'), (0x2F9D2, 'M', u'豕'), (0x2F9D3, 'M', u'𧲨'), (0x2F9D4, 'M', u'貫'), (0x2F9D5, 'M', u'賁'), (0x2F9D6, 'M', u'贛'), (0x2F9D7, 'M', u'起'), (0x2F9D8, 'M', u'𧼯'), (0x2F9D9, 'M', u'𠠄'), (0x2F9DA, 'M', u'跋'), (0x2F9DB, 'M', u'趼'), (0x2F9DC, 'M', u'跰'), (0x2F9DD, 'M', u'𠣞'), (0x2F9DE, 'M', u'軔'), (0x2F9DF, 'M', u'輸'), (0x2F9E0, 'M', u'𨗒'), (0x2F9E1, 'M', u'𨗭'), (0x2F9E2, 'M', u'邔'), (0x2F9E3, 'M', u'郱'), (0x2F9E4, 'M', u'鄑'), (0x2F9E5, 'M', u'𨜮'), (0x2F9E6, 'M', u'鄛'), (0x2F9E7, 'M', u'鈸'), (0x2F9E8, 'M', u'鋗'), (0x2F9E9, 'M', u'鋘'), (0x2F9EA, 'M', u'鉼'), (0x2F9EB, 'M', u'鏹'), (0x2F9EC, 'M', u'鐕'), (0x2F9ED, 'M', u'𨯺'), (0x2F9EE, 'M', u'開'), (0x2F9EF, 'M', u'䦕'), (0x2F9F0, 'M', u'閷'), (0x2F9F1, 'M', u'𨵷'), (0x2F9F2, 'M', u'䧦'), (0x2F9F3, 'M', u'雃'), (0x2F9F4, 'M', u'嶲'), (0x2F9F5, 'M', u'霣'), (0x2F9F6, 'M', u'𩅅'), (0x2F9F7, 'M', u'𩈚'), (0x2F9F8, 'M', u'䩮'), (0x2F9F9, 'M', u'䩶'), (0x2F9FA, 'M', u'韠'), (0x2F9FB, 'M', u'𩐊'), (0x2F9FC, 'M', u'䪲'), (0x2F9FD, 'M', u'𩒖'), (0x2F9FE, 'M', u'頋'), (0x2FA00, 'M', u'頩'), (0x2FA01, 'M', u'𩖶'), (0x2FA02, 'M', u'飢'), (0x2FA03, 'M', u'䬳'), (0x2FA04, 'M', u'餩'), (0x2FA05, 'M', u'馧'), (0x2FA06, 'M', u'駂'), (0x2FA07, 'M', u'駾'), (0x2FA08, 'M', u'䯎'), (0x2FA09, 'M', u'𩬰'), (0x2FA0A, 'M', u'鬒'), (0x2FA0B, 'M', u'鱀'), (0x2FA0C, 'M', u'鳽'), (0x2FA0D, 'M', u'䳎'), (0x2FA0E, 'M', u'䳭'), (0x2FA0F, 'M', u'鵧'), (0x2FA10, 'M', u'𪃎'), (0x2FA11, 'M', u'䳸'), (0x2FA12, 'M', u'𪄅'), (0x2FA13, 'M', u'𪈎'), (0x2FA14, 'M', u'𪊑'), (0x2FA15, 'M', u'麻'), (0x2FA16, 'M', u'䵖'), (0x2FA17, 'M', u'黹'), (0x2FA18, 'M', u'黾'), (0x2FA19, 'M', u'鼅'), (0x2FA1A, 'M', u'鼏'), (0x2FA1B, 'M', u'鼖'), (0x2FA1C, 'M', u'鼻'), (0x2FA1D, 'M', u'𪘀'), (0x2FA1E, 'X'), (0xE0100, 'I'), ] def _seg_78(): return [ (0xE01F0, 'X'), ] uts46data = tuple( _seg_0() + _seg_1() + _seg_2() + _seg_3() + _seg_4() + _seg_5() + _seg_6() + _seg_7() + _seg_8() + _seg_9() + _seg_10() + _seg_11() + _seg_12() + _seg_13() + _seg_14() + _seg_15() + _seg_16() + _seg_17() + _seg_18() + _seg_19() + _seg_20() + _seg_21() + _seg_22() + _seg_23() + _seg_24() + _seg_25() + _seg_26() + _seg_27() + _seg_28() + _seg_29() + _seg_30() + _seg_31() + _seg_32() + _seg_33() + _seg_34() + _seg_35() + _seg_36() + _seg_37() + _seg_38() + _seg_39() + _seg_40() + _seg_41() + _seg_42() + _seg_43() + _seg_44() + _seg_45() + _seg_46() + _seg_47() + _seg_48() + _seg_49() + _seg_50() + _seg_51() + _seg_52() + _seg_53() + _seg_54() + _seg_55() + _seg_56() + _seg_57() + _seg_58() + _seg_59() + _seg_60() + _seg_61() + _seg_62() + _seg_63() + _seg_64() + _seg_65() + _seg_66() + _seg_67() + _seg_68() + _seg_69() + _seg_70() + _seg_71() + _seg_72() + _seg_73() + _seg_74() + _seg_75() + _seg_76() + _seg_77() + _seg_78() )
[]
alex4321/ctp
tests/kbcr/smart/test_smart.py
22a6a55442a648e5f7d8c10f90708a7340360720
# -*- coding: utf-8 -*- import numpy as np import torch from torch import nn from kbcr.kernels import GaussianKernel from kbcr.smart import NeuralKB import pytest @pytest.mark.light def test_smart_v1(): embedding_size = 50 rs = np.random.RandomState(0) for _ in range(32): with torch.no_grad(): triples = [ ('a', 'p', 'b'), ('c', 'q', 'd'), ('e', 'q', 'f'), ('g', 'q', 'h'), ('i', 'q', 'l'), ('m', 'q', 'n'), ('o', 'q', 'p'), ('q', 'q', 'r'), ('s', 'q', 't'), ('u', 'q', 'v') ] entity_lst = sorted({s for (s, _, _) in triples} | {o for (_, _, o) in triples}) predicate_lst = sorted({p for (_, p, _) in triples}) nb_entities, nb_predicates = len(entity_lst), len(predicate_lst) entity_to_index = {e: i for i, e in enumerate(entity_lst)} predicate_to_index = {p: i for i, p in enumerate(predicate_lst)} kernel = GaussianKernel() entity_embeddings = nn.Embedding(nb_entities, embedding_size * 2, sparse=True) predicate_embeddings = nn.Embedding(nb_predicates, embedding_size * 2, sparse=True) fact_rel = torch.LongTensor(np.array([predicate_to_index[p] for (_, p, _) in triples])) fact_arg1 = torch.LongTensor(np.array([entity_to_index[s] for (s, _, _) in triples])) fact_arg2 = torch.LongTensor(np.array([entity_to_index[o] for (_, _, o) in triples])) facts = [fact_rel, fact_arg1, fact_arg2] model = NeuralKB(entity_embeddings=entity_embeddings, predicate_embeddings=predicate_embeddings, kernel=kernel, facts=facts) xs_np = rs.randint(nb_entities, size=32) xp_np = rs.randint(nb_predicates, size=32) xo_np = rs.randint(nb_entities, size=32) xs_np[0] = 0 xp_np[0] = 0 xo_np[0] = 1 xs_np[1] = 2 xp_np[1] = 1 xo_np[1] = 3 xs = torch.LongTensor(xs_np) xp = torch.LongTensor(xp_np) xo = torch.LongTensor(xo_np) xs_emb = entity_embeddings(xs) xp_emb = predicate_embeddings(xp) xo_emb = entity_embeddings(xo) print('xp_emb', xp_emb.shape) res_sp, res_po = model.forward(xp_emb, xs_emb, xo_emb) inf = model.score(xp_emb, xs_emb, xo_emb) assert inf[0] > 0.9 assert inf[1] > 0.9 scores_sp, emb_sp = res_sp scores_po, emb_po = res_po print(scores_sp.shape, emb_sp.shape) print(scores_po.shape, emb_po.shape) inf = inf.cpu().numpy() scores_sp = scores_sp.cpu().numpy() scores_po = scores_po.cpu().numpy() print('AAA', inf) print('BBB', scores_sp) if __name__ == '__main__': pytest.main([__file__]) # test_smart_v1()
[((18, 9, 18, 33), 'numpy.random.RandomState', 'np.random.RandomState', ({(18, 31, 18, 32): '0'}, {}), '(0)', True, 'import numpy as np\n'), ((99, 4, 99, 27), 'pytest.main', 'pytest.main', ({(99, 16, 99, 26): '[__file__]'}, {}), '([__file__])', False, 'import pytest\n'), ((21, 13, 21, 28), 'torch.no_grad', 'torch.no_grad', ({}, {}), '()', False, 'import torch\n'), ((43, 21, 43, 37), 'kbcr.kernels.GaussianKernel', 'GaussianKernel', ({}, {}), '()', False, 'from kbcr.kernels import GaussianKernel\n'), ((45, 32, 45, 90), 'torch.nn.Embedding', 'nn.Embedding', (), '', False, 'from torch import nn\n'), ((46, 35, 46, 95), 'torch.nn.Embedding', 'nn.Embedding', (), '', False, 'from torch import nn\n'), ((53, 20, 54, 56), 'kbcr.smart.NeuralKB', 'NeuralKB', (), '', False, 'from kbcr.smart import NeuralKB\n'), ((68, 17, 68, 40), 'torch.LongTensor', 'torch.LongTensor', ({(68, 34, 68, 39): 'xs_np'}, {}), '(xs_np)', False, 'import torch\n'), ((69, 17, 69, 40), 'torch.LongTensor', 'torch.LongTensor', ({(69, 34, 69, 39): 'xp_np'}, {}), '(xp_np)', False, 'import torch\n'), ((70, 17, 70, 40), 'torch.LongTensor', 'torch.LongTensor', ({(70, 34, 70, 39): 'xo_np'}, {}), '(xo_np)', False, 'import torch\n'), ((48, 40, 48, 98), 'numpy.array', 'np.array', ({(48, 49, 48, 97): '[predicate_to_index[p] for _, p, _ in triples]'}, {}), '([predicate_to_index[p] for _, p, _ in triples])', True, 'import numpy as np\n'), ((49, 41, 49, 96), 'numpy.array', 'np.array', ({(49, 50, 49, 95): '[entity_to_index[s] for s, _, _ in triples]'}, {}), '([entity_to_index[s] for s, _, _ in triples])', True, 'import numpy as np\n'), ((50, 41, 50, 96), 'numpy.array', 'np.array', ({(50, 50, 50, 95): '[entity_to_index[o] for _, _, o in triples]'}, {}), '([entity_to_index[o] for _, _, o in triples])', True, 'import numpy as np\n')]
eseJiHeaLim/find_child
test.py
29596529ccf39241492b092b01baf03b76d0eb3a
import tkinter window=tkinter.Tk() window.title("YUN DAE HEE") window.geometry("640x400+100+100") window.resizable(True, True) image=tkinter.PhotoImage(file="opencv_frame_0.png") label=tkinter.Label(window, image=image) label.pack() window.mainloop()
[((3, 7, 3, 19), 'tkinter.Tk', 'tkinter.Tk', ({}, {}), '()', False, 'import tkinter\n'), ((8, 6, 8, 51), 'tkinter.PhotoImage', 'tkinter.PhotoImage', (), '', False, 'import tkinter\n'), ((10, 6, 10, 40), 'tkinter.Label', 'tkinter.Label', (), '', False, 'import tkinter\n')]
trujivan/climate-impact-changes
UMSLHackRestAPI/api/urls.py
609b8197b0ede1c1fdac3aa82b34e73e6f4526e3
from django.urls import path, include from .views import main_view, PredictionView #router = routers.DefaultRouter(trailing_slash=False) #router.register('years', YearView, basename='years') #router.register('predict', PredictionView, basename='predict') urlpatterns = [ #path('api/', get_dummy_data), #path('pollution/predict', get_prediction, name='test_predict'), #path('myform/', api_form_view, name='year_form'), #path('api/', include(router.urls)), path(r'', main_view, name="main"), path(r'api/v1/predict', PredictionView.as_view(), name='predict') ]
[((14, 4, 14, 37), 'django.urls.path', 'path', (), '', False, 'from django.urls import path, include\n')]
appressoas/ievv_opensource
ievv_opensource/utils/ievv_colorize.py
63e87827952ddc8f6f86145b79478ef21d6a0990
from django.conf import settings from termcolor import colored #: Red color constant for :func:`.ievv_colorize`. COLOR_RED = 'red' #: Blue color constant for :func:`.ievv_colorize`. COLOR_BLUE = 'blue' #: Yellow color constant for :func:`.ievv_colorize`. COLOR_YELLOW = 'yellow' #: Grey color constant for :func:`.ievv_colorize`. COLOR_GREY = 'grey' #: Green color constant for :func:`.ievv_colorize`. COLOR_GREEN = 'green' def colorize(text, color, bold=False): """ Colorize a string for stdout/stderr. Colors are only applied if :setting:`IEVV_COLORIZE_USE_COLORS` is ``True`` or not defined (so it defaults to ``True``). Examples: Print blue text:: from ievv_opensource.utils import ievv_colorize print(ievv_colorize('Test', color=ievv_colorize.COLOR_BLUE)) Print bold red text:: print(ievv_colorize('Test', color=ievv_colorize.COLOR_RED, bold=True)) Args: text: The text (string) to colorize. color: The color to use. Should be one of: - :obj:`.COLOR_RED` - :obj:`.COLOR_BLUE` - :obj:`.COLOR_YELLOW` - :obj:`.COLOR_GREY` - :obj:`.COLOR_GREEN` - ``None`` (no color) bold: Set this to ``True`` to use bold font. """ if getattr(settings, 'IEVV_COLORIZE_USE_COLORS', True) and color: attrs = [] if bold: attrs.append('bold') return colored(text, color=color, attrs=attrs) else: return text
[((57, 15, 57, 54), 'termcolor.colored', 'colored', (), '', False, 'from termcolor import colored\n')]
bluefin1986/tinyspark
RSICompute.py
0b086d3af5316062c2f3aaa7d4492341ed5c71c2
# coding: utf-8 # In[1]: import baostock as bs import pandas as pd import numpy as np import talib as ta import matplotlib.pyplot as plt import KlineService import BaoStockUtil import math import datetime from scipy import integrate from RSI import DayRSI,WeekRSI,MonthRSI,SixtyMinRSI from concurrent.futures import ThreadPoolExecutor, as_completed from Stock import Stock import dbutil from IPython.core.debugger import set_trace #算积分用的节点数 INTEGRATE_CALC_RANGE = 4 RSI_OVER_BUY = 80 RSI_OVER_SELL = 20 RSI_OVER_BUY_12 = 75 RSI_OVER_SELL_12 = 25 RSI_OVER_BUY_24 = 70 RSI_OVER_SELL_24 = 30 RSI_MIDDLE = 50 #日线超卖区域积分阈值 RSI_INTE_OVERSELL_THRESHOLD_DAY = 50 # In[3]: def findLatestRSIDate(period): mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] cursor = collection.find().sort("date",-1).limit(1) df = pd.DataFrame(list(cursor)) if df.empty: return "1970-01-01" return df["date"][0] def clearRSI(period): mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] collection.delete_many({}) indexes = collection.index_information() if "code_1_date_1" in indexes.keys(): collection.drop_index( "code_1_date_1" ) def createIndex(period): mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] collection.create_index( [("code", 1), ("date",1)]) def integrateValues(valuesArray): return integrate.trapz(valuesArray, x=None, dx=1.0, axis=-1) ## # 从数据库读指定日期RSI数据 # # def readRSI(period, stockCode, startDate, endDate): mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] if type(startDate) == str: startDate = datetime.datetime.strptime(startDate + "T00:00:00.000Z", "%Y-%m-%dT%H:%M:%S.000Z") endDate = datetime.datetime.strptime(endDate + "T23:59:59.000Z", "%Y-%m-%dT%H:%M:%S.000Z") cursor = collection.find({"code":stockCode,"date":{"$gte":startDate,"$lte":endDate}}) df = pd.DataFrame(list(cursor)) return df ## # 写RSI数据库 # # def writeRSIToDB(period, stockCode, stockName, rsi_df): dataList = [] for index,rsi in rsi_df.iterrows(): rsiDate = rsi['date'] if period == "day": rsiObj = DayRSI(stockCode, stockName) elif period == "week": rsiObj = WeekRSI(stockCode, stockName) elif period == "month": rsiObj = MonthRSI(stockCode, stockName) elif period == "5m": rsiObj = FiveMinRSI(stockCode, stockName) elif period == "15m": rsiObj = FiftyMinRSI(stockCode, stockName) elif period == "30m": rsiObj = ThirtyMinRSI(stockCode, stockName) elif period == "60m": rsiObj = SixtyMinRSI(stockCode, stockName) rsiObj.date = rsiDate rsiObj.rsi_6 = rsi['rsi_6'] rsiObj.rsi_12 = rsi['rsi_12'] rsiObj.rsi_24 = rsi['rsi_24'] rsiObj.overBuy = rsi['overBuyFlag'] rsiObj.overSell = rsi['overSellFlag'] dataList.append(rsiObj.__dict__) mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] if len(dataList) > 0: collection.insert_many(dataList) else: raise RuntimeError("RSI数据为空") def computeStockRSI(period, stockCode, stockName, startDate, endDate): try: # compute1 = datetime.datetime.now().timestamp() df = KlineService.readStockKline(stockCode, period, startDate, endDate) # compute2 = datetime.datetime.now().timestamp() # print("read stockLine:", compute2 - compute1) if df.empty: return False if period == "day": # 剔除日线停盘数据 df = df[df['tradeStatus'] == '1'] rsi_df = computeRSI(df) # compute3 = datetime.datetime.now().timestamp() # print("compute rsi:", compute3 - compute2) writeRSIToDB(period, stockCode, stockName, rsi_df) # compute4 = datetime.datetime.now().timestamp() # print("write to db:", compute4 - compute3) return True except BaseException as e: print ("download " + stockCode + " error:" + str(e)) return False ## # 选择不同的Kline Collection # def chooseRSICollection(period): periodRSICollection = { "day" : "RSI_Day", "week" : "RSI_Week", "month" : "RSI_Month", "5m" : "RSI_5m", "15m" : "RSI_15m", "30m" : "RSI_30m", "60m" : "RSI_60m" } return periodRSICollection.get(period) def computeRSI(klineDataFrame): rsi_12days = ta.RSI(klineDataFrame['closePrice'],timeperiod=12) rsi_6days = ta.RSI(klineDataFrame['closePrice'],timeperiod=6) rsi_24days = ta.RSI(klineDataFrame['closePrice'],timeperiod=24) rsiFrame = pd.DataFrame(klineDataFrame, columns=["date"]) rsiFrame['rsi_6'] = rsi_6days rsiFrame['rsi_12'] = rsi_12days rsiFrame['rsi_24'] = rsi_24days ##添加参考线位置 rsiFrame['overBuy'] = RSI_OVER_BUY rsiFrame['overSell'] = RSI_OVER_SELL rsiFrame['middle'] = RSI_MIDDLE # RSI超卖和超买 rsi_buy_position = rsiFrame['rsi_12'] > RSI_OVER_BUY_12 rsi_sell_position = rsiFrame['rsi_12'] < RSI_OVER_SELL_12 rsiFrame.loc[rsi_buy_position[(rsi_buy_position == True) & (rsi_buy_position.shift() == False)].index, 'overBuyFlag'] = 'Yes' rsiFrame.loc[rsi_sell_position[(rsi_sell_position == True) & (rsi_sell_position.shift() == False)].index, 'overSellFlag'] = 'Yes' return rsiFrame ## # 计算自起始日期起的RSI # # def computeAllRSIDataOfPeriod(period, startDate): # currtime = datetime.datetime.now().timestamp() print("begin clear RSI period:", period) clearRSI(period) print("cleared RSI period:", period) # time1 = datetime.datetime.now().timestamp() # print("clear finished:",time1 - currtime) stockDict = KlineService.allStocks() # time2 = datetime.datetime.now().timestamp() # print("read stocks finished:",time2 - time1) endDate = str(datetime.date.today()) jobStart = datetime.datetime.now().timestamp() processCount = 0 failCount = 0 jobTotal = len(stockDict) ''' #起线程池来跑,单线程太慢了, 事实证明慢个鬼 executor = ThreadPoolExecutor(max_workers=1) funcVars = [] for key,stock in stockDict.items(): #指数没有分钟线,调过指数的RSI分钟线计算 if period.endswith("m") and (key.startswith("sh.000") or key.startswith("sz.399")): continue funcVars.append([period, key, stock["name"], startDate, endDate]) all_task = [executor.submit(computeStockRSI, funcVar[0], funcVar[1], funcVar[2], funcVar[3], funcVar[4]) for funcVar in funcVars] for future in as_completed(all_task): processCount = processCount + 1 if not future.result(): failCount = failCount + 1 if processCount % 100 == 0 and processCount > 0: print ("rsi process:", processCount, " of ", jobTotal ," failed:", failCount) ''' for key,stock in stockDict.items(): processCount = processCount + 1 #指数没有分钟线,调过指数的RSI分钟线计算 if period.endswith("m") and (key.startswith("sh.000") or key.startswith("sz.399")): continue result = computeStockRSI(period, key, stock["name"], startDate, endDate) if not result: failCount = failCount + 1 if processCount % 100 == 0 and processCount > 0: print ("rsi process:", processCount, " of ", jobTotal ," failed:", failCount) jobFinished = datetime.datetime.now().timestamp() createIndex(period) print("write all stock RSI to db finished, cost:", jobFinished - jobStart) return True ## # 计算指定日期的RSI积分 # # def computeAllRSIDataIntegrate(period, specifiedDateStr, includeST): BaoStockUtil.customLogin() specifiedDate = datetime.datetime.strptime(specifiedDateStr, "%Y-%m-%d") today = datetime.date.today() #如果把时间设成未来,自动调成今天 if specifiedDate > datetime.datetime.today(): specifiedDate = datetime.date.today() #避免跨年问题,直接从去年开始取 startDate = specifiedDate - datetime.timedelta(days = 365) #取交易日列表,用作倒推周期使用 rs = bs.query_trade_dates(start_date=datetime.datetime.strftime(startDate, "%Y-%m-%d"), end_date = specifiedDate) BaoStockUtil.customLogout() if rs.error_code != '0': raise RuntimeError("交易日api调用失败了:" + rs.error_code) tradeDates = [] while (rs.error_code == '0') & rs.next(): row = rs.get_row_data() if row[1] == "1": tradeDates.append(row[0]) if len(tradeDates) == 0: raise RuntimeError("取不到最新的交易日") #若期望计算的日期比库里RSI最新日期还晚,数据不全待补齐 rsiLatestDate = findLatestRSIDate(period) rsiLatestDateStr = datetime.datetime.strftime(rsiLatestDate, "%Y-%m-%d") if rsiLatestDate < specifiedDate: raise RuntimeError(specifiedDateStr + " 的 " + period + " RSI的数据不存在,待补齐数据") #找到指定日期以及rsi存量数据最近日期在交易日周期的序号 specifiedDateIndex = tradeDates.index(specifiedDateStr) if specifiedDateIndex == -1: raise RuntimeError(specifiedDateStr + " 可能不是交易日") daysBefore = computeRSIDataStartTradeDateRange(period, specifiedDateStr) startDateIndex = specifiedDateIndex - daysBefore #起始日期index负数,说明rsi数据不够 if startDateIndex < 0: raise RuntimeError(period + " rsi数据不够") startDateStr = tradeDates[startDateIndex] print("compute rsi tradeDates from ", startDateStr, "to", specifiedDateStr) processCount = 0 failCount = 0 startDateIndex = -1 dictStocks = KlineService.allStocks() klineDataFrame = KlineService.readAllStockKline(period, specifiedDateStr, specifiedDateStr) klineDataFrame = klineDataFrame.set_index("code") klineDict = klineDataFrame.to_dict('index') jobTotal = len(dictStocks) rsiValueArrs = [] for i in range(0, 6): rsiValueArrs.append([]) for key,stock in dictStocks.items(): processCount = processCount + 1 #指数没有分钟线,跳过指数的RSI分钟线计算 if period.endswith("m") and stock.stockType != 1: continue #如果不计算ST,跳过 if not includeST and stock["isST"]: continue #退市股就不要算了 if "退" in stock["name"]: continue #科创板不达门槛没法买,不看 if key.startswith("sh.68"): continue try: rsiDF = readRSI(period, key, startDateStr, specifiedDateStr) rsiCount = len(rsiDF) if rsiCount < INTEGRATE_CALC_RANGE: raise RuntimeError("积分计算节点不够") rsiValueArrs[0].append(key) rsiValueArrs[1].append(stock["name"]) rsiValueArrs[2].append(klineDict[key]["closePrice"]) #取最近的数据用于计算积分 rsiValueArrs[3].append(rsiDF["rsi_6"][rsiCount - INTEGRATE_CALC_RANGE : rsiCount]) rsiValueArrs[4].append(rsiDF["rsi_12"][rsiCount - INTEGRATE_CALC_RANGE : rsiCount]) rsiValueArrs[5].append(rsiDF["rsi_24"][rsiCount - INTEGRATE_CALC_RANGE : rsiCount]) except BaseException as e: failCount = failCount + 1 print ("compute rsi integrate " + key + " error:" + str(e)) if processCount % 100 == 0 and processCount > 0: print ("compute rsi integrate process:", processCount, " of ", jobTotal ," failed:", failCount) rsi6Arr = np.array(rsiValueArrs[3]).reshape(-1, INTEGRATE_CALC_RANGE) rsi6InteArr = integrateValues(rsi6Arr) rsi12Arr = np.array(rsiValueArrs[4]).reshape(-1, INTEGRATE_CALC_RANGE) rsi12InteArr = integrateValues(rsi12Arr) rsi24Arr = np.array(rsiValueArrs[5]).reshape(-1, INTEGRATE_CALC_RANGE) rsi24InteArr = integrateValues(rsi24Arr) rsiInteDF = pd.DataFrame() rsiInteDF["code"] = rsiValueArrs[0] rsiInteDF["name"] = rsiValueArrs[1] rsiInteDF["closePrice"] = rsiValueArrs[2] rsiInteDF["rsi_inte_6"] = rsi6InteArr rsiInteDF["rsi_inte_12"] = rsi12InteArr rsiInteDF["rsi_inte_24"] = rsi24InteArr return rsiInteDF #算出计算本周期下指定数据需要的起始交易日 #每个交易日一共4小时,所以取4小时为一天,而不是24小时 #每个计算周期一共至少需要4个节点,分钟线RSI统一除以4*60=240分钟算出所需计算数据天数,最少为一天 #日线不用除分钟 ## TODO 周线没想好怎么算,更别说月线了。 def computeRSIDataStartTradeDateRange(period, specifiedDate): daysBefore = 0 if period.endswith("m"): daysBefore = math.ceil(INTEGRATE_CALC_RANGE * (int(period.replace("m", "")) + 1) / (60 * 4)) elif period == "day": daysBefore = INTEGRATE_CALC_RANGE else: raise RuntimeError("周期有误") return daysBefore
[((44, 11, 44, 29), 'dbutil.connectDB', 'dbutil.connectDB', ({}, {}), '()', False, 'import dbutil\n'), ((53, 11, 53, 29), 'dbutil.connectDB', 'dbutil.connectDB', ({}, {}), '()', False, 'import dbutil\n'), ((61, 11, 61, 29), 'dbutil.connectDB', 'dbutil.connectDB', ({}, {}), '()', False, 'import dbutil\n'), ((66, 11, 66, 64), 'scipy.integrate.trapz', 'integrate.trapz', (), '', False, 'from scipy import integrate\n'), ((73, 11, 73, 29), 'dbutil.connectDB', 'dbutil.connectDB', ({}, {}), '()', False, 'import dbutil\n'), ((114, 11, 114, 29), 'dbutil.connectDB', 'dbutil.connectDB', ({}, {}), '()', False, 'import dbutil\n'), ((161, 17, 161, 67), 'talib.RSI', 'ta.RSI', (), '', True, 'import talib as ta\n'), ((162, 16, 162, 65), 'talib.RSI', 'ta.RSI', (), '', True, 'import talib as ta\n'), ((163, 17, 163, 67), 'talib.RSI', 'ta.RSI', (), '', True, 'import talib as ta\n'), ((165, 15, 165, 61), 'pandas.DataFrame', 'pd.DataFrame', (), '', True, 'import pandas as pd\n'), ((193, 16, 193, 40), 'KlineService.allStocks', 'KlineService.allStocks', ({}, {}), '()', False, 'import KlineService\n'), ((242, 4, 242, 30), 'BaoStockUtil.customLogin', 'BaoStockUtil.customLogin', ({}, {}), '()', False, 'import BaoStockUtil\n'), ((243, 20, 243, 76), 'datetime.datetime.strptime', 'datetime.datetime.strptime', ({(243, 47, 243, 63): 'specifiedDateStr', (243, 65, 243, 75): '"""%Y-%m-%d"""'}, {}), "(specifiedDateStr, '%Y-%m-%d')", False, 'import datetime\n'), ((244, 12, 244, 33), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((252, 4, 252, 31), 'BaoStockUtil.customLogout', 'BaoStockUtil.customLogout', ({}, {}), '()', False, 'import BaoStockUtil\n'), ((265, 23, 265, 76), 'datetime.datetime.strftime', 'datetime.datetime.strftime', ({(265, 50, 265, 63): 'rsiLatestDate', (265, 65, 265, 75): '"""%Y-%m-%d"""'}, {}), "(rsiLatestDate, '%Y-%m-%d')", False, 'import datetime\n'), ((287, 17, 287, 41), 'KlineService.allStocks', 'KlineService.allStocks', ({}, {}), '()', False, 'import KlineService\n'), ((288, 21, 288, 95), 'KlineService.readAllStockKline', 'KlineService.readAllStockKline', ({(288, 52, 288, 58): 'period', (288, 60, 288, 76): 'specifiedDateStr', (288, 78, 288, 94): 'specifiedDateStr'}, {}), '(period, specifiedDateStr, specifiedDateStr)', False, 'import KlineService\n'), ((336, 16, 336, 30), 'pandas.DataFrame', 'pd.DataFrame', ({}, {}), '()', True, 'import pandas as pd\n'), ((76, 20, 76, 102), 'datetime.datetime.strptime', 'datetime.datetime.strptime', ({(76, 47, 76, 75): "startDate + 'T00:00:00.000Z'", (76, 77, 76, 101): '"""%Y-%m-%dT%H:%M:%S.000Z"""'}, {}), "(startDate + 'T00:00:00.000Z',\n '%Y-%m-%dT%H:%M:%S.000Z')", False, 'import datetime\n'), ((77, 18, 77, 98), 'datetime.datetime.strptime', 'datetime.datetime.strptime', ({(77, 45, 77, 71): "endDate + 'T23:59:59.000Z'", (77, 73, 77, 97): '"""%Y-%m-%dT%H:%M:%S.000Z"""'}, {}), "(endDate + 'T23:59:59.000Z', '%Y-%m-%dT%H:%M:%S.000Z'\n )", False, 'import datetime\n'), ((125, 13, 125, 79), 'KlineService.readStockKline', 'KlineService.readStockKline', ({(125, 41, 125, 50): 'stockCode', (125, 52, 125, 58): 'period', (125, 60, 125, 69): 'startDate', (125, 71, 125, 78): 'endDate'}, {}), '(stockCode, period, startDate, endDate)', False, 'import KlineService\n'), ((196, 18, 196, 39), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((246, 23, 246, 48), 'datetime.datetime.today', 'datetime.datetime.today', ({}, {}), '()', False, 'import datetime\n'), ((247, 24, 247, 45), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((249, 32, 249, 62), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((91, 21, 91, 49), 'RSI.DayRSI', 'DayRSI', ({(91, 28, 91, 37): 'stockCode', (91, 39, 91, 48): 'stockName'}, {}), '(stockCode, stockName)', False, 'from RSI import DayRSI, WeekRSI, MonthRSI, SixtyMinRSI\n'), ((197, 15, 197, 38), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((232, 18, 232, 41), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((251, 41, 251, 90), 'datetime.datetime.strftime', 'datetime.datetime.strftime', ({(251, 68, 251, 77): 'startDate', (251, 79, 251, 89): '"""%Y-%m-%d"""'}, {}), "(startDate, '%Y-%m-%d')", False, 'import datetime\n'), ((329, 14, 329, 39), 'numpy.array', 'np.array', ({(329, 23, 329, 38): 'rsiValueArrs[3]'}, {}), '(rsiValueArrs[3])', True, 'import numpy as np\n'), ((331, 15, 331, 40), 'numpy.array', 'np.array', ({(331, 24, 331, 39): 'rsiValueArrs[4]'}, {}), '(rsiValueArrs[4])', True, 'import numpy as np\n'), ((333, 15, 333, 40), 'numpy.array', 'np.array', ({(333, 24, 333, 39): 'rsiValueArrs[5]'}, {}), '(rsiValueArrs[5])', True, 'import numpy as np\n'), ((93, 21, 93, 50), 'RSI.WeekRSI', 'WeekRSI', ({(93, 29, 93, 38): 'stockCode', (93, 40, 93, 49): 'stockName'}, {}), '(stockCode, stockName)', False, 'from RSI import DayRSI, WeekRSI, MonthRSI, SixtyMinRSI\n'), ((95, 21, 95, 51), 'RSI.MonthRSI', 'MonthRSI', ({(95, 30, 95, 39): 'stockCode', (95, 41, 95, 50): 'stockName'}, {}), '(stockCode, stockName)', False, 'from RSI import DayRSI, WeekRSI, MonthRSI, SixtyMinRSI\n'), ((103, 21, 103, 54), 'RSI.SixtyMinRSI', 'SixtyMinRSI', ({(103, 33, 103, 42): 'stockCode', (103, 44, 103, 53): 'stockName'}, {}), '(stockCode, stockName)', False, 'from RSI import DayRSI, WeekRSI, MonthRSI, SixtyMinRSI\n')]
abousselmi/OSNoise
osnoise/conf/base.py
f0e4baa51921f672179c014beb89555958c7ddca
# Copyright 2016 Orange # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_config import cfg base_options = [ cfg.StrOpt( 'log_file_name', default='osnoise.log', help='Osnoise file name.'), cfg.StrOpt( 'log_dir', default='/var/log/osnoise/', help='Osnoise log directory.'), cfg.StrOpt( 'log_level', default='info', help='Log level.'), cfg.StrOpt( 'log_file', default='/var/log/osnoise/osnoise.log', help='Log file'), cfg.IntOpt( 'log_maxBytes', default=1000000, min=1000, help='Log level.'), cfg.IntOpt( 'log_backupCount', default=5, min=1, help='Log level.'), cfg.BoolOpt('log_config_append', default=False, deprecated_group='DEFAULT', help='To append logs to existent log file or not.'), ] def register_opts(conf): conf.register_opts(base_options) def list_opts(): return {'DEFAULT' : base_options}
[((19, 4, 22, 34), 'oslo_config.cfg.StrOpt', 'cfg.StrOpt', (), '', False, 'from oslo_config import cfg\n'), ((23, 4, 26, 38), 'oslo_config.cfg.StrOpt', 'cfg.StrOpt', (), '', False, 'from oslo_config import cfg\n'), ((27, 4, 30, 26), 'oslo_config.cfg.StrOpt', 'cfg.StrOpt', (), '', False, 'from oslo_config import cfg\n'), ((32, 4, 35, 24), 'oslo_config.cfg.StrOpt', 'cfg.StrOpt', (), '', False, 'from oslo_config import cfg\n'), ((37, 4, 41, 26), 'oslo_config.cfg.IntOpt', 'cfg.IntOpt', (), '', False, 'from oslo_config import cfg\n'), ((42, 4, 46, 26), 'oslo_config.cfg.IntOpt', 'cfg.IntOpt', (), '', False, 'from oslo_config import cfg\n'), ((47, 4, 50, 67), 'oslo_config.cfg.BoolOpt', 'cfg.BoolOpt', (), '', False, 'from oslo_config import cfg\n')]
Ginkooo/ORION-sensor-visualizer
src/orionsensor/gui/sensors/proximitysensor.py
550b2e692d711bb8104fe827570ef9b9112536d3
from kivy.properties import NumericProperty from gui.sensors.sensor import Sensor import config class ProximitySensor(Sensor): """Proximity sensor view""" # maximum possible reading max = NumericProperty(config.ProximitySensor.max) # minimum possible reading min = NumericProperty(config.ProximitySensor.min)
[((11, 10, 11, 53), 'kivy.properties.NumericProperty', 'NumericProperty', ({(11, 26, 11, 52): 'config.ProximitySensor.max'}, {}), '(config.ProximitySensor.max)', False, 'from kivy.properties import NumericProperty\n'), ((13, 10, 13, 53), 'kivy.properties.NumericProperty', 'NumericProperty', ({(13, 26, 13, 52): 'config.ProximitySensor.min'}, {}), '(config.ProximitySensor.min)', False, 'from kivy.properties import NumericProperty\n')]
gudtldn/DiscordStockBot
Cogs/HelpCommand.py
d1b06e49738092ccf3c5d5a26b35fd321a3bd0f2
#도움말 import discord from discord.ext import commands from discord.ext.commands import Context from define import * class HelpCommand_Context(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="도움말", aliases=["명령어", "?"]) @CommandExecutionTime async def _HelpCommand(self, ctx: Context, command: str=None): logger.info(f"[{type(ctx)}] {ctx.author.name}: {ctx.invoked_with} {command}") if ctx.guild is None: logger.info("Guild is None") return if command is not None: if command.startswith("."): command = command.replace(".", "", 1) if command is None: embed = discord.Embed(title="도움말", description="[] <-- 필수 입력항목 | <> <-- 선택 입력항목", color=RandomEmbedColor()) embed.add_field(name=".사용자등록", value="데이터 베이스에 사용자를 등록합니다.", inline=False) embed.add_field(name=".자산정보", value="현재 자신의 자산정보를 확인합니다.", inline=False) embed.add_field(name=".주가", value="현재 주가를 검색합니다.", inline=False) embed.add_field(name=".매수", value="입력한 기업의 주식을 매수합니다.", inline=False) embed.add_field(name=".매도", value="입력한 기업의 주식을 매도합니다.", inline=False) embed.add_field(name=".지원금", value="1만원 ~ 10만원 사이의 돈을 랜덤으로 지급합니다.", inline=False) embed.add_field(name=".초기화", value="자신의 자산정보를 초기화 합니다.", inline=False) embed.add_field(name=".탈퇴", value="이 봇에 저장되어있는 사용자의 정보를 삭제합니다.", inline=False) embed.add_field(name=".개인설정", value="개인설정을 확인 또는 수정합니다.", inline=False) embed.add_field(name=".단축어설정", value="단축어목록을 확인하거나, 추가 또는 제거합니다.", inline=False) embed.add_field(name=".관심종목", value="관심종목에 추가된 주식의 가격을 확인하거나, 추가 또는 제거합니다.", inline=False) embed.set_footer(text="명령어를 자세히 보려면 「.도움말 <명령어 이름>」 을 써 주세요.") await ctx.reply(embed=embed) return elif command in ("도움말", "명령어", "?"): command_list = ["도움말", "명령어", "?"] command_list.remove(command) embed = discord.Embed(title="도움말", description="등록되어있는 명령어들을 출력합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) await ctx.reply(embed=embed) return elif command in ("사용자등록", "등록"): command_list = ["사용자등록", "등록"] command_list.remove(command) embed = discord.Embed(title="사용자등록", description="데이터 베이스에 사용자를 등록합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) await ctx.reply(embed=embed) return elif command in ("자산정보", "자산조회"): command_list = ["자산정보", "자산조회"] command_list.remove(command) embed = discord.Embed(title="자산정보", description="자신의 자산정보를 확인합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) embed.add_field(name=".자산정보 <@유저>", value="@유저의 자산정보를 확인합니다.", inline=False) embed.add_field(name=".자산정보 <랭킹 | 순위>", value="이 서버에 있는 유저의 자산랭킹을 나열합니다.", inline=False) await ctx.reply(embed=embed) return elif command in ("주가", "시세"): command_list = ["주가", "시세"] command_list.remove(command) embed = discord.Embed(title="주가", description="입력한 기업의 현재 주가를 확인합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) embed.add_field(name=".주가 [기업이름 | 기업번호]", value="기업이름 또는 기업번호로 검색합니다.", inline=False) await ctx.reply(embed=embed) return elif command in ("매수", "구매", "주식구매", "주식매수"): command_list = ["매수", "구매", "주식구매", "주식매수"] command_list.remove(command) embed = discord.Embed(title="매수", description="입력한 기업의 주식을 매수합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) embed.add_field(name=".매수 [기업이름 | 기업번호] [매수 할 주식 개수]", value="입력한 기업의 주식을, 주식 개수만큼 매수합니다.", inline=False) embed.add_field(name=".매수 [기업이름 | 기업번호] [풀매수 | 모두]", value="입력한 기업의 주식을 최대까지 매수합니다.", inline=False) await ctx.reply(embed=embed) return elif command in ("매도", "판매", "주식판매", "주식매도"): command_list = ["매도", "판매", "주식판매", "주식매도"] command_list.remove(command) embed = discord.Embed(title="매도", description="입력한 기업의 주식을 매도합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) embed.add_field(name=".매도 [기업이름 | 기업번호] [매도 할 주식 개수]", value="입력한 기업의 주식을, 주식 개수만큼 매도합니다.", inline=False) embed.add_field(name=".매도 [기업이름 | 기업번호] [반매도]", value="입력한 기업의 주식의 절반을 매도합니다.", inline=False) embed.add_field(name=".매도 [기업이름 | 기업번호] [풀매도 | 모두]", value="입력한 기업의 주식을 모두 매도합니다.", inline=False) await ctx.reply(embed=embed) return elif command in ("지원금", "돈받기"): command_list = ["지원금", "돈받기"] command_list.remove(command) embed = discord.Embed(title="지원금", description="1만원 ~ 10만원 사이의 돈을 랜덤으로 지급합니다. (쿨타임: 4시간)", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) await ctx.reply(embed=embed) return elif command == "초기화": embed = discord.Embed(title="초기화", description="「초기화확인」를 입력해 자신의 자산정보를 초기화 합니다.", color=RandomEmbedColor()) embed.add_field(name=".초기화 [확인문구]", value="확인문구에는 「초기화확인」를 입력해 주세요.") await ctx.reply(embed=embed) return elif command in ("탈퇴", "회원탈퇴"): command_list = ["탈퇴", "회원탈퇴"] command_list.remove(command) embed = discord.Embed(title="탈퇴", description="「탈퇴확인」를 입력해 데이터 베이스에서 자신의 자산정보를 삭제합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) embed.add_field(name=".탈퇴 [확인문구]", value="확인문구에는 「탈퇴확인」를 입력해 주세요.") await ctx.reply(embed=embed) return elif command in ("개인설정", "설정"): command_list = ["개인설정", "설정"] command_list.remove(command) embed = discord.Embed(title="개인설정", description="개인설정을 확인 또는 수정합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) embed.add_field(name=".개인설정 설정정보", value="설정할 수 있는 목록을 확인합니다.", inline=False) embed.add_field(name=".개인설정 자산정보 [true | false]", value="자산정보 공개여부를 설정합니다.", inline=False) embed.add_field(name=".개인설정 지원금표시 [true | false]", value="지원금으로 얻은 돈 표시여부를 설정합니다.", inline=False) embed.add_field(name=".개인설정 차트표시 [true | false]", value="`주가` 명령어에 차트를 표시합니다.", inline=False) embed.add_field(name=".개인설정 쿨타임표시 [true | false]", value="`지원금` 명령어에 쿨타임을 바로 표시합니다.", inline=False) embed.add_field(name=".개인설정 어제대비가격 [true | false]", value="`자산정보` 명령어에 현재 주가 대신, 어제 대비 가격을 표시합니다.", inline=False) await ctx.reply(embed=embed) return elif command in ("단축어설정", "단축어"): command_list = ["단축어설정", "단축어"] command_list.remove(command) embed = discord.Embed(title="단축어설정", description="단축어목록을 확인하거나, 추가 또는 제거합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) embed.add_field(name=".단축어설정 목록", value="자신의 단축어 목록을 확인합니다.", inline=False) embed.add_field(name=".단축어설정 추가 -이름 [기업이름] -번호 [기업번호]", value="단축어 목록에 단축어를 새로 추가합니다.\n\ 사용 예: `.단축어 추가 -이름 삼전 -번호 005930`", inline=False) embed.add_field(name=".단축어설정 추가 -번호 [기업번호]", value="단축어 목록에 단축어를 새로 추가합니다.(이름은 기업이름으로 설정됩니다)\n\ 사용 예: `.단축어 추가 -번호 005930`", inline=False) embed.add_field(name=".단축어설정 제거 -이름 [기업이름]", value="단축어 목록에 있는 단축어를 제거합니다.\n\ 사용 예: `.단축어 제거 -이름 삼전`", inline=False) await ctx.reply(embed=embed) return elif command in ("관심종목", "관심"): command_list = ["관심종목", "관심"] command_list.remove(command) embed = discord.Embed(title="관심종목", description="관심종목에 추가된 주식의 가격을 확인하거나, 추가 또는 제거합니다.", color=RandomEmbedColor()) embed.add_field(name="다른이름", value=f"{', '.join(command_list)}", inline=False) embed.add_field(name=".관심종목 주가", value="관심종목에 추가된 주식의 주가를 나열합니다.", inline=False) embed.add_field(name=".관심종목 추가", value="관심종목에 주식을 추가합니다.", inline=False) embed.add_field(name=".관심종목 제거", value="관심종목에서 주식을 제거합니다.", inline=False) await ctx.reply(embed=embed) return else: await ctx.reply("알 수 없는 명령어 입니다.") return def setup(bot: commands.Bot): bot.add_cog(HelpCommand_Context(bot))
[((13, 5, 13, 67), 'discord.ext.commands.command', 'commands.command', (), '', False, 'from discord.ext import commands\n')]
SupermeLC/PyNeval
test/test_model/cprofile_test.py
2cccfb1af7d97857454e9cbc3515ba75e5d8d4b0
import cProfile import pstats import os # 性能分析装饰器定义 def do_cprofile(filename): """ Decorator for function profiling. """ def wrapper(func): def profiled_func(*args, **kwargs): # Flag for do profiling or not. DO_PROF = False if DO_PROF: profile = cProfile.Profile() profile.enable() result = func(*args, **kwargs) profile.disable() # Sort stat by internal time. sortby = "tottime" ps = pstats.Stats(profile).sort_stats(sortby) ps.dump_stats(filename) else: result = func(*args, **kwargs) return result return profiled_func return wrapper
[((16, 26, 16, 44), 'cProfile.Profile', 'cProfile.Profile', ({}, {}), '()', False, 'import cProfile\n'), ((22, 21, 22, 42), 'pstats.Stats', 'pstats.Stats', ({(22, 34, 22, 41): 'profile'}, {}), '(profile)', False, 'import pstats\n')]
cyberhck/renku-python
renku/core/commands/providers/api.py
2e52dff9dd627c93764aadb9fd1e91bd190a5de7
# Copyright 2019 - Swiss Data Science Center (SDSC) # A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and # Eidgenössische Technische Hochschule Zürich (ETHZ). # # 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. """API for providers.""" import abc class ProviderApi(abc.ABC): """Interface defining provider methods.""" @abc.abstractmethod def find_record(self, uri): """Find record by uri.""" pass @abc.abstractmethod def get_exporter(self, dataset, secret): """Get export manager.""" pass @staticmethod @abc.abstractmethod def supports(uri): """Whether or not this provider supports a given uri.""" pass class ExporterApi(abc.ABC): """Interface defining exporter methods.""" @abc.abstractmethod def set_access_token(self, access_token): """Set access token.""" pass @abc.abstractmethod def access_token_url(self): """Endpoint for creation of access token.""" pass @abc.abstractmethod def export(self, publish): """Execute export process.""" pass
[]
bluetech/cattrs
cattr/__init__.py
be438d5566bd308b584359a9b0011a7bd0006b06
# -*- coding: utf-8 -*- from .converters import Converter, UnstructureStrategy __all__ = ('global_converter', 'unstructure', 'structure', 'structure_attrs_fromtuple', 'structure_attrs_fromdict', 'UnstructureStrategy') __author__ = 'Tin Tvrtković' __email__ = '[email protected]' global_converter = Converter() unstructure = global_converter.unstructure structure = global_converter.structure structure_attrs_fromtuple = global_converter.structure_attrs_fromtuple structure_attrs_fromdict = global_converter.structure_attrs_fromdict register_structure_hook = global_converter.register_structure_hook register_structure_hook_func = global_converter.register_structure_hook_func register_unstructure_hook = global_converter.register_unstructure_hook register_unstructure_hook_func = \ global_converter.register_unstructure_hook_func
[]
zjzh/vega
vega/security/run_dask.py
aa6e7b8c69024262fc483ee06113b4d1bd5156d8
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. 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. """Run dask scheduler and worker.""" import os import subprocess import shutil import logging import socket import random from distributed import Client from distributed.security import Security from .conf import get_config from .verify_cert import verify_cert sec_cfg = get_config('server') def get_client_security(address): """Get client.""" address = address.replace("tcp", "tls") if not verify_cert(sec_cfg.ca_cert, sec_cfg.client_cert_dask): logging.error(f"The cert {sec_cfg.ca_cert} and {sec_cfg.client_cert_dask} are invalid, please check.") sec = Security(tls_ca_file=sec_cfg.ca_cert, tls_client_cert=sec_cfg.client_cert_dask, tls_client_key=sec_cfg.client_secret_key_dask, require_encryption=True) return Client(address, security=sec) def get_address_security(master_host, master_port): """Get address.""" return "tls://{}:{}".format(master_host, master_port) def run_scheduler_security(ip, port, tmp_file): """Run scheduler.""" if not verify_cert(sec_cfg.ca_cert, sec_cfg.server_cert_dask): logging.error(f"The cert {sec_cfg.ca_cert} and {sec_cfg.server_cert_dask} are invalid, please check.") return subprocess.Popen( [ "dask-scheduler", "--no-dashboard", "--no-show", f"--tls-ca-file={sec_cfg.ca_cert}", f"--tls-cert={sec_cfg.server_cert_dask}", f"--tls-key={sec_cfg.server_secret_key_dask}", f"--host={ip}", "--protocol=tls", f"--port={port}", f"--scheduler-file={tmp_file}", f"--local-directory={os.path.dirname(tmp_file)}", ], env=os.environ ) def _available_port(min_port, max_port) -> int: _sock = socket.socket() while True: port = random.randint(min_port, max_port) try: _sock.bind(('', port)) _sock.close() return port except Exception: logging.debug('Failed to get available port, continue.') continue return None def run_local_worker_security(slave_ip, address, local_dir): """Run dask-worker on local node.""" address = address.replace("tcp", "tls") nanny_port = _available_port(30000, 30999) worker_port = _available_port(29000, 29999) pid = subprocess.Popen( [ "dask-worker", address, '--nthreads=1', '--nprocs=1', '--memory-limit=0', f"--local-directory={local_dir}", f"--tls-ca-file={sec_cfg.ca_cert}", f"--tls-cert={sec_cfg.client_cert_dask}", f"--tls-key={sec_cfg.client_secret_key_dask}", "--no-dashboard", f"--host={slave_ip}", "--protocol=tls", f"--nanny-port={nanny_port}", f"--worker-port={worker_port}", ], env=os.environ ) return pid def run_remote_worker_security(slave_ip, address, local_dir): """Run dask-worker on remote node.""" address = address.replace("tcp", "tls") nanny_port = _available_port(30000, 30999) worker_port = _available_port(29000, 29999) pid = subprocess.Popen( [ "ssh", slave_ip, shutil.which("dask-worker"), address, '--nthreads=1', '--nprocs=1', '--memory-limit=0', f"--local-directory={local_dir}", f"--tls-ca-file={sec_cfg.ca_cert}", f"--tls-cert={sec_cfg.client_cert_dask}", f"--tls-key={sec_cfg.client_secret_key_dask}", "--no-dashboard", f"--host={slave_ip}", "--protocol=tls", f"--nanny-port={nanny_port}", f"--worker-port={worker_port}", ], env=os.environ ) return pid
[((38, 10, 41, 43), 'distributed.security.Security', 'Security', (), '', False, 'from distributed.security import Security\n'), ((42, 11, 42, 40), 'distributed.Client', 'Client', (), '', False, 'from distributed import Client\n'), ((73, 12, 73, 27), 'socket.socket', 'socket.socket', ({}, {}), '()', False, 'import socket\n'), ((91, 10, 109, 5), 'subprocess.Popen', 'subprocess.Popen', (), '', False, 'import subprocess\n'), ((37, 8, 37, 110), 'logging.error', 'logging.error', ({(37, 22, 37, 109): 'f"""The cert {sec_cfg.ca_cert} and {sec_cfg.client_cert_dask} are invalid, please check."""'}, {}), "(\n f'The cert {sec_cfg.ca_cert} and {sec_cfg.client_cert_dask} are invalid, please check.'\n )", False, 'import logging\n'), ((53, 8, 53, 110), 'logging.error', 'logging.error', ({(53, 22, 53, 109): 'f"""The cert {sec_cfg.ca_cert} and {sec_cfg.server_cert_dask} are invalid, please check."""'}, {}), "(\n f'The cert {sec_cfg.ca_cert} and {sec_cfg.server_cert_dask} are invalid, please check.'\n )", False, 'import logging\n'), ((75, 15, 75, 49), 'random.randint', 'random.randint', ({(75, 30, 75, 38): 'min_port', (75, 40, 75, 48): 'max_port'}, {}), '(min_port, max_port)', False, 'import random\n'), ((122, 12, 122, 39), 'shutil.which', 'shutil.which', ({(122, 25, 122, 38): '"""dask-worker"""'}, {}), "('dask-worker')", False, 'import shutil\n'), ((81, 12, 81, 68), 'logging.debug', 'logging.debug', ({(81, 26, 81, 67): '"""Failed to get available port, continue."""'}, {}), "('Failed to get available port, continue.')", False, 'import logging\n'), ((66, 33, 66, 58), 'os.path.dirname', 'os.path.dirname', ({(66, 49, 66, 57): 'tmp_file'}, {}), '(tmp_file)', False, 'import os\n')]
NoaBrazilay/DeepLearningProject
MISSGANvsStarGAN/core/solver.py
5c44d21069de1fc5fa2687c4121286670be3d773
""" StarGAN v2 Copyright (c) 2020-present NAVER Corp. This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. """ import os from os.path import join as ospj import time import datetime from munch import Munch import torch import torch.nn as nn import torch.nn.functional as F from core.model import build_model from core.checkpoint import CheckpointIO from core.data_loader import InputFetcher import core.utils as utils from metrics.eval import calculate_metrics class Solver(nn.Module): def __init__(self, args): super().__init__() self.args = args self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.nets, self.nets_ema, self.vgg, self.VggExtract = build_model(args) self.instancenorm = nn.InstanceNorm2d(512, affine=False) self.L1Loss = nn.L1Loss() # below setattrs are to make networks be children of Solver, e.g., for self.to(self.device) for name, module in self.nets.items(): utils.print_network(module, name) setattr(self, name, module) for name, module in self.nets_ema.items(): setattr(self, name + '_ema', module) if args.mode == 'train': self.optims = Munch() for net in self.nets.keys(): if net == 'fan': continue self.optims[net] = torch.optim.Adam( params=self.nets[net].parameters(), lr=args.f_lr if net == 'mapping_network' else args.lr, betas=[args.beta1, args.beta2], weight_decay=args.weight_decay) self.ckptios = [CheckpointIO(ospj(args.checkpoint_dir, '100000_nets.ckpt'), **self.nets), CheckpointIO(ospj(args.checkpoint_dir, '100000_nets_ema.ckpt'), **self.nets_ema), CheckpointIO(ospj(args.checkpoint_dir, '100000_optims.ckpt'), **self.optims)] else: self.ckptios = [CheckpointIO(ospj(args.checkpoint_dir, '100000_nets_ema.ckpt'), **self.nets_ema)] self.to(self.device) for name, network in self.named_children(): # Do not initialize the FAN parameters if ('ema' not in name) and ('fan' not in name): print('Initializing %s...' % name) network.apply(utils.he_init) def _save_checkpoint(self, step): for ckptio in self.ckptios: ckptio.save(step) def _load_checkpoint(self, step): for ckptio in self.ckptios: ckptio.load(step) def _reset_grad(self): for optim in self.optims.values(): optim.zero_grad() def train(self, loaders): args = self.args nets = self.nets nets_ema = self.nets_ema optims = self.optims # fetch random validation images for debugging fetcher = InputFetcher(loaders.src, loaders.ref, args.latent_dim, 'train') fetcher_val = InputFetcher(loaders.val, None, args.latent_dim, 'val') inputs_val = next(fetcher_val) # resume training if necessary if args.resume_iter > 0: self._load_checkpoint(args.resume_iter) # remember the initial value of ds weight initial_lambda_ds = args.lambda_ds print('Start training...') start_time = time.time() for i in range(args.resume_iter, args.total_iters): # fetch images and labels inputs = next(fetcher) x_real, y_org = inputs.x_src, inputs.y_src x_ref, x_ref2, y_trg = inputs.x_ref, inputs.x_ref2, inputs.y_ref z_trg, z_trg2 = inputs.z_trg, inputs.z_trg2 masks = nets.fan.get_heatmap(x_real) if args.w_hpf > 0 else None # train the discriminator d_loss, d_losses_latent = compute_d_loss( nets, args, x_real, y_org, y_trg, z_trg=z_trg, masks=masks) self._reset_grad() d_loss.backward() optims.discriminator.step() d_loss, d_losses_ref = compute_d_loss( nets, args, x_real, y_org, y_trg, x_ref=x_ref, masks=masks) self._reset_grad() d_loss.backward() optims.discriminator.step() # train the generator g_loss, g_losses_latent = compute_g_loss( nets, args, x_real, y_org, y_trg, z_trgs=[z_trg, z_trg2], masks=masks,VggExtract=self.VggExtract, IN = self.instancenorm, L1Loss=self.L1Loss) self._reset_grad() g_loss.backward() optims.generator.step() optims.mapping_network.step() optims.style_encoder.step() g_loss, g_losses_ref = compute_g_loss( nets, args, x_real, y_org, y_trg, x_refs=[x_ref, x_ref2], masks=masks, VggExtract=self.VggExtract, IN = self.instancenorm, L1Loss=self.L1Loss) self._reset_grad() g_loss.backward() optims.generator.step() # compute moving average of network parameters moving_average(nets.generator, nets_ema.generator, beta=0.999) moving_average(nets.mapping_network, nets_ema.mapping_network, beta=0.999) moving_average(nets.style_encoder, nets_ema.style_encoder, beta=0.999) # decay weight for diversity sensitive loss if args.lambda_ds > 0: args.lambda_ds -= (initial_lambda_ds / args.ds_iter) # print out log info if (i+1) % args.print_every == 0: elapsed = time.time() - start_time elapsed = str(datetime.timedelta(seconds=elapsed))[:-7] log = "Elapsed time [%s], Iteration [%i/%i], " % (elapsed, i+1, args.total_iters) all_losses = dict() for loss, prefix in zip([d_losses_latent, d_losses_ref, g_losses_latent, g_losses_ref], ['D/latent_', 'D/ref_', 'G/latent_', 'G/ref_']): for key, value in loss.items(): all_losses[prefix + key] = value all_losses['G/lambda_ds'] = args.lambda_ds log += ' '.join(['%s: [%.4f]' % (key, value) for key, value in all_losses.items()]) print(log) # generate images for debugging if (i+1) % args.sample_every == 0: os.makedirs(args.sample_dir, exist_ok=True) utils.debug_image(nets_ema, args, inputs=inputs_val, step=i+1) # save model checkpoints if (i+1) % args.save_every == 0: self._save_checkpoint(step=i+1) # compute FID and LPIPS if necessary if (i+1) % args.eval_every == 0: calculate_metrics(nets_ema, args, i+1, mode='latent') calculate_metrics(nets_ema, args, i+1, mode='reference') @torch.no_grad() def sample(self, loaders): args = self.args nets_ema = self.nets_ema os.makedirs(args.result_dir, exist_ok=True) self._load_checkpoint(args.resume_iter) src = next(InputFetcher(loaders.src, None, args.latent_dim, 'test')) ref = next(InputFetcher(loaders.ref, None, args.latent_dim, 'test')) fname = ospj(args.result_dir, 'reference.jpg') print('Working on {}...'.format(fname)) utils.translate_using_reference(nets_ema, args, src.x, ref.x, ref.y, fname) # fname = ospj(args.result_dir, 'video_ref.mp4') # print('Working on {}...'.format(fname)) # utils.video_ref(nets_ema, args, src.x, ref.x, ref.y, fname) @torch.no_grad() def evaluate(self): args = self.args nets_ema = self.nets_ema resume_iter = args.resume_iter self._load_checkpoint(args.resume_iter) calculate_metrics(nets_ema, args, step=resume_iter, mode='latent') calculate_metrics(nets_ema, args, step=resume_iter, mode='reference') def compute_d_loss(nets, args, x_real, y_org, y_trg, z_trg=None, x_ref=None, masks=None): assert (z_trg is None) != (x_ref is None) # with real images x_real.requires_grad_() out = nets.discriminator(x_real, y_org) loss_real = adv_loss(out, 1) loss_reg = r1_reg(out, x_real) # with fake images with torch.no_grad(): if z_trg is not None: s_trg = nets.mapping_network(z_trg, y_trg) else: # x_ref is not None s_trg = nets.style_encoder(x_ref, y_trg) x_fake,_ = nets.generator(x_real, s_trg, masks=masks) out = nets.discriminator(x_fake, y_trg) loss_fake = adv_loss(out, 0) loss = loss_real + loss_fake + args.lambda_reg * loss_reg return loss, Munch(real=loss_real.item(), fake=loss_fake.item(), reg=loss_reg.item()) def compute_g_loss(nets, args, x_real, y_org, y_trg, z_trgs=None, x_refs=None, masks=None, VggExtract= None, IN= None, L1Loss=None): assert (z_trgs is None) != (x_refs is None) if z_trgs is not None: z_trg, z_trg2 = z_trgs if x_refs is not None: x_ref, x_ref2 = x_refs # adversarial loss if z_trgs is not None: s_trg = nets.mapping_network(z_trg, y_trg) else: s_trg = nets.style_encoder(x_ref, y_trg) x_fake, content_latent_real = nets.generator(x_real, s_trg, masks=masks) out = nets.discriminator(x_fake, y_trg) loss_adv = adv_loss(out, 1) # style reconstruction loss s_pred = nets.style_encoder(x_fake, y_trg) loss_sty = torch.mean(torch.abs(s_pred - s_trg)) # diversity sensitive loss if z_trgs is not None: s_trg2 = nets.mapping_network(z_trg2, y_trg) else: s_trg2 = nets.style_encoder(x_ref2, y_trg) x_fake2, content_latent_real2 = nets.generator(x_real, s_trg2, masks=masks) x_fake2 = x_fake2.detach() loss_ds = torch.mean(torch.abs(x_fake - x_fake2)) # cycle-consistency loss masks = nets.fan.get_heatmap(x_fake) if args.w_hpf > 0 else None s_org = nets.style_encoder(x_real, y_org) x_rec, content_latent_reco = nets.generator(x_fake, s_org, masks=masks) loss_cyc = torch.mean(torch.abs(x_rec - x_real)) loss_vgg = compute_vgg_loss(x_fake, x_real, VggExtract, IN, L1Loss) if args.vgg_w > 0 else 0 loss_sacl = utils.abs_criterion(content_latent_real, content_latent_reco) if args.loss_sacl > 0 else 0 # Loss style aware content loss loss_sacl2 = utils.abs_criterion(content_latent_real2, content_latent_reco) if args.loss_sacl > 0 else 0 # Loss style aware content loss loss = loss_adv + args.lambda_sty * loss_sty \ - args.lambda_ds * loss_ds + args.lambda_cyc * loss_cyc + args.lambda_vgg * loss_vgg + args.lambda_loss_sacl * loss_sacl+ args.lambda_loss_sacl * loss_sacl2 return loss, Munch(adv=loss_adv.item(), sty=loss_sty.item(), ds=loss_ds.item(), cyc=loss_cyc.item()) def moving_average(model, model_test, beta=0.999): for param, param_test in zip(model.parameters(), model_test.parameters()): param_test.data = torch.lerp(param.data, param_test.data, beta) def adv_loss(logits, target): assert target in [1, 0] targets = torch.full_like(logits, fill_value=target) loss = F.binary_cross_entropy_with_logits(logits, targets) return loss def compute_vgg_loss(img, target, VggExtract, IN, L1Loss): # img_vgg = utils.vgg_preprocess(img) # target_vgg = utils.vgg_preprocess(target) # img_fea = vgg(img_vgg) # target_fea = vgg(target_vgg) img_fea_dict = VggExtract(img) target_fea_dict = VggExtract(target) # loss = torch.mean((img_fea_dict['relu3_3'] - target_fea_dict['relu3_3']) ** 2) # loss = torch.mean(torch.abs(img_fea_dict['relu3_3'] - target_fea_dict['relu3_3'])) loss = L1Loss(img_fea_dict['relu2_2'] , target_fea_dict['relu2_2']) return loss def r1_reg(d_out, x_in): # zero-centered gradient penalty for real images batch_size = x_in.size(0) grad_dout = torch.autograd.grad( outputs=d_out.sum(), inputs=x_in, create_graph=True, retain_graph=True, only_inputs=True )[0] grad_dout2 = grad_dout.pow(2) assert(grad_dout2.size() == x_in.size()) reg = 0.5 * grad_dout2.view(batch_size, -1).sum(1).mean(0) return reg
[((174, 5, 174, 20), 'torch.no_grad', 'torch.no_grad', ({}, {}), '()', False, 'import torch\n'), ((192, 5, 192, 20), 'torch.no_grad', 'torch.no_grad', ({}, {}), '()', False, 'import torch\n'), ((282, 14, 282, 56), 'torch.full_like', 'torch.full_like', (), '', False, 'import torch\n'), ((283, 11, 283, 62), 'torch.nn.functional.binary_cross_entropy_with_logits', 'F.binary_cross_entropy_with_logits', ({(283, 46, 283, 52): 'logits', (283, 54, 283, 61): 'targets'}, {}), '(logits, targets)', True, 'import torch.nn.functional as F\n'), ((34, 62, 34, 79), 'core.model.build_model', 'build_model', ({(34, 74, 34, 78): 'args'}, {}), '(args)', False, 'from core.model import build_model\n'), ((35, 28, 35, 64), 'torch.nn.InstanceNorm2d', 'nn.InstanceNorm2d', (), '', True, 'import torch.nn as nn\n'), ((36, 22, 36, 33), 'torch.nn.L1Loss', 'nn.L1Loss', ({}, {}), '()', True, 'import torch.nn as nn\n'), ((87, 18, 87, 82), 'core.data_loader.InputFetcher', 'InputFetcher', ({(87, 31, 87, 42): 'loaders.src', (87, 44, 87, 55): 'loaders.ref', (87, 57, 87, 72): 'args.latent_dim', (87, 74, 87, 81): '"""train"""'}, {}), "(loaders.src, loaders.ref, args.latent_dim, 'train')", False, 'from core.data_loader import InputFetcher\n'), ((88, 22, 88, 77), 'core.data_loader.InputFetcher', 'InputFetcher', ({(88, 35, 88, 46): 'loaders.val', (88, 48, 88, 52): 'None', (88, 54, 88, 69): 'args.latent_dim', (88, 71, 88, 76): '"""val"""'}, {}), "(loaders.val, None, args.latent_dim, 'val')", False, 'from core.data_loader import InputFetcher\n'), ((99, 21, 99, 32), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((178, 8, 178, 51), 'os.makedirs', 'os.makedirs', (), '', False, 'import os\n'), ((184, 16, 184, 54), 'os.path.join', 'ospj', ({(184, 21, 184, 36): 'args.result_dir', (184, 38, 184, 53): '"""reference.jpg"""'}, {}), "(args.result_dir, 'reference.jpg')", True, 'from os.path import join as ospj\n'), ((186, 8, 186, 83), 'core.utils.translate_using_reference', 'utils.translate_using_reference', ({(186, 40, 186, 48): 'nets_ema', (186, 50, 186, 54): 'args', (186, 56, 186, 61): 'src.x', (186, 63, 186, 68): 'ref.x', (186, 70, 186, 75): 'ref.y', (186, 77, 186, 82): 'fname'}, {}), '(nets_ema, args, src.x, ref.x, ref.y, fname)', True, 'import core.utils as utils\n'), ((198, 8, 198, 74), 'metrics.eval.calculate_metrics', 'calculate_metrics', (), '', False, 'from metrics.eval import calculate_metrics\n'), ((199, 8, 199, 77), 'metrics.eval.calculate_metrics', 'calculate_metrics', (), '', False, 'from metrics.eval import calculate_metrics\n'), ((211, 9, 211, 24), 'torch.no_grad', 'torch.no_grad', ({}, {}), '()', False, 'import torch\n'), ((246, 26, 246, 51), 'torch.abs', 'torch.abs', ({(246, 36, 246, 50): 's_pred - s_trg'}, {}), '(s_pred - s_trg)', False, 'import torch\n'), ((255, 25, 255, 52), 'torch.abs', 'torch.abs', ({(255, 35, 255, 51): 'x_fake - x_fake2'}, {}), '(x_fake - x_fake2)', False, 'import torch\n'), ((261, 26, 261, 51), 'torch.abs', 'torch.abs', ({(261, 36, 261, 50): 'x_rec - x_real'}, {}), '(x_rec - x_real)', False, 'import torch\n'), ((264, 16, 264, 78), 'core.utils.abs_criterion', 'utils.abs_criterion', ({(264, 36, 264, 55): 'content_latent_real', (264, 58, 264, 77): 'content_latent_reco'}, {}), '(content_latent_real, content_latent_reco)', True, 'import core.utils as utils\n'), ((265, 17, 265, 80), 'core.utils.abs_criterion', 'utils.abs_criterion', ({(265, 37, 265, 57): 'content_latent_real2', (265, 60, 265, 79): 'content_latent_reco'}, {}), '(content_latent_real2, content_latent_reco)', True, 'import core.utils as utils\n'), ((277, 26, 277, 71), 'torch.lerp', 'torch.lerp', ({(277, 37, 277, 47): 'param.data', (277, 49, 277, 64): 'param_test.data', (277, 66, 277, 70): 'beta'}, {}), '(param.data, param_test.data, beta)', False, 'import torch\n'), ((39, 12, 39, 45), 'core.utils.print_network', 'utils.print_network', ({(39, 32, 39, 38): 'module', (39, 40, 39, 44): 'name'}, {}), '(module, name)', True, 'import core.utils as utils\n'), ((45, 26, 45, 33), 'munch.Munch', 'Munch', ({}, {}), '()', False, 'from munch import Munch\n'), ((181, 19, 181, 75), 'core.data_loader.InputFetcher', 'InputFetcher', ({(181, 32, 181, 43): 'loaders.src', (181, 45, 181, 49): 'None', (181, 51, 181, 66): 'args.latent_dim', (181, 68, 181, 74): '"""test"""'}, {}), "(loaders.src, None, args.latent_dim, 'test')", False, 'from core.data_loader import InputFetcher\n'), ((182, 19, 182, 75), 'core.data_loader.InputFetcher', 'InputFetcher', ({(182, 32, 182, 43): 'loaders.ref', (182, 45, 182, 49): 'None', (182, 51, 182, 66): 'args.latent_dim', (182, 68, 182, 74): '"""test"""'}, {}), "(loaders.ref, None, args.latent_dim, 'test')", False, 'from core.data_loader import InputFetcher\n'), ((32, 45, 32, 70), 'torch.cuda.is_available', 'torch.cuda.is_available', ({}, {}), '()', False, 'import torch\n'), ((162, 16, 162, 59), 'os.makedirs', 'os.makedirs', (), '', False, 'import os\n'), ((163, 16, 163, 78), 'core.utils.debug_image', 'utils.debug_image', (), '', True, 'import core.utils as utils\n'), ((171, 16, 171, 69), 'metrics.eval.calculate_metrics', 'calculate_metrics', (), '', False, 'from metrics.eval import calculate_metrics\n'), ((172, 16, 172, 72), 'metrics.eval.calculate_metrics', 'calculate_metrics', (), '', False, 'from metrics.eval import calculate_metrics\n'), ((55, 41, 55, 86), 'os.path.join', 'ospj', ({(55, 46, 55, 65): 'args.checkpoint_dir', (55, 67, 55, 85): '"""100000_nets.ckpt"""'}, {}), "(args.checkpoint_dir, '100000_nets.ckpt')", True, 'from os.path import join as ospj\n'), ((56, 29, 56, 78), 'os.path.join', 'ospj', ({(56, 34, 56, 53): 'args.checkpoint_dir', (56, 55, 56, 77): '"""100000_nets_ema.ckpt"""'}, {}), "(args.checkpoint_dir, '100000_nets_ema.ckpt')", True, 'from os.path import join as ospj\n'), ((57, 29, 57, 76), 'os.path.join', 'ospj', ({(57, 34, 57, 53): 'args.checkpoint_dir', (57, 55, 57, 75): '"""100000_optims.ckpt"""'}, {}), "(args.checkpoint_dir, '100000_optims.ckpt')", True, 'from os.path import join as ospj\n'), ((59, 41, 59, 90), 'os.path.join', 'ospj', ({(59, 46, 59, 65): 'args.checkpoint_dir', (59, 67, 59, 89): '"""100000_nets_ema.ckpt"""'}, {}), "(args.checkpoint_dir, '100000_nets_ema.ckpt')", True, 'from os.path import join as ospj\n'), ((148, 26, 148, 37), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((149, 30, 149, 65), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n')]
vishweshwartyagi/Data-Structures-and-Algorithms-UCSD
1. Algorithmic Toolbox/week2_algorithmic_warmup/4_lcm.py
de942b3a0eb2bf56f949f47c297fad713aa81489
# Uses python3 import sys def lcm_naive(a, b): for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def gcd(a, b): if a%b == 0: return b elif b%a == 0: return a if a > b: return gcd(a%b, b) else: return gcd(b%a, a) def lcm(a, b): return int((a*b) / gcd(a, b)) if __name__ == '__main__': # input = sys.stdin.read() a, b = map(int, input().split()) # print(lcm_naive(a, b)) print(lcm(a, b))
[]
JoviCastillo/TH-Project-1-guessing-game-
guessing_game.py
efa5c7080b1a484b20655ddb01873dc3edefc415
import random highscore = [] def not_in_range(guess_it): """This is to check that the numbers inputted by the user are in range, and will let the user know. If the numbers are in range then it passes. """ if guess_it < 1: print('I am not thinking of negative numbers!') elif guess_it > 10: print('That number is way bigger than 10!') else: pass def new_game(tries): """After the user has guessed the number correctly, the game will ask the player if they would like to play again. Yes will start the game again. No will exit the game. Highscore will be displayed by the lowest amount of tries recorded. """ play_again = input('Would you like to play again? (Yes/No) ') if play_again.upper() == 'YES': highscore.append(tries) highscore.sort print('The highscore is {}.'.format(highscore[0])) start_game() elif play_again.upper() == 'NO': exit() else: play_again = input('Please let me know by typing yes or no: ') def start_game(): # title screen of the game """This is the start of the game which include the title screen and is the main function that runs all the other functions as well. """ print('-' * 40) print('Welcome to the Number Guessing Game!!!') print('-' * 40) print('I am thinking of a number between 1-10.') random_number = random.randint(1, 10) tries = 0 while True: try: guess_it = int(input('Can you guess it?: ')) except ValueError: print('I said number, not gibberish!') else: while guess_it != random_number: not_in_range(guess_it) tries += 1 if guess_it > random_number: print('That is too high!') elif guess_it < random_number: print('That is too low') break else: print('You guessed it right! Your number was {}.'.format(random_number)) print('It took you {} tries.'.format(tries)) break new_game(tries) if __name__ == '__main__': # Kick off the program by calling the start_game function. start_game()
[((44, 20, 44, 41), 'random.randint', 'random.randint', ({(44, 35, 44, 36): '1', (44, 38, 44, 40): '10'}, {}), '(1, 10)', False, 'import random\n')]
dastacy/gve_devnet_unity_unread_voicemail_notifier
MAIL_SERVER.py
445177d1107e465d90971d3d6ebb3249c5ed7b29
#!/usr/bin/env python3 USER = r'server\user' PASSWORD = 'server_password' HOSTNAME = 'hostname.goes.here.com' DOMAIN = 'domain.goes.here.com' FROM_ADDR = '[email protected]'
[]
anetczuk/rsscast
src/testrsscast/rss/ytconverter_example.py
8649d1143679afcabbe19e5499f104fa1325bff1
#!/usr/bin/python3 # # MIT License # # Copyright (c) 2021 Arkadiusz Netczuk <[email protected]> # # 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. # try: ## following import success only when file is directly executed from command line ## otherwise will throw exception when executing as parameter for "python -m" # pylint: disable=W0611 import __init__ except ImportError as error: ## when import fails then it means that the script was executed indirectly ## in this case __init__ is already loaded pass import sys import argparse import rsscast.logger as logger from rsscast.rss.ytconverter import convert_yt if __name__ != '__main__': sys.exit(0) parser = argparse.ArgumentParser(description='YouTube convert example') args = parser.parse_args() logger.configure_console() converted = convert_yt( "https://www.youtube.com/watch?v=BLRUiVXeZKU", "/tmp/yt_example.mp3" ) print("converted:", converted)
[((47, 9, 47, 71), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (), '', False, 'import argparse\n'), ((52, 0, 52, 26), 'rsscast.logger.configure_console', 'logger.configure_console', ({}, {}), '()', True, 'import rsscast.logger as logger\n'), ((55, 12, 55, 94), 'rsscast.rss.ytconverter.convert_yt', 'convert_yt', ({(55, 24, 55, 69): '"""https://www.youtube.com/watch?v=BLRUiVXeZKU"""', (55, 71, 55, 92): '"""/tmp/yt_example.mp3"""'}, {}), "('https://www.youtube.com/watch?v=BLRUiVXeZKU', '/tmp/yt_example.mp3'\n )", False, 'from rsscast.rss.ytconverter import convert_yt\n'), ((44, 4, 44, 15), 'sys.exit', 'sys.exit', ({(44, 13, 44, 14): '(0)'}, {}), '(0)', False, 'import sys\n')]
palazzem/elmo-server
cli.py
b2e02d600a431dc1db31090f0d8dd09a8d586373
import click APP_YAML_TEMPLATE = """runtime: python37 env_variables: ELMO_BASE_URL: '{BASE_URL}' ELMO_VENDOR: '{VENDOR}' handlers: - url: /.* script: auto secure: always redirect_http_response_code: 301 """ @click.command() @click.argument("base_url") @click.argument("vendor") def generate_app_yaml(base_url, vendor): """Use APP_YAML_TEMPLATE to generate app.yaml for AppEngine deployments. Args: base_url: defines ELMO_BASE_URL env variable in AppEngine config. vendor: defines ELMO_VENDOR env variable in AppEngine config. Returns: Writes `app.yaml` file in the current folder. """ print("Writing the following deployment config to disk:") app_yaml = APP_YAML_TEMPLATE.format(BASE_URL=base_url, VENDOR=vendor) print(app_yaml) with open("app.yaml", "w") as f: f.write(app_yaml) print("Done! You can deploy the service with `gcloud app deploy`") if __name__ == "__main__": generate_app_yaml()
[((16, 1, 16, 16), 'click.command', 'click.command', ({}, {}), '()', False, 'import click\n'), ((17, 1, 17, 27), 'click.argument', 'click.argument', ({(17, 16, 17, 26): '"""base_url"""'}, {}), "('base_url')", False, 'import click\n'), ((18, 1, 18, 25), 'click.argument', 'click.argument', ({(18, 16, 18, 24): '"""vendor"""'}, {}), "('vendor')", False, 'import click\n')]