hexsha
stringlengths
40
40
size
int64
10
805k
ext
stringclasses
6 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
176
max_stars_repo_name
stringlengths
7
114
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
176
max_issues_repo_name
stringlengths
7
114
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
176
max_forks_repo_name
stringlengths
7
114
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
10
805k
avg_line_length
float64
5.53
11k
max_line_length
int64
10
129k
alphanum_fraction
float64
0.13
0.93
content_no_comment
stringlengths
0
449k
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f7167dafa438abb972d4d287944bf016ae2c3bf7
15,655
py
Python
MuJoCo/modules/utils.py
mosesnah-shared/whip-project-targeting
7f47598635f027e2cb05ad33b66ed67627d20329
[ "BSD-3-Clause" ]
null
null
null
MuJoCo/modules/utils.py
mosesnah-shared/whip-project-targeting
7f47598635f027e2cb05ad33b66ed67627d20329
[ "BSD-3-Clause" ]
null
null
null
MuJoCo/modules/utils.py
mosesnah-shared/whip-project-targeting
7f47598635f027e2cb05ad33b66ed67627d20329
[ "BSD-3-Clause" ]
null
null
null
# [Built-in modules] import os import re import sys import shutil import time, datetime import math as myMath import glob # [3rd party modules] import cv2 import numpy as np import xml.etree.ElementTree as ET import sympy as sp from sympy.utilities.lambdify import lambdify, implemented_function from scipy.special import lambertw from scipy.integrate import quad from scipy.spatial.transform import Rotation as R # [Local modules] from modules.constants import Constants class MyVideo: """ Description ---------- Arguments --------- Returns ------- """ def __init__( self, vid_dir = None, height = 1440, width = 850, fps = 60 ): # self.height = height # self.width = width self.height = 2880 self.width = 1800 self.vid_dir = vid_dir if not None else "." self.fps = fps fourcc = cv2.VideoWriter_fourcc( *'MP4V' ) # 4-character code of codec used to compress the frames. # For example, VideoWriter::fourcc('P','I','M','1') is a MPEG-1 codec, # VideoWriter::fourcc('M','J','P','G') is a motion-jpeg codec etc. # List of codes can be obtained at Video Codecs by FOURCC page. # self.outVideo = cv2.VideoWriter( self.vid_dir + "/video.mp4", fourcc, fps, ( self.height, self.width ) ) self.outVideo = cv2.VideoWriter( self.vid_dir + "/video.mp4", fourcc, fps, ( self.height//2, self.width//2 ) ) def write( self, myViewer ): data = myViewer.read_pixels( self.height, self.width, depth = False ) # Get the pixel from the render screen data = cv2.cvtColor( data, cv2.COLOR_BGR2RGB ) # data = cv2.resize( data,( self.height, self.width ) ) data = cv2.resize( data,( self.height//2, self.width//2 ) ) self.outVideo.write( np.flip( data, axis = 0 ) ) def release( self ): self.outVideo.release() def length_elem2elem( mjModel, mjData, elem_name1, elem_name2 ): type1 = get_elem_type( mjModel, elem_name1 ) type2 = get_elem_type( mjModel, elem_name2 ) # The euclidean distance between two elements, calling using "get_geom_xpos" or "get_site_xpos" or "get_body_xpos" methods return np.linalg.norm( getattr( mjData, "get_" + type1 + "_" + "xpos" )( elem_name1 ) - getattr( mjData, "get_" + type2 + "_" + "xpos" )( elem_name2 ) , ord = 2 ) def get_elem_type( mjModel, elem_name ): """ The naming convention of our mujoco simulation is "{elem}_name", where elem = [geom, site, body] The string before the first underbar '_' describes the elem(ent) of the model. This function parses the string and returns the first string (i.e., the element of the model) """ return elem_name.split( '_' )[ 0 ] # Parse and get the first string before "_" def get_property( mjModel, elem_name, prop_name ): # Get the property of the name # The name of the elements start with "XXXX_", hence getting the string before the underbar. type = get_elem_type( mjModel, elem_name ) for idx, s in enumerate( getattr( mjModel, type + "_" + "names" ) ): # run through the list of "geom_names" or "body_names" if elem_name == s: tmp = getattr( mjModel, type + "_" + prop_name ) return tmp[ idx ] # If couldn't match in list, raise error raise NameError( 'Cannot find geom_name with {0} in list, please check'.format( elem_name ) ) def snake2camel( s ): """ Switch string s from snake_form_naming to CamelCase """ return ''.join( word.title() for word in s.split( '_' ) ) def camel2snake( s ): """ Switch string s from CamelCase to snake_form_naming [REF] https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case """ re.sub( r'(?<!^)(?=[A-Z])', '_', s ).lower() def clear_dir( dir ): """ Cleaning up the contents in the directory """ def args_cleanup( args, s ): """ Description ----------- Clean-up the substring s for keys in args Arguments --------- args: The dictionary to be parsed s : Substring to be discarded. e.g. s = '--', then "--record" --> "record" """ if not isinstance( args, dict ) or not isinstance( s, str ): raise ValueError( "Wrong input type. args should be type dict and s should be type str. {0:} and {1:} are rather given".format( type( args ), type( str ) ) ) for old_key in list( args ) : new_key = old_key.replace( s, '' ) args[ new_key ] = args.pop( old_key ) return args def rot2quat( rot ): # Taking the SO(3) matrix as an input and return the quaternion return quat def euler2quaternion( euler_angs ): """ Description ----------- This code is directly from the following reference [REF] https://computergraphics.stackexchange.com/questions/8195/how-to-convert-euler-angles-to-quaternions-and-get-the-same-euler-angles-back-fr Converting a R4 quaternion vector (w, x, y, z) to Euler Angle (Roll, Pitch, Yaw) Arguments --------- [NAME] [TYPE] [DESCRIPTION] (1) yaw, pitch, roll The euler angles of the given quaternion vector. [OUTPUTS] ----------- [NAME] [TYPE] [DESCRIPTION] (1) quatVec List The quaternion vector, ordered in w, x, y and z """ yaw, pitch, roll = euler_angs[ : ] cy = np.cos( yaw * 0.5 ) sy = np.sin( yaw * 0.5 ) cp = np.cos( pitch * 0.5 ) sp = np.sin( pitch * 0.5 ) cr = np.cos( roll * 0.5 ) sr = np.sin( roll * 0.5 ) w = cr * cp * cy + sr * sp * sy; x = sr * cp * cy - cr * sp * sy; y = cr * sp * cy + sr * cp * sy; z = cr * cp * sy - sr * sp * cy; return w,x,y,z def quaternion2euler( quatVec ): # Inputting quaternion matrix and outputing the yaw, pitch, roll of the euler angle. """ Description ----------- Converting a R4 quaternion vector (w, x, y, z) to Euler Angle (Roll, Pitch, Yaw) This code is directly from the following reference [REF] https://computergraphics.stackexchange.com/questions/8195/how-to-convert-euler-angles-to-quaternions-and-get-the-same-euler-angles-back-fr Arguments --------- [NAME] [TYPE] [DESCRIPTION] (1) quatVec List The quaternion vector, ordered in w, x, y and z Outputs -------- [NAME] [TYPE] [DESCRIPTION] (1) yaw, pitch, roll The euler angles of the given quaternion vector. """ if len( quatVec ) != 4: raise ValueError( "Wrong size of input argument. Given size is [{0:d}] while it should be 4".format( len( quatVec ) ) ) w, x, y ,z = quatVec[:] t0 = + 2.0 * ( w * x + y * z ) t1 = + 1.0 - 2.0 * ( x * x + y * y ) roll = myMath.atan2( t0, t1 ) t2 = + 2.0 * ( w * y - z * x ) t2 = + 1.0 if t2 > +1.0 else t2 t2 = - 1.0 if t2 < -1.0 else t2 pitch = myMath.asin( t2 ) t3 = + 2.0 * ( w * z + x * y ) t4 = + 1.0 - 2.0 * ( y * y + z * z ) yaw = myMath.atan2( t3, t4 ) return yaw, pitch, roll def str2bool( s ): """ Description: ---------- Converting an input string to a boolean Arguments: ---------- [NAME] [TYPE] [DESCRIPTION] (1) s dict, str The string which Returns: ---------- True/False depending on the given input strin gv """ if isinstance( s, dict ): for key, _ in s.items(): s[ key ] = str2bool( s[ key ] ) else: return v.lower() in ( "yes", "true", "t", "1" ) def str2float( s ): """ Description: ---------- Converting an input string to a float arraay Arguments: ---------- [NAME] [TYPE] [DESCRIPTION] (1) s str The string which will be parsed to float array Returns: ---------- The parsed float array """ if not isinstance( s, str ): raise ValueError( "Input argument should be string, but {} is given".format( type( s ) ) ) return [ float( i ) for i in re.findall( r"[-+]?\d*\.\d+|[-+]?\d+", s ) ] def my_mkdir( ): dir = Constants.TMP_DIR # Temporarily saving at tmp dir += datetime.datetime.now().strftime( "%Y%m%d_%H%M%S/" ) # Appending the date when this directory is called. if not os.path.exists( dir ): # If directory not exist os.makedirs( dir, exist_ok = True ) # mkdir -p functionality via exist_ok return dir def my_mvdir( from_dir, to_dir ): shutil.move( from_dir , to_dir ) def my_rmdir( dir ): if not isinstance( dir, str ): raise ValueError( "Input directory should be a str, {} is given".format( type ( dir ) ) ) try: shutil.rmtree( dir ) except: print( "{0:s} Doesn't exist, hence cannot remove the directory".format( dir ) ) print( "Erasing Directory [{0:s}]".format( dir ) ) def my_print( **kwargs ): """ Description: ---------- ** double asterisk means giving the argument as dictionary By using double asterisk "kwargs" as input argument, Arguments: ---------- Returns: ---------- """ prec = kwargs[ "prec" ] if "prec" in kwargs else 5 f = kwargs[ "file" ] if "file" in kwargs else sys.stdout # If there is a keyword called "file" then use that as our standard output tmpMaxLen = len( max( kwargs.keys( ), key = len ) ) # Getting the maximum length of a string list for args in kwargs: if 'file' == args.lower( ): # Ignore the file's value, since it should not be added to the "output.txt" log file. continue print( "[{1:{0}s}]:".format( tmpMaxLen, args ), end = ' ', file = f ) # Printing out the name of the array # {1:{0}s} Enables to set a variable as format length. tmpData = kwargs[ args ] if isinstance( tmpData, ( float, int ) ): tmpPrint = "{2:{1}.{0}f}".format( prec, prec + 2, tmpData ) elif isinstance( tmpData, list ): tmpPrint = np.array2string( np.array( tmpData ).flatten(), precision = prec, separator = ',' ) elif isinstance( tmpData, np.ndarray ): tmpPrint = np.array2string( tmpData.flatten() , precision = prec, separator = ',' ) elif isinstance( tmpData, str ): tmpPrint = tmpData elif tmpData is None: tmpPrint = "None" else: raise ValueError( "CHECK INPUT") print( tmpPrint, file = f ) def solve_eq_posture( q0 ): q1_0 = q0[ 0 ] q2_0 = q0[ 1 ] q3_0 = q0[ 2 ] q4_0 = q0[ 3 ] q1 = sp.Symbol( 'q1' ) q2 = sp.Symbol( 'q2' ) q3 = sp.Symbol( 'q3' ) q4 = sp.Symbol( 'q4' ) eqn1 = 0.52444712807465876380774716380984*sp.cos(q2)*sp.sin(q1) - 0.12721953522735995889547666592989*sp.cos(q1)*sp.sin(q2) - 0.05501625493258266441642945210333*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) - 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) - 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) + 0.1762293392050615636890142923221*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) + 0.1762293392050615636890142923221*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) - 0.063807174539763700238381716189906*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) + 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) + 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) + 0.1762293392050615636890142923221*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q1 - q1_0 eqn2 = 0.1966778910733553153988850681344*sp.cos(q1)*sp.sin(q2) - 0.12721953522735995889547666592989*sp.cos(q2)*sp.sin(q1) + 0.020788410744410568131712579997838*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) + 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) + 0.066089435759419945526360606891103*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) - 0.042749427781976545581699156173272*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) - 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) + 0.015478241093474287559672575298464*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) - 0.066089435759419945526360606891103*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) - 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) - 0.042749427781976545581699156173272*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q2 - q2_0 eqn3 = 0.1637248203220158515591720060911*sp.cos(q2)*sp.sin(q1) - 0.061864967327922570916598488111049*sp.cos(q1)*sp.sin(q2) - 0.083555731966853175052278857037891*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) - 0.019919678510073035582195188908372*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) - 0.020788410744410568131712579997838*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) + 0.05501625493258266441642945210333*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) + 0.05501625493258266441642945210333*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) - 0.019919678510073035582195188908372*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) + 0.020788410744410568131712579997838*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) + 0.019919678510073035582195188908372*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) + 0.05501625493258266441642945210333*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q3 - q3_0 eqn4 = 0.046062245513354471704303705337225*sp.cos(q1)*sp.sin(q2) - 0.18988602913048024944941971625667*sp.cos(q2)*sp.sin(q1) + 0.019919678510073035582195188908372*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) + 0.10117159250577656415259752975544*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) + 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) - 0.063807174539763700238381716189906*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) - 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) + 0.10117159250577656415259752975544*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) - 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) - 0.10117159250577656415259752975544*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) - 0.063807174539763700238381716189906*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q4 - q4_0 sol = sp.solvers.nsolve( ( eqn1, eqn2, eqn3, eqn4 ), ( q1, q2, q3, q4 ), q0 ) sol = np.array( sol ) return np.array( [ sol[ 0 ][ 0 ], sol[ 1 ][ 0 ], sol[ 2 ][ 0 ], sol[ 3 ][ 0 ] ] ) if __name__ == '__main__': pass
42.196765
846
0.570808
import os import re import sys import shutil import time, datetime import math as myMath import glob import cv2 import numpy as np import xml.etree.ElementTree as ET import sympy as sp from sympy.utilities.lambdify import lambdify, implemented_function from scipy.special import lambertw from scipy.integrate import quad from scipy.spatial.transform import Rotation as R from modules.constants import Constants class MyVideo: def __init__( self, vid_dir = None, height = 1440, width = 850, fps = 60 ): self.height = 2880 self.width = 1800 self.vid_dir = vid_dir if not None else "." self.fps = fps fourcc = cv2.VideoWriter_fourcc( *'MP4V' ) self.outVideo = cv2.VideoWriter( self.vid_dir + "/video.mp4", fourcc, fps, ( self.height//2, self.width//2 ) ) def write( self, myViewer ): data = myViewer.read_pixels( self.height, self.width, depth = False ) data = cv2.cvtColor( data, cv2.COLOR_BGR2RGB ) data = cv2.resize( data,( self.height//2, self.width//2 ) ) self.outVideo.write( np.flip( data, axis = 0 ) ) def release( self ): self.outVideo.release() def length_elem2elem( mjModel, mjData, elem_name1, elem_name2 ): type1 = get_elem_type( mjModel, elem_name1 ) type2 = get_elem_type( mjModel, elem_name2 ) return np.linalg.norm( getattr( mjData, "get_" + type1 + "_" + "xpos" )( elem_name1 ) - getattr( mjData, "get_" + type2 + "_" + "xpos" )( elem_name2 ) , ord = 2 ) def get_elem_type( mjModel, elem_name ): return elem_name.split( '_' )[ 0 ] def get_property( mjModel, elem_name, prop_name ): type = get_elem_type( mjModel, elem_name ) for idx, s in enumerate( getattr( mjModel, type + "_" + "names" ) ): if elem_name == s: tmp = getattr( mjModel, type + "_" + prop_name ) return tmp[ idx ] raise NameError( 'Cannot find geom_name with {0} in list, please check'.format( elem_name ) ) def snake2camel( s ): return ''.join( word.title() for word in s.split( '_' ) ) def camel2snake( s ): re.sub( r'(?<!^)(?=[A-Z])', '_', s ).lower() def clear_dir( dir ): def args_cleanup( args, s ): if not isinstance( args, dict ) or not isinstance( s, str ): raise ValueError( "Wrong input type. args should be type dict and s should be type str. {0:} and {1:} are rather given".format( type( args ), type( str ) ) ) for old_key in list( args ) : new_key = old_key.replace( s, '' ) args[ new_key ] = args.pop( old_key ) return args def rot2quat( rot ): # Taking the SO(3) matrix as an input and return the quaternion return quat def euler2quaternion( euler_angs ): yaw, pitch, roll = euler_angs[ : ] cy = np.cos( yaw * 0.5 ) sy = np.sin( yaw * 0.5 ) cp = np.cos( pitch * 0.5 ) sp = np.sin( pitch * 0.5 ) cr = np.cos( roll * 0.5 ) sr = np.sin( roll * 0.5 ) w = cr * cp * cy + sr * sp * sy; x = sr * cp * cy - cr * sp * sy; y = cr * sp * cy + sr * cp * sy; z = cr * cp * sy - sr * sp * cy; return w,x,y,z def quaternion2euler( quatVec ): # Inputting quaternion matrix and outputing the yaw, pitch, roll of the euler angle. if len( quatVec ) != 4: raise ValueError( "Wrong size of input argument. Given size is [{0:d}] while it should be 4".format( len( quatVec ) ) ) w, x, y ,z = quatVec[:] t0 = + 2.0 * ( w * x + y * z ) t1 = + 1.0 - 2.0 * ( x * x + y * y ) roll = myMath.atan2( t0, t1 ) t2 = + 2.0 * ( w * y - z * x ) t2 = + 1.0 if t2 > +1.0 else t2 t2 = - 1.0 if t2 < -1.0 else t2 pitch = myMath.asin( t2 ) t3 = + 2.0 * ( w * z + x * y ) t4 = + 1.0 - 2.0 * ( y * y + z * z ) yaw = myMath.atan2( t3, t4 ) return yaw, pitch, roll def str2bool( s ): if isinstance( s, dict ): for key, _ in s.items(): s[ key ] = str2bool( s[ key ] ) else: return v.lower() in ( "yes", "true", "t", "1" ) def str2float( s ): if not isinstance( s, str ): raise ValueError( "Input argument should be string, but {} is given".format( type( s ) ) ) return [ float( i ) for i in re.findall( r"[-+]?\d*\.\d+|[-+]?\d+", s ) ] def my_mkdir( ): dir = Constants.TMP_DIR # Temporarily saving at tmp dir += datetime.datetime.now().strftime( "%Y%m%d_%H%M%S/" ) # Appending the date when this directory is called. if not os.path.exists( dir ): # If directory not exist os.makedirs( dir, exist_ok = True ) # mkdir -p functionality via exist_ok return dir def my_mvdir( from_dir, to_dir ): shutil.move( from_dir , to_dir ) def my_rmdir( dir ): if not isinstance( dir, str ): raise ValueError( "Input directory should be a str, {} is given".format( type ( dir ) ) ) try: shutil.rmtree( dir ) except: print( "{0:s} Doesn't exist, hence cannot remove the directory".format( dir ) ) print( "Erasing Directory [{0:s}]".format( dir ) ) def my_print( **kwargs ): prec = kwargs[ "prec" ] if "prec" in kwargs else 5 f = kwargs[ "file" ] if "file" in kwargs else sys.stdout tmpMaxLen = len( max( kwargs.keys( ), key = len ) ) for args in kwargs: if 'file' == args.lower( ): continue print( "[{1:{0}s}]:".format( tmpMaxLen, args ), end = ' ', file = f ) # Printing out the name of the array # {1:{0}s} Enables to set a variable as format length. tmpData = kwargs[ args ] if isinstance( tmpData, ( float, int ) ): tmpPrint = "{2:{1}.{0}f}".format( prec, prec + 2, tmpData ) elif isinstance( tmpData, list ): tmpPrint = np.array2string( np.array( tmpData ).flatten(), precision = prec, separator = ',' ) elif isinstance( tmpData, np.ndarray ): tmpPrint = np.array2string( tmpData.flatten() , precision = prec, separator = ',' ) elif isinstance( tmpData, str ): tmpPrint = tmpData elif tmpData is None: tmpPrint = "None" else: raise ValueError( "CHECK INPUT") print( tmpPrint, file = f ) def solve_eq_posture( q0 ): q1_0 = q0[ 0 ] q2_0 = q0[ 1 ] q3_0 = q0[ 2 ] q4_0 = q0[ 3 ] q1 = sp.Symbol( 'q1' ) q2 = sp.Symbol( 'q2' ) q3 = sp.Symbol( 'q3' ) q4 = sp.Symbol( 'q4' ) eqn1 = 0.52444712807465876380774716380984*sp.cos(q2)*sp.sin(q1) - 0.12721953522735995889547666592989*sp.cos(q1)*sp.sin(q2) - 0.05501625493258266441642945210333*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) - 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) - 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) + 0.1762293392050615636890142923221*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) + 0.1762293392050615636890142923221*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) - 0.063807174539763700238381716189906*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) + 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) + 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) + 0.1762293392050615636890142923221*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q1 - q1_0 eqn2 = 0.1966778910733553153988850681344*sp.cos(q1)*sp.sin(q2) - 0.12721953522735995889547666592989*sp.cos(q2)*sp.sin(q1) + 0.020788410744410568131712579997838*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) + 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) + 0.066089435759419945526360606891103*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) - 0.042749427781976545581699156173272*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) - 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) + 0.015478241093474287559672575298464*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) - 0.066089435759419945526360606891103*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) - 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) - 0.042749427781976545581699156173272*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q2 - q2_0 eqn3 = 0.1637248203220158515591720060911*sp.cos(q2)*sp.sin(q1) - 0.061864967327922570916598488111049*sp.cos(q1)*sp.sin(q2) - 0.083555731966853175052278857037891*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) - 0.019919678510073035582195188908372*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) - 0.020788410744410568131712579997838*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) + 0.05501625493258266441642945210333*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) + 0.05501625493258266441642945210333*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) - 0.019919678510073035582195188908372*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) + 0.020788410744410568131712579997838*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) + 0.019919678510073035582195188908372*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) + 0.05501625493258266441642945210333*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q3 - q3_0 eqn4 = 0.046062245513354471704303705337225*sp.cos(q1)*sp.sin(q2) - 0.18988602913048024944941971625667*sp.cos(q2)*sp.sin(q1) + 0.019919678510073035582195188908372*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) + 0.10117159250577656415259752975544*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) + 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) - 0.063807174539763700238381716189906*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) - 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) + 0.10117159250577656415259752975544*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) - 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) - 0.10117159250577656415259752975544*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) - 0.063807174539763700238381716189906*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q4 - q4_0 sol = sp.solvers.nsolve( ( eqn1, eqn2, eqn3, eqn4 ), ( q1, q2, q3, q4 ), q0 ) sol = np.array( sol ) return np.array( [ sol[ 0 ][ 0 ], sol[ 1 ][ 0 ], sol[ 2 ][ 0 ], sol[ 3 ][ 0 ] ] ) if __name__ == '__main__': pass
true
true
f7167e61cefc29e05e76cf5f35782284b46a20aa
4,682
py
Python
sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/aio/operations/_operations.py
ankitarorabit/azure-sdk-for-python
dd90281cbad9400f8080754a5ef2f56791a5a88f
[ "MIT" ]
3
2020-06-23T02:25:27.000Z
2021-09-07T18:48:11.000Z
sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/aio/operations/_operations.py
ankitarorabit/azure-sdk-for-python
dd90281cbad9400f8080754a5ef2f56791a5a88f
[ "MIT" ]
510
2019-07-17T16:11:19.000Z
2021-08-02T08:38:32.000Z
sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/aio/operations/_operations.py
ankitarorabit/azure-sdk-for-python
dd90281cbad9400f8080754a5ef2f56791a5a88f
[ "MIT" ]
5
2019-09-04T12:51:37.000Z
2020-09-16T07:28:40.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class Operations: """Operations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.netapp.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs: Any ) -> AsyncIterable["_models.OperationListResult"]: """Describes the Resource Provider. Lists all of the available Microsoft.NetApp Rest API operations. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OperationListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.netapp.models.OperationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-02-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('OperationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/providers/Microsoft.NetApp/operations'} # type: ignore
43.757009
133
0.65912
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class Operations: models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs: Any ) -> AsyncIterable["_models.OperationListResult"]: cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-02-01" accept = "application/json" def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: url = self.list.metadata['url'] query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('OperationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/providers/Microsoft.NetApp/operations'}
true
true
f7167ea0d6c0f9e11b4a88a19c5af9d2c9a92a69
17,093
py
Python
intersight/model/niatelemetry_supervisor_module_details.py
CiscoDevNet/intersight-python
04b721f37c3044646a91c185c7259edfb991557a
[ "Apache-2.0" ]
5
2021-12-16T15:13:32.000Z
2022-03-29T16:09:54.000Z
intersight/model/niatelemetry_supervisor_module_details.py
CiscoDevNet/intersight-python
04b721f37c3044646a91c185c7259edfb991557a
[ "Apache-2.0" ]
4
2022-01-25T19:05:51.000Z
2022-03-29T20:18:37.000Z
intersight/model/niatelemetry_supervisor_module_details.py
CiscoDevNet/intersight-python
04b721f37c3044646a91c185c7259edfb991557a
[ "Apache-2.0" ]
2
2020-07-07T15:01:08.000Z
2022-01-31T04:27:35.000Z
""" Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. The Intersight OpenAPI document defines the complete set of properties that are returned in the HTTP response. From that perspective, a client can expect that no additional properties are returned, unless these properties are explicitly defined in the OpenAPI document. However, when a client uses an older version of the Intersight OpenAPI document, the server may send additional properties because the software is more recent than the client. In that case, the client may receive properties that it does not know about. Some generated SDKs perform a strict validation of the HTTP response body against the OpenAPI document. # noqa: E501 The version of the OpenAPI document: 1.0.9-4950 Contact: intersight@cisco.com Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from intersight.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) def lazy_import(): from intersight.model.asset_device_registration_relationship import AssetDeviceRegistrationRelationship from intersight.model.display_names import DisplayNames from intersight.model.mo_base_mo import MoBaseMo from intersight.model.mo_base_mo_relationship import MoBaseMoRelationship from intersight.model.mo_tag import MoTag from intersight.model.mo_version_context import MoVersionContext from intersight.model.niatelemetry_supervisor_module_details_all_of import NiatelemetrySupervisorModuleDetailsAllOf globals()['AssetDeviceRegistrationRelationship'] = AssetDeviceRegistrationRelationship globals()['DisplayNames'] = DisplayNames globals()['MoBaseMo'] = MoBaseMo globals()['MoBaseMoRelationship'] = MoBaseMoRelationship globals()['MoTag'] = MoTag globals()['MoVersionContext'] = MoVersionContext globals()['NiatelemetrySupervisorModuleDetailsAllOf'] = NiatelemetrySupervisorModuleDetailsAllOf class NiatelemetrySupervisorModuleDetails(ModelComposed): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { ('class_id',): { 'NIATELEMETRY.SUPERVISORMODULEDETAILS': "niatelemetry.SupervisorModuleDetails", }, ('object_type',): { 'NIATELEMETRY.SUPERVISORMODULEDETAILS': "niatelemetry.SupervisorModuleDetails", }, } validations = { } @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { 'class_id': (str,), # noqa: E501 'object_type': (str,), # noqa: E501 'dn': (str,), # noqa: E501 'hw_ver': (str,), # noqa: E501 'model': (str,), # noqa: E501 'record_type': (str,), # noqa: E501 'record_version': (str,), # noqa: E501 'serial': (str,), # noqa: E501 'site_name': (str,), # noqa: E501 'registered_device': (AssetDeviceRegistrationRelationship,), # noqa: E501 'account_moid': (str,), # noqa: E501 'create_time': (datetime,), # noqa: E501 'domain_group_moid': (str,), # noqa: E501 'mod_time': (datetime,), # noqa: E501 'moid': (str,), # noqa: E501 'owners': ([str], none_type,), # noqa: E501 'shared_scope': (str,), # noqa: E501 'tags': ([MoTag], none_type,), # noqa: E501 'version_context': (MoVersionContext,), # noqa: E501 'ancestors': ([MoBaseMoRelationship], none_type,), # noqa: E501 'parent': (MoBaseMoRelationship,), # noqa: E501 'permission_resources': ([MoBaseMoRelationship], none_type,), # noqa: E501 'display_names': (DisplayNames,), # noqa: E501 } @cached_property def discriminator(): val = { } if not val: return None return {'class_id': val} attribute_map = { 'class_id': 'ClassId', # noqa: E501 'object_type': 'ObjectType', # noqa: E501 'dn': 'Dn', # noqa: E501 'hw_ver': 'HwVer', # noqa: E501 'model': 'Model', # noqa: E501 'record_type': 'RecordType', # noqa: E501 'record_version': 'RecordVersion', # noqa: E501 'serial': 'Serial', # noqa: E501 'site_name': 'SiteName', # noqa: E501 'registered_device': 'RegisteredDevice', # noqa: E501 'account_moid': 'AccountMoid', # noqa: E501 'create_time': 'CreateTime', # noqa: E501 'domain_group_moid': 'DomainGroupMoid', # noqa: E501 'mod_time': 'ModTime', # noqa: E501 'moid': 'Moid', # noqa: E501 'owners': 'Owners', # noqa: E501 'shared_scope': 'SharedScope', # noqa: E501 'tags': 'Tags', # noqa: E501 'version_context': 'VersionContext', # noqa: E501 'ancestors': 'Ancestors', # noqa: E501 'parent': 'Parent', # noqa: E501 'permission_resources': 'PermissionResources', # noqa: E501 'display_names': 'DisplayNames', # noqa: E501 } required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', '_composed_instances', '_var_name_to_model_instances', '_additional_properties_model_instances', ]) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """NiatelemetrySupervisorModuleDetails - a model defined in OpenAPI Args: Keyword Args: class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.. defaults to "niatelemetry.SupervisorModuleDetails", must be one of ["niatelemetry.SupervisorModuleDetails", ] # noqa: E501 object_type (str): The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property.. defaults to "niatelemetry.SupervisorModuleDetails", must be one of ["niatelemetry.SupervisorModuleDetails", ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) dn (str): Dn of the supervisor module in APIC.. [optional] # noqa: E501 hw_ver (str): Hardware version of supervisor module.. [optional] # noqa: E501 model (str): Model of the supervisor module.. [optional] # noqa: E501 record_type (str): Type of record DCNM / APIC / SE. This determines the type of platform where inventory was collected.. [optional] # noqa: E501 record_version (str): Version of record being pushed. This determines what was the API version for data available from the device.. [optional] # noqa: E501 serial (str): Serial number of the supervisor module.. [optional] # noqa: E501 site_name (str): Name of the APIC site from which this data is being collected.. [optional] # noqa: E501 registered_device (AssetDeviceRegistrationRelationship): [optional] # noqa: E501 account_moid (str): The Account ID for this managed object.. [optional] # noqa: E501 create_time (datetime): The time when this managed object was created.. [optional] # noqa: E501 domain_group_moid (str): The DomainGroup ID for this managed object.. [optional] # noqa: E501 mod_time (datetime): The time when this managed object was last modified.. [optional] # noqa: E501 moid (str): The unique identifier of this Managed Object instance.. [optional] # noqa: E501 owners ([str], none_type): [optional] # noqa: E501 shared_scope (str): Intersight provides pre-built workflows, tasks and policies to end users through global catalogs. Objects that are made available through global catalogs are said to have a 'shared' ownership. Shared objects are either made globally available to all end users or restricted to end users based on their license entitlement. Users can use this property to differentiate the scope (global or a specific license tier) to which a shared MO belongs.. [optional] # noqa: E501 tags ([MoTag], none_type): [optional] # noqa: E501 version_context (MoVersionContext): [optional] # noqa: E501 ancestors ([MoBaseMoRelationship], none_type): An array of relationships to moBaseMo resources.. [optional] # noqa: E501 parent (MoBaseMoRelationship): [optional] # noqa: E501 permission_resources ([MoBaseMoRelationship], none_type): An array of relationships to moBaseMo resources.. [optional] # noqa: E501 display_names (DisplayNames): [optional] # noqa: E501 """ class_id = kwargs.get('class_id', "niatelemetry.SupervisorModuleDetails") object_type = kwargs.get('object_type', "niatelemetry.SupervisorModuleDetails") _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) constant_args = { '_check_type': _check_type, '_path_to_item': _path_to_item, '_spec_property_naming': _spec_property_naming, '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } required_args = { 'class_id': class_id, 'object_type': object_type, } model_args = {} model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] for var_name, var_value in required_args.items(): setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): if var_name in unused_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ not self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) @cached_property def _composed_schemas(): # we need this here to make our import statements work # we must store _composed_schemas in here so the code is only run # when we invoke this method. If we kept this at the class # level we would get an error beause the class level # code would be run when this module is imported, and these composed # classes don't exist yet because their module has not finished # loading lazy_import() return { 'anyOf': [ ], 'allOf': [ MoBaseMo, NiatelemetrySupervisorModuleDetailsAllOf, ], 'oneOf': [ ], }
54.091772
1,678
0.639677
import re import sys from intersight.model_utils import ( ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) def lazy_import(): from intersight.model.asset_device_registration_relationship import AssetDeviceRegistrationRelationship from intersight.model.display_names import DisplayNames from intersight.model.mo_base_mo import MoBaseMo from intersight.model.mo_base_mo_relationship import MoBaseMoRelationship from intersight.model.mo_tag import MoTag from intersight.model.mo_version_context import MoVersionContext from intersight.model.niatelemetry_supervisor_module_details_all_of import NiatelemetrySupervisorModuleDetailsAllOf globals()['AssetDeviceRegistrationRelationship'] = AssetDeviceRegistrationRelationship globals()['DisplayNames'] = DisplayNames globals()['MoBaseMo'] = MoBaseMo globals()['MoBaseMoRelationship'] = MoBaseMoRelationship globals()['MoTag'] = MoTag globals()['MoVersionContext'] = MoVersionContext globals()['NiatelemetrySupervisorModuleDetailsAllOf'] = NiatelemetrySupervisorModuleDetailsAllOf class NiatelemetrySupervisorModuleDetails(ModelComposed): allowed_values = { ('class_id',): { 'NIATELEMETRY.SUPERVISORMODULEDETAILS': "niatelemetry.SupervisorModuleDetails", }, ('object_type',): { 'NIATELEMETRY.SUPERVISORMODULEDETAILS': "niatelemetry.SupervisorModuleDetails", }, } validations = { } @cached_property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type,) _nullable = False @cached_property def openapi_types(): lazy_import() return { 'class_id': (str,), 'object_type': (str,), 'dn': (str,), 'hw_ver': (str,), 'model': (str,), 'record_type': (str,), 'record_version': (str,), 'serial': (str,), 'site_name': (str,), 'registered_device': (AssetDeviceRegistrationRelationship,), 'account_moid': (str,), 'create_time': (datetime,), 'domain_group_moid': (str,), 'mod_time': (datetime,), 'moid': (str,), 'owners': ([str], none_type,), 'shared_scope': (str,), 'tags': ([MoTag], none_type,), 'version_context': (MoVersionContext,), 'ancestors': ([MoBaseMoRelationship], none_type,), 'parent': (MoBaseMoRelationship,), 'permission_resources': ([MoBaseMoRelationship], none_type,), 'display_names': (DisplayNames,), } @cached_property def discriminator(): val = { } if not val: return None return {'class_id': val} attribute_map = { 'class_id': 'ClassId', 'object_type': 'ObjectType', 'dn': 'Dn', 'hw_ver': 'HwVer', 'model': 'Model', 'record_type': 'RecordType', 'record_version': 'RecordVersion', 'serial': 'Serial', 'site_name': 'SiteName', 'registered_device': 'RegisteredDevice', 'account_moid': 'AccountMoid', 'create_time': 'CreateTime', 'domain_group_moid': 'DomainGroupMoid', 'mod_time': 'ModTime', 'moid': 'Moid', 'owners': 'Owners', 'shared_scope': 'SharedScope', 'tags': 'Tags', 'version_context': 'VersionContext', 'ancestors': 'Ancestors', 'parent': 'Parent', 'permission_resources': 'PermissionResources', 'display_names': 'DisplayNames', } required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', '_composed_instances', '_var_name_to_model_instances', '_additional_properties_model_instances', ]) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): class_id = kwargs.get('class_id', "niatelemetry.SupervisorModuleDetails") object_type = kwargs.get('object_type', "niatelemetry.SupervisorModuleDetails") _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) constant_args = { '_check_type': _check_type, '_path_to_item': _path_to_item, '_spec_property_naming': _spec_property_naming, '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } required_args = { 'class_id': class_id, 'object_type': object_type, } model_args = {} model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] for var_name, var_value in required_args.items(): setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): if var_name in unused_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ not self._additional_properties_model_instances: continue setattr(self, var_name, var_value) @cached_property def _composed_schemas(): # loading lazy_import() return { 'anyOf': [ ], 'allOf': [ MoBaseMo, NiatelemetrySupervisorModuleDetailsAllOf, ], 'oneOf': [ ], }
true
true
f7167ec21a6a129bda61142db392f78aae4d6960
271
py
Python
tests/database.py
tophat/ormar-postgres-extensions
88fcab5a73bc89090739c38f063191d8473957a5
[ "Apache-2.0" ]
6
2021-08-02T22:24:34.000Z
2022-03-21T08:59:22.000Z
tests/database.py
tophat/ormar-postgres-extensions
88fcab5a73bc89090739c38f063191d8473957a5
[ "Apache-2.0" ]
14
2021-08-03T00:03:55.000Z
2022-02-17T02:10:08.000Z
tests/database.py
tophat/ormar-postgres-extensions
88fcab5a73bc89090739c38f063191d8473957a5
[ "Apache-2.0" ]
2
2022-01-28T20:10:12.000Z
2022-02-09T16:49:01.000Z
import databases import sqlalchemy DB_HOST = "localhost" DB_NAME = "TEST_DATABASE" DATABASE_URL = databases.DatabaseURL( f"postgres://DEV_USER:DEV_PASSWORD@{DB_HOST}:5432/{DB_NAME}" ) database = databases.Database(str(DATABASE_URL)) metadata = sqlalchemy.MetaData()
24.636364
64
0.782288
import databases import sqlalchemy DB_HOST = "localhost" DB_NAME = "TEST_DATABASE" DATABASE_URL = databases.DatabaseURL( f"postgres://DEV_USER:DEV_PASSWORD@{DB_HOST}:5432/{DB_NAME}" ) database = databases.Database(str(DATABASE_URL)) metadata = sqlalchemy.MetaData()
true
true
f71680e22b485ad498455c52808137f6caab7e0c
910
py
Python
gammapy/stats/tests/test_significance.py
qpiel/gammapy
cfb976909e63f4d5d578e1495245c0baad69482b
[ "BSD-3-Clause" ]
null
null
null
gammapy/stats/tests/test_significance.py
qpiel/gammapy
cfb976909e63f4d5d578e1495245c0baad69482b
[ "BSD-3-Clause" ]
1
2020-10-29T19:55:46.000Z
2020-10-29T19:55:46.000Z
gammapy/stats/tests/test_significance.py
qpiel/gammapy
cfb976909e63f4d5d578e1495245c0baad69482b
[ "BSD-3-Clause" ]
null
null
null
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals from numpy.testing import assert_allclose from ...stats import ( significance_to_probability_normal, probability_to_significance_normal, probability_to_significance_normal_limit, significance_to_probability_normal_limit, ) def test_significance_to_probability_normal(): significance = 5 p = significance_to_probability_normal(significance) assert_allclose(p, 2.8665157187919328e-07) s = probability_to_significance_normal(p) assert_allclose(s, significance) def test_significance_to_probability_normal_limit(): significance = 5 p = significance_to_probability_normal_limit(significance) assert_allclose(p, 2.792513e-07) s = probability_to_significance_normal_limit(p) assert_allclose(s, significance)
32.5
82
0.806593
from __future__ import absolute_import, division, print_function, unicode_literals from numpy.testing import assert_allclose from ...stats import ( significance_to_probability_normal, probability_to_significance_normal, probability_to_significance_normal_limit, significance_to_probability_normal_limit, ) def test_significance_to_probability_normal(): significance = 5 p = significance_to_probability_normal(significance) assert_allclose(p, 2.8665157187919328e-07) s = probability_to_significance_normal(p) assert_allclose(s, significance) def test_significance_to_probability_normal_limit(): significance = 5 p = significance_to_probability_normal_limit(significance) assert_allclose(p, 2.792513e-07) s = probability_to_significance_normal_limit(p) assert_allclose(s, significance)
true
true
f716815fb86995f906bd4284b72bbcf1851ecedc
9,243
py
Python
ros_pkg/dock/scripts/dock_generator.py
introlab/securbot
0652ddf3e2dbcf0bb6ffcf76898749b67e443327
[ "Apache-2.0" ]
20
2019-03-13T13:37:51.000Z
2022-01-25T16:56:35.000Z
ros_pkg/dock/scripts/dock_generator.py
introlab/securbot
0652ddf3e2dbcf0bb6ffcf76898749b67e443327
[ "Apache-2.0" ]
15
2019-02-27T20:29:34.000Z
2020-08-24T19:44:20.000Z
ros_pkg/dock/scripts/dock_generator.py
introlab/securbot
0652ddf3e2dbcf0bb6ffcf76898749b67e443327
[ "Apache-2.0" ]
13
2019-07-31T00:47:49.000Z
2021-04-15T01:33:02.000Z
#!/usr/bin/env python """Provide docking motivation layer node.""" import rospy import json import math from enum import Enum from threading import Lock import tf from tf.transformations import euler_from_quaternion from std_msgs.msg import Bool from std_msgs.msg import Empty from geometry_msgs.msg import PoseStamped from sensor_msgs.msg import BatteryState from hbba_msgs.msg import Desire from hbba_msgs.msg import Intention from hbba_msgs.srv import AddDesires from hbba_msgs.srv import RemoveDesires class DockState(Enum): """Define dockig process states.""" idle = 0 # No dock required approaching = 1 # Driving to dock approach goal docking = 2 # Docking to station docked = 3 # Docked at station and dock required class DockGenerator: """Generate dock desires according to robot and dock state.""" def force_callback(self, msg): """Receive force docking command from electron.""" self.lock.acquire() self.force_docking = msg.data self.last_force = rospy.Time.now() self.lock.release() def battery_callback(self, msg): """Receive battery level from battery board.""" self.lock.acquire() if msg.percentage < self.min_percent: self.low_battery = True if msg.percentage > self.charge_percent: self.low_battery = False self.lock.release() def collision_callback(self, msg): """Receive collision events from collision detector.""" self.lock.acquire() if self.state == DockState.docking: self.finish_docking() self.lock.release() def intention_callback(self, msg): """Monitor current robot intention from hbba.""" self.lock.acquire() self.approach_active = self.approach_desire.id in msg.desires if self.state == DockState.docking: if self.loiter_desire.id in msg.desires: self.state = DockState.docked elif self.dock_desire.id not in msg.desires: self.restart_docking() if self.state == DockState.docked: if self.loiter_desire.id not in msg.desires: self.stop_docking() self.lock.release() def approach_callback(self, msg): """Set approach goal.""" self.lock.acquire() self.approach_goal['frame_id'] = msg.header.frame_id self.approach_goal['x'] = msg.pose.position.x self.approach_goal['y'] = msg.pose.position.y quat = ( msg.pose.orientation.w, msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z ) euler = euler_from_quaternion(quat) self.approach_goal['t'] = euler[2] self.lock.release() def start_docking(self): """Initialize docking sequence.""" self.add_desire([self.dock_desire]) self.restart_docking() def restart_docking(self): """Restart approach after interuption.""" self.approach_desire.params = json.dumps(self.approach_goal) self.add_desire([self.approach_desire]) self.state = DockState.approaching def finish_approach(self): """End approach phase.""" self.rem_desire([self.approach_desire.id]) self.state = DockState.docking def finish_docking(self): """End docking phase.""" self.add_desire([self.loiter_desire]) self.rem_desire([self.dock_desire.id]) def stop_docking(self): """Cancel docking process.""" if self.state == DockState.approaching: # both dock and approach must be removed self.rem_desire([ self.dock_desire.id, self.approach_desire.id ]) elif self.state == DockState.docking: # only dock desire must be removed self.rem_desire([self.dock_desire.id]) elif self.state == DockState.docked: # loiter desire must be removed self.rem_desire([self.loiter_desire.id]) self.state = DockState.idle def run(self): """Update desires and check if robot reached approach goal.""" rospy.Subscriber('force_docking', Bool, self.force_callback) rospy.Subscriber('collision', Empty, self.collision_callback) rospy.Subscriber('battery_state', BatteryState, self.battery_callback) rospy.Subscriber('approach_goal', PoseStamped, self.approach_callback) rospy.Subscriber('hbba/intention', Intention, self.intention_callback) tf_listener = tf.TransformListener() rate = rospy.Rate(1) while not rospy.is_shutdown(): rate.sleep() self.lock.acquire() # Check if force is expired now = rospy.Time.now() timeout = rospy.Duration(self.force_timeout) if now - self.last_force > timeout: self.force_docking = False # Check if we need to start docking if (self.force_docking or self.low_battery)\ and self.state == DockState.idle: self.start_docking() self.lock.release() continue # Check if we need to stop docking if not self.force_docking\ and not self.low_battery\ and self.state != DockState.idle: self.stop_docking() self.lock.release() continue # We are not approaching we cancel tf lookup if self.state != DockState.approaching or not self.approach_active: self.lock.release() continue # Lookup robot pose in map try: pos, quat = tf_listener.lookupTransform( self.map_frame, self.robot_frame, rospy.Time()) except (tf.Exception): self.lock.release() continue # Check if we reached our approach goal dx = pos[0] - self.approach_goal['x'] dy = pos[1] - self.approach_goal['y'] lin_dst = math.sqrt(dx*dx + dy*dy) angles = euler_from_quaternion(quat) yaw_dst = angles[2] - self.approach_goal['t'] if lin_dst < self.appr_lin_tol and abs(yaw_dst) < self.appr_yaw_tol: self.finish_approach() self.lock.release() def __init__(self): """Initialize dock generator node.""" self.lock = Lock() self.low_battery = False self.force_docking = False self.approach_active = False self.state = DockState.idle self.last_force = rospy.Time() rospy.init_node('dock_generator') rospy.loginfo('waiting for add desire to be availble') rospy.wait_for_service('/hbba/add_desires') self.add_desire = rospy.ServiceProxy( '/hbba/add_desires', AddDesires) rospy.loginfo('add desire registered') rospy.loginfo('waiting for remove desire to be availbe') rospy.wait_for_service('/hbba/remove_desires') self.rem_desire = rospy.ServiceProxy( '/hbba/remove_desires', RemoveDesires) rospy.loginfo('remove desire registered') self.map_frame = rospy.get_param('~map_frame', 'map') self.robot_frame = rospy.get_param('~robot_frame', 'base_footprint') self.appr_lin_tol = rospy.get_param('~appr_lin_tol', 0.40) self.appr_yaw_tol = rospy.get_param('~appr_yaw_tol', 0.1) self.min_percent = rospy.get_param('~min_percent', 30) self.charge_percent = rospy.get_param('~charge_percent', 80) self.undock_time = rospy.get_param('~undock_time', 4.0) self.force_timeout = rospy.get_param('~force_timeout', 10.0) self.approach_goal = dict() self.approach_goal['x'] = rospy.get_param('approach/x', 0.0) self.approach_goal['y'] = rospy.get_param('approach/y', 0.0) self.approach_goal['t'] = rospy.get_param('approach/t', 0.0) self.approach_goal['frame_id'] = self.map_frame self.approach_desire = Desire() self.approach_desire.id = 'dock_approach' self.approach_desire.type = 'GoTo' self.approach_desire.intensity = 1 self.approach_desire.utility = 1 self.approach_desire.security = False self.dock_desire = Desire() self.dock_desire.id = 'dock_dock' self.dock_desire.type = 'Dock' self.dock_desire.intensity = 1 self.dock_desire.utility = 1 self.dock_desire.security = False self.loiter_desire = Desire() self.loiter_desire.id = 'dock_charge' self.loiter_desire.type = 'Loiter' self.loiter_desire.intensity = 1 self.loiter_desire.utility = 1 self.loiter_desire.security = False params = dict() params['t'] = self.undock_time self.loiter_desire.params = json.dumps(params) def node(): """Run the docking motivation node.""" generator_node = DockGenerator() generator_node.run() if __name__ == '__main__': node()
33.48913
80
0.612896
import rospy import json import math from enum import Enum from threading import Lock import tf from tf.transformations import euler_from_quaternion from std_msgs.msg import Bool from std_msgs.msg import Empty from geometry_msgs.msg import PoseStamped from sensor_msgs.msg import BatteryState from hbba_msgs.msg import Desire from hbba_msgs.msg import Intention from hbba_msgs.srv import AddDesires from hbba_msgs.srv import RemoveDesires class DockState(Enum): idle = 0 approaching = 1 docking = 2 docked = 3 class DockGenerator: def force_callback(self, msg): self.lock.acquire() self.force_docking = msg.data self.last_force = rospy.Time.now() self.lock.release() def battery_callback(self, msg): self.lock.acquire() if msg.percentage < self.min_percent: self.low_battery = True if msg.percentage > self.charge_percent: self.low_battery = False self.lock.release() def collision_callback(self, msg): self.lock.acquire() if self.state == DockState.docking: self.finish_docking() self.lock.release() def intention_callback(self, msg): self.lock.acquire() self.approach_active = self.approach_desire.id in msg.desires if self.state == DockState.docking: if self.loiter_desire.id in msg.desires: self.state = DockState.docked elif self.dock_desire.id not in msg.desires: self.restart_docking() if self.state == DockState.docked: if self.loiter_desire.id not in msg.desires: self.stop_docking() self.lock.release() def approach_callback(self, msg): self.lock.acquire() self.approach_goal['frame_id'] = msg.header.frame_id self.approach_goal['x'] = msg.pose.position.x self.approach_goal['y'] = msg.pose.position.y quat = ( msg.pose.orientation.w, msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z ) euler = euler_from_quaternion(quat) self.approach_goal['t'] = euler[2] self.lock.release() def start_docking(self): self.add_desire([self.dock_desire]) self.restart_docking() def restart_docking(self): self.approach_desire.params = json.dumps(self.approach_goal) self.add_desire([self.approach_desire]) self.state = DockState.approaching def finish_approach(self): self.rem_desire([self.approach_desire.id]) self.state = DockState.docking def finish_docking(self): self.add_desire([self.loiter_desire]) self.rem_desire([self.dock_desire.id]) def stop_docking(self): if self.state == DockState.approaching: self.rem_desire([ self.dock_desire.id, self.approach_desire.id ]) elif self.state == DockState.docking: self.rem_desire([self.dock_desire.id]) elif self.state == DockState.docked: self.rem_desire([self.loiter_desire.id]) self.state = DockState.idle def run(self): rospy.Subscriber('force_docking', Bool, self.force_callback) rospy.Subscriber('collision', Empty, self.collision_callback) rospy.Subscriber('battery_state', BatteryState, self.battery_callback) rospy.Subscriber('approach_goal', PoseStamped, self.approach_callback) rospy.Subscriber('hbba/intention', Intention, self.intention_callback) tf_listener = tf.TransformListener() rate = rospy.Rate(1) while not rospy.is_shutdown(): rate.sleep() self.lock.acquire() now = rospy.Time.now() timeout = rospy.Duration(self.force_timeout) if now - self.last_force > timeout: self.force_docking = False if (self.force_docking or self.low_battery)\ and self.state == DockState.idle: self.start_docking() self.lock.release() continue if not self.force_docking\ and not self.low_battery\ and self.state != DockState.idle: self.stop_docking() self.lock.release() continue if self.state != DockState.approaching or not self.approach_active: self.lock.release() continue try: pos, quat = tf_listener.lookupTransform( self.map_frame, self.robot_frame, rospy.Time()) except (tf.Exception): self.lock.release() continue dx = pos[0] - self.approach_goal['x'] dy = pos[1] - self.approach_goal['y'] lin_dst = math.sqrt(dx*dx + dy*dy) angles = euler_from_quaternion(quat) yaw_dst = angles[2] - self.approach_goal['t'] if lin_dst < self.appr_lin_tol and abs(yaw_dst) < self.appr_yaw_tol: self.finish_approach() self.lock.release() def __init__(self): self.lock = Lock() self.low_battery = False self.force_docking = False self.approach_active = False self.state = DockState.idle self.last_force = rospy.Time() rospy.init_node('dock_generator') rospy.loginfo('waiting for add desire to be availble') rospy.wait_for_service('/hbba/add_desires') self.add_desire = rospy.ServiceProxy( '/hbba/add_desires', AddDesires) rospy.loginfo('add desire registered') rospy.loginfo('waiting for remove desire to be availbe') rospy.wait_for_service('/hbba/remove_desires') self.rem_desire = rospy.ServiceProxy( '/hbba/remove_desires', RemoveDesires) rospy.loginfo('remove desire registered') self.map_frame = rospy.get_param('~map_frame', 'map') self.robot_frame = rospy.get_param('~robot_frame', 'base_footprint') self.appr_lin_tol = rospy.get_param('~appr_lin_tol', 0.40) self.appr_yaw_tol = rospy.get_param('~appr_yaw_tol', 0.1) self.min_percent = rospy.get_param('~min_percent', 30) self.charge_percent = rospy.get_param('~charge_percent', 80) self.undock_time = rospy.get_param('~undock_time', 4.0) self.force_timeout = rospy.get_param('~force_timeout', 10.0) self.approach_goal = dict() self.approach_goal['x'] = rospy.get_param('approach/x', 0.0) self.approach_goal['y'] = rospy.get_param('approach/y', 0.0) self.approach_goal['t'] = rospy.get_param('approach/t', 0.0) self.approach_goal['frame_id'] = self.map_frame self.approach_desire = Desire() self.approach_desire.id = 'dock_approach' self.approach_desire.type = 'GoTo' self.approach_desire.intensity = 1 self.approach_desire.utility = 1 self.approach_desire.security = False self.dock_desire = Desire() self.dock_desire.id = 'dock_dock' self.dock_desire.type = 'Dock' self.dock_desire.intensity = 1 self.dock_desire.utility = 1 self.dock_desire.security = False self.loiter_desire = Desire() self.loiter_desire.id = 'dock_charge' self.loiter_desire.type = 'Loiter' self.loiter_desire.intensity = 1 self.loiter_desire.utility = 1 self.loiter_desire.security = False params = dict() params['t'] = self.undock_time self.loiter_desire.params = json.dumps(params) def node(): generator_node = DockGenerator() generator_node.run() if __name__ == '__main__': node()
true
true
f716825448eb20eaa87e600968288d77efb47ddf
14,659
py
Python
dataReader.py
tsfw/yolov3
bf6d03d9a84a0ac1e94bcc4f9a026f7d32dfbdab
[ "Apache-2.0" ]
null
null
null
dataReader.py
tsfw/yolov3
bf6d03d9a84a0ac1e94bcc4f9a026f7d32dfbdab
[ "Apache-2.0" ]
null
null
null
dataReader.py
tsfw/yolov3
bf6d03d9a84a0ac1e94bcc4f9a026f7d32dfbdab
[ "Apache-2.0" ]
null
null
null
import os import config import json import tensorflow as tf import numpy as np from collections import defaultdict class Reader: def __init__(self, mode, data_dir, anchors_path, num_classes, tfrecord_num = 12, input_shape = 416, max_boxes = 20): """ Introduction ------------ 构造函数 Parameters ---------- data_dir: 文件路径 mode: 数据集模式 anchors: 数据集聚类得到的anchor num_classes: 数据集图片类别数量 input_shape: 图像输入模型的大小 max_boxes: 每张图片最大的box数量 jitter: 随机长宽比系数 hue: 调整hsv颜色空间系数 sat: 调整饱和度系数 cont: 调整对比度系数 bri: 调整亮度系数 """ self.data_dir = data_dir self.input_shape = input_shape self.max_boxes = max_boxes self.mode = mode self.annotations_file = {'train' : config.train_annotations_file, 'val' : config.val_annotations_file} self.data_file = {'train': config.train_data_file, 'val': config.val_data_file} self.anchors_path = anchors_path self.anchors = self._get_anchors() self.num_classes = num_classes file_pattern = self.data_dir + "/*" + self.mode + '.tfrecords' self.TfrecordFile = tf.gfile.Glob(file_pattern) self.class_names = self._get_class(config.classes_path) if len(self.TfrecordFile) == 0: self.convert_to_tfrecord(self.data_dir, tfrecord_num) def _get_anchors(self): """ Introduction ------------ 获取anchors Returns ------- anchors: anchor数组 """ anchors_path = os.path.expanduser(self.anchors_path) with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2) def _get_class(self, classes_path): """ Introduction ------------ 获取类别名字 Returns ------- class_names: coco数据集类别对应的名字 """ classes_path = os.path.expanduser(classes_path) with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names def Preprocess_true_boxes(self, true_boxes): """ Introduction ------------ 对训练数据的ground truth box进行预处理 Parameters ---------- true_boxes: ground truth box 形状为[boxes, 5], x_min, y_min, x_max, y_max, class_id """ num_layers = len(self.anchors) // 3 anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] true_boxes = np.array(true_boxes, dtype='float32') input_shape = np.array([self.input_shape, self.input_shape], dtype='int32') boxes_xy = (true_boxes[..., 0:2] + true_boxes[..., 2:4]) // 2. boxes_wh = true_boxes[..., 2:4] - true_boxes[..., 0:2] true_boxes[..., 0:2] = boxes_xy / input_shape[::-1] true_boxes[..., 2:4] = boxes_wh / input_shape[::-1] grid_shapes = [input_shape // 32, input_shape // 16, input_shape // 8] y_true = [np.zeros((grid_shapes[l][0], grid_shapes[l][1], len(anchor_mask[l]), 5 + self.num_classes), dtype='float32') for l in range(num_layers)] # 这里扩充维度是为了后面应用广播计算每个图中所有box的anchor互相之间的iou anchors = np.expand_dims(self.anchors, 0) anchors_max = anchors / 2. anchors_min = -anchors_max # 因为之前对box做了padding, 因此需要去除全0行 valid_mask = boxes_wh[..., 0] > 0 wh = boxes_wh[valid_mask] # 为了应用广播扩充维度 wh = np.expand_dims(wh, -2) # wh 的shape为[box_num, 1, 2] boxes_max = wh / 2. boxes_min = -boxes_max intersect_min = np.maximum(boxes_min, anchors_min) intersect_max = np.minimum(boxes_max, anchors_max) intersect_wh = np.maximum(intersect_max - intersect_min, 0.) intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] box_area = wh[..., 0] * wh[..., 1] anchor_area = anchors[..., 0] * anchors[..., 1] iou = intersect_area / (box_area + anchor_area - intersect_area) # 找出和ground truth box的iou最大的anchor box, 然后将对应不同比例的负责该ground turth box 的位置置为ground truth box坐标 best_anchor = np.argmax(iou, axis = -1) for t, n in enumerate(best_anchor): for l in range(num_layers): if n in anchor_mask[l]: i = np.floor(true_boxes[t, 0] * grid_shapes[l][1]).astype('int32') j = np.floor(true_boxes[t, 1] * grid_shapes[l][0]).astype('int32') k = anchor_mask[l].index(n) c = true_boxes[t, 4].astype('int32') y_true[l][j, i, k, 0:4] = true_boxes[t, 0:4] y_true[l][j, i, k, 4] = 1. y_true[l][j, i, k, 5 + c] = 1. return y_true[0], y_true[1], y_true[2] def read_annotations(self): """ Introduction ------------ 读取COCO数据集图片路径和对应的标注 Parameters ---------- data_file: 文件路径 """ image_data = [] boxes_data = [] name_box_id = defaultdict(list) with open(self.annotations_file[self.mode], encoding='utf-8') as file: data = json.load(file) annotations = data['annotations'] for ant in annotations: id = ant['image_id'] name = os.path.join(self.data_file[self.mode], '%012d.jpg' % id) cat = ant['category_id'] if cat >= 1 and cat <= 11: cat = cat - 1 elif cat >= 13 and cat <= 25: cat = cat - 2 elif cat >= 27 and cat <= 28: cat = cat - 3 elif cat >= 31 and cat <= 44: cat = cat - 5 elif cat >= 46 and cat <= 65: cat = cat - 6 elif cat == 67: cat = cat - 7 elif cat == 70: cat = cat - 9 elif cat >= 72 and cat <= 82: cat = cat - 10 elif cat >= 84 and cat <= 90: cat = cat - 11 name_box_id[name].append([ant['bbox'], cat]) for key in name_box_id.keys(): boxes = [] image_data.append(key) box_infos = name_box_id[key] for info in box_infos: x_min = info[0][0] y_min = info[0][1] x_max = x_min + info[0][2] y_max = y_min + info[0][3] boxes.append(np.array([x_min, y_min, x_max, y_max, info[1]])) boxes_data.append(np.array(boxes)) return image_data, boxes_data def convert_to_tfrecord(self, tfrecord_path, num_tfrecords): """ Introduction ------------ 将图片和boxes数据存储为tfRecord Parameters ---------- tfrecord_path: tfrecord文件存储路径 num_tfrecords: 分成多少个tfrecord """ image_data, boxes_data = self.read_annotations() images_num = int(len(image_data) / num_tfrecords) for index_records in range(num_tfrecords): output_file = os.path.join(tfrecord_path, str(index_records) + '_' + self.mode + '.tfrecords') with tf.python_io.TFRecordWriter(output_file) as record_writer: for index in range(index_records * images_num, (index_records + 1) * images_num): with tf.gfile.FastGFile(image_data[index], 'rb') as file: image = file.read() xmin, xmax, ymin, ymax, label = [], [], [], [], [] for box in boxes_data[index]: xmin.append(box[0]) ymin.append(box[1]) xmax.append(box[2]) ymax.append(box[3]) label.append(box[4]) example = tf.train.Example(features = tf.train.Features( feature = { 'image/encoded' : tf.train.Feature(bytes_list = tf.train.BytesList(value = [image])), 'image/object/bbox/xmin' : tf.train.Feature(float_list = tf.train.FloatList(value = xmin)), 'image/object/bbox/xmax': tf.train.Feature(float_list = tf.train.FloatList(value = xmax)), 'image/object/bbox/ymin': tf.train.Feature(float_list = tf.train.FloatList(value = ymin)), 'image/object/bbox/ymax': tf.train.Feature(float_list = tf.train.FloatList(value = ymax)), 'image/object/bbox/label': tf.train.Feature(float_list = tf.train.FloatList(value = label)), } )) record_writer.write(example.SerializeToString()) if index % 1000 == 0: print('Processed {} of {} images'.format(index + 1, len(image_data))) def parser(self, serialized_example): """ Introduction ------------ 解析tfRecord数据 Parameters ---------- serialized_example: 序列化的每条数据 """ features = tf.parse_single_example( serialized_example, features = { 'image/encoded' : tf.FixedLenFeature([], dtype = tf.string), 'image/object/bbox/xmin' : tf.VarLenFeature(dtype = tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature(dtype = tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(dtype = tf.float32), 'image/object/bbox/ymax': tf.VarLenFeature(dtype = tf.float32), 'image/object/bbox/label': tf.VarLenFeature(dtype = tf.float32) } ) image = tf.image.decode_jpeg(features['image/encoded'], channels = 3) image = tf.image.convert_image_dtype(image, tf.uint8) xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, axis = 0) ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, axis = 0) xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, axis = 0) ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, axis = 0) label = tf.expand_dims(features['image/object/bbox/label'].values, axis = 0) bbox = tf.concat(axis = 0, values = [xmin, ymin, xmax, ymax, label]) bbox = tf.transpose(bbox, [1, 0]) image, bbox = self.Preprocess(image, bbox) bbox_true_13, bbox_true_26, bbox_true_52 = tf.py_func(self.Preprocess_true_boxes, [bbox], [tf.float32, tf.float32, tf.float32]) return image, bbox, bbox_true_13, bbox_true_26, bbox_true_52 def Preprocess(self, image, bbox): """ Introduction ------------ 对图片进行预处理,增强数据集 Parameters ---------- image: tensorflow解析的图片 bbox: 图片中对应的box坐标 """ image_width, image_high = tf.cast(tf.shape(image)[1], tf.float32), tf.cast(tf.shape(image)[0], tf.float32) input_width = tf.cast(self.input_shape, tf.float32) input_high = tf.cast(self.input_shape, tf.float32) new_high = image_high * tf.minimum(input_width / image_width, input_high / image_high) new_width = image_width * tf.minimum(input_width / image_width, input_high / image_high) # 将图片按照固定长宽比进行padding缩放 dx = (input_width - new_width) / 2 dy = (input_high - new_high) / 2 image = tf.image.resize_images(image, [tf.cast(new_high, tf.int32), tf.cast(new_width, tf.int32)], method = tf.image.ResizeMethod.BICUBIC) new_image = tf.image.pad_to_bounding_box(image, tf.cast(dy, tf.int32), tf.cast(dx, tf.int32), tf.cast(input_high, tf.int32), tf.cast(input_width, tf.int32)) image_ones = tf.ones_like(image) image_ones_padded = tf.image.pad_to_bounding_box(image_ones, tf.cast(dy, tf.int32), tf.cast(dx, tf.int32), tf.cast(input_high, tf.int32), tf.cast(input_width, tf.int32)) image_color_padded = (1 - image_ones_padded) * 128 image = image_color_padded + new_image # 矫正bbox坐标 xmin, ymin, xmax, ymax, label = tf.split(value = bbox, num_or_size_splits=5, axis = 1) xmin = xmin * new_width / image_width + dx xmax = xmax * new_width / image_width + dx ymin = ymin * new_high / image_high + dy ymax = ymax * new_high / image_high + dy bbox = tf.concat([xmin, ymin, xmax, ymax, label], 1) if self.mode == 'train': # 随机左右翻转图片 def _flip_left_right_boxes(boxes): xmin, ymin, xmax, ymax, label = tf.split(value = boxes, num_or_size_splits = 5, axis = 1) flipped_xmin = tf.subtract(input_width, xmax) flipped_xmax = tf.subtract(input_width, xmin) flipped_boxes = tf.concat([flipped_xmin, ymin, flipped_xmax, ymax, label], 1) return flipped_boxes flip_left_right = tf.greater(tf.random_uniform([], dtype = tf.float32, minval = 0, maxval = 1), 0.5) image = tf.cond(flip_left_right, lambda : tf.image.flip_left_right(image), lambda : image) bbox = tf.cond(flip_left_right, lambda: _flip_left_right_boxes(bbox), lambda: bbox) # 将图片归一化到0和1之间 image = image / 255. image = tf.clip_by_value(image, clip_value_min = 0.0, clip_value_max = 1.0) bbox = tf.clip_by_value(bbox, clip_value_min = 0, clip_value_max = input_width - 1) bbox = tf.cond(tf.greater(tf.shape(bbox)[0], config.max_boxes), lambda: bbox[:config.max_boxes], lambda: tf.pad(bbox, paddings = [[0, config.max_boxes - tf.shape(bbox)[0]], [0, 0]], mode = 'CONSTANT')) return image, bbox def build_dataset(self, batch_size): """ Introduction ------------ 建立数据集dataset Parameters ---------- batch_size: batch大小 Return ------ dataset: 返回tensorflow的dataset """ dataset = tf.data.TFRecordDataset(filenames = self.TfrecordFile) dataset = dataset.map(self.parser, num_parallel_calls = 10) if self.mode == 'train': dataset = dataset.repeat().shuffle(9000).batch(batch_size).prefetch(batch_size) else: dataset = dataset.repeat().batch(batch_size).prefetch(batch_size) return dataset
44.966258
209
0.548469
import os import config import json import tensorflow as tf import numpy as np from collections import defaultdict class Reader: def __init__(self, mode, data_dir, anchors_path, num_classes, tfrecord_num = 12, input_shape = 416, max_boxes = 20): self.data_dir = data_dir self.input_shape = input_shape self.max_boxes = max_boxes self.mode = mode self.annotations_file = {'train' : config.train_annotations_file, 'val' : config.val_annotations_file} self.data_file = {'train': config.train_data_file, 'val': config.val_data_file} self.anchors_path = anchors_path self.anchors = self._get_anchors() self.num_classes = num_classes file_pattern = self.data_dir + "/*" + self.mode + '.tfrecords' self.TfrecordFile = tf.gfile.Glob(file_pattern) self.class_names = self._get_class(config.classes_path) if len(self.TfrecordFile) == 0: self.convert_to_tfrecord(self.data_dir, tfrecord_num) def _get_anchors(self): anchors_path = os.path.expanduser(self.anchors_path) with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2) def _get_class(self, classes_path): classes_path = os.path.expanduser(classes_path) with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names def Preprocess_true_boxes(self, true_boxes): num_layers = len(self.anchors) // 3 anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] true_boxes = np.array(true_boxes, dtype='float32') input_shape = np.array([self.input_shape, self.input_shape], dtype='int32') boxes_xy = (true_boxes[..., 0:2] + true_boxes[..., 2:4]) // 2. boxes_wh = true_boxes[..., 2:4] - true_boxes[..., 0:2] true_boxes[..., 0:2] = boxes_xy / input_shape[::-1] true_boxes[..., 2:4] = boxes_wh / input_shape[::-1] grid_shapes = [input_shape // 32, input_shape // 16, input_shape // 8] y_true = [np.zeros((grid_shapes[l][0], grid_shapes[l][1], len(anchor_mask[l]), 5 + self.num_classes), dtype='float32') for l in range(num_layers)] anchors = np.expand_dims(self.anchors, 0) anchors_max = anchors / 2. anchors_min = -anchors_max valid_mask = boxes_wh[..., 0] > 0 wh = boxes_wh[valid_mask] wh = np.expand_dims(wh, -2) boxes_max = wh / 2. boxes_min = -boxes_max intersect_min = np.maximum(boxes_min, anchors_min) intersect_max = np.minimum(boxes_max, anchors_max) intersect_wh = np.maximum(intersect_max - intersect_min, 0.) intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] box_area = wh[..., 0] * wh[..., 1] anchor_area = anchors[..., 0] * anchors[..., 1] iou = intersect_area / (box_area + anchor_area - intersect_area) best_anchor = np.argmax(iou, axis = -1) for t, n in enumerate(best_anchor): for l in range(num_layers): if n in anchor_mask[l]: i = np.floor(true_boxes[t, 0] * grid_shapes[l][1]).astype('int32') j = np.floor(true_boxes[t, 1] * grid_shapes[l][0]).astype('int32') k = anchor_mask[l].index(n) c = true_boxes[t, 4].astype('int32') y_true[l][j, i, k, 0:4] = true_boxes[t, 0:4] y_true[l][j, i, k, 4] = 1. y_true[l][j, i, k, 5 + c] = 1. return y_true[0], y_true[1], y_true[2] def read_annotations(self): image_data = [] boxes_data = [] name_box_id = defaultdict(list) with open(self.annotations_file[self.mode], encoding='utf-8') as file: data = json.load(file) annotations = data['annotations'] for ant in annotations: id = ant['image_id'] name = os.path.join(self.data_file[self.mode], '%012d.jpg' % id) cat = ant['category_id'] if cat >= 1 and cat <= 11: cat = cat - 1 elif cat >= 13 and cat <= 25: cat = cat - 2 elif cat >= 27 and cat <= 28: cat = cat - 3 elif cat >= 31 and cat <= 44: cat = cat - 5 elif cat >= 46 and cat <= 65: cat = cat - 6 elif cat == 67: cat = cat - 7 elif cat == 70: cat = cat - 9 elif cat >= 72 and cat <= 82: cat = cat - 10 elif cat >= 84 and cat <= 90: cat = cat - 11 name_box_id[name].append([ant['bbox'], cat]) for key in name_box_id.keys(): boxes = [] image_data.append(key) box_infos = name_box_id[key] for info in box_infos: x_min = info[0][0] y_min = info[0][1] x_max = x_min + info[0][2] y_max = y_min + info[0][3] boxes.append(np.array([x_min, y_min, x_max, y_max, info[1]])) boxes_data.append(np.array(boxes)) return image_data, boxes_data def convert_to_tfrecord(self, tfrecord_path, num_tfrecords): image_data, boxes_data = self.read_annotations() images_num = int(len(image_data) / num_tfrecords) for index_records in range(num_tfrecords): output_file = os.path.join(tfrecord_path, str(index_records) + '_' + self.mode + '.tfrecords') with tf.python_io.TFRecordWriter(output_file) as record_writer: for index in range(index_records * images_num, (index_records + 1) * images_num): with tf.gfile.FastGFile(image_data[index], 'rb') as file: image = file.read() xmin, xmax, ymin, ymax, label = [], [], [], [], [] for box in boxes_data[index]: xmin.append(box[0]) ymin.append(box[1]) xmax.append(box[2]) ymax.append(box[3]) label.append(box[4]) example = tf.train.Example(features = tf.train.Features( feature = { 'image/encoded' : tf.train.Feature(bytes_list = tf.train.BytesList(value = [image])), 'image/object/bbox/xmin' : tf.train.Feature(float_list = tf.train.FloatList(value = xmin)), 'image/object/bbox/xmax': tf.train.Feature(float_list = tf.train.FloatList(value = xmax)), 'image/object/bbox/ymin': tf.train.Feature(float_list = tf.train.FloatList(value = ymin)), 'image/object/bbox/ymax': tf.train.Feature(float_list = tf.train.FloatList(value = ymax)), 'image/object/bbox/label': tf.train.Feature(float_list = tf.train.FloatList(value = label)), } )) record_writer.write(example.SerializeToString()) if index % 1000 == 0: print('Processed {} of {} images'.format(index + 1, len(image_data))) def parser(self, serialized_example): features = tf.parse_single_example( serialized_example, features = { 'image/encoded' : tf.FixedLenFeature([], dtype = tf.string), 'image/object/bbox/xmin' : tf.VarLenFeature(dtype = tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature(dtype = tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(dtype = tf.float32), 'image/object/bbox/ymax': tf.VarLenFeature(dtype = tf.float32), 'image/object/bbox/label': tf.VarLenFeature(dtype = tf.float32) } ) image = tf.image.decode_jpeg(features['image/encoded'], channels = 3) image = tf.image.convert_image_dtype(image, tf.uint8) xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, axis = 0) ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, axis = 0) xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, axis = 0) ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, axis = 0) label = tf.expand_dims(features['image/object/bbox/label'].values, axis = 0) bbox = tf.concat(axis = 0, values = [xmin, ymin, xmax, ymax, label]) bbox = tf.transpose(bbox, [1, 0]) image, bbox = self.Preprocess(image, bbox) bbox_true_13, bbox_true_26, bbox_true_52 = tf.py_func(self.Preprocess_true_boxes, [bbox], [tf.float32, tf.float32, tf.float32]) return image, bbox, bbox_true_13, bbox_true_26, bbox_true_52 def Preprocess(self, image, bbox): image_width, image_high = tf.cast(tf.shape(image)[1], tf.float32), tf.cast(tf.shape(image)[0], tf.float32) input_width = tf.cast(self.input_shape, tf.float32) input_high = tf.cast(self.input_shape, tf.float32) new_high = image_high * tf.minimum(input_width / image_width, input_high / image_high) new_width = image_width * tf.minimum(input_width / image_width, input_high / image_high) dx = (input_width - new_width) / 2 dy = (input_high - new_high) / 2 image = tf.image.resize_images(image, [tf.cast(new_high, tf.int32), tf.cast(new_width, tf.int32)], method = tf.image.ResizeMethod.BICUBIC) new_image = tf.image.pad_to_bounding_box(image, tf.cast(dy, tf.int32), tf.cast(dx, tf.int32), tf.cast(input_high, tf.int32), tf.cast(input_width, tf.int32)) image_ones = tf.ones_like(image) image_ones_padded = tf.image.pad_to_bounding_box(image_ones, tf.cast(dy, tf.int32), tf.cast(dx, tf.int32), tf.cast(input_high, tf.int32), tf.cast(input_width, tf.int32)) image_color_padded = (1 - image_ones_padded) * 128 image = image_color_padded + new_image xmin, ymin, xmax, ymax, label = tf.split(value = bbox, num_or_size_splits=5, axis = 1) xmin = xmin * new_width / image_width + dx xmax = xmax * new_width / image_width + dx ymin = ymin * new_high / image_high + dy ymax = ymax * new_high / image_high + dy bbox = tf.concat([xmin, ymin, xmax, ymax, label], 1) if self.mode == 'train': def _flip_left_right_boxes(boxes): xmin, ymin, xmax, ymax, label = tf.split(value = boxes, num_or_size_splits = 5, axis = 1) flipped_xmin = tf.subtract(input_width, xmax) flipped_xmax = tf.subtract(input_width, xmin) flipped_boxes = tf.concat([flipped_xmin, ymin, flipped_xmax, ymax, label], 1) return flipped_boxes flip_left_right = tf.greater(tf.random_uniform([], dtype = tf.float32, minval = 0, maxval = 1), 0.5) image = tf.cond(flip_left_right, lambda : tf.image.flip_left_right(image), lambda : image) bbox = tf.cond(flip_left_right, lambda: _flip_left_right_boxes(bbox), lambda: bbox) image = image / 255. image = tf.clip_by_value(image, clip_value_min = 0.0, clip_value_max = 1.0) bbox = tf.clip_by_value(bbox, clip_value_min = 0, clip_value_max = input_width - 1) bbox = tf.cond(tf.greater(tf.shape(bbox)[0], config.max_boxes), lambda: bbox[:config.max_boxes], lambda: tf.pad(bbox, paddings = [[0, config.max_boxes - tf.shape(bbox)[0]], [0, 0]], mode = 'CONSTANT')) return image, bbox def build_dataset(self, batch_size): dataset = tf.data.TFRecordDataset(filenames = self.TfrecordFile) dataset = dataset.map(self.parser, num_parallel_calls = 10) if self.mode == 'train': dataset = dataset.repeat().shuffle(9000).batch(batch_size).prefetch(batch_size) else: dataset = dataset.repeat().batch(batch_size).prefetch(batch_size) return dataset
true
true
f71684275afc20018793ca67d49712a2693a0850
10,212
py
Python
a3c_master_sewak.py
sebtac/MLxE
93baa6b7c9fd14e54abd7199e868fb828e9a7c52
[ "Apache-2.0" ]
1
2020-12-15T17:19:33.000Z
2020-12-15T17:19:33.000Z
a3c_master_sewak.py
sebtac/MLxE
93baa6b7c9fd14e54abd7199e868fb828e9a7c52
[ "Apache-2.0" ]
null
null
null
a3c_master_sewak.py
sebtac/MLxE
93baa6b7c9fd14e54abd7199e868fb828e9a7c52
[ "Apache-2.0" ]
null
null
null
""" A3C in Code - Centralized/ Gobal Network Parameter Server/ Controller Based On: A3C Code as in the book Deep Reinforcement Learning, Chapter 12. Runtime: Python 3.6.5 Dependencies: numpy, matplotlib, tensorflow (/ tensorflow-gpu), gym DocStrings: GoogleStyle Author : Mohit Sewak (p20150023@goa-bits-pilani.ac.in) Inspired from: A3C implementation on TensorFLow official github repository (Tensorflow/models/research) ********************************************************************** Adjusted by Seabstian Taciak as part of develeopment of MLxE Architecture @author: sebtac @contact: https://www.linkedin.com/in/sebastian-taciak-5893861/ """ # SET BEFORE RUNNIG # AGENT TYPE # 0 - Sewak Base Agent (Fixed) # 1 - Sewak DNN Adjusted # 2 - Sewak "Task" Modified # 3 - Sewak ISTB (Iterative, Synchronous Thread Based) Agent_Type = 3 learning_rate = 0.0001 import multiprocessing cores = multiprocessing.cpu_count() # DEFAULT SETTING #cores = 1 # FOR DEBUGGING # GENERAL IMPORTS import sys sys.path.append(r'C:\Users\surface\Documents\Python\RL\MLxE\Mohit Sewak RL\Mohit12_A3C') import time import winsound import logging import os import numpy as np import matplotlib.pyplot as plt logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.DEBUG) # DEEP LEARING and ENVIRONEMENT RELATER IMPORTS import tensorflow as tf import tensorflow_addons as tfa # ST for DNN Adjustment import gym # CUSTOM SEWAK's MODULES with OPTIONAL SEBTAC ADJUSTMENTS from experience_replay_sewak import SimpleListBasedMemory if Agent_Type == 0: from actorcritic_model_sewak import ActorCriticModel as ACModel # For Sewak Fixed version from a3c_worker_sewak_base import A3C_Worker # the intial Sewak's implementation with fixes of the Policy_Loss Calcultion elif Agent_Type == 1: from actorcritic_model_sewak import ActorCriticModel_Dimond as ACModel from a3c_worker_sewak_DNN_Adjusted import A3C_Worker elif Agent_Type == 2: from actorcritic_model_sewak import ActorCriticModel_Dimond as ACModel from a3c_worker_sewak_Task_Modifications import A3C_Worker elif Agent_Type == 3: from actorcritic_model_sewak import ActorCriticModel_DoubleDimond as ACModel from a3c_worker_sewak_ISTB import A3C_Worker # SEWAK's Implementation Fix """ - Policy Loss Calcualtion - Using actual play in example generation (was random) """ # DNN Adjustments """ - Adding monotonic decrease in Learing Rate relative to the number of episodes run with: self.alpha_power = 0.998 self.alpha_limit = 0.000001 - Modifying the Model to: common_network_size=[128,256,128], policy_network_size=[64,128,64], value_network_size=[64,128,64] - Changing the Optimizer to RectifiedAdam -- requaires tensorflow_addons - Changing Gamma coeffcient to 0.97 """ # Task Specific Modifications """ - Modified state representation with addition of 5th parameter representing the squared distance of the cart from the center of the plane - Adverse Initial Position - Negative Reward: -10.0 (originally 0.0) - Monotonically Decreasing Discount Factor (Gamma Coefficent) - Goal Specific Reward for cart being close to center of the pland and the pole being close to vertical """ class A3C_Master(): """A3C Master Centralized Master class of A3C used for hosting the global network parameters and spawning the agents. Args: env_name (str): Name of a valid gym environment model_dir (str): Directory for saving the model during training, and loading the same while playing learning_rate (float): The learning rate (alpha) for the optimizer Examples: agent = A3C_Master() agent.train() agent.play() """ def __init__(self, Agent_Type=Agent_Type, env_name='CartPole-v0', model_dir="models", learning_rate=learning_rate): #ST 0.001 for Fixed, 0.0001 otherwise self.env_name = env_name self.model_dir = model_dir self.alpha = learning_rate if not os.path.exists(model_dir): os.makedirs(model_dir) self.env = gym.make(self.env_name) self.action_size = self.env.action_space.n if Agent_Type <= 1: self.state_size = self.env.observation_space.shape[0] # For None TaH imlementations elif Agent_Type == 2: self.state_size = self.env.observation_space.shape[0] + 1 # ST for TaH implementation elif Agent_Type == 3: self.state_size = self.env.observation_space.shape[0] + 1 # ST for TaH implementation if Agent_Type == 0: self.optimizer = tf.keras.optimizers.Adam(self.alpha) else: self.optimizer = tfa.optimizers.RectifiedAdam(self.alpha) # ST DNN Adjustment logger.debug("StateSize:{}, ActionSize:{}".format(self.state_size, self.action_size)) self.master_model = ACModel(self.action_size) self.master_model(tf.convert_to_tensor(np.random.random((1, self.state_size)), dtype=tf.float32)) def train(self, cores): """Train the A3C agent Main function to train the A3C agent after instantiation. This method uses the number of processor cores to spawns as many Workers. The workers are spawned as multiple parallel threads instead of multiple parallel processes. Being a threaded execution, the workers share memory and hence can write directly into the shared global variables. A more optimal, completely asynchronous implementation could be to spawn the workers as different processes using a task queue or multiprocessing. In case if this is adopted, then the shared variables need to made accessible in the distributed environment. """ a3c_workers = [A3C_Worker(self.master_model, self.optimizer, i, self.env_name, self.model_dir, workers_num = cores, learning_rate = learning_rate) for i in range(cores)] for i, worker in enumerate(a3c_workers): logger.info("Starting worker {}".format(i)) worker.start() [worker.join() for worker in a3c_workers] self.plot_training_statistics() def play(self): """Play the environment using a trained agent This function opens a (graphical) window that will play a trained agent. The function will try to retrieve the model saved in the model_dir with filename formatted to contain the associated env_name. If the model is not found, then the function will first call the train function to start the training. """ env = self.env.unwrapped state = env.reset() model = self.master_model model_path = os.path.join(self.model_dir, 'model_{}.h5'.format(self.env_name)) if not os.path.exists(model_path): logger.info('A3CMaster: No model found at {}, starting fresh training before playing!'.format(model_path)) self.train() logger.info('A3CMaster: Playing env, Loading model from: {}'.format(model_path)) print("Model Path:", model_path) #model.load_weights(model_path) done = False step_counter = 0 reward_sum = 0 try: while not done: env.render(mode='rgb_array') policy, value = model(tf.convert_to_tensor(state[None, :], dtype=tf.float32)) policy = tf.nn.softmax(policy) action = np.argmax(policy) state, reward, done, _ = env.step(action) reward_sum += reward logger.info("{}. Reward: {}, action: {}".format(step_counter, reward_sum, action)) step_counter += 1 except KeyboardInterrupt: print("Received Keyboard Interrupt. Shutting down.") finally: env.close() def plot_training_statistics(self, training_statistics=None): """Plot training statistics This function plot the training statistics like the steps, rewards, discounted_rewards, and loss in each of the training episode. """ training_statistics = A3C_Worker.global_shared_training_stats if training_statistics is None \ else training_statistics all_episodes = [] all_steps = [] all_rewards = [] all_discounted_rewards = [] all_losses = [] for stats in training_statistics: worker, episode, steps, reward, discounted_rewards, loss = stats all_episodes.append(episode) all_steps.append(steps) all_rewards.append(reward) all_discounted_rewards.append(discounted_rewards) all_losses.append(loss) self._make_double_axis_plot(all_episodes, all_steps, all_rewards) self._make_double_axis_plot(all_episodes,all_discounted_rewards,all_losses, label_y1="Discounted Reward", label_y2="Loss", color_y1="cyan", color_y2="black") np.savetxt('run.csv', all_steps, delimiter=',', fmt='%d') @staticmethod def _make_double_axis_plot(data_x, data_y1, data_y2, x_label='Episodes (e)', label_y1='Steps To Episode Completion', label_y2='Reward in each Episode', color_y1="red", color_y2="blue"): """Internal helper function for plotting dual axis plots """ fig, ax1 = plt.subplots() ax1.set_xlabel(x_label) ax1.set_ylabel(label_y1, color=color_y1) ax1.plot(data_x, data_y1, color=color_y1) ax2 = ax1.twinx() ax2.set_ylabel(label_y2, color=color_y2) ax2.plot(data_x, data_y2, color=color_y2) fig.tight_layout() plt.show() if __name__ == "__main__": """Main function for testing the A3C Master code's implementation """ agent = A3C_Master(Agent_Type=Agent_Type) agent.train(cores) #agent.play() for i in range(10): winsound.Beep(500,500)
39.890625
158
0.665785
Agent_Type = 3 learning_rate = 0.0001 import multiprocessing cores = multiprocessing.cpu_count() ys.path.append(r'C:\Users\surface\Documents\Python\RL\MLxE\Mohit Sewak RL\Mohit12_A3C') import time import winsound import logging import os import numpy as np import matplotlib.pyplot as plt logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.DEBUG) import tensorflow as tf import tensorflow_addons as tfa import gym from experience_replay_sewak import SimpleListBasedMemory if Agent_Type == 0: from actorcritic_model_sewak import ActorCriticModel as ACModel # For Sewak Fixed version from a3c_worker_sewak_base import A3C_Worker # the intial Sewak's implementation with fixes of the Policy_Loss Calcultion elif Agent_Type == 1: from actorcritic_model_sewak import ActorCriticModel_Dimond as ACModel from a3c_worker_sewak_DNN_Adjusted import A3C_Worker elif Agent_Type == 2: from actorcritic_model_sewak import ActorCriticModel_Dimond as ACModel from a3c_worker_sewak_Task_Modifications import A3C_Worker elif Agent_Type == 3: from actorcritic_model_sewak import ActorCriticModel_DoubleDimond as ACModel from a3c_worker_sewak_ISTB import A3C_Worker # DNN Adjustments # Task Specific Modifications class A3C_Master(): def __init__(self, Agent_Type=Agent_Type, env_name='CartPole-v0', model_dir="models", learning_rate=learning_rate): #ST 0.001 for Fixed, 0.0001 otherwise self.env_name = env_name self.model_dir = model_dir self.alpha = learning_rate if not os.path.exists(model_dir): os.makedirs(model_dir) self.env = gym.make(self.env_name) self.action_size = self.env.action_space.n if Agent_Type <= 1: self.state_size = self.env.observation_space.shape[0] # For None TaH imlementations elif Agent_Type == 2: self.state_size = self.env.observation_space.shape[0] + 1 # ST for TaH implementation elif Agent_Type == 3: self.state_size = self.env.observation_space.shape[0] + 1 # ST for TaH implementation if Agent_Type == 0: self.optimizer = tf.keras.optimizers.Adam(self.alpha) else: self.optimizer = tfa.optimizers.RectifiedAdam(self.alpha) # ST DNN Adjustment logger.debug("StateSize:{}, ActionSize:{}".format(self.state_size, self.action_size)) self.master_model = ACModel(self.action_size) self.master_model(tf.convert_to_tensor(np.random.random((1, self.state_size)), dtype=tf.float32)) def train(self, cores): a3c_workers = [A3C_Worker(self.master_model, self.optimizer, i, self.env_name, self.model_dir, workers_num = cores, learning_rate = learning_rate) for i in range(cores)] for i, worker in enumerate(a3c_workers): logger.info("Starting worker {}".format(i)) worker.start() [worker.join() for worker in a3c_workers] self.plot_training_statistics() def play(self): env = self.env.unwrapped state = env.reset() model = self.master_model model_path = os.path.join(self.model_dir, 'model_{}.h5'.format(self.env_name)) if not os.path.exists(model_path): logger.info('A3CMaster: No model found at {}, starting fresh training before playing!'.format(model_path)) self.train() logger.info('A3CMaster: Playing env, Loading model from: {}'.format(model_path)) print("Model Path:", model_path) #model.load_weights(model_path) done = False step_counter = 0 reward_sum = 0 try: while not done: env.render(mode='rgb_array') policy, value = model(tf.convert_to_tensor(state[None, :], dtype=tf.float32)) policy = tf.nn.softmax(policy) action = np.argmax(policy) state, reward, done, _ = env.step(action) reward_sum += reward logger.info("{}. Reward: {}, action: {}".format(step_counter, reward_sum, action)) step_counter += 1 except KeyboardInterrupt: print("Received Keyboard Interrupt. Shutting down.") finally: env.close() def plot_training_statistics(self, training_statistics=None): training_statistics = A3C_Worker.global_shared_training_stats if training_statistics is None \ else training_statistics all_episodes = [] all_steps = [] all_rewards = [] all_discounted_rewards = [] all_losses = [] for stats in training_statistics: worker, episode, steps, reward, discounted_rewards, loss = stats all_episodes.append(episode) all_steps.append(steps) all_rewards.append(reward) all_discounted_rewards.append(discounted_rewards) all_losses.append(loss) self._make_double_axis_plot(all_episodes, all_steps, all_rewards) self._make_double_axis_plot(all_episodes,all_discounted_rewards,all_losses, label_y1="Discounted Reward", label_y2="Loss", color_y1="cyan", color_y2="black") np.savetxt('run.csv', all_steps, delimiter=',', fmt='%d') @staticmethod def _make_double_axis_plot(data_x, data_y1, data_y2, x_label='Episodes (e)', label_y1='Steps To Episode Completion', label_y2='Reward in each Episode', color_y1="red", color_y2="blue"): fig, ax1 = plt.subplots() ax1.set_xlabel(x_label) ax1.set_ylabel(label_y1, color=color_y1) ax1.plot(data_x, data_y1, color=color_y1) ax2 = ax1.twinx() ax2.set_ylabel(label_y2, color=color_y2) ax2.plot(data_x, data_y2, color=color_y2) fig.tight_layout() plt.show() if __name__ == "__main__": agent = A3C_Master(Agent_Type=Agent_Type) agent.train(cores) #agent.play() for i in range(10): winsound.Beep(500,500)
true
true
f716847b7e7f2b74e68a21c9fff18732128dc20b
1,196
py
Python
examples/cdv/plttraj.py
geflaspohler/deep-OTD
0daec276669776952b5142149007175b8a3c4d87
[ "MIT" ]
1
2020-07-18T02:00:50.000Z
2020-07-18T02:00:50.000Z
examples/cdv/plttraj.py
geflaspohler/deep-OTD
0daec276669776952b5142149007175b8a3c4d87
[ "MIT" ]
null
null
null
examples/cdv/plttraj.py
geflaspohler/deep-OTD
0daec276669776952b5142149007175b8a3c4d87
[ "MIT" ]
3
2019-11-28T04:15:59.000Z
2020-03-27T16:15:36.000Z
import numpy as np import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.size'] = 9 ndim = 6 data = np.genfromtxt('dOTD_tst1.out') xticks = [900, 1100, 1300] yticks = [[0.7, 0.8, 0.9, 1], [-0.2, 0, 0.2, 0.4], [-0.5, 0, 0.5], [-1, -0.5, 0], [-0.5, 0, 0.5], [-0.5, 0, 0.5, 1]] def latexify(ticklabels): """Manually set LaTeX format for tick labels.""" return [r"$" + str(label) + "$" for label in ticklabels] for ii in range(ndim): fig = plt.figure(figsize=(2.2,1.3), constrained_layout=True) fig.set_constrained_layout_pads(w_pad=0, h_pad=0) ax = plt.axes() plt.plot(data[:,0], data[:,ii+1], 'k-', linewidth=0.75) plt.xlabel('$t$') plt.ylabel('$z_{' + str(ii+1) + '}$') plt.xlim(xticks[0], xticks[-1]) plt.ylim(yticks[ii][0], yticks[ii][-1]) ax.set_xticks(xticks) ax.set_yticks(yticks[ii]) ax.set_xticklabels(latexify(xticks)) ax.set_yticklabels(latexify(yticks[ii])) ax.yaxis.set_label_coords(-0.2, 0.5) ax.tick_params(direction='in', length=2) plt.savefig('traj' + str(ii+1) + '.pdf')
29.170732
64
0.591137
import numpy as np import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.size'] = 9 ndim = 6 data = np.genfromtxt('dOTD_tst1.out') xticks = [900, 1100, 1300] yticks = [[0.7, 0.8, 0.9, 1], [-0.2, 0, 0.2, 0.4], [-0.5, 0, 0.5], [-1, -0.5, 0], [-0.5, 0, 0.5], [-0.5, 0, 0.5, 1]] def latexify(ticklabels): return [r"$" + str(label) + "$" for label in ticklabels] for ii in range(ndim): fig = plt.figure(figsize=(2.2,1.3), constrained_layout=True) fig.set_constrained_layout_pads(w_pad=0, h_pad=0) ax = plt.axes() plt.plot(data[:,0], data[:,ii+1], 'k-', linewidth=0.75) plt.xlabel('$t$') plt.ylabel('$z_{' + str(ii+1) + '}$') plt.xlim(xticks[0], xticks[-1]) plt.ylim(yticks[ii][0], yticks[ii][-1]) ax.set_xticks(xticks) ax.set_yticks(yticks[ii]) ax.set_xticklabels(latexify(xticks)) ax.set_yticklabels(latexify(yticks[ii])) ax.yaxis.set_label_coords(-0.2, 0.5) ax.tick_params(direction='in', length=2) plt.savefig('traj' + str(ii+1) + '.pdf')
true
true
f7168651a64c6d1d8e833e8659ea210c7750b724
662
py
Python
exercicio55Corrigido.py
adrianomdantas/Exercicios-Python
ef5025a186615258aec0cf35ed839fe49577d983
[ "MIT" ]
null
null
null
exercicio55Corrigido.py
adrianomdantas/Exercicios-Python
ef5025a186615258aec0cf35ed839fe49577d983
[ "MIT" ]
null
null
null
exercicio55Corrigido.py
adrianomdantas/Exercicios-Python
ef5025a186615258aec0cf35ed839fe49577d983
[ "MIT" ]
null
null
null
'''maior = 0 menor = 0 for p in range(1, 6): peso = float(input('digite o {}o peso '.format(p))) if p == 1: menor = peso maior = peso else: if peso >= maior: maior = peso if peso < menor: menor = peso print('O maior peso registrado foi {:.1f}kg \nO menor peso registrado foi {:.1f}kg'.format(maior, menor)) ''' lst=[] #lista vazia for c in range(1, 6): peso=float(input('Peso da {}ª pessoa: '.format(c))) lst+=[peso] #adc os valores de peso na lista print('') print('O Maior peso foi:', max(lst)) #maximo valor da lista print('O Menor peso foi:', min(lst)) #minimo valor da lista
28.782609
105
0.575529
lst=[] for c in range(1, 6): peso=float(input('Peso da {}ª pessoa: '.format(c))) lst+=[peso] print('') print('O Maior peso foi:', max(lst)) print('O Menor peso foi:', min(lst))
true
true
f71686608991387d6cf7844d049a4fbe7531d303
1,071
py
Python
learning/set-background-image-v2.py
CrtomirJuren/pyfirmata-arduino
020873972d119955e80387f44bcc193ad0b460a6
[ "MIT" ]
null
null
null
learning/set-background-image-v2.py
CrtomirJuren/pyfirmata-arduino
020873972d119955e80387f44bcc193ad0b460a6
[ "MIT" ]
null
null
null
learning/set-background-image-v2.py
CrtomirJuren/pyfirmata-arduino
020873972d119955e80387f44bcc193ad0b460a6
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Jan 25 15:21:34 2021 @author: crtjur """ import tkinter as tk from PIL import Image, ImageTk root = tk.Tk() root.title("Title") root.geometry("280x350") root.configure(background="black") class Example(tk.Frame): def __init__(self, master, *pargs): tk.Frame.__init__(self, master, *pargs) self.image = Image.open("diagram-v2.png") self.img_copy= self.image.copy() self.background_image = ImageTk.PhotoImage(self.image) self.background = tk.Label(self, image=self.background_image) self.background.pack(fill= tk.BOTH, expand=True) #, self.background.bind('<Configure>', self._resize_image) def _resize_image(self,event): new_width = event.width new_height = event.height self.image = self.img_copy.resize((new_width, new_height)) self.background_image = ImageTk.PhotoImage(self.image) self.background.configure(image = self.background_image) e = Example(root) e.pack(fill=tk.BOTH, expand=True) root.mainloop()
24.340909
69
0.674136
import tkinter as tk from PIL import Image, ImageTk root = tk.Tk() root.title("Title") root.geometry("280x350") root.configure(background="black") class Example(tk.Frame): def __init__(self, master, *pargs): tk.Frame.__init__(self, master, *pargs) self.image = Image.open("diagram-v2.png") self.img_copy= self.image.copy() self.background_image = ImageTk.PhotoImage(self.image) self.background = tk.Label(self, image=self.background_image) self.background.pack(fill= tk.BOTH, expand=True) self.background.bind('<Configure>', self._resize_image) def _resize_image(self,event): new_width = event.width new_height = event.height self.image = self.img_copy.resize((new_width, new_height)) self.background_image = ImageTk.PhotoImage(self.image) self.background.configure(image = self.background_image) e = Example(root) e.pack(fill=tk.BOTH, expand=True) root.mainloop()
true
true
f716868e337d9c56b7761e3167f53df728c5c6c1
4,185
py
Python
tools/train.py
nikhilrayaprolu/food-version2
5fe558ba96be34e52e48ee60bdde2298245a769e
[ "Apache-2.0" ]
null
null
null
tools/train.py
nikhilrayaprolu/food-version2
5fe558ba96be34e52e48ee60bdde2298245a769e
[ "Apache-2.0" ]
null
null
null
tools/train.py
nikhilrayaprolu/food-version2
5fe558ba96be34e52e48ee60bdde2298245a769e
[ "Apache-2.0" ]
1
2020-12-22T08:38:56.000Z
2020-12-22T08:38:56.000Z
from __future__ import division import argparse import os import os.path as osp import time import mmcv import torch from mmcv import Config from mmcv.runner import init_dist from mmdet import __version__ from mmdet.apis import set_random_seed, train_detector from mmdet.datasets import build_dataset from mmdet.models import build_detector from mmdet.utils import get_root_logger import warnings warnings.filterwarnings("ignore") def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') parser.add_argument('--work_dir', help='the dir to save logs and models') parser.add_argument( '--resume_from', help='the checkpoint file to resume from') parser.add_argument( '--validate', action='store_true', help='whether to evaluate the checkpoint during training') parser.add_argument( '--gpus', type=int, default=1, help='number of gpus to use ' '(only applicable to non-distributed training)') parser.add_argument('--seed', type=int, default=None, help='random seed') parser.add_argument( '--deterministic', action='store_true', help='whether to set deterministic options for CUDNN backend.') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) parser.add_argument( '--autoscale-lr', action='store_true', help='automatically scale lr with the number of gpus') args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def main(): args = parse_args() cfg = Config.fromfile(args.config) # set cudnn_benchmark if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True # update configs according to CLI args if args.work_dir is not None: cfg.work_dir = args.work_dir if args.resume_from is not None: cfg.resume_from = args.resume_from cfg.gpus = args.gpus if args.autoscale_lr: # apply the linear scaling rule (https://arxiv.org/abs/1706.02677) cfg.optimizer['lr'] = cfg.optimizer['lr'] * cfg.gpus / 8 # init distributed env first, since logger depends on the dist info. if args.launcher == 'none': distributed = False else: distributed = True init_dist(args.launcher, **cfg.dist_params) # create work_dir mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir)) # init the logger before other steps timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) log_file = osp.join(cfg.work_dir, '{}.log'.format(timestamp)) logger = get_root_logger(log_file=log_file, log_level=cfg.log_level) # log some basic info logger.info('Distributed training: {}'.format(distributed)) logger.info('MMDetection Version: {}'.format(__version__)) logger.info('Config:\n{}'.format(cfg.text)) # set random seeds if args.seed is not None: logger.info('Set random seed to {}, deterministic: {}'.format( args.seed, args.deterministic)) set_random_seed(args.seed, deterministic=args.deterministic) model = build_detector( cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg) datasets = [build_dataset(cfg.data.train)] if len(cfg.workflow) == 2: datasets.append(build_dataset(cfg.data.val)) if cfg.checkpoint_config is not None: # save mmdet version, config file content and class names in # checkpoints as meta data cfg.checkpoint_config.meta = dict( mmdet_version=__version__, config=cfg.text, CLASSES=datasets[0].CLASSES) # add an attribute for visualization convenience model.CLASSES = datasets[0].CLASSES train_detector( model, datasets, cfg, distributed=distributed, validate=args.validate, timestamp=timestamp) if __name__ == '__main__': main()
32.952756
77
0.6681
from __future__ import division import argparse import os import os.path as osp import time import mmcv import torch from mmcv import Config from mmcv.runner import init_dist from mmdet import __version__ from mmdet.apis import set_random_seed, train_detector from mmdet.datasets import build_dataset from mmdet.models import build_detector from mmdet.utils import get_root_logger import warnings warnings.filterwarnings("ignore") def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') parser.add_argument('--work_dir', help='the dir to save logs and models') parser.add_argument( '--resume_from', help='the checkpoint file to resume from') parser.add_argument( '--validate', action='store_true', help='whether to evaluate the checkpoint during training') parser.add_argument( '--gpus', type=int, default=1, help='number of gpus to use ' '(only applicable to non-distributed training)') parser.add_argument('--seed', type=int, default=None, help='random seed') parser.add_argument( '--deterministic', action='store_true', help='whether to set deterministic options for CUDNN backend.') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) parser.add_argument( '--autoscale-lr', action='store_true', help='automatically scale lr with the number of gpus') args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def main(): args = parse_args() cfg = Config.fromfile(args.config) if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True if args.work_dir is not None: cfg.work_dir = args.work_dir if args.resume_from is not None: cfg.resume_from = args.resume_from cfg.gpus = args.gpus if args.autoscale_lr: cfg.optimizer['lr'] = cfg.optimizer['lr'] * cfg.gpus / 8 if args.launcher == 'none': distributed = False else: distributed = True init_dist(args.launcher, **cfg.dist_params) mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir)) timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) log_file = osp.join(cfg.work_dir, '{}.log'.format(timestamp)) logger = get_root_logger(log_file=log_file, log_level=cfg.log_level) logger.info('Distributed training: {}'.format(distributed)) logger.info('MMDetection Version: {}'.format(__version__)) logger.info('Config:\n{}'.format(cfg.text)) if args.seed is not None: logger.info('Set random seed to {}, deterministic: {}'.format( args.seed, args.deterministic)) set_random_seed(args.seed, deterministic=args.deterministic) model = build_detector( cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg) datasets = [build_dataset(cfg.data.train)] if len(cfg.workflow) == 2: datasets.append(build_dataset(cfg.data.val)) if cfg.checkpoint_config is not None: cfg.checkpoint_config.meta = dict( mmdet_version=__version__, config=cfg.text, CLASSES=datasets[0].CLASSES) model.CLASSES = datasets[0].CLASSES train_detector( model, datasets, cfg, distributed=distributed, validate=args.validate, timestamp=timestamp) if __name__ == '__main__': main()
true
true
f71687e21d8ea9780570ef161a23f33fdc061d2f
2,837
py
Python
samples/basic/executor/models/cisco-ios-xr/Cisco-IOS-XR-snmp-test-trap-act/nc-execute-xr-snmp-test-trap-act-115-ydk.py
maccioni/ydk-py-samples
d1758694bef97327c5477e65649326c7595ce499
[ "Apache-2.0" ]
1
2021-07-08T14:02:12.000Z
2021-07-08T14:02:12.000Z
samples/basic/executor/models/cisco-ios-xr/Cisco-IOS-XR-snmp-test-trap-act/nc-execute-xr-snmp-test-trap-act-115-ydk.py
maccioni/ydk-py-samples
d1758694bef97327c5477e65649326c7595ce499
[ "Apache-2.0" ]
null
null
null
samples/basic/executor/models/cisco-ios-xr/Cisco-IOS-XR-snmp-test-trap-act/nc-execute-xr-snmp-test-trap-act-115-ydk.py
maccioni/ydk-py-samples
d1758694bef97327c5477e65649326c7595ce499
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # # Copyright 2016 Cisco Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Execute RPC for model Cisco-IOS-XR-snmp-test-trap-act. usage: nc-execute-xr-snmp-test-trap-act-115-ydk.py [-h] [-v] device positional arguments: device NETCONF device (ssh://user:password@host:port) optional arguments: -h, --help show this help message and exit -v, --verbose print debugging messages """ from argparse import ArgumentParser from urlparse import urlparse from ydk.services import ExecutorService from ydk.providers import NetconfServiceProvider from ydk.models.cisco_ios_xr import Cisco_IOS_XR_snmp_test_trap_act \ as xr_snmp_test_trap_act import logging def prepare_sonet_line_status_rpc(sonet_line_status_rpc): """Add RPC input data to sonet_line_status_rpc object.""" pass if __name__ == "__main__": """Execute main program.""" parser = ArgumentParser() parser.add_argument("-v", "--verbose", help="print debugging messages", action="store_true") parser.add_argument("device", help="NETCONF device (ssh://user:password@host:port)") args = parser.parse_args() device = urlparse(args.device) # log debug messages if verbose argument specified if args.verbose: logger = logging.getLogger("ydk") logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter(("%(asctime)s - %(name)s - " "%(levelname)s - %(message)s")) handler.setFormatter(formatter) logger.addHandler(handler) # create NETCONF provider provider = NetconfServiceProvider(address=device.hostname, port=device.port, username=device.username, password=device.password, protocol=device.scheme) # create executor service executor = ExecutorService() sonet_line_status_rpc = xr_snmp_test_trap_act.SonetLineStatusRpc() # create object prepare_sonet_line_status_rpc(sonet_line_status_rpc) # add RPC input # execute RPC on NETCONF device # executor.execute_rpc(provider, sonet_line_status_rpc) exit() # End of script
34.180723
87
0.673599
from argparse import ArgumentParser from urlparse import urlparse from ydk.services import ExecutorService from ydk.providers import NetconfServiceProvider from ydk.models.cisco_ios_xr import Cisco_IOS_XR_snmp_test_trap_act \ as xr_snmp_test_trap_act import logging def prepare_sonet_line_status_rpc(sonet_line_status_rpc): pass if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("-v", "--verbose", help="print debugging messages", action="store_true") parser.add_argument("device", help="NETCONF device (ssh://user:password@host:port)") args = parser.parse_args() device = urlparse(args.device) if args.verbose: logger = logging.getLogger("ydk") logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter(("%(asctime)s - %(name)s - " "%(levelname)s - %(message)s")) handler.setFormatter(formatter) logger.addHandler(handler) provider = NetconfServiceProvider(address=device.hostname, port=device.port, username=device.username, password=device.password, protocol=device.scheme) executor = ExecutorService() sonet_line_status_rpc = xr_snmp_test_trap_act.SonetLineStatusRpc() prepare_sonet_line_status_rpc(sonet_line_status_rpc) exit()
true
true
f7168881dda3037f1831c4695a51ad6b12964680
963
py
Python
membership/forms.py
carpentries/membershipdb
9f6270cea7251c490686926f041e21a929218e6c
[ "MIT" ]
3
2018-05-31T16:09:52.000Z
2018-09-30T21:35:06.000Z
membership/forms.py
carpentries/membershipdb
9f6270cea7251c490686926f041e21a929218e6c
[ "MIT" ]
5
2018-06-19T21:51:16.000Z
2020-01-19T20:18:48.000Z
membership/forms.py
carpentries/membershipdb
9f6270cea7251c490686926f041e21a929218e6c
[ "MIT" ]
1
2020-07-07T03:23:34.000Z
2020-07-07T03:23:34.000Z
"""Membership forms module """ from django.forms import ModelForm from .models import Note, Term, Organization, Contact, Membership class NoteForm(ModelForm): """Note Form """ class Meta: model = Note fields = ['title', 'content', 'date_time'] class TermForm(ModelForm): """Term Form """ class Meta: model = Term fields = ['mem_type', 'n_workshops', 'n_instructors', 'reserve', 'inh_trainer', 'local_train', 'publicize', 'recruit', 'coordinate'] class OrganizationForm(ModelForm): """Organization Form """ class Meta: model = Organization fields = [] class ContactForm(ModelForm): """Contact Form """ class Meta: model = Contact fields = [] class MembershipForm(ModelForm): """Membership Form """ class Meta: model = Membership fields = []
19.26
65
0.553479
from django.forms import ModelForm from .models import Note, Term, Organization, Contact, Membership class NoteForm(ModelForm): class Meta: model = Note fields = ['title', 'content', 'date_time'] class TermForm(ModelForm): class Meta: model = Term fields = ['mem_type', 'n_workshops', 'n_instructors', 'reserve', 'inh_trainer', 'local_train', 'publicize', 'recruit', 'coordinate'] class OrganizationForm(ModelForm): class Meta: model = Organization fields = [] class ContactForm(ModelForm): class Meta: model = Contact fields = [] class MembershipForm(ModelForm): class Meta: model = Membership fields = []
true
true
f71688edd94f6768ac57dec0eba3a526f1529856
28,910
py
Python
sdk/python/pulumi_azure_native/insights/v20150501/component.py
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/insights/v20150501/component.py
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/insights/v20150501/component.py
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * __all__ = ['ComponentArgs', 'Component'] @pulumi.input_type class ComponentArgs: def __init__(__self__, *, application_type: pulumi.Input[Union[str, 'ApplicationType']], kind: pulumi.Input[str], resource_group_name: pulumi.Input[str], disable_ip_masking: Optional[pulumi.Input[bool]] = None, flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None, hockey_app_id: Optional[pulumi.Input[str]] = None, immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None, ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None, location: Optional[pulumi.Input[str]] = None, request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None, resource_name: Optional[pulumi.Input[str]] = None, retention_in_days: Optional[pulumi.Input[int]] = None, sampling_percentage: Optional[pulumi.Input[float]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): """ The set of arguments for constructing a Component resource. :param pulumi.Input[Union[str, 'ApplicationType']] application_type: Type of application being monitored. :param pulumi.Input[str] kind: The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone. :param pulumi.Input[str] resource_group_name: The name of the resource group. The name is case insensitive. :param pulumi.Input[bool] disable_ip_masking: Disable IP masking. :param pulumi.Input[Union[str, 'FlowType']] flow_type: Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API. :param pulumi.Input[str] hockey_app_id: The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp. :param pulumi.Input[bool] immediate_purge_data_on30_days: Purge data immediately after 30 days. :param pulumi.Input[Union[str, 'IngestionMode']] ingestion_mode: Indicates the flow of the ingestion. :param pulumi.Input[str] location: Resource location :param pulumi.Input[Union[str, 'RequestSource']] request_source: Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'. :param pulumi.Input[str] resource_name: The name of the Application Insights component resource. :param pulumi.Input[int] retention_in_days: Retention period in days. :param pulumi.Input[float] sampling_percentage: Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags """ if application_type is None: application_type = 'web' pulumi.set(__self__, "application_type", application_type) pulumi.set(__self__, "kind", kind) pulumi.set(__self__, "resource_group_name", resource_group_name) if disable_ip_masking is not None: pulumi.set(__self__, "disable_ip_masking", disable_ip_masking) if flow_type is None: flow_type = 'Bluefield' if flow_type is not None: pulumi.set(__self__, "flow_type", flow_type) if hockey_app_id is not None: pulumi.set(__self__, "hockey_app_id", hockey_app_id) if immediate_purge_data_on30_days is not None: pulumi.set(__self__, "immediate_purge_data_on30_days", immediate_purge_data_on30_days) if ingestion_mode is None: ingestion_mode = 'ApplicationInsights' if ingestion_mode is not None: pulumi.set(__self__, "ingestion_mode", ingestion_mode) if location is not None: pulumi.set(__self__, "location", location) if request_source is None: request_source = 'rest' if request_source is not None: pulumi.set(__self__, "request_source", request_source) if resource_name is not None: pulumi.set(__self__, "resource_name", resource_name) if retention_in_days is None: retention_in_days = 90 if retention_in_days is not None: pulumi.set(__self__, "retention_in_days", retention_in_days) if sampling_percentage is not None: pulumi.set(__self__, "sampling_percentage", sampling_percentage) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="applicationType") def application_type(self) -> pulumi.Input[Union[str, 'ApplicationType']]: """ Type of application being monitored. """ return pulumi.get(self, "application_type") @application_type.setter def application_type(self, value: pulumi.Input[Union[str, 'ApplicationType']]): pulumi.set(self, "application_type", value) @property @pulumi.getter def kind(self) -> pulumi.Input[str]: """ The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone. """ return pulumi.get(self, "kind") @kind.setter def kind(self, value: pulumi.Input[str]): pulumi.set(self, "kind", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ The name of the resource group. The name is case insensitive. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="disableIpMasking") def disable_ip_masking(self) -> Optional[pulumi.Input[bool]]: """ Disable IP masking. """ return pulumi.get(self, "disable_ip_masking") @disable_ip_masking.setter def disable_ip_masking(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "disable_ip_masking", value) @property @pulumi.getter(name="flowType") def flow_type(self) -> Optional[pulumi.Input[Union[str, 'FlowType']]]: """ Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API. """ return pulumi.get(self, "flow_type") @flow_type.setter def flow_type(self, value: Optional[pulumi.Input[Union[str, 'FlowType']]]): pulumi.set(self, "flow_type", value) @property @pulumi.getter(name="hockeyAppId") def hockey_app_id(self) -> Optional[pulumi.Input[str]]: """ The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp. """ return pulumi.get(self, "hockey_app_id") @hockey_app_id.setter def hockey_app_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "hockey_app_id", value) @property @pulumi.getter(name="immediatePurgeDataOn30Days") def immediate_purge_data_on30_days(self) -> Optional[pulumi.Input[bool]]: """ Purge data immediately after 30 days. """ return pulumi.get(self, "immediate_purge_data_on30_days") @immediate_purge_data_on30_days.setter def immediate_purge_data_on30_days(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "immediate_purge_data_on30_days", value) @property @pulumi.getter(name="ingestionMode") def ingestion_mode(self) -> Optional[pulumi.Input[Union[str, 'IngestionMode']]]: """ Indicates the flow of the ingestion. """ return pulumi.get(self, "ingestion_mode") @ingestion_mode.setter def ingestion_mode(self, value: Optional[pulumi.Input[Union[str, 'IngestionMode']]]): pulumi.set(self, "ingestion_mode", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: """ Resource location """ return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter(name="requestSource") def request_source(self) -> Optional[pulumi.Input[Union[str, 'RequestSource']]]: """ Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'. """ return pulumi.get(self, "request_source") @request_source.setter def request_source(self, value: Optional[pulumi.Input[Union[str, 'RequestSource']]]): pulumi.set(self, "request_source", value) @property @pulumi.getter(name="resourceName") def resource_name(self) -> Optional[pulumi.Input[str]]: """ The name of the Application Insights component resource. """ return pulumi.get(self, "resource_name") @resource_name.setter def resource_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "resource_name", value) @property @pulumi.getter(name="retentionInDays") def retention_in_days(self) -> Optional[pulumi.Input[int]]: """ Retention period in days. """ return pulumi.get(self, "retention_in_days") @retention_in_days.setter def retention_in_days(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "retention_in_days", value) @property @pulumi.getter(name="samplingPercentage") def sampling_percentage(self) -> Optional[pulumi.Input[float]]: """ Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry. """ return pulumi.get(self, "sampling_percentage") @sampling_percentage.setter def sampling_percentage(self, value: Optional[pulumi.Input[float]]): pulumi.set(self, "sampling_percentage", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ Resource tags """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) class Component(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None, disable_ip_masking: Optional[pulumi.Input[bool]] = None, flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None, hockey_app_id: Optional[pulumi.Input[str]] = None, immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None, ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None, kind: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, resource_name_: Optional[pulumi.Input[str]] = None, retention_in_days: Optional[pulumi.Input[int]] = None, sampling_percentage: Optional[pulumi.Input[float]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): """ An Application Insights component definition. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Union[str, 'ApplicationType']] application_type: Type of application being monitored. :param pulumi.Input[bool] disable_ip_masking: Disable IP masking. :param pulumi.Input[Union[str, 'FlowType']] flow_type: Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API. :param pulumi.Input[str] hockey_app_id: The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp. :param pulumi.Input[bool] immediate_purge_data_on30_days: Purge data immediately after 30 days. :param pulumi.Input[Union[str, 'IngestionMode']] ingestion_mode: Indicates the flow of the ingestion. :param pulumi.Input[str] kind: The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone. :param pulumi.Input[str] location: Resource location :param pulumi.Input[Union[str, 'RequestSource']] request_source: Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'. :param pulumi.Input[str] resource_group_name: The name of the resource group. The name is case insensitive. :param pulumi.Input[str] resource_name_: The name of the Application Insights component resource. :param pulumi.Input[int] retention_in_days: Retention period in days. :param pulumi.Input[float] sampling_percentage: Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags """ ... @overload def __init__(__self__, resource_name: str, args: ComponentArgs, opts: Optional[pulumi.ResourceOptions] = None): """ An Application Insights component definition. :param str resource_name: The name of the resource. :param ComponentArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ComponentArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None, disable_ip_masking: Optional[pulumi.Input[bool]] = None, flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None, hockey_app_id: Optional[pulumi.Input[str]] = None, immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None, ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None, kind: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, resource_name_: Optional[pulumi.Input[str]] = None, retention_in_days: Optional[pulumi.Input[int]] = None, sampling_percentage: Optional[pulumi.Input[float]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ComponentArgs.__new__(ComponentArgs) if application_type is None: application_type = 'web' if application_type is None and not opts.urn: raise TypeError("Missing required property 'application_type'") __props__.__dict__["application_type"] = application_type __props__.__dict__["disable_ip_masking"] = disable_ip_masking if flow_type is None: flow_type = 'Bluefield' __props__.__dict__["flow_type"] = flow_type __props__.__dict__["hockey_app_id"] = hockey_app_id __props__.__dict__["immediate_purge_data_on30_days"] = immediate_purge_data_on30_days if ingestion_mode is None: ingestion_mode = 'ApplicationInsights' __props__.__dict__["ingestion_mode"] = ingestion_mode if kind is None and not opts.urn: raise TypeError("Missing required property 'kind'") __props__.__dict__["kind"] = kind __props__.__dict__["location"] = location if request_source is None: request_source = 'rest' __props__.__dict__["request_source"] = request_source if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["resource_name"] = resource_name_ if retention_in_days is None: retention_in_days = 90 __props__.__dict__["retention_in_days"] = retention_in_days __props__.__dict__["sampling_percentage"] = sampling_percentage __props__.__dict__["tags"] = tags __props__.__dict__["app_id"] = None __props__.__dict__["application_id"] = None __props__.__dict__["connection_string"] = None __props__.__dict__["creation_date"] = None __props__.__dict__["hockey_app_token"] = None __props__.__dict__["instrumentation_key"] = None __props__.__dict__["name"] = None __props__.__dict__["private_link_scoped_resources"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["tenant_id"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:insights/v20150501:Component"), pulumi.Alias(type_="azure-native:insights:Component"), pulumi.Alias(type_="azure-nextgen:insights:Component"), pulumi.Alias(type_="azure-native:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-native:insights/v20200202:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202:Component"), pulumi.Alias(type_="azure-native:insights/v20200202preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202preview:Component")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(Component, __self__).__init__( 'azure-native:insights/v20150501:Component', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Component': """ Get an existing Component resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ComponentArgs.__new__(ComponentArgs) __props__.__dict__["app_id"] = None __props__.__dict__["application_id"] = None __props__.__dict__["application_type"] = None __props__.__dict__["connection_string"] = None __props__.__dict__["creation_date"] = None __props__.__dict__["disable_ip_masking"] = None __props__.__dict__["flow_type"] = None __props__.__dict__["hockey_app_id"] = None __props__.__dict__["hockey_app_token"] = None __props__.__dict__["immediate_purge_data_on30_days"] = None __props__.__dict__["ingestion_mode"] = None __props__.__dict__["instrumentation_key"] = None __props__.__dict__["kind"] = None __props__.__dict__["location"] = None __props__.__dict__["name"] = None __props__.__dict__["private_link_scoped_resources"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["request_source"] = None __props__.__dict__["retention_in_days"] = None __props__.__dict__["sampling_percentage"] = None __props__.__dict__["tags"] = None __props__.__dict__["tenant_id"] = None __props__.__dict__["type"] = None return Component(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="appId") def app_id(self) -> pulumi.Output[str]: """ Application Insights Unique ID for your Application. """ return pulumi.get(self, "app_id") @property @pulumi.getter(name="applicationId") def application_id(self) -> pulumi.Output[str]: """ The unique ID of your application. This field mirrors the 'Name' field and cannot be changed. """ return pulumi.get(self, "application_id") @property @pulumi.getter(name="applicationType") def application_type(self) -> pulumi.Output[str]: """ Type of application being monitored. """ return pulumi.get(self, "application_type") @property @pulumi.getter(name="connectionString") def connection_string(self) -> pulumi.Output[str]: """ Application Insights component connection string. """ return pulumi.get(self, "connection_string") @property @pulumi.getter(name="creationDate") def creation_date(self) -> pulumi.Output[str]: """ Creation Date for the Application Insights component, in ISO 8601 format. """ return pulumi.get(self, "creation_date") @property @pulumi.getter(name="disableIpMasking") def disable_ip_masking(self) -> pulumi.Output[Optional[bool]]: """ Disable IP masking. """ return pulumi.get(self, "disable_ip_masking") @property @pulumi.getter(name="flowType") def flow_type(self) -> pulumi.Output[Optional[str]]: """ Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API. """ return pulumi.get(self, "flow_type") @property @pulumi.getter(name="hockeyAppId") def hockey_app_id(self) -> pulumi.Output[Optional[str]]: """ The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp. """ return pulumi.get(self, "hockey_app_id") @property @pulumi.getter(name="hockeyAppToken") def hockey_app_token(self) -> pulumi.Output[str]: """ Token used to authenticate communications with between Application Insights and HockeyApp. """ return pulumi.get(self, "hockey_app_token") @property @pulumi.getter(name="immediatePurgeDataOn30Days") def immediate_purge_data_on30_days(self) -> pulumi.Output[Optional[bool]]: """ Purge data immediately after 30 days. """ return pulumi.get(self, "immediate_purge_data_on30_days") @property @pulumi.getter(name="ingestionMode") def ingestion_mode(self) -> pulumi.Output[Optional[str]]: """ Indicates the flow of the ingestion. """ return pulumi.get(self, "ingestion_mode") @property @pulumi.getter(name="instrumentationKey") def instrumentation_key(self) -> pulumi.Output[str]: """ Application Insights Instrumentation key. A read-only value that applications can use to identify the destination for all telemetry sent to Azure Application Insights. This value will be supplied upon construction of each new Application Insights component. """ return pulumi.get(self, "instrumentation_key") @property @pulumi.getter def kind(self) -> pulumi.Output[str]: """ The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone. """ return pulumi.get(self, "kind") @property @pulumi.getter def location(self) -> pulumi.Output[str]: """ Resource location """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Azure resource name """ return pulumi.get(self, "name") @property @pulumi.getter(name="privateLinkScopedResources") def private_link_scoped_resources(self) -> pulumi.Output[Sequence['outputs.PrivateLinkScopedResourceResponse']]: """ List of linked private link scope resources. """ return pulumi.get(self, "private_link_scoped_resources") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ Current state of this component: whether or not is has been provisioned within the resource group it is defined. Users cannot change this value but are able to read from it. Values will include Succeeded, Deploying, Canceled, and Failed. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="requestSource") def request_source(self) -> pulumi.Output[Optional[str]]: """ Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'. """ return pulumi.get(self, "request_source") @property @pulumi.getter(name="retentionInDays") def retention_in_days(self) -> pulumi.Output[Optional[int]]: """ Retention period in days. """ return pulumi.get(self, "retention_in_days") @property @pulumi.getter(name="samplingPercentage") def sampling_percentage(self) -> pulumi.Output[Optional[float]]: """ Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry. """ return pulumi.get(self, "sampling_percentage") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Resource tags """ return pulumi.get(self, "tags") @property @pulumi.getter(name="tenantId") def tenant_id(self) -> pulumi.Output[str]: """ Azure Tenant Id. """ return pulumi.get(self, "tenant_id") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Azure resource type """ return pulumi.get(self, "type")
46.779935
651
0.661397
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * __all__ = ['ComponentArgs', 'Component'] @pulumi.input_type class ComponentArgs: def __init__(__self__, *, application_type: pulumi.Input[Union[str, 'ApplicationType']], kind: pulumi.Input[str], resource_group_name: pulumi.Input[str], disable_ip_masking: Optional[pulumi.Input[bool]] = None, flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None, hockey_app_id: Optional[pulumi.Input[str]] = None, immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None, ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None, location: Optional[pulumi.Input[str]] = None, request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None, resource_name: Optional[pulumi.Input[str]] = None, retention_in_days: Optional[pulumi.Input[int]] = None, sampling_percentage: Optional[pulumi.Input[float]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): if application_type is None: application_type = 'web' pulumi.set(__self__, "application_type", application_type) pulumi.set(__self__, "kind", kind) pulumi.set(__self__, "resource_group_name", resource_group_name) if disable_ip_masking is not None: pulumi.set(__self__, "disable_ip_masking", disable_ip_masking) if flow_type is None: flow_type = 'Bluefield' if flow_type is not None: pulumi.set(__self__, "flow_type", flow_type) if hockey_app_id is not None: pulumi.set(__self__, "hockey_app_id", hockey_app_id) if immediate_purge_data_on30_days is not None: pulumi.set(__self__, "immediate_purge_data_on30_days", immediate_purge_data_on30_days) if ingestion_mode is None: ingestion_mode = 'ApplicationInsights' if ingestion_mode is not None: pulumi.set(__self__, "ingestion_mode", ingestion_mode) if location is not None: pulumi.set(__self__, "location", location) if request_source is None: request_source = 'rest' if request_source is not None: pulumi.set(__self__, "request_source", request_source) if resource_name is not None: pulumi.set(__self__, "resource_name", resource_name) if retention_in_days is None: retention_in_days = 90 if retention_in_days is not None: pulumi.set(__self__, "retention_in_days", retention_in_days) if sampling_percentage is not None: pulumi.set(__self__, "sampling_percentage", sampling_percentage) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="applicationType") def application_type(self) -> pulumi.Input[Union[str, 'ApplicationType']]: return pulumi.get(self, "application_type") @application_type.setter def application_type(self, value: pulumi.Input[Union[str, 'ApplicationType']]): pulumi.set(self, "application_type", value) @property @pulumi.getter def kind(self) -> pulumi.Input[str]: return pulumi.get(self, "kind") @kind.setter def kind(self, value: pulumi.Input[str]): pulumi.set(self, "kind", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="disableIpMasking") def disable_ip_masking(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "disable_ip_masking") @disable_ip_masking.setter def disable_ip_masking(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "disable_ip_masking", value) @property @pulumi.getter(name="flowType") def flow_type(self) -> Optional[pulumi.Input[Union[str, 'FlowType']]]: return pulumi.get(self, "flow_type") @flow_type.setter def flow_type(self, value: Optional[pulumi.Input[Union[str, 'FlowType']]]): pulumi.set(self, "flow_type", value) @property @pulumi.getter(name="hockeyAppId") def hockey_app_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "hockey_app_id") @hockey_app_id.setter def hockey_app_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "hockey_app_id", value) @property @pulumi.getter(name="immediatePurgeDataOn30Days") def immediate_purge_data_on30_days(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "immediate_purge_data_on30_days") @immediate_purge_data_on30_days.setter def immediate_purge_data_on30_days(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "immediate_purge_data_on30_days", value) @property @pulumi.getter(name="ingestionMode") def ingestion_mode(self) -> Optional[pulumi.Input[Union[str, 'IngestionMode']]]: return pulumi.get(self, "ingestion_mode") @ingestion_mode.setter def ingestion_mode(self, value: Optional[pulumi.Input[Union[str, 'IngestionMode']]]): pulumi.set(self, "ingestion_mode", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter(name="requestSource") def request_source(self) -> Optional[pulumi.Input[Union[str, 'RequestSource']]]: return pulumi.get(self, "request_source") @request_source.setter def request_source(self, value: Optional[pulumi.Input[Union[str, 'RequestSource']]]): pulumi.set(self, "request_source", value) @property @pulumi.getter(name="resourceName") def resource_name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "resource_name") @resource_name.setter def resource_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "resource_name", value) @property @pulumi.getter(name="retentionInDays") def retention_in_days(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "retention_in_days") @retention_in_days.setter def retention_in_days(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "retention_in_days", value) @property @pulumi.getter(name="samplingPercentage") def sampling_percentage(self) -> Optional[pulumi.Input[float]]: return pulumi.get(self, "sampling_percentage") @sampling_percentage.setter def sampling_percentage(self, value: Optional[pulumi.Input[float]]): pulumi.set(self, "sampling_percentage", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) class Component(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None, disable_ip_masking: Optional[pulumi.Input[bool]] = None, flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None, hockey_app_id: Optional[pulumi.Input[str]] = None, immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None, ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None, kind: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, resource_name_: Optional[pulumi.Input[str]] = None, retention_in_days: Optional[pulumi.Input[int]] = None, sampling_percentage: Optional[pulumi.Input[float]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): ... @overload def __init__(__self__, resource_name: str, args: ComponentArgs, opts: Optional[pulumi.ResourceOptions] = None): ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ComponentArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None, disable_ip_masking: Optional[pulumi.Input[bool]] = None, flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None, hockey_app_id: Optional[pulumi.Input[str]] = None, immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None, ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None, kind: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, resource_name_: Optional[pulumi.Input[str]] = None, retention_in_days: Optional[pulumi.Input[int]] = None, sampling_percentage: Optional[pulumi.Input[float]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ComponentArgs.__new__(ComponentArgs) if application_type is None: application_type = 'web' if application_type is None and not opts.urn: raise TypeError("Missing required property 'application_type'") __props__.__dict__["application_type"] = application_type __props__.__dict__["disable_ip_masking"] = disable_ip_masking if flow_type is None: flow_type = 'Bluefield' __props__.__dict__["flow_type"] = flow_type __props__.__dict__["hockey_app_id"] = hockey_app_id __props__.__dict__["immediate_purge_data_on30_days"] = immediate_purge_data_on30_days if ingestion_mode is None: ingestion_mode = 'ApplicationInsights' __props__.__dict__["ingestion_mode"] = ingestion_mode if kind is None and not opts.urn: raise TypeError("Missing required property 'kind'") __props__.__dict__["kind"] = kind __props__.__dict__["location"] = location if request_source is None: request_source = 'rest' __props__.__dict__["request_source"] = request_source if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["resource_name"] = resource_name_ if retention_in_days is None: retention_in_days = 90 __props__.__dict__["retention_in_days"] = retention_in_days __props__.__dict__["sampling_percentage"] = sampling_percentage __props__.__dict__["tags"] = tags __props__.__dict__["app_id"] = None __props__.__dict__["application_id"] = None __props__.__dict__["connection_string"] = None __props__.__dict__["creation_date"] = None __props__.__dict__["hockey_app_token"] = None __props__.__dict__["instrumentation_key"] = None __props__.__dict__["name"] = None __props__.__dict__["private_link_scoped_resources"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["tenant_id"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:insights/v20150501:Component"), pulumi.Alias(type_="azure-native:insights:Component"), pulumi.Alias(type_="azure-nextgen:insights:Component"), pulumi.Alias(type_="azure-native:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-native:insights/v20200202:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202:Component"), pulumi.Alias(type_="azure-native:insights/v20200202preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202preview:Component")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(Component, __self__).__init__( 'azure-native:insights/v20150501:Component', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Component': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ComponentArgs.__new__(ComponentArgs) __props__.__dict__["app_id"] = None __props__.__dict__["application_id"] = None __props__.__dict__["application_type"] = None __props__.__dict__["connection_string"] = None __props__.__dict__["creation_date"] = None __props__.__dict__["disable_ip_masking"] = None __props__.__dict__["flow_type"] = None __props__.__dict__["hockey_app_id"] = None __props__.__dict__["hockey_app_token"] = None __props__.__dict__["immediate_purge_data_on30_days"] = None __props__.__dict__["ingestion_mode"] = None __props__.__dict__["instrumentation_key"] = None __props__.__dict__["kind"] = None __props__.__dict__["location"] = None __props__.__dict__["name"] = None __props__.__dict__["private_link_scoped_resources"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["request_source"] = None __props__.__dict__["retention_in_days"] = None __props__.__dict__["sampling_percentage"] = None __props__.__dict__["tags"] = None __props__.__dict__["tenant_id"] = None __props__.__dict__["type"] = None return Component(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="appId") def app_id(self) -> pulumi.Output[str]: return pulumi.get(self, "app_id") @property @pulumi.getter(name="applicationId") def application_id(self) -> pulumi.Output[str]: return pulumi.get(self, "application_id") @property @pulumi.getter(name="applicationType") def application_type(self) -> pulumi.Output[str]: return pulumi.get(self, "application_type") @property @pulumi.getter(name="connectionString") def connection_string(self) -> pulumi.Output[str]: return pulumi.get(self, "connection_string") @property @pulumi.getter(name="creationDate") def creation_date(self) -> pulumi.Output[str]: return pulumi.get(self, "creation_date") @property @pulumi.getter(name="disableIpMasking") def disable_ip_masking(self) -> pulumi.Output[Optional[bool]]: return pulumi.get(self, "disable_ip_masking") @property @pulumi.getter(name="flowType") def flow_type(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "flow_type") @property @pulumi.getter(name="hockeyAppId") def hockey_app_id(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "hockey_app_id") @property @pulumi.getter(name="hockeyAppToken") def hockey_app_token(self) -> pulumi.Output[str]: return pulumi.get(self, "hockey_app_token") @property @pulumi.getter(name="immediatePurgeDataOn30Days") def immediate_purge_data_on30_days(self) -> pulumi.Output[Optional[bool]]: return pulumi.get(self, "immediate_purge_data_on30_days") @property @pulumi.getter(name="ingestionMode") def ingestion_mode(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "ingestion_mode") @property @pulumi.getter(name="instrumentationKey") def instrumentation_key(self) -> pulumi.Output[str]: return pulumi.get(self, "instrumentation_key") @property @pulumi.getter def kind(self) -> pulumi.Output[str]: return pulumi.get(self, "kind") @property @pulumi.getter def location(self) -> pulumi.Output[str]: return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, "name") @property @pulumi.getter(name="privateLinkScopedResources") def private_link_scoped_resources(self) -> pulumi.Output[Sequence['outputs.PrivateLinkScopedResourceResponse']]: return pulumi.get(self, "private_link_scoped_resources") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="requestSource") def request_source(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "request_source") @property @pulumi.getter(name="retentionInDays") def retention_in_days(self) -> pulumi.Output[Optional[int]]: return pulumi.get(self, "retention_in_days") @property @pulumi.getter(name="samplingPercentage") def sampling_percentage(self) -> pulumi.Output[Optional[float]]: return pulumi.get(self, "sampling_percentage") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: return pulumi.get(self, "tags") @property @pulumi.getter(name="tenantId") def tenant_id(self) -> pulumi.Output[str]: return pulumi.get(self, "tenant_id") @property @pulumi.getter def type(self) -> pulumi.Output[str]: return pulumi.get(self, "type")
true
true
f7168a4422b050f7d1300a0db6bbaf4282e7bd75
1,953
py
Python
jungle/code/sorting.py
nate-russell/Jungle
114d744ed66fec11b8d5e62444253892a7ffa5cd
[ "MIT" ]
null
null
null
jungle/code/sorting.py
nate-russell/Jungle
114d744ed66fec11b8d5e62444253892a7ffa5cd
[ "MIT" ]
4
2017-12-28T02:07:33.000Z
2018-01-04T06:38:43.000Z
jungle/code/sorting.py
nate-russell/Jungle
114d744ed66fec11b8d5e62444253892a7ffa5cd
[ "MIT" ]
null
null
null
''' Sorting Examples for showcasing and developing Jungle features ''' import inspect from jungle import JungleExperiment, JungleProfiler import numpy as np print('Finished Loading Modules') class Sorting_Prototype: print('\n---Test Sort N---') @JungleExperiment(reps=1, n=[100, 500]) def test_sort_n(self, n=100, seed=1234): ''' Test sorting an iterable of size n with a random distribution ''' # make data to sort with random distribution np.random.seed(seed) list_2_sort = list(np.random.randn(n)) @JungleProfiler() def sort_n(l): sorted_list = self.sort(l) return sorted_list # Sort and check sort status sorted_list, _ = sort_n(list_2_sort) sort_status = all(sorted_list[i] <= sorted_list[i + 1] for i in range(len(sorted_list) - 1)) return sort_status print('\n---Test Block Sort---') @JungleExperiment(reps=1, n_blocks=[2, 4], block_size=[50, 100]) @JungleProfiler() def test_block_random_sort(self, n_blocks=4, block_size=100): print('n_blocks: %s' % n_blocks) print('block_size: %s' % block_size) return 'something' class NP_QuickSort(Sorting_Prototype): def sort(self, l): return np.sort(l, kind='quicksort') class NP_MergeSort(Sorting_Prototype): def sort(self, l): return np.sort(l, kind='mergesort') class NP_HeapSort(Sorting_Prototype): def sort(self, l): return np.sort(l, kind='heapsort') if __name__ == '__main__': print('\n__main__\n') print('\n---Starting Call #1---') m1 = NP_QuickSort() jc1 = m1.test_sort_n() print('\n---Starting Call #2---') m2 = NP_MergeSort() jc2 = m2.test_sort_n() print('\n---Starting Call #3---') m1 = NP_QuickSort() jc1 = m1.test_block_random_sort() print('\n---Starting Call #4---') m2 = NP_MergeSort() jc2 = m2.test_block_random_sort()
24.721519
100
0.63236
import inspect from jungle import JungleExperiment, JungleProfiler import numpy as np print('Finished Loading Modules') class Sorting_Prototype: print('\n---Test Sort N---') @JungleExperiment(reps=1, n=[100, 500]) def test_sort_n(self, n=100, seed=1234): np.random.seed(seed) list_2_sort = list(np.random.randn(n)) @JungleProfiler() def sort_n(l): sorted_list = self.sort(l) return sorted_list sorted_list, _ = sort_n(list_2_sort) sort_status = all(sorted_list[i] <= sorted_list[i + 1] for i in range(len(sorted_list) - 1)) return sort_status print('\n---Test Block Sort---') @JungleExperiment(reps=1, n_blocks=[2, 4], block_size=[50, 100]) @JungleProfiler() def test_block_random_sort(self, n_blocks=4, block_size=100): print('n_blocks: %s' % n_blocks) print('block_size: %s' % block_size) return 'something' class NP_QuickSort(Sorting_Prototype): def sort(self, l): return np.sort(l, kind='quicksort') class NP_MergeSort(Sorting_Prototype): def sort(self, l): return np.sort(l, kind='mergesort') class NP_HeapSort(Sorting_Prototype): def sort(self, l): return np.sort(l, kind='heapsort') if __name__ == '__main__': print('\n__main__\n') print('\n---Starting Call #1---') m1 = NP_QuickSort() jc1 = m1.test_sort_n() print('\n---Starting Call #2---') m2 = NP_MergeSort() jc2 = m2.test_sort_n() print('\n---Starting Call #3---') m1 = NP_QuickSort() jc1 = m1.test_block_random_sort() print('\n---Starting Call #4---') m2 = NP_MergeSort() jc2 = m2.test_block_random_sort()
true
true
f7168a45d1129bfe9f7ee66ee3c14b06f2b75b19
432
py
Python
exercicios/ex052.py
MaikolSantos/curso-em-video-python3
3a1ab2761b8a0f98e128083a7b0e50b19a75b7bf
[ "MIT" ]
null
null
null
exercicios/ex052.py
MaikolSantos/curso-em-video-python3
3a1ab2761b8a0f98e128083a7b0e50b19a75b7bf
[ "MIT" ]
null
null
null
exercicios/ex052.py
MaikolSantos/curso-em-video-python3
3a1ab2761b8a0f98e128083a7b0e50b19a75b7bf
[ "MIT" ]
null
null
null
n = int(input('Digite um número inteiro: ')) cont = 0 for c in range(1, n + 1): if n % c == 0: print('\033[034m{}\033[m'.format(c), end=' ') cont += 1 else: print('\033[031m{}\033[m'.format(c), end=' ') print('\nO número {} foi divisível {} vezes '.format(n, cont)) if cont == 2: print('Portanto, o número {} é PRIMO'.format(n)) else: print('Portanto, o número {} NÃO é PRIMO'.format(n))
24
62
0.546296
n = int(input('Digite um número inteiro: ')) cont = 0 for c in range(1, n + 1): if n % c == 0: print('\033[034m{}\033[m'.format(c), end=' ') cont += 1 else: print('\033[031m{}\033[m'.format(c), end=' ') print('\nO número {} foi divisível {} vezes '.format(n, cont)) if cont == 2: print('Portanto, o número {} é PRIMO'.format(n)) else: print('Portanto, o número {} NÃO é PRIMO'.format(n))
true
true
f7168a487b6bc455015981782fb336330a0490cd
26,905
py
Python
src/sage/rings/polynomial/flatten.py
nikmihale/sage
e2dcdeeabb578c37bcf0361c0be3079315e9252c
[ "BSL-1.0" ]
null
null
null
src/sage/rings/polynomial/flatten.py
nikmihale/sage
e2dcdeeabb578c37bcf0361c0be3079315e9252c
[ "BSL-1.0" ]
null
null
null
src/sage/rings/polynomial/flatten.py
nikmihale/sage
e2dcdeeabb578c37bcf0361c0be3079315e9252c
[ "BSL-1.0" ]
null
null
null
# -*- coding: utf-8 -*- r""" Class to flatten polynomial rings over polynomial ring For example ``QQ['a','b'],['x','y']`` flattens to ``QQ['a','b','x','y']``. EXAMPLES:: sage: R = QQ['x']['y']['s','t']['X'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: phi = FlatteningMorphism(R); phi Flattening morphism: From: Univariate Polynomial Ring in X over Multivariate Polynomial Ring in s, t over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field To: Multivariate Polynomial Ring in x, y, s, t, X over Rational Field sage: phi('x*y*s + t*X').parent() Multivariate Polynomial Ring in x, y, s, t, X over Rational Field Authors: Vincent Delecroix, Ben Hutz (July 2016): initial implementation """ # **************************************************************************** # Copyright (C) 2016 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** from __future__ import absolute_import, print_function import itertools from sage.categories.homset import Homset from sage.categories.morphism import Morphism from sage.misc.cachefunc import cached_method from .polynomial_ring_constructor import PolynomialRing from .polynomial_ring import is_PolynomialRing from .multi_polynomial_ring_base import is_MPolynomialRing from sage.rings.fraction_field import is_FractionField from sage.rings.fraction_field_element import FractionFieldElement from sage.rings.polynomial.polydict import ETuple class FlatteningMorphism(Morphism): r""" EXAMPLES:: sage: R = QQ['a','b']['x','y','z']['t1','t2'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: f = FlatteningMorphism(R) sage: f.codomain() Multivariate Polynomial Ring in a, b, x, y, z, t1, t2 over Rational Field sage: p = R('(a+b)*x + (a^2-b)*t2*(z+y)') sage: p ((a^2 - b)*y + (a^2 - b)*z)*t2 + (a + b)*x sage: f(p) a^2*y*t2 + a^2*z*t2 - b*y*t2 - b*z*t2 + a*x + b*x sage: f(p).parent() Multivariate Polynomial Ring in a, b, x, y, z, t1, t2 over Rational Field Also works when univariate polynomial ring are involved:: sage: R = QQ['x']['y']['s','t']['X'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: f = FlatteningMorphism(R) sage: f.codomain() Multivariate Polynomial Ring in x, y, s, t, X over Rational Field sage: p = R('((x^2 + 1) + (x+2)*y + x*y^3)*(s+t) + x*y*X') sage: p x*y*X + (x*y^3 + (x + 2)*y + x^2 + 1)*s + (x*y^3 + (x + 2)*y + x^2 + 1)*t sage: f(p) x*y^3*s + x*y^3*t + x^2*s + x*y*s + x^2*t + x*y*t + x*y*X + 2*y*s + 2*y*t + s + t sage: f(p).parent() Multivariate Polynomial Ring in x, y, s, t, X over Rational Field """ def __init__(self, domain): """ The Python constructor EXAMPLES:: sage: R = ZZ['a', 'b', 'c']['x', 'y', 'z'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: FlatteningMorphism(R) Flattening morphism: From: Multivariate Polynomial Ring in x, y, z over Multivariate Polynomial Ring in a, b, c over Integer Ring To: Multivariate Polynomial Ring in a, b, c, x, y, z over Integer Ring :: sage: R = ZZ['a']['b']['c'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: FlatteningMorphism(R) Flattening morphism: From: Univariate Polynomial Ring in c over Univariate Polynomial Ring in b over Univariate Polynomial Ring in a over Integer Ring To: Multivariate Polynomial Ring in a, b, c over Integer Ring :: sage: R = ZZ['a']['a','b'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: FlatteningMorphism(R) Flattening morphism: From: Multivariate Polynomial Ring in a, b over Univariate Polynomial Ring in a over Integer Ring To: Multivariate Polynomial Ring in a, a0, b over Integer Ring :: sage: K.<v> = NumberField(x^3 - 2) sage: R = K['x','y']['a','b'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: f = FlatteningMorphism(R) sage: f(R('v*a*x^2 + b^2 + 1/v*y')) (v)*x^2*a + b^2 + (1/2*v^2)*y :: sage: R = QQbar['x','y']['a','b'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: f = FlatteningMorphism(R) sage: f(R('QQbar(sqrt(2))*a*x^2 + b^2 + QQbar(I)*y')) 1.414213562373095?*x^2*a + b^2 + I*y :: sage: R.<z> = PolynomialRing(QQbar,1) sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: f = FlatteningMorphism(R) sage: f.domain(), f.codomain() (Multivariate Polynomial Ring in z over Algebraic Field, Multivariate Polynomial Ring in z over Algebraic Field) :: sage: R.<z> = PolynomialRing(QQbar) sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: f = FlatteningMorphism(R) sage: f.domain(), f.codomain() (Univariate Polynomial Ring in z over Algebraic Field, Univariate Polynomial Ring in z over Algebraic Field) TESTS:: sage: Pol = QQ['x']['x0']['x'] sage: fl = FlatteningMorphism(Pol) sage: fl Flattening morphism: From: Univariate Polynomial Ring in x over Univariate Polynomial Ring in x0 over Univariate Polynomial Ring in x over Rational Field To: Multivariate Polynomial Ring in x, x0, x1 over Rational Field sage: p = Pol([[[1,2],[3,4]],[[5,6],[7,8]]]) sage: fl.section()(fl(p)) == p True """ if not is_PolynomialRing(domain) and not is_MPolynomialRing(domain): raise ValueError("domain should be a polynomial ring") ring = domain variables = [] intermediate_rings = [] while is_PolynomialRing(ring) or is_MPolynomialRing(ring): intermediate_rings.append(ring) v = ring.variable_names() variables.extend(reversed(v)) ring = ring.base_ring() self._intermediate_rings = intermediate_rings variables.reverse() for i, a in enumerate(variables): if a in variables[:i]: for index in itertools.count(): b = a + str(index) if b not in variables: # not just variables[:i]! break variables[i] = b if is_MPolynomialRing(domain): codomain = PolynomialRing(ring, variables, len(variables)) else: codomain = PolynomialRing(ring, variables) hom = Homset(domain, codomain, base=ring, check=False) Morphism.__init__(self, hom) self._repr_type_str = 'Flattening' def _call_(self, p): r""" Evaluate a flattening morphism. EXAMPLES:: sage: R = QQ['a','b','c']['x','y','z'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: h = FlatteningMorphism(R)('2*a*x + b*z'); h 2*a*x + b*z sage: h.parent() Multivariate Polynomial Ring in a, b, c, x, y, z over Rational Field TESTS:: sage: R = QQ['x']['y']['s','t'] sage: p = R('s*x + y*t + x^2*s + 1 + t') sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: f = FlatteningMorphism(R) sage: f._call_(p) x^2*s + x*s + y*t + t + 1 """ # If we are just specializing a univariate polynomial, then # the flattening morphism is the identity if self.codomain().ngens() == 1: return p p = {(): p} for ring in self._intermediate_rings: new_p = {} if is_PolynomialRing(ring): for mon, pp in p.items(): assert pp.parent() is ring for i, j in pp.dict().items(): new_p[(i,)+(mon)] = j elif is_MPolynomialRing(ring): for mon, pp in p.items(): assert pp.parent() is ring for mmon, q in pp.dict().items(): new_p[tuple(mmon)+mon] = q else: raise RuntimeError p = new_p return self.codomain()(p, check=False) @cached_method def section(self): """ Inverse of this flattening morphism. EXAMPLES:: sage: R = QQ['a','b','c']['x','y','z'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: h = FlatteningMorphism(R) sage: h.section() Unflattening morphism: From: Multivariate Polynomial Ring in a, b, c, x, y, z over Rational Field To: Multivariate Polynomial Ring in x, y, z over Multivariate Polynomial Ring in a, b, c over Rational Field :: sage: R = ZZ['a']['b']['c'] sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: FlatteningMorphism(R).section() Unflattening morphism: From: Multivariate Polynomial Ring in a, b, c over Integer Ring To: Univariate Polynomial Ring in c over Univariate Polynomial Ring in b over Univariate Polynomial Ring in a over Integer Ring """ return UnflatteningMorphism(self.codomain(), self.domain()) class UnflatteningMorphism(Morphism): r""" Inverses for :class:`FlatteningMorphism` EXAMPLES:: sage: R = QQ['c','x','y','z'] sage: S = QQ['c']['x','y','z'] sage: from sage.rings.polynomial.flatten import UnflatteningMorphism sage: f = UnflatteningMorphism(R, S) sage: g = f(R('x^2 + c*y^2 - z^2'));g x^2 + c*y^2 - z^2 sage: g.parent() Multivariate Polynomial Ring in x, y, z over Univariate Polynomial Ring in c over Rational Field :: sage: R = QQ['a','b', 'x','y'] sage: S = QQ['a','b']['x','y'] sage: from sage.rings.polynomial.flatten import UnflatteningMorphism sage: UnflatteningMorphism(R, S) Unflattening morphism: From: Multivariate Polynomial Ring in a, b, x, y over Rational Field To: Multivariate Polynomial Ring in x, y over Multivariate Polynomial Ring in a, b over Rational Field """ def __init__(self, domain, codomain): """ The Python constructor EXAMPLES:: sage: R = QQ['x']['y']['s','t']['X'] sage: p = R.random_element() sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: f = FlatteningMorphism(R) sage: g = f.section() sage: g(f(p)) == p True :: sage: R = QQ['a','b','x','y'] sage: S = ZZ['a','b']['x','z'] sage: from sage.rings.polynomial.flatten import UnflatteningMorphism sage: UnflatteningMorphism(R, S) Traceback (most recent call last): ... ValueError: rings must have same base ring :: sage: R = QQ['a','b','x','y'] sage: S = QQ['a','b']['x','z','w'] sage: from sage.rings.polynomial.flatten import UnflatteningMorphism sage: UnflatteningMorphism(R, S) Traceback (most recent call last): ... ValueError: rings must have the same number of variables """ if not is_MPolynomialRing(domain): raise ValueError("domain should be a multivariate polynomial ring") if not is_PolynomialRing(codomain) and not is_MPolynomialRing(codomain): raise ValueError("codomain should be a polynomial ring") ring = codomain intermediate_rings = [] while True: is_polynomial_ring = is_PolynomialRing(ring) if not (is_polynomial_ring or is_MPolynomialRing(ring)): break intermediate_rings.append((ring, is_polynomial_ring)) ring = ring.base_ring() if domain.base_ring() != intermediate_rings[-1][0].base_ring(): raise ValueError("rings must have same base ring") if domain.ngens() != sum([R.ngens() for R, _ in intermediate_rings]): raise ValueError("rings must have the same number of variables") self._intermediate_rings = intermediate_rings hom = Homset(domain, codomain, base=ring, check=False) Morphism.__init__(self, hom) self._repr_type_str = 'Unflattening' def _call_(self, p): """ Evaluate an unflattening morphism. TESTS:: sage: from sage.rings.polynomial.flatten import FlatteningMorphism sage: for R in [ZZ['x']['y']['a,b,c'], GF(4)['x','y']['a','b'], ....: AA['x']['a','b']['y'], QQbar['a1','a2']['t']['X','Y']]: ....: f = FlatteningMorphism(R) ....: g = f.section() ....: for _ in range(10): ....: p = R.random_element() ....: assert p == g(f(p)) ....: z = R.zero() ....: assert z == g(f(z)) """ index = [0] for R, _ in reversed(self._intermediate_rings): index.append(index[-1] + len(R.gens())) newpol = [{} for _ in self._intermediate_rings] expo = sorted(p.exponents(), key=lambda e: tuple(reversed(e))) for i in range(len(expo)): cur_exp = expo[i] for l in range(len(self._intermediate_rings)): R, univariate = self._intermediate_rings[-1 - l] idx = index[l + 1] sub_exp = (cur_exp[index[l]] if univariate else cur_exp[index[l]:idx]) if l == 0: newpol[l][sub_exp] = p[cur_exp] else: newpol[l][sub_exp] = newpol[l - 1] newpol[l - 1] = {} if (i == len(expo) - 1 or expo[i + 1][idx:] != cur_exp[idx:]): newpol[l] = R(newpol[l], check=False) else: break return R(newpol[-1], check=False) class SpecializationMorphism(Morphism): r""" Morphisms to specialize parameters in (stacked) polynomial rings EXAMPLES:: sage: R.<c> = PolynomialRing(QQ) sage: S.<x,y,z> = PolynomialRing(R) sage: D = dict({c:1}) sage: from sage.rings.polynomial.flatten import SpecializationMorphism sage: f = SpecializationMorphism(S, D) sage: g = f(x^2 + c*y^2 - z^2); g x^2 + y^2 - z^2 sage: g.parent() Multivariate Polynomial Ring in x, y, z over Rational Field :: sage: R.<c> = PolynomialRing(QQ) sage: S.<z> = PolynomialRing(R) sage: from sage.rings.polynomial.flatten import SpecializationMorphism sage: xi = SpecializationMorphism(S, {c:0}); xi Specialization morphism: From: Univariate Polynomial Ring in z over Univariate Polynomial Ring in c over Rational Field To: Univariate Polynomial Ring in z over Rational Field sage: xi(z^2+c) z^2 :: sage: R1.<u,v> = PolynomialRing(QQ) sage: R2.<a,b,c> = PolynomialRing(R1) sage: S.<x,y,z> = PolynomialRing(R2) sage: D = dict({a:1, b:2, x:0, u:1}) sage: from sage.rings.polynomial.flatten import SpecializationMorphism sage: xi = SpecializationMorphism(S, D); xi Specialization morphism: From: Multivariate Polynomial Ring in x, y, z over Multivariate Polynomial Ring in a, b, c over Multivariate Polynomial Ring in u, v over Rational Field To: Multivariate Polynomial Ring in y, z over Univariate Polynomial Ring in c over Univariate Polynomial Ring in v over Rational Field sage: xi(a*(x*z+y^2)*u+b*v*u*(x*z+y^2)*y^2*c+c*y^2*z^2) 2*v*c*y^4 + c*y^2*z^2 + y^2 """ def __init__(self, domain, D): """ The Python constructor EXAMPLES:: sage: S.<x,y> = PolynomialRing(QQ) sage: D = dict({x:1}) sage: from sage.rings.polynomial.flatten import SpecializationMorphism sage: phi = SpecializationMorphism(S, D); phi Specialization morphism: From: Multivariate Polynomial Ring in x, y over Rational Field To: Univariate Polynomial Ring in y over Rational Field sage: phi(x^2 + y^2) y^2 + 1 :: sage: R.<a,b,c> = PolynomialRing(ZZ) sage: S.<x,y,z> = PolynomialRing(R) sage: from sage.rings.polynomial.flatten import SpecializationMorphism sage: xi = SpecializationMorphism(S, {a:1/2}) Traceback (most recent call last): ... TypeError: no conversion of this rational to integer The following was fixed in :trac:`23811`:: sage: R.<c> = RR[] sage: P.<z> = AffineSpace(R, 1) sage: H = End(P) sage: f = H([z^2 + c]) sage: f.specialization({c:1}) Scheme endomorphism of Affine Space of dimension 1 over Real Field with 53 bits of precision Defn: Defined on coordinates by sending (z) to (z^2 + 1.00000000000000) """ if not is_PolynomialRing(domain) and not is_MPolynomialRing(domain): raise TypeError("domain should be a polynomial ring") # use only the generators that are in the stack somewhere, # and ignore the rest all_gens = domain.gens_dict_recursive() new_D = {} for gen in D: if str(gen) in all_gens: new_D[gen] = D[gen] D = new_D # _sub_specialization is a specialization morphism (recursive) # which is applied to the base Fraction field, or None if it's # any other base ring self._sub_specialization = None # We use this composition where "flat" is a flattened # polynomial ring. # # phi D psi # domain → flat → flat → R # │ │ │ # └─────────┴───────────────┘ # _flattening_morph _eval_morph # = phi = psi ∘ D phi = FlatteningMorphism(domain) flat = phi.codomain() base = flat.base_ring() # Change domain of D to "flat" and ensure that the values lie # in the base ring. D = {phi(k): base(D[k]) for k in D} # Construct unflattened codomain R new_vars = [] R = domain while is_PolynomialRing(R) or is_MPolynomialRing(R) or is_FractionField(R): if is_FractionField(R): # We've hit base_ring, so set _sub_specialization and exit the loop field_over = R.base() applicable_vars = {key: val for key, val in D.items() if key not in flat.gens()} # If there are any variables in D to set in _sub_specialization if applicable_vars: # Coerce the generators to be in the right ring # This un-does changing the domain of D to be in the flat base ring tmp = {} for var, val in applicable_vars.items(): for gstr, gen in field_over.gens_dict_recursive().items(): if str(var) == gstr: tmp[gen] = val break else: # Should have been caught earlier raise NameError("argument " + str(var) + " is not a generator anywhere in the polynomial tower") applicable_vars = tmp self._sub_specialization = FractionSpecializationMorphism(R, applicable_vars) break # We're still in the polynomials, so keep track of the tower old = R.gens() new = [t for t in old if t not in D] force_multivariate = ((len(old) == 1) and is_MPolynomialRing(R)) new_vars.append((new, force_multivariate, old)) R = R.base_ring() if self._sub_specialization: # The sub_specialization range will be different # if it applied some variables from D R = self._sub_specialization.codomain().fraction_field() # Construct unflattening map psi (only defined on the variables # of "flat" which are not involved in D) psi = dict() # Reconstruct the proper domain of this morphism # based on the sub_specialization domains new_domain = R for new, force_multivariate, old in reversed(new_vars): if self._sub_specialization: if force_multivariate: new_domain = PolynomialRing(new_domain, old, len(old)) else: new_domain = PolynomialRing(new_domain, old) if not new: continue var_names = [str(var) for var in new] if force_multivariate: R = PolynomialRing(R, var_names, len(var_names)) else: R = PolynomialRing(R, var_names) # Map variables in "new" to R psi.update(zip([phi(w) for w in new], R.gens())) # Fix domain of eval_morph # (note: phi's domain is correct) if self._sub_specialization: phi_prime = FlatteningMorphism(new_domain) flat_old = flat flat = phi_prime.codomain() base_prime = flat.base_ring() D = {phi(k): base_prime(D[k]) for k in D} else: # The bottom of our tower has not changed def flat_old(x): return x # Compose D with psi vals = [] for t in flat.gens(): if t in D: vals.append(R.coerce(D[t])) else: # Make sure keys are in the old domain # or else they won't match exactly vals.append(psi[flat_old(t)]) self._flattening_morph = phi self._eval_morph = flat.hom(vals, R) self._repr_type_str = 'Specialization' Morphism.__init__(self, domain, R) def _call_(self, p): """ Evaluate a specialization morphism. EXAMPLES:: sage: R.<a,b,c> = PolynomialRing(ZZ) sage: S.<x,y,z> = PolynomialRing(R) sage: D = dict({a:1, b:2, c:3}) sage: from sage.rings.polynomial.flatten import SpecializationMorphism sage: xi = SpecializationMorphism(S, D) sage: xi(a*x + b*y + c*z) x + 2*y + 3*z """ flat = self._flattening_morph(p) if self._sub_specialization is not None: # The base_ring should be a fraction field, so # apply _sub_specialization to each coefficient # in the flattened polynomial tmp = {} for exponent, coefficient in flat.dict().items(): # Fix the type of exponent from (a,) to a # (necessary for R(tmp) later) if isinstance(exponent, ETuple) and len(exponent) == 1: exponent = exponent[0] # Coefficient should be a fraction tmp[exponent] = self._sub_specialization._call_(coefficient) # tmp's parent should be the same construction as flat # but over _sub_specialization's codomain ring_constructor = flat.parent().construction()[0] fraction_type = self._sub_specialization.codomain() R = ring_constructor(fraction_type) flat = R(tmp) return self._eval_morph(flat) class FractionSpecializationMorphism(Morphism): """ A specialization morphism for fraction fields over (stacked) polynomial rings """ def __init__(self, domain, D): """ Initialize the morphism with a domain and dictionary of specializations EXAMPLES:: sage: R.<a,c> = QQ[] sage: S.<x,y> = R[] sage: from sage.rings.polynomial.flatten import FractionSpecializationMorphism sage: phi = FractionSpecializationMorphism(Frac(S), {c:3}) sage: phi Fraction Specialization morphism: From: Fraction Field of Multivariate Polynomial Ring in x, y over Multivariate Polynomial Ring in a, c over Rational Field To: Fraction Field of Multivariate Polynomial Ring in x, y over Univariate Polynomial Ring in a over Rational Field """ if not is_FractionField(domain): raise TypeError("domain must be a fraction field") self._specialization = SpecializationMorphism(domain.base(), D) self._repr_type_str = 'Fraction Specialization' Morphism.__init__(self, domain, self._specialization.codomain().fraction_field()) def _call_(self, p): """ Evaluate a fraction specialization morphism EXAMPLES:: sage: R.<a,b,c> = QQ[] sage: S.<x,y,z> = R[] sage: from sage.rings.polynomial.flatten import FractionSpecializationMorphism sage: phi = FractionSpecializationMorphism(Frac(S), {a:3, b:2, c:-2}) sage: spec = phi((a*x + b*y) / (c*z)) sage: spec (3*x + 2*y)/(-2*z) sage: spec.parent() Fraction Field of Multivariate Polynomial Ring in x, y, z over Rational Field """ if not isinstance(p, FractionFieldElement): raise TypeError("p must be a fraction field element") numerator = self._specialization._call_(p.numerator()) denominator = self._specialization._call_(p.denominator()) return numerator / denominator
39.918398
179
0.55551
from __future__ import absolute_import, print_function import itertools from sage.categories.homset import Homset from sage.categories.morphism import Morphism from sage.misc.cachefunc import cached_method from .polynomial_ring_constructor import PolynomialRing from .polynomial_ring import is_PolynomialRing from .multi_polynomial_ring_base import is_MPolynomialRing from sage.rings.fraction_field import is_FractionField from sage.rings.fraction_field_element import FractionFieldElement from sage.rings.polynomial.polydict import ETuple class FlatteningMorphism(Morphism): def __init__(self, domain): if not is_PolynomialRing(domain) and not is_MPolynomialRing(domain): raise ValueError("domain should be a polynomial ring") ring = domain variables = [] intermediate_rings = [] while is_PolynomialRing(ring) or is_MPolynomialRing(ring): intermediate_rings.append(ring) v = ring.variable_names() variables.extend(reversed(v)) ring = ring.base_ring() self._intermediate_rings = intermediate_rings variables.reverse() for i, a in enumerate(variables): if a in variables[:i]: for index in itertools.count(): b = a + str(index) if b not in variables: break variables[i] = b if is_MPolynomialRing(domain): codomain = PolynomialRing(ring, variables, len(variables)) else: codomain = PolynomialRing(ring, variables) hom = Homset(domain, codomain, base=ring, check=False) Morphism.__init__(self, hom) self._repr_type_str = 'Flattening' def _call_(self, p): if self.codomain().ngens() == 1: return p p = {(): p} for ring in self._intermediate_rings: new_p = {} if is_PolynomialRing(ring): for mon, pp in p.items(): assert pp.parent() is ring for i, j in pp.dict().items(): new_p[(i,)+(mon)] = j elif is_MPolynomialRing(ring): for mon, pp in p.items(): assert pp.parent() is ring for mmon, q in pp.dict().items(): new_p[tuple(mmon)+mon] = q else: raise RuntimeError p = new_p return self.codomain()(p, check=False) @cached_method def section(self): return UnflatteningMorphism(self.codomain(), self.domain()) class UnflatteningMorphism(Morphism): def __init__(self, domain, codomain): if not is_MPolynomialRing(domain): raise ValueError("domain should be a multivariate polynomial ring") if not is_PolynomialRing(codomain) and not is_MPolynomialRing(codomain): raise ValueError("codomain should be a polynomial ring") ring = codomain intermediate_rings = [] while True: is_polynomial_ring = is_PolynomialRing(ring) if not (is_polynomial_ring or is_MPolynomialRing(ring)): break intermediate_rings.append((ring, is_polynomial_ring)) ring = ring.base_ring() if domain.base_ring() != intermediate_rings[-1][0].base_ring(): raise ValueError("rings must have same base ring") if domain.ngens() != sum([R.ngens() for R, _ in intermediate_rings]): raise ValueError("rings must have the same number of variables") self._intermediate_rings = intermediate_rings hom = Homset(domain, codomain, base=ring, check=False) Morphism.__init__(self, hom) self._repr_type_str = 'Unflattening' def _call_(self, p): index = [0] for R, _ in reversed(self._intermediate_rings): index.append(index[-1] + len(R.gens())) newpol = [{} for _ in self._intermediate_rings] expo = sorted(p.exponents(), key=lambda e: tuple(reversed(e))) for i in range(len(expo)): cur_exp = expo[i] for l in range(len(self._intermediate_rings)): R, univariate = self._intermediate_rings[-1 - l] idx = index[l + 1] sub_exp = (cur_exp[index[l]] if univariate else cur_exp[index[l]:idx]) if l == 0: newpol[l][sub_exp] = p[cur_exp] else: newpol[l][sub_exp] = newpol[l - 1] newpol[l - 1] = {} if (i == len(expo) - 1 or expo[i + 1][idx:] != cur_exp[idx:]): newpol[l] = R(newpol[l], check=False) else: break return R(newpol[-1], check=False) class SpecializationMorphism(Morphism): def __init__(self, domain, D): if not is_PolynomialRing(domain) and not is_MPolynomialRing(domain): raise TypeError("domain should be a polynomial ring") all_gens = domain.gens_dict_recursive() new_D = {} for gen in D: if str(gen) in all_gens: new_D[gen] = D[gen] D = new_D # any other base ring self._sub_specialization = None # We use this composition where "flat" is a flattened # polynomial ring. # # phi D psi # domain → flat → flat → R # │ │ │ # └─────────┴───────────────┘ # _flattening_morph _eval_morph # = phi = psi ∘ D phi = FlatteningMorphism(domain) flat = phi.codomain() base = flat.base_ring() # Change domain of D to "flat" and ensure that the values lie # in the base ring. D = {phi(k): base(D[k]) for k in D} # Construct unflattened codomain R new_vars = [] R = domain while is_PolynomialRing(R) or is_MPolynomialRing(R) or is_FractionField(R): if is_FractionField(R): # We've hit base_ring, so set _sub_specialization and exit the loop field_over = R.base() applicable_vars = {key: val for key, val in D.items() if key not in flat.gens()} if applicable_vars: tmp = {} for var, val in applicable_vars.items(): for gstr, gen in field_over.gens_dict_recursive().items(): if str(var) == gstr: tmp[gen] = val break else: raise NameError("argument " + str(var) + " is not a generator anywhere in the polynomial tower") applicable_vars = tmp self._sub_specialization = FractionSpecializationMorphism(R, applicable_vars) break old = R.gens() new = [t for t in old if t not in D] force_multivariate = ((len(old) == 1) and is_MPolynomialRing(R)) new_vars.append((new, force_multivariate, old)) R = R.base_ring() if self._sub_specialization: # The sub_specialization range will be different # if it applied some variables from D R = self._sub_specialization.codomain().fraction_field() # Construct unflattening map psi (only defined on the variables # of "flat" which are not involved in D) psi = dict() # Reconstruct the proper domain of this morphism # based on the sub_specialization domains new_domain = R for new, force_multivariate, old in reversed(new_vars): if self._sub_specialization: if force_multivariate: new_domain = PolynomialRing(new_domain, old, len(old)) else: new_domain = PolynomialRing(new_domain, old) if not new: continue var_names = [str(var) for var in new] if force_multivariate: R = PolynomialRing(R, var_names, len(var_names)) else: R = PolynomialRing(R, var_names) # Map variables in "new" to R psi.update(zip([phi(w) for w in new], R.gens())) # Fix domain of eval_morph # (note: phi's domain is correct) if self._sub_specialization: phi_prime = FlatteningMorphism(new_domain) flat_old = flat flat = phi_prime.codomain() base_prime = flat.base_ring() D = {phi(k): base_prime(D[k]) for k in D} else: def flat_old(x): return x vals = [] for t in flat.gens(): if t in D: vals.append(R.coerce(D[t])) else: vals.append(psi[flat_old(t)]) self._flattening_morph = phi self._eval_morph = flat.hom(vals, R) self._repr_type_str = 'Specialization' Morphism.__init__(self, domain, R) def _call_(self, p): flat = self._flattening_morph(p) if self._sub_specialization is not None: # The base_ring should be a fraction field, so # apply _sub_specialization to each coefficient # in the flattened polynomial tmp = {} for exponent, coefficient in flat.dict().items(): # Fix the type of exponent from (a,) to a # (necessary for R(tmp) later) if isinstance(exponent, ETuple) and len(exponent) == 1: exponent = exponent[0] # Coefficient should be a fraction tmp[exponent] = self._sub_specialization._call_(coefficient) # tmp's parent should be the same construction as flat ring_constructor = flat.parent().construction()[0] fraction_type = self._sub_specialization.codomain() R = ring_constructor(fraction_type) flat = R(tmp) return self._eval_morph(flat) class FractionSpecializationMorphism(Morphism): def __init__(self, domain, D): if not is_FractionField(domain): raise TypeError("domain must be a fraction field") self._specialization = SpecializationMorphism(domain.base(), D) self._repr_type_str = 'Fraction Specialization' Morphism.__init__(self, domain, self._specialization.codomain().fraction_field()) def _call_(self, p): if not isinstance(p, FractionFieldElement): raise TypeError("p must be a fraction field element") numerator = self._specialization._call_(p.numerator()) denominator = self._specialization._call_(p.denominator()) return numerator / denominator
true
true
f7168ba8849334a57d1b394944e515d207126631
19,617
py
Python
main.py
gmathez/Project_ADA_2018_Bruttin_Mathez_Petitpierre
e237300b3d9fb966b0eb747dd66816cc6cfc11b3
[ "Apache-2.0" ]
1
2018-12-01T12:17:58.000Z
2018-12-01T12:17:58.000Z
main.py
gmathez/Project_ADA_2018_Bruttin_Mathez_Petitpierre
e237300b3d9fb966b0eb747dd66816cc6cfc11b3
[ "Apache-2.0" ]
null
null
null
main.py
gmathez/Project_ADA_2018_Bruttin_Mathez_Petitpierre
e237300b3d9fb966b0eb747dd66816cc6cfc11b3
[ "Apache-2.0" ]
null
null
null
# Import kivy tools from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.recycleboxlayout import RecycleBoxLayout from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.checkbox import CheckBox from kivy.uix.spinner import Spinner from kivy.uix.recycleview import RecycleView from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.properties import BooleanProperty, ObjectProperty from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder # Import the kv files Builder.load_file('./src/rv.kv') Builder.load_file('./src/screenhome.kv') Builder.load_file('./src/screenprofile.kv') Builder.load_file('./src/screensettings.kv') Builder.load_file('./src/screenproduct.kv') Builder.load_file('./src/screenquantities.kv') Builder.load_file('./src/screenfinal.kv') Builder.load_file('./src/manager.kv') # Other imports import pandas as pd import re from Algo_main import algo # Import the algorithm for NutriScore computation class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): ''' Add selection and focus behaviour to the view ''' pass class SelectableGrid(RecycleDataViewBehavior, GridLayout): ''' Add selection support to the Label ''' index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) def refresh_view_attrs(self, rv, index, data): ''' Catch and handle the view changes ''' self.index = index self.ids['id_label1'].text = data['label1']['text'] self.ids['id_label2'].text = data['label2']['text'] self.ids['id_label3'].text = data['label3']['text'] return super(SelectableGrid, self).refresh_view_attrs( rv, index, data) def on_touch_down(self, touch): ''' Add selection on touch down ''' if super(SelectableGrid, self).on_touch_down(touch): return True if self.collide_point(*touch.pos) and self.selectable: return self.parent.select_with_touch(self.index, touch) def apply_selection(self, rv, index, is_selected): ''' Respond to the selection of items ''' self.selected = is_selected class SelectableQuantity(RecycleDataViewBehavior, GridLayout): ''' Add selection support to the Label ''' index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) def refresh_view_attrs(self, rv, index, data): ''' Catch and handle the view changes ''' self.index = index self.ids['id_label1'].text = data['label1']['text'] self.ids['id_label2'].text = data['label2']['text'] self.ids['id_label3'].text = data['label3']['text'] return super(SelectableQuantity, self).refresh_view_attrs( rv, index, data) class RV(RecycleView): ''' Class for the RecycleView Controller ''' def __init__(self, **kwargs): super(RV, self).__init__(**kwargs) def upload(self, query, active): ''' Search data according to the user input ''' # Reset data self.data = [] # Check if the Raw Food CheckBox is active or not if active: self.parent.parent.getSelection('API', query, True) self.data = [{'label1': {'text': 'API'}, 'label2': {'text': query}, 'label3': {'text': 'Add/Remove'}}] else: isinside = allTrue for item in query.split(): # Split the query in keywords isinside = isinside & \ (DF['product_name'].str.contains(item, case=False) | \ DF['Brands'].str.contains(item, case=False)) if any(isinside): selection = DF[isinside] # Select products to display for row in selection.itertuples(): # Iterate through the columns of DF d = {'label1': {'text': str(row[0])}, \ 'label2': {'text': str(row[1])}, 'label3': {'text': str(row[-1])}} # barcode, product_name, brand self.data.append(d) else: isinside = DF.index.str.contains(query, case=False) # Search for Barcode if any(isinside): selection = DF[isinside] for row in selection.itertuples(): d = {'label1': {'text': str(row[0])}, \ 'label2': {'text': str(row[1])}, 'label3': {'text': str(row[-1])}} # barcode, product_name, brand self.data.append(d) else: # In case no product is found self.data = [{'label1': {'text': ''}, \ 'label2': {'text': 'No product found'}, 'label3': {'text': ''}}] def getQuantities(self, dict): ''' Gather data for display on Quantities Screen ''' self.data = [] code = dict['code'] product_name = dict['product_name'] quantity = dict['quantity'] for index in range(len(code)): d = {'label1': {'text': code[index]}, 'label2': {'text': product_name[index]}, \ 'label3': {'text': quantity[index]}} self.data.append(d) class ScreenHome(Screen): ''' Class for the Home Screen. No variables or functions needed for this screen ''' pass class ScreenProfile(Screen): ''' Class for the Profile Screen ''' def updateDF(self): global DF DF = pd.read_csv('https://drive.google.com/uc?export=download&id=1aLUh1UoQcS9lBa6oVRln-DuskxK5uK3y', \ index_col=[0], low_memory = False) DF.to_csv('./data/OpenFoodFacts_final.csv.gz', compression='gzip') self.ids['update'].text = 'Updated' self.ids['update'].background_color = (0,1,0,1) def update(self): self.ids['update'].text = 'Updating' self.ids['update'].background_color = (50/255,164/255,206/255,1) class ScreenSettings(Screen): ''' Class for the Settings Screen ''' settings = {'rec': True,'name': '', 'surname': '', 'age': 0, 'sex': True, 'weight': 0, \ 'email': '', 'activity': 0, 'days': 0} id_profile = -999 def resetForm(self): ''' Reset the indicators of invalid input ''' self.ids.sex.color = (1,1,1,1) self.ids.activity.color = (1,1,1,1) self.ids.age.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.weight.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.days.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.email.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.name.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.surname.hint_text_color = (0.5, 0.5, 0.5, 1.0) def setForm(self, id_profile): self.id_profile = id_profile self.settings = {'rec': True,'name': '', 'surname': '', 'age': 0, 'sex': True, 'weight': 0, \ 'email': '', 'activity': 0, 'days': 0} if int(self.id_profile) >= 0: self.ids.name.text = str(profile_list.iloc[self.id_profile]['name']) self.ids.surname.text= str(profile_list.iloc[self.id_profile]['surname']) self.ids.age.text = str(profile_list.iloc[self.id_profile]['age']) if bool(profile_list.iloc[self.id_profile]['sex']): self.ids.male.active = True self.ids.female.active = False else: self.ids.male.active = False self.ids.female.active = True self.ids.weight.text = str(profile_list.iloc[self.id_profile]['weight']) self.ids.email.text = str(profile_list.iloc[self.id_profile]['email']) self.ids.days.text = str(profile_list.iloc[self.id_profile]['days']) if int(profile_list.iloc[self.id_profile]['activity']) == 1.8: self.ids.seated.active = False self.ids.both.active = False self.ids.standing.active = True elif int(profile_list.iloc[self.id_profile]['activity']) == 1.6: self.ids.seated.active = False self.ids.both.active = True self.ids.standing.active = False else: self.ids.seated.active = True self.ids.both.active = False self.ids.standing.active = False elif int(self.id_profile) == -999: self.ids.name.text = '' self.ids.surname.text = '' self.ids.age.text = '' self.ids.male.active = False self.ids.female.active = False self.ids.email.text = '' self.ids.weight.text = '' self.ids.seated.active = False self.ids.both.active = False self.ids.standing.active = False self.ids.days.text = '' else: self.changeScreen(False) def changeScreen(self, valid): ''' Handle the validity of the inputs and the change of current screen ''' if valid: self.resetForm() # Check name validity if self.ids.name.text.strip() == '': self.ids.name.hint_text_color = (1,0,0,1) return False # Check surname validity elif self.ids.surname.text.strip() == '': self.ids.surname.hint_text_color = (1,0,0,1) return False # Check age validity elif self.ids.age.text.strip() == '' or int(self.ids.age.text) <= 0 or \ int(self.ids.age.text) >= 120: self.ids.age.text = '' self.ids.age.hint_text_color = (1,0,0,1) return False # Check sex validity elif not(self.ids.male.active or self.ids.female.active): self.ids.sex.color = (1,0,0,1) return False # Check email validity elif not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", self.ids.email.text): self.ids.email.text = '' self.ids.email.hint_text_color = (1,0,0,1) return False # Check weight validity elif self.ids.weight.text.strip() == '' or int(self.ids.weight.text) <= 0: self.ids.weight.text = '' self.ids.weight.hint_text_color = (1,0,0,1) return False # Check activity validity elif not(self.ids.seated.active or self.ids.both.active or self.ids.standing.active): self.ids.activity.color = (1,0,0,1) return False # Check days validity elif self.ids.days.text.strip() == '' or int(self.ids.days.text) <= 0: self.ids.days.text = '' self.ids.days.hint_text_color = (1,0,0,1) return False else: # Validation of the form and reset self.settings['rec'] = True self.settings['name'] = self.ids.name.text self.settings['surname'] = self.ids.surname.text self.settings['age'] = int(self.ids.age.text) self.settings['weight'] = int(self.ids.weight.text) self.settings['email'] = self.ids.email.text self.settings['days'] = int(self.ids.days.text) self.settings['sex'] = self.ids.male.active if self.ids.seated.active: self.settings['activity'] = 1.4 if self.ids.both.active: self.settings['activity'] = 1.6 if self.ids.standing.active: self.settings['activity'] = 1.8 self.resetForm() else: # If the user pass the settings screen self.settings['rec'] = False self.manager.setSettings(self.settings, self.id_profile) # Change the current screen self.manager.current = 'Product Screen' class ScreenProduct(Screen): ''' Class for the Product Screen ''' temp_dict = {'code':'', 'product_name': ''} def getSelection(self, text1, text2, state): # Select or deselect temporarly a product if state: self.temp_dict['code'] = text1 self.temp_dict['product_name'] = text2 else: self.temp_dict['code'] = '' self.temp_dict['product_name'] = '' class ScreenQuantities(Screen): ''' Class for the Quantities Screen ''' temp_dict = {'code': [], 'product_name': [], 'quantity': [], 'color': []} def initQuantity(self, data): ''' Initialize the dictionary of the products ''' if self.temp_dict['quantity'] == []: self.temp_dict = data self.ids.rv.getQuantities(data) def updateQuantity(self, index, text1, text2, text3): ''' Store the quantities input by the user ''' l = len(self.temp_dict['quantity']) if text3 == '' or text3 == '-' or int(text3) < 0: text3 = '0' if index < l: self.temp_dict['code'][index] = text1 self.temp_dict['product_name'][index] = text2 self.temp_dict['quantity'][index] = text3 # Append the list of quantities if needed else: temp = ['0' for i in range(index-l)] self.temp_dict['code'] = self.temp_dict['code'] + temp + [text1] self.temp_dict['product_name'] = self.temp_dict['product_name'] + temp + [text2] self.temp_dict['quantity'] = self.temp_dict['quantity'] + temp + [text3] # Update the data displayed self.initQuantity(self.temp_dict) class ScreenFinal(Screen): ''' Class for the Final Screen. No variables or functions needed for this screen ''' pass class Manager(ScreenManager): ''' Class for the Manager Controller. Store main data ''' selected_products = {'code': [], 'product_name': [], 'quantity': []} settings = {'Rec': True, 'Name': '', 'Surname': '', 'Email': '', 'Age': 0, 'Sex': True, 'Pal': 0, \ 'Weight': 0, 'Day': 0} def getProfiles(self): self.ids.screen_profile.ids.profile_spinner.values = \ [str(index + 1) + ' : ' + str(profile_list['name'][index]) + ' ' + str(profile_list['surname'][index]) \ for index in profile_list.index] def toSettings(self, text): if text == 'new': id_profile = -999 elif text == 'pass': id_profile = -1000 else: items = text.split() id_profile = items[0].strip() id_profile = int(id_profile) - 1 self.ids.screen_settings.setForm(id_profile) if id_profile != -1000: self.current = 'Settings Screen' def addProduct(self): ''' Add product to main storage ''' item1 = self.ids.screen_product.temp_dict['code'] item2 = self.ids.screen_product.temp_dict['product_name'] if item1 != '' and item2 != '': self.selected_products['code'].append(item1) self.selected_products['product_name'].append(item2) self.selected_products['quantity'].append('0') def deleteProduct(self): ''' Remove product of main storage ''' item1 = self.ids.screen_product.temp_dict['code'] item2 = self.ids.screen_product.temp_dict['product_name'] if item1 in self.selected_products['code'] and item2 in self.selected_products['product_name']: self.selected_products['code'].remove(item1) self.selected_products['product_name'].remove(item2) self.selected_products['quantity'].pop() def getQuantities(self, data): ''' Add quantities to main storage ''' self.selected_products['quantity'] = data['quantity'] l = len(self.selected_products['quantity']) for item in range(l): if self.selected_products['quantity'][item] == '': self.selected_products['quantity'][item] = '0' self.current = 'Final Screen' def setSettings(self, data, new): ''' Add settings to main storage ''' self.settings['Rec'] = data['rec'] self.settings['Name'] = data['name'] self.settings['Surname'] = data['surname'] self.settings['Email'] = data['email'] self.settings['Pal'] = data['activity'] self.settings['Weight'] = data['weight'] self.settings['Day'] = data['days'] self.settings['Sex'] = data['sex'] self.settings['Age'] = data['age'] update = True if new == -999: temp_df = pd.DataFrame.from_dict({'index': [len(profile_list)], \ 'name': [data['name']], 'surname': [data['surname']], \ 'age': [data['age']], 'sex': [data['sex']], 'email': [data['email']], \ 'weight': [data['weight']], \ 'activity': [data['activity']], 'days': [data['days']]}).set_index('index') new_profile_list = pd.concat([profile_list, temp_df]) elif new == -1000: update = False else: temp_df = pd.DataFrame.from_dict({'name': [data['name']], 'surname': [data['surname']], \ 'age': [data['age']], 'sex': [data['sex']], 'email': [data['email']], 'weight': [data['weight']], \ 'activity': [data['activity']], 'days': [data['days']]}) new_profile_list= profile_list new_profile_list.iloc[new] = temp_df.iloc[0] if update: new_profile_list.to_csv('./data/profile.csv', sep=';') def computation(self): ''' Call algo for computation of NutriScore and recommendation. Display results ''' dict_product = {'Product': [], 'API': []} for index in range(len(self.selected_products['code'])): # Separation of API and OpenFoodFacts data if str(self.selected_products['code'][index]) == 'API': dict_product['API'].append((str(self.selected_products[ 'product_name'][index]), int(self.selected_products['quantity'][index]))) else: dict_product['Product'].append((str(self.selected_products[ 'code'][index]), int(self.selected_products['quantity'][index]))) # Run the algorithm to get the recommendation to print on-screen text_app_beverages, text_app_nonbeverages = algo(dict_product, self.settings, DF) self.ids.screen_final.ids.beverages.text = text_app_beverages self.ids.screen_final.ids.non_beverages.text = text_app_nonbeverages class NutriScoreApp(App): ''' Main class of the App ''' def build(self): ''' Import the database for the whole application ''' global DF, allTrue, profile_list try: DF = pd.read_csv('./data/OpenFoodFacts_final.csv.gz', low_memory=False, index_col = [0]) allTrue = DF['product_name'].str.contains('', case=False) # True Vector of length len(DF) profile_list = pd.read_csv('./data/profile.csv', sep=';', index_col=[0]) except: print('Fatal error: files missing') return Manager() if __name__ == '__main__': NutriScoreApp().run()
39.470825
116
0.568181
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.recycleboxlayout import RecycleBoxLayout from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.checkbox import CheckBox from kivy.uix.spinner import Spinner from kivy.uix.recycleview import RecycleView from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.properties import BooleanProperty, ObjectProperty from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder Builder.load_file('./src/rv.kv') Builder.load_file('./src/screenhome.kv') Builder.load_file('./src/screenprofile.kv') Builder.load_file('./src/screensettings.kv') Builder.load_file('./src/screenproduct.kv') Builder.load_file('./src/screenquantities.kv') Builder.load_file('./src/screenfinal.kv') Builder.load_file('./src/manager.kv') import pandas as pd import re from Algo_main import algo class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): pass class SelectableGrid(RecycleDataViewBehavior, GridLayout): index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) def refresh_view_attrs(self, rv, index, data): self.index = index self.ids['id_label1'].text = data['label1']['text'] self.ids['id_label2'].text = data['label2']['text'] self.ids['id_label3'].text = data['label3']['text'] return super(SelectableGrid, self).refresh_view_attrs( rv, index, data) def on_touch_down(self, touch): if super(SelectableGrid, self).on_touch_down(touch): return True if self.collide_point(*touch.pos) and self.selectable: return self.parent.select_with_touch(self.index, touch) def apply_selection(self, rv, index, is_selected): self.selected = is_selected class SelectableQuantity(RecycleDataViewBehavior, GridLayout): index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) def refresh_view_attrs(self, rv, index, data): self.index = index self.ids['id_label1'].text = data['label1']['text'] self.ids['id_label2'].text = data['label2']['text'] self.ids['id_label3'].text = data['label3']['text'] return super(SelectableQuantity, self).refresh_view_attrs( rv, index, data) class RV(RecycleView): def __init__(self, **kwargs): super(RV, self).__init__(**kwargs) def upload(self, query, active): self.data = [] if active: self.parent.parent.getSelection('API', query, True) self.data = [{'label1': {'text': 'API'}, 'label2': {'text': query}, 'label3': {'text': 'Add/Remove'}}] else: isinside = allTrue for item in query.split(): isinside = isinside & \ (DF['product_name'].str.contains(item, case=False) | \ DF['Brands'].str.contains(item, case=False)) if any(isinside): selection = DF[isinside] for row in selection.itertuples(): d = {'label1': {'text': str(row[0])}, \ 'label2': {'text': str(row[1])}, 'label3': {'text': str(row[-1])}} self.data.append(d) else: isinside = DF.index.str.contains(query, case=False) if any(isinside): selection = DF[isinside] for row in selection.itertuples(): d = {'label1': {'text': str(row[0])}, \ 'label2': {'text': str(row[1])}, 'label3': {'text': str(row[-1])}} self.data.append(d) else: self.data = [{'label1': {'text': ''}, \ 'label2': {'text': 'No product found'}, 'label3': {'text': ''}}] def getQuantities(self, dict): self.data = [] code = dict['code'] product_name = dict['product_name'] quantity = dict['quantity'] for index in range(len(code)): d = {'label1': {'text': code[index]}, 'label2': {'text': product_name[index]}, \ 'label3': {'text': quantity[index]}} self.data.append(d) class ScreenHome(Screen): pass class ScreenProfile(Screen): def updateDF(self): global DF DF = pd.read_csv('https://drive.google.com/uc?export=download&id=1aLUh1UoQcS9lBa6oVRln-DuskxK5uK3y', \ index_col=[0], low_memory = False) DF.to_csv('./data/OpenFoodFacts_final.csv.gz', compression='gzip') self.ids['update'].text = 'Updated' self.ids['update'].background_color = (0,1,0,1) def update(self): self.ids['update'].text = 'Updating' self.ids['update'].background_color = (50/255,164/255,206/255,1) class ScreenSettings(Screen): settings = {'rec': True,'name': '', 'surname': '', 'age': 0, 'sex': True, 'weight': 0, \ 'email': '', 'activity': 0, 'days': 0} id_profile = -999 def resetForm(self): self.ids.sex.color = (1,1,1,1) self.ids.activity.color = (1,1,1,1) self.ids.age.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.weight.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.days.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.email.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.name.hint_text_color = (0.5, 0.5, 0.5, 1.0) self.ids.surname.hint_text_color = (0.5, 0.5, 0.5, 1.0) def setForm(self, id_profile): self.id_profile = id_profile self.settings = {'rec': True,'name': '', 'surname': '', 'age': 0, 'sex': True, 'weight': 0, \ 'email': '', 'activity': 0, 'days': 0} if int(self.id_profile) >= 0: self.ids.name.text = str(profile_list.iloc[self.id_profile]['name']) self.ids.surname.text= str(profile_list.iloc[self.id_profile]['surname']) self.ids.age.text = str(profile_list.iloc[self.id_profile]['age']) if bool(profile_list.iloc[self.id_profile]['sex']): self.ids.male.active = True self.ids.female.active = False else: self.ids.male.active = False self.ids.female.active = True self.ids.weight.text = str(profile_list.iloc[self.id_profile]['weight']) self.ids.email.text = str(profile_list.iloc[self.id_profile]['email']) self.ids.days.text = str(profile_list.iloc[self.id_profile]['days']) if int(profile_list.iloc[self.id_profile]['activity']) == 1.8: self.ids.seated.active = False self.ids.both.active = False self.ids.standing.active = True elif int(profile_list.iloc[self.id_profile]['activity']) == 1.6: self.ids.seated.active = False self.ids.both.active = True self.ids.standing.active = False else: self.ids.seated.active = True self.ids.both.active = False self.ids.standing.active = False elif int(self.id_profile) == -999: self.ids.name.text = '' self.ids.surname.text = '' self.ids.age.text = '' self.ids.male.active = False self.ids.female.active = False self.ids.email.text = '' self.ids.weight.text = '' self.ids.seated.active = False self.ids.both.active = False self.ids.standing.active = False self.ids.days.text = '' else: self.changeScreen(False) def changeScreen(self, valid): if valid: self.resetForm() if self.ids.name.text.strip() == '': self.ids.name.hint_text_color = (1,0,0,1) return False elif self.ids.surname.text.strip() == '': self.ids.surname.hint_text_color = (1,0,0,1) return False elif self.ids.age.text.strip() == '' or int(self.ids.age.text) <= 0 or \ int(self.ids.age.text) >= 120: self.ids.age.text = '' self.ids.age.hint_text_color = (1,0,0,1) return False elif not(self.ids.male.active or self.ids.female.active): self.ids.sex.color = (1,0,0,1) return False elif not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", self.ids.email.text): self.ids.email.text = '' self.ids.email.hint_text_color = (1,0,0,1) return False elif self.ids.weight.text.strip() == '' or int(self.ids.weight.text) <= 0: self.ids.weight.text = '' self.ids.weight.hint_text_color = (1,0,0,1) return False elif not(self.ids.seated.active or self.ids.both.active or self.ids.standing.active): self.ids.activity.color = (1,0,0,1) return False elif self.ids.days.text.strip() == '' or int(self.ids.days.text) <= 0: self.ids.days.text = '' self.ids.days.hint_text_color = (1,0,0,1) return False else: self.settings['rec'] = True self.settings['name'] = self.ids.name.text self.settings['surname'] = self.ids.surname.text self.settings['age'] = int(self.ids.age.text) self.settings['weight'] = int(self.ids.weight.text) self.settings['email'] = self.ids.email.text self.settings['days'] = int(self.ids.days.text) self.settings['sex'] = self.ids.male.active if self.ids.seated.active: self.settings['activity'] = 1.4 if self.ids.both.active: self.settings['activity'] = 1.6 if self.ids.standing.active: self.settings['activity'] = 1.8 self.resetForm() else: self.settings['rec'] = False self.manager.setSettings(self.settings, self.id_profile) self.manager.current = 'Product Screen' class ScreenProduct(Screen): temp_dict = {'code':'', 'product_name': ''} def getSelection(self, text1, text2, state): if state: self.temp_dict['code'] = text1 self.temp_dict['product_name'] = text2 else: self.temp_dict['code'] = '' self.temp_dict['product_name'] = '' class ScreenQuantities(Screen): temp_dict = {'code': [], 'product_name': [], 'quantity': [], 'color': []} def initQuantity(self, data): if self.temp_dict['quantity'] == []: self.temp_dict = data self.ids.rv.getQuantities(data) def updateQuantity(self, index, text1, text2, text3): l = len(self.temp_dict['quantity']) if text3 == '' or text3 == '-' or int(text3) < 0: text3 = '0' if index < l: self.temp_dict['code'][index] = text1 self.temp_dict['product_name'][index] = text2 self.temp_dict['quantity'][index] = text3 else: temp = ['0' for i in range(index-l)] self.temp_dict['code'] = self.temp_dict['code'] + temp + [text1] self.temp_dict['product_name'] = self.temp_dict['product_name'] + temp + [text2] self.temp_dict['quantity'] = self.temp_dict['quantity'] + temp + [text3] self.initQuantity(self.temp_dict) class ScreenFinal(Screen): pass class Manager(ScreenManager): selected_products = {'code': [], 'product_name': [], 'quantity': []} settings = {'Rec': True, 'Name': '', 'Surname': '', 'Email': '', 'Age': 0, 'Sex': True, 'Pal': 0, \ 'Weight': 0, 'Day': 0} def getProfiles(self): self.ids.screen_profile.ids.profile_spinner.values = \ [str(index + 1) + ' : ' + str(profile_list['name'][index]) + ' ' + str(profile_list['surname'][index]) \ for index in profile_list.index] def toSettings(self, text): if text == 'new': id_profile = -999 elif text == 'pass': id_profile = -1000 else: items = text.split() id_profile = items[0].strip() id_profile = int(id_profile) - 1 self.ids.screen_settings.setForm(id_profile) if id_profile != -1000: self.current = 'Settings Screen' def addProduct(self): item1 = self.ids.screen_product.temp_dict['code'] item2 = self.ids.screen_product.temp_dict['product_name'] if item1 != '' and item2 != '': self.selected_products['code'].append(item1) self.selected_products['product_name'].append(item2) self.selected_products['quantity'].append('0') def deleteProduct(self): item1 = self.ids.screen_product.temp_dict['code'] item2 = self.ids.screen_product.temp_dict['product_name'] if item1 in self.selected_products['code'] and item2 in self.selected_products['product_name']: self.selected_products['code'].remove(item1) self.selected_products['product_name'].remove(item2) self.selected_products['quantity'].pop() def getQuantities(self, data): self.selected_products['quantity'] = data['quantity'] l = len(self.selected_products['quantity']) for item in range(l): if self.selected_products['quantity'][item] == '': self.selected_products['quantity'][item] = '0' self.current = 'Final Screen' def setSettings(self, data, new): self.settings['Rec'] = data['rec'] self.settings['Name'] = data['name'] self.settings['Surname'] = data['surname'] self.settings['Email'] = data['email'] self.settings['Pal'] = data['activity'] self.settings['Weight'] = data['weight'] self.settings['Day'] = data['days'] self.settings['Sex'] = data['sex'] self.settings['Age'] = data['age'] update = True if new == -999: temp_df = pd.DataFrame.from_dict({'index': [len(profile_list)], \ 'name': [data['name']], 'surname': [data['surname']], \ 'age': [data['age']], 'sex': [data['sex']], 'email': [data['email']], \ 'weight': [data['weight']], \ 'activity': [data['activity']], 'days': [data['days']]}).set_index('index') new_profile_list = pd.concat([profile_list, temp_df]) elif new == -1000: update = False else: temp_df = pd.DataFrame.from_dict({'name': [data['name']], 'surname': [data['surname']], \ 'age': [data['age']], 'sex': [data['sex']], 'email': [data['email']], 'weight': [data['weight']], \ 'activity': [data['activity']], 'days': [data['days']]}) new_profile_list= profile_list new_profile_list.iloc[new] = temp_df.iloc[0] if update: new_profile_list.to_csv('./data/profile.csv', sep=';') def computation(self): dict_product = {'Product': [], 'API': []} for index in range(len(self.selected_products['code'])): if str(self.selected_products['code'][index]) == 'API': dict_product['API'].append((str(self.selected_products[ 'product_name'][index]), int(self.selected_products['quantity'][index]))) else: dict_product['Product'].append((str(self.selected_products[ 'code'][index]), int(self.selected_products['quantity'][index]))) text_app_beverages, text_app_nonbeverages = algo(dict_product, self.settings, DF) self.ids.screen_final.ids.beverages.text = text_app_beverages self.ids.screen_final.ids.non_beverages.text = text_app_nonbeverages class NutriScoreApp(App): def build(self): global DF, allTrue, profile_list try: DF = pd.read_csv('./data/OpenFoodFacts_final.csv.gz', low_memory=False, index_col = [0]) allTrue = DF['product_name'].str.contains('', case=False) profile_list = pd.read_csv('./data/profile.csv', sep=';', index_col=[0]) except: print('Fatal error: files missing') return Manager() if __name__ == '__main__': NutriScoreApp().run()
true
true
f7168bb426ad7afb8dbd70d8b80b3ec7a14dbc4b
28,177
py
Python
sppas/sppas/src/ui/phoenix/page_files/associate.py
mirfan899/MTTS
3167b65f576abcc27a8767d24c274a04712bd948
[ "MIT" ]
null
null
null
sppas/sppas/src/ui/phoenix/page_files/associate.py
mirfan899/MTTS
3167b65f576abcc27a8767d24c274a04712bd948
[ "MIT" ]
null
null
null
sppas/sppas/src/ui/phoenix/page_files/associate.py
mirfan899/MTTS
3167b65f576abcc27a8767d24c274a04712bd948
[ "MIT" ]
null
null
null
""" .. --------------------------------------------------------------------- ___ __ __ __ ___ / | \ | \ | \ / the automatic \__ |__/ |__/ |___| \__ annotation and \ | | | | \ analysis ___/ | | | | ___/ of speech http://www.sppas.org/ Use of this software is governed by the GNU Public License, version 3. SPPAS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SPPAS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SPPAS. If not, see <http://www.gnu.org/licenses/>. This banner notice must not be removed. --------------------------------------------------------------------- ui.phoenix.page_files.associate.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Actions to associate files and references of the catalogue. """ import wx import logging from sppas import sppasTypeError from sppas import sg from sppas.src.config import ui_translation from sppas.src.files import FileData from sppas.src.files import States from sppas.src.files import sppasFileDataFilters from ..dialogs import Information, Error from ..windows import sppasStaticText, sppasTextCtrl from ..windows import sppasPanel from ..windows import sppasDialog from ..windows import sppasToolbar from ..windows import BitmapTextButton, CheckButton from ..windows import sppasRadioBoxPanel from ..main_events import DataChangedEvent from .filesutils import IdentifierTextValidator # --------------------------------------------------------------------------- MSG_HEADER_FILTER = ui_translation.gettext("Checking files") MSG_NB_CHECKED = "{:d} files were matching the given filters and were checked." MSG_NO_CHECKED = "None of the files is matching the given filters." ASS_ACT_CHECK_ERROR = "Files can't be filtered due to the following" \ " error:\n{!s:s}" # --------------------------------------------------------------------------- class AssociatePanel(sppasPanel): """Panel with tools to associate files and references of the catalogue. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi """ def __init__(self, parent, name=wx.PanelNameStr): super(AssociatePanel, self).__init__( parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BORDER_NONE | wx.TAB_TRAVERSAL | wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN, name=name) # The data this page is working on self.__data = FileData() # State of the button to check all or none of the filenames self._checkall = False # Construct the panel self._create_content() self._setup_events() self.Layout() # ------------------------------------------------------------------------ def set_data(self, data): """Assign new data to this panel. :param data: (FileData) """ if isinstance(data, FileData) is False: raise sppasTypeError("FileData", type(data)) logging.debug('New data to set in the associate panel. ' 'Id={:s}'.format(data.id)) self.__data = data # ------------------------------------------------------------------------ # Private methods to construct the panel. # ------------------------------------------------------------------------ def _create_content(self): """Create the main content.""" filtr = self.__create_button("check_filter") check = self.__create_button("checklist") link = self.__create_button("link_add") unlink = self.__create_button("link_del") sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddStretchSpacer(4) sizer.Add(filtr, 1, wx.TOP | wx.ALIGN_CENTRE, 0) sizer.Add(check, 1, wx.TOP | wx.ALIGN_CENTRE, 0) sizer.AddStretchSpacer(2) sizer.Add(link, 1, wx.BOTTOM | wx.ALIGN_CENTRE, 0) sizer.Add(unlink, 1, wx.BOTTOM | wx.ALIGN_CENTRE, 0) sizer.AddStretchSpacer(4) self.SetMinSize(wx.Size(sppasPanel.fix_size(32), -1)) self.SetSizer(sizer) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ def __create_button(self, icon, label=None): btn = BitmapTextButton(self, name=icon, label=label) btn.FocusStyle = wx.PENSTYLE_SOLID btn.FocusWidth = 3 btn.FocusColour = wx.Colour(128, 128, 196, 128) # violet btn.LabelPosition = wx.BOTTOM btn.Spacing = 4 btn.BorderWidth = 0 btn.BitmapColour = self.GetForegroundColour() btn.SetMinSize(wx.Size(sppasPanel.fix_size(24), sppasPanel.fix_size(24))) return btn # ----------------------------------------------------------------------- # Events management # ----------------------------------------------------------------------- def _setup_events(self): """Associate a handler function with the events. It means that when an event occurs then the process handler function will be called. """ # The user pressed a key of its keyboard self.Bind(wx.EVT_KEY_DOWN, self._process_key_event) # The user clicked (LeftDown - LeftUp) an action button self.Bind(wx.EVT_BUTTON, self._process_action) # ------------------------------------------------------------------------ def notify(self): """Send the EVT_DATA_CHANGED to the parent.""" if self.GetParent() is not None: self.__data.set_state(States().CHECKED) evt = DataChangedEvent(data=self.__data) evt.SetEventObject(self) wx.PostEvent(self.GetParent(), evt) # ------------------------------------------------------------------------ # Callbacks to events # ------------------------------------------------------------------------ def _process_key_event(self, event): """Respond to a keypress event.""" key_code = event.GetKeyCode() logging.debug('Associate panel received a key event. key_code={:d}'.format(key_code)) logging.debug('Key event skipped by the associate panel.') event.Skip() # ------------------------------------------------------------------------ def _process_action(self, event): """Respond to an association event.""" name = event.GetButtonObj().GetName() if name == "check_filter": self.check_filter() elif name == "checklist": self.check_all() elif name == "link_add": self.add_links() elif name == "link_del": self.delete_links() event.Skip() # ------------------------------------------------------------------------ # GUI methods to perform actions on the data # ------------------------------------------------------------------------ def check_filter(self): """Check filenames matching the user-defined filters.""" dlg = sppasFilesFilterDialog(self) response = dlg.ShowModal() if response != wx.ID_CANCEL: data_filters = dlg.get_filters() if len(data_filters) > 0: wx.BeginBusyCursor() try: data_set = self.__process_filter(data_filters, dlg.match_all) if len(data_set) == 0: Information(MSG_NO_CHECKED) else: # Uncheck all files (except the locked ones!) and all references self.__data.set_object_state(States().UNUSED) roots = list() # Check files of the filtered data_set for fn in data_set: self.__data.set_object_state(States().CHECKED, fn) root = self.__data.get_parent(fn) if root not in roots: roots.append(root) Information(MSG_NB_CHECKED.format(len(data_set))) # Check references matching the checked files for fr in roots: for ref in fr.get_references(): ref.set_state(States().CHECKED) self.notify() wx.EndBusyCursor() except Exception as e: wx.EndBusyCursor() Error(ASS_ACT_CHECK_ERROR.format(str(e)), "Check error") dlg.Destroy() # ------------------------------------------------------------------------ def __process_filter(self, data_filters, match_all=True): """Perform the filter process. :param data_filters: list of tuples with (filter name, function name, values) :param match_all: (bool) """ logging.info("Check files matching the following: ") logging.info(" >>> filter = sppasFileDataFilters()") f = sppasFileDataFilters(self.__data) data_sets = list() for d in data_filters: if len(d) != 3: logging.error("Bad data format: {:s}".format(str(d))) continue # the method to be uses by Compare method = d[0] # the function to be applied fct = d[1] if method == "att": # identifier:value are separated by a ":" but a tuple is needed values = tuple(d[2].split(":")) logging.info(" >>> filter.{:s}({:s}={!s:s})".format(method, fct, str(values))) data_set = getattr(f, method)(**{fct: values}) # a little bit of doc: # - getattr() returns the value of the named attributed of object: # it returns f.tag if called like getattr(f, "tag") # - func(**{'x': '3'}) is equivalent to func(x='3') else: # all the possible values are separated by commas values = d[2].split(",") logging.info(" >>> filter.{:s}({:s}={!s:s})".format(method, fct, values[0])) data_set = getattr(f, method)(**{fct: values[0]}) # Apply "or" between each data_set matching a value for i in range(1, len(values)): v = values[i].strip() data_set = data_set | getattr(f, method)(**{fct: v}) logging.info(" >>> | filter.{:s}({:s}={!s:s})".format(method, fct, v)) data_sets.append(data_set) # no filename is matching if len(data_sets) == 0: return list() # Merge results (apply '&' or '|' on the resulting data sets) data_set = data_sets[0] if match_all is True: for i in range(1, len(data_sets)): data_set = data_set & data_sets[i] if len(data_set) == 0: # no need to go further... return list() else: for i in range(1, len(data_sets)): data_set = data_set | data_sets[i] return data_set # ------------------------------------------------------------------------ def check_all(self): """Check all or any of the filenames and references.""" # reverse the current state self._checkall = not self._checkall # ask the data to change their state if self._checkall is True: state = States().CHECKED else: state = States().UNUSED self.__data.set_object_state(state) # update the view of checked references & checked files self.notify() # ------------------------------------------------------------------------ def add_links(self): """Associate checked filenames with checked references.""" associed = self.__data.associate() if associed > 0: self.notify() # ------------------------------------------------------------------------ def delete_links(self): """Dissociate checked filenames with checked references.""" dissocied = self.__data.dissociate() if dissocied > 0: self.notify() # --------------------------------------------------------------------------- class sppasFilesFilterDialog(sppasDialog): """Dialog to get filters to check files and references. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi """ def __init__(self, parent): """Create a files filter dialog. :param parent: (wx.Window) """ super(sppasFilesFilterDialog, self).__init__( parent=parent, title='{:s} Files selection'.format(sg.__name__), style=wx.DEFAULT_FRAME_STYLE) self.match_all = True self.CreateHeader(title="Define filters to check files", icon_name="check_filter") self._create_content() self._create_buttons() self.Bind(wx.EVT_BUTTON, self._process_event) self.SetSize(wx.Size(480, 320)) self.LayoutComponents() self.CenterOnParent() self.FadeIn(deltaN=-8) # ----------------------------------------------------------------------- # Public methods # ----------------------------------------------------------------------- def get_filters(self): """Return a list of (filter, function, values).""" filters = list() for i in range(self.listctrl.GetItemCount()): filter_name = self.listctrl.GetValue(i, 0) fct_name = self.listctrl.GetValue(i, 1) values = self.listctrl.GetValue(i, 2) filters.append((filter_name, fct_name, values)) return filters # ----------------------------------------------------------------------- # Methods to construct the GUI # ----------------------------------------------------------------------- def _create_content(self): """Create the content of the message dialog.""" panel = sppasPanel(self, name="content") tb = self.__create_toolbar(panel) self.listctrl = wx.dataview.DataViewListCtrl(panel, wx.ID_ANY) self.listctrl.AppendTextColumn("filter", width=80) self.listctrl.AppendTextColumn("function", width=90) self.listctrl.AppendTextColumn("value", width=120) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(tb, proportion=0, flag=wx.EXPAND, border=0) sizer.Add(self.listctrl, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5) panel.SetSizer(sizer) self.SetMinSize(wx.Size(320, 200)) panel.SetAutoLayout(True) self.SetContent(panel) # ----------------------------------------------------------------------- def __create_toolbar(self, parent): """Create the toolbar.""" tb = sppasToolbar(parent) tb.set_focus_color(wx.Colour(196, 196, 96, 128)) tb.AddTextButton("filter_path", "+ Path") tb.AddTextButton("filter_name", "+ Name") tb.AddTextButton("filter_ext", "+ Type") tb.AddTextButton("filter_ref", "+ Ref.") tb.AddTextButton("filter_att", "+ Value") tb.AddSpacer() #tb.AddTextButton(None, "- Remove") return tb # ----------------------------------------------------------------------- def _create_buttons(self): """Create the buttons and bind events.""" panel = sppasPanel(self, name="actions") # panel.SetMinSize(wx.Size(-1, wx.GetApp().settings.action_height)) sizer = wx.BoxSizer(wx.HORIZONTAL) # Create the buttons cancel_btn = self.__create_action_button(panel, "Cancel", "cancel") apply_or_btn = self.__create_action_button(panel, "Apply - OR", "apply") apply_and_btn = self.__create_action_button(panel, "Apply - AND", "ok") apply_and_btn.SetFocus() sizer.Add(cancel_btn, 1, wx.ALL | wx.EXPAND, 0) sizer.Add(self.VertLine(parent=panel), 0, wx.ALL | wx.EXPAND, 0) sizer.Add(apply_or_btn, 1, wx.ALL | wx.EXPAND, 0) sizer.Add(self.VertLine(parent=panel), 0, wx.ALL | wx.EXPAND, 0) sizer.Add(apply_and_btn, 1, wx.ALL | wx.EXPAND, 0) panel.SetSizer(sizer) self.SetActions(panel) # ----------------------------------------------------------------------- def __create_action_button(self, parent, text, icon): btn = BitmapTextButton(parent, label=text, name=icon) btn.LabelPosition = wx.RIGHT btn.Spacing = sppasDialog.fix_size(12) btn.BorderWidth = 0 btn.BitmapColour = self.GetForegroundColour() btn.SetMinSize(wx.Size(sppasDialog.fix_size(32), sppasDialog.fix_size(32))) return btn # ------------------------------------------------------------------------ # Callback to events # ------------------------------------------------------------------------ def _process_event(self, event): """Process any kind of events. :param event: (wx.Event) """ event_obj = event.GetEventObject() event_name = event_obj.GetName() if event_name == "filter_path": self.__append_filter("path") elif event_name == "filter_name": self.__append_filter("name") elif event_name == "filter_ext": self.__append_filter("extension") elif event_name == "filter_ref": self.__append_filter("ref") elif event_name == "filter_att": dlg = sppasAttributeFilterDialog(self) response = dlg.ShowModal() if response == wx.ID_OK: # Name of the method in sppasFileDataFilters, # Name of the function and its value f = dlg.get_data() v = f[1].split(':') if len(v[0].strip()) > 1 and len(v[1].strip()) > 0: self.listctrl.AppendItem(["att", f[0], f[1].strip()]) else: logging.error("Invalid input string for identifier or value.") dlg.Destroy() elif event_name == "cancel": self.SetReturnCode(wx.ID_CANCEL) self.Close() elif event_name == "apply": self.match_all = False self.EndModal(wx.ID_APPLY) elif event_name == "ok": self.match_all = True self.EndModal(wx.ID_OK) else: event.Skip() # ------------------------------------------------------------------------ def __append_filter(self, fct): dlg = sppasStringFilterDialog(self) response = dlg.ShowModal() if response == wx.ID_OK: # Name of the method in sppasFileDataFilters, # Name of the function and its value f = dlg.get_data() if len(f[1].strip()) > 0: self.listctrl.AppendItem([fct, f[0], f[1].strip()]) else: logging.error("Empty input pattern.") dlg.Destroy() # --------------------------------------------------------------------------- class sppasStringFilterDialog(sppasDialog): """Dialog to get a filter on a string. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi """ choices = ( ("exact", "exact"), ("contains", "contains"), ("starts with", "startswith"), ("ends with", "endswith"), ("match (regexp)", "regexp"), ("not exact", "exact"), ("not contains", "contains"), ("not starts with", "startswith"), ("not ends with", "endswith"), ("not match", "regexp") ) def __init__(self, parent): """Create a string filter dialog. :param parent: (wx.Window) """ super(sppasStringFilterDialog, self).__init__( parent=parent, title='{:s} filter'.format(sg.__name__), style=wx.DEFAULT_FRAME_STYLE) self._create_content() self.CreateActions([wx.ID_CANCEL, wx.ID_OK]) self.SetSize(wx.Size(380, 320)) self.LayoutComponents() self.CenterOnParent() # ----------------------------------------------------------------------- def get_data(self): """Return the data defined by the user. Returns: (tuple) with: - function (str): one of the methods in Compare - values (list): patterns to find separated by commas """ idx = self.radiobox.GetSelection() label = self.radiobox.GetStringSelection() given_fct = self.choices[idx][1] # Fill the resulting dict prepend_fct = "" if given_fct != "regexp": # prepend "not_" if reverse if "not" in label: prepend_fct += "not_" # prepend "i" if case-insensitive if self.checkbox.GetValue() is False: prepend_fct += "i" return prepend_fct+given_fct, self.text.GetValue() # ----------------------------------------------------------------------- # Methods to construct the GUI # ----------------------------------------------------------------------- def _create_content(self): """Create the content of the message dialog.""" panel = sppasPanel(self, name="content") label = sppasStaticText(panel, label="Search for pattern(s): ") self.text = sppasTextCtrl(panel, value="") choices = [row[0] for row in self.choices] self.radiobox = sppasRadioBoxPanel( panel, choices=choices, majorDimension=2, style=wx.RA_SPECIFY_COLS) self.radiobox.SetSelection(1) self.checkbox = CheckButton(panel, label="Case sensitive") self.checkbox.SetValue(False) # Layout sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(label, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.text, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.radiobox, 1, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.checkbox, 0, flag=wx.EXPAND | wx.ALL, border=4) panel.SetSizer(sizer) panel.SetMinSize((240, 160)) panel.SetAutoLayout(True) self.SetContent(panel) # --------------------------------------------------------------------------- class sppasAttributeFilterDialog(sppasDialog): """Dialog to get a filter on an attribute. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi """ choices = ( ("exact", "exact"), ("contains", "contains"), ("starts with", "startswith"), ("ends with", "endswith"), ("match (regexp)", "regexp"), ("not exact", "exact"), ("not contains", "contains"), ("not starts with", "startswith"), ("not ends with", "endswith"), ("not match", "regexp"), ("equal", "equal"), ("greater than", "gt"), ("greater or equal", "ge"), ("lower than", "lt"), ("lower or equal", "le") ) def __init__(self, parent): """Create an attribute filter dialog. :param parent: (wx.Window) """ super(sppasAttributeFilterDialog, self).__init__( parent=parent, title='{:s} filter'.format(sg.__name__), style=wx.DEFAULT_FRAME_STYLE) self._create_content() self.CreateActions([wx.ID_CANCEL, wx.ID_OK]) self.SetMinSize(wx.Size(sppasDialog.fix_size(420), sppasDialog.fix_size(320))) self.LayoutComponents() self.CenterOnParent() # ------------------------------------------------------------------------ def get_data(self): """Return the data defined by the user. Returns: (tuple) with: - function (str): one of the methods in Compare - values (list): attribute to find as identifier, value """ idx = self.radiobox.GetSelection() label = self.radiobox.GetStringSelection() given_fct = self.choices[idx][1] # Fill the resulting dict prepend_fct = "" if idx < 10 and given_fct != "regexp": # prepend "not_" if reverse if "not" in label: prepend_fct += "not_" # prepend "i" if case-insensitive if self.checkbox.GetValue() is False: prepend_fct += "i" return prepend_fct + given_fct, \ self.text_ident.GetValue() + ":" + self.text_value.GetValue() # ----------------------------------------------------------------------- # Methods to construct the GUI # ----------------------------------------------------------------------- def _create_content(self): """Create the content of the message dialog.""" panel = sppasPanel(self, name="content") label = sppasStaticText(panel, label="Identifier: ") self.text_ident = sppasTextCtrl( panel, value="", validator=IdentifierTextValidator()) choices = [row[0] for row in sppasAttributeFilterDialog.choices] self.radiobox = sppasRadioBoxPanel( panel, choices=choices, majorDimension=3, style=wx.RA_SPECIFY_COLS) self.radiobox.SetSelection(1) self.radiobox.Bind(wx.EVT_RADIOBOX, self._on_radiobox_checked) self.checkbox = CheckButton(panel, label="Case sensitive") self.checkbox.SetValue(False) self.text_value = sppasTextCtrl(panel, value="") # Layout sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(label, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.text_ident, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.radiobox, 1, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.text_value, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.checkbox, 0, flag=wx.EXPAND | wx.ALL, border=4) panel.SetSizer(sizer) panel.SetMinSize((240, 160)) panel.SetAutoLayout(True) self.SetContent(panel) def _on_radiobox_checked(self, event): value = self.radiobox.GetStringSelection() if value in sppasAttributeFilterDialog.choices[10:]: self.checkbox.SetValue(False) self.checkbox.Enable(False) else: self.checkbox.Enable(True)
35.894268
119
0.509245
import wx import logging from sppas import sppasTypeError from sppas import sg from sppas.src.config import ui_translation from sppas.src.files import FileData from sppas.src.files import States from sppas.src.files import sppasFileDataFilters from ..dialogs import Information, Error from ..windows import sppasStaticText, sppasTextCtrl from ..windows import sppasPanel from ..windows import sppasDialog from ..windows import sppasToolbar from ..windows import BitmapTextButton, CheckButton from ..windows import sppasRadioBoxPanel from ..main_events import DataChangedEvent from .filesutils import IdentifierTextValidator MSG_HEADER_FILTER = ui_translation.gettext("Checking files") MSG_NB_CHECKED = "{:d} files were matching the given filters and were checked." MSG_NO_CHECKED = "None of the files is matching the given filters." ASS_ACT_CHECK_ERROR = "Files can't be filtered due to the following" \ " error:\n{!s:s}" # --------------------------------------------------------------------------- class AssociatePanel(sppasPanel): def __init__(self, parent, name=wx.PanelNameStr): super(AssociatePanel, self).__init__( parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BORDER_NONE | wx.TAB_TRAVERSAL | wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN, name=name) # The data this page is working on self.__data = FileData() # State of the button to check all or none of the filenames self._checkall = False # Construct the panel self._create_content() self._setup_events() self.Layout() # ------------------------------------------------------------------------ def set_data(self, data): if isinstance(data, FileData) is False: raise sppasTypeError("FileData", type(data)) logging.debug('New data to set in the associate panel. ' 'Id={:s}'.format(data.id)) self.__data = data # ------------------------------------------------------------------------ # Private methods to construct the panel. # ------------------------------------------------------------------------ def _create_content(self): filtr = self.__create_button("check_filter") check = self.__create_button("checklist") link = self.__create_button("link_add") unlink = self.__create_button("link_del") sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddStretchSpacer(4) sizer.Add(filtr, 1, wx.TOP | wx.ALIGN_CENTRE, 0) sizer.Add(check, 1, wx.TOP | wx.ALIGN_CENTRE, 0) sizer.AddStretchSpacer(2) sizer.Add(link, 1, wx.BOTTOM | wx.ALIGN_CENTRE, 0) sizer.Add(unlink, 1, wx.BOTTOM | wx.ALIGN_CENTRE, 0) sizer.AddStretchSpacer(4) self.SetMinSize(wx.Size(sppasPanel.fix_size(32), -1)) self.SetSizer(sizer) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ def __create_button(self, icon, label=None): btn = BitmapTextButton(self, name=icon, label=label) btn.FocusStyle = wx.PENSTYLE_SOLID btn.FocusWidth = 3 btn.FocusColour = wx.Colour(128, 128, 196, 128) # violet btn.LabelPosition = wx.BOTTOM btn.Spacing = 4 btn.BorderWidth = 0 btn.BitmapColour = self.GetForegroundColour() btn.SetMinSize(wx.Size(sppasPanel.fix_size(24), sppasPanel.fix_size(24))) return btn # ----------------------------------------------------------------------- # Events management # ----------------------------------------------------------------------- def _setup_events(self): # The user pressed a key of its keyboard self.Bind(wx.EVT_KEY_DOWN, self._process_key_event) # The user clicked (LeftDown - LeftUp) an action button self.Bind(wx.EVT_BUTTON, self._process_action) # ------------------------------------------------------------------------ def notify(self): if self.GetParent() is not None: self.__data.set_state(States().CHECKED) evt = DataChangedEvent(data=self.__data) evt.SetEventObject(self) wx.PostEvent(self.GetParent(), evt) # ------------------------------------------------------------------------ # Callbacks to events # ------------------------------------------------------------------------ def _process_key_event(self, event): key_code = event.GetKeyCode() logging.debug('Associate panel received a key event. key_code={:d}'.format(key_code)) logging.debug('Key event skipped by the associate panel.') event.Skip() # ------------------------------------------------------------------------ def _process_action(self, event): name = event.GetButtonObj().GetName() if name == "check_filter": self.check_filter() elif name == "checklist": self.check_all() elif name == "link_add": self.add_links() elif name == "link_del": self.delete_links() event.Skip() # ------------------------------------------------------------------------ # GUI methods to perform actions on the data # ------------------------------------------------------------------------ def check_filter(self): dlg = sppasFilesFilterDialog(self) response = dlg.ShowModal() if response != wx.ID_CANCEL: data_filters = dlg.get_filters() if len(data_filters) > 0: wx.BeginBusyCursor() try: data_set = self.__process_filter(data_filters, dlg.match_all) if len(data_set) == 0: Information(MSG_NO_CHECKED) else: # Uncheck all files (except the locked ones!) and all references self.__data.set_object_state(States().UNUSED) roots = list() # Check files of the filtered data_set for fn in data_set: self.__data.set_object_state(States().CHECKED, fn) root = self.__data.get_parent(fn) if root not in roots: roots.append(root) Information(MSG_NB_CHECKED.format(len(data_set))) # Check references matching the checked files for fr in roots: for ref in fr.get_references(): ref.set_state(States().CHECKED) self.notify() wx.EndBusyCursor() except Exception as e: wx.EndBusyCursor() Error(ASS_ACT_CHECK_ERROR.format(str(e)), "Check error") dlg.Destroy() # ------------------------------------------------------------------------ def __process_filter(self, data_filters, match_all=True): logging.info("Check files matching the following: ") logging.info(" >>> filter = sppasFileDataFilters()") f = sppasFileDataFilters(self.__data) data_sets = list() for d in data_filters: if len(d) != 3: logging.error("Bad data format: {:s}".format(str(d))) continue # the method to be uses by Compare method = d[0] # the function to be applied fct = d[1] if method == "att": # identifier:value are separated by a ":" but a tuple is needed values = tuple(d[2].split(":")) logging.info(" >>> filter.{:s}({:s}={!s:s})".format(method, fct, str(values))) data_set = getattr(f, method)(**{fct: values}) # a little bit of doc: # - getattr() returns the value of the named attributed of object: # it returns f.tag if called like getattr(f, "tag") # - func(**{'x': '3'}) is equivalent to func(x='3') else: # all the possible values are separated by commas values = d[2].split(",") logging.info(" >>> filter.{:s}({:s}={!s:s})".format(method, fct, values[0])) data_set = getattr(f, method)(**{fct: values[0]}) # Apply "or" between each data_set matching a value for i in range(1, len(values)): v = values[i].strip() data_set = data_set | getattr(f, method)(**{fct: v}) logging.info(" >>> | filter.{:s}({:s}={!s:s})".format(method, fct, v)) data_sets.append(data_set) # no filename is matching if len(data_sets) == 0: return list() # Merge results (apply '&' or '|' on the resulting data sets) data_set = data_sets[0] if match_all is True: for i in range(1, len(data_sets)): data_set = data_set & data_sets[i] if len(data_set) == 0: # no need to go further... return list() else: for i in range(1, len(data_sets)): data_set = data_set | data_sets[i] return data_set # ------------------------------------------------------------------------ def check_all(self): # reverse the current state self._checkall = not self._checkall # ask the data to change their state if self._checkall is True: state = States().CHECKED else: state = States().UNUSED self.__data.set_object_state(state) # update the view of checked references & checked files self.notify() # ------------------------------------------------------------------------ def add_links(self): associed = self.__data.associate() if associed > 0: self.notify() # ------------------------------------------------------------------------ def delete_links(self): dissocied = self.__data.dissociate() if dissocied > 0: self.notify() # --------------------------------------------------------------------------- class sppasFilesFilterDialog(sppasDialog): def __init__(self, parent): super(sppasFilesFilterDialog, self).__init__( parent=parent, title='{:s} Files selection'.format(sg.__name__), style=wx.DEFAULT_FRAME_STYLE) self.match_all = True self.CreateHeader(title="Define filters to check files", icon_name="check_filter") self._create_content() self._create_buttons() self.Bind(wx.EVT_BUTTON, self._process_event) self.SetSize(wx.Size(480, 320)) self.LayoutComponents() self.CenterOnParent() self.FadeIn(deltaN=-8) # ----------------------------------------------------------------------- # Public methods # ----------------------------------------------------------------------- def get_filters(self): filters = list() for i in range(self.listctrl.GetItemCount()): filter_name = self.listctrl.GetValue(i, 0) fct_name = self.listctrl.GetValue(i, 1) values = self.listctrl.GetValue(i, 2) filters.append((filter_name, fct_name, values)) return filters # ----------------------------------------------------------------------- # Methods to construct the GUI # ----------------------------------------------------------------------- def _create_content(self): panel = sppasPanel(self, name="content") tb = self.__create_toolbar(panel) self.listctrl = wx.dataview.DataViewListCtrl(panel, wx.ID_ANY) self.listctrl.AppendTextColumn("filter", width=80) self.listctrl.AppendTextColumn("function", width=90) self.listctrl.AppendTextColumn("value", width=120) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(tb, proportion=0, flag=wx.EXPAND, border=0) sizer.Add(self.listctrl, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5) panel.SetSizer(sizer) self.SetMinSize(wx.Size(320, 200)) panel.SetAutoLayout(True) self.SetContent(panel) # ----------------------------------------------------------------------- def __create_toolbar(self, parent): tb = sppasToolbar(parent) tb.set_focus_color(wx.Colour(196, 196, 96, 128)) tb.AddTextButton("filter_path", "+ Path") tb.AddTextButton("filter_name", "+ Name") tb.AddTextButton("filter_ext", "+ Type") tb.AddTextButton("filter_ref", "+ Ref.") tb.AddTextButton("filter_att", "+ Value") tb.AddSpacer() #tb.AddTextButton(None, "- Remove") return tb # ----------------------------------------------------------------------- def _create_buttons(self): panel = sppasPanel(self, name="actions") # panel.SetMinSize(wx.Size(-1, wx.GetApp().settings.action_height)) sizer = wx.BoxSizer(wx.HORIZONTAL) # Create the buttons cancel_btn = self.__create_action_button(panel, "Cancel", "cancel") apply_or_btn = self.__create_action_button(panel, "Apply - OR", "apply") apply_and_btn = self.__create_action_button(panel, "Apply - AND", "ok") apply_and_btn.SetFocus() sizer.Add(cancel_btn, 1, wx.ALL | wx.EXPAND, 0) sizer.Add(self.VertLine(parent=panel), 0, wx.ALL | wx.EXPAND, 0) sizer.Add(apply_or_btn, 1, wx.ALL | wx.EXPAND, 0) sizer.Add(self.VertLine(parent=panel), 0, wx.ALL | wx.EXPAND, 0) sizer.Add(apply_and_btn, 1, wx.ALL | wx.EXPAND, 0) panel.SetSizer(sizer) self.SetActions(panel) # ----------------------------------------------------------------------- def __create_action_button(self, parent, text, icon): btn = BitmapTextButton(parent, label=text, name=icon) btn.LabelPosition = wx.RIGHT btn.Spacing = sppasDialog.fix_size(12) btn.BorderWidth = 0 btn.BitmapColour = self.GetForegroundColour() btn.SetMinSize(wx.Size(sppasDialog.fix_size(32), sppasDialog.fix_size(32))) return btn # ------------------------------------------------------------------------ # Callback to events # ------------------------------------------------------------------------ def _process_event(self, event): event_obj = event.GetEventObject() event_name = event_obj.GetName() if event_name == "filter_path": self.__append_filter("path") elif event_name == "filter_name": self.__append_filter("name") elif event_name == "filter_ext": self.__append_filter("extension") elif event_name == "filter_ref": self.__append_filter("ref") elif event_name == "filter_att": dlg = sppasAttributeFilterDialog(self) response = dlg.ShowModal() if response == wx.ID_OK: # Name of the method in sppasFileDataFilters, # Name of the function and its value f = dlg.get_data() v = f[1].split(':') if len(v[0].strip()) > 1 and len(v[1].strip()) > 0: self.listctrl.AppendItem(["att", f[0], f[1].strip()]) else: logging.error("Invalid input string for identifier or value.") dlg.Destroy() elif event_name == "cancel": self.SetReturnCode(wx.ID_CANCEL) self.Close() elif event_name == "apply": self.match_all = False self.EndModal(wx.ID_APPLY) elif event_name == "ok": self.match_all = True self.EndModal(wx.ID_OK) else: event.Skip() # ------------------------------------------------------------------------ def __append_filter(self, fct): dlg = sppasStringFilterDialog(self) response = dlg.ShowModal() if response == wx.ID_OK: # Name of the method in sppasFileDataFilters, # Name of the function and its value f = dlg.get_data() if len(f[1].strip()) > 0: self.listctrl.AppendItem([fct, f[0], f[1].strip()]) else: logging.error("Empty input pattern.") dlg.Destroy() # --------------------------------------------------------------------------- class sppasStringFilterDialog(sppasDialog): choices = ( ("exact", "exact"), ("contains", "contains"), ("starts with", "startswith"), ("ends with", "endswith"), ("match (regexp)", "regexp"), ("not exact", "exact"), ("not contains", "contains"), ("not starts with", "startswith"), ("not ends with", "endswith"), ("not match", "regexp") ) def __init__(self, parent): super(sppasStringFilterDialog, self).__init__( parent=parent, title='{:s} filter'.format(sg.__name__), style=wx.DEFAULT_FRAME_STYLE) self._create_content() self.CreateActions([wx.ID_CANCEL, wx.ID_OK]) self.SetSize(wx.Size(380, 320)) self.LayoutComponents() self.CenterOnParent() # ----------------------------------------------------------------------- def get_data(self): idx = self.radiobox.GetSelection() label = self.radiobox.GetStringSelection() given_fct = self.choices[idx][1] # Fill the resulting dict prepend_fct = "" if given_fct != "regexp": # prepend "not_" if reverse if "not" in label: prepend_fct += "not_" # prepend "i" if case-insensitive if self.checkbox.GetValue() is False: prepend_fct += "i" return prepend_fct+given_fct, self.text.GetValue() # ----------------------------------------------------------------------- # Methods to construct the GUI # ----------------------------------------------------------------------- def _create_content(self): panel = sppasPanel(self, name="content") label = sppasStaticText(panel, label="Search for pattern(s): ") self.text = sppasTextCtrl(panel, value="") choices = [row[0] for row in self.choices] self.radiobox = sppasRadioBoxPanel( panel, choices=choices, majorDimension=2, style=wx.RA_SPECIFY_COLS) self.radiobox.SetSelection(1) self.checkbox = CheckButton(panel, label="Case sensitive") self.checkbox.SetValue(False) # Layout sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(label, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.text, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.radiobox, 1, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.checkbox, 0, flag=wx.EXPAND | wx.ALL, border=4) panel.SetSizer(sizer) panel.SetMinSize((240, 160)) panel.SetAutoLayout(True) self.SetContent(panel) # --------------------------------------------------------------------------- class sppasAttributeFilterDialog(sppasDialog): choices = ( ("exact", "exact"), ("contains", "contains"), ("starts with", "startswith"), ("ends with", "endswith"), ("match (regexp)", "regexp"), ("not exact", "exact"), ("not contains", "contains"), ("not starts with", "startswith"), ("not ends with", "endswith"), ("not match", "regexp"), ("equal", "equal"), ("greater than", "gt"), ("greater or equal", "ge"), ("lower than", "lt"), ("lower or equal", "le") ) def __init__(self, parent): super(sppasAttributeFilterDialog, self).__init__( parent=parent, title='{:s} filter'.format(sg.__name__), style=wx.DEFAULT_FRAME_STYLE) self._create_content() self.CreateActions([wx.ID_CANCEL, wx.ID_OK]) self.SetMinSize(wx.Size(sppasDialog.fix_size(420), sppasDialog.fix_size(320))) self.LayoutComponents() self.CenterOnParent() # ------------------------------------------------------------------------ def get_data(self): idx = self.radiobox.GetSelection() label = self.radiobox.GetStringSelection() given_fct = self.choices[idx][1] # Fill the resulting dict prepend_fct = "" if idx < 10 and given_fct != "regexp": # prepend "not_" if reverse if "not" in label: prepend_fct += "not_" # prepend "i" if case-insensitive if self.checkbox.GetValue() is False: prepend_fct += "i" return prepend_fct + given_fct, \ self.text_ident.GetValue() + ":" + self.text_value.GetValue() # ----------------------------------------------------------------------- # Methods to construct the GUI # ----------------------------------------------------------------------- def _create_content(self): panel = sppasPanel(self, name="content") label = sppasStaticText(panel, label="Identifier: ") self.text_ident = sppasTextCtrl( panel, value="", validator=IdentifierTextValidator()) choices = [row[0] for row in sppasAttributeFilterDialog.choices] self.radiobox = sppasRadioBoxPanel( panel, choices=choices, majorDimension=3, style=wx.RA_SPECIFY_COLS) self.radiobox.SetSelection(1) self.radiobox.Bind(wx.EVT_RADIOBOX, self._on_radiobox_checked) self.checkbox = CheckButton(panel, label="Case sensitive") self.checkbox.SetValue(False) self.text_value = sppasTextCtrl(panel, value="") # Layout sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(label, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.text_ident, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.radiobox, 1, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.text_value, 0, flag=wx.EXPAND | wx.ALL, border=4) sizer.Add(self.checkbox, 0, flag=wx.EXPAND | wx.ALL, border=4) panel.SetSizer(sizer) panel.SetMinSize((240, 160)) panel.SetAutoLayout(True) self.SetContent(panel) def _on_radiobox_checked(self, event): value = self.radiobox.GetStringSelection() if value in sppasAttributeFilterDialog.choices[10:]: self.checkbox.SetValue(False) self.checkbox.Enable(False) else: self.checkbox.Enable(True)
true
true
f7168c18be9b4f3d5729f54a2173850564c1755b
617
py
Python
src/DoorControl_manual.py
oulkaid/MoSIG-SystemDesign-WCET
bbe640ebbad7a372e4bd826a3334a69f3aca28e7
[ "MIT" ]
null
null
null
src/DoorControl_manual.py
oulkaid/MoSIG-SystemDesign-WCET
bbe640ebbad7a372e4bd826a3334a69f3aca28e7
[ "MIT" ]
null
null
null
src/DoorControl_manual.py
oulkaid/MoSIG-SystemDesign-WCET
bbe640ebbad7a372e4bd826a3334a69f3aca28e7
[ "MIT" ]
null
null
null
start_addr = [] next_addr = [] start_addr.append(['8478']) next_addr.append(['84a4','8498']) start_addr.append(['8498']) next_addr.append(['84b0','84a4']) start_addr.append(['84a4']) next_addr.append(['84b0']) start_addr.append(['84b0']) next_addr.append(['84e0','84d4']) start_addr.append(['84d4']) next_addr.append(['84ec','84e0']) start_addr.append(['84e0']) next_addr.append(['84ec']) start_addr.append(['84ec']) next_addr.append(['8514','84fc']) for index in range(len(start_addr)): print("BB " + str(index+1) + ": Start@ = " + str(start_addr[index]) + " , Next@ = " + str(next_addr[index]))
20.566667
117
0.648298
start_addr = [] next_addr = [] start_addr.append(['8478']) next_addr.append(['84a4','8498']) start_addr.append(['8498']) next_addr.append(['84b0','84a4']) start_addr.append(['84a4']) next_addr.append(['84b0']) start_addr.append(['84b0']) next_addr.append(['84e0','84d4']) start_addr.append(['84d4']) next_addr.append(['84ec','84e0']) start_addr.append(['84e0']) next_addr.append(['84ec']) start_addr.append(['84ec']) next_addr.append(['8514','84fc']) for index in range(len(start_addr)): print("BB " + str(index+1) + ": Start@ = " + str(start_addr[index]) + " , Next@ = " + str(next_addr[index]))
true
true
f7168c43af7fe79343018a0288432cf66f89741a
1,124
py
Python
app/auth/views.py
0xff-dev/SutAcmDRA
f3e744c19f66f930deb3f921b75d5f1189354b41
[ "MIT" ]
2
2018-07-16T16:14:32.000Z
2018-07-23T06:48:29.000Z
app/auth/views.py
0xff-dev/SutAcmDRA
f3e744c19f66f930deb3f921b75d5f1189354b41
[ "MIT" ]
3
2021-06-08T19:23:40.000Z
2021-12-13T19:56:54.000Z
app/auth/views.py
stevenshuang/SutAcmDRA
f3e744c19f66f930deb3f921b75d5f1189354b41
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding=utf-8 from flask import render_template, request from flask import redirect, url_for, flash from flask_login import login_user from flask_login import login_required from flask_login import logout_user from . import auth from ..models import User from .. import logger @auth.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: user_name = request.form.get('username') passwd = request.form.get('password') try: user = User.query.filter_by(hdoj_username=user_name).first() except Exception as e: logger.info('用户不存在') if user is not None and user.verify_password(passwd): login_user(user) return redirect( request.args.get('next') or url_for('main.index', ) ) flash('Invald Username Or Password') @auth.route('/logout') @login_required def logout(): logout_user() flash('You have been logged out') return redirect(url_for('main.index'))
28.1
72
0.6379
from flask import render_template, request from flask import redirect, url_for, flash from flask_login import login_user from flask_login import login_required from flask_login import logout_user from . import auth from ..models import User from .. import logger @auth.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: user_name = request.form.get('username') passwd = request.form.get('password') try: user = User.query.filter_by(hdoj_username=user_name).first() except Exception as e: logger.info('用户不存在') if user is not None and user.verify_password(passwd): login_user(user) return redirect( request.args.get('next') or url_for('main.index', ) ) flash('Invald Username Or Password') @auth.route('/logout') @login_required def logout(): logout_user() flash('You have been logged out') return redirect(url_for('main.index'))
true
true
f7168e80f5e8ed5edf7f7288316f9a3d0d8192e3
5,675
py
Python
nimiqclient/models/block.py
rraallvv/python-client
65d0c3f835ed8ce3ba6bfa2565cac61f7da6b748
[ "Apache-2.0" ]
4
2020-11-03T21:13:13.000Z
2022-01-18T08:40:27.000Z
nimiqclient/models/block.py
rraallvv/python-client
65d0c3f835ed8ce3ba6bfa2565cac61f7da6b748
[ "Apache-2.0" ]
1
2020-08-09T21:36:02.000Z
2020-08-09T21:36:02.000Z
nimiqclient/models/block.py
rraallvv/python-client
65d0c3f835ed8ce3ba6bfa2565cac61f7da6b748
[ "Apache-2.0" ]
1
2020-08-03T01:05:44.000Z
2020-08-03T01:05:44.000Z
__all__ = ["Block", "BlockTemplateHeader", "BlockTemplateBody", "BlockTemplate"] from .transaction import Transaction class Block: """ Block returned by the server. :param number: Height of the block. :type number: int :param hash: Hex-encoded 32-byte hash of the block. :type hash: str :param pow: Hex-encoded 32-byte Proof-of-Work hash of the block. :type pow: str :param parentHash: Hex-encoded 32-byte hash of the predecessor block. :type parentHash: str :param nonce: The nonce of the block used to fulfill the Proof-of-Work. :type nonce: int :param bodyHash: Hex-encoded 32-byte hash of the block body Merkle root. :type bodyHash: str :param accountsHash: Hex-encoded 32-byte hash of the accounts tree root. :type accountsHash: str :param difficulty: Block difficulty, encoded as decimal number in string. :type difficulty: str :param timestamp: UNIX timestamp of the block. :type timestamp: int :param confirmations: Number of confirmations for this transaction (number of blocks on top of the block where this transaction was in). :type confirmations: int :param miner: Hex-encoded 20 byte address of the miner of the block. :type miner: str :param minerAddress: User friendly address (NQ-address) of the miner of the block. :type minerAddress: str :param extraData: Hex-encoded value of the extra data field, maximum of 255 bytes. :type extraData: str :param size: Block size in byte. :type size: int :param transactions: List of transactions. Either represented by the transaction hash or a Transaction object. :type transactions: list of (Transaction or str) """ def __init__( self, number, hash, pow, parentHash, nonce, bodyHash, accountsHash, difficulty, timestamp, confirmations, miner, minerAddress, extraData, size, transactions, ): self.number = number self.hash = hash self.pow = pow self.parentHash = parentHash self.nonce = nonce self.bodyHash = bodyHash self.accountsHash = accountsHash self.difficulty = difficulty self.timestamp = timestamp self.confirmations = confirmations self.miner = miner self.minerAddress = minerAddress self.extraData = extraData self.size = size for index, transaction in enumerate(transactions): tt = type(transaction) if tt is not str and tt is not Transaction: if tt is dict: transactions[index] = Transaction(**transaction) else: from ..nimiq_client import InternalErrorException raise InternalErrorException( "Couldn't parse Transaction {0}".format(transaction) ) self.transactions = transactions class BlockTemplateHeader: """ Block template header returned by the server. :param version: Version in block header. :type version: int :param prevHash: 32-byte hex-encoded hash of the previous block. :type prevHash: str :param interlinkHash: 32-byte hex-encoded hash of the interlink. :type interlinkHash: str :param accountsHash: 32-byte hex-encoded hash of the accounts tree. :type accountsHash: str :param nBits: Compact form of the hash target for this block. :type nBits: int :param height: Height of the block in the block chain (also known as block number). :type height: int """ def __init__(self, version, prevHash, interlinkHash, accountsHash, nBits, height): self.version = version self.prevHash = prevHash self.interlinkHash = interlinkHash self.accountsHash = accountsHash self.nBits = nBits self.height = height class BlockTemplateBody: """ Block template body returned by the server. :param hash: 32-byte hex-encoded hash of the block body. :type hash: str :param minerAddr: 20-byte hex-encoded miner address. :type minerAddr: str :param extraData: Hex-encoded value of the extra data field. :type extraData: str :param transactions: List of hex-encoded transactions for this block. :type transactions: str :param prunedAccounts: List of hex-encoded pruned accounts for this block. :type prunedAccounts: str :param merkleHashes: List of hex-encoded hashes that verify the path of the miner address in the merkle tree. This can be used to change the miner address easily. :type merkleHashes: str """ def __init__( self, hash, minerAddr, extraData, transactions, prunedAccounts, merkleHashes ): self.hash = hash self.minerAddr = minerAddr self.extraData = extraData self.transactions = transactions self.prunedAccounts = prunedAccounts self.merkleHashes = merkleHashes class BlockTemplate: """ Block template returned by the server. :param header: Block template header returned by the server. :type header: BlockTemplateHeader :param interlink: Hex-encoded interlink. :type interlink: str :param body: Block template body returned by the server. :type body: BlockTemplateBody :param target: Compact form of the hash target to submit a block to this client. :type target: int """ def __init__(self, header, interlink, body, target): self.header = header self.interlink = interlink self.body = body self.target = target
34.815951
166
0.66185
__all__ = ["Block", "BlockTemplateHeader", "BlockTemplateBody", "BlockTemplate"] from .transaction import Transaction class Block: def __init__( self, number, hash, pow, parentHash, nonce, bodyHash, accountsHash, difficulty, timestamp, confirmations, miner, minerAddress, extraData, size, transactions, ): self.number = number self.hash = hash self.pow = pow self.parentHash = parentHash self.nonce = nonce self.bodyHash = bodyHash self.accountsHash = accountsHash self.difficulty = difficulty self.timestamp = timestamp self.confirmations = confirmations self.miner = miner self.minerAddress = minerAddress self.extraData = extraData self.size = size for index, transaction in enumerate(transactions): tt = type(transaction) if tt is not str and tt is not Transaction: if tt is dict: transactions[index] = Transaction(**transaction) else: from ..nimiq_client import InternalErrorException raise InternalErrorException( "Couldn't parse Transaction {0}".format(transaction) ) self.transactions = transactions class BlockTemplateHeader: def __init__(self, version, prevHash, interlinkHash, accountsHash, nBits, height): self.version = version self.prevHash = prevHash self.interlinkHash = interlinkHash self.accountsHash = accountsHash self.nBits = nBits self.height = height class BlockTemplateBody: def __init__( self, hash, minerAddr, extraData, transactions, prunedAccounts, merkleHashes ): self.hash = hash self.minerAddr = minerAddr self.extraData = extraData self.transactions = transactions self.prunedAccounts = prunedAccounts self.merkleHashes = merkleHashes class BlockTemplate: def __init__(self, header, interlink, body, target): self.header = header self.interlink = interlink self.body = body self.target = target
true
true
f7168f6333b407972ae83a3eb73553f078b2cd44
7,304
py
Python
src/sage/combinat/kazhdan_lusztig.py
saraedum/sage-renamed
d2da67b14da2ad766a5906425d60d43a3b3e1270
[ "BSL-1.0" ]
null
null
null
src/sage/combinat/kazhdan_lusztig.py
saraedum/sage-renamed
d2da67b14da2ad766a5906425d60d43a3b3e1270
[ "BSL-1.0" ]
null
null
null
src/sage/combinat/kazhdan_lusztig.py
saraedum/sage-renamed
d2da67b14da2ad766a5906425d60d43a3b3e1270
[ "BSL-1.0" ]
null
null
null
r""" Kazhdan-Lusztig Polynomials AUTHORS: - Daniel Bump (2008): initial version - Alan J.X. Guo (2014-03-18): ``R_tilde()`` method. """ #***************************************************************************** # Copyright (C) 2008 Daniel Bump <bump at match.stanford.edu> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from __future__ import absolute_import, print_function, division from sage.rings.polynomial.polynomial_element import is_Polynomial from sage.misc.cachefunc import cached_method from sage.rings.polynomial.laurent_polynomial import LaurentPolynomial from sage.structure.sage_object import SageObject from sage.structure.unique_representation import UniqueRepresentation class KazhdanLusztigPolynomial(UniqueRepresentation, SageObject): """ A Kazhdan-Lusztig polynomial. INPUT: - ``W`` -- a Weyl Group - ``q`` -- an indeterminate OPTIONAL: - ``trace`` -- if ``True``, then this displays the trace: the intermediate results. This is instructive and fun. The parent of ``q`` may be a :class:`PolynomialRing` or a :class:`LaurentPolynomialRing`. REFERENCES: .. [KL79] \D. Kazhdan and G. Lusztig. *Representations of Coxeter groups and Hecke algebras*. Invent. Math. **53** (1979). no. 2, 165--184. :doi:`10.1007/BF01390031` :mathscinet:`MR0560412` .. [Dy93] \M. J. Dyer. *Hecke algebras and shellings of Bruhat intervals*. Compositio Mathematica, 1993, 89(1): 91-115. .. [BB05] \A. Bjorner, F. Brenti. *Combinatorics of Coxeter groups*. New York: Springer, 2005. EXAMPLES:: sage: W = WeylGroup("B3",prefix="s") sage: [s1,s2,s3] = W.simple_reflections() sage: R.<q> = LaurentPolynomialRing(QQ) sage: KL = KazhdanLusztigPolynomial(W,q) sage: KL.P(s2,s3*s2*s3*s1*s2) 1 + q A faster implementation (using the optional package Coxeter 3) is given by:: sage: W = CoxeterGroup(['B', 3], implementation='coxeter3') # optional - coxeter3 sage: W.kazhdan_lusztig_polynomial([2], [3,2,3,1,2]) # optional - coxeter3 q + 1 """ def __init__(self, W, q, trace=False): """ Initialize ``self``. EXAMPLES:: sage: W = WeylGroup("B3",prefix="s") sage: R.<q> = LaurentPolynomialRing(QQ) sage: KL = KazhdanLusztigPolynomial(W,q) sage: TestSuite(KL).run() """ self._coxeter_group = W self._q = q self._trace = trace self._one = W.one() self._base_ring = q.parent() if is_Polynomial(q): self._base_ring_type = "polynomial" elif isinstance(q, LaurentPolynomial): self._base_ring_type = "laurent" else: self._base_ring_type = "unknown" @cached_method def R(self, x, y): """ Return the Kazhdan-Lusztig `R` polynomial. INPUT: - ``x``, ``y`` -- elements of the underlying Coxeter group EXAMPLES:: sage: R.<q>=QQ[] sage: W = WeylGroup("A2", prefix="s") sage: [s1,s2]=W.simple_reflections() sage: KL = KazhdanLusztigPolynomial(W, q) sage: [KL.R(x,s2*s1) for x in [1,s1,s2,s1*s2]] [q^2 - 2*q + 1, q - 1, q - 1, 0] """ if x == 1: x = self._one if y == 1: y = self._one if x == y: return self._base_ring.one() if not x.bruhat_le(y): return self._base_ring.zero() if y.length() == 0: if x.length() == 0: return self._base_ring.one() else: return self._base_ring.zero() s = self._coxeter_group.simple_reflection(y.first_descent(side="left")) if (s*x).length() < x.length(): ret = self.R(s*x,s*y) if self._trace: print(" R(%s,%s)=%s" % (x, y, ret)) return ret else: ret = (self._q-1)*self.R(s*x,y)+self._q*self.R(s*x,s*y) if self._trace: print(" R(%s,%s)=%s" % (x, y, ret)) return ret @cached_method def R_tilde(self, x, y): r""" Return the Kazhdan-Lusztig `\tilde{R}` polynomial. Information about the `\tilde{R}` polynomials can be found in [Dy93]_ and [BB05]_. INPUT: - ``x``, ``y`` -- elements of the underlying Coxeter group EXAMPLES:: sage: R.<q> = QQ[] sage: W = WeylGroup("A2", prefix="s") sage: [s1,s2] = W.simple_reflections() sage: KL = KazhdanLusztigPolynomial(W, q) sage: [KL.R_tilde(x,s2*s1) for x in [1,s1,s2,s1*s2]] [q^2, q, q, 0] """ if x == 1: x = self._one if y == 1: y = self._one if not x.bruhat_le(y): return self._base_ring.zero() if x == y: return self._base_ring.one() s = self._coxeter_group.simple_reflection(y.first_descent(side="right")) if (x * s).length() < x.length(): ret = self.R_tilde(x * s, y * s) if self._trace: print(" R_tilde(%s,%s)=%s" % (x, y, ret)) return ret else: ret = self.R_tilde(x * s, y * s) + self._q * self.R_tilde(x, y * s) if self._trace: print(" R_tilde(%s,%s)=%s" % (x, y, ret)) return ret @cached_method def P(self, x, y): """ Return the Kazhdan-Lusztig `P` polynomial. If the rank is large, this runs slowly at first but speeds up as you do repeated calculations due to the caching. INPUT: - ``x``, ``y`` -- elements of the underlying Coxeter group .. SEEALSO:: :mod:`~sage.libs.coxeter3.coxeter_group.CoxeterGroup.kazhdan_lusztig_polynomial` for a faster implementation using Fokko Ducloux's Coxeter3 C++ library. EXAMPLES:: sage: R.<q> = QQ[] sage: W = WeylGroup("A3", prefix="s") sage: [s1,s2,s3] = W.simple_reflections() sage: KL = KazhdanLusztigPolynomial(W, q) sage: KL.P(s2,s2*s1*s3*s2) q + 1 """ if x == 1: x = self._one if y == 1: y = self._one if x == y: return self._base_ring.one() if not x.bruhat_le(y): return self._base_ring.zero() if y.length() == 0: if x.length() == 0: return self._base_ring.one() else: return self._base_ring.zero() p = sum(-self.R(x, t) * self.P(t, y) for t in self._coxeter_group.bruhat_interval(x, y) if t != x) tr = (y.length() - x.length() + 1) // 2 ret = p.truncate(tr) if self._trace: print(" P({},{})={}".format(x, y, ret)) return ret
32.035088
92
0.529299
from __future__ import absolute_import, print_function, division from sage.rings.polynomial.polynomial_element import is_Polynomial from sage.misc.cachefunc import cached_method from sage.rings.polynomial.laurent_polynomial import LaurentPolynomial from sage.structure.sage_object import SageObject from sage.structure.unique_representation import UniqueRepresentation class KazhdanLusztigPolynomial(UniqueRepresentation, SageObject): def __init__(self, W, q, trace=False): self._coxeter_group = W self._q = q self._trace = trace self._one = W.one() self._base_ring = q.parent() if is_Polynomial(q): self._base_ring_type = "polynomial" elif isinstance(q, LaurentPolynomial): self._base_ring_type = "laurent" else: self._base_ring_type = "unknown" @cached_method def R(self, x, y): if x == 1: x = self._one if y == 1: y = self._one if x == y: return self._base_ring.one() if not x.bruhat_le(y): return self._base_ring.zero() if y.length() == 0: if x.length() == 0: return self._base_ring.one() else: return self._base_ring.zero() s = self._coxeter_group.simple_reflection(y.first_descent(side="left")) if (s*x).length() < x.length(): ret = self.R(s*x,s*y) if self._trace: print(" R(%s,%s)=%s" % (x, y, ret)) return ret else: ret = (self._q-1)*self.R(s*x,y)+self._q*self.R(s*x,s*y) if self._trace: print(" R(%s,%s)=%s" % (x, y, ret)) return ret @cached_method def R_tilde(self, x, y): if x == 1: x = self._one if y == 1: y = self._one if not x.bruhat_le(y): return self._base_ring.zero() if x == y: return self._base_ring.one() s = self._coxeter_group.simple_reflection(y.first_descent(side="right")) if (x * s).length() < x.length(): ret = self.R_tilde(x * s, y * s) if self._trace: print(" R_tilde(%s,%s)=%s" % (x, y, ret)) return ret else: ret = self.R_tilde(x * s, y * s) + self._q * self.R_tilde(x, y * s) if self._trace: print(" R_tilde(%s,%s)=%s" % (x, y, ret)) return ret @cached_method def P(self, x, y): if x == 1: x = self._one if y == 1: y = self._one if x == y: return self._base_ring.one() if not x.bruhat_le(y): return self._base_ring.zero() if y.length() == 0: if x.length() == 0: return self._base_ring.one() else: return self._base_ring.zero() p = sum(-self.R(x, t) * self.P(t, y) for t in self._coxeter_group.bruhat_interval(x, y) if t != x) tr = (y.length() - x.length() + 1) // 2 ret = p.truncate(tr) if self._trace: print(" P({},{})={}".format(x, y, ret)) return ret
true
true
f716900640c20a86067bea4f88ec8a40a962d91a
1,771
py
Python
server/apps/widgets/serializers/widget.py
Sergey-x/SibdevPractice
12e3f7e704af93911a0c4a66aad60733d2121e15
[ "MIT" ]
null
null
null
server/apps/widgets/serializers/widget.py
Sergey-x/SibdevPractice
12e3f7e704af93911a0c4a66aad60733d2121e15
[ "MIT" ]
null
null
null
server/apps/widgets/serializers/widget.py
Sergey-x/SibdevPractice
12e3f7e704af93911a0c4a66aad60733d2121e15
[ "MIT" ]
null
null
null
from datetime import timedelta from rest_framework import serializers from ..models.widget import Widget class BaseWidgetSerializer(serializers.ModelSerializer): """ This is the base serializer class for Widget model. Other widget serializers must be inherited from it. """ class Meta: model = Widget fields = ( 'id', 'category', 'limit', 'duration', 'criteria', 'color', 'creation_date', ) class CreateWidgetSerializer(BaseWidgetSerializer): color = serializers.CharField(max_length=10) def validate_duration(self, value: timedelta): """ Check that duration is acceptable quantity of days. """ if value.days not in Widget.VALID_DURATION: raise serializers.ValidationError( f"You can chose only this day-periods {Widget.VALID_DURATION}." ) return timedelta(days=value.days) def validate_color(self, value): """ Check that color specified in hex correctly. """ if value.startswith('0x'): return value[2:] return value def create(self, validated_data): validated_data['owner'] = self.context['request'].user return Widget.objects.create(**validated_data) class DestroyWidgetSerializer(BaseWidgetSerializer): pass class ListWidgetSerializer(BaseWidgetSerializer): class Meta(BaseWidgetSerializer.Meta): fields = ( 'id', 'category', 'limit', 'duration', 'criteria', 'color', 'creation_date', 'ending_date', 'sum', 'owner', )
24.943662
79
0.579898
from datetime import timedelta from rest_framework import serializers from ..models.widget import Widget class BaseWidgetSerializer(serializers.ModelSerializer): class Meta: model = Widget fields = ( 'id', 'category', 'limit', 'duration', 'criteria', 'color', 'creation_date', ) class CreateWidgetSerializer(BaseWidgetSerializer): color = serializers.CharField(max_length=10) def validate_duration(self, value: timedelta): if value.days not in Widget.VALID_DURATION: raise serializers.ValidationError( f"You can chose only this day-periods {Widget.VALID_DURATION}." ) return timedelta(days=value.days) def validate_color(self, value): if value.startswith('0x'): return value[2:] return value def create(self, validated_data): validated_data['owner'] = self.context['request'].user return Widget.objects.create(**validated_data) class DestroyWidgetSerializer(BaseWidgetSerializer): pass class ListWidgetSerializer(BaseWidgetSerializer): class Meta(BaseWidgetSerializer.Meta): fields = ( 'id', 'category', 'limit', 'duration', 'criteria', 'color', 'creation_date', 'ending_date', 'sum', 'owner', )
true
true
f716900a4d34d8a8bb3af91bb18c52ab94dfe78e
2,563
py
Python
src/server.py
alamminsalo/lua-webshop
2f0f1123a9d693103c4dbaef02836777e779844c
[ "MIT" ]
1
2016-09-12T16:16:33.000Z
2016-09-12T16:16:33.000Z
src/server.py
alamminsalo/py-webshop
2f0f1123a9d693103c4dbaef02836777e779844c
[ "MIT" ]
null
null
null
src/server.py
alamminsalo/py-webshop
2f0f1123a9d693103c4dbaef02836777e779844c
[ "MIT" ]
null
null
null
# Restfull api using falcon framework from wsgiref import simple_server import falcon import json #Resource endpoints import from cartsResource import * from productsResource import * # Check that client has application/json in Accept header # and Content-Type, if request has body class RequireJSON(object): def process_request(self, req, resp): if not req.client_accepts_json: raise falcon.HTTPNotAcceptable( 'This API only supports responses encoded as JSON.', href='http://docs.examples.com/api/json') if req.method in ('POST', 'PUT'): if 'application/json' not in req.content_type: raise falcon.HTTPUnsupportedMediaType( 'This API only supports requests encoded as JSON.', href='http://docs.examples.com/api/json') #JSON builder func for both incoming and outgoing messages class JSONBuilder(object): def process_request(self, req, resp): if req.content_length in (None, 0): # Nothing to do return body = req.stream.read() if not body: raise falcon.HTTPBadRequest('Empty request body', 'A valid JSON document is required.') try: req.context['doc'] = json.loads(body.decode('utf-8')) except (ValueError, UnicodeDecodeError): raise falcon.HTTPError(falcon.HTTP_753, 'Malformed JSON', 'Could not decode the request body. The ' 'JSON was incorrect or not encoded as ' 'UTF-8.') def process_response(self, req, resp, resource): if 'result' not in req.context: return resp.body = json.dumps(req.context['result']) api = falcon.API(middleware=[ RequireJSON(), JSONBuilder() ]) #Add api endpoints products = ProductsResource() api.add_route('/api/products', products) product = ProductResource() api.add_route('/api/products/{productId}', product) shopcart = ShopCartResource() api.add_route('/api/shopcarts/{userId}', shopcart) shopcartProducts = ShopCartProductsResource() api.add_route('/api/shopcarts/{userId}/products', shopcartProducts) #Start the server if __name__ == '__main__': print("Staring server in 127.0.0.1:8000") httpd = simple_server.make_server('127.0.0.1', 8000, api) httpd.serve_forever()
29.802326
81
0.60359
from wsgiref import simple_server import falcon import json from cartsResource import * from productsResource import * class RequireJSON(object): def process_request(self, req, resp): if not req.client_accepts_json: raise falcon.HTTPNotAcceptable( 'This API only supports responses encoded as JSON.', href='http://docs.examples.com/api/json') if req.method in ('POST', 'PUT'): if 'application/json' not in req.content_type: raise falcon.HTTPUnsupportedMediaType( 'This API only supports requests encoded as JSON.', href='http://docs.examples.com/api/json') class JSONBuilder(object): def process_request(self, req, resp): if req.content_length in (None, 0): return body = req.stream.read() if not body: raise falcon.HTTPBadRequest('Empty request body', 'A valid JSON document is required.') try: req.context['doc'] = json.loads(body.decode('utf-8')) except (ValueError, UnicodeDecodeError): raise falcon.HTTPError(falcon.HTTP_753, 'Malformed JSON', 'Could not decode the request body. The ' 'JSON was incorrect or not encoded as ' 'UTF-8.') def process_response(self, req, resp, resource): if 'result' not in req.context: return resp.body = json.dumps(req.context['result']) api = falcon.API(middleware=[ RequireJSON(), JSONBuilder() ]) products = ProductsResource() api.add_route('/api/products', products) product = ProductResource() api.add_route('/api/products/{productId}', product) shopcart = ShopCartResource() api.add_route('/api/shopcarts/{userId}', shopcart) shopcartProducts = ShopCartProductsResource() api.add_route('/api/shopcarts/{userId}/products', shopcartProducts) if __name__ == '__main__': print("Staring server in 127.0.0.1:8000") httpd = simple_server.make_server('127.0.0.1', 8000, api) httpd.serve_forever()
true
true
f7169146ec3baeb91915b19f26b91545909663f8
149
py
Python
foundation/migrate.py
shreyashah115/foundation
42f19d23cfda77bae533f4884aecc15b3cd07f14
[ "MIT" ]
null
null
null
foundation/migrate.py
shreyashah115/foundation
42f19d23cfda77bae533f4884aecc15b3cd07f14
[ "MIT" ]
null
null
null
foundation/migrate.py
shreyashah115/foundation
42f19d23cfda77bae533f4884aecc15b3cd07f14
[ "MIT" ]
null
null
null
import frappe from frappe.database import Database from markdown2 import markdown from frappe.utils import validate_email_add def migrate(): pass
16.555556
43
0.832215
import frappe from frappe.database import Database from markdown2 import markdown from frappe.utils import validate_email_add def migrate(): pass
true
true
f716914b86089ef9a2f697d9a1dfeb32bd90f95f
599
py
Python
HelloWorld/Models/admin.py
xautshuanglong/PythonWebApp
68ae417121740e4115f0e56c12a2a4831df30fc1
[ "MIT" ]
null
null
null
HelloWorld/Models/admin.py
xautshuanglong/PythonWebApp
68ae417121740e4115f0e56c12a2a4831df30fc1
[ "MIT" ]
null
null
null
HelloWorld/Models/admin.py
xautshuanglong/PythonWebApp
68ae417121740e4115f0e56c12a2a4831df30fc1
[ "MIT" ]
null
null
null
from django.contrib import admin from Models.models import UserInfo, Question, Choice admin.site.register(UserInfo) # admin.site.register(Question) # admin.site.register(Choice) class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes':['collapse']}), ] inlines = [ChoiceInline] list_display = ('question_text', 'pub_date') admin.site.register(Question, QuestionAdmin)
23.038462
80
0.661102
from django.contrib import admin from Models.models import UserInfo, Question, Choice admin.site.register(UserInfo) class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes':['collapse']}), ] inlines = [ChoiceInline] list_display = ('question_text', 'pub_date') admin.site.register(Question, QuestionAdmin)
true
true
f71693818cb726573e4d1f282b8d61fe8a87df6b
678
py
Python
resource-timing/resources/fake_responses.py
shs96c/web-platform-tests
61acad6dd9bb99d32340eb41f5146de64f542359
[ "BSD-3-Clause" ]
1
2022-03-19T09:43:35.000Z
2022-03-19T09:43:35.000Z
resource-timing/resources/fake_responses.py
shs96c/web-platform-tests
61acad6dd9bb99d32340eb41f5146de64f542359
[ "BSD-3-Clause" ]
1
2021-12-13T19:49:45.000Z
2021-12-13T19:49:45.000Z
resource-timing/resources/fake_responses.py
shs96c/web-platform-tests
61acad6dd9bb99d32340eb41f5146de64f542359
[ "BSD-3-Clause" ]
1
2021-04-06T20:06:58.000Z
2021-04-06T20:06:58.000Z
# /xhr/resources/conditional.py -- to fake a 304 response def main(request, response): tag = request.GET.first("tag", None) match = request.headers.get("If-None-Match", None) date = request.GET.first("date", "") modified = request.headers.get("If-Modified-Since", None) if tag: response.headers.set("ETag", '"%s"' % tag) elif date: response.headers.set("Last-Modified", date) if ((match is not None and match == tag) or (modified is not None and modified == date)): response.status = (304, "SUPERCOOL") return "" else: response.headers.set("Content-Type", "text/plain") return "MAYBE NOT"
35.684211
61
0.613569
def main(request, response): tag = request.GET.first("tag", None) match = request.headers.get("If-None-Match", None) date = request.GET.first("date", "") modified = request.headers.get("If-Modified-Since", None) if tag: response.headers.set("ETag", '"%s"' % tag) elif date: response.headers.set("Last-Modified", date) if ((match is not None and match == tag) or (modified is not None and modified == date)): response.status = (304, "SUPERCOOL") return "" else: response.headers.set("Content-Type", "text/plain") return "MAYBE NOT"
true
true
f71695c7f499b72a9e1e239c8622fe0294a9c60f
3,752
py
Python
personal/Ervin/run_knn_collaborative_item.py
edervishaj/spotify-recsys-challenge
4077201ac7e4ed9da433bd10a92c183614182437
[ "Apache-2.0" ]
3
2018-10-12T20:19:57.000Z
2019-12-11T01:11:38.000Z
personal/Ervin/run_knn_collaborative_item.py
kiminh/spotify-recsys-challenge
5e7844a77ce3c26658400f161d2d74d682f30e69
[ "Apache-2.0" ]
null
null
null
personal/Ervin/run_knn_collaborative_item.py
kiminh/spotify-recsys-challenge
5e7844a77ce3c26658400f161d2d74d682f30e69
[ "Apache-2.0" ]
4
2018-10-27T20:30:18.000Z
2020-10-14T07:43:27.000Z
from utils.datareader import Datareader from utils.evaluator import Evaluator from utils.submitter import Submitter from utils.post_processing import eurm_to_recommendation_list_submission from utils.post_processing import eurm_to_recommendation_list from utils.pre_processing import norm_l1_row, norm_max_row, norm_max_col from recommenders.knn_collaborative_item import Knn_collaborative_item import recommenders.similarity.similarity as sm import scipy.sparse as sps import sys import numpy as np from personal.Ervin.other_similarity import position_similarity ''' This file contains just an example on how to run the algorithm. The parameter used are just the result of a first research of the optimum value. To run this file just set the parameter at the start of the main function or set from console as argv parameter. As argv you can even set mode of execution (online, offline) and the name of the result file ''' if __name__ == '__main__': ### Select execution mode: 'offline', 'online' ### mode = "offline" name = "CFitem" knn = 200 topk = 750 if len(sys.argv) > 1: mode = sys.argv[1] name = sys.argv[2] knn = int(sys.argv[3]) topk = int(sys.argv[4]) complete_name = mode+"_"+name+"_knn="+str(knn)+"_topk="+str(topk) if mode == "offline": """Test Set""" #Data initialization dr = Datareader(verbose=True, mode=mode, only_load=True) #Evaluetor initialization ev = Evaluator(dr) #Recommender algorithm initialization rec = Knn_collaborative_item() #Getting for the recommender algorithm urm = dr.get_urm() urm.data = np.ones(len(urm.data)) position_urm = dr.get_position_matrix(position_type='last') pos_urm = position_urm.T.tocoo().tocsr() pid = dr.get_test_pids() #Fitting data rec.fit(urm, pid) #Computing similarity/model rec.compute_model(top_k= knn, sm_type=sm.TVERSKY, shrink=200, alpha=0.1, beta=1, binary=True, verbose=True) rec.model = rec.model.tocsr() rec.model.eliminate_zeros() # rec.model = norm_max_row(rec.model) print('Initial model has {:2} data'.format(len(rec.model.data))) print('[ Updating the model ]') rec.model = position_similarity(rec.model, pos_urm, knn=knn, verbose=True) rec.model.eliminate_zeros() print('New model has {:2} data'.format(len(rec.model.data))) #Computing ratings rec.compute_rating(top_k=topk,verbose=True, small=True, remove_seed=False) #evaluation and saving sps.save_npz(complete_name+".npz", rec.eurm) ev.evaluate(recommendation_list=eurm_to_recommendation_list(rec.eurm, datareader=dr, remove_seed=True), name=name, old_mode=False) if mode == "online": """Submission""" #Data initialization dr = Datareader(verbose=True, mode=mode, only_load=False) #Recommender algorithm initialization rec = Knn_collaborative_item() #Submitter initialization sb = Submitter(dr) #Getting for the recommender algorithm urm = dr.get_urm() pid = dr.get_test_pids() #Fitting data rec.fit(urm, pid) #Computing similarity/model rec.compute_model(top_k=knn, sm_type=sm.TVERSKY,shrink=200, alpha=0.1, beta=1, binary=True, verbose=True) #Computing ratings rec.compute_rating(top_k=topk, verbose=True, small=True) #submission sps.save_npz(complete_name+".npz", rec.eurm) sb.submit(recommendation_list=eurm_to_recommendation_list_submission(rec.eurm), name=name, track="main", verify=True, gzipped=False)
32.912281
140
0.676972
from utils.datareader import Datareader from utils.evaluator import Evaluator from utils.submitter import Submitter from utils.post_processing import eurm_to_recommendation_list_submission from utils.post_processing import eurm_to_recommendation_list from utils.pre_processing import norm_l1_row, norm_max_row, norm_max_col from recommenders.knn_collaborative_item import Knn_collaborative_item import recommenders.similarity.similarity as sm import scipy.sparse as sps import sys import numpy as np from personal.Ervin.other_similarity import position_similarity if __name__ == '__main__': mode = sys.argv[1] name = sys.argv[2] knn = int(sys.argv[3]) topk = int(sys.argv[4]) complete_name = mode+"_"+name+"_knn="+str(knn)+"_topk="+str(topk) if mode == "offline": dr = Datareader(verbose=True, mode=mode, only_load=True) ev = Evaluator(dr) rec = Knn_collaborative_item() urm = dr.get_urm() urm.data = np.ones(len(urm.data)) position_urm = dr.get_position_matrix(position_type='last') pos_urm = position_urm.T.tocoo().tocsr() pid = dr.get_test_pids() rec.fit(urm, pid) rec.compute_model(top_k= knn, sm_type=sm.TVERSKY, shrink=200, alpha=0.1, beta=1, binary=True, verbose=True) rec.model = rec.model.tocsr() rec.model.eliminate_zeros() print('Initial model has {:2} data'.format(len(rec.model.data))) print('[ Updating the model ]') rec.model = position_similarity(rec.model, pos_urm, knn=knn, verbose=True) rec.model.eliminate_zeros() print('New model has {:2} data'.format(len(rec.model.data))) rec.compute_rating(top_k=topk,verbose=True, small=True, remove_seed=False) sps.save_npz(complete_name+".npz", rec.eurm) ev.evaluate(recommendation_list=eurm_to_recommendation_list(rec.eurm, datareader=dr, remove_seed=True), name=name, old_mode=False) if mode == "online": dr = Datareader(verbose=True, mode=mode, only_load=False) rec = Knn_collaborative_item() sb = Submitter(dr) urm = dr.get_urm() pid = dr.get_test_pids() rec.fit(urm, pid) rec.compute_model(top_k=knn, sm_type=sm.TVERSKY,shrink=200, alpha=0.1, beta=1, binary=True, verbose=True) rec.compute_rating(top_k=topk, verbose=True, small=True) sps.save_npz(complete_name+".npz", rec.eurm) sb.submit(recommendation_list=eurm_to_recommendation_list_submission(rec.eurm), name=name, track="main", verify=True, gzipped=False)
true
true
f71695f6ec0e1e0a59e525bb30d5fb132322b04b
564
py
Python
wagtail/core/migrations/0036_populate_page_last_published_at.py
brownaa/wagtail
c97bc56c6822eb1b6589d5c33e07f71acfc48845
[ "BSD-3-Clause" ]
8,851
2016-12-09T19:01:45.000Z
2022-03-31T04:45:06.000Z
wagtail/core/migrations/0036_populate_page_last_published_at.py
brownaa/wagtail
c97bc56c6822eb1b6589d5c33e07f71acfc48845
[ "BSD-3-Clause" ]
5,197
2016-12-09T19:24:37.000Z
2022-03-31T22:17:55.000Z
wagtail/core/migrations/0036_populate_page_last_published_at.py
brownaa/wagtail
c97bc56c6822eb1b6589d5c33e07f71acfc48845
[ "BSD-3-Clause" ]
2,548
2016-12-09T18:16:55.000Z
2022-03-31T21:34:38.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-01 11:03 from django.db import migrations from django.db.models import F def forwards_func(apps, schema_editor): Page = apps.get_model("wagtailcore", "Page") Page.objects.filter(has_unpublished_changes=False).update(last_published_at=F('latest_revision_created_at')) class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0035_page_last_published_at'), ] operations = [ migrations.RunPython(forwards_func, migrations.RunPython.noop), ]
26.857143
112
0.719858
from django.db import migrations from django.db.models import F def forwards_func(apps, schema_editor): Page = apps.get_model("wagtailcore", "Page") Page.objects.filter(has_unpublished_changes=False).update(last_published_at=F('latest_revision_created_at')) class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0035_page_last_published_at'), ] operations = [ migrations.RunPython(forwards_func, migrations.RunPython.noop), ]
true
true
f71696347edb214d95d4dd5dbb9b50d0df5285c4
5,287
py
Python
integration-testing/test/test_multiple_deploys.py
ArturGajowy/rchain
7785a9195a4863a89f8aa22743e245c3e5f7940c
[ "Apache-2.0" ]
null
null
null
integration-testing/test/test_multiple_deploys.py
ArturGajowy/rchain
7785a9195a4863a89f8aa22743e245c3e5f7940c
[ "Apache-2.0" ]
null
null
null
integration-testing/test/test_multiple_deploys.py
ArturGajowy/rchain
7785a9195a4863a89f8aa22743e245c3e5f7940c
[ "Apache-2.0" ]
1
2018-09-12T10:26:23.000Z
2018-09-12T10:26:23.000Z
import logging import contextlib import threading from typing import ( TYPE_CHECKING, Generator, ) import pytest import conftest from rnode_testing.common import TestingContext from rnode_testing.rnode import ( docker_network_with_started_bootstrap, started_peer, ) from rnode_testing.wait import ( wait_for_blocks_count_at_least, wait_for_approved_block_received_handler_state, ) if TYPE_CHECKING: from _pytest.fixtures import SubRequest from docker.client import DockerClient from rnode_testing.rnode import Node class DeployThread(threading.Thread): def __init__(self, name, node, contract, count): threading.Thread.__init__(self) self.name = name self.node = node self.contract = contract self.count = count logging.info(f"Setup thread - {self.contract} to node {self.name}, amount {count}.") def run(self): for i in range(self.count): logging.info(f"[{self.name}]-[{i}] Will deploy {self.contract}.") d = self.node.deploy(self.contract) logging.info(f"[{self.name}]-[{i}] Deploy {self.contract}: {d}") p = self.node.propose() logging.info(f"[{self.name}]-[{i}] Proposed {self.contract}: {p}") s = self.node.show_blocks_with_depth(1) logging.info(f"[{self.name}]-[{i}] Show blocks: {s}") BOOTSTRAP_NODE_KEYS = conftest.KeyPair(private_key='80366db5fbb8dad7946f27037422715e4176dda41d582224db87b6c3b783d709', public_key='1cd8bf79a2c1bd0afa160f6cdfeb8597257e48135c9bf5e4823f2875a1492c97') BONDED_VALIDATOR_KEY_1 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821') BONDED_VALIDATOR_KEY_2 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821') BONDED_VALIDATOR_KEY_3 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821') @contextlib.contextmanager def started_bonded_validator(context: TestingContext, bootstrap_node: "Node", no, key_pair) -> Generator["Node", None, None]: with started_peer( context=context, network=bootstrap_node.network, name='bonded-validator-' + str(no), bootstrap=bootstrap_node, key_pair=key_pair, ) as bonded_validator: wait_for_approved_block_received_handler_state(bonded_validator, context.node_startup_timeout) yield bonded_validator @pytest.mark.xfail def test_multiple_deploys_at_once(command_line_options_fixture, docker_client_fixture) -> None: contract_path = '/opt/docker/examples/hello_world_again.rho' peers_keypairs = [BONDED_VALIDATOR_KEY_1, BONDED_VALIDATOR_KEY_2, BONDED_VALIDATOR_KEY_3] with conftest.testing_context(command_line_options_fixture, docker_client_fixture, bootstrap_keypair=BOOTSTRAP_NODE_KEYS, peers_keypairs=peers_keypairs) as context: with docker_network_with_started_bootstrap(context=context) as bootstrap_node: with started_bonded_validator(context, bootstrap_node, 1, BONDED_VALIDATOR_KEY_1) as no1: with started_bonded_validator(context, bootstrap_node, 2, BONDED_VALIDATOR_KEY_2) as no2: with started_bonded_validator(context, bootstrap_node, 3, BONDED_VALIDATOR_KEY_3) as no3: deploy1 = DeployThread("node1", no1, contract_path, 1) deploy1.start() expected_blocks_count = 1 max_retrieved_blocks = 1 wait_for_blocks_count_at_least( no1, expected_blocks_count, max_retrieved_blocks, expected_blocks_count * 10, ) deploy2 = DeployThread("node2", no2, contract_path, 3) deploy2.start() deploy3 = DeployThread("node3", no3, contract_path, 3) deploy3.start() expected_blocks_count = 7 max_retrieved_blocks = 7 wait_for_blocks_count_at_least( no1, expected_blocks_count, max_retrieved_blocks, 480 ) wait_for_blocks_count_at_least( no2, expected_blocks_count, max_retrieved_blocks, expected_blocks_count * 10, ) wait_for_blocks_count_at_least( no3, expected_blocks_count, max_retrieved_blocks, expected_blocks_count * 10, ) deploy1.join() deploy2.join() deploy3.join()
44.058333
200
0.635521
import logging import contextlib import threading from typing import ( TYPE_CHECKING, Generator, ) import pytest import conftest from rnode_testing.common import TestingContext from rnode_testing.rnode import ( docker_network_with_started_bootstrap, started_peer, ) from rnode_testing.wait import ( wait_for_blocks_count_at_least, wait_for_approved_block_received_handler_state, ) if TYPE_CHECKING: from _pytest.fixtures import SubRequest from docker.client import DockerClient from rnode_testing.rnode import Node class DeployThread(threading.Thread): def __init__(self, name, node, contract, count): threading.Thread.__init__(self) self.name = name self.node = node self.contract = contract self.count = count logging.info(f"Setup thread - {self.contract} to node {self.name}, amount {count}.") def run(self): for i in range(self.count): logging.info(f"[{self.name}]-[{i}] Will deploy {self.contract}.") d = self.node.deploy(self.contract) logging.info(f"[{self.name}]-[{i}] Deploy {self.contract}: {d}") p = self.node.propose() logging.info(f"[{self.name}]-[{i}] Proposed {self.contract}: {p}") s = self.node.show_blocks_with_depth(1) logging.info(f"[{self.name}]-[{i}] Show blocks: {s}") BOOTSTRAP_NODE_KEYS = conftest.KeyPair(private_key='80366db5fbb8dad7946f27037422715e4176dda41d582224db87b6c3b783d709', public_key='1cd8bf79a2c1bd0afa160f6cdfeb8597257e48135c9bf5e4823f2875a1492c97') BONDED_VALIDATOR_KEY_1 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821') BONDED_VALIDATOR_KEY_2 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821') BONDED_VALIDATOR_KEY_3 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821') @contextlib.contextmanager def started_bonded_validator(context: TestingContext, bootstrap_node: "Node", no, key_pair) -> Generator["Node", None, None]: with started_peer( context=context, network=bootstrap_node.network, name='bonded-validator-' + str(no), bootstrap=bootstrap_node, key_pair=key_pair, ) as bonded_validator: wait_for_approved_block_received_handler_state(bonded_validator, context.node_startup_timeout) yield bonded_validator @pytest.mark.xfail def test_multiple_deploys_at_once(command_line_options_fixture, docker_client_fixture) -> None: contract_path = '/opt/docker/examples/hello_world_again.rho' peers_keypairs = [BONDED_VALIDATOR_KEY_1, BONDED_VALIDATOR_KEY_2, BONDED_VALIDATOR_KEY_3] with conftest.testing_context(command_line_options_fixture, docker_client_fixture, bootstrap_keypair=BOOTSTRAP_NODE_KEYS, peers_keypairs=peers_keypairs) as context: with docker_network_with_started_bootstrap(context=context) as bootstrap_node: with started_bonded_validator(context, bootstrap_node, 1, BONDED_VALIDATOR_KEY_1) as no1: with started_bonded_validator(context, bootstrap_node, 2, BONDED_VALIDATOR_KEY_2) as no2: with started_bonded_validator(context, bootstrap_node, 3, BONDED_VALIDATOR_KEY_3) as no3: deploy1 = DeployThread("node1", no1, contract_path, 1) deploy1.start() expected_blocks_count = 1 max_retrieved_blocks = 1 wait_for_blocks_count_at_least( no1, expected_blocks_count, max_retrieved_blocks, expected_blocks_count * 10, ) deploy2 = DeployThread("node2", no2, contract_path, 3) deploy2.start() deploy3 = DeployThread("node3", no3, contract_path, 3) deploy3.start() expected_blocks_count = 7 max_retrieved_blocks = 7 wait_for_blocks_count_at_least( no1, expected_blocks_count, max_retrieved_blocks, 480 ) wait_for_blocks_count_at_least( no2, expected_blocks_count, max_retrieved_blocks, expected_blocks_count * 10, ) wait_for_blocks_count_at_least( no3, expected_blocks_count, max_retrieved_blocks, expected_blocks_count * 10, ) deploy1.join() deploy2.join() deploy3.join()
true
true
f716972ac65d7ac3dcdcd16d28ba7fac85854f2f
4,791
py
Python
estonian_learner/verb.py
natter1/estonian_learner
da7837f0d64f4c1f6a212a9c473252c4b834699a
[ "MIT" ]
null
null
null
estonian_learner/verb.py
natter1/estonian_learner
da7837f0d64f4c1f6a212a9c473252c4b834699a
[ "MIT" ]
null
null
null
estonian_learner/verb.py
natter1/estonian_learner
da7837f0d64f4c1f6a212a9c473252c4b834699a
[ "MIT" ]
null
null
null
""" @author: Nathanael Jöhrmann """ import json import textwrap class Conjugations: def __init__(self): self.person = {} self.negative = ["", ""] self.passive = ["", ""] self.passive_negative = ["", ""] @property def summary(self) -> str: result = "" sep = " " for i in range(1, 7): try: result += sep.join([f"{i}P", self.person[str(i)][0], self.person[i][1]]) + "\n" except KeyError: # needed, if data where put to json and back (int becomes str) result += sep.join([f"{i}P", self.person[str(i)][0], self.person[str(i)][1]]) + "\n" result += sep.join(["negative", self.negative[0], self.negative[1]]) + "\n" result += sep.join(["passive", self.passive[0], self.passive[1]]) + "\n" result += sep.join(["passive negative", self.passive_negative[0], self.passive_negative[1]]) + "\n" return result # def add_person(self, original, translation, index): # self.person[index] = original # self.person_translation[index] = translation def to_json(self) -> dict: """ Returns a jsonified dict containing the data of self. :return: dict """ my_dict = {"person": self.person, "negative": self.negative, "passive": self.passive, "passive_negative": self.passive_negative } result = json.loads(json.dumps(my_dict, indent=2, ensure_ascii=False)) # print((my_dict)) # print(result) # return my_dict # todo: test if this works with SQLAlchemy return result def from_json(self, _json: dict) -> None: self.person = _json["person"] self.negative = _json["negative"] self.passive = _json["passive"] self.passive_negative = _json["passive_negative"] class Verb: def __init__(self): self.infinitive_ma = ("", "") self.infinitive_da = ("", "") self.past_active_participle = ("", "") self.past_passive_participle = ("", "") self.present = Conjugations() self.conditional_mood = Conjugations() self.imperative_mood = Conjugations() self.imperative_negative_mood = Conjugations() self.perfect = Conjugations() self.past = Conjugations() self.plusperfect = Conjugations() self.conditional_perfect_mood = Conjugations() self.quotative = Conjugations() self.quotative_perfect = Conjugations() self.jussive = Conjugations() self.jussive_perfect = Conjugations() self.other = {} self.usage_info = "" self.audio = None @property def summary(self) -> str: result = textwrap.dedent(f"""\ --------------------------------------------------------- Usage info: {self.usage_info}\n Infinitive (-ma -da translation): {self.infinitive_ma[0]} {self.infinitive_da[0]} {self.infinitive_ma[1]}\n Past active participle: {self.past_active_participle[0]} {self.past_active_participle[1]}\n Past passive participle: {self.past_passive_participle[0]} {self.past_passive_participle[1]} """) result += "\nPast passive participle\n" result += self.past_passive_participle[0] + " " + self.past_passive_participle[1] + "\n" result += "\nPresent tense\n" result += self.present.summary result += "\nConditional mood\n" result += self.conditional_mood.summary result += "\nImperative mood\n" result += self.imperative_mood.summary result += "\nImperative negative mood\n" result += self.imperative_negative_mood.summary result += "\nPerfect tense\n" result += self.perfect.summary result += "\nPast tense\n" result += self.past.summary result += "\nPlusperfect tense\n" result += self.plusperfect.summary result += "\nConditional perfect mood\n" result += self.conditional_perfect_mood.summary result += "\nQuotative tense\n" result += self.quotative.summary result += "\nQuotative perfect tense\n" result += self.quotative_perfect.summary result += "\nJussive tense\n" result += self.jussive.summary result += "\nJussive perfect tense\n" result += self.jussive_perfect.summary result += "\nOther\n" for key in self.other: result += key + " " + self.other[key][0] + " " + self.other[key][1] + "\n" result += "---------------------------------------------------------\n" return result
33.041379
107
0.557921
import json import textwrap class Conjugations: def __init__(self): self.person = {} self.negative = ["", ""] self.passive = ["", ""] self.passive_negative = ["", ""] @property def summary(self) -> str: result = "" sep = " " for i in range(1, 7): try: result += sep.join([f"{i}P", self.person[str(i)][0], self.person[i][1]]) + "\n" except KeyError: result += sep.join([f"{i}P", self.person[str(i)][0], self.person[str(i)][1]]) + "\n" result += sep.join(["negative", self.negative[0], self.negative[1]]) + "\n" result += sep.join(["passive", self.passive[0], self.passive[1]]) + "\n" result += sep.join(["passive negative", self.passive_negative[0], self.passive_negative[1]]) + "\n" return result def to_json(self) -> dict: my_dict = {"person": self.person, "negative": self.negative, "passive": self.passive, "passive_negative": self.passive_negative } result = json.loads(json.dumps(my_dict, indent=2, ensure_ascii=False)) self, _json: dict) -> None: self.person = _json["person"] self.negative = _json["negative"] self.passive = _json["passive"] self.passive_negative = _json["passive_negative"] class Verb: def __init__(self): self.infinitive_ma = ("", "") self.infinitive_da = ("", "") self.past_active_participle = ("", "") self.past_passive_participle = ("", "") self.present = Conjugations() self.conditional_mood = Conjugations() self.imperative_mood = Conjugations() self.imperative_negative_mood = Conjugations() self.perfect = Conjugations() self.past = Conjugations() self.plusperfect = Conjugations() self.conditional_perfect_mood = Conjugations() self.quotative = Conjugations() self.quotative_perfect = Conjugations() self.jussive = Conjugations() self.jussive_perfect = Conjugations() self.other = {} self.usage_info = "" self.audio = None @property def summary(self) -> str: result = textwrap.dedent(f"""\ --------------------------------------------------------- Usage info: {self.usage_info}\n Infinitive (-ma -da translation): {self.infinitive_ma[0]} {self.infinitive_da[0]} {self.infinitive_ma[1]}\n Past active participle: {self.past_active_participle[0]} {self.past_active_participle[1]}\n Past passive participle: {self.past_passive_participle[0]} {self.past_passive_participle[1]} """) result += "\nPast passive participle\n" result += self.past_passive_participle[0] + " " + self.past_passive_participle[1] + "\n" result += "\nPresent tense\n" result += self.present.summary result += "\nConditional mood\n" result += self.conditional_mood.summary result += "\nImperative mood\n" result += self.imperative_mood.summary result += "\nImperative negative mood\n" result += self.imperative_negative_mood.summary result += "\nPerfect tense\n" result += self.perfect.summary result += "\nPast tense\n" result += self.past.summary result += "\nPlusperfect tense\n" result += self.plusperfect.summary result += "\nConditional perfect mood\n" result += self.conditional_perfect_mood.summary result += "\nQuotative tense\n" result += self.quotative.summary result += "\nQuotative perfect tense\n" result += self.quotative_perfect.summary result += "\nJussive tense\n" result += self.jussive.summary result += "\nJussive perfect tense\n" result += self.jussive_perfect.summary result += "\nOther\n" for key in self.other: result += key + " " + self.other[key][0] + " " + self.other[key][1] + "\n" result += "---------------------------------------------------------\n" return result
true
true
f71697bced2a9b09c787e7d1ea296be902ceb742
2,498
py
Python
src/cobald/daemon/runners/asyncio_runner.py
thoto/cobald
27f7a0b5208383e8a7a386f358009a433084908e
[ "MIT" ]
7
2019-06-11T12:57:10.000Z
2019-10-07T17:46:41.000Z
src/cobald/daemon/runners/asyncio_runner.py
thoto/cobald
27f7a0b5208383e8a7a386f358009a433084908e
[ "MIT" ]
76
2019-03-01T08:24:08.000Z
2022-03-24T20:37:23.000Z
src/cobald/daemon/runners/asyncio_runner.py
thoto/cobald
27f7a0b5208383e8a7a386f358009a433084908e
[ "MIT" ]
8
2019-06-27T13:06:12.000Z
2022-02-15T15:27:58.000Z
import asyncio from functools import partial from .base_runner import BaseRunner from .async_tools import raise_return, AsyncExecution class AsyncioRunner(BaseRunner): """Runner for coroutines with :py:mod:`asyncio`""" flavour = asyncio def __init__(self): super().__init__() self.event_loop = asyncio.new_event_loop() self._tasks = set() def register_payload(self, payload): super().register_payload(partial(raise_return, payload)) def run_payload(self, payload): execution = AsyncExecution(payload) super().register_payload(execution.coroutine) return execution.wait() def _run(self): asyncio.set_event_loop(self.event_loop) self.event_loop.run_until_complete(self._run_payloads()) async def _run_payloads(self): """Async component of _run""" delay = 0.0 try: while self.running.is_set(): await self._start_payloads() await self._reap_payloads() await asyncio.sleep(delay) delay = min(delay + 0.1, 1.0) except Exception: await self._cancel_payloads() raise async def _start_payloads(self): """Start all queued payloads""" with self._lock: for coroutine in self._payloads: task = self.event_loop.create_task(coroutine()) self._tasks.add(task) self._payloads.clear() await asyncio.sleep(0) async def _reap_payloads(self): """Clean up all finished payloads""" for task in self._tasks.copy(): if task.done(): self._tasks.remove(task) if task.exception() is not None: raise task.exception() await asyncio.sleep(0) async def _cancel_payloads(self): """Cancel all remaining payloads""" for task in self._tasks: task.cancel() await asyncio.sleep(0) for task in self._tasks: while not task.done(): await asyncio.sleep(0.1) task.cancel() def stop(self): if not self.running.wait(0.2): return self._logger.debug("runner disabled: %s", self) with self._lock: self.running.clear() for task in self._tasks: task.cancel() self._stopped.wait() self.event_loop.stop() self.event_loop.close()
30.463415
64
0.583667
import asyncio from functools import partial from .base_runner import BaseRunner from .async_tools import raise_return, AsyncExecution class AsyncioRunner(BaseRunner): flavour = asyncio def __init__(self): super().__init__() self.event_loop = asyncio.new_event_loop() self._tasks = set() def register_payload(self, payload): super().register_payload(partial(raise_return, payload)) def run_payload(self, payload): execution = AsyncExecution(payload) super().register_payload(execution.coroutine) return execution.wait() def _run(self): asyncio.set_event_loop(self.event_loop) self.event_loop.run_until_complete(self._run_payloads()) async def _run_payloads(self): delay = 0.0 try: while self.running.is_set(): await self._start_payloads() await self._reap_payloads() await asyncio.sleep(delay) delay = min(delay + 0.1, 1.0) except Exception: await self._cancel_payloads() raise async def _start_payloads(self): with self._lock: for coroutine in self._payloads: task = self.event_loop.create_task(coroutine()) self._tasks.add(task) self._payloads.clear() await asyncio.sleep(0) async def _reap_payloads(self): for task in self._tasks.copy(): if task.done(): self._tasks.remove(task) if task.exception() is not None: raise task.exception() await asyncio.sleep(0) async def _cancel_payloads(self): for task in self._tasks: task.cancel() await asyncio.sleep(0) for task in self._tasks: while not task.done(): await asyncio.sleep(0.1) task.cancel() def stop(self): if not self.running.wait(0.2): return self._logger.debug("runner disabled: %s", self) with self._lock: self.running.clear() for task in self._tasks: task.cancel() self._stopped.wait() self.event_loop.stop() self.event_loop.close()
true
true
f71697bcf73bda98b7059ee2d3fd8ac5e69857ec
2,881
py
Python
tests/test_fuzzy_completion.py
vijayraavi/mssql-cli
bc16073e371314b970479c2830266ff24d63bd16
[ "BSD-3-Clause" ]
null
null
null
tests/test_fuzzy_completion.py
vijayraavi/mssql-cli
bc16073e371314b970479c2830266ff24d63bd16
[ "BSD-3-Clause" ]
null
null
null
tests/test_fuzzy_completion.py
vijayraavi/mssql-cli
bc16073e371314b970479c2830266ff24d63bd16
[ "BSD-3-Clause" ]
null
null
null
from __future__ import unicode_literals import pytest @pytest.fixture def completer(): import mssqlcli.mssqlcompleter as mssqlcompleter return mssqlcompleter.MssqlCompleter() def test_ranking_ignores_identifier_quotes(completer): """When calculating result rank, identifier quotes should be ignored. The result ranking algorithm ignores identifier quotes. Without this correction, the match "user", which Postgres requires to be quoted since it is also a reserved word, would incorrectly fall below the match user_action because the literal quotation marks in "user" alter the position of the match. This test checks that the fuzzy ranking algorithm correctly ignores quotation marks when computing match ranks. """ text = 'user' collection = ['user_action', '"user"'] matches = completer.find_matches(text, collection) assert len(matches) == 2 def test_ranking_based_on_shortest_match(completer): """Fuzzy result rank should be based on shortest match. Result ranking in fuzzy searching is partially based on the length of matches: shorter matches are considered more relevant than longer ones. When searching for the text 'user', the length component of the match 'user_group' could be either 4 ('user') or 7 ('user_gr'). This test checks that the fuzzy ranking algorithm uses the shorter match when calculating result rank. """ text = 'user' collection = ['api_user', 'user_group'] matches = completer.find_matches(text, collection) assert matches[1].priority > matches[0].priority @pytest.mark.parametrize('collection', [ ['user_action', 'user'], ['user_group', 'user'], ['user_group', 'user_action'], ]) def test_should_break_ties_using_lexical_order(completer, collection): """Fuzzy result rank should use lexical order to break ties. When fuzzy matching, if multiple matches have the same match length and start position, present them in lexical (rather than arbitrary) order. For example, if we have tables 'user', 'user_action', and 'user_group', a search for the text 'user' should present these tables in this order. The input collections to this test are out of order; each run checks that the search text 'user' results in the input tables being reordered lexically. """ text = 'user' matches = completer.find_matches(text, collection) assert matches[1].priority > matches[0].priority def test_matching_should_be_case_insensitive(completer): """Fuzzy matching should keep matches even if letter casing doesn't match. This test checks that variations of the text which have different casing are still matched. """ text = 'foo' collection = ['Foo', 'FOO', 'fOO'] matches = completer.find_matches(text, collection) assert len(matches) == 3
32.370787
78
0.72579
from __future__ import unicode_literals import pytest @pytest.fixture def completer(): import mssqlcli.mssqlcompleter as mssqlcompleter return mssqlcompleter.MssqlCompleter() def test_ranking_ignores_identifier_quotes(completer): text = 'user' collection = ['user_action', '"user"'] matches = completer.find_matches(text, collection) assert len(matches) == 2 def test_ranking_based_on_shortest_match(completer): text = 'user' collection = ['api_user', 'user_group'] matches = completer.find_matches(text, collection) assert matches[1].priority > matches[0].priority @pytest.mark.parametrize('collection', [ ['user_action', 'user'], ['user_group', 'user'], ['user_group', 'user_action'], ]) def test_should_break_ties_using_lexical_order(completer, collection): text = 'user' matches = completer.find_matches(text, collection) assert matches[1].priority > matches[0].priority def test_matching_should_be_case_insensitive(completer): text = 'foo' collection = ['Foo', 'FOO', 'fOO'] matches = completer.find_matches(text, collection) assert len(matches) == 3
true
true
f71697d88f48702950eaef9afcbbc278acd2b761
606
py
Python
codewars/7 kyu/string-ends-with.py
sirken/coding-practice
9c5e23b2c24f525a89a5e1d15ce3aec3ad1a01ab
[ "MIT" ]
null
null
null
codewars/7 kyu/string-ends-with.py
sirken/coding-practice
9c5e23b2c24f525a89a5e1d15ce3aec3ad1a01ab
[ "MIT" ]
null
null
null
codewars/7 kyu/string-ends-with.py
sirken/coding-practice
9c5e23b2c24f525a89a5e1d15ce3aec3ad1a01ab
[ "MIT" ]
null
null
null
from Test import Test, Test as test ''' Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string). Examples: solution('abc', 'bc') # returns true solution('abc', 'd') # returns false ''' def solution(string, ending): return True if string[-len(ending):] == ending or len(ending) == 0 else False # Top solution def solution(string, ending): return string.endswith(ending) test.assert_equals(solution('abcde', 'cde'), True) test.assert_equals(solution('abcde', 'abc'), False) test.assert_equals(solution('abcde', ''), True)
28.857143
129
0.714521
from Test import Test, Test as test def solution(string, ending): return True if string[-len(ending):] == ending or len(ending) == 0 else False def solution(string, ending): return string.endswith(ending) test.assert_equals(solution('abcde', 'cde'), True) test.assert_equals(solution('abcde', 'abc'), False) test.assert_equals(solution('abcde', ''), True)
true
true
f7169805436b5cf887fbf1c99fd59f5c2e43d93c
7,209
py
Python
ros/src/styx/bridge.py
Valentinkvn/Udacity-Full-Autonomous-Vehicle-Project
b1313345a09f84c122a91c1145230fe69da0d20f
[ "MIT" ]
null
null
null
ros/src/styx/bridge.py
Valentinkvn/Udacity-Full-Autonomous-Vehicle-Project
b1313345a09f84c122a91c1145230fe69da0d20f
[ "MIT" ]
6
2021-02-22T08:44:36.000Z
2022-03-12T00:13:46.000Z
ros/src/styx/bridge.py
Valentinkvn/Udacity-Full-Autonomous-Vehicle-Project
b1313345a09f84c122a91c1145230fe69da0d20f
[ "MIT" ]
null
null
null
import rospy import tf from geometry_msgs.msg import PoseStamped, Quaternion, TwistStamped from dbw_mkz_msgs.msg import SteeringReport, ThrottleCmd, BrakeCmd, SteeringCmd from std_msgs.msg import Float32 as Float from std_msgs.msg import Bool from sensor_msgs.msg import PointCloud2 from sensor_msgs.msg import Image import sensor_msgs.point_cloud2 as pcl2 from std_msgs.msg import Header from cv_bridge import CvBridge, CvBridgeError from styx_msgs.msg import TrafficLight, TrafficLightArray, Lane import numpy as np from PIL import Image as PIL_Image from io import BytesIO import base64 import math TYPE = { 'bool': Bool, 'float': Float, 'pose': PoseStamped, 'pcl': PointCloud2, 'twist': TwistStamped, 'steer': SteeringReport, 'trafficlights': TrafficLightArray, 'steer_cmd': SteeringCmd, 'brake_cmd': BrakeCmd, 'throttle_cmd': ThrottleCmd, 'path_draw': Lane, 'image':Image } NUM_IMAGES_TO_SKIP = 2 class Bridge(object): def __init__(self, conf, server): rospy.init_node('styx_server') self.server = server self.vel = 0. self.yaw = None self.angular_vel = 0. self.bridge = CvBridge() self.img_count = 0 self.callbacks = { '/vehicle/steering_cmd': self.callback_steering, '/vehicle/throttle_cmd': self.callback_throttle, '/vehicle/brake_cmd': self.callback_brake, '/final_waypoints': self.callback_path } self.subscribers = [rospy.Subscriber(e.topic, TYPE[e.type], self.callbacks[e.topic]) for e in conf.subscribers] self.publishers = {e.name: rospy.Publisher(e.topic, TYPE[e.type], queue_size=1) for e in conf.publishers} def create_light(self, x, y, z, yaw, state): light = TrafficLight() light.header = Header() light.header.stamp = rospy.Time.now() light.header.frame_id = '/world' light.pose = self.create_pose(x, y, z, yaw) light.state = state return light def create_pose(self, x, y, z, yaw=0.): pose = PoseStamped() pose.header = Header() pose.header.stamp = rospy.Time.now() pose.header.frame_id = '/world' pose.pose.position.x = x pose.pose.position.y = y pose.pose.position.z = z q = tf.transformations.quaternion_from_euler(0., 0., math.pi * yaw/180.) pose.pose.orientation = Quaternion(*q) return pose def create_float(self, val): fl = Float() fl.data = val return fl def create_twist(self, velocity, angular): tw = TwistStamped() tw.twist.linear.x = velocity tw.twist.angular.z = angular return tw def create_steer(self, val): st = SteeringReport() st.steering_wheel_angle_cmd = val * math.pi/180. st.enabled = True st.speed = self.vel return st def calc_angular(self, yaw): angular_vel = 0. if self.yaw is not None: angular_vel = (yaw - self.yaw)/(rospy.get_time() - self.prev_time) self.yaw = yaw self.prev_time = rospy.get_time() return angular_vel def create_point_cloud_message(self, pts): header = Header() header.stamp = rospy.Time.now() header.frame_id = '/world' cloud_message = pcl2.create_cloud_xyz32(header, pts) return cloud_message def broadcast_transform(self, name, position, orientation): br = tf.TransformBroadcaster() br.sendTransform(position, orientation, rospy.Time.now(), name, "world") def publish_odometry(self, data): pose = self.create_pose(data['x'], data['y'], data['z'], data['yaw']) position = (data['x'], data['y'], data['z']) orientation = tf.transformations.quaternion_from_euler(0, 0, math.pi * data['yaw']/180.) self.broadcast_transform("base_link", position, orientation) self.publishers['current_pose'].publish(pose) self.vel = data['velocity']* 0.44704 self.angular = self.calc_angular(data['yaw'] * math.pi/180.) self.publishers['current_velocity'].publish(self.create_twist(self.vel, self.angular)) def publish_controls(self, data): steering, throttle, brake = data['steering_angle'], data['throttle'], data['brake'] self.publishers['steering_report'].publish(self.create_steer(steering)) self.publishers['throttle_report'].publish(self.create_float(throttle)) self.publishers['brake_report'].publish(self.create_float(brake)) def publish_obstacles(self, data): for obs in data['obstacles']: pose = self.create_pose(obs[0], obs[1], obs[2]) self.publishers['obstacle'].publish(pose) header = Header() header.stamp = rospy.Time.now() header.frame_id = '/world' cloud = pcl2.create_cloud_xyz32(header, data['obstacles']) self.publishers['obstacle_points'].publish(cloud) def publish_lidar(self, data): self.publishers['lidar'].publish(self.create_point_cloud_message(zip(data['lidar_x'], data['lidar_y'], data['lidar_z']))) def publish_traffic(self, data): x, y, z = data['light_pos_x'], data['light_pos_y'], data['light_pos_z'], yaw = [math.atan2(dy, dx) for dx, dy in zip(data['light_pos_dx'], data['light_pos_dy'])] status = data['light_state'] lights = TrafficLightArray() header = Header() header.stamp = rospy.Time.now() header.frame_id = '/world' lights.lights = [self.create_light(*e) for e in zip(x, y, z, yaw, status)] self.publishers['trafficlights'].publish(lights) def publish_dbw_status(self, data): self.publishers['dbw_status'].publish(Bool(data)) def publish_camera(self, data): self.img_count += 1 if self.img_count >= NUM_IMAGES_TO_SKIP: # rospy.logwarn("Publish camera data") imgString = data["image"] image = PIL_Image.open(BytesIO(base64.b64decode(imgString))) image_array = np.asarray(image) image_message = self.bridge.cv2_to_imgmsg(image_array, encoding="rgb8") self.publishers['image'].publish(image_message) self.img_count = 0 def callback_steering(self, data): self.server('steer', data={'steering_angle': str(data.steering_wheel_angle_cmd)}) def callback_throttle(self, data): self.server('throttle', data={'throttle': str(data.pedal_cmd)}) def callback_brake(self, data): self.server('brake', data={'brake': str(data.pedal_cmd)}) def callback_path(self, data): x_values = [] y_values = [] z_values = [] for waypoint in data.waypoints: x = waypoint.pose.pose.position.x y = waypoint.pose.pose.position.y z = waypoint.pose.pose.position.z+0.5 x_values.append(x) y_values.append(y) z_values.append(z) self.server('drawline', data={'next_x': x_values, 'next_y': y_values, 'next_z': z_values})
34.004717
129
0.627688
import rospy import tf from geometry_msgs.msg import PoseStamped, Quaternion, TwistStamped from dbw_mkz_msgs.msg import SteeringReport, ThrottleCmd, BrakeCmd, SteeringCmd from std_msgs.msg import Float32 as Float from std_msgs.msg import Bool from sensor_msgs.msg import PointCloud2 from sensor_msgs.msg import Image import sensor_msgs.point_cloud2 as pcl2 from std_msgs.msg import Header from cv_bridge import CvBridge, CvBridgeError from styx_msgs.msg import TrafficLight, TrafficLightArray, Lane import numpy as np from PIL import Image as PIL_Image from io import BytesIO import base64 import math TYPE = { 'bool': Bool, 'float': Float, 'pose': PoseStamped, 'pcl': PointCloud2, 'twist': TwistStamped, 'steer': SteeringReport, 'trafficlights': TrafficLightArray, 'steer_cmd': SteeringCmd, 'brake_cmd': BrakeCmd, 'throttle_cmd': ThrottleCmd, 'path_draw': Lane, 'image':Image } NUM_IMAGES_TO_SKIP = 2 class Bridge(object): def __init__(self, conf, server): rospy.init_node('styx_server') self.server = server self.vel = 0. self.yaw = None self.angular_vel = 0. self.bridge = CvBridge() self.img_count = 0 self.callbacks = { '/vehicle/steering_cmd': self.callback_steering, '/vehicle/throttle_cmd': self.callback_throttle, '/vehicle/brake_cmd': self.callback_brake, '/final_waypoints': self.callback_path } self.subscribers = [rospy.Subscriber(e.topic, TYPE[e.type], self.callbacks[e.topic]) for e in conf.subscribers] self.publishers = {e.name: rospy.Publisher(e.topic, TYPE[e.type], queue_size=1) for e in conf.publishers} def create_light(self, x, y, z, yaw, state): light = TrafficLight() light.header = Header() light.header.stamp = rospy.Time.now() light.header.frame_id = '/world' light.pose = self.create_pose(x, y, z, yaw) light.state = state return light def create_pose(self, x, y, z, yaw=0.): pose = PoseStamped() pose.header = Header() pose.header.stamp = rospy.Time.now() pose.header.frame_id = '/world' pose.pose.position.x = x pose.pose.position.y = y pose.pose.position.z = z q = tf.transformations.quaternion_from_euler(0., 0., math.pi * yaw/180.) pose.pose.orientation = Quaternion(*q) return pose def create_float(self, val): fl = Float() fl.data = val return fl def create_twist(self, velocity, angular): tw = TwistStamped() tw.twist.linear.x = velocity tw.twist.angular.z = angular return tw def create_steer(self, val): st = SteeringReport() st.steering_wheel_angle_cmd = val * math.pi/180. st.enabled = True st.speed = self.vel return st def calc_angular(self, yaw): angular_vel = 0. if self.yaw is not None: angular_vel = (yaw - self.yaw)/(rospy.get_time() - self.prev_time) self.yaw = yaw self.prev_time = rospy.get_time() return angular_vel def create_point_cloud_message(self, pts): header = Header() header.stamp = rospy.Time.now() header.frame_id = '/world' cloud_message = pcl2.create_cloud_xyz32(header, pts) return cloud_message def broadcast_transform(self, name, position, orientation): br = tf.TransformBroadcaster() br.sendTransform(position, orientation, rospy.Time.now(), name, "world") def publish_odometry(self, data): pose = self.create_pose(data['x'], data['y'], data['z'], data['yaw']) position = (data['x'], data['y'], data['z']) orientation = tf.transformations.quaternion_from_euler(0, 0, math.pi * data['yaw']/180.) self.broadcast_transform("base_link", position, orientation) self.publishers['current_pose'].publish(pose) self.vel = data['velocity']* 0.44704 self.angular = self.calc_angular(data['yaw'] * math.pi/180.) self.publishers['current_velocity'].publish(self.create_twist(self.vel, self.angular)) def publish_controls(self, data): steering, throttle, brake = data['steering_angle'], data['throttle'], data['brake'] self.publishers['steering_report'].publish(self.create_steer(steering)) self.publishers['throttle_report'].publish(self.create_float(throttle)) self.publishers['brake_report'].publish(self.create_float(brake)) def publish_obstacles(self, data): for obs in data['obstacles']: pose = self.create_pose(obs[0], obs[1], obs[2]) self.publishers['obstacle'].publish(pose) header = Header() header.stamp = rospy.Time.now() header.frame_id = '/world' cloud = pcl2.create_cloud_xyz32(header, data['obstacles']) self.publishers['obstacle_points'].publish(cloud) def publish_lidar(self, data): self.publishers['lidar'].publish(self.create_point_cloud_message(zip(data['lidar_x'], data['lidar_y'], data['lidar_z']))) def publish_traffic(self, data): x, y, z = data['light_pos_x'], data['light_pos_y'], data['light_pos_z'], yaw = [math.atan2(dy, dx) for dx, dy in zip(data['light_pos_dx'], data['light_pos_dy'])] status = data['light_state'] lights = TrafficLightArray() header = Header() header.stamp = rospy.Time.now() header.frame_id = '/world' lights.lights = [self.create_light(*e) for e in zip(x, y, z, yaw, status)] self.publishers['trafficlights'].publish(lights) def publish_dbw_status(self, data): self.publishers['dbw_status'].publish(Bool(data)) def publish_camera(self, data): self.img_count += 1 if self.img_count >= NUM_IMAGES_TO_SKIP: imgString = data["image"] image = PIL_Image.open(BytesIO(base64.b64decode(imgString))) image_array = np.asarray(image) image_message = self.bridge.cv2_to_imgmsg(image_array, encoding="rgb8") self.publishers['image'].publish(image_message) self.img_count = 0 def callback_steering(self, data): self.server('steer', data={'steering_angle': str(data.steering_wheel_angle_cmd)}) def callback_throttle(self, data): self.server('throttle', data={'throttle': str(data.pedal_cmd)}) def callback_brake(self, data): self.server('brake', data={'brake': str(data.pedal_cmd)}) def callback_path(self, data): x_values = [] y_values = [] z_values = [] for waypoint in data.waypoints: x = waypoint.pose.pose.position.x y = waypoint.pose.pose.position.y z = waypoint.pose.pose.position.z+0.5 x_values.append(x) y_values.append(y) z_values.append(z) self.server('drawline', data={'next_x': x_values, 'next_y': y_values, 'next_z': z_values})
true
true
f716984bca20b513662e2e393027677207b388b1
1,954
py
Python
mfr2.py
HeegyuKim/face_recognition
d96d2c94225e49d3dd8f2cae4444d35d5c88d13b
[ "MIT" ]
null
null
null
mfr2.py
HeegyuKim/face_recognition
d96d2c94225e49d3dd8f2cae4444d35d5c88d13b
[ "MIT" ]
null
null
null
mfr2.py
HeegyuKim/face_recognition
d96d2c94225e49d3dd8f2cae4444d35d5c88d13b
[ "MIT" ]
null
null
null
import os import shutil import os from glob import glob import pandas as pd import random from collections import defaultdict from PIL import Image from torch.utils.data import Dataset, DataLoader def get_all_images(dir): types = ["jpeg", "jpg", "png"] files = [] for t in types: path = os.path.join(dir, "**", "*." + t) files.extend(glob(path)) return files def casia(dir): files = get_all_images(dir) users = defaultdict(set) rows = [] for file in files: user = file.split("/")[-2] users[user].add(file) rows.append({ "image": file, "id": user }) df = pd.DataFrame(rows) positives = [] negatives = [] for user, files in users.items(): if len(files) <= 1: continue samples = random.sample(files, 2) positives.append({ "image1": samples[0], "image2": samples[1], "id1": user, "id2": user, "label": 1 }) user_ids = list(users.keys()) for i in range(0, len(user_ids), 2): if i == len(user_ids) - 1: continue id1, id2 = user_ids[i], user_ids[i + 1] files1, files2 = users[id1], users[id2] if len(files1) < 2 or len(files2) < 2: break samples1, samples2 = random.sample(files1, 2), random.sample(files2, 2) for j in range(2): negatives.append({ "image1": samples1[j], "image2": samples2[j], "id1": id1, "id2": id2, "label": -1 }) test_set = pd.DataFrame(positives + negatives) return df, test_set # trainset, testset = casia("train/") # trainset.to_csv("train.csv", index=False) # testset.to_csv("train_eval.csv", index=False) for file in glob("dataset/validation/**/*.png", recursive=True): tokens = file.split("/") filename = tokens[-1] id = tokens[-3] dst = f"mfeval/{id}/{filename}" os.makedirs(os.path.abspath(os.path.dirname(dst)), exist_ok=True) shutil.copyfile(file, dst)
22.45977
75
0.592119
import os import shutil import os from glob import glob import pandas as pd import random from collections import defaultdict from PIL import Image from torch.utils.data import Dataset, DataLoader def get_all_images(dir): types = ["jpeg", "jpg", "png"] files = [] for t in types: path = os.path.join(dir, "**", "*." + t) files.extend(glob(path)) return files def casia(dir): files = get_all_images(dir) users = defaultdict(set) rows = [] for file in files: user = file.split("/")[-2] users[user].add(file) rows.append({ "image": file, "id": user }) df = pd.DataFrame(rows) positives = [] negatives = [] for user, files in users.items(): if len(files) <= 1: continue samples = random.sample(files, 2) positives.append({ "image1": samples[0], "image2": samples[1], "id1": user, "id2": user, "label": 1 }) user_ids = list(users.keys()) for i in range(0, len(user_ids), 2): if i == len(user_ids) - 1: continue id1, id2 = user_ids[i], user_ids[i + 1] files1, files2 = users[id1], users[id2] if len(files1) < 2 or len(files2) < 2: break samples1, samples2 = random.sample(files1, 2), random.sample(files2, 2) for j in range(2): negatives.append({ "image1": samples1[j], "image2": samples2[j], "id1": id1, "id2": id2, "label": -1 }) test_set = pd.DataFrame(positives + negatives) return df, test_set for file in glob("dataset/validation/**/*.png", recursive=True): tokens = file.split("/") filename = tokens[-1] id = tokens[-3] dst = f"mfeval/{id}/{filename}" os.makedirs(os.path.abspath(os.path.dirname(dst)), exist_ok=True) shutil.copyfile(file, dst)
true
true
f716985e68c4ca47db77d1c2d95da2329e93bfc9
1,483
py
Python
official/nlp/modeling/networks/__init__.py
akineeic/models
2912042352009c9993dc05403624100bfe42d9c1
[ "Apache-2.0" ]
15
2018-08-15T19:29:39.000Z
2021-11-05T02:14:59.000Z
official/nlp/modeling/networks/__init__.py
yangxl-2014-fe/models
11ea5237818e791a5717716d5413977f4c4db1e3
[ "Apache-2.0" ]
5
2020-10-01T09:02:34.000Z
2021-02-21T12:50:11.000Z
official/nlp/modeling/networks/__init__.py
yangxl-2014-fe/models
11ea5237818e791a5717716d5413977f4c4db1e3
[ "Apache-2.0" ]
8
2019-06-06T20:37:15.000Z
2022-03-04T13:54:38.000Z
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Networks package definition.""" from official.nlp.modeling.networks.albert_encoder import AlbertEncoder from official.nlp.modeling.networks.bert_encoder import BertEncoder from official.nlp.modeling.networks.classification import Classification from official.nlp.modeling.networks.encoder_scaffold import EncoderScaffold from official.nlp.modeling.networks.mobile_bert_encoder import MobileBERTEncoder from official.nlp.modeling.networks.packed_sequence_embedding import PackedSequenceEmbedding from official.nlp.modeling.networks.span_labeling import SpanLabeling from official.nlp.modeling.networks.span_labeling import XLNetSpanLabeling from official.nlp.modeling.networks.xlnet_base import XLNetBase # Backward compatibility. The modules are deprecated. TransformerEncoder = BertEncoder
54.925926
92
0.784895
from official.nlp.modeling.networks.albert_encoder import AlbertEncoder from official.nlp.modeling.networks.bert_encoder import BertEncoder from official.nlp.modeling.networks.classification import Classification from official.nlp.modeling.networks.encoder_scaffold import EncoderScaffold from official.nlp.modeling.networks.mobile_bert_encoder import MobileBERTEncoder from official.nlp.modeling.networks.packed_sequence_embedding import PackedSequenceEmbedding from official.nlp.modeling.networks.span_labeling import SpanLabeling from official.nlp.modeling.networks.span_labeling import XLNetSpanLabeling from official.nlp.modeling.networks.xlnet_base import XLNetBase TransformerEncoder = BertEncoder
true
true
f71698db8367f39cb85d20a59c8f5d11cc1b4ccc
4,301
py
Python
coding_problems/move_zeros.py
NescobarAlopLop/miscellaneous
8e33cb34ddc54dad233d2418d4a90a96ce3c393e
[ "MIT" ]
null
null
null
coding_problems/move_zeros.py
NescobarAlopLop/miscellaneous
8e33cb34ddc54dad233d2418d4a90a96ce3c393e
[ "MIT" ]
null
null
null
coding_problems/move_zeros.py
NescobarAlopLop/miscellaneous
8e33cb34ddc54dad233d2418d4a90a96ce3c393e
[ "MIT" ]
null
null
null
""" Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. """ from unittest import TestCase class Solution: @staticmethod def get_next(nums, start, zero=True): for idx in range(start, len(nums)): if zero and nums[idx] == 0: return idx if not zero and nums[idx] != zero: return idx return len(nums) def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ z = self.get_next(nums, 0, zero=True) n = self.get_next(nums, 0, zero=False) while n < len(nums): if n > z and nums[n] != 0: nums[z], nums[n] = nums[n], nums[z] z = self.get_next(nums, z, zero=True) n = self.get_next(nums, n, zero=False) continue else: n += 1 class TestSolution(TestCase): sol = Solution() def test_0(self): nums = [0, 1, 2, 3, 4] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1, 2, 3, 4, 0], nums) def test_1(self): nums = [0, 1, 0, 2, 0, 3, 0, 1] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1, 2, 3, 1, 0, 0, 0, 0], nums) def test_3(self): nums = [0,1,0,3,12] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1, 3, 12, 0, 0], nums) def test_4(self): nums = [1] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1], nums) def test_5(self): nums = [1, -2, 0, 0, 3, 0, 4, 0] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1, -2, 3, 4, 0, 0, 0, 0], nums) def test_6(self): nums = [-959151711,623836953,209446690,-1950418142,1339915067,-733626417,481171539,-2125997010,-1225423476,1462109565,147434687,-1800073781,-1431212205,-450443973,50097298,753533734,-747189404,-2070885638,0,-1484353894,-340296594,-2133744570,619639811,-1626162038,669689561,0,112220218,502447212,-787793179,0,-726846372,-1611013491,204107194,1605165582,-566891128,2082852116,0,532995238,-1502590712,0,2136989777,-2031153343,371398938,-1907397429,342796391,609166045,-2007448660,-1096076344,-323570318,0,-2082980371,2129956379,-243553361,-1549960929,1502383415,0,-1394618779,694799815,78595689,-1439173023,-1416578800,685225786,-333502212,-1181308536,-380569313,772035354,0,-915266376,663709718,1443496021,-777017729,-883300731,-387828385,1907473488,-725483724,-972961871,-1255712537,383120918,1383877998,1722751914,0,-1156050682,1952527902,-560244497,1304305692,1173974542,-1313227247,-201476579,-298899493,-1828496581,-1724396350,1933643204,1531804925,1728655262,-955565449,0,-69843702,-461760848,268336768,1446130876] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([-959151711,623836953,209446690,-1950418142,1339915067,-733626417,481171539,-2125997010,-1225423476,1462109565,147434687,-1800073781,-1431212205,-450443973,50097298,753533734,-747189404,-2070885638,-1484353894,-340296594,-2133744570,619639811,-1626162038,669689561,112220218,502447212,-787793179,-726846372,-1611013491,204107194,1605165582,-566891128,2082852116,532995238,-1502590712,2136989777,-2031153343,371398938,-1907397429,342796391,609166045,-2007448660,-1096076344,-323570318,-2082980371,2129956379,-243553361,-1549960929,1502383415,-1394618779,694799815,78595689,-1439173023,-1416578800,685225786,-333502212,-1181308536,-380569313,772035354,-915266376,663709718,1443496021,-777017729,-883300731,-387828385,1907473488,-725483724,-972961871,-1255712537,383120918,1383877998,1722751914,-1156050682,1952527902,-560244497,1304305692,1173974542,-1313227247,-201476579,-298899493,-1828496581,-1724396350,1933643204,1531804925,1728655262,-955565449,-69843702,-461760848,268336768,1446130876,0,0,0,0,0,0,0,0,0,0], nums)
52.45122
1,044
0.681702
from unittest import TestCase class Solution: @staticmethod def get_next(nums, start, zero=True): for idx in range(start, len(nums)): if zero and nums[idx] == 0: return idx if not zero and nums[idx] != zero: return idx return len(nums) def moveZeroes(self, nums): z = self.get_next(nums, 0, zero=True) n = self.get_next(nums, 0, zero=False) while n < len(nums): if n > z and nums[n] != 0: nums[z], nums[n] = nums[n], nums[z] z = self.get_next(nums, z, zero=True) n = self.get_next(nums, n, zero=False) continue else: n += 1 class TestSolution(TestCase): sol = Solution() def test_0(self): nums = [0, 1, 2, 3, 4] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1, 2, 3, 4, 0], nums) def test_1(self): nums = [0, 1, 0, 2, 0, 3, 0, 1] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1, 2, 3, 1, 0, 0, 0, 0], nums) def test_3(self): nums = [0,1,0,3,12] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1, 3, 12, 0, 0], nums) def test_4(self): nums = [1] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1], nums) def test_5(self): nums = [1, -2, 0, 0, 3, 0, 4, 0] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([1, -2, 3, 4, 0, 0, 0, 0], nums) def test_6(self): nums = [-959151711,623836953,209446690,-1950418142,1339915067,-733626417,481171539,-2125997010,-1225423476,1462109565,147434687,-1800073781,-1431212205,-450443973,50097298,753533734,-747189404,-2070885638,0,-1484353894,-340296594,-2133744570,619639811,-1626162038,669689561,0,112220218,502447212,-787793179,0,-726846372,-1611013491,204107194,1605165582,-566891128,2082852116,0,532995238,-1502590712,0,2136989777,-2031153343,371398938,-1907397429,342796391,609166045,-2007448660,-1096076344,-323570318,0,-2082980371,2129956379,-243553361,-1549960929,1502383415,0,-1394618779,694799815,78595689,-1439173023,-1416578800,685225786,-333502212,-1181308536,-380569313,772035354,0,-915266376,663709718,1443496021,-777017729,-883300731,-387828385,1907473488,-725483724,-972961871,-1255712537,383120918,1383877998,1722751914,0,-1156050682,1952527902,-560244497,1304305692,1173974542,-1313227247,-201476579,-298899493,-1828496581,-1724396350,1933643204,1531804925,1728655262,-955565449,0,-69843702,-461760848,268336768,1446130876] self.sol.moveZeroes(nums) print("result: {}".format(nums)) self.assertEqual([-959151711,623836953,209446690,-1950418142,1339915067,-733626417,481171539,-2125997010,-1225423476,1462109565,147434687,-1800073781,-1431212205,-450443973,50097298,753533734,-747189404,-2070885638,-1484353894,-340296594,-2133744570,619639811,-1626162038,669689561,112220218,502447212,-787793179,-726846372,-1611013491,204107194,1605165582,-566891128,2082852116,532995238,-1502590712,2136989777,-2031153343,371398938,-1907397429,342796391,609166045,-2007448660,-1096076344,-323570318,-2082980371,2129956379,-243553361,-1549960929,1502383415,-1394618779,694799815,78595689,-1439173023,-1416578800,685225786,-333502212,-1181308536,-380569313,772035354,-915266376,663709718,1443496021,-777017729,-883300731,-387828385,1907473488,-725483724,-972961871,-1255712537,383120918,1383877998,1722751914,-1156050682,1952527902,-560244497,1304305692,1173974542,-1313227247,-201476579,-298899493,-1828496581,-1724396350,1933643204,1531804925,1728655262,-955565449,-69843702,-461760848,268336768,1446130876,0,0,0,0,0,0,0,0,0,0], nums)
true
true
f71699ccf4bde15c74f7288f21e09a3602fee877
4,755
py
Python
events/yukicon2015/management/commands/setup_yukicon2015.py
jlaunonen/turska
fc6ec4e0ae50a823e931152ce8835098b96f5966
[ "CC-BY-3.0" ]
null
null
null
events/yukicon2015/management/commands/setup_yukicon2015.py
jlaunonen/turska
fc6ec4e0ae50a823e931152ce8835098b96f5966
[ "CC-BY-3.0" ]
null
null
null
events/yukicon2015/management/commands/setup_yukicon2015.py
jlaunonen/turska
fc6ec4e0ae50a823e931152ce8835098b96f5966
[ "CC-BY-3.0" ]
null
null
null
# encoding: utf-8 from datetime import datetime, timedelta from django.conf import settings from django.core.management.base import BaseCommand from django.utils.timezone import now from dateutil.tz import tzlocal from core.utils import slugify class Setup(object): def setup(self, test=False): self.test = test self.tz = tzlocal() self.setup_core() self.setup_tickets() def setup_core(self): from core.models import Venue, Event self.venue, unused = Venue.objects.get_or_create(name='Espoon kulttuurikeskus', defaults=dict( name_inessive='Espoon kulttuurikeskuksessa', )) self.event, unused = Event.objects.get_or_create(slug='yukicon2015', defaults=dict( name='Yukicon 2.0', name_genitive='Yukicon 2.0 -tapahtuman', name_illative='Yukicon 2.0 -tapahtumaan', name_inessive='Yukicon 2.0 -tapahtumassa', homepage_url='http://www.yukicon.fi', organization_name='Yukitea ry', organization_url='http://www.yukicon.fi', start_time=datetime(2015, 1, 10, 10, 0, tzinfo=self.tz), end_time=datetime(2015, 1, 11, 18, 0, tzinfo=self.tz), venue=self.venue, )) def setup_tickets(self): from tickets.models import TicketsEventMeta, LimitGroup, Product tickets_admin_group, = TicketsEventMeta.get_or_create_groups(self.event, ['admins']) defaults = dict( admin_group=tickets_admin_group, due_days=14, shipping_and_handling_cents=0, reference_number_template="2015{:05d}", contact_email='Yukicon <yukicon@yukicon.fi>', plain_contact_email='yukicon@yukicon.fi', ticket_free_text=u"Tämä on sähköinen lippusi Yukicon 2.0 -tapahtumaan. Sähköinen lippu vaihdetaan rannekkeeseen\n" u"lipunvaihtopisteessä saapuessasi tapahtumaan. Voit tulostaa tämän lipun tai näyttää sen\n" u"älypuhelimen tai tablettitietokoneen näytöltä. Mikäli kumpikaan näistä ei ole mahdollista, ota ylös\n" u"kunkin viivakoodin alla oleva neljästä tai viidestä sanasta koostuva sanakoodi ja ilmoita se\n" u"lipunvaihtopisteessä.\n\n" u"Tervetuloa Yukiconiin!", front_page_text=u"<h2>Tervetuloa ostamaan pääsylippuja Yukicon 2.0 -tapahtumaan!</h2>" u"<p>Liput maksetaan suomalaisilla verkkopankkitunnuksilla heti tilauksen yhteydessä.</p>" u"<p>Lue lisää tapahtumasta <a href='http://www.yukicon.fi'>Yukiconin kotisivuilta</a>.</p>", ) if self.test: t = now() defaults.update( ticket_sales_starts=t - timedelta(days=60), ticket_sales_ends=t + timedelta(days=60), ) else: defaults.update( ticket_sales_starts=datetime(2014, 11, 20, 18, 0, tzinfo=self.tz), ticket_sales_ends=datetime(2015, 1, 11, 18, 0, tzinfo=self.tz), ) meta, unused = TicketsEventMeta.objects.get_or_create(event=self.event, defaults=defaults) def limit_group(description, limit): limit_group, unused = LimitGroup.objects.get_or_create( event=self.event, description=description, defaults=dict(limit=limit), ) return limit_group def ordering(): ordering.counter += 10 return ordering.counter ordering.counter = 0 for product_info in [ dict( name=u'Yukicon 2015 -pääsylippu', description=u'Lippu kattaa koko viikonlopun. Maksettuasi sinulle lähetetään PDF-lippu antamaasi sähköpostiin, jota vastaan saat rannekkeen tapahtuman ovelta.', limit_groups=[ limit_group('Pääsyliput', 1450), ], price_cents=1700, requires_shipping=False, electronic_ticket=True, available=True, ordering=ordering(), ), ]: name = product_info.pop('name') limit_groups = product_info.pop('limit_groups') product, unused = Product.objects.get_or_create( event=self.event, name=name, defaults=product_info ) if not product.limit_groups.exists(): product.limit_groups = limit_groups product.save() class Command(BaseCommand): args = '' help = 'Setup yukicon2015 specific stuff' def handle(self, *args, **opts): Setup().setup(test=settings.DEBUG)
38.04
175
0.606519
from datetime import datetime, timedelta from django.conf import settings from django.core.management.base import BaseCommand from django.utils.timezone import now from dateutil.tz import tzlocal from core.utils import slugify class Setup(object): def setup(self, test=False): self.test = test self.tz = tzlocal() self.setup_core() self.setup_tickets() def setup_core(self): from core.models import Venue, Event self.venue, unused = Venue.objects.get_or_create(name='Espoon kulttuurikeskus', defaults=dict( name_inessive='Espoon kulttuurikeskuksessa', )) self.event, unused = Event.objects.get_or_create(slug='yukicon2015', defaults=dict( name='Yukicon 2.0', name_genitive='Yukicon 2.0 -tapahtuman', name_illative='Yukicon 2.0 -tapahtumaan', name_inessive='Yukicon 2.0 -tapahtumassa', homepage_url='http://www.yukicon.fi', organization_name='Yukitea ry', organization_url='http://www.yukicon.fi', start_time=datetime(2015, 1, 10, 10, 0, tzinfo=self.tz), end_time=datetime(2015, 1, 11, 18, 0, tzinfo=self.tz), venue=self.venue, )) def setup_tickets(self): from tickets.models import TicketsEventMeta, LimitGroup, Product tickets_admin_group, = TicketsEventMeta.get_or_create_groups(self.event, ['admins']) defaults = dict( admin_group=tickets_admin_group, due_days=14, shipping_and_handling_cents=0, reference_number_template="2015{:05d}", contact_email='Yukicon <yukicon@yukicon.fi>', plain_contact_email='yukicon@yukicon.fi', ticket_free_text=u"Tämä on sähköinen lippusi Yukicon 2.0 -tapahtumaan. Sähköinen lippu vaihdetaan rannekkeeseen\n" u"lipunvaihtopisteessä saapuessasi tapahtumaan. Voit tulostaa tämän lipun tai näyttää sen\n" u"älypuhelimen tai tablettitietokoneen näytöltä. Mikäli kumpikaan näistä ei ole mahdollista, ota ylös\n" u"kunkin viivakoodin alla oleva neljästä tai viidestä sanasta koostuva sanakoodi ja ilmoita se\n" u"lipunvaihtopisteessä.\n\n" u"Tervetuloa Yukiconiin!", front_page_text=u"<h2>Tervetuloa ostamaan pääsylippuja Yukicon 2.0 -tapahtumaan!</h2>" u"<p>Liput maksetaan suomalaisilla verkkopankkitunnuksilla heti tilauksen yhteydessä.</p>" u"<p>Lue lisää tapahtumasta <a href='http://www.yukicon.fi'>Yukiconin kotisivuilta</a>.</p>", ) if self.test: t = now() defaults.update( ticket_sales_starts=t - timedelta(days=60), ticket_sales_ends=t + timedelta(days=60), ) else: defaults.update( ticket_sales_starts=datetime(2014, 11, 20, 18, 0, tzinfo=self.tz), ticket_sales_ends=datetime(2015, 1, 11, 18, 0, tzinfo=self.tz), ) meta, unused = TicketsEventMeta.objects.get_or_create(event=self.event, defaults=defaults) def limit_group(description, limit): limit_group, unused = LimitGroup.objects.get_or_create( event=self.event, description=description, defaults=dict(limit=limit), ) return limit_group def ordering(): ordering.counter += 10 return ordering.counter ordering.counter = 0 for product_info in [ dict( name=u'Yukicon 2015 -pääsylippu', description=u'Lippu kattaa koko viikonlopun. Maksettuasi sinulle lähetetään PDF-lippu antamaasi sähköpostiin, jota vastaan saat rannekkeen tapahtuman ovelta.', limit_groups=[ limit_group('Pääsyliput', 1450), ], price_cents=1700, requires_shipping=False, electronic_ticket=True, available=True, ordering=ordering(), ), ]: name = product_info.pop('name') limit_groups = product_info.pop('limit_groups') product, unused = Product.objects.get_or_create( event=self.event, name=name, defaults=product_info ) if not product.limit_groups.exists(): product.limit_groups = limit_groups product.save() class Command(BaseCommand): args = '' help = 'Setup yukicon2015 specific stuff' def handle(self, *args, **opts): Setup().setup(test=settings.DEBUG)
true
true
f7169a3697dd8cdb379fbd71762594e9c77e9d4a
5,784
py
Python
emerge.py
puiterwijk/dnf-plugins-emerge
fc5640a374fb9fbc5eb6c749e1f6f32617dd9532
[ "MIT" ]
2
2018-02-27T23:25:36.000Z
2018-03-01T09:18:47.000Z
emerge.py
puiterwijk/dnf-plugins-emerge
fc5640a374fb9fbc5eb6c749e1f6f32617dd9532
[ "MIT" ]
null
null
null
emerge.py
puiterwijk/dnf-plugins-emerge
fc5640a374fb9fbc5eb6c749e1f6f32617dd9532
[ "MIT" ]
null
null
null
import dnf import dnf.cli from glob import glob import logging import threading import tempfile import subprocess import shutil import os logger = logging.getLogger('dnf') class ErrorThread(threading.Thread): _my_exception = None def run(self, *args): try: self._run(*self._args) except Exception as ex: self._my_exception = ex class BuildThread(ErrorThread): @property def branch(self): return 'master' @property def template_mock_config(self): return '/etc/mock/fedora-rawhide-x86_64.cfg' def _run(self, workdir, pkg): pkgdir = os.path.join(workdir, pkg) # Grab sources logger.info('Grabbing sources') subprocess.run(['fedpkg', 'clone', '--anonymous', '--branch', self.branch, 'rpms/%s' % pkg, pkgdir], check=True) # Generate mockconfig logger.info('Generating mock config') mock_config = os.path.join(workdir, '_mockconfig', 'emerge-%s.cfg' % pkg) with open(self.template_mock_config, 'r') as template: with open(mock_config, 'w') as out: out.write("config_opts['basedir'] = '%s'\n" % (os.path.join(workdir, '_mockroots'))) for line in template.readlines(): if "config_opts['root']" in line: out.write("config_opts['root'] = 'emerge-%s'\n" % pkg) else: out.write(line) # Run mockbuild logger.info('Building') subprocess.run(['fedpkg', 'mockbuild', '--root', mock_config, '--no-clean-all'], check=True, cwd=pkgdir) @dnf.plugin.register_command class EmergeCommand(dnf.cli.Command): aliases = ['emerge'] workdir = None def configure(self): self.cli.demands.available_repos = True self.cli.demands.sack_activation = True self.cli.demands.root_user = True self.cli.demands.resolving = True @staticmethod def set_argparser(parser): parser.add_argument('package', nargs='+', metavar='package', help='Package to emerge') parser.add_argument('--workdir') parser.add_argument('--skip-build', action='store_true') parser.add_argument('--skip-clean', action='store_true') def run_transaction(self): self._rmworkdir() def _rmworkdir(self): if self.workdir and not self.opts.workdir and not self.opts.skip_clean: shutil.rmtree(self.workdir) def run(self): try: self._run() except: self._rmworkdir() raise def _run(self): q = self.base.sack.query() pkgs = self.base.sack.query().available().filter(name=self.opts.package).latest().run() if not pkgs: raise dnf.exceptions.Error('no package matched') to_build_install = {} for pkg in pkgs: if pkg.source_name in to_build_install: to_build_install[pkg.source_name].add(pkg.name) else: to_build_install[pkg.source_name] = set([pkg.name]) logger.info('Building/installing: %s' % to_build_install) if self.opts.workdir: self.workdir = self.opts.workdir else: self.workdir = tempfile.TemporaryDirectory(prefix='dnf-emerge-').name logger.debug('Workdir: %s', self.workdir) self._build(self.workdir, to_build_install) pkgs = self._find_packages(self.workdir, to_build_install) err_pkgs = [] for pkg in self.base.add_remote_rpms(pkgs): try: self.base.package_install(pkg) except dnf.exceptions.MarkingError: logger.info('Unable to install %s' % self.base.output.term.bold(pkg.location)) err_pkgs.append(pkg) if len(err_pkgs) != 0 and strict: raise dnf.exceptions.PackagesNotAvailableError( 'Unable to find a match', packages=err_pkgs) @staticmethod def _is_wanted_file(fname, haystack): for needle in haystack: if fname.endswith('.src.rpm'): continue if not fname.startswith(needle + '-'): continue rest = fname[len(needle)+1:].split('-') if len(rest) > 2: continue if not rest[0][0].isdigit(): continue return True return False def _find_packages(self, workdir, to_build_install): to_install = [] for source, binaries in to_build_install.items(): sourcedir = os.path.join(workdir, source, 'results_%s' % source, '*', '*', '*.rpm') for fpath in glob(sourcedir): fname = os.path.basename(fpath) if self._is_wanted_file(fname, binaries): to_install.append(fpath) logger.info('Marking for installation: %s', to_install) return to_install def _build(self, workdir, to_build_install): if self.opts.skip_build: logger.error('Skipping build per request') return os.makedirs(os.path.join(workdir, '_mockconfig')) os.makedirs(os.path.join(workdir, '_mockroots')) buildthreads = [] for pkg in to_build_install.keys(): bthread = BuildThread(name='emerge-build-%s' % pkg, args=(workdir, pkg)) buildthreads.append(bthread) bthread.start() logger.info('All builds started, waiting for them to finish...') for bthread in buildthreads: bthread.join() if bthread._my_exception: raise bthread._my_exception logger.info('All builds finished')
32.494382
112
0.584198
import dnf import dnf.cli from glob import glob import logging import threading import tempfile import subprocess import shutil import os logger = logging.getLogger('dnf') class ErrorThread(threading.Thread): _my_exception = None def run(self, *args): try: self._run(*self._args) except Exception as ex: self._my_exception = ex class BuildThread(ErrorThread): @property def branch(self): return 'master' @property def template_mock_config(self): return '/etc/mock/fedora-rawhide-x86_64.cfg' def _run(self, workdir, pkg): pkgdir = os.path.join(workdir, pkg) logger.info('Grabbing sources') subprocess.run(['fedpkg', 'clone', '--anonymous', '--branch', self.branch, 'rpms/%s' % pkg, pkgdir], check=True) logger.info('Generating mock config') mock_config = os.path.join(workdir, '_mockconfig', 'emerge-%s.cfg' % pkg) with open(self.template_mock_config, 'r') as template: with open(mock_config, 'w') as out: out.write("config_opts['basedir'] = '%s'\n" % (os.path.join(workdir, '_mockroots'))) for line in template.readlines(): if "config_opts['root']" in line: out.write("config_opts['root'] = 'emerge-%s'\n" % pkg) else: out.write(line) logger.info('Building') subprocess.run(['fedpkg', 'mockbuild', '--root', mock_config, '--no-clean-all'], check=True, cwd=pkgdir) @dnf.plugin.register_command class EmergeCommand(dnf.cli.Command): aliases = ['emerge'] workdir = None def configure(self): self.cli.demands.available_repos = True self.cli.demands.sack_activation = True self.cli.demands.root_user = True self.cli.demands.resolving = True @staticmethod def set_argparser(parser): parser.add_argument('package', nargs='+', metavar='package', help='Package to emerge') parser.add_argument('--workdir') parser.add_argument('--skip-build', action='store_true') parser.add_argument('--skip-clean', action='store_true') def run_transaction(self): self._rmworkdir() def _rmworkdir(self): if self.workdir and not self.opts.workdir and not self.opts.skip_clean: shutil.rmtree(self.workdir) def run(self): try: self._run() except: self._rmworkdir() raise def _run(self): q = self.base.sack.query() pkgs = self.base.sack.query().available().filter(name=self.opts.package).latest().run() if not pkgs: raise dnf.exceptions.Error('no package matched') to_build_install = {} for pkg in pkgs: if pkg.source_name in to_build_install: to_build_install[pkg.source_name].add(pkg.name) else: to_build_install[pkg.source_name] = set([pkg.name]) logger.info('Building/installing: %s' % to_build_install) if self.opts.workdir: self.workdir = self.opts.workdir else: self.workdir = tempfile.TemporaryDirectory(prefix='dnf-emerge-').name logger.debug('Workdir: %s', self.workdir) self._build(self.workdir, to_build_install) pkgs = self._find_packages(self.workdir, to_build_install) err_pkgs = [] for pkg in self.base.add_remote_rpms(pkgs): try: self.base.package_install(pkg) except dnf.exceptions.MarkingError: logger.info('Unable to install %s' % self.base.output.term.bold(pkg.location)) err_pkgs.append(pkg) if len(err_pkgs) != 0 and strict: raise dnf.exceptions.PackagesNotAvailableError( 'Unable to find a match', packages=err_pkgs) @staticmethod def _is_wanted_file(fname, haystack): for needle in haystack: if fname.endswith('.src.rpm'): continue if not fname.startswith(needle + '-'): continue rest = fname[len(needle)+1:].split('-') if len(rest) > 2: continue if not rest[0][0].isdigit(): continue return True return False def _find_packages(self, workdir, to_build_install): to_install = [] for source, binaries in to_build_install.items(): sourcedir = os.path.join(workdir, source, 'results_%s' % source, '*', '*', '*.rpm') for fpath in glob(sourcedir): fname = os.path.basename(fpath) if self._is_wanted_file(fname, binaries): to_install.append(fpath) logger.info('Marking for installation: %s', to_install) return to_install def _build(self, workdir, to_build_install): if self.opts.skip_build: logger.error('Skipping build per request') return os.makedirs(os.path.join(workdir, '_mockconfig')) os.makedirs(os.path.join(workdir, '_mockroots')) buildthreads = [] for pkg in to_build_install.keys(): bthread = BuildThread(name='emerge-build-%s' % pkg, args=(workdir, pkg)) buildthreads.append(bthread) bthread.start() logger.info('All builds started, waiting for them to finish...') for bthread in buildthreads: bthread.join() if bthread._my_exception: raise bthread._my_exception logger.info('All builds finished')
true
true
f7169acccf677a901455907c655d4e12841b5f55
11,443
py
Python
tf_agents/experimental/examples/sac/haarnoja18/sac_train_eval.py
cmarlin/agents
1729e06f42237b34dab8bd9d8c01980c2d2b391c
[ "Apache-2.0" ]
1
2021-04-19T02:28:24.000Z
2021-04-19T02:28:24.000Z
tf_agents/experimental/examples/sac/haarnoja18/sac_train_eval.py
cmarlin/agents
1729e06f42237b34dab8bd9d8c01980c2d2b391c
[ "Apache-2.0" ]
null
null
null
tf_agents/experimental/examples/sac/haarnoja18/sac_train_eval.py
cmarlin/agents
1729e06f42237b34dab8bd9d8c01980c2d2b391c
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 r"""Train and Eval SAC. All hyperparameters come from the SAC paper https://arxiv.org/pdf/1812.05905.pdf """ import functools import os from absl import app from absl import flags from absl import logging import gin import reverb import tensorflow as tf from tf_agents.agents.sac import sac_agent from tf_agents.agents.sac import tanh_normal_projection_network from tf_agents.environments import suite_mujoco from tf_agents.keras_layers import inner_reshape from tf_agents.metrics import py_metrics from tf_agents.networks import nest_map from tf_agents.networks import sequential from tf_agents.policies import greedy_policy from tf_agents.policies import py_tf_eager_policy from tf_agents.policies import random_py_policy from tf_agents.replay_buffers import reverb_replay_buffer from tf_agents.replay_buffers import reverb_utils from tf_agents.train import actor from tf_agents.train import learner from tf_agents.train import triggers from tf_agents.train.utils import spec_utils from tf_agents.train.utils import train_utils FLAGS = flags.FLAGS flags.DEFINE_string('root_dir', os.getenv('TEST_UNDECLARED_OUTPUTS_DIR'), 'Root directory for writing logs/summaries/checkpoints.') flags.DEFINE_integer( 'reverb_port', None, 'Port for reverb server, if None, use a randomly chosen unused port.') flags.DEFINE_integer('num_iterations', 3000000, 'Total number train/eval iterations to perform.') flags.DEFINE_integer( 'eval_interval', 10000, 'Number of train steps between evaluations. Set to 0 to skip.') flags.DEFINE_multi_string('gin_file', None, 'Paths to the gin-config files.') flags.DEFINE_multi_string('gin_bindings', None, 'Gin binding parameters.') dense = functools.partial( tf.keras.layers.Dense, activation=tf.keras.activations.relu, kernel_initializer='glorot_uniform') def create_fc_network(layer_units): return sequential.Sequential([dense(num_units) for num_units in layer_units]) def create_identity_layer(): return tf.keras.layers.Lambda(lambda x: x) def create_sequential_critic_network(obs_fc_layer_units, action_fc_layer_units, joint_fc_layer_units): """Create a sequential critic network.""" # Split the inputs into observations and actions. def split_inputs(inputs): return {'observation': inputs[0], 'action': inputs[1]} # Create an observation network. obs_network = (create_fc_network(obs_fc_layer_units) if obs_fc_layer_units else create_identity_layer()) # Create an action network. action_network = (create_fc_network(action_fc_layer_units) if action_fc_layer_units else create_identity_layer()) # Create a joint network. joint_network = (create_fc_network(joint_fc_layer_units) if joint_fc_layer_units else create_identity_layer()) # Final layer. value_layer = tf.keras.layers.Dense(1, kernel_initializer='glorot_uniform') return sequential.Sequential([ tf.keras.layers.Lambda(split_inputs), nest_map.NestMap({ 'observation': obs_network, 'action': action_network }), nest_map.NestFlatten(), tf.keras.layers.Concatenate(), joint_network, value_layer, inner_reshape.InnerReshape(current_shape=[1], new_shape=[]) ], name='sequential_critic') class _TanhNormalProjectionNetworkWrapper( tanh_normal_projection_network.TanhNormalProjectionNetwork): """Wrapper to pass predefined `outer_rank` to underlying projection net.""" def __init__(self, sample_spec, predefined_outer_rank=1): super(_TanhNormalProjectionNetworkWrapper, self).__init__(sample_spec) self.predefined_outer_rank = predefined_outer_rank def call(self, inputs, network_state=(), **kwargs): kwargs['outer_rank'] = self.predefined_outer_rank if 'step_type' in kwargs: del kwargs['step_type'] return super(_TanhNormalProjectionNetworkWrapper, self).call(inputs, **kwargs) def create_sequential_actor_network(actor_fc_layers, action_tensor_spec): """Create a sequential actor network.""" def tile_as_nest(non_nested_output): return tf.nest.map_structure(lambda _: non_nested_output, action_tensor_spec) return sequential.Sequential( [dense(num_units) for num_units in actor_fc_layers] + [tf.keras.layers.Lambda(tile_as_nest)] + [ nest_map.NestMap( tf.nest.map_structure(_TanhNormalProjectionNetworkWrapper, action_tensor_spec)) ]) @gin.configurable def train_eval( root_dir, env_name='HalfCheetah-v2', # Training params initial_collect_steps=10000, num_iterations=3200000, actor_fc_layers=(256, 256), critic_obs_fc_layers=None, critic_action_fc_layers=None, critic_joint_fc_layers=(256, 256), # Agent params batch_size=256, actor_learning_rate=3e-4, critic_learning_rate=3e-4, alpha_learning_rate=3e-4, gamma=0.99, target_update_tau=0.005, target_update_period=1, reward_scale_factor=0.1, # Replay params reverb_port=None, replay_capacity=1000000, # Others policy_save_interval=10000, replay_buffer_save_interval=100000, eval_interval=10000, eval_episodes=30, debug_summaries=False, summarize_grads_and_vars=False): """Trains and evaluates SAC.""" logging.info('Training SAC on: %s', env_name) collect_env = suite_mujoco.load(env_name) eval_env = suite_mujoco.load(env_name) _, action_tensor_spec, time_step_tensor_spec = ( spec_utils.get_tensor_specs(collect_env)) train_step = train_utils.create_train_step() actor_net = create_sequential_actor_network( actor_fc_layers=actor_fc_layers, action_tensor_spec=action_tensor_spec) critic_net = create_sequential_critic_network( obs_fc_layer_units=critic_obs_fc_layers, action_fc_layer_units=critic_action_fc_layers, joint_fc_layer_units=critic_joint_fc_layers) agent = sac_agent.SacAgent( time_step_tensor_spec, action_tensor_spec, actor_network=actor_net, critic_network=critic_net, actor_optimizer=tf.keras.optimizers.Adam( learning_rate=actor_learning_rate), critic_optimizer=tf.keras.optimizers.Adam( learning_rate=critic_learning_rate), alpha_optimizer=tf.keras.optimizers.Adam( learning_rate=alpha_learning_rate), target_update_tau=target_update_tau, target_update_period=target_update_period, td_errors_loss_fn=tf.math.squared_difference, gamma=gamma, reward_scale_factor=reward_scale_factor, gradient_clipping=None, debug_summaries=debug_summaries, summarize_grads_and_vars=summarize_grads_and_vars, train_step_counter=train_step) agent.initialize() table_name = 'uniform_table' table = reverb.Table( table_name, max_size=replay_capacity, sampler=reverb.selectors.Uniform(), remover=reverb.selectors.Fifo(), rate_limiter=reverb.rate_limiters.MinSize(1)) reverb_checkpoint_dir = os.path.join(root_dir, learner.TRAIN_DIR, learner.REPLAY_BUFFER_CHECKPOINT_DIR) reverb_checkpointer = reverb.platform.checkpointers_lib.DefaultCheckpointer( path=reverb_checkpoint_dir) reverb_server = reverb.Server([table], port=reverb_port, checkpointer=reverb_checkpointer) reverb_replay = reverb_replay_buffer.ReverbReplayBuffer( agent.collect_data_spec, sequence_length=2, table_name=table_name, local_server=reverb_server) rb_observer = reverb_utils.ReverbAddTrajectoryObserver( reverb_replay.py_client, table_name, sequence_length=2, stride_length=1) dataset = reverb_replay.as_dataset( sample_batch_size=batch_size, num_steps=2).prefetch(50) experience_dataset_fn = lambda: dataset saved_model_dir = os.path.join(root_dir, learner.POLICY_SAVED_MODEL_DIR) env_step_metric = py_metrics.EnvironmentSteps() learning_triggers = [ triggers.PolicySavedModelTrigger( saved_model_dir, agent, train_step, interval=policy_save_interval, metadata_metrics={triggers.ENV_STEP_METADATA_KEY: env_step_metric}), triggers.ReverbCheckpointTrigger( train_step, interval=replay_buffer_save_interval, reverb_client=reverb_replay.py_client), # TODO(b/165023684): Add SIGTERM handler to checkpoint before preemption. triggers.StepPerSecondLogTrigger(train_step, interval=1000), ] agent_learner = learner.Learner( root_dir, train_step, agent, experience_dataset_fn, triggers=learning_triggers) random_policy = random_py_policy.RandomPyPolicy( collect_env.time_step_spec(), collect_env.action_spec()) initial_collect_actor = actor.Actor( collect_env, random_policy, train_step, steps_per_run=initial_collect_steps, observers=[rb_observer]) logging.info('Doing initial collect.') initial_collect_actor.run() tf_collect_policy = agent.collect_policy collect_policy = py_tf_eager_policy.PyTFEagerPolicy( tf_collect_policy, use_tf_function=True) collect_actor = actor.Actor( collect_env, collect_policy, train_step, steps_per_run=1, metrics=actor.collect_metrics(10), summary_dir=os.path.join(root_dir, learner.TRAIN_DIR), observers=[rb_observer, env_step_metric]) tf_greedy_policy = greedy_policy.GreedyPolicy(agent.policy) eval_greedy_policy = py_tf_eager_policy.PyTFEagerPolicy( tf_greedy_policy, use_tf_function=True) eval_actor = actor.Actor( eval_env, eval_greedy_policy, train_step, episodes_per_run=eval_episodes, metrics=actor.eval_metrics(eval_episodes), summary_dir=os.path.join(root_dir, 'eval'), ) if eval_interval: logging.info('Evaluating.') eval_actor.run_and_log() logging.info('Training.') for _ in range(num_iterations): collect_actor.run() agent_learner.run(iterations=1) if eval_interval and agent_learner.train_step_numpy % eval_interval == 0: logging.info('Evaluating.') eval_actor.run_and_log() rb_observer.close() reverb_server.stop() def main(_): logging.set_verbosity(logging.INFO) tf.compat.v1.enable_v2_behavior() gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_bindings) train_eval( FLAGS.root_dir, num_iterations=FLAGS.num_iterations, reverb_port=FLAGS.reverb_port, eval_interval=FLAGS.eval_interval) if __name__ == '__main__': flags.mark_flag_as_required('root_dir') app.run(main)
33.361516
79
0.733811
import functools import os from absl import app from absl import flags from absl import logging import gin import reverb import tensorflow as tf from tf_agents.agents.sac import sac_agent from tf_agents.agents.sac import tanh_normal_projection_network from tf_agents.environments import suite_mujoco from tf_agents.keras_layers import inner_reshape from tf_agents.metrics import py_metrics from tf_agents.networks import nest_map from tf_agents.networks import sequential from tf_agents.policies import greedy_policy from tf_agents.policies import py_tf_eager_policy from tf_agents.policies import random_py_policy from tf_agents.replay_buffers import reverb_replay_buffer from tf_agents.replay_buffers import reverb_utils from tf_agents.train import actor from tf_agents.train import learner from tf_agents.train import triggers from tf_agents.train.utils import spec_utils from tf_agents.train.utils import train_utils FLAGS = flags.FLAGS flags.DEFINE_string('root_dir', os.getenv('TEST_UNDECLARED_OUTPUTS_DIR'), 'Root directory for writing logs/summaries/checkpoints.') flags.DEFINE_integer( 'reverb_port', None, 'Port for reverb server, if None, use a randomly chosen unused port.') flags.DEFINE_integer('num_iterations', 3000000, 'Total number train/eval iterations to perform.') flags.DEFINE_integer( 'eval_interval', 10000, 'Number of train steps between evaluations. Set to 0 to skip.') flags.DEFINE_multi_string('gin_file', None, 'Paths to the gin-config files.') flags.DEFINE_multi_string('gin_bindings', None, 'Gin binding parameters.') dense = functools.partial( tf.keras.layers.Dense, activation=tf.keras.activations.relu, kernel_initializer='glorot_uniform') def create_fc_network(layer_units): return sequential.Sequential([dense(num_units) for num_units in layer_units]) def create_identity_layer(): return tf.keras.layers.Lambda(lambda x: x) def create_sequential_critic_network(obs_fc_layer_units, action_fc_layer_units, joint_fc_layer_units): def split_inputs(inputs): return {'observation': inputs[0], 'action': inputs[1]} obs_network = (create_fc_network(obs_fc_layer_units) if obs_fc_layer_units else create_identity_layer()) action_network = (create_fc_network(action_fc_layer_units) if action_fc_layer_units else create_identity_layer()) joint_network = (create_fc_network(joint_fc_layer_units) if joint_fc_layer_units else create_identity_layer()) value_layer = tf.keras.layers.Dense(1, kernel_initializer='glorot_uniform') return sequential.Sequential([ tf.keras.layers.Lambda(split_inputs), nest_map.NestMap({ 'observation': obs_network, 'action': action_network }), nest_map.NestFlatten(), tf.keras.layers.Concatenate(), joint_network, value_layer, inner_reshape.InnerReshape(current_shape=[1], new_shape=[]) ], name='sequential_critic') class _TanhNormalProjectionNetworkWrapper( tanh_normal_projection_network.TanhNormalProjectionNetwork): def __init__(self, sample_spec, predefined_outer_rank=1): super(_TanhNormalProjectionNetworkWrapper, self).__init__(sample_spec) self.predefined_outer_rank = predefined_outer_rank def call(self, inputs, network_state=(), **kwargs): kwargs['outer_rank'] = self.predefined_outer_rank if 'step_type' in kwargs: del kwargs['step_type'] return super(_TanhNormalProjectionNetworkWrapper, self).call(inputs, **kwargs) def create_sequential_actor_network(actor_fc_layers, action_tensor_spec): def tile_as_nest(non_nested_output): return tf.nest.map_structure(lambda _: non_nested_output, action_tensor_spec) return sequential.Sequential( [dense(num_units) for num_units in actor_fc_layers] + [tf.keras.layers.Lambda(tile_as_nest)] + [ nest_map.NestMap( tf.nest.map_structure(_TanhNormalProjectionNetworkWrapper, action_tensor_spec)) ]) @gin.configurable def train_eval( root_dir, env_name='HalfCheetah-v2', initial_collect_steps=10000, num_iterations=3200000, actor_fc_layers=(256, 256), critic_obs_fc_layers=None, critic_action_fc_layers=None, critic_joint_fc_layers=(256, 256), batch_size=256, actor_learning_rate=3e-4, critic_learning_rate=3e-4, alpha_learning_rate=3e-4, gamma=0.99, target_update_tau=0.005, target_update_period=1, reward_scale_factor=0.1, reverb_port=None, replay_capacity=1000000, policy_save_interval=10000, replay_buffer_save_interval=100000, eval_interval=10000, eval_episodes=30, debug_summaries=False, summarize_grads_and_vars=False): logging.info('Training SAC on: %s', env_name) collect_env = suite_mujoco.load(env_name) eval_env = suite_mujoco.load(env_name) _, action_tensor_spec, time_step_tensor_spec = ( spec_utils.get_tensor_specs(collect_env)) train_step = train_utils.create_train_step() actor_net = create_sequential_actor_network( actor_fc_layers=actor_fc_layers, action_tensor_spec=action_tensor_spec) critic_net = create_sequential_critic_network( obs_fc_layer_units=critic_obs_fc_layers, action_fc_layer_units=critic_action_fc_layers, joint_fc_layer_units=critic_joint_fc_layers) agent = sac_agent.SacAgent( time_step_tensor_spec, action_tensor_spec, actor_network=actor_net, critic_network=critic_net, actor_optimizer=tf.keras.optimizers.Adam( learning_rate=actor_learning_rate), critic_optimizer=tf.keras.optimizers.Adam( learning_rate=critic_learning_rate), alpha_optimizer=tf.keras.optimizers.Adam( learning_rate=alpha_learning_rate), target_update_tau=target_update_tau, target_update_period=target_update_period, td_errors_loss_fn=tf.math.squared_difference, gamma=gamma, reward_scale_factor=reward_scale_factor, gradient_clipping=None, debug_summaries=debug_summaries, summarize_grads_and_vars=summarize_grads_and_vars, train_step_counter=train_step) agent.initialize() table_name = 'uniform_table' table = reverb.Table( table_name, max_size=replay_capacity, sampler=reverb.selectors.Uniform(), remover=reverb.selectors.Fifo(), rate_limiter=reverb.rate_limiters.MinSize(1)) reverb_checkpoint_dir = os.path.join(root_dir, learner.TRAIN_DIR, learner.REPLAY_BUFFER_CHECKPOINT_DIR) reverb_checkpointer = reverb.platform.checkpointers_lib.DefaultCheckpointer( path=reverb_checkpoint_dir) reverb_server = reverb.Server([table], port=reverb_port, checkpointer=reverb_checkpointer) reverb_replay = reverb_replay_buffer.ReverbReplayBuffer( agent.collect_data_spec, sequence_length=2, table_name=table_name, local_server=reverb_server) rb_observer = reverb_utils.ReverbAddTrajectoryObserver( reverb_replay.py_client, table_name, sequence_length=2, stride_length=1) dataset = reverb_replay.as_dataset( sample_batch_size=batch_size, num_steps=2).prefetch(50) experience_dataset_fn = lambda: dataset saved_model_dir = os.path.join(root_dir, learner.POLICY_SAVED_MODEL_DIR) env_step_metric = py_metrics.EnvironmentSteps() learning_triggers = [ triggers.PolicySavedModelTrigger( saved_model_dir, agent, train_step, interval=policy_save_interval, metadata_metrics={triggers.ENV_STEP_METADATA_KEY: env_step_metric}), triggers.ReverbCheckpointTrigger( train_step, interval=replay_buffer_save_interval, reverb_client=reverb_replay.py_client), triggers.StepPerSecondLogTrigger(train_step, interval=1000), ] agent_learner = learner.Learner( root_dir, train_step, agent, experience_dataset_fn, triggers=learning_triggers) random_policy = random_py_policy.RandomPyPolicy( collect_env.time_step_spec(), collect_env.action_spec()) initial_collect_actor = actor.Actor( collect_env, random_policy, train_step, steps_per_run=initial_collect_steps, observers=[rb_observer]) logging.info('Doing initial collect.') initial_collect_actor.run() tf_collect_policy = agent.collect_policy collect_policy = py_tf_eager_policy.PyTFEagerPolicy( tf_collect_policy, use_tf_function=True) collect_actor = actor.Actor( collect_env, collect_policy, train_step, steps_per_run=1, metrics=actor.collect_metrics(10), summary_dir=os.path.join(root_dir, learner.TRAIN_DIR), observers=[rb_observer, env_step_metric]) tf_greedy_policy = greedy_policy.GreedyPolicy(agent.policy) eval_greedy_policy = py_tf_eager_policy.PyTFEagerPolicy( tf_greedy_policy, use_tf_function=True) eval_actor = actor.Actor( eval_env, eval_greedy_policy, train_step, episodes_per_run=eval_episodes, metrics=actor.eval_metrics(eval_episodes), summary_dir=os.path.join(root_dir, 'eval'), ) if eval_interval: logging.info('Evaluating.') eval_actor.run_and_log() logging.info('Training.') for _ in range(num_iterations): collect_actor.run() agent_learner.run(iterations=1) if eval_interval and agent_learner.train_step_numpy % eval_interval == 0: logging.info('Evaluating.') eval_actor.run_and_log() rb_observer.close() reverb_server.stop() def main(_): logging.set_verbosity(logging.INFO) tf.compat.v1.enable_v2_behavior() gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_bindings) train_eval( FLAGS.root_dir, num_iterations=FLAGS.num_iterations, reverb_port=FLAGS.reverb_port, eval_interval=FLAGS.eval_interval) if __name__ == '__main__': flags.mark_flag_as_required('root_dir') app.run(main)
true
true
f7169b0b69005cd6f9c943ebfaa084ff31332512
1,045
py
Python
parameter_tutorial_py/setup.py
JaehyunShim/ros2_tutorial_py
ed94477341ae6053dbd126fe5092b5cbf44ffa89
[ "Apache-2.0" ]
null
null
null
parameter_tutorial_py/setup.py
JaehyunShim/ros2_tutorial_py
ed94477341ae6053dbd126fe5092b5cbf44ffa89
[ "Apache-2.0" ]
null
null
null
parameter_tutorial_py/setup.py
JaehyunShim/ros2_tutorial_py
ed94477341ae6053dbd126fe5092b5cbf44ffa89
[ "Apache-2.0" ]
null
null
null
from glob import glob import os from setuptools import setup package_name = 'parameter_tutorial_py' setup( name=package_name, version='0.0.0', packages=[package_name], data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), (os.path.join('share', package_name), glob('launch/*.launch.py')), # (os.path.join('share', package_name), glob('param/*')), ('share/' + package_name, ['param/param.yaml']), # ('share/' + package_name, ['param']), ], install_requires=['setuptools'], zip_safe=True, maintainer='Jaehyun Shim', maintainer_email='jhshim@robotis.com', description='ROS 2 packages for parameter_tutorial_py', license='Apache 2.0', author='Jaehyun Shim', author_email='jhshim@robotis.com', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'parameter = parameter_tutorial_py.parameter:main' ], }, )
29.027778
74
0.622967
from glob import glob import os from setuptools import setup package_name = 'parameter_tutorial_py' setup( name=package_name, version='0.0.0', packages=[package_name], data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), (os.path.join('share', package_name), glob('launch/*.launch.py')), ('share/' + package_name, ['param/param.yaml']), ], install_requires=['setuptools'], zip_safe=True, maintainer='Jaehyun Shim', maintainer_email='jhshim@robotis.com', description='ROS 2 packages for parameter_tutorial_py', license='Apache 2.0', author='Jaehyun Shim', author_email='jhshim@robotis.com', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'parameter = parameter_tutorial_py.parameter:main' ], }, )
true
true
f7169bb6a32f8e404c1c0086cbe414701694aecd
2,198
py
Python
ros/src/twist_controller/twist_controller.py
ysavchenko/carnd-capstone
682eb7ed52153c667f63e7c7eb46f13584469888
[ "MIT" ]
null
null
null
ros/src/twist_controller/twist_controller.py
ysavchenko/carnd-capstone
682eb7ed52153c667f63e7c7eb46f13584469888
[ "MIT" ]
null
null
null
ros/src/twist_controller/twist_controller.py
ysavchenko/carnd-capstone
682eb7ed52153c667f63e7c7eb46f13584469888
[ "MIT" ]
null
null
null
from yaw_controller import YawController from pid import PID from lowpass import LowPassFilter import rospy GAS_DENSITY = 2.858 ONE_MPH = 0.44704 class Controller(object): def __init__(self, vehicle_mass, wheel_radius, decel_limit): self.yaw_controller = None self.throttle_controller = None self.velocity_filter = LowPassFilter(.5, .02) self.vehicle_mass = vehicle_mass self.wheel_radius = wheel_radius self.decel_limit = decel_limit self.last_time = rospy.get_time() def init_yaw(self, wheel_base, steer_ratio, min_speed, max_lat_accel, max_steer_angle): self.yaw_controller = YawController( wheel_base, steer_ratio, min_speed, max_lat_accel, max_steer_angle ) def init_throttle(self, kp, ki, kd, min_throttle, max_throttle): self.throttle_controller = PID(kp, ki, kd, min_throttle, max_throttle) def control(self, target_linear_velocity, target_angular_velocity, current_linear_velocity): if self.yaw_controller is None or self.throttle_controller is None: return 0., 0., 0. current_linear_velocity = self.velocity_filter.filt(current_linear_velocity) steering = self.yaw_controller.get_steering(target_linear_velocity, target_angular_velocity, current_linear_velocity) delta_velocity = target_linear_velocity - current_linear_velocity current_time = rospy.get_time() delta_time = current_time - self.last_time self.last_time = current_time throttle = self.throttle_controller.step(delta_velocity, delta_time) brake = 0. if target_linear_velocity == 0. and current_linear_velocity < 0.1: # Full stop throttle = 0. brake = 400 elif throttle < .1 and delta_velocity < 0: # Slow deceleration throttle = 0. deceleration = max(delta_velocity, self.decel_limit) brake = abs(deceleration) * self.vehicle_mass * self.wheel_radius return throttle, brake, steering def reset(self): self.throttle_controller.reset()
33.815385
125
0.674249
from yaw_controller import YawController from pid import PID from lowpass import LowPassFilter import rospy GAS_DENSITY = 2.858 ONE_MPH = 0.44704 class Controller(object): def __init__(self, vehicle_mass, wheel_radius, decel_limit): self.yaw_controller = None self.throttle_controller = None self.velocity_filter = LowPassFilter(.5, .02) self.vehicle_mass = vehicle_mass self.wheel_radius = wheel_radius self.decel_limit = decel_limit self.last_time = rospy.get_time() def init_yaw(self, wheel_base, steer_ratio, min_speed, max_lat_accel, max_steer_angle): self.yaw_controller = YawController( wheel_base, steer_ratio, min_speed, max_lat_accel, max_steer_angle ) def init_throttle(self, kp, ki, kd, min_throttle, max_throttle): self.throttle_controller = PID(kp, ki, kd, min_throttle, max_throttle) def control(self, target_linear_velocity, target_angular_velocity, current_linear_velocity): if self.yaw_controller is None or self.throttle_controller is None: return 0., 0., 0. current_linear_velocity = self.velocity_filter.filt(current_linear_velocity) steering = self.yaw_controller.get_steering(target_linear_velocity, target_angular_velocity, current_linear_velocity) delta_velocity = target_linear_velocity - current_linear_velocity current_time = rospy.get_time() delta_time = current_time - self.last_time self.last_time = current_time throttle = self.throttle_controller.step(delta_velocity, delta_time) brake = 0. if target_linear_velocity == 0. and current_linear_velocity < 0.1: throttle = 0. brake = 400 elif throttle < .1 and delta_velocity < 0: throttle = 0. deceleration = max(delta_velocity, self.decel_limit) brake = abs(deceleration) * self.vehicle_mass * self.wheel_radius return throttle, brake, steering def reset(self): self.throttle_controller.reset()
true
true
f7169e22e550d5a34ea898f7d6792737a32dc834
2,050
py
Python
pyJCal.py
Geeknux/jalali-calendar-widget
034d6895cead2059825a931294ef9ffce7436caa
[ "MIT" ]
1
2015-09-01T03:57:05.000Z
2015-09-01T03:57:05.000Z
pyJCal.py
Geeknux/jalali-calendar-widget
034d6895cead2059825a931294ef9ffce7436caa
[ "MIT" ]
1
2015-09-01T03:56:35.000Z
2015-09-01T03:56:35.000Z
pyJCal.py
Geeknux/jalali-calendar-widget
034d6895cead2059825a931294ef9ffce7436caa
[ "MIT" ]
null
null
null
#! /usr/bin/python2 # coding=utf-8 class pyJCal: def __init__(self): pass def div(self, a, b): return a / b def gregorian_to_jalali(self, g_y, g_m, g_d): """ this function returns result of converting ye gregorian date to jalali """ g_days_in_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) j_days_in_month = (31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29) gy = g_y - 1600 gm = g_m - 1 gd = g_d - 1 g_day_no = 365 * gy + self.div(gy+3, 4) - self.div(gy+99, 100) + self.div(gy+399, 400) i = 0 while i < gm: g_day_no += g_days_in_month[i] i += 1 if(gm > 1 and ((gy % 4 == 0 and gy % 100 != 0) or (gy % 400 == 0))): g_day_no += 1 g_day_no += gd j_day_no = g_day_no - 79 j_np = self.div(j_day_no, 12053) j_day_no = j_day_no % 12053 jy = 979 + 33 * j_np + 4 * self.div(j_day_no, 1461) j_day_no %= 1461 if j_day_no >= 365: jy += self.div(j_day_no - 1, 365) j_day_no = (j_day_no - 1) % 365 i = 0 while (i < 11 and j_day_no >= j_days_in_month[i]): j_day_no -= j_days_in_month[i] i += 1 jm = i + 1 jd = j_day_no + 1 return (jy, jm, jd) def MonthName(self, _m_num): _m_num = int(_m_num) if _m_num == 1: return 'فروردین' elif _m_num == 2: return 'اردیبهشت' elif _m_num == 3: return 'خرداد' elif _m_num == 4: return 'تیر' elif _m_num == 5: return 'مرداد' elif _m_num == 6: return 'شهریور' elif _m_num == 7: return 'مهر' elif _m_num == 8: return 'آبان' elif _m_num == 9: return 'آذر' elif _m_num == 10: return 'دی' elif _m_num == 11: return 'بهمن' elif _m_num == 12: return 'اسفند' else: return False def WeekDayName(self, _d): if _d == 'Saturday': return 'شنبه' elif _d == 'Sunday': return 'یکشنبه' elif _d == 'Monday': return 'دوشنبه' elif _d == 'Tuesday': return 'سه شنبه' elif _d == 'Wednesday': return 'چهارشنبه' elif _d == 'Thursday': return 'پنجشنبه' elif _d == 'Friday': return 'جمعه' else: return _d
19.711538
88
0.57122
class pyJCal: def __init__(self): pass def div(self, a, b): return a / b def gregorian_to_jalali(self, g_y, g_m, g_d): g_days_in_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) j_days_in_month = (31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29) gy = g_y - 1600 gm = g_m - 1 gd = g_d - 1 g_day_no = 365 * gy + self.div(gy+3, 4) - self.div(gy+99, 100) + self.div(gy+399, 400) i = 0 while i < gm: g_day_no += g_days_in_month[i] i += 1 if(gm > 1 and ((gy % 4 == 0 and gy % 100 != 0) or (gy % 400 == 0))): g_day_no += 1 g_day_no += gd j_day_no = g_day_no - 79 j_np = self.div(j_day_no, 12053) j_day_no = j_day_no % 12053 jy = 979 + 33 * j_np + 4 * self.div(j_day_no, 1461) j_day_no %= 1461 if j_day_no >= 365: jy += self.div(j_day_no - 1, 365) j_day_no = (j_day_no - 1) % 365 i = 0 while (i < 11 and j_day_no >= j_days_in_month[i]): j_day_no -= j_days_in_month[i] i += 1 jm = i + 1 jd = j_day_no + 1 return (jy, jm, jd) def MonthName(self, _m_num): _m_num = int(_m_num) if _m_num == 1: return 'فروردین' elif _m_num == 2: return 'اردیبهشت' elif _m_num == 3: return 'خرداد' elif _m_num == 4: return 'تیر' elif _m_num == 5: return 'مرداد' elif _m_num == 6: return 'شهریور' elif _m_num == 7: return 'مهر' elif _m_num == 8: return 'آبان' elif _m_num == 9: return 'آذر' elif _m_num == 10: return 'دی' elif _m_num == 11: return 'بهمن' elif _m_num == 12: return 'اسفند' else: return False def WeekDayName(self, _d): if _d == 'Saturday': return 'شنبه' elif _d == 'Sunday': return 'یکشنبه' elif _d == 'Monday': return 'دوشنبه' elif _d == 'Tuesday': return 'سه شنبه' elif _d == 'Wednesday': return 'چهارشنبه' elif _d == 'Thursday': return 'پنجشنبه' elif _d == 'Friday': return 'جمعه' else: return _d
true
true
f7169ea9d45728fbd3a7a434bf6954f50de55d91
8,833
py
Python
source/conf.py
abhivishal/website
5debb3bc7da05a018996a7fbf7d140ad8b91a66e
[ "Apache-2.0" ]
40
2015-07-24T14:11:25.000Z
2021-08-02T14:25:09.000Z
source/conf.py
abhivishal/website
5debb3bc7da05a018996a7fbf7d140ad8b91a66e
[ "Apache-2.0" ]
79
2015-01-07T20:46:42.000Z
2021-06-08T19:02:48.000Z
source/conf.py
abhivishal/website
5debb3bc7da05a018996a7fbf7d140ad8b91a66e
[ "Apache-2.0" ]
41
2015-01-29T00:10:00.000Z
2022-03-20T02:55:45.000Z
# -*- coding: utf-8 -*- # # OSU DevOps BootCamp documentation build configuration file, created by # sphinx-quickstart on Tue Oct 15 12:20:17 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo',] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'OSU DevOps BootCamp' copyright = u'2013-2017, Oregon State Unviersity' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.1' # The full version, including alpha/beta/rc tags. release = '0.0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Hieroglyph Congfig ------------------------------------------------------- # When autoslides is True, Hieroglyph will generate slides from the document # sections. If autoslides is set to False, only generate slides from the slide # directive. # This can be overridden on a per-document basis using the slideconf directive. if not os.environ.get('READTHEDOCS', None): extensions += ['hieroglyph',] autoslides = True slide_theme = 'single-level' # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' html_context = { 'display_github': True, 'github_user': 'devopsbootcamp', 'github_repo': 'website', 'github_version': 'master', 'conf_py_path': '/source/', 'source_suffix': '.rst' } # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' html_style = 'styles.css' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'OSUDevOpsBootCampdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'OSUDevOpsBootCamp.tex', u'OSU DevOps BootCamp Documentation', u'OSU OSL & OSU LUG', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'osudevopsbootcamp', u'OSU DevOps BootCamp Documentation', [u'OSU OSL & OSU LUG'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'OSUDevOpsBootCamp', u'OSU DevOps BootCamp Documentation', u'OSU OSL & OSU LUG', 'OSUDevOpsBootCamp', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' slide_theme_options = { 'custom_css': 'custom.css', 'custom_js': 'ga.js', } if not os.environ.get('READTHEDOCS', None): import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
32.355311
81
0.709498
import sys, os extensions = ['sphinx.ext.todo',] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'OSU DevOps BootCamp' copyright = u'2013-2017, Oregon State Unviersity' # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.1' # The full version, including alpha/beta/rc tags. release = '0.0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Hieroglyph Congfig ------------------------------------------------------- # When autoslides is True, Hieroglyph will generate slides from the document # sections. If autoslides is set to False, only generate slides from the slide # directive. # This can be overridden on a per-document basis using the slideconf directive. if not os.environ.get('READTHEDOCS', None): extensions += ['hieroglyph',] autoslides = True slide_theme = 'single-level' # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' html_context = { 'display_github': True, 'github_user': 'devopsbootcamp', 'github_repo': 'website', 'github_version': 'master', 'conf_py_path': '/source/', 'source_suffix': '.rst' } # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' html_style = 'styles.css' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'OSUDevOpsBootCampdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'OSUDevOpsBootCamp.tex', u'OSU DevOps BootCamp Documentation', u'OSU OSL & OSU LUG', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'osudevopsbootcamp', u'OSU DevOps BootCamp Documentation', [u'OSU OSL & OSU LUG'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'OSUDevOpsBootCamp', u'OSU DevOps BootCamp Documentation', u'OSU OSL & OSU LUG', 'OSUDevOpsBootCamp', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' slide_theme_options = { 'custom_css': 'custom.css', 'custom_js': 'ga.js', } if not os.environ.get('READTHEDOCS', None): import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
true
true
f7169eeeb7b39a8b509cb6a7cc0f4ab643571126
331
py
Python
api/app/api/endpoints/bets.py
franloza/apiestas
46978f58858b1d3822b2f80eb8948009944aa005
[ "MIT" ]
53
2019-11-19T03:02:06.000Z
2022-01-13T15:29:38.000Z
api/app/api/endpoints/bets.py
franloza/apiestas
46978f58858b1d3822b2f80eb8948009944aa005
[ "MIT" ]
3
2019-12-27T22:49:11.000Z
2021-03-31T18:59:36.000Z
api/app/api/endpoints/bets.py
franloza/apiestas
46978f58858b1d3822b2f80eb8948009944aa005
[ "MIT" ]
5
2021-04-25T13:02:48.000Z
2022-02-16T13:57:21.000Z
from fastapi import APIRouter, Depends from ...api.dependencies.bets import get_bet_by_slug_from_path from ...models.bets import Bet router = APIRouter() @router.get( '/{slug}', response_model=Bet, name="bets:get-bet" ) async def get_bet(bet=Depends(get_bet_by_slug_from_path)) -> Bet: return Bet(**bet.dict())
20.6875
65
0.719033
from fastapi import APIRouter, Depends from ...api.dependencies.bets import get_bet_by_slug_from_path from ...models.bets import Bet router = APIRouter() @router.get( '/{slug}', response_model=Bet, name="bets:get-bet" ) async def get_bet(bet=Depends(get_bet_by_slug_from_path)) -> Bet: return Bet(**bet.dict())
true
true
f7169fa15e8d91d107ba43a0da61b69e67f59f1d
34,678
py
Python
networking_sfc/tests/unit/extensions/test_flowclassifier.py
huiweics/networking-sfc
e7675aa1a31769d55740c025a39644cc6e1ca8dd
[ "Apache-2.0" ]
null
null
null
networking_sfc/tests/unit/extensions/test_flowclassifier.py
huiweics/networking-sfc
e7675aa1a31769d55740c025a39644cc6e1ca8dd
[ "Apache-2.0" ]
null
null
null
networking_sfc/tests/unit/extensions/test_flowclassifier.py
huiweics/networking-sfc
e7675aa1a31769d55740c025a39644cc6e1ca8dd
[ "Apache-2.0" ]
null
null
null
# Copyright 2015 Futurewei. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import mock from neutron.api.v2 import resource as api_res_log from neutron import manager from neutron.notifiers import nova as nova_log from neutron.tests.unit.api.v2 import test_base as test_api_v2 from neutron.tests.unit.extensions import base as test_api_v2_extension from neutron_lib import constants as const from oslo_config import cfg from oslo_utils import uuidutils from webob import exc import webtest from networking_sfc.extensions import flowclassifier as fc_ext _uuid = uuidutils.generate_uuid _get_path = test_api_v2._get_path FLOW_CLASSIFIER_PATH = (fc_ext.FLOW_CLASSIFIER_PREFIX[1:] + '/' + fc_ext.FLOW_CLASSIFIER_EXT + 's') class FlowClassifierExtensionTestCase( test_api_v2_extension.ExtensionTestCase ): fmt = 'json' def setUp(self): self._mock_unnecessary_logging() super(FlowClassifierExtensionTestCase, self).setUp() self.setup_extension( 'networking_sfc.extensions.flowclassifier.' 'FlowClassifierPluginBase', fc_ext.FLOW_CLASSIFIER_EXT, fc_ext.Flowclassifier, fc_ext.FLOW_CLASSIFIER_PREFIX[1:], plural_mappings={} ) def _mock_unnecessary_logging(self): mock_log_cfg_p = mock.patch.object(cfg, 'LOG') self.mock_log_cfg = mock_log_cfg_p.start() mock_log_manager_p = mock.patch.object(manager, 'LOG') self.mock_log_manager = mock_log_manager_p.start() mock_log_nova_p = mock.patch.object(nova_log, 'LOG') self.mock_log_nova = mock_log_nova_p.start() mock_log_api_res_log_p = mock.patch.object(api_res_log, 'LOG') self.mock_log_api_res_log = mock_log_api_res_log_p.start() def _get_expected_flow_classifier(self, data): source_port_range_min = data['flow_classifier'].get( 'source_port_range_min') if source_port_range_min is not None: source_port_range_min = int(source_port_range_min) source_port_range_max = data['flow_classifier'].get( 'source_port_range_max') if source_port_range_max is not None: source_port_range_max = int(source_port_range_max) destination_port_range_min = data['flow_classifier'].get( 'destination_port_range_min') if destination_port_range_min is not None: destination_port_range_min = int(destination_port_range_min) destination_port_range_max = data['flow_classifier'].get( 'destination_port_range_max') if destination_port_range_max is not None: destination_port_range_max = int(destination_port_range_max) return {'flow_classifier': { 'name': data['flow_classifier'].get('name') or '', 'description': data['flow_classifier'].get('description') or '', 'tenant_id': data['flow_classifier']['tenant_id'], 'project_id': data['flow_classifier']['project_id'], 'source_port_range_min': source_port_range_min, 'source_port_range_max': source_port_range_max, 'destination_port_range_min': destination_port_range_min, 'destination_port_range_max': destination_port_range_max, 'l7_parameters': data['flow_classifier'].get( 'l7_parameters') or {}, 'destination_ip_prefix': data['flow_classifier'].get( 'destination_ip_prefix'), 'source_ip_prefix': data['flow_classifier'].get( 'source_ip_prefix'), 'logical_source_port': data['flow_classifier'].get( 'logical_source_port'), 'logical_destination_port': data['flow_classifier'].get( 'logical_destination_port'), 'ethertype': data['flow_classifier'].get( 'ethertype') or 'IPv4', 'protocol': data['flow_classifier'].get( 'protocol') }} def test_create_flow_classifier(self): flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_source_port_range(self): for source_port_range_min in [None, 100, '100']: for source_port_range_max in [None, 200, '200']: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'source_port_range_min': source_port_range_min, 'source_port_range_max': source_port_range_max, 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_destination_port_range(self): for destination_port_range_min in [None, 100, '100']: for destination_port_range_max in [None, 200, '200']: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'destination_port_range_min': destination_port_range_min, 'destination_port_range_max': destination_port_range_max, 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_source_ip_prefix(self): for logical_source_ip_prefix in [ None, '10.0.0.0/8' ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'source_ip_prefix': logical_source_ip_prefix, 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_destination_ip_prefix(self): for logical_destination_ip_prefix in [ None, '10.0.0.0/8' ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'destination_ip_prefix': logical_destination_ip_prefix, 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(res.status_int, exc.HTTPCreated.code) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_logical_source_port(self): for logical_source_port in [ None, _uuid() ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': logical_source_port, 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_logical_destination_port(self): for logical_destination_port in [ None, _uuid() ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_destination_port': logical_destination_port, 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_l7_parameters(self): for l7_parameters in [None, {}]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, 'l7_parameters': l7_parameters }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_ethertype(self): for ethertype in [None, 'IPv4', 'IPv6']: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, 'ethertype': ethertype }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_protocol(self): for protocol in [ None, const.PROTO_NAME_TCP, const.PROTO_NAME_UDP, const.PROTO_NAME_ICMP ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, 'protocol': protocol }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_all_fields(self): flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'name': 'test1', 'description': 'desc', 'tenant_id': tenant_id, 'project_id': tenant_id, 'source_port_range_min': 100, 'source_port_range_max': 200, 'destination_port_range_min': 100, 'destination_port_range_max': 200, 'l7_parameters': {}, 'destination_ip_prefix': '10.0.0.0/8', 'source_ip_prefix': '10.0.0.0/8', 'logical_source_port': _uuid(), 'logical_destination_port': _uuid(), 'ethertype': None, 'protocol': None }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_invalid_l7_parameters(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'l7_parameters': {'abc': 'def'}, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_invalid_protocol(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'protocol': 'unknown', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_invalid_ethertype(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'ethertype': 'unknown', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_port_small(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'source_port_range_min': -1, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_port_large(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'source_port_range_min': 65536, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_ip_prefix_no_cidr(self): tenant_id = _uuid() data = {'flow_classifier': { 'source_ip_prefix': '10.0.0.0', 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_ip_prefix_invalid_cidr(self): tenant_id = _uuid() data = {'flow_classifier': { 'source_ip_prefix': '10.0.0.0/33', 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_port_id_nouuid(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': 'unknown', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_list(self): tenant_id = _uuid() flowclassifier_id = _uuid() return_value = [{ 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id }] instance = self.plugin.return_value instance.get_flow_classifiers.return_value = return_value res = self.api.get( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt)) instance.get_flow_classifiers.assert_called_with( mock.ANY, fields=mock.ANY, filters=mock.ANY ) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifiers', res) self.assertEqual(return_value, res['flow_classifiers']) def test_flow_classifier_list_all_fields(self): tenant_id = _uuid() flowclassifier_id = _uuid() return_value = [{ 'name': 'abc', 'description': 'abc', 'ethertype': 'IPv4', 'protocol': const.PROTO_NAME_TCP, 'source_ip_prefix': '10.0.0.0/8', 'destination_ip_prefix': '10.0.0.0/8', 'source_port_range_min': 100, 'source_port_range_max': 200, 'destination_port_range_min': 100, 'destination_port_range_max': 200, 'logical_source_port': _uuid(), 'logical_destination_port': _uuid(), 'l7_parameters': {}, 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id }] instance = self.plugin.return_value instance.get_flow_classifiers.return_value = return_value res = self.api.get( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt)) instance.get_flow_classifiers.assert_called_with( mock.ANY, fields=mock.ANY, filters=mock.ANY ) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifiers', res) self.assertEqual(return_value, res['flow_classifiers']) def test_flow_classifier_list_unknown_fields(self): tenant_id = _uuid() flowclassifier_id = _uuid() return_value = [{ 'logical_source_port': _uuid(), 'new_key': 'value', 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id }] expected_return = copy.copy(return_value) for item in expected_return: del item['new_key'] instance = self.plugin.return_value instance.get_flow_classifiers.return_value = return_value res = self.api.get( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt)) instance.get_flow_classifiers.assert_called_with( mock.ANY, fields=mock.ANY, filters=mock.ANY ) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifiers', res) self.assertEqual(expected_return, res['flow_classifiers']) def test_flow_classifier_get(self): tenant_id = _uuid() flowclassifier_id = _uuid() return_value = { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id } instance = self.plugin.return_value instance.get_flow_classifier.return_value = return_value res = self.api.get( _get_path( FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt ) ) instance.get_flow_classifier.assert_called_with( mock.ANY, flowclassifier_id, fields=mock.ANY ) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_flow_classifier_update(self): tenant_id = _uuid() flowclassifier_id = _uuid() update_data = {'flow_classifier': { 'name': 'new_name', 'description': 'new_desc', }} return_value = { 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id } instance = self.plugin.return_value instance.update_flow_classifier.return_value = return_value res = self.api.put( _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(update_data)) instance.update_flow_classifier.assert_called_with( mock.ANY, flowclassifier_id, flow_classifier=update_data) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_flow_classifier_update_source_port_range_min(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'source_port_range_min': 100, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_source_port_range_max(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'source_port_range_max': 100, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_destination_port_range_min(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'destination_port_range_min': 100, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_destination_port_range_max(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'destination_port_range_max': 100, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_source_ip_prefix(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'source_ip_prefix': '10.0.0.0/8', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_destination_ip_prefix(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'destination_ip_prefix': '10.0.0.0/8', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_logical_source_port(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_logical_destination_port(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'logical_destination_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_ethertype(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'ethertype': None, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_protocol(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'protococol': None, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_l7_parameters(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'l7_parameters': {}, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_delete(self): self._test_entity_delete('flow_classifier')
41.630252
78
0.603639
import copy import mock from neutron.api.v2 import resource as api_res_log from neutron import manager from neutron.notifiers import nova as nova_log from neutron.tests.unit.api.v2 import test_base as test_api_v2 from neutron.tests.unit.extensions import base as test_api_v2_extension from neutron_lib import constants as const from oslo_config import cfg from oslo_utils import uuidutils from webob import exc import webtest from networking_sfc.extensions import flowclassifier as fc_ext _uuid = uuidutils.generate_uuid _get_path = test_api_v2._get_path FLOW_CLASSIFIER_PATH = (fc_ext.FLOW_CLASSIFIER_PREFIX[1:] + '/' + fc_ext.FLOW_CLASSIFIER_EXT + 's') class FlowClassifierExtensionTestCase( test_api_v2_extension.ExtensionTestCase ): fmt = 'json' def setUp(self): self._mock_unnecessary_logging() super(FlowClassifierExtensionTestCase, self).setUp() self.setup_extension( 'networking_sfc.extensions.flowclassifier.' 'FlowClassifierPluginBase', fc_ext.FLOW_CLASSIFIER_EXT, fc_ext.Flowclassifier, fc_ext.FLOW_CLASSIFIER_PREFIX[1:], plural_mappings={} ) def _mock_unnecessary_logging(self): mock_log_cfg_p = mock.patch.object(cfg, 'LOG') self.mock_log_cfg = mock_log_cfg_p.start() mock_log_manager_p = mock.patch.object(manager, 'LOG') self.mock_log_manager = mock_log_manager_p.start() mock_log_nova_p = mock.patch.object(nova_log, 'LOG') self.mock_log_nova = mock_log_nova_p.start() mock_log_api_res_log_p = mock.patch.object(api_res_log, 'LOG') self.mock_log_api_res_log = mock_log_api_res_log_p.start() def _get_expected_flow_classifier(self, data): source_port_range_min = data['flow_classifier'].get( 'source_port_range_min') if source_port_range_min is not None: source_port_range_min = int(source_port_range_min) source_port_range_max = data['flow_classifier'].get( 'source_port_range_max') if source_port_range_max is not None: source_port_range_max = int(source_port_range_max) destination_port_range_min = data['flow_classifier'].get( 'destination_port_range_min') if destination_port_range_min is not None: destination_port_range_min = int(destination_port_range_min) destination_port_range_max = data['flow_classifier'].get( 'destination_port_range_max') if destination_port_range_max is not None: destination_port_range_max = int(destination_port_range_max) return {'flow_classifier': { 'name': data['flow_classifier'].get('name') or '', 'description': data['flow_classifier'].get('description') or '', 'tenant_id': data['flow_classifier']['tenant_id'], 'project_id': data['flow_classifier']['project_id'], 'source_port_range_min': source_port_range_min, 'source_port_range_max': source_port_range_max, 'destination_port_range_min': destination_port_range_min, 'destination_port_range_max': destination_port_range_max, 'l7_parameters': data['flow_classifier'].get( 'l7_parameters') or {}, 'destination_ip_prefix': data['flow_classifier'].get( 'destination_ip_prefix'), 'source_ip_prefix': data['flow_classifier'].get( 'source_ip_prefix'), 'logical_source_port': data['flow_classifier'].get( 'logical_source_port'), 'logical_destination_port': data['flow_classifier'].get( 'logical_destination_port'), 'ethertype': data['flow_classifier'].get( 'ethertype') or 'IPv4', 'protocol': data['flow_classifier'].get( 'protocol') }} def test_create_flow_classifier(self): flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_source_port_range(self): for source_port_range_min in [None, 100, '100']: for source_port_range_max in [None, 200, '200']: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'source_port_range_min': source_port_range_min, 'source_port_range_max': source_port_range_max, 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_destination_port_range(self): for destination_port_range_min in [None, 100, '100']: for destination_port_range_max in [None, 200, '200']: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'destination_port_range_min': destination_port_range_min, 'destination_port_range_max': destination_port_range_max, 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_source_ip_prefix(self): for logical_source_ip_prefix in [ None, '10.0.0.0/8' ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'source_ip_prefix': logical_source_ip_prefix, 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_destination_ip_prefix(self): for logical_destination_ip_prefix in [ None, '10.0.0.0/8' ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'destination_ip_prefix': logical_destination_ip_prefix, 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(res.status_int, exc.HTTPCreated.code) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_logical_source_port(self): for logical_source_port in [ None, _uuid() ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': logical_source_port, 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_logical_destination_port(self): for logical_destination_port in [ None, _uuid() ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_destination_port': logical_destination_port, 'tenant_id': tenant_id, 'project_id': tenant_id, }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_l7_parameters(self): for l7_parameters in [None, {}]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, 'l7_parameters': l7_parameters }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_ethertype(self): for ethertype in [None, 'IPv4', 'IPv6']: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, 'ethertype': ethertype }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_protocol(self): for protocol in [ None, const.PROTO_NAME_TCP, const.PROTO_NAME_UDP, const.PROTO_NAME_ICMP ]: flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, 'protocol': protocol }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_all_fields(self): flowclassifier_id = _uuid() tenant_id = _uuid() data = {'flow_classifier': { 'name': 'test1', 'description': 'desc', 'tenant_id': tenant_id, 'project_id': tenant_id, 'source_port_range_min': 100, 'source_port_range_max': 200, 'destination_port_range_min': 100, 'destination_port_range_max': 200, 'l7_parameters': {}, 'destination_ip_prefix': '10.0.0.0/8', 'source_ip_prefix': '10.0.0.0/8', 'logical_source_port': _uuid(), 'logical_destination_port': _uuid(), 'ethertype': None, 'protocol': None }} expected_data = self._get_expected_flow_classifier(data) return_value = copy.copy(expected_data['flow_classifier']) return_value.update({'id': flowclassifier_id}) instance = self.plugin.return_value instance.create_flow_classifier.return_value = return_value res = self.api.post( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_flow_classifier.assert_called_with( mock.ANY, flow_classifier=expected_data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_create_flow_classifier_invalid_l7_parameters(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'l7_parameters': {'abc': 'def'}, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_invalid_protocol(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'protocol': 'unknown', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_invalid_ethertype(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'ethertype': 'unknown', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_port_small(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'source_port_range_min': -1, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_port_large(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'source_port_range_min': 65536, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_ip_prefix_no_cidr(self): tenant_id = _uuid() data = {'flow_classifier': { 'source_ip_prefix': '10.0.0.0', 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_ip_prefix_invalid_cidr(self): tenant_id = _uuid() data = {'flow_classifier': { 'source_ip_prefix': '10.0.0.0/33', 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_create_flow_classifier_port_id_nouuid(self): tenant_id = _uuid() data = {'flow_classifier': { 'logical_source_port': 'unknown', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.post, _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_list(self): tenant_id = _uuid() flowclassifier_id = _uuid() return_value = [{ 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id }] instance = self.plugin.return_value instance.get_flow_classifiers.return_value = return_value res = self.api.get( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt)) instance.get_flow_classifiers.assert_called_with( mock.ANY, fields=mock.ANY, filters=mock.ANY ) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifiers', res) self.assertEqual(return_value, res['flow_classifiers']) def test_flow_classifier_list_all_fields(self): tenant_id = _uuid() flowclassifier_id = _uuid() return_value = [{ 'name': 'abc', 'description': 'abc', 'ethertype': 'IPv4', 'protocol': const.PROTO_NAME_TCP, 'source_ip_prefix': '10.0.0.0/8', 'destination_ip_prefix': '10.0.0.0/8', 'source_port_range_min': 100, 'source_port_range_max': 200, 'destination_port_range_min': 100, 'destination_port_range_max': 200, 'logical_source_port': _uuid(), 'logical_destination_port': _uuid(), 'l7_parameters': {}, 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id }] instance = self.plugin.return_value instance.get_flow_classifiers.return_value = return_value res = self.api.get( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt)) instance.get_flow_classifiers.assert_called_with( mock.ANY, fields=mock.ANY, filters=mock.ANY ) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifiers', res) self.assertEqual(return_value, res['flow_classifiers']) def test_flow_classifier_list_unknown_fields(self): tenant_id = _uuid() flowclassifier_id = _uuid() return_value = [{ 'logical_source_port': _uuid(), 'new_key': 'value', 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id }] expected_return = copy.copy(return_value) for item in expected_return: del item['new_key'] instance = self.plugin.return_value instance.get_flow_classifiers.return_value = return_value res = self.api.get( _get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt)) instance.get_flow_classifiers.assert_called_with( mock.ANY, fields=mock.ANY, filters=mock.ANY ) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifiers', res) self.assertEqual(expected_return, res['flow_classifiers']) def test_flow_classifier_get(self): tenant_id = _uuid() flowclassifier_id = _uuid() return_value = { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id } instance = self.plugin.return_value instance.get_flow_classifier.return_value = return_value res = self.api.get( _get_path( FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt ) ) instance.get_flow_classifier.assert_called_with( mock.ANY, flowclassifier_id, fields=mock.ANY ) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_flow_classifier_update(self): tenant_id = _uuid() flowclassifier_id = _uuid() update_data = {'flow_classifier': { 'name': 'new_name', 'description': 'new_desc', }} return_value = { 'tenant_id': tenant_id, 'project_id': tenant_id, 'id': flowclassifier_id } instance = self.plugin.return_value instance.update_flow_classifier.return_value = return_value res = self.api.put( _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(update_data)) instance.update_flow_classifier.assert_called_with( mock.ANY, flowclassifier_id, flow_classifier=update_data) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('flow_classifier', res) self.assertEqual(return_value, res['flow_classifier']) def test_flow_classifier_update_source_port_range_min(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'source_port_range_min': 100, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_source_port_range_max(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'source_port_range_max': 100, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_destination_port_range_min(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'destination_port_range_min': 100, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_destination_port_range_max(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'destination_port_range_max': 100, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_source_ip_prefix(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'source_ip_prefix': '10.0.0.0/8', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_destination_ip_prefix(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'destination_ip_prefix': '10.0.0.0/8', 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_logical_source_port(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'logical_source_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_logical_destination_port(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'logical_destination_port': _uuid(), 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_ethertype(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'ethertype': None, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_protocol(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'protococol': None, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_update_l7_parameters(self): tenant_id = _uuid() flowclassifier_id = _uuid() data = {'flow_classifier': { 'l7_parameters': {}, 'tenant_id': tenant_id, 'project_id': tenant_id, }} self.assertRaises( webtest.app.AppError, self.api.put, _get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id, fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) def test_flow_classifier_delete(self): self._test_entity_delete('flow_classifier')
true
true
f716a0394e3827031c5c048b941822b24f227531
7,848
py
Python
research/compression/entropy_coder/core/entropy_coder_train.py
jdavidagudelo/tensorflow-models
6f019beec73b01861363bf717706e27f4210b979
[ "Apache-2.0" ]
1
2021-05-17T01:42:29.000Z
2021-05-17T01:42:29.000Z
research/compression/entropy_coder/core/entropy_coder_train.py
jdavidagudelo/tensorflow-models
6f019beec73b01861363bf717706e27f4210b979
[ "Apache-2.0" ]
null
null
null
research/compression/entropy_coder/core/entropy_coder_train.py
jdavidagudelo/tensorflow-models
6f019beec73b01861363bf717706e27f4210b979
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Train an entropy coder model.""" import time import tensorflow as tf from research.compression.entropy_coder.core import code_loader from research.compression.entropy_coder.core import config_helper # pylint: enable=unused-import from research.compression.entropy_coder.model import model_factory FLAGS = tf.app.flags.FLAGS # Hardware resources configuration. tf.app.flags.DEFINE_string('master', '', """Name of the TensorFlow master to use.""") tf.app.flags.DEFINE_string('train_dir', None, """Directory where to write event logs.""") tf.app.flags.DEFINE_integer('task', None, """Task id of the replica running the training.""") tf.app.flags.DEFINE_integer('ps_tasks', 0, """Number of tasks in the ps job. If 0 no ps job is used.""") # Model selection and configuration. tf.app.flags.DEFINE_string('model', None, """Underlying encoder model.""") tf.app.flags.DEFINE_string('model_config', None, """Model config protobuf given as text file.""") # Training data and parameters configuration. tf.app.flags.DEFINE_string('input_config', None, """Path to the training input config file.""") tf.app.flags.DEFINE_string('train_config', None, """Path to the training experiment config file.""") def train(): if FLAGS.train_dir is None: raise ValueError('Parameter train_dir must be provided') if FLAGS.task is None: raise ValueError('Parameter task must be provided') if FLAGS.model is None: raise ValueError('Parameter model must be provided') input_config_string = config_helper.GetConfigString(FLAGS.input_config) input_config = config_helper.InputConfig(input_config_string) # Training parameters. train_config_string = config_helper.GetConfigString(FLAGS.train_config) train_config = config_helper.TrainConfig(train_config_string) batch_size = train_config.batch_size initial_learning_rate = train_config.learning_rate decay_rate = train_config.decay_rate samples_per_decay = train_config.samples_per_decay # Parameters for learning-rate decay. # The formula is decay_rate ** floor(steps / decay_steps). decay_steps = samples_per_decay / batch_size decay_steps = max(decay_steps, 1) first_code = code_loader.ReadFirstCode(input_config.data) first_code_height = ( first_code.features.feature['code_shape'].int64_list.value[0]) first_code_width = ( first_code.features.feature['code_shape'].int64_list.value[1]) max_bit_depth = ( first_code.features.feature['code_shape'].int64_list.value[2]) print('Maximum code depth: {}'.format(max_bit_depth)) with tf.Graph().as_default(): ps_ops = ["Variable", "VariableV2", "AutoReloadVariable", "VarHandleOp"] with tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks, ps_ops=ps_ops)): codes = code_loader.LoadBinaryCode( input_config=input_config, batch_size=batch_size) if input_config.unique_code_size: print('Input code size: {} x {}'.format(first_code_height, first_code_width)) codes.set_shape( [batch_size, first_code_height, first_code_width, max_bit_depth]) else: codes.set_shape([batch_size, None, None, max_bit_depth]) codes_effective_shape = tf.shape(codes) global_step = tf.contrib.framework.create_global_step() # Apply learning-rate decay. learning_rate = tf.train.exponential_decay( learning_rate=initial_learning_rate, global_step=global_step, decay_steps=decay_steps, decay_rate=decay_rate, staircase=True) tf.summary.scalar('Learning Rate', learning_rate) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, epsilon=1.0) # Create the entropy coder model. model = model_factory.GetModelRegistry().CreateModel(FLAGS.model) model_config_string = config_helper.GetConfigString(FLAGS.model_config) model.Initialize(global_step, optimizer, model_config_string) model.BuildGraph(codes) summary_op = tf.summary.merge_all() # Verify that the model can actually be trained. if model.train_op is None: raise ValueError('Input model {} is not trainable'.format(FLAGS.model)) # We disable the summary thread run by Supervisor class by passing # summary_op=None. We still pass save_summaries_secs because it is used by # the global step counter thread. is_chief = (FLAGS.task == 0) sv = tf.train.Supervisor(logdir=FLAGS.train_dir, is_chief=is_chief, global_step=global_step, # saver=model.saver, summary_op=None, save_summaries_secs=120, save_model_secs=600, recovery_wait_secs=30) sess = sv.PrepareSession(FLAGS.master) sv.StartQueueRunners(sess) step = sess.run(global_step) print('Trainer initial step: {}.'.format(step)) # Once everything has been setup properly, save the configs. if is_chief: config_helper.SaveConfig(FLAGS.train_dir, 'input_config.json', input_config_string) config_helper.SaveConfig(FLAGS.train_dir, 'model_config.json', model_config_string) config_helper.SaveConfig(FLAGS.train_dir, 'train_config.json', train_config_string) # Train the model. next_summary_time = time.time() while not sv.ShouldStop(): feed_dict = None # Once in a while, update the summaries on the chief worker. if is_chief and next_summary_time < time.time(): summary_str = sess.run(summary_op, feed_dict=feed_dict) sv.SummaryComputed(sess, summary_str) next_summary_time = time.time() + sv.save_summaries_secs else: tf_tensors = { 'train': model.train_op, 'code_length': model.average_code_length } np_tensors = sess.run(tf_tensors, feed_dict=feed_dict) print(np_tensors['code_length']) sv.Stop() def main(argv=None): # pylint: disable=unused-argument train() if __name__ == '__main__': tf.app.run()
43.120879
87
0.605377
import time import tensorflow as tf from research.compression.entropy_coder.core import code_loader from research.compression.entropy_coder.core import config_helper from research.compression.entropy_coder.model import model_factory FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('master', '', """Name of the TensorFlow master to use.""") tf.app.flags.DEFINE_string('train_dir', None, """Directory where to write event logs.""") tf.app.flags.DEFINE_integer('task', None, """Task id of the replica running the training.""") tf.app.flags.DEFINE_integer('ps_tasks', 0, """Number of tasks in the ps job. If 0 no ps job is used.""") tf.app.flags.DEFINE_string('model', None, """Underlying encoder model.""") tf.app.flags.DEFINE_string('model_config', None, """Model config protobuf given as text file.""") tf.app.flags.DEFINE_string('input_config', None, """Path to the training input config file.""") tf.app.flags.DEFINE_string('train_config', None, """Path to the training experiment config file.""") def train(): if FLAGS.train_dir is None: raise ValueError('Parameter train_dir must be provided') if FLAGS.task is None: raise ValueError('Parameter task must be provided') if FLAGS.model is None: raise ValueError('Parameter model must be provided') input_config_string = config_helper.GetConfigString(FLAGS.input_config) input_config = config_helper.InputConfig(input_config_string) train_config_string = config_helper.GetConfigString(FLAGS.train_config) train_config = config_helper.TrainConfig(train_config_string) batch_size = train_config.batch_size initial_learning_rate = train_config.learning_rate decay_rate = train_config.decay_rate samples_per_decay = train_config.samples_per_decay decay_steps = samples_per_decay / batch_size decay_steps = max(decay_steps, 1) first_code = code_loader.ReadFirstCode(input_config.data) first_code_height = ( first_code.features.feature['code_shape'].int64_list.value[0]) first_code_width = ( first_code.features.feature['code_shape'].int64_list.value[1]) max_bit_depth = ( first_code.features.feature['code_shape'].int64_list.value[2]) print('Maximum code depth: {}'.format(max_bit_depth)) with tf.Graph().as_default(): ps_ops = ["Variable", "VariableV2", "AutoReloadVariable", "VarHandleOp"] with tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks, ps_ops=ps_ops)): codes = code_loader.LoadBinaryCode( input_config=input_config, batch_size=batch_size) if input_config.unique_code_size: print('Input code size: {} x {}'.format(first_code_height, first_code_width)) codes.set_shape( [batch_size, first_code_height, first_code_width, max_bit_depth]) else: codes.set_shape([batch_size, None, None, max_bit_depth]) codes_effective_shape = tf.shape(codes) global_step = tf.contrib.framework.create_global_step() learning_rate = tf.train.exponential_decay( learning_rate=initial_learning_rate, global_step=global_step, decay_steps=decay_steps, decay_rate=decay_rate, staircase=True) tf.summary.scalar('Learning Rate', learning_rate) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, epsilon=1.0) model = model_factory.GetModelRegistry().CreateModel(FLAGS.model) model_config_string = config_helper.GetConfigString(FLAGS.model_config) model.Initialize(global_step, optimizer, model_config_string) model.BuildGraph(codes) summary_op = tf.summary.merge_all() if model.train_op is None: raise ValueError('Input model {} is not trainable'.format(FLAGS.model)) is_chief = (FLAGS.task == 0) sv = tf.train.Supervisor(logdir=FLAGS.train_dir, is_chief=is_chief, global_step=global_step, summary_op=None, save_summaries_secs=120, save_model_secs=600, recovery_wait_secs=30) sess = sv.PrepareSession(FLAGS.master) sv.StartQueueRunners(sess) step = sess.run(global_step) print('Trainer initial step: {}.'.format(step)) if is_chief: config_helper.SaveConfig(FLAGS.train_dir, 'input_config.json', input_config_string) config_helper.SaveConfig(FLAGS.train_dir, 'model_config.json', model_config_string) config_helper.SaveConfig(FLAGS.train_dir, 'train_config.json', train_config_string) next_summary_time = time.time() while not sv.ShouldStop(): feed_dict = None if is_chief and next_summary_time < time.time(): summary_str = sess.run(summary_op, feed_dict=feed_dict) sv.SummaryComputed(sess, summary_str) next_summary_time = time.time() + sv.save_summaries_secs else: tf_tensors = { 'train': model.train_op, 'code_length': model.average_code_length } np_tensors = sess.run(tf_tensors, feed_dict=feed_dict) print(np_tensors['code_length']) sv.Stop() def main(argv=None): train() if __name__ == '__main__': tf.app.run()
true
true
f716a0a3d08f1b810ae639fdca8086b153407a06
260,784
py
Python
instances/passenger_demand/pas-20210422-1717-int14000000000000001e/48.py
LHcau/scheduling-shared-passenger-and-freight-transport-on-a-fixed-infrastructure
bba1e6af5bc8d9deaa2dc3b83f6fe9ddf15d2a11
[ "BSD-3-Clause" ]
null
null
null
instances/passenger_demand/pas-20210422-1717-int14000000000000001e/48.py
LHcau/scheduling-shared-passenger-and-freight-transport-on-a-fixed-infrastructure
bba1e6af5bc8d9deaa2dc3b83f6fe9ddf15d2a11
[ "BSD-3-Clause" ]
null
null
null
instances/passenger_demand/pas-20210422-1717-int14000000000000001e/48.py
LHcau/scheduling-shared-passenger-and-freight-transport-on-a-fixed-infrastructure
bba1e6af5bc8d9deaa2dc3b83f6fe9ddf15d2a11
[ "BSD-3-Clause" ]
null
null
null
""" PASSENGERS """ numPassengers = 26645 passenger_arriving = ( (9, 10, 5, 5, 3, 2, 2, 3, 3, 1, 1, 0, 0, 6, 9, 0, 8, 12, 3, 4, 1, 0, 2, 2, 2, 0), # 0 (5, 10, 9, 11, 6, 2, 0, 5, 1, 1, 1, 0, 0, 11, 5, 5, 6, 6, 1, 2, 2, 1, 4, 0, 0, 0), # 1 (7, 9, 3, 3, 3, 3, 3, 5, 4, 4, 2, 0, 0, 9, 6, 5, 7, 9, 1, 5, 4, 2, 2, 2, 2, 0), # 2 (5, 10, 11, 9, 12, 3, 6, 6, 4, 1, 0, 0, 0, 6, 10, 2, 8, 8, 8, 2, 2, 3, 2, 2, 0, 0), # 3 (11, 9, 6, 8, 7, 3, 4, 5, 4, 1, 0, 0, 0, 8, 12, 3, 5, 10, 3, 0, 4, 1, 1, 0, 3, 0), # 4 (11, 9, 9, 13, 3, 3, 7, 7, 4, 2, 0, 2, 0, 7, 13, 7, 8, 9, 5, 5, 1, 2, 5, 1, 1, 0), # 5 (12, 13, 8, 8, 8, 4, 1, 4, 3, 4, 3, 2, 0, 9, 8, 7, 9, 6, 2, 7, 3, 6, 3, 0, 1, 0), # 6 (12, 8, 8, 11, 13, 3, 3, 1, 4, 1, 1, 0, 0, 12, 7, 11, 4, 9, 4, 3, 2, 3, 2, 1, 1, 0), # 7 (14, 11, 17, 10, 8, 3, 3, 2, 3, 1, 3, 0, 0, 11, 7, 9, 6, 11, 2, 7, 4, 1, 3, 1, 0, 0), # 8 (11, 10, 7, 9, 8, 8, 7, 5, 5, 0, 3, 3, 0, 17, 12, 9, 6, 10, 9, 4, 2, 3, 2, 4, 1, 0), # 9 (10, 12, 11, 10, 7, 3, 6, 3, 7, 3, 2, 2, 0, 18, 13, 12, 9, 12, 6, 2, 3, 6, 2, 3, 2, 0), # 10 (15, 11, 10, 11, 12, 7, 4, 3, 3, 1, 3, 2, 0, 10, 5, 13, 8, 12, 6, 6, 3, 1, 1, 4, 1, 0), # 11 (11, 16, 10, 11, 9, 2, 7, 4, 3, 3, 1, 2, 0, 17, 8, 9, 5, 8, 5, 5, 0, 6, 4, 1, 1, 0), # 12 (11, 17, 10, 10, 6, 7, 4, 2, 6, 1, 3, 1, 0, 14, 12, 4, 3, 5, 6, 4, 5, 3, 7, 3, 1, 0), # 13 (12, 21, 12, 12, 11, 7, 4, 4, 4, 3, 5, 0, 0, 10, 12, 6, 7, 12, 6, 7, 1, 4, 4, 0, 0, 0), # 14 (6, 12, 9, 21, 12, 3, 3, 4, 6, 2, 1, 2, 0, 9, 19, 8, 3, 6, 7, 7, 6, 8, 0, 0, 2, 0), # 15 (7, 12, 10, 13, 12, 7, 5, 4, 4, 3, 2, 3, 0, 12, 8, 4, 6, 14, 10, 4, 2, 4, 4, 1, 1, 0), # 16 (15, 15, 18, 15, 7, 9, 4, 3, 5, 6, 3, 1, 0, 12, 10, 7, 11, 10, 6, 2, 5, 7, 3, 1, 0, 0), # 17 (14, 14, 16, 17, 15, 4, 6, 4, 4, 1, 2, 1, 0, 16, 17, 7, 4, 7, 7, 9, 5, 6, 4, 2, 2, 0), # 18 (23, 16, 12, 13, 6, 6, 6, 3, 7, 0, 1, 1, 0, 17, 18, 11, 11, 15, 13, 6, 3, 5, 6, 4, 2, 0), # 19 (12, 12, 13, 13, 10, 7, 6, 4, 6, 2, 2, 1, 0, 10, 17, 13, 7, 11, 7, 5, 5, 6, 5, 4, 1, 0), # 20 (16, 18, 12, 13, 8, 6, 2, 6, 11, 2, 1, 1, 0, 7, 12, 10, 10, 16, 4, 4, 7, 4, 3, 1, 2, 0), # 21 (14, 13, 8, 11, 7, 7, 2, 3, 9, 4, 2, 0, 0, 18, 9, 6, 12, 12, 7, 3, 3, 3, 8, 0, 3, 0), # 22 (16, 9, 10, 8, 14, 9, 6, 2, 9, 3, 2, 1, 0, 16, 21, 9, 4, 5, 7, 6, 6, 1, 4, 1, 1, 0), # 23 (11, 13, 11, 10, 6, 4, 10, 6, 6, 1, 5, 1, 0, 18, 17, 16, 3, 12, 13, 8, 2, 4, 1, 4, 1, 0), # 24 (11, 16, 17, 7, 12, 5, 8, 5, 6, 2, 0, 2, 0, 10, 14, 10, 7, 20, 5, 12, 4, 3, 3, 3, 2, 0), # 25 (18, 15, 18, 8, 12, 4, 14, 2, 7, 1, 1, 1, 0, 9, 10, 10, 9, 16, 3, 4, 2, 4, 4, 1, 1, 0), # 26 (9, 9, 8, 9, 5, 7, 11, 5, 8, 2, 3, 1, 0, 10, 13, 9, 8, 12, 13, 3, 1, 3, 4, 1, 1, 0), # 27 (18, 14, 17, 16, 17, 2, 7, 7, 7, 7, 2, 2, 0, 20, 13, 12, 8, 7, 1, 4, 2, 6, 1, 2, 2, 0), # 28 (16, 16, 9, 15, 6, 4, 4, 7, 5, 3, 8, 1, 0, 12, 14, 11, 9, 11, 7, 2, 7, 2, 7, 6, 0, 0), # 29 (13, 12, 17, 14, 12, 7, 9, 4, 2, 1, 3, 0, 0, 22, 14, 9, 9, 20, 6, 9, 3, 11, 3, 0, 2, 0), # 30 (17, 9, 10, 22, 14, 6, 4, 2, 3, 5, 3, 0, 0, 19, 13, 9, 7, 15, 3, 2, 3, 5, 2, 1, 1, 0), # 31 (12, 14, 16, 12, 11, 11, 5, 5, 6, 1, 2, 1, 0, 15, 12, 13, 7, 8, 13, 4, 5, 4, 7, 1, 2, 0), # 32 (11, 16, 15, 17, 3, 7, 1, 6, 6, 1, 4, 1, 0, 18, 10, 9, 8, 14, 2, 3, 3, 5, 8, 1, 1, 0), # 33 (8, 11, 12, 15, 18, 9, 4, 6, 5, 2, 4, 0, 0, 13, 13, 5, 4, 11, 7, 6, 5, 2, 2, 1, 0, 0), # 34 (23, 16, 11, 5, 13, 3, 4, 4, 4, 3, 3, 1, 0, 13, 12, 8, 6, 9, 7, 4, 5, 6, 6, 6, 1, 0), # 35 (13, 12, 17, 16, 14, 3, 4, 4, 5, 3, 1, 0, 0, 11, 5, 6, 11, 6, 9, 6, 3, 6, 5, 1, 1, 0), # 36 (15, 9, 13, 12, 8, 5, 9, 8, 8, 1, 1, 1, 0, 22, 18, 11, 7, 14, 11, 8, 2, 5, 7, 3, 0, 0), # 37 (15, 14, 16, 13, 8, 4, 4, 4, 4, 6, 1, 1, 0, 13, 8, 16, 3, 4, 7, 7, 3, 7, 6, 2, 1, 0), # 38 (16, 17, 8, 14, 9, 4, 4, 3, 6, 0, 4, 0, 0, 17, 15, 11, 7, 13, 6, 4, 3, 5, 6, 0, 0, 0), # 39 (11, 13, 11, 7, 9, 3, 1, 6, 8, 3, 3, 0, 0, 15, 7, 6, 12, 11, 6, 5, 7, 5, 6, 3, 1, 0), # 40 (15, 11, 11, 7, 10, 5, 6, 3, 8, 5, 1, 1, 0, 9, 9, 13, 7, 9, 12, 6, 3, 3, 3, 3, 1, 0), # 41 (21, 12, 14, 12, 7, 0, 4, 5, 4, 0, 0, 2, 0, 22, 14, 7, 4, 14, 13, 6, 5, 7, 6, 1, 0, 0), # 42 (17, 16, 8, 12, 13, 1, 7, 4, 6, 1, 2, 0, 0, 15, 5, 9, 8, 13, 4, 9, 4, 1, 3, 2, 1, 0), # 43 (11, 17, 16, 10, 7, 5, 7, 4, 4, 3, 1, 4, 0, 18, 14, 8, 8, 15, 7, 5, 7, 4, 4, 0, 3, 0), # 44 (12, 14, 12, 14, 10, 4, 4, 4, 3, 2, 1, 2, 0, 13, 13, 13, 8, 6, 5, 5, 2, 4, 2, 4, 1, 0), # 45 (18, 21, 10, 16, 12, 4, 4, 6, 6, 3, 1, 0, 0, 8, 5, 7, 7, 13, 8, 5, 4, 10, 2, 0, 3, 0), # 46 (7, 10, 11, 16, 9, 8, 5, 3, 8, 0, 3, 1, 0, 20, 17, 8, 3, 7, 12, 6, 4, 7, 4, 2, 3, 0), # 47 (19, 12, 8, 5, 7, 4, 3, 3, 5, 3, 1, 1, 0, 9, 7, 12, 11, 19, 9, 8, 4, 8, 2, 3, 1, 0), # 48 (9, 7, 14, 20, 17, 2, 7, 3, 4, 3, 4, 3, 0, 13, 11, 10, 9, 13, 7, 4, 3, 3, 6, 1, 1, 0), # 49 (15, 21, 13, 12, 7, 6, 7, 4, 4, 1, 1, 2, 0, 18, 12, 11, 8, 13, 10, 7, 2, 4, 6, 3, 2, 0), # 50 (11, 9, 13, 15, 9, 2, 6, 2, 4, 7, 1, 2, 0, 21, 18, 9, 9, 14, 5, 5, 1, 5, 3, 3, 3, 0), # 51 (15, 15, 11, 10, 8, 4, 3, 5, 6, 1, 1, 1, 0, 7, 7, 12, 11, 14, 5, 5, 2, 4, 0, 1, 3, 0), # 52 (11, 11, 8, 13, 9, 4, 5, 5, 2, 3, 3, 1, 0, 13, 15, 8, 4, 16, 5, 6, 6, 5, 3, 2, 1, 0), # 53 (17, 18, 6, 15, 9, 4, 5, 6, 10, 4, 2, 2, 0, 21, 17, 14, 8, 16, 6, 4, 6, 6, 3, 1, 1, 0), # 54 (10, 12, 18, 10, 11, 7, 1, 7, 7, 3, 1, 0, 0, 14, 7, 15, 7, 7, 7, 5, 3, 1, 10, 0, 0, 0), # 55 (6, 12, 13, 14, 15, 2, 4, 4, 4, 1, 3, 1, 0, 21, 16, 11, 6, 15, 4, 7, 7, 5, 4, 4, 1, 0), # 56 (6, 16, 19, 17, 4, 4, 7, 6, 8, 2, 0, 0, 0, 19, 14, 6, 2, 13, 10, 6, 4, 4, 0, 2, 1, 0), # 57 (15, 13, 15, 19, 8, 3, 6, 6, 5, 0, 2, 2, 0, 14, 9, 8, 6, 14, 3, 9, 6, 7, 4, 4, 1, 0), # 58 (13, 4, 10, 14, 7, 4, 7, 3, 7, 6, 0, 2, 0, 10, 12, 9, 10, 11, 6, 3, 5, 7, 4, 2, 0, 0), # 59 (14, 24, 6, 17, 14, 6, 4, 1, 1, 2, 1, 3, 0, 14, 10, 12, 12, 19, 5, 9, 1, 6, 6, 1, 0, 0), # 60 (13, 20, 9, 10, 11, 7, 5, 9, 9, 1, 1, 2, 0, 16, 12, 11, 7, 16, 13, 3, 6, 6, 4, 0, 1, 0), # 61 (17, 7, 12, 12, 8, 5, 5, 4, 6, 3, 1, 0, 0, 13, 8, 10, 10, 11, 4, 4, 5, 3, 6, 4, 3, 0), # 62 (8, 14, 19, 12, 9, 5, 5, 5, 2, 0, 7, 0, 0, 12, 13, 3, 7, 10, 5, 1, 4, 3, 1, 1, 0, 0), # 63 (16, 10, 11, 8, 12, 2, 7, 8, 5, 1, 4, 0, 0, 14, 16, 8, 11, 14, 7, 5, 4, 8, 4, 1, 1, 0), # 64 (7, 13, 15, 14, 9, 2, 4, 4, 3, 1, 2, 0, 0, 16, 12, 19, 4, 13, 6, 5, 1, 11, 4, 1, 1, 0), # 65 (18, 14, 11, 11, 11, 2, 0, 5, 6, 6, 1, 1, 0, 15, 10, 7, 8, 14, 10, 2, 2, 5, 4, 0, 1, 0), # 66 (15, 17, 9, 12, 15, 4, 7, 7, 8, 0, 2, 3, 0, 17, 10, 6, 11, 9, 4, 12, 2, 1, 8, 3, 0, 0), # 67 (10, 11, 6, 11, 12, 4, 7, 4, 8, 2, 2, 1, 0, 10, 8, 9, 7, 11, 3, 8, 3, 4, 4, 5, 0, 0), # 68 (14, 10, 9, 16, 6, 4, 8, 7, 3, 1, 0, 4, 0, 12, 10, 9, 5, 12, 7, 9, 3, 4, 4, 2, 0, 0), # 69 (19, 11, 8, 18, 13, 6, 7, 4, 4, 0, 5, 1, 0, 16, 8, 10, 6, 11, 6, 6, 2, 6, 4, 1, 2, 0), # 70 (17, 6, 13, 11, 15, 9, 2, 1, 9, 4, 2, 0, 0, 11, 10, 8, 4, 7, 5, 9, 4, 6, 5, 0, 0, 0), # 71 (15, 9, 19, 17, 10, 5, 9, 6, 7, 3, 1, 0, 0, 16, 11, 12, 17, 9, 2, 8, 7, 7, 4, 2, 3, 0), # 72 (17, 11, 11, 15, 9, 6, 3, 7, 9, 2, 2, 0, 0, 16, 9, 5, 5, 16, 6, 7, 5, 2, 1, 2, 0, 0), # 73 (9, 8, 8, 14, 12, 11, 3, 2, 3, 3, 0, 0, 0, 18, 17, 13, 4, 13, 5, 5, 1, 5, 4, 4, 0, 0), # 74 (11, 13, 14, 11, 13, 7, 6, 3, 7, 3, 2, 1, 0, 14, 14, 9, 9, 7, 5, 6, 1, 8, 4, 3, 1, 0), # 75 (19, 12, 16, 10, 11, 5, 8, 3, 3, 6, 1, 0, 0, 7, 12, 10, 8, 19, 9, 7, 2, 5, 6, 4, 0, 0), # 76 (10, 8, 14, 12, 13, 5, 9, 5, 5, 1, 3, 0, 0, 18, 21, 9, 11, 6, 2, 2, 4, 8, 2, 3, 1, 0), # 77 (12, 14, 6, 17, 15, 6, 4, 4, 6, 2, 2, 0, 0, 11, 12, 9, 5, 11, 6, 4, 2, 5, 7, 0, 0, 0), # 78 (12, 8, 10, 13, 10, 6, 4, 6, 6, 3, 2, 0, 0, 16, 7, 7, 8, 5, 4, 5, 6, 9, 2, 1, 0, 0), # 79 (17, 17, 12, 9, 15, 8, 2, 3, 5, 1, 1, 1, 0, 10, 15, 13, 5, 13, 4, 6, 4, 7, 3, 1, 0, 0), # 80 (13, 11, 12, 8, 12, 6, 8, 6, 8, 2, 3, 0, 0, 19, 9, 12, 10, 12, 4, 5, 2, 5, 1, 1, 1, 0), # 81 (13, 13, 7, 15, 11, 7, 6, 6, 5, 2, 0, 7, 0, 18, 14, 7, 12, 7, 3, 3, 8, 3, 6, 3, 2, 0), # 82 (12, 6, 13, 6, 6, 5, 8, 3, 6, 4, 2, 0, 0, 17, 9, 8, 8, 12, 7, 5, 3, 7, 4, 2, 0, 0), # 83 (11, 13, 14, 16, 11, 7, 8, 7, 6, 2, 1, 1, 0, 7, 16, 8, 5, 5, 3, 6, 4, 5, 3, 2, 0, 0), # 84 (12, 14, 21, 14, 14, 7, 6, 3, 8, 4, 1, 1, 0, 9, 15, 10, 2, 13, 3, 6, 4, 6, 3, 3, 0, 0), # 85 (16, 11, 11, 11, 15, 4, 4, 4, 6, 1, 2, 1, 0, 11, 7, 8, 11, 10, 8, 3, 3, 5, 8, 2, 0, 0), # 86 (17, 7, 11, 12, 6, 3, 4, 2, 5, 2, 1, 0, 0, 11, 16, 8, 10, 7, 8, 5, 6, 7, 9, 1, 0, 0), # 87 (11, 17, 10, 9, 10, 6, 6, 2, 3, 4, 5, 0, 0, 21, 12, 9, 10, 13, 1, 2, 5, 6, 5, 2, 1, 0), # 88 (15, 9, 14, 15, 7, 4, 4, 5, 4, 1, 3, 1, 0, 18, 14, 9, 4, 9, 6, 9, 4, 5, 4, 2, 0, 0), # 89 (13, 8, 9, 11, 11, 9, 7, 2, 3, 2, 0, 0, 0, 13, 13, 7, 3, 6, 9, 4, 4, 6, 1, 3, 1, 0), # 90 (18, 13, 7, 14, 9, 4, 4, 0, 8, 2, 2, 0, 0, 14, 10, 11, 5, 7, 4, 10, 3, 2, 2, 5, 2, 0), # 91 (12, 12, 7, 13, 13, 7, 1, 8, 5, 4, 5, 1, 0, 14, 17, 8, 8, 11, 4, 5, 3, 5, 5, 2, 1, 0), # 92 (11, 5, 12, 12, 4, 4, 3, 4, 10, 3, 1, 0, 0, 13, 10, 10, 6, 21, 6, 4, 3, 2, 3, 2, 1, 0), # 93 (14, 13, 12, 13, 13, 2, 4, 7, 3, 2, 2, 1, 0, 12, 13, 4, 7, 15, 6, 5, 1, 6, 5, 0, 0, 0), # 94 (9, 19, 11, 11, 7, 5, 2, 4, 3, 4, 0, 3, 0, 12, 17, 7, 11, 11, 6, 5, 2, 3, 3, 0, 2, 0), # 95 (9, 8, 14, 10, 7, 6, 8, 7, 9, 3, 1, 2, 0, 10, 10, 9, 8, 7, 6, 3, 9, 9, 5, 5, 0, 0), # 96 (13, 10, 8, 14, 10, 4, 2, 10, 5, 2, 2, 3, 0, 11, 3, 8, 8, 12, 7, 5, 1, 8, 1, 2, 1, 0), # 97 (17, 8, 12, 12, 12, 7, 4, 2, 4, 4, 0, 2, 0, 8, 9, 5, 6, 10, 5, 3, 1, 7, 4, 4, 2, 0), # 98 (14, 10, 11, 15, 12, 4, 5, 3, 4, 1, 0, 2, 0, 14, 13, 13, 7, 9, 4, 4, 0, 2, 6, 4, 2, 0), # 99 (9, 9, 11, 10, 11, 5, 2, 5, 8, 1, 0, 5, 0, 12, 8, 12, 8, 12, 2, 7, 3, 10, 4, 4, 1, 0), # 100 (16, 11, 10, 7, 12, 3, 2, 3, 6, 1, 1, 1, 0, 13, 12, 4, 5, 10, 9, 6, 3, 6, 4, 2, 0, 0), # 101 (17, 12, 8, 14, 5, 6, 5, 5, 4, 2, 1, 0, 0, 15, 7, 5, 12, 9, 6, 2, 5, 3, 7, 3, 3, 0), # 102 (14, 12, 8, 12, 8, 5, 4, 5, 7, 2, 1, 0, 0, 20, 14, 10, 8, 6, 4, 4, 2, 8, 3, 0, 1, 0), # 103 (14, 6, 11, 14, 11, 4, 4, 5, 5, 3, 1, 1, 0, 10, 6, 14, 6, 8, 9, 4, 5, 2, 3, 1, 0, 0), # 104 (16, 11, 9, 13, 12, 5, 8, 5, 8, 2, 2, 0, 0, 17, 10, 15, 8, 10, 3, 6, 1, 6, 4, 3, 0, 0), # 105 (8, 12, 13, 10, 6, 5, 5, 2, 8, 2, 1, 1, 0, 19, 14, 7, 4, 12, 4, 3, 4, 5, 3, 1, 1, 0), # 106 (11, 12, 16, 5, 3, 9, 3, 2, 7, 2, 0, 2, 0, 15, 13, 3, 3, 8, 5, 7, 4, 6, 4, 3, 1, 0), # 107 (12, 9, 7, 9, 7, 5, 4, 3, 2, 1, 2, 3, 0, 24, 10, 11, 9, 9, 5, 6, 2, 6, 4, 1, 4, 0), # 108 (10, 15, 14, 10, 7, 7, 9, 5, 8, 2, 1, 2, 0, 17, 9, 6, 5, 9, 9, 3, 5, 9, 1, 3, 0, 0), # 109 (15, 7, 10, 8, 8, 4, 4, 4, 5, 0, 0, 0, 0, 13, 9, 13, 9, 9, 6, 5, 5, 5, 4, 0, 2, 0), # 110 (19, 13, 9, 13, 16, 2, 2, 2, 9, 4, 1, 0, 0, 8, 8, 11, 4, 10, 1, 5, 2, 6, 2, 3, 0, 0), # 111 (15, 18, 10, 14, 4, 2, 3, 2, 9, 0, 1, 0, 0, 12, 10, 6, 11, 7, 2, 2, 3, 10, 3, 2, 0, 0), # 112 (9, 7, 13, 17, 5, 2, 0, 1, 8, 1, 3, 1, 0, 18, 9, 11, 6, 9, 11, 2, 2, 5, 5, 4, 1, 0), # 113 (14, 4, 12, 10, 8, 7, 2, 2, 6, 2, 2, 0, 0, 13, 11, 9, 6, 10, 1, 6, 3, 4, 3, 2, 1, 0), # 114 (15, 7, 9, 13, 10, 3, 7, 1, 4, 0, 2, 2, 0, 11, 11, 15, 4, 12, 4, 3, 3, 4, 5, 4, 3, 0), # 115 (4, 14, 12, 13, 12, 6, 1, 6, 4, 0, 0, 1, 0, 11, 9, 9, 4, 7, 11, 3, 2, 4, 5, 1, 1, 0), # 116 (15, 9, 13, 10, 9, 6, 4, 3, 9, 5, 1, 2, 0, 10, 10, 9, 9, 12, 1, 3, 4, 5, 2, 1, 0, 0), # 117 (10, 10, 13, 17, 10, 6, 3, 3, 4, 1, 2, 2, 0, 12, 15, 10, 9, 5, 4, 3, 3, 6, 4, 0, 1, 0), # 118 (5, 8, 8, 7, 11, 3, 3, 5, 5, 2, 4, 1, 0, 10, 9, 11, 3, 11, 7, 3, 3, 3, 2, 4, 3, 0), # 119 (9, 9, 9, 9, 11, 4, 4, 2, 5, 3, 1, 0, 0, 11, 12, 7, 8, 8, 8, 3, 3, 8, 2, 4, 2, 0), # 120 (10, 15, 17, 15, 15, 5, 4, 4, 10, 3, 3, 0, 0, 17, 9, 6, 7, 4, 4, 2, 3, 4, 5, 4, 0, 0), # 121 (23, 10, 9, 8, 11, 4, 2, 3, 9, 1, 2, 0, 0, 17, 12, 6, 7, 8, 5, 2, 3, 8, 3, 3, 0, 0), # 122 (16, 5, 5, 14, 10, 3, 4, 1, 4, 3, 2, 1, 0, 17, 11, 11, 4, 9, 3, 5, 5, 3, 2, 4, 1, 0), # 123 (10, 19, 10, 15, 5, 6, 5, 2, 5, 2, 0, 0, 0, 7, 11, 6, 6, 10, 6, 2, 4, 7, 3, 0, 1, 0), # 124 (7, 8, 9, 6, 11, 4, 5, 2, 4, 3, 1, 0, 0, 13, 11, 11, 10, 11, 6, 7, 4, 5, 2, 4, 0, 0), # 125 (15, 13, 6, 12, 4, 5, 6, 2, 0, 3, 1, 1, 0, 19, 6, 6, 6, 8, 4, 4, 3, 4, 3, 1, 1, 0), # 126 (7, 8, 9, 11, 12, 4, 4, 2, 6, 2, 0, 0, 0, 8, 7, 4, 3, 9, 5, 2, 2, 6, 1, 5, 1, 0), # 127 (15, 12, 9, 9, 4, 7, 4, 2, 8, 5, 1, 2, 0, 11, 5, 9, 5, 11, 3, 4, 3, 3, 3, 4, 1, 0), # 128 (13, 9, 14, 9, 10, 5, 4, 1, 6, 1, 1, 1, 0, 14, 10, 6, 5, 10, 9, 5, 2, 1, 8, 0, 0, 0), # 129 (8, 12, 10, 11, 11, 5, 2, 6, 5, 1, 2, 1, 0, 8, 5, 5, 6, 9, 3, 7, 1, 2, 2, 3, 0, 0), # 130 (5, 6, 19, 7, 5, 2, 1, 4, 6, 1, 0, 0, 0, 9, 10, 9, 5, 8, 7, 3, 4, 3, 1, 2, 0, 0), # 131 (12, 10, 10, 5, 10, 6, 4, 7, 2, 1, 1, 0, 0, 17, 9, 5, 10, 13, 3, 2, 3, 1, 4, 7, 1, 0), # 132 (6, 10, 12, 11, 5, 4, 4, 4, 3, 1, 2, 3, 0, 9, 11, 6, 4, 14, 4, 6, 4, 10, 5, 3, 1, 0), # 133 (15, 8, 11, 16, 9, 5, 2, 3, 7, 2, 1, 1, 0, 11, 5, 12, 5, 12, 1, 5, 5, 5, 4, 2, 0, 0), # 134 (12, 11, 13, 13, 13, 2, 0, 2, 4, 2, 3, 0, 0, 10, 11, 7, 5, 15, 7, 6, 2, 3, 3, 1, 3, 0), # 135 (17, 7, 13, 15, 7, 6, 5, 2, 5, 1, 0, 1, 0, 10, 7, 8, 4, 14, 4, 4, 4, 5, 1, 2, 0, 0), # 136 (10, 11, 12, 12, 12, 5, 2, 3, 2, 2, 2, 0, 0, 18, 11, 8, 6, 12, 4, 7, 2, 6, 3, 3, 1, 0), # 137 (17, 4, 5, 12, 11, 3, 7, 2, 6, 6, 0, 1, 0, 11, 11, 6, 5, 8, 2, 3, 3, 7, 6, 3, 1, 0), # 138 (16, 12, 12, 8, 8, 6, 6, 3, 4, 1, 3, 1, 0, 13, 8, 8, 7, 9, 8, 2, 4, 4, 4, 5, 1, 0), # 139 (13, 9, 5, 14, 8, 5, 3, 5, 6, 2, 3, 1, 0, 6, 9, 7, 3, 11, 6, 5, 7, 5, 6, 3, 1, 0), # 140 (16, 6, 11, 8, 7, 6, 6, 2, 6, 0, 1, 1, 0, 14, 13, 8, 7, 10, 2, 4, 1, 5, 2, 1, 0, 0), # 141 (7, 5, 9, 11, 8, 5, 2, 6, 5, 2, 0, 2, 0, 12, 5, 4, 2, 10, 6, 5, 3, 3, 4, 0, 3, 0), # 142 (17, 14, 13, 10, 15, 4, 5, 5, 7, 0, 3, 4, 0, 13, 10, 6, 6, 15, 5, 6, 3, 2, 5, 1, 1, 0), # 143 (11, 11, 15, 13, 5, 4, 6, 6, 1, 4, 5, 0, 0, 11, 11, 7, 4, 11, 4, 4, 8, 7, 3, 1, 0, 0), # 144 (6, 13, 11, 4, 7, 6, 2, 7, 7, 1, 1, 1, 0, 9, 7, 13, 5, 8, 11, 6, 8, 5, 5, 2, 3, 0), # 145 (15, 12, 8, 10, 9, 5, 4, 5, 4, 0, 1, 1, 0, 11, 9, 13, 5, 11, 4, 5, 2, 3, 3, 1, 0, 0), # 146 (12, 12, 9, 8, 7, 4, 2, 5, 2, 1, 2, 1, 0, 16, 12, 6, 5, 9, 4, 3, 3, 4, 3, 2, 2, 0), # 147 (10, 9, 15, 12, 8, 7, 6, 6, 4, 2, 1, 2, 0, 14, 8, 9, 6, 8, 4, 4, 3, 2, 4, 2, 0, 0), # 148 (18, 13, 6, 15, 12, 4, 6, 2, 5, 4, 2, 0, 0, 10, 7, 8, 5, 8, 2, 3, 4, 7, 2, 3, 2, 0), # 149 (18, 3, 10, 10, 4, 5, 2, 3, 2, 1, 2, 0, 0, 9, 11, 4, 5, 18, 3, 7, 4, 6, 3, 2, 2, 0), # 150 (9, 5, 4, 3, 7, 5, 3, 3, 5, 0, 3, 0, 0, 10, 12, 8, 6, 10, 5, 1, 1, 1, 3, 1, 1, 0), # 151 (9, 3, 9, 12, 8, 3, 1, 1, 4, 3, 1, 0, 0, 14, 6, 3, 4, 9, 4, 3, 7, 3, 5, 0, 0, 0), # 152 (7, 5, 7, 12, 5, 6, 3, 3, 4, 3, 2, 0, 0, 10, 11, 5, 8, 9, 5, 2, 4, 7, 3, 2, 1, 0), # 153 (7, 10, 8, 8, 8, 3, 3, 0, 2, 2, 1, 1, 0, 9, 11, 10, 7, 14, 4, 4, 2, 3, 2, 1, 2, 0), # 154 (17, 6, 10, 13, 6, 1, 5, 2, 1, 0, 1, 0, 0, 14, 3, 5, 3, 7, 3, 2, 4, 5, 4, 1, 0, 0), # 155 (4, 5, 4, 8, 4, 6, 3, 4, 3, 0, 1, 1, 0, 10, 9, 5, 4, 7, 10, 3, 7, 4, 5, 1, 0, 0), # 156 (3, 7, 6, 5, 14, 6, 3, 1, 2, 2, 1, 2, 0, 13, 8, 6, 5, 11, 2, 4, 3, 3, 5, 4, 0, 0), # 157 (9, 5, 16, 8, 8, 4, 6, 4, 7, 3, 2, 0, 0, 5, 9, 1, 8, 12, 5, 4, 2, 3, 1, 4, 0, 0), # 158 (7, 6, 10, 5, 8, 5, 4, 5, 6, 1, 1, 0, 0, 6, 13, 7, 6, 7, 6, 3, 4, 4, 1, 1, 0, 0), # 159 (13, 5, 12, 5, 6, 4, 1, 5, 2, 2, 2, 0, 0, 11, 7, 6, 5, 7, 4, 1, 5, 5, 1, 1, 0, 0), # 160 (11, 6, 9, 7, 4, 2, 1, 6, 7, 2, 0, 0, 0, 6, 11, 7, 3, 6, 7, 7, 3, 6, 3, 2, 1, 0), # 161 (12, 10, 5, 6, 9, 6, 2, 5, 7, 1, 1, 0, 0, 10, 5, 10, 4, 13, 3, 1, 1, 7, 2, 3, 0, 0), # 162 (9, 6, 12, 8, 4, 3, 2, 3, 7, 2, 3, 0, 0, 12, 6, 7, 1, 5, 2, 3, 6, 3, 4, 2, 0, 0), # 163 (9, 5, 7, 9, 8, 3, 2, 3, 6, 1, 0, 0, 0, 9, 5, 4, 2, 8, 3, 3, 4, 5, 3, 1, 1, 0), # 164 (11, 8, 12, 7, 5, 4, 6, 1, 6, 3, 1, 1, 0, 6, 9, 3, 1, 4, 5, 2, 3, 2, 4, 0, 0, 0), # 165 (5, 3, 13, 9, 4, 2, 1, 4, 5, 1, 1, 0, 0, 12, 5, 5, 5, 9, 6, 2, 1, 2, 4, 1, 0, 0), # 166 (6, 7, 8, 8, 4, 3, 6, 5, 6, 1, 3, 0, 0, 13, 6, 10, 5, 5, 4, 1, 3, 5, 1, 0, 1, 0), # 167 (9, 5, 11, 11, 5, 3, 3, 3, 2, 2, 1, 2, 0, 8, 8, 6, 3, 8, 3, 3, 1, 1, 2, 1, 0, 0), # 168 (5, 5, 8, 10, 3, 2, 5, 3, 4, 0, 2, 0, 0, 13, 6, 4, 2, 6, 2, 2, 3, 0, 2, 3, 0, 0), # 169 (11, 5, 5, 6, 5, 2, 3, 3, 3, 0, 2, 1, 0, 9, 6, 9, 6, 7, 3, 3, 4, 6, 1, 2, 2, 0), # 170 (10, 4, 5, 4, 11, 4, 1, 4, 2, 1, 1, 1, 0, 7, 6, 11, 4, 13, 7, 0, 0, 2, 4, 0, 0, 0), # 171 (9, 2, 4, 6, 3, 5, 1, 1, 2, 3, 2, 0, 0, 4, 5, 4, 3, 8, 2, 2, 3, 1, 1, 3, 0, 0), # 172 (8, 6, 2, 4, 6, 3, 2, 0, 2, 1, 0, 0, 0, 8, 7, 9, 5, 4, 1, 3, 2, 3, 6, 0, 1, 0), # 173 (6, 5, 6, 6, 7, 3, 2, 0, 2, 2, 0, 0, 0, 8, 6, 3, 2, 6, 4, 0, 2, 4, 2, 0, 0, 0), # 174 (8, 3, 5, 7, 5, 1, 2, 0, 2, 2, 3, 1, 0, 6, 3, 1, 5, 5, 1, 0, 3, 2, 2, 2, 2, 0), # 175 (5, 5, 4, 7, 8, 4, 2, 1, 2, 1, 1, 2, 0, 5, 0, 2, 2, 5, 3, 1, 1, 2, 3, 0, 0, 0), # 176 (11, 4, 9, 6, 5, 3, 3, 2, 1, 2, 0, 1, 0, 8, 1, 4, 3, 5, 1, 3, 0, 3, 1, 0, 0, 0), # 177 (5, 4, 4, 3, 6, 2, 1, 3, 5, 1, 0, 2, 0, 9, 1, 1, 2, 4, 0, 2, 0, 5, 2, 2, 1, 0), # 178 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # 179 ) station_arriving_intensity = ( (7.029211809720476, 7.735403983570434, 7.29579652145751, 8.700534883408807, 7.776559850653457, 4.394116904852274, 5.804449861523481, 6.514446642171193, 8.52613868703521, 5.541221021731318, 5.887371229439844, 6.857081109628643, 7.117432297609708), # 0 (7.496058012827964, 8.246084971802663, 7.777485227862214, 9.275201954587263, 8.291486472463932, 4.684377017659578, 6.187256517769172, 6.943319212067992, 9.089143456866074, 5.90657296918801, 6.2763345903385845, 7.309703325140097, 7.587708306415797), # 1 (7.9614122125716245, 8.754739239247371, 8.257259199766379, 9.847582786530712, 8.804548163249642, 4.9734791603174235, 6.568545911144986, 7.370475347066188, 9.64990152962857, 6.270479285028765, 6.663752408286839, 7.760525712874277, 8.056110759493567), # 2 (8.423460910405188, 9.259348702711026, 8.733215217047796, 10.415406970544904, 9.313726346402664, 5.260276871619158, 6.946805098307138, 7.79422162049231, 10.206189225289531, 6.631495777796654, 7.0480877765583365, 8.207759958902646, 8.520781928755916), # 3 (8.880390607782374, 9.757895279000085, 9.203450059584252, 10.976404097935598, 9.81700244531509, 5.543623690358135, 7.320521135911843, 8.212864605672882, 10.75578286381579, 6.988178256034751, 7.4278037884268056, 8.64961774929667, 8.979864086115745), # 4 (9.330387806156915, 10.248360884921025, 9.666060507253526, 11.528303760008551, 10.312357883378994, 5.822373155327701, 7.688181080615314, 8.62471087593443, 11.296458765174183, 7.339082528286129, 7.801363537165986, 9.084310770127807, 9.43149950348596), # 5 (9.771639006982534, 10.728727437280302, 10.119143339933412, 12.068835548069513, 10.79777408398646, 6.09537880532121, 8.048271989073768, 9.028067004603484, 11.825993249331543, 7.682764403093862, 8.167230116049597, 9.510050707467531, 9.87383045277945), # 6 (10.202330711712957, 11.196976852884385, 10.56079533750169, 12.595729053424249, 11.271232470529577, 6.36149417913201, 8.39928091794342, 9.421239565006573, 12.342162636254702, 8.017779689001022, 8.523866618351377, 9.925049247387301, 10.304999205909127), # 7 (10.62064942180191, 11.651091048539739, 10.989113279836156, 13.1067138673785, 11.730714466400421, 6.619572815553446, 8.739694923880478, 9.802535130470215, 12.842743245910489, 8.342684194550685, 8.86973613734505, 10.327518075958585, 10.723148034787885), # 8 (11.02478163870312, 12.089051941052832, 11.402193946814586, 13.599519581238038, 12.174201494991074, 6.868468253378878, 9.068001063541168, 10.170260274320949, 13.325511398265744, 8.65603372828592, 9.20330176630435, 10.71566887925284, 11.126419211328628), # 9 (11.412913863870306, 12.508841447230123, 11.798134118314776, 14.071875786308604, 12.599674979693622, 7.107034031401651, 9.382686393581697, 10.522721569885295, 13.7882434132873, 8.956384098749801, 9.523026598503003, 11.087713343341534, 11.512955007444255), # 10 (11.783232598757209, 12.90844148387809, 12.175030574214501, 14.521512073895957, 13.005116343900148, 7.334123688415116, 9.682237970658283, 10.85822559048978, 14.228715610941991, 9.242291114485408, 9.82737372721475, 11.441863154296136, 11.880897695047656), # 11 (12.133924344817538, 13.285833967803178, 12.530980094391557, 14.946158035305858, 13.38850701100273, 7.5485907632126175, 9.965142851427137, 11.17507890946093, 14.644704311196652, 9.512310584035802, 10.114806245713309, 11.776329998188096, 12.22838954605175), # 12 (12.463175603505027, 13.639000815811869, 12.864079458723728, 15.343543261844063, 13.747828404393443, 7.749288794587514, 10.22988809254448, 11.471588100125276, 15.033985834018106, 9.764998315944066, 10.383787247272418, 12.08932556108889, 12.55357283236943), # 13 (12.769172876273403, 13.965923944710624, 13.172425447088806, 15.71139734481631, 14.081061947464386, 7.935071321333148, 10.474960750666526, 11.746059735809345, 15.39433649937319, 9.998910118753269, 10.6327798251658, 12.379061529069986, 12.85458982591359), # 14 (13.050102664576398, 14.264585271305906, 13.45411483936456, 16.047449875528383, 14.386189063607633, 8.104791882242878, 10.698847882449478, 11.99680038983966, 15.723532627228748, 10.212601801006487, 10.860247072667189, 12.64374958820284, 13.129582798597134), # 15 (13.30415146986772, 14.532966712404187, 13.707244415428796, 16.349430445286004, 14.661191176215267, 8.257304016110044, 10.900036544549568, 12.222116635542745, 16.019350537551603, 10.404629171246796, 11.06465208305032, 12.881601424558916, 13.376694022332964), # 16 (13.529505793601107, 14.769050184811926, 13.929910955159293, 16.61506864539496, 14.904049708679375, 8.391461261728, 11.077013793622996, 12.420315046245145, 16.27956655030858, 10.573548038017254, 11.24445794958892, 13.090828724209679, 13.594065769033982), # 17 (13.724352137230287, 14.970817605335585, 14.120211238433834, 16.842094067160993, 15.112746084392025, 8.506117157890104, 11.228266686325993, 12.589702195273366, 16.501956985466535, 10.717914209860952, 11.398127765556712, 13.269643173226603, 13.779840310613086), # 18 (13.88687700220898, 15.136250890781643, 14.27624204513021, 17.02823630188984, 15.285261726745313, 8.600125243389693, 11.352282279314753, 12.728584655953943, 16.68429816299229, 10.83628349532096, 11.52412462422743, 13.416256457681136, 13.932159918983176), # 19 (14.015266889990915, 15.263331957956549, 14.396100155126206, 17.171224940887296, 15.419578059131322, 8.672339057020126, 11.44754762924551, 12.835269001613405, 16.82436640285268, 10.927211702940342, 11.62091161887481, 13.528880263644748, 14.049166866057154), # 20 (14.107708302029813, 15.350042723666784, 14.477882348299607, 17.26878957545908, 15.513676504942126, 8.72161213757475, 11.512549792774463, 12.908061805578273, 16.91993802501453, 10.989254641262178, 11.686951842772585, 13.60572627718891, 14.12900342374791), # 21 (14.162387739779412, 15.394365104718803, 14.5196854045282, 17.31865979691097, 15.565538487569807, 8.746798023846914, 11.54577582655784, 12.945269641175082, 16.968789349444684, 11.02096811882954, 11.720708389194478, 13.645006184385087, 14.16981186396836), # 22 (14.182550708679697, 15.39961303155007, 14.524892455418383, 17.324903137860087, 15.578824878445637, 8.75, 11.549725603163076, 12.949291358024693, 16.974896728395063, 11.024709181527207, 11.724941252026436, 13.649856607224509, 14.175), # 23 (14.197417378247815, 15.396551851851854, 14.524040740740743, 17.324134722222226, 15.586350659060795, 8.75, 11.547555337690634, 12.943700000000002, 16.974078333333335, 11.02241086419753, 11.724474410774413, 13.648720987654322, 14.175), # 24 (14.211970122296213, 15.390517832647463, 14.522359396433473, 17.322614454732513, 15.593710923832306, 8.75, 11.543278463648836, 12.932716049382718, 16.97246141975309, 11.01788637402835, 11.723548759196907, 13.646479195244629, 14.175), # 25 (14.226207826667249, 15.381603155006863, 14.519871467764064, 17.320359619341563, 15.600905415789548, 8.75, 11.53696140563221, 12.916546913580248, 16.97006672839506, 11.011210992226795, 11.722172677391198, 13.643161957018751, 14.175), # 26 (14.240129377203292, 15.3699, 14.5166, 17.3173875, 15.607933877961901, 8.75, 11.528670588235297, 12.895400000000002, 16.966915, 11.00246, 11.720354545454546, 13.638800000000003, 14.175), # 27 (14.253733659746702, 15.355500548696845, 14.51256803840878, 17.313715380658437, 15.614796053378763, 8.75, 11.518472436052612, 12.869482716049385, 16.963026975308644, 10.9917086785551, 11.718102743484225, 13.633424051211708, 14.175), # 28 (14.26701956013985, 15.338496982167355, 14.50779862825789, 17.30936054526749, 15.62149168506951, 8.75, 11.506433373678693, 12.839002469135803, 16.95842339506173, 10.979032309099225, 11.715425651577503, 13.627064837677183, 14.175), # 29 (14.279985964225098, 15.318981481481483, 14.502314814814815, 17.30434027777778, 15.628020516063533, 8.75, 11.492619825708061, 12.804166666666665, 16.953125, 10.964506172839508, 11.71233164983165, 13.619753086419752, 14.175), # 30 (14.292631757844802, 15.297046227709194, 14.496139643347053, 17.29867186213992, 15.634382289390214, 8.75, 11.477098216735257, 12.765182716049384, 16.947152530864198, 10.948205550983083, 11.708829118343933, 13.611519524462738, 14.175), # 31 (14.304955826841338, 15.27278340192044, 14.489296159122084, 17.29237258230453, 15.640576748078935, 8.75, 11.4599349713548, 12.72225802469136, 16.940526728395064, 10.930205724737084, 11.704926437211622, 13.602394878829449, 14.175), # 32 (14.316957057057056, 15.246285185185185, 14.481807407407409, 17.28545972222222, 15.646603635159089, 8.75, 11.441196514161222, 12.675600000000001, 16.933268333333334, 10.910581975308643, 11.700631986531986, 13.59240987654321, 14.175), # 33 (14.328634334334335, 15.217643758573388, 14.473696433470508, 17.27795056584362, 15.652462693660054, 8.75, 11.420949269749054, 12.625416049382716, 16.925398086419758, 10.889409583904893, 11.695954146402293, 13.581595244627344, 14.175), # 34 (14.339986544515531, 15.186951303155007, 14.464986282578877, 17.26986239711934, 15.65815366661122, 8.75, 11.399259662712824, 12.571913580246914, 16.916936728395065, 10.866763831732968, 11.690901296919815, 13.569981710105168, 14.175), # 35 (14.35101257344301, 15.1543, 14.455700000000002, 17.2612125, 15.663676297041972, 8.75, 11.37619411764706, 12.515300000000002, 16.907905, 10.84272, 11.685481818181819, 13.557600000000003, 14.175), # 36 (14.361711306959135, 15.119782030178326, 14.445860631001374, 17.252018158436215, 15.669030327981691, 8.75, 11.351819059146292, 12.455782716049384, 16.89832364197531, 10.817353369913125, 11.679704090285574, 13.544480841335163, 14.175), # 37 (14.372081630906267, 15.083489574759948, 14.43549122085048, 17.242296656378603, 15.674215502459768, 8.75, 11.326200911805053, 12.393569135802473, 16.88821339506173, 10.790739222679472, 11.673576493328346, 13.530654961133976, 14.175), # 38 (14.382122431126781, 15.045514814814815, 14.424614814814818, 17.232065277777778, 15.679231563505585, 8.75, 11.299406100217867, 12.328866666666666, 16.877595000000003, 10.762952839506175, 11.667107407407409, 13.516153086419752, 14.175), # 39 (14.39183259346303, 15.005949931412895, 14.413254458161866, 17.221341306584364, 15.684078254148528, 8.75, 11.271501048979264, 12.261882716049385, 16.866489197530868, 10.734069501600368, 11.660305212620028, 13.501005944215823, 14.175), # 40 (14.40121100375738, 14.964887105624143, 14.401433196159124, 17.210142026748972, 15.688755317417984, 8.75, 11.242552182683774, 12.192824691358027, 16.85491672839506, 10.704164490169182, 11.653178289063476, 13.485244261545498, 14.175), # 41 (14.410256547852201, 14.922418518518521, 14.389174074074077, 17.198484722222226, 15.693262496343333, 8.75, 11.212625925925927, 12.121900000000002, 16.842898333333338, 10.673313086419753, 11.645735016835017, 13.4688987654321, 14.175), # 42 (14.418968111589852, 14.878636351165984, 14.376500137174213, 17.186386676954736, 15.697599533953966, 8.75, 11.181788703300251, 12.049316049382718, 16.83045475308642, 10.641590571559215, 11.637983776031925, 13.452000182898951, 14.175), # 43 (14.427344580812699, 14.83363278463649, 14.363434430727025, 17.173865174897124, 15.701766173279264, 8.75, 11.150106939401276, 11.975280246913583, 16.817606728395063, 10.609072226794698, 11.629932946751465, 13.434579240969367, 14.175), # 44 (14.435384841363105, 14.787500000000001, 14.350000000000001, 17.160937500000003, 15.705762157348616, 8.75, 11.11764705882353, 11.9, 16.804375, 10.575833333333335, 11.62159090909091, 13.416666666666666, 14.175), # 45 (14.443087779083434, 14.740330178326476, 14.336219890260631, 17.147620936213993, 15.709587229191404, 8.75, 11.084475486161544, 11.823682716049385, 16.790780308641974, 10.541949172382258, 11.612966043147525, 13.398293187014175, 14.175), # 46 (14.45045227981605, 14.692215500685872, 14.322117146776408, 17.133932767489714, 15.713241131837016, 8.75, 11.050658646009847, 11.746535802469136, 16.776843395061732, 10.507495025148607, 11.604066729018582, 13.37948952903521, 14.175), # 47 (14.457477229403315, 14.64324814814815, 14.307714814814817, 17.11989027777778, 15.716723608314837, 8.75, 11.016262962962964, 11.668766666666668, 16.762585, 10.472546172839506, 11.594901346801347, 13.360286419753088, 14.175), # 48 (14.464161513687602, 14.593520301783265, 14.29303593964335, 17.10551075102881, 15.720034401654251, 8.75, 10.981354861615428, 11.590582716049383, 16.748025864197533, 10.437177896662096, 11.585478276593093, 13.340714586191131, 14.175), # 49 (14.470504018511264, 14.543124142661183, 14.278103566529495, 17.090811471193415, 15.723173254884642, 8.75, 10.94600076656177, 11.512191358024692, 16.73318672839506, 10.401465477823503, 11.575805898491085, 13.32080475537266, 14.175), # 50 (14.476503629716676, 14.492151851851853, 14.262940740740742, 17.075809722222225, 15.726139911035398, 8.75, 10.910267102396515, 11.433800000000002, 16.718088333333338, 10.365484197530865, 11.565892592592595, 13.30058765432099, 14.175), # 51 (14.482159233146191, 14.440695610425243, 14.247570507544584, 17.060522788065846, 15.728934113135901, 8.75, 10.874220293714194, 11.355616049382716, 16.70275141975309, 10.329309336991313, 11.555746738994888, 13.280094010059445, 14.175), # 52 (14.487469714642183, 14.388847599451307, 14.232015912208508, 17.0449679526749, 15.731555604215542, 8.75, 10.837926765109337, 11.277846913580248, 16.687196728395065, 10.293016177411982, 11.545376717795238, 13.259354549611341, 14.175), # 53 (14.492433960047004, 14.336700000000002, 14.2163, 17.0291625, 15.734004127303704, 8.75, 10.801452941176471, 11.2007, 16.671445000000002, 10.256680000000001, 11.534790909090908, 13.2384, 14.175), # 54 (14.497050855203032, 14.284344993141291, 14.200445816186559, 17.01312371399177, 15.736279425429768, 8.75, 10.764865246510128, 11.124382716049384, 16.655516975308643, 10.220376085962506, 11.523997692979176, 13.217261088248744, 14.175), # 55 (14.501319285952622, 14.231874759945132, 14.184476406035667, 16.996868878600825, 15.738381241623124, 8.75, 10.728230105704835, 11.049102469135804, 16.63943339506173, 10.184179716506632, 11.513005449557303, 13.195968541380887, 14.175), # 56 (14.505238138138138, 14.179381481481483, 14.168414814814819, 16.98041527777778, 15.740309318913155, 8.75, 10.69161394335512, 10.975066666666669, 16.623215000000002, 10.148166172839508, 11.50182255892256, 13.174553086419753, 14.175), # 57 (14.508806297601952, 14.126957338820304, 14.152284087791497, 16.96378019547325, 15.742063400329245, 8.75, 10.655083184055517, 10.902482716049382, 16.606882530864198, 10.112410736168268, 11.490457401172218, 13.153045450388662, 14.175), # 58 (14.51202265018642, 14.07469451303155, 14.136107270233198, 16.946980915637862, 15.743643228900785, 8.75, 10.61870425240055, 10.83155802469136, 16.590456728395065, 10.076988687700048, 11.478918356403542, 13.131476360310929, 14.175), # 59 (14.51488608173391, 14.022685185185187, 14.119907407407407, 16.930034722222224, 15.745048547657152, 8.75, 10.582543572984749, 10.762500000000001, 16.573958333333337, 10.041975308641977, 11.467213804713806, 13.109876543209879, 14.175), # 60 (14.517395478086781, 13.971021536351168, 14.10370754458162, 16.912958899176957, 15.746279099627737, 8.75, 10.546667570402647, 10.695516049382718, 16.557408086419755, 10.00744588020119, 11.455352126200275, 13.088276726108827, 14.175), # 61 (14.519549725087407, 13.919795747599453, 14.087530727023323, 16.89577073045268, 15.74733462784193, 8.75, 10.51114266924877, 10.630813580246915, 16.540826728395064, 9.973475683584821, 11.44334170096022, 13.066707636031095, 14.175), # 62 (14.521347708578144, 13.869100000000001, 14.071400000000002, 16.878487500000002, 15.7482148753291, 8.75, 10.476035294117647, 10.568600000000002, 16.524235, 9.94014, 11.43119090909091, 13.045200000000001, 14.175), # 63 (14.522788314401359, 13.819026474622772, 14.05533840877915, 16.86112649176955, 15.74891958511865, 8.75, 10.44141186960381, 10.509082716049384, 16.50765364197531, 9.907514110653864, 11.41890813068961, 13.023784545038868, 14.175), # 64 (14.523870428399414, 13.769667352537724, 14.03936899862826, 16.843704989711934, 15.749448500239955, 8.75, 10.407338820301785, 10.45246913580247, 16.49110339506173, 9.875673296753543, 11.4065017458536, 13.00249199817101, 14.175), # 65 (14.524592936414676, 13.721114814814818, 14.023514814814817, 16.826240277777778, 15.749801363722403, 8.75, 10.373882570806101, 10.398966666666668, 16.474605000000004, 9.844692839506173, 11.393980134680135, 12.981353086419755, 14.175), # 66 (14.524954724289511, 13.673461042524005, 14.00779890260631, 16.808749639917696, 15.749977918595382, 8.75, 10.341109545711289, 10.348782716049385, 16.458179197530864, 9.814648020118886, 11.381351677266494, 12.960398536808412, 14.175), # 67 (14.524708260273156, 13.626548095048452, 13.99216832990398, 16.7910984366613, 15.749829137416285, 8.74983761621704, 10.308921272761506, 10.301681390032009, 16.44172298811157, 9.785468618306034, 11.368400383956526, 12.939542030659641, 14.174825210048013), # 68 (14.522398389694043, 13.578943727598569, 13.976183796296295, 16.772396920289854, 15.748474945533768, 8.748553909465022, 10.27637545388526, 10.25513827160494, 16.424516975308645, 9.756328946986201, 11.35380797448166, 12.918106562703056, 14.17344039351852), # 69 (14.517840102582454, 13.5304294437807, 13.95977580589849, 16.752521973966722, 15.74579903978052, 8.746025758268557, 10.243324188385918, 10.208733424782809, 16.40646404892547, 9.727087334247829, 11.337408441136512, 12.895991865809934, 14.170705268347055), # 70 (14.511097524900102, 13.481034236028144, 13.942950120027435, 16.731502905260335, 15.74183531025579, 8.742294131992075, 10.209782323354585, 10.162482213077277, 16.387591095107457, 9.697744503079695, 11.319262319097408, 12.873214112097802, 14.166655842764062), # 71 (14.502234782608697, 13.430787096774193, 13.9257125, 16.709369021739132, 15.736617647058825, 8.737400000000001, 10.175764705882354, 10.1164, 16.367925000000003, 9.668301176470589, 11.299430143540672, 12.849789473684211, 14.161328125), # 72 (14.491316001669949, 13.379717018452144, 13.90806870713306, 16.686149630971553, 15.730179940288872, 8.73138433165676, 10.141286183060329, 10.070502149062644, 16.347492649748517, 9.63875807740929, 11.277972449642624, 12.825734122686688, 14.154758123285324), # 73 (14.478405308045566, 13.32785299349529, 13.890024502743485, 16.661874040526033, 15.722556080045187, 8.72428809632678, 10.106361601979613, 10.024804023776863, 16.3263209304984, 9.609115928884586, 11.254949772579598, 12.801064231222776, 14.146981845850483), # 74 (14.463566827697262, 13.275224014336917, 13.871585648148148, 16.636571557971017, 15.713779956427018, 8.716152263374488, 10.0710058097313, 9.979320987654322, 16.30443672839506, 9.579375453885259, 11.23042264752791, 12.775795971410007, 14.138035300925928), # 75 (14.44686468658675, 13.22185907341033, 13.852757904663925, 16.610271490874936, 15.703885459533609, 8.707017802164305, 10.035233653406493, 9.934068404206677, 16.281866929583906, 9.549537375400092, 11.20445160966389, 12.749945515365916, 14.127954496742113), # 76 (14.428363010675731, 13.167787163148816, 13.833547033607681, 16.583003146806227, 15.692906479464213, 8.696925682060662, 9.999059980096293, 9.88906163694559, 16.258638420210335, 9.519602416417872, 11.177097194163862, 12.723529035208049, 14.116775441529496), # 77 (14.408125925925928, 13.113037275985667, 13.813958796296298, 16.554795833333333, 15.680876906318085, 8.685916872427983, 9.962499636891796, 9.844316049382718, 16.23477808641975, 9.489571299927379, 11.148419936204148, 12.696562703053933, 14.10453414351852), # 78 (14.386217558299041, 13.057638404354178, 13.793998954046641, 16.525678858024694, 15.667830630194468, 8.674032342630696, 9.925567470884102, 9.799847005029722, 16.210312814357568, 9.4594447489174, 11.118480370961072, 12.669062691021107, 14.091266610939643), # 79 (14.362702033756786, 13.001619540687642, 13.773673268175584, 16.495681528448742, 15.653801541192612, 8.661313062033226, 9.888278329164315, 9.755669867398264, 16.185269490169183, 9.429223486376719, 11.087339033610965, 12.64104517122711, 14.07700885202332), # 80 (14.337643478260873, 12.945009677419357, 13.752987500000001, 16.464833152173917, 15.638823529411765, 8.6478, 9.85064705882353, 9.711800000000002, 16.159675, 9.398908235294119, 11.055056459330146, 12.612526315789475, 14.061796875), # 81 (14.311106017773009, 12.887837806982612, 13.731947410836765, 16.433163036768654, 15.622930484951183, 8.633534125895444, 9.812688506952853, 9.668252766346594, 16.133556229995428, 9.368499718658382, 11.02169318329494, 12.583522296825743, 14.045666688100141), # 82 (14.283153778254908, 12.8301329218107, 13.710558762002744, 16.400700489801395, 15.606156297910111, 8.618556409083983, 9.774417520643375, 9.625043529949703, 16.10694006630087, 9.337998659458297, 10.987309740681672, 12.554049286453447, 14.028654299554185), # 83 (14.253850885668278, 12.77192401433692, 13.688827314814816, 16.36747481884058, 15.588534858387801, 8.602907818930042, 9.735848946986202, 9.582187654320988, 16.07985339506173, 9.307405780682645, 10.951966666666667, 12.524123456790125, 14.010795717592593), # 84 (14.223261465974833, 12.713240076994557, 13.666758830589849, 16.333515331454645, 15.5701000564835, 8.58662932479805, 9.696997633072435, 9.53970050297211, 16.05232310242341, 9.276721805320209, 10.915724496426252, 12.493760979953313, 13.992126950445819), # 85 (14.191449645136279, 12.654110102216913, 13.644359070644722, 16.298851335212028, 15.550885782296458, 8.569761896052432, 9.65787842599317, 9.497597439414724, 16.024376074531325, 9.245947456359774, 10.878643765136749, 12.462978028060553, 13.97268400634431), # 86 (14.15847954911433, 12.594563082437277, 13.621633796296296, 16.26351213768116, 15.53092592592593, 8.552346502057613, 9.618506172839506, 9.455893827160494, 15.996039197530868, 9.215083456790124, 10.840785007974482, 12.43179077322937, 13.95250289351852), # 87 (14.124415303870702, 12.534628010088941, 13.598588768861456, 16.22752704643049, 15.510254377471155, 8.534424112178023, 9.578895720702548, 9.414605029721079, 15.967339357567447, 9.184130529600042, 10.802208760115779, 12.400215387577312, 13.931619620198905), # 88 (14.089321035367092, 12.474333877605204, 13.575229749657066, 16.19092536902845, 15.488905027031391, 8.516035695778085, 9.539061916673392, 9.37374641060814, 15.938303440786468, 9.153089397778317, 10.762975556736963, 12.36826804322191, 13.910070194615912), # 89 (14.053260869565218, 12.413709677419357, 13.551562500000001, 16.153736413043482, 15.466911764705886, 8.497222222222224, 9.499019607843138, 9.333333333333334, 15.908958333333336, 9.121960784313726, 10.723145933014354, 12.335964912280703, 13.887890625), # 90 (14.016298932426789, 12.352784401964689, 13.527592781207133, 16.11598948604402, 15.444308480593882, 8.478024660874867, 9.458783641302887, 9.293381161408323, 15.879330921353455, 9.090745412195057, 10.682780424124285, 12.303322166871226, 13.865116919581618), # 91 (13.978499349913523, 12.2915870436745, 13.503326354595337, 16.0777138955985, 15.421129064794641, 8.458483981100443, 9.418368864143739, 9.253905258344766, 15.84944809099223, 9.059444004411093, 10.641939565243074, 12.270355979111017, 13.841785086591221), # 92 (13.939926247987117, 12.230146594982081, 13.478768981481483, 16.038938949275366, 15.397407407407409, 8.438641152263374, 9.37779012345679, 9.214920987654322, 15.819336728395063, 9.028057283950616, 10.600683891547051, 12.23708252111761, 13.81793113425926), # 93 (13.900643752609293, 12.168492048320722, 13.453926423182445, 15.999693954643051, 15.37317739853143, 8.418537143728091, 9.337062266333147, 9.176443712848654, 15.789023719707364, 8.996585973802416, 10.559073938212535, 12.203517965008546, 13.793591070816188), # 94 (13.860715989741754, 12.106652396123724, 13.42880444101509, 15.960008219269996, 15.34847292826596, 8.398212924859017, 9.296200139863902, 9.138488797439416, 15.758535951074533, 8.96503079695527, 10.517170240415854, 12.169678482901354, 13.768800904492457), # 95 (13.820207085346219, 12.044656630824377, 13.403408796296299, 15.91991105072464, 15.32332788671024, 8.377709465020576, 9.25521859114016, 9.101071604938273, 15.727900308641976, 8.933392476397968, 10.475033333333334, 12.135580246913582, 13.74359664351852), # 96 (13.779181165384388, 11.98253374485597, 13.377745250342937, 15.879431756575416, 15.297776163963531, 8.357067733577198, 9.21413246725302, 9.064207498856883, 15.6971436785551, 8.901671735119288, 10.432723752141296, 12.101239429162758, 13.718014296124831), # 97 (13.737702355817978, 11.9203127306518, 13.35181956447188, 15.83859964439077, 15.271851650125074, 8.336328699893311, 9.17295661529358, 9.027911842706905, 15.666292946959304, 8.86986929610802, 10.390302032016068, 12.066672201766417, 13.69208987054184), # 98 (13.695834782608697, 11.858022580645162, 13.325637500000003, 15.797444021739132, 15.24558823529412, 8.315533333333335, 9.131705882352943, 8.9922, 15.635375000000002, 8.83798588235294, 10.347828708133973, 12.031894736842107, 13.665859375000002), # 99 (13.653642571718258, 11.795692287269347, 13.29920481824417, 15.755994196188944, 15.21901980956992, 8.294722603261699, 9.090395115522204, 8.957087334247829, 15.60441672382259, 8.806022216842843, 10.305364315671335, 11.996923206507354, 13.639358817729768), # 100 (13.611189849108369, 11.733350842957654, 13.272527280521263, 15.714279475308645, 15.192180263051725, 8.273937479042829, 9.049039161892468, 8.922589208962048, 15.573445004572475, 8.773979022566504, 10.262969389804478, 11.961773782879694, 13.612624206961591), # 101 (13.568540740740744, 11.67102724014337, 13.245610648148148, 15.67232916666667, 15.165103485838781, 8.253218930041154, 9.00765286855483, 8.888720987654322, 15.542486728395062, 8.741857022512711, 10.22070446570973, 11.926462638076675, 13.585691550925928), # 102 (13.525759372577088, 11.60875047125979, 13.218460682441702, 15.630172577831457, 15.137823368030341, 8.232607925621096, 8.966251082600394, 8.855498033836307, 15.511568781435757, 8.709656939670245, 10.178630078563414, 11.891005944215824, 13.558596857853223), # 103 (13.482909870579116, 11.546549528740211, 13.191083144718794, 15.587839016371445, 15.110373799725652, 8.212145435147082, 8.924848651120257, 8.822935711019662, 15.480718049839965, 8.677379497027893, 10.13680676354185, 11.855419873414677, 13.53137613597394), # 104 (13.440056360708535, 11.484453405017922, 13.163483796296298, 15.545357789855073, 15.082788671023966, 8.19187242798354, 8.883460421205521, 8.79104938271605, 15.449961419753087, 8.64502541757444, 10.095295055821373, 11.819720597790775, 13.50406539351852), # 105 (13.39726296892706, 11.42249109252622, 13.135668398491084, 15.50275820585078, 15.055101872024531, 8.171829873494895, 8.842101239947283, 8.759854412437129, 15.41932577732053, 8.612595424298663, 10.054155490578298, 11.783924289461654, 13.476700638717421), # 106 (13.3545938211964, 11.360691583698395, 13.10764271262003, 15.460069571927, 15.027347292826596, 8.152058741045574, 8.800785954436646, 8.72936616369456, 15.388838008687703, 8.580090240189355, 10.013448602988953, 11.748047120544847, 13.449317879801098), # 107 (13.312113043478263, 11.299083870967744, 13.079412500000002, 15.417321195652177, 14.999558823529412, 8.132600000000002, 8.759529411764706, 8.699600000000002, 15.358525000000002, 8.547510588235296, 9.973234928229665, 11.712105263157897, 13.421953125000002), # 108 (13.26988476173436, 11.237696946767558, 13.050983521947876, 15.374542384594738, 14.97177035423223, 8.113494619722603, 8.718346459022568, 8.670571284865114, 15.328413637402836, 8.514857191425268, 9.933575001476758, 11.676114889418335, 13.394642382544584), # 109 (13.227973101926404, 11.176559803531132, 13.022361539780524, 15.331762446323136, 14.944015775034297, 8.094783569577809, 8.677251943301325, 8.642295381801555, 15.29853080704161, 8.482130772748057, 9.894529357906551, 11.640092171443701, 13.367421660665297), # 110 (13.186442190016104, 11.11570143369176, 12.993552314814819, 15.2890106884058, 14.91632897603486, 8.076507818930043, 8.636260711692085, 8.614787654320988, 15.26890339506173, 8.449332055192448, 9.856158532695375, 11.60405328135153, 13.340326967592594), # 111 (13.14535615196517, 11.055150829682729, 12.96456160836763, 15.246316418411165, 14.888743847333174, 8.05870833714373, 8.595387611285942, 8.588063465935072, 15.239558287608595, 8.416461761747223, 9.818523061019553, 11.568014391259355, 13.313394311556928), # 112 (13.104705913184263, 10.995038066300333, 12.935464959552897, 15.203767435488858, 14.861245952243188, 8.04141767690032, 8.554736349119478, 8.562193596292849, 15.21059793576207, 8.383626631257822, 9.781693468614014, 11.5320701111062, 13.286621461180511), # 113 (13.064073257060091, 10.935956056935751, 12.906663945030267, 15.161705189788272, 14.833550696392859, 8.024596451941862, 8.514825491774811, 8.537495763307168, 15.182466649998286, 8.351441235077896, 9.745742071958476, 11.496677040958165, 13.25978557982405), # 114 (13.023338864205595, 10.877926078156266, 12.878175705790246, 15.120118307254492, 14.805570749044042, 8.008200917498272, 8.475683510268187, 8.513963715990194, 15.155174970136306, 8.319955459183308, 9.710616315997932, 11.461852615582393, 13.232809284324528), # 115 (12.982451822532688, 10.820863593808383, 12.849945065977423, 15.078932610372966, 14.777263936937292, 7.992192428201937, 8.43724674453905, 8.491532438058591, 15.128653874918964, 8.289110701829367, 9.676248303780074, 11.427532476482286, 13.205650163658248), # 116 (12.941361219953283, 10.76468406773861, 12.82191684973638, 15.038073921629142, 14.748588086813156, 7.976532338685248, 8.399451534526854, 8.47013691322902, 15.102834343089086, 8.258848361271381, 9.642570138352598, 11.39365226516125, 13.178265806801516), # 117 (12.900016144379297, 10.709302963793455, 12.794035881211714, 14.997468063508467, 14.71950102541218, 7.9611820035805945, 8.362234220171041, 8.449712125218136, 15.07764735338951, 8.229109835764664, 9.609513922763194, 11.36014762312269, 13.150613802730636), # 118 (12.858365683722639, 10.654635745819421, 12.766246984548014, 14.95704085849639, 14.689960579474912, 7.946102777520366, 8.325531141411059, 8.430193057742605, 15.053023884563062, 8.199836523564521, 9.577011760059559, 11.326954191870009, 13.122651740421906), # 119 (12.816358925895228, 10.600597877663022, 12.738494983889867, 14.916718129078353, 14.659924575741897, 7.931256015136952, 8.289278638186355, 8.41151469451908, 15.028894915352582, 8.170969822926269, 9.544995753289383, 11.294007612906617, 13.094337208851638), # 120 (12.773944958808976, 10.547104823170763, 12.710724703381864, 14.876425697739808, 14.629350840953688, 7.9166030710627435, 8.253413050436373, 8.39361201926423, 15.0051914245009, 8.142451132105215, 9.513398005500363, 11.261243527735912, 13.065627796996127), # 121 (12.731072870375797, 10.494072046189146, 12.682880967168597, 14.836089386966199, 14.598197201850828, 7.902105299930128, 8.217870718100565, 8.376420015694709, 14.981844390750846, 8.11422184935667, 9.482150619740192, 11.228597577861303, 13.036481093831679), # 122 (12.687691748507607, 10.441415010564684, 12.65490859939465, 14.795635019242972, 14.56642148517387, 7.887724056371495, 8.182587981118376, 8.359873667527177, 14.958784792845258, 8.086223372935942, 9.451185699056563, 11.19600540478619, 13.0068546883346), # 123 (12.643750681116316, 10.389049180143882, 12.62675242420462, 14.754988417055582, 14.533981517663353, 7.873420695019235, 8.147501179429248, 8.343907958478297, 14.935943609526962, 8.058397101098347, 9.420435346497168, 11.163402650013985, 12.976706169481197), # 124 (12.599198756113843, 10.33689001877325, 12.598357265743093, 14.714075402889465, 14.500835126059833, 7.859156570505739, 8.112546652972636, 8.328457872264728, 14.913251819538791, 8.030684432099187, 9.389831665109703, 11.130724955048088, 12.94599312624776), # 125 (12.553985061412101, 10.284852990299292, 12.56966794815466, 14.672821799230077, 14.466940137103851, 7.844893037463395, 8.077660741687978, 8.31345839260313, 14.890640401623585, 8.00302676419378, 9.359306757941859, 11.097907961391908, 12.91467314761061), # 126 (12.508058684923006, 10.232853558568515, 12.540629295583907, 14.63115342856286, 14.432254377535958, 7.830591450524592, 8.042779785514732, 8.298844503210164, 14.86804033452417, 7.975365495637434, 9.32879272804133, 11.064887310548842, 12.88270382254604), # 127 (12.461368714558466, 10.18080718742743, 12.51118613217543, 14.588996113373266, 14.396735674096707, 7.816213164321722, 8.007840124392336, 8.284551187802489, 14.845382596983379, 7.947642024685458, 9.298221678455814, 11.031598644022305, 12.850042740030352), # 128 (12.413864238230394, 10.128629340722538, 12.481283282073816, 14.546275676146736, 14.360341853526638, 7.801719533487173, 7.972778098260239, 8.270513430096765, 14.822598167744045, 7.919797749593164, 9.267525712233, 10.997977603315691, 12.816647489039854), # 129 (12.365494343850713, 10.076235482300353, 12.450865569423652, 14.502917939368722, 14.3230307425663, 7.7870719126533325, 7.937530047057888, 8.256666213809652, 14.799618025549002, 7.89177406861586, 9.236636932420582, 10.963959829932413, 12.78247565855085), # 130 (12.316208119331334, 10.023541076007378, 12.419877818369534, 14.458848725524668, 14.284760167956243, 7.772231656452593, 7.902032310724733, 8.24294452265781, 14.776373149141081, 7.86351238000886, 9.205487442066255, 10.929480965375875, 12.747484837539638), # 131 (12.265954652584163, 9.970461585690122, 12.388264853056045, 14.413993857100023, 14.245487956437017, 7.757160119517344, 7.8662212292002165, 8.229283340357902, 14.752794517263117, 7.834954082027471, 9.17400934421771, 10.894476651149478, 12.711632614982527), # 132 (12.21468303152113, 9.91691247519509, 12.355971497627777, 14.368279156580234, 14.205171934749162, 7.741818656479974, 7.830033142423786, 8.215617650626585, 14.728813108657938, 7.806040572927006, 9.142134741922645, 10.85888252875663, 12.674876579855821), # 133 (12.162342344054133, 9.862809208368793, 12.322942576229327, 14.321630446450746, 14.163769929633231, 7.726168621972872, 7.79340439033489, 8.201882437180522, 14.704359902068381, 7.776713250962773, 9.109795738228751, 10.822634239700733, 12.637174321135817), # 134 (12.108881678095097, 9.808067249057736, 12.289122913005274, 14.273973549197011, 14.12123976782977, 7.710171370628429, 7.756271312872975, 8.18801268373637, 14.679365876237274, 7.746913514390087, 9.07692443618372, 10.785667425485194, 12.59848342779883), # 135 (12.05425012155593, 9.752602061108423, 12.254457332100213, 14.225234287304469, 14.077539276079325, 7.693788257079036, 7.718570249977489, 8.173943374010788, 14.65376200990745, 7.716582761464252, 9.043452938835248, 10.747917727613418, 12.558761488821151), # 136 (11.998396762348548, 9.696329108367367, 12.218890657658735, 14.175338483258576, 14.032626281122448, 7.6769806359570785, 7.6802375415878785, 8.159609491720442, 14.627479281821747, 7.685662390440583, 9.009313349231029, 10.709320787588808, 12.517966093179089), # 137 (11.941270688384867, 9.639163854681073, 12.182367713825425, 14.12421195954477, 13.986458609699687, 7.6597098618949495, 7.6412095276435865, 8.144946020581987, 14.600448670722995, 7.654093799574386, 8.974437770418753, 10.66981224691477, 12.476054829848946), # 138 (11.882820987576796, 9.581021763896047, 12.144833324744877, 14.071780538648504, 13.938994088551583, 7.641937289525037, 7.601422548084064, 8.129887944312085, 14.572601155354022, 7.621818387120976, 8.938758305446116, 10.62932774709471, 12.432985287807028), # 139 (11.822996747836257, 9.521818299858795, 12.106232314561684, 14.017970043055223, 13.890190544418692, 7.623624273479732, 7.560812942848756, 8.114370246627395, 14.543867714457667, 7.588777551335661, 8.902207057360812, 10.58780292963203, 12.38871505602964), # 140 (11.761747057075162, 9.46146892641583, 12.066509507420426, 13.962706295250376, 13.840005804041555, 7.604732168391422, 7.519317051877113, 8.09832791124458, 14.514179326776754, 7.554912690473753, 8.864716129210535, 10.545173436030137, 12.34320172349308), # 141 (11.69902100320542, 9.399889107413653, 12.0256097274657, 13.90591511771941, 13.788397694160723, 7.585222328892499, 7.476871215108577, 8.081695921880296, 14.48346697105412, 7.52016520279056, 8.826217624042977, 10.501374907792433, 12.296402879173653), # 142 (11.634767674138946, 9.336994306698774, 11.983477798842097, 13.847522332947767, 13.735324041516742, 7.56505610961535, 7.4334117724825965, 8.064409262251205, 14.451661626032607, 7.484476486541395, 8.786643644905832, 10.456342986422326, 12.248276112047666), # 143 (11.56893615778766, 9.2726999881177, 11.9400585456942, 13.787453763420901, 13.680742672850162, 7.544194865192366, 7.3888750639386185, 8.04640291607397, 14.418694270455035, 7.4477879399815645, 8.745926294846791, 10.41001331342322, 12.198779011091421), # 144 (11.501475542063469, 9.20692161551694, 11.895296792166606, 13.725635231624254, 13.624611414901528, 7.5225999502559375, 7.343197429416091, 8.027611867065247, 14.384495883064238, 7.410040961366383, 8.703997676913554, 10.36232153029852, 12.14786916528122), # 145 (11.432334914878291, 9.139574652742999, 11.849137362403903, 13.661992560043277, 13.566888094411391, 7.500232719438453, 7.2963152088544625, 8.007971098941699, 14.34899744260305, 7.37117694895116, 8.660789894153808, 10.313203278551628, 12.095504163593366), # 146 (11.361463364144042, 9.070574563642383, 11.801525080550675, 13.596451571163414, 13.507530538120294, 7.477054527372301, 7.2481647421931745, 7.987415595419982, 14.312129927814308, 7.331137300991204, 8.616235049615252, 10.262594199685955, 12.041641595004167), # 147 (11.288809977772631, 8.999836812061604, 11.752404770751518, 13.528938087470117, 13.446496572768787, 7.453026728689875, 7.198682369371678, 7.965880340216761, 14.273824317440841, 7.289863415741826, 8.570265246345576, 10.210429935204898, 11.986239048489919), # 148 (11.214323843675977, 8.927276861847163, 11.701721257151021, 13.459377931448826, 13.38374402509742, 7.42811067802356, 7.147804430329418, 7.943300317048694, 14.234011590225474, 7.247296691458339, 8.522812587392474, 10.156646126611868, 11.929254113026934), # 149 (11.137954049765991, 8.852810176845571, 11.649419363893772, 13.387696925584994, 13.319230721846738, 7.402267730005749, 7.0954672650058415, 7.91961050963244, 14.192622724911054, 7.2033785263960475, 8.473809175803641, 10.101178415410269, 11.870644377591507), # 150 (11.059649683954586, 8.776352220903336, 11.59544391512436, 13.313820892364063, 13.252914489757288, 7.375459239268828, 7.041607213340397, 7.8947459016846615, 14.149588700240406, 7.15805031881027, 8.423187114626767, 10.043962443103501, 11.810367431159946), # 151 (10.979359834153682, 8.697818457866962, 11.539739734987382, 13.237675654271488, 13.184753155569618, 7.34764656044519, 6.986160615272531, 7.8686414769220185, 14.10484049495636, 7.11125346695631, 8.37087850690955, 9.984933851194974, 11.748380862708558), # 152 (10.897033588275185, 8.61712435158296, 11.482251647627416, 13.159187033792707, 13.11470454602428, 7.318791048167222, 6.929063810741687, 7.841232219061167, 14.058309087801755, 7.062929369089481, 8.316815455699683, 9.92402828118809, 11.68464226121364), # 153 (10.81262003423102, 8.534185365897834, 11.422924477189063, 13.078280853413174, 13.042726487861813, 7.288854057067317, 6.87025313968732, 7.8124531118187726, 14.009925457519413, 7.013019423465095, 8.260930064044857, 9.861181374586256, 11.6191092156515), # 154 (10.72606825993309, 8.448916964658093, 11.361703047816906, 12.99488293561833, 12.968776807822776, 7.257796941777861, 6.809664942048866, 7.782239138911491, 13.95962058285218, 6.9614650283384565, 8.203154434992767, 9.796328772892876, 11.551739314998438), # 155 (10.637327353293314, 8.361234611710243, 11.298532183655539, 12.908919102893627, 12.892813332647707, 7.225581056931246, 6.74723555776578, 7.750525284055986, 13.907325442542877, 6.9082075819648825, 8.143420671591107, 9.729406117611353, 11.48249014823076), # 156 (10.546346402223609, 8.271053770900794, 11.233356708849547, 12.820315177724513, 12.81479388907716, 7.19216775715986, 6.6829013267775075, 7.717246530968915, 13.852971015334345, 6.853188482599679, 8.08166087688757, 9.660349050245092, 11.411319304324769), # 157 (10.450553324967336, 8.176634369081162, 11.163028735463298, 12.725677414311741, 12.731153548219398, 7.155434266843955, 6.615149409299001, 7.680115733289122, 13.792326928238738, 6.794712282807602, 8.01583405355452, 9.586639389872076, 11.335080203181485), # 158 (10.335201473769764, 8.06829144743927, 11.069432945764184, 12.605568022303835, 12.62126783369428, 7.103165507209945, 6.535497868740003, 7.626098945870136, 13.700998165711002, 6.723193391738244, 7.934383709866593, 9.493907533156353, 11.235598705688274), # 159 (10.198820932866035, 7.945135419957, 10.950689341138245, 12.458008514572404, 12.482988183885514, 7.034077814466758, 6.443141247737298, 7.553838865338286, 13.576395318120113, 6.637687912608051, 7.8361633120533565, 9.380702728442985, 11.110988852451014), # 160 (10.042510876420344, 7.8079692153126565, 10.808065760674433, 12.28440150525942, 12.317750373994958, 6.94900813819844, 6.338754024409627, 7.464240746353693, 13.420161673798626, 6.5389214704393135, 7.7220383164395905, 9.248074456470599, 10.962523662746737), # 161 (9.8673704785969, 7.657595762184535, 10.642830043461695, 12.086149608506858, 12.126990179224487, 6.848793427989039, 6.223010676875733, 7.358209843576484, 13.233940521079093, 6.427619690254325, 7.592874179350069, 9.09707219797781, 10.791476155852466), # 162 (9.674498913559898, 7.494817989250934, 10.456250028588983, 11.864655438456708, 11.912143374775964, 6.734270633422602, 6.096585683254362, 7.2366514116667755, 13.019375148294069, 6.304508197075376, 7.449536357109572, 8.928745433703247, 10.599119351045232), # 163 (9.464995355473539, 7.320438825190149, 10.249593555145248, 11.621321609250947, 11.674645735851264, 6.606276704083181, 5.960153521664253, 7.100470705284697, 12.778108843776113, 6.170312615924756, 7.292890306042875, 8.744143644385526, 10.386726267602059), # 164 (9.239958978502024, 7.135261198680485, 10.024128462219437, 11.357550735031554, 11.415933037652254, 6.465648589554821, 5.814388670224151, 6.950572979090365, 12.511784895857772, 6.02575857182476, 7.123801482474756, 8.544316310763268, 10.155569924799979), # 165 (9.000488956809557, 6.940088038400237, 9.7811225889005, 11.074745429940503, 11.137441055380801, 6.313223239421572, 5.659965607052801, 6.787863487743908, 12.222046592871603, 5.871571689797677, 6.943135342729992, 8.330312913575103, 9.906923341916015), # 166 (8.747684464560333, 6.735722273027703, 9.521843774277388, 10.774308308119782, 10.840605564238773, 6.149837603267482, 5.497558810268945, 6.613247485905448, 11.91053722315016, 5.7084775948658, 6.751757343133359, 8.103182933559642, 9.642059538227196), # 167 (8.482644675918554, 6.52296683124118, 9.247559857439049, 10.457641983711365, 10.526862339428039, 5.9763286306765995, 5.327842757991326, 6.427630228235103, 11.578900075025999, 5.5372019120514215, 6.550532940009634, 7.863975851455517, 9.362251533010546), # 168 (8.206468765048422, 6.302624641718972, 8.959538677474432, 10.126149070857236, 10.197647156150468, 5.793533271232973, 5.151491928338689, 6.231916969393004, 11.228778436831673, 5.358470266376831, 6.3403275896835956, 7.613741148001342, 9.0687723455431), # 169 (7.9202559061141375, 6.0754986331393726, 8.659048073472489, 9.781232183699368, 9.854395789607928, 5.60228847452065, 4.9691807994297745, 6.027012964039266, 10.861815596899735, 5.173008282864322, 6.122006748480023, 7.353528303935743, 8.762894995101878), # 170 (7.6251052732799005, 5.842391734180682, 8.34735588452217, 9.424293936379751, 9.498544015002288, 5.403431190123678, 4.781583849383328, 5.813823466834017, 10.47965484356274, 4.981541586536184, 5.896435872723688, 7.0843867999973416, 8.445892500963913), # 171 (7.322116040709912, 5.604106873521197, 8.025729949712423, 9.056736943040356, 9.131527607535416, 5.197798367626108, 4.5893755563180925, 5.593253732437379, 10.083939465153241, 4.784795802414712, 5.664480418739371, 6.80736611692476, 8.119037882406225), # 172 (7.012387382568372, 5.3614469798392195, 7.695438108132197, 8.679963817823166, 8.754782342409182, 4.9862269566119855, 4.39323039835281, 5.366209015509473, 9.676312750003792, 4.583496555522195, 5.427005842851849, 6.523515735456615, 7.783604158705848), # 173 (6.697018473019482, 5.115214981813045, 7.357748198870443, 8.295377174870158, 8.369743994825454, 4.76955390666536, 4.193822853606226, 5.133594570710425, 9.25841798644695, 4.3783694708809255, 5.1848776013858995, 6.233885136331535, 7.440864349139807), # 174 (6.377108486227438, 4.866213808120973, 7.013928061016112, 7.904379628323315, 7.977848339986097, 4.54861616737028, 3.9918274001970815, 4.896315652700355, 8.831898462815268, 4.170140173513194, 4.938961150666297, 5.939523800288141, 7.092091472985131), # 175 (6.053756596356447, 4.615246387441302, 6.66524553365815, 7.508373792324615, 7.580531153092983, 4.324250688310793, 3.787918516244121, 4.655277516139389, 8.3983974674413, 3.959534288441294, 4.690121947017822, 5.641481208065051, 6.738558549518844), # 176 (5.7280619775707065, 4.363115648452332, 6.3129684558855095, 7.108762281016037, 7.179228209347984, 4.097294419070949, 3.582770679866088, 4.411385415687646, 7.959558288657599, 3.7472774406875144, 4.43922544676525, 5.340806840400891, 6.381538598017975), # 177 (5.401123804034416, 4.11062451983236, 5.95836466678714, 6.7069477085395635, 6.775375283952959, 3.8685843092347962, 3.3770583691817246, 4.165544606005252, 7.51702421479672, 3.5340952552741505, 4.187137106233358, 5.038550178034279, 6.022304637759553), # 178 (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 179 ) passenger_arriving_acc = ( (9, 10, 5, 5, 3, 2, 2, 3, 3, 1, 1, 0, 0, 6, 9, 0, 8, 12, 3, 4, 1, 0, 2, 2, 2, 0), # 0 (14, 20, 14, 16, 9, 4, 2, 8, 4, 2, 2, 0, 0, 17, 14, 5, 14, 18, 4, 6, 3, 1, 6, 2, 2, 0), # 1 (21, 29, 17, 19, 12, 7, 5, 13, 8, 6, 4, 0, 0, 26, 20, 10, 21, 27, 5, 11, 7, 3, 8, 4, 4, 0), # 2 (26, 39, 28, 28, 24, 10, 11, 19, 12, 7, 4, 0, 0, 32, 30, 12, 29, 35, 13, 13, 9, 6, 10, 6, 4, 0), # 3 (37, 48, 34, 36, 31, 13, 15, 24, 16, 8, 4, 0, 0, 40, 42, 15, 34, 45, 16, 13, 13, 7, 11, 6, 7, 0), # 4 (48, 57, 43, 49, 34, 16, 22, 31, 20, 10, 4, 2, 0, 47, 55, 22, 42, 54, 21, 18, 14, 9, 16, 7, 8, 0), # 5 (60, 70, 51, 57, 42, 20, 23, 35, 23, 14, 7, 4, 0, 56, 63, 29, 51, 60, 23, 25, 17, 15, 19, 7, 9, 0), # 6 (72, 78, 59, 68, 55, 23, 26, 36, 27, 15, 8, 4, 0, 68, 70, 40, 55, 69, 27, 28, 19, 18, 21, 8, 10, 0), # 7 (86, 89, 76, 78, 63, 26, 29, 38, 30, 16, 11, 4, 0, 79, 77, 49, 61, 80, 29, 35, 23, 19, 24, 9, 10, 0), # 8 (97, 99, 83, 87, 71, 34, 36, 43, 35, 16, 14, 7, 0, 96, 89, 58, 67, 90, 38, 39, 25, 22, 26, 13, 11, 0), # 9 (107, 111, 94, 97, 78, 37, 42, 46, 42, 19, 16, 9, 0, 114, 102, 70, 76, 102, 44, 41, 28, 28, 28, 16, 13, 0), # 10 (122, 122, 104, 108, 90, 44, 46, 49, 45, 20, 19, 11, 0, 124, 107, 83, 84, 114, 50, 47, 31, 29, 29, 20, 14, 0), # 11 (133, 138, 114, 119, 99, 46, 53, 53, 48, 23, 20, 13, 0, 141, 115, 92, 89, 122, 55, 52, 31, 35, 33, 21, 15, 0), # 12 (144, 155, 124, 129, 105, 53, 57, 55, 54, 24, 23, 14, 0, 155, 127, 96, 92, 127, 61, 56, 36, 38, 40, 24, 16, 0), # 13 (156, 176, 136, 141, 116, 60, 61, 59, 58, 27, 28, 14, 0, 165, 139, 102, 99, 139, 67, 63, 37, 42, 44, 24, 16, 0), # 14 (162, 188, 145, 162, 128, 63, 64, 63, 64, 29, 29, 16, 0, 174, 158, 110, 102, 145, 74, 70, 43, 50, 44, 24, 18, 0), # 15 (169, 200, 155, 175, 140, 70, 69, 67, 68, 32, 31, 19, 0, 186, 166, 114, 108, 159, 84, 74, 45, 54, 48, 25, 19, 0), # 16 (184, 215, 173, 190, 147, 79, 73, 70, 73, 38, 34, 20, 0, 198, 176, 121, 119, 169, 90, 76, 50, 61, 51, 26, 19, 0), # 17 (198, 229, 189, 207, 162, 83, 79, 74, 77, 39, 36, 21, 0, 214, 193, 128, 123, 176, 97, 85, 55, 67, 55, 28, 21, 0), # 18 (221, 245, 201, 220, 168, 89, 85, 77, 84, 39, 37, 22, 0, 231, 211, 139, 134, 191, 110, 91, 58, 72, 61, 32, 23, 0), # 19 (233, 257, 214, 233, 178, 96, 91, 81, 90, 41, 39, 23, 0, 241, 228, 152, 141, 202, 117, 96, 63, 78, 66, 36, 24, 0), # 20 (249, 275, 226, 246, 186, 102, 93, 87, 101, 43, 40, 24, 0, 248, 240, 162, 151, 218, 121, 100, 70, 82, 69, 37, 26, 0), # 21 (263, 288, 234, 257, 193, 109, 95, 90, 110, 47, 42, 24, 0, 266, 249, 168, 163, 230, 128, 103, 73, 85, 77, 37, 29, 0), # 22 (279, 297, 244, 265, 207, 118, 101, 92, 119, 50, 44, 25, 0, 282, 270, 177, 167, 235, 135, 109, 79, 86, 81, 38, 30, 0), # 23 (290, 310, 255, 275, 213, 122, 111, 98, 125, 51, 49, 26, 0, 300, 287, 193, 170, 247, 148, 117, 81, 90, 82, 42, 31, 0), # 24 (301, 326, 272, 282, 225, 127, 119, 103, 131, 53, 49, 28, 0, 310, 301, 203, 177, 267, 153, 129, 85, 93, 85, 45, 33, 0), # 25 (319, 341, 290, 290, 237, 131, 133, 105, 138, 54, 50, 29, 0, 319, 311, 213, 186, 283, 156, 133, 87, 97, 89, 46, 34, 0), # 26 (328, 350, 298, 299, 242, 138, 144, 110, 146, 56, 53, 30, 0, 329, 324, 222, 194, 295, 169, 136, 88, 100, 93, 47, 35, 0), # 27 (346, 364, 315, 315, 259, 140, 151, 117, 153, 63, 55, 32, 0, 349, 337, 234, 202, 302, 170, 140, 90, 106, 94, 49, 37, 0), # 28 (362, 380, 324, 330, 265, 144, 155, 124, 158, 66, 63, 33, 0, 361, 351, 245, 211, 313, 177, 142, 97, 108, 101, 55, 37, 0), # 29 (375, 392, 341, 344, 277, 151, 164, 128, 160, 67, 66, 33, 0, 383, 365, 254, 220, 333, 183, 151, 100, 119, 104, 55, 39, 0), # 30 (392, 401, 351, 366, 291, 157, 168, 130, 163, 72, 69, 33, 0, 402, 378, 263, 227, 348, 186, 153, 103, 124, 106, 56, 40, 0), # 31 (404, 415, 367, 378, 302, 168, 173, 135, 169, 73, 71, 34, 0, 417, 390, 276, 234, 356, 199, 157, 108, 128, 113, 57, 42, 0), # 32 (415, 431, 382, 395, 305, 175, 174, 141, 175, 74, 75, 35, 0, 435, 400, 285, 242, 370, 201, 160, 111, 133, 121, 58, 43, 0), # 33 (423, 442, 394, 410, 323, 184, 178, 147, 180, 76, 79, 35, 0, 448, 413, 290, 246, 381, 208, 166, 116, 135, 123, 59, 43, 0), # 34 (446, 458, 405, 415, 336, 187, 182, 151, 184, 79, 82, 36, 0, 461, 425, 298, 252, 390, 215, 170, 121, 141, 129, 65, 44, 0), # 35 (459, 470, 422, 431, 350, 190, 186, 155, 189, 82, 83, 36, 0, 472, 430, 304, 263, 396, 224, 176, 124, 147, 134, 66, 45, 0), # 36 (474, 479, 435, 443, 358, 195, 195, 163, 197, 83, 84, 37, 0, 494, 448, 315, 270, 410, 235, 184, 126, 152, 141, 69, 45, 0), # 37 (489, 493, 451, 456, 366, 199, 199, 167, 201, 89, 85, 38, 0, 507, 456, 331, 273, 414, 242, 191, 129, 159, 147, 71, 46, 0), # 38 (505, 510, 459, 470, 375, 203, 203, 170, 207, 89, 89, 38, 0, 524, 471, 342, 280, 427, 248, 195, 132, 164, 153, 71, 46, 0), # 39 (516, 523, 470, 477, 384, 206, 204, 176, 215, 92, 92, 38, 0, 539, 478, 348, 292, 438, 254, 200, 139, 169, 159, 74, 47, 0), # 40 (531, 534, 481, 484, 394, 211, 210, 179, 223, 97, 93, 39, 0, 548, 487, 361, 299, 447, 266, 206, 142, 172, 162, 77, 48, 0), # 41 (552, 546, 495, 496, 401, 211, 214, 184, 227, 97, 93, 41, 0, 570, 501, 368, 303, 461, 279, 212, 147, 179, 168, 78, 48, 0), # 42 (569, 562, 503, 508, 414, 212, 221, 188, 233, 98, 95, 41, 0, 585, 506, 377, 311, 474, 283, 221, 151, 180, 171, 80, 49, 0), # 43 (580, 579, 519, 518, 421, 217, 228, 192, 237, 101, 96, 45, 0, 603, 520, 385, 319, 489, 290, 226, 158, 184, 175, 80, 52, 0), # 44 (592, 593, 531, 532, 431, 221, 232, 196, 240, 103, 97, 47, 0, 616, 533, 398, 327, 495, 295, 231, 160, 188, 177, 84, 53, 0), # 45 (610, 614, 541, 548, 443, 225, 236, 202, 246, 106, 98, 47, 0, 624, 538, 405, 334, 508, 303, 236, 164, 198, 179, 84, 56, 0), # 46 (617, 624, 552, 564, 452, 233, 241, 205, 254, 106, 101, 48, 0, 644, 555, 413, 337, 515, 315, 242, 168, 205, 183, 86, 59, 0), # 47 (636, 636, 560, 569, 459, 237, 244, 208, 259, 109, 102, 49, 0, 653, 562, 425, 348, 534, 324, 250, 172, 213, 185, 89, 60, 0), # 48 (645, 643, 574, 589, 476, 239, 251, 211, 263, 112, 106, 52, 0, 666, 573, 435, 357, 547, 331, 254, 175, 216, 191, 90, 61, 0), # 49 (660, 664, 587, 601, 483, 245, 258, 215, 267, 113, 107, 54, 0, 684, 585, 446, 365, 560, 341, 261, 177, 220, 197, 93, 63, 0), # 50 (671, 673, 600, 616, 492, 247, 264, 217, 271, 120, 108, 56, 0, 705, 603, 455, 374, 574, 346, 266, 178, 225, 200, 96, 66, 0), # 51 (686, 688, 611, 626, 500, 251, 267, 222, 277, 121, 109, 57, 0, 712, 610, 467, 385, 588, 351, 271, 180, 229, 200, 97, 69, 0), # 52 (697, 699, 619, 639, 509, 255, 272, 227, 279, 124, 112, 58, 0, 725, 625, 475, 389, 604, 356, 277, 186, 234, 203, 99, 70, 0), # 53 (714, 717, 625, 654, 518, 259, 277, 233, 289, 128, 114, 60, 0, 746, 642, 489, 397, 620, 362, 281, 192, 240, 206, 100, 71, 0), # 54 (724, 729, 643, 664, 529, 266, 278, 240, 296, 131, 115, 60, 0, 760, 649, 504, 404, 627, 369, 286, 195, 241, 216, 100, 71, 0), # 55 (730, 741, 656, 678, 544, 268, 282, 244, 300, 132, 118, 61, 0, 781, 665, 515, 410, 642, 373, 293, 202, 246, 220, 104, 72, 0), # 56 (736, 757, 675, 695, 548, 272, 289, 250, 308, 134, 118, 61, 0, 800, 679, 521, 412, 655, 383, 299, 206, 250, 220, 106, 73, 0), # 57 (751, 770, 690, 714, 556, 275, 295, 256, 313, 134, 120, 63, 0, 814, 688, 529, 418, 669, 386, 308, 212, 257, 224, 110, 74, 0), # 58 (764, 774, 700, 728, 563, 279, 302, 259, 320, 140, 120, 65, 0, 824, 700, 538, 428, 680, 392, 311, 217, 264, 228, 112, 74, 0), # 59 (778, 798, 706, 745, 577, 285, 306, 260, 321, 142, 121, 68, 0, 838, 710, 550, 440, 699, 397, 320, 218, 270, 234, 113, 74, 0), # 60 (791, 818, 715, 755, 588, 292, 311, 269, 330, 143, 122, 70, 0, 854, 722, 561, 447, 715, 410, 323, 224, 276, 238, 113, 75, 0), # 61 (808, 825, 727, 767, 596, 297, 316, 273, 336, 146, 123, 70, 0, 867, 730, 571, 457, 726, 414, 327, 229, 279, 244, 117, 78, 0), # 62 (816, 839, 746, 779, 605, 302, 321, 278, 338, 146, 130, 70, 0, 879, 743, 574, 464, 736, 419, 328, 233, 282, 245, 118, 78, 0), # 63 (832, 849, 757, 787, 617, 304, 328, 286, 343, 147, 134, 70, 0, 893, 759, 582, 475, 750, 426, 333, 237, 290, 249, 119, 79, 0), # 64 (839, 862, 772, 801, 626, 306, 332, 290, 346, 148, 136, 70, 0, 909, 771, 601, 479, 763, 432, 338, 238, 301, 253, 120, 80, 0), # 65 (857, 876, 783, 812, 637, 308, 332, 295, 352, 154, 137, 71, 0, 924, 781, 608, 487, 777, 442, 340, 240, 306, 257, 120, 81, 0), # 66 (872, 893, 792, 824, 652, 312, 339, 302, 360, 154, 139, 74, 0, 941, 791, 614, 498, 786, 446, 352, 242, 307, 265, 123, 81, 0), # 67 (882, 904, 798, 835, 664, 316, 346, 306, 368, 156, 141, 75, 0, 951, 799, 623, 505, 797, 449, 360, 245, 311, 269, 128, 81, 0), # 68 (896, 914, 807, 851, 670, 320, 354, 313, 371, 157, 141, 79, 0, 963, 809, 632, 510, 809, 456, 369, 248, 315, 273, 130, 81, 0), # 69 (915, 925, 815, 869, 683, 326, 361, 317, 375, 157, 146, 80, 0, 979, 817, 642, 516, 820, 462, 375, 250, 321, 277, 131, 83, 0), # 70 (932, 931, 828, 880, 698, 335, 363, 318, 384, 161, 148, 80, 0, 990, 827, 650, 520, 827, 467, 384, 254, 327, 282, 131, 83, 0), # 71 (947, 940, 847, 897, 708, 340, 372, 324, 391, 164, 149, 80, 0, 1006, 838, 662, 537, 836, 469, 392, 261, 334, 286, 133, 86, 0), # 72 (964, 951, 858, 912, 717, 346, 375, 331, 400, 166, 151, 80, 0, 1022, 847, 667, 542, 852, 475, 399, 266, 336, 287, 135, 86, 0), # 73 (973, 959, 866, 926, 729, 357, 378, 333, 403, 169, 151, 80, 0, 1040, 864, 680, 546, 865, 480, 404, 267, 341, 291, 139, 86, 0), # 74 (984, 972, 880, 937, 742, 364, 384, 336, 410, 172, 153, 81, 0, 1054, 878, 689, 555, 872, 485, 410, 268, 349, 295, 142, 87, 0), # 75 (1003, 984, 896, 947, 753, 369, 392, 339, 413, 178, 154, 81, 0, 1061, 890, 699, 563, 891, 494, 417, 270, 354, 301, 146, 87, 0), # 76 (1013, 992, 910, 959, 766, 374, 401, 344, 418, 179, 157, 81, 0, 1079, 911, 708, 574, 897, 496, 419, 274, 362, 303, 149, 88, 0), # 77 (1025, 1006, 916, 976, 781, 380, 405, 348, 424, 181, 159, 81, 0, 1090, 923, 717, 579, 908, 502, 423, 276, 367, 310, 149, 88, 0), # 78 (1037, 1014, 926, 989, 791, 386, 409, 354, 430, 184, 161, 81, 0, 1106, 930, 724, 587, 913, 506, 428, 282, 376, 312, 150, 88, 0), # 79 (1054, 1031, 938, 998, 806, 394, 411, 357, 435, 185, 162, 82, 0, 1116, 945, 737, 592, 926, 510, 434, 286, 383, 315, 151, 88, 0), # 80 (1067, 1042, 950, 1006, 818, 400, 419, 363, 443, 187, 165, 82, 0, 1135, 954, 749, 602, 938, 514, 439, 288, 388, 316, 152, 89, 0), # 81 (1080, 1055, 957, 1021, 829, 407, 425, 369, 448, 189, 165, 89, 0, 1153, 968, 756, 614, 945, 517, 442, 296, 391, 322, 155, 91, 0), # 82 (1092, 1061, 970, 1027, 835, 412, 433, 372, 454, 193, 167, 89, 0, 1170, 977, 764, 622, 957, 524, 447, 299, 398, 326, 157, 91, 0), # 83 (1103, 1074, 984, 1043, 846, 419, 441, 379, 460, 195, 168, 90, 0, 1177, 993, 772, 627, 962, 527, 453, 303, 403, 329, 159, 91, 0), # 84 (1115, 1088, 1005, 1057, 860, 426, 447, 382, 468, 199, 169, 91, 0, 1186, 1008, 782, 629, 975, 530, 459, 307, 409, 332, 162, 91, 0), # 85 (1131, 1099, 1016, 1068, 875, 430, 451, 386, 474, 200, 171, 92, 0, 1197, 1015, 790, 640, 985, 538, 462, 310, 414, 340, 164, 91, 0), # 86 (1148, 1106, 1027, 1080, 881, 433, 455, 388, 479, 202, 172, 92, 0, 1208, 1031, 798, 650, 992, 546, 467, 316, 421, 349, 165, 91, 0), # 87 (1159, 1123, 1037, 1089, 891, 439, 461, 390, 482, 206, 177, 92, 0, 1229, 1043, 807, 660, 1005, 547, 469, 321, 427, 354, 167, 92, 0), # 88 (1174, 1132, 1051, 1104, 898, 443, 465, 395, 486, 207, 180, 93, 0, 1247, 1057, 816, 664, 1014, 553, 478, 325, 432, 358, 169, 92, 0), # 89 (1187, 1140, 1060, 1115, 909, 452, 472, 397, 489, 209, 180, 93, 0, 1260, 1070, 823, 667, 1020, 562, 482, 329, 438, 359, 172, 93, 0), # 90 (1205, 1153, 1067, 1129, 918, 456, 476, 397, 497, 211, 182, 93, 0, 1274, 1080, 834, 672, 1027, 566, 492, 332, 440, 361, 177, 95, 0), # 91 (1217, 1165, 1074, 1142, 931, 463, 477, 405, 502, 215, 187, 94, 0, 1288, 1097, 842, 680, 1038, 570, 497, 335, 445, 366, 179, 96, 0), # 92 (1228, 1170, 1086, 1154, 935, 467, 480, 409, 512, 218, 188, 94, 0, 1301, 1107, 852, 686, 1059, 576, 501, 338, 447, 369, 181, 97, 0), # 93 (1242, 1183, 1098, 1167, 948, 469, 484, 416, 515, 220, 190, 95, 0, 1313, 1120, 856, 693, 1074, 582, 506, 339, 453, 374, 181, 97, 0), # 94 (1251, 1202, 1109, 1178, 955, 474, 486, 420, 518, 224, 190, 98, 0, 1325, 1137, 863, 704, 1085, 588, 511, 341, 456, 377, 181, 99, 0), # 95 (1260, 1210, 1123, 1188, 962, 480, 494, 427, 527, 227, 191, 100, 0, 1335, 1147, 872, 712, 1092, 594, 514, 350, 465, 382, 186, 99, 0), # 96 (1273, 1220, 1131, 1202, 972, 484, 496, 437, 532, 229, 193, 103, 0, 1346, 1150, 880, 720, 1104, 601, 519, 351, 473, 383, 188, 100, 0), # 97 (1290, 1228, 1143, 1214, 984, 491, 500, 439, 536, 233, 193, 105, 0, 1354, 1159, 885, 726, 1114, 606, 522, 352, 480, 387, 192, 102, 0), # 98 (1304, 1238, 1154, 1229, 996, 495, 505, 442, 540, 234, 193, 107, 0, 1368, 1172, 898, 733, 1123, 610, 526, 352, 482, 393, 196, 104, 0), # 99 (1313, 1247, 1165, 1239, 1007, 500, 507, 447, 548, 235, 193, 112, 0, 1380, 1180, 910, 741, 1135, 612, 533, 355, 492, 397, 200, 105, 0), # 100 (1329, 1258, 1175, 1246, 1019, 503, 509, 450, 554, 236, 194, 113, 0, 1393, 1192, 914, 746, 1145, 621, 539, 358, 498, 401, 202, 105, 0), # 101 (1346, 1270, 1183, 1260, 1024, 509, 514, 455, 558, 238, 195, 113, 0, 1408, 1199, 919, 758, 1154, 627, 541, 363, 501, 408, 205, 108, 0), # 102 (1360, 1282, 1191, 1272, 1032, 514, 518, 460, 565, 240, 196, 113, 0, 1428, 1213, 929, 766, 1160, 631, 545, 365, 509, 411, 205, 109, 0), # 103 (1374, 1288, 1202, 1286, 1043, 518, 522, 465, 570, 243, 197, 114, 0, 1438, 1219, 943, 772, 1168, 640, 549, 370, 511, 414, 206, 109, 0), # 104 (1390, 1299, 1211, 1299, 1055, 523, 530, 470, 578, 245, 199, 114, 0, 1455, 1229, 958, 780, 1178, 643, 555, 371, 517, 418, 209, 109, 0), # 105 (1398, 1311, 1224, 1309, 1061, 528, 535, 472, 586, 247, 200, 115, 0, 1474, 1243, 965, 784, 1190, 647, 558, 375, 522, 421, 210, 110, 0), # 106 (1409, 1323, 1240, 1314, 1064, 537, 538, 474, 593, 249, 200, 117, 0, 1489, 1256, 968, 787, 1198, 652, 565, 379, 528, 425, 213, 111, 0), # 107 (1421, 1332, 1247, 1323, 1071, 542, 542, 477, 595, 250, 202, 120, 0, 1513, 1266, 979, 796, 1207, 657, 571, 381, 534, 429, 214, 115, 0), # 108 (1431, 1347, 1261, 1333, 1078, 549, 551, 482, 603, 252, 203, 122, 0, 1530, 1275, 985, 801, 1216, 666, 574, 386, 543, 430, 217, 115, 0), # 109 (1446, 1354, 1271, 1341, 1086, 553, 555, 486, 608, 252, 203, 122, 0, 1543, 1284, 998, 810, 1225, 672, 579, 391, 548, 434, 217, 117, 0), # 110 (1465, 1367, 1280, 1354, 1102, 555, 557, 488, 617, 256, 204, 122, 0, 1551, 1292, 1009, 814, 1235, 673, 584, 393, 554, 436, 220, 117, 0), # 111 (1480, 1385, 1290, 1368, 1106, 557, 560, 490, 626, 256, 205, 122, 0, 1563, 1302, 1015, 825, 1242, 675, 586, 396, 564, 439, 222, 117, 0), # 112 (1489, 1392, 1303, 1385, 1111, 559, 560, 491, 634, 257, 208, 123, 0, 1581, 1311, 1026, 831, 1251, 686, 588, 398, 569, 444, 226, 118, 0), # 113 (1503, 1396, 1315, 1395, 1119, 566, 562, 493, 640, 259, 210, 123, 0, 1594, 1322, 1035, 837, 1261, 687, 594, 401, 573, 447, 228, 119, 0), # 114 (1518, 1403, 1324, 1408, 1129, 569, 569, 494, 644, 259, 212, 125, 0, 1605, 1333, 1050, 841, 1273, 691, 597, 404, 577, 452, 232, 122, 0), # 115 (1522, 1417, 1336, 1421, 1141, 575, 570, 500, 648, 259, 212, 126, 0, 1616, 1342, 1059, 845, 1280, 702, 600, 406, 581, 457, 233, 123, 0), # 116 (1537, 1426, 1349, 1431, 1150, 581, 574, 503, 657, 264, 213, 128, 0, 1626, 1352, 1068, 854, 1292, 703, 603, 410, 586, 459, 234, 123, 0), # 117 (1547, 1436, 1362, 1448, 1160, 587, 577, 506, 661, 265, 215, 130, 0, 1638, 1367, 1078, 863, 1297, 707, 606, 413, 592, 463, 234, 124, 0), # 118 (1552, 1444, 1370, 1455, 1171, 590, 580, 511, 666, 267, 219, 131, 0, 1648, 1376, 1089, 866, 1308, 714, 609, 416, 595, 465, 238, 127, 0), # 119 (1561, 1453, 1379, 1464, 1182, 594, 584, 513, 671, 270, 220, 131, 0, 1659, 1388, 1096, 874, 1316, 722, 612, 419, 603, 467, 242, 129, 0), # 120 (1571, 1468, 1396, 1479, 1197, 599, 588, 517, 681, 273, 223, 131, 0, 1676, 1397, 1102, 881, 1320, 726, 614, 422, 607, 472, 246, 129, 0), # 121 (1594, 1478, 1405, 1487, 1208, 603, 590, 520, 690, 274, 225, 131, 0, 1693, 1409, 1108, 888, 1328, 731, 616, 425, 615, 475, 249, 129, 0), # 122 (1610, 1483, 1410, 1501, 1218, 606, 594, 521, 694, 277, 227, 132, 0, 1710, 1420, 1119, 892, 1337, 734, 621, 430, 618, 477, 253, 130, 0), # 123 (1620, 1502, 1420, 1516, 1223, 612, 599, 523, 699, 279, 227, 132, 0, 1717, 1431, 1125, 898, 1347, 740, 623, 434, 625, 480, 253, 131, 0), # 124 (1627, 1510, 1429, 1522, 1234, 616, 604, 525, 703, 282, 228, 132, 0, 1730, 1442, 1136, 908, 1358, 746, 630, 438, 630, 482, 257, 131, 0), # 125 (1642, 1523, 1435, 1534, 1238, 621, 610, 527, 703, 285, 229, 133, 0, 1749, 1448, 1142, 914, 1366, 750, 634, 441, 634, 485, 258, 132, 0), # 126 (1649, 1531, 1444, 1545, 1250, 625, 614, 529, 709, 287, 229, 133, 0, 1757, 1455, 1146, 917, 1375, 755, 636, 443, 640, 486, 263, 133, 0), # 127 (1664, 1543, 1453, 1554, 1254, 632, 618, 531, 717, 292, 230, 135, 0, 1768, 1460, 1155, 922, 1386, 758, 640, 446, 643, 489, 267, 134, 0), # 128 (1677, 1552, 1467, 1563, 1264, 637, 622, 532, 723, 293, 231, 136, 0, 1782, 1470, 1161, 927, 1396, 767, 645, 448, 644, 497, 267, 134, 0), # 129 (1685, 1564, 1477, 1574, 1275, 642, 624, 538, 728, 294, 233, 137, 0, 1790, 1475, 1166, 933, 1405, 770, 652, 449, 646, 499, 270, 134, 0), # 130 (1690, 1570, 1496, 1581, 1280, 644, 625, 542, 734, 295, 233, 137, 0, 1799, 1485, 1175, 938, 1413, 777, 655, 453, 649, 500, 272, 134, 0), # 131 (1702, 1580, 1506, 1586, 1290, 650, 629, 549, 736, 296, 234, 137, 0, 1816, 1494, 1180, 948, 1426, 780, 657, 456, 650, 504, 279, 135, 0), # 132 (1708, 1590, 1518, 1597, 1295, 654, 633, 553, 739, 297, 236, 140, 0, 1825, 1505, 1186, 952, 1440, 784, 663, 460, 660, 509, 282, 136, 0), # 133 (1723, 1598, 1529, 1613, 1304, 659, 635, 556, 746, 299, 237, 141, 0, 1836, 1510, 1198, 957, 1452, 785, 668, 465, 665, 513, 284, 136, 0), # 134 (1735, 1609, 1542, 1626, 1317, 661, 635, 558, 750, 301, 240, 141, 0, 1846, 1521, 1205, 962, 1467, 792, 674, 467, 668, 516, 285, 139, 0), # 135 (1752, 1616, 1555, 1641, 1324, 667, 640, 560, 755, 302, 240, 142, 0, 1856, 1528, 1213, 966, 1481, 796, 678, 471, 673, 517, 287, 139, 0), # 136 (1762, 1627, 1567, 1653, 1336, 672, 642, 563, 757, 304, 242, 142, 0, 1874, 1539, 1221, 972, 1493, 800, 685, 473, 679, 520, 290, 140, 0), # 137 (1779, 1631, 1572, 1665, 1347, 675, 649, 565, 763, 310, 242, 143, 0, 1885, 1550, 1227, 977, 1501, 802, 688, 476, 686, 526, 293, 141, 0), # 138 (1795, 1643, 1584, 1673, 1355, 681, 655, 568, 767, 311, 245, 144, 0, 1898, 1558, 1235, 984, 1510, 810, 690, 480, 690, 530, 298, 142, 0), # 139 (1808, 1652, 1589, 1687, 1363, 686, 658, 573, 773, 313, 248, 145, 0, 1904, 1567, 1242, 987, 1521, 816, 695, 487, 695, 536, 301, 143, 0), # 140 (1824, 1658, 1600, 1695, 1370, 692, 664, 575, 779, 313, 249, 146, 0, 1918, 1580, 1250, 994, 1531, 818, 699, 488, 700, 538, 302, 143, 0), # 141 (1831, 1663, 1609, 1706, 1378, 697, 666, 581, 784, 315, 249, 148, 0, 1930, 1585, 1254, 996, 1541, 824, 704, 491, 703, 542, 302, 146, 0), # 142 (1848, 1677, 1622, 1716, 1393, 701, 671, 586, 791, 315, 252, 152, 0, 1943, 1595, 1260, 1002, 1556, 829, 710, 494, 705, 547, 303, 147, 0), # 143 (1859, 1688, 1637, 1729, 1398, 705, 677, 592, 792, 319, 257, 152, 0, 1954, 1606, 1267, 1006, 1567, 833, 714, 502, 712, 550, 304, 147, 0), # 144 (1865, 1701, 1648, 1733, 1405, 711, 679, 599, 799, 320, 258, 153, 0, 1963, 1613, 1280, 1011, 1575, 844, 720, 510, 717, 555, 306, 150, 0), # 145 (1880, 1713, 1656, 1743, 1414, 716, 683, 604, 803, 320, 259, 154, 0, 1974, 1622, 1293, 1016, 1586, 848, 725, 512, 720, 558, 307, 150, 0), # 146 (1892, 1725, 1665, 1751, 1421, 720, 685, 609, 805, 321, 261, 155, 0, 1990, 1634, 1299, 1021, 1595, 852, 728, 515, 724, 561, 309, 152, 0), # 147 (1902, 1734, 1680, 1763, 1429, 727, 691, 615, 809, 323, 262, 157, 0, 2004, 1642, 1308, 1027, 1603, 856, 732, 518, 726, 565, 311, 152, 0), # 148 (1920, 1747, 1686, 1778, 1441, 731, 697, 617, 814, 327, 264, 157, 0, 2014, 1649, 1316, 1032, 1611, 858, 735, 522, 733, 567, 314, 154, 0), # 149 (1938, 1750, 1696, 1788, 1445, 736, 699, 620, 816, 328, 266, 157, 0, 2023, 1660, 1320, 1037, 1629, 861, 742, 526, 739, 570, 316, 156, 0), # 150 (1947, 1755, 1700, 1791, 1452, 741, 702, 623, 821, 328, 269, 157, 0, 2033, 1672, 1328, 1043, 1639, 866, 743, 527, 740, 573, 317, 157, 0), # 151 (1956, 1758, 1709, 1803, 1460, 744, 703, 624, 825, 331, 270, 157, 0, 2047, 1678, 1331, 1047, 1648, 870, 746, 534, 743, 578, 317, 157, 0), # 152 (1963, 1763, 1716, 1815, 1465, 750, 706, 627, 829, 334, 272, 157, 0, 2057, 1689, 1336, 1055, 1657, 875, 748, 538, 750, 581, 319, 158, 0), # 153 (1970, 1773, 1724, 1823, 1473, 753, 709, 627, 831, 336, 273, 158, 0, 2066, 1700, 1346, 1062, 1671, 879, 752, 540, 753, 583, 320, 160, 0), # 154 (1987, 1779, 1734, 1836, 1479, 754, 714, 629, 832, 336, 274, 158, 0, 2080, 1703, 1351, 1065, 1678, 882, 754, 544, 758, 587, 321, 160, 0), # 155 (1991, 1784, 1738, 1844, 1483, 760, 717, 633, 835, 336, 275, 159, 0, 2090, 1712, 1356, 1069, 1685, 892, 757, 551, 762, 592, 322, 160, 0), # 156 (1994, 1791, 1744, 1849, 1497, 766, 720, 634, 837, 338, 276, 161, 0, 2103, 1720, 1362, 1074, 1696, 894, 761, 554, 765, 597, 326, 160, 0), # 157 (2003, 1796, 1760, 1857, 1505, 770, 726, 638, 844, 341, 278, 161, 0, 2108, 1729, 1363, 1082, 1708, 899, 765, 556, 768, 598, 330, 160, 0), # 158 (2010, 1802, 1770, 1862, 1513, 775, 730, 643, 850, 342, 279, 161, 0, 2114, 1742, 1370, 1088, 1715, 905, 768, 560, 772, 599, 331, 160, 0), # 159 (2023, 1807, 1782, 1867, 1519, 779, 731, 648, 852, 344, 281, 161, 0, 2125, 1749, 1376, 1093, 1722, 909, 769, 565, 777, 600, 332, 160, 0), # 160 (2034, 1813, 1791, 1874, 1523, 781, 732, 654, 859, 346, 281, 161, 0, 2131, 1760, 1383, 1096, 1728, 916, 776, 568, 783, 603, 334, 161, 0), # 161 (2046, 1823, 1796, 1880, 1532, 787, 734, 659, 866, 347, 282, 161, 0, 2141, 1765, 1393, 1100, 1741, 919, 777, 569, 790, 605, 337, 161, 0), # 162 (2055, 1829, 1808, 1888, 1536, 790, 736, 662, 873, 349, 285, 161, 0, 2153, 1771, 1400, 1101, 1746, 921, 780, 575, 793, 609, 339, 161, 0), # 163 (2064, 1834, 1815, 1897, 1544, 793, 738, 665, 879, 350, 285, 161, 0, 2162, 1776, 1404, 1103, 1754, 924, 783, 579, 798, 612, 340, 162, 0), # 164 (2075, 1842, 1827, 1904, 1549, 797, 744, 666, 885, 353, 286, 162, 0, 2168, 1785, 1407, 1104, 1758, 929, 785, 582, 800, 616, 340, 162, 0), # 165 (2080, 1845, 1840, 1913, 1553, 799, 745, 670, 890, 354, 287, 162, 0, 2180, 1790, 1412, 1109, 1767, 935, 787, 583, 802, 620, 341, 162, 0), # 166 (2086, 1852, 1848, 1921, 1557, 802, 751, 675, 896, 355, 290, 162, 0, 2193, 1796, 1422, 1114, 1772, 939, 788, 586, 807, 621, 341, 163, 0), # 167 (2095, 1857, 1859, 1932, 1562, 805, 754, 678, 898, 357, 291, 164, 0, 2201, 1804, 1428, 1117, 1780, 942, 791, 587, 808, 623, 342, 163, 0), # 168 (2100, 1862, 1867, 1942, 1565, 807, 759, 681, 902, 357, 293, 164, 0, 2214, 1810, 1432, 1119, 1786, 944, 793, 590, 808, 625, 345, 163, 0), # 169 (2111, 1867, 1872, 1948, 1570, 809, 762, 684, 905, 357, 295, 165, 0, 2223, 1816, 1441, 1125, 1793, 947, 796, 594, 814, 626, 347, 165, 0), # 170 (2121, 1871, 1877, 1952, 1581, 813, 763, 688, 907, 358, 296, 166, 0, 2230, 1822, 1452, 1129, 1806, 954, 796, 594, 816, 630, 347, 165, 0), # 171 (2130, 1873, 1881, 1958, 1584, 818, 764, 689, 909, 361, 298, 166, 0, 2234, 1827, 1456, 1132, 1814, 956, 798, 597, 817, 631, 350, 165, 0), # 172 (2138, 1879, 1883, 1962, 1590, 821, 766, 689, 911, 362, 298, 166, 0, 2242, 1834, 1465, 1137, 1818, 957, 801, 599, 820, 637, 350, 166, 0), # 173 (2144, 1884, 1889, 1968, 1597, 824, 768, 689, 913, 364, 298, 166, 0, 2250, 1840, 1468, 1139, 1824, 961, 801, 601, 824, 639, 350, 166, 0), # 174 (2152, 1887, 1894, 1975, 1602, 825, 770, 689, 915, 366, 301, 167, 0, 2256, 1843, 1469, 1144, 1829, 962, 801, 604, 826, 641, 352, 168, 0), # 175 (2157, 1892, 1898, 1982, 1610, 829, 772, 690, 917, 367, 302, 169, 0, 2261, 1843, 1471, 1146, 1834, 965, 802, 605, 828, 644, 352, 168, 0), # 176 (2168, 1896, 1907, 1988, 1615, 832, 775, 692, 918, 369, 302, 170, 0, 2269, 1844, 1475, 1149, 1839, 966, 805, 605, 831, 645, 352, 168, 0), # 177 (2173, 1900, 1911, 1991, 1621, 834, 776, 695, 923, 370, 302, 172, 0, 2278, 1845, 1476, 1151, 1843, 966, 807, 605, 836, 647, 354, 169, 0), # 178 (2173, 1900, 1911, 1991, 1621, 834, 776, 695, 923, 370, 302, 172, 0, 2278, 1845, 1476, 1151, 1843, 966, 807, 605, 836, 647, 354, 169, 0), # 179 ) passenger_arriving_rate = ( (7.029211809720476, 7.090786984939564, 6.079830434547925, 6.525401162556605, 5.184373233768971, 2.563234861163827, 2.9022249307617405, 2.7143527675713304, 2.8420462290117365, 1.3853052554328298, 0.9812285382399741, 0.571423425802387, 0.0, 7.117432297609708, 6.285657683826256, 4.90614269119987, 4.155915766298489, 5.684092458023473, 3.8000938745998627, 2.9022249307617405, 1.8308820436884476, 2.5921866168844856, 2.175133720852202, 1.2159660869095852, 0.6446169986308695, 0.0), # 0 (7.496058012827964, 7.558911224152441, 6.4812376898851785, 6.956401465940448, 5.527657648309288, 2.7325532603014207, 3.093628258884586, 2.893049671694997, 3.0297144856220246, 1.4766432422970026, 1.0460557650564308, 0.6091419437616749, 0.0, 7.587708306415797, 6.700561381378422, 5.230278825282154, 4.429929726891007, 6.059428971244049, 4.050269540372995, 3.093628258884586, 1.9518237573581576, 2.763828824154644, 2.3188004886468163, 1.2962475379770357, 0.687173747650222, 0.0), # 1 (7.9614122125716245, 8.025177635976757, 6.881049333138649, 7.385687089898034, 5.869698775499761, 2.9011961768518306, 3.284272955572493, 3.071031394610912, 3.2166338432095234, 1.5676198212571917, 1.1106254013811399, 0.6467104760728565, 0.0, 8.056110759493567, 7.113815236801421, 5.553127006905699, 4.702859463771574, 6.433267686419047, 4.2994439524552766, 3.284272955572493, 2.0722829834655934, 2.9348493877498805, 2.4618956966326784, 1.37620986662773, 0.7295616032706144, 0.0), # 2 (8.423460910405188, 8.487736310818441, 7.277679347539831, 7.811555227908678, 6.209150897601775, 3.0684948417778424, 3.473402549153569, 3.2475923418717962, 3.4020630750965104, 1.657873944449164, 1.1746812960930562, 0.6839799965752206, 0.0, 8.520781928755916, 7.523779962327425, 5.873406480465281, 4.97362183334749, 6.804126150193021, 4.5466292786205145, 3.473402549153569, 2.191782029841316, 3.1045754488008876, 2.6038517426362264, 1.455535869507966, 0.7716123918925856, 0.0), # 3 (8.880390607782374, 8.94473733908341, 7.669541716320211, 8.232303073451698, 6.5446682968767265, 3.233780486042246, 3.6602605679559215, 3.4220269190303676, 3.585260954605263, 1.7470445640086882, 1.2379672980711345, 0.7208014791080559, 0.0, 8.979864086115745, 7.928816270188614, 6.189836490355671, 5.241133692026064, 7.170521909210526, 4.790837686642515, 3.6602605679559215, 2.30984320431589, 3.2723341484383632, 2.7441010244839, 1.5339083432640421, 0.8131579399166738, 0.0), # 4 (9.330387806156915, 9.394330811177607, 8.055050422711272, 8.646227820006413, 6.874905255585995, 3.396384340607826, 3.844090540307657, 3.593629531639346, 3.765486255058061, 1.8347706320715327, 1.300227256194331, 0.7570258975106506, 0.0, 9.43149950348596, 8.327284872617156, 6.501136280971655, 5.504311896214597, 7.530972510116122, 5.031081344295084, 3.844090540307657, 2.4259888147198754, 3.4374526277929975, 2.8820759400021383, 1.6110100845422546, 0.8540300737434189, 0.0), # 5 (9.771639006982534, 9.834666817506942, 8.43261944994451, 9.051626661052135, 7.198516055990973, 3.5556376364373725, 4.024135994536884, 3.7616945852514516, 3.9419977497771805, 1.920691100773466, 1.3612050193415997, 0.7925042256222944, 0.0, 9.87383045277945, 8.717546481845236, 6.806025096707997, 5.762073302320396, 7.883995499554361, 5.266372419352033, 4.024135994536884, 2.5397411688838374, 3.5992580279954867, 3.017208887017379, 1.6865238899889023, 0.8940606197733586, 0.0), # 6 (10.202330711712957, 10.263895448477353, 8.800662781251408, 9.446796790068186, 7.514154980353052, 3.710871604493673, 4.19964045897171, 3.9255164854194056, 4.1140542120849, 2.004444922250256, 1.4206444363918964, 0.8270874372822752, 0.0, 10.304999205909127, 9.097961810105026, 7.103222181959481, 6.013334766750766, 8.2281084241698, 5.495723079587168, 4.19964045897171, 2.6506225746383376, 3.757077490176526, 3.148932263356063, 1.7601325562502819, 0.9330814044070321, 0.0), # 7 (10.62064942180191, 10.68016679449476, 9.157594399863463, 9.830035400533875, 7.820476310933614, 3.8614174757395103, 4.369847461940239, 4.0843896376959234, 4.280914415303496, 2.0856710486376717, 1.4782893562241752, 0.8606265063298821, 0.0, 10.723148034787885, 9.466891569628702, 7.391446781120876, 6.257013145913014, 8.561828830606991, 5.718145492774292, 4.369847461940239, 2.758155339813936, 3.910238155466807, 3.276678466844626, 1.831518879972693, 0.9709242540449783, 0.0), # 8 (11.02478163870312, 11.081630945965095, 9.501828289012156, 10.199639685928528, 8.116134329994049, 4.006606481137679, 4.534000531770584, 4.237608447633729, 4.441837132755248, 2.1640084320714803, 1.5338836277173917, 0.8929724066044035, 0.0, 11.126419211328628, 9.822696472648436, 7.669418138586958, 6.49202529621444, 8.883674265510496, 5.932651826687221, 4.534000531770584, 2.861861772241199, 4.058067164997024, 3.3998798953095104, 1.9003656578024313, 1.0074209950877362, 0.0), # 9 (11.412913863870306, 11.46643799329428, 9.83177843192898, 10.553906839731454, 8.399783319795748, 4.145769851650964, 4.691343196790848, 4.38446732078554, 4.596081137762433, 2.2390960246874507, 1.5871710997505006, 0.923976111945128, 0.0, 11.512955007444255, 10.163737231396405, 7.935855498752503, 6.717288074062351, 9.192162275524867, 6.138254249099756, 4.691343196790848, 2.961264179750688, 4.199891659897874, 3.517968946577152, 1.9663556863857963, 1.0424034539358438, 0.0), # 10 (11.783232598757209, 11.832738026888249, 10.145858811845418, 10.891134055421968, 8.670077562600099, 4.278238818242151, 4.841118985329142, 4.524260662704076, 4.7429052036473305, 2.3105727786213524, 1.6378956212024585, 0.9534885961913449, 0.0, 11.880897695047656, 10.488374558104791, 8.189478106012292, 6.931718335864056, 9.485810407294661, 6.333964927785706, 4.841118985329142, 3.055884870172965, 4.3350387813000495, 3.63037801847399, 2.0291717623690837, 1.075703456989841, 0.0), # 11 (12.133924344817538, 12.178681137152912, 10.442483411992965, 11.209618526479394, 8.925671340668487, 4.403344611874027, 4.9825714257135685, 4.656282878942054, 4.881568103732217, 2.378077646008951, 1.6858010409522184, 0.9813608331823415, 0.0, 12.22838954605175, 10.794969165005755, 8.429005204761092, 7.134232938026852, 9.763136207464434, 6.518796030518876, 4.9825714257135685, 3.1452461513385908, 4.462835670334243, 3.7365395088264655, 2.0884966823985933, 1.107152830650265, 0.0), # 12 (12.463175603505027, 12.502417414494213, 10.720066215603106, 11.507657446383048, 9.165218936262296, 4.520418463509383, 5.11494404627224, 4.779828375052198, 5.011328611339368, 2.441249578986017, 1.7306312078787365, 1.0074437967574077, 0.0, 12.55357283236943, 11.08188176433148, 8.653156039393682, 7.323748736958049, 10.022657222678736, 6.691759725073078, 5.11494404627224, 3.228870331078131, 4.582609468131148, 3.8358858154610167, 2.1440132431206216, 1.136583401317656, 0.0), # 13 (12.769172876273403, 12.802096949318072, 10.977021205907338, 11.783548008612232, 9.387374631642924, 4.6287916041110035, 5.237480375333263, 4.894191556587227, 5.131445499791063, 2.4997275296883177, 1.7721299708609668, 1.0315884607558323, 0.0, 12.85458982591359, 11.347473068314153, 8.860649854304834, 7.499182589064952, 10.262890999582126, 6.8518681792221185, 5.237480375333263, 3.306279717222145, 4.693687315821462, 3.9278493362040785, 2.195404241181468, 1.1638269953925522, 0.0), # 14 (13.050102664576398, 13.075869832030413, 11.211762366137135, 12.035587406646286, 9.590792709071755, 4.72779526464168, 5.349423941224739, 4.998666829099858, 5.241177542409583, 2.5531504502516222, 1.810041178777865, 1.0536457990169035, 0.0, 13.129582798597134, 11.590103789185937, 9.050205893889325, 7.659451350754866, 10.482355084819165, 6.998133560739801, 5.349423941224739, 3.3769966176011996, 4.795396354535877, 4.0118624688820965, 2.242352473227427, 1.1887154392754924, 0.0), # 15 (13.30415146986772, 13.321886153037171, 11.422703679523998, 12.262072833964503, 9.774127450810177, 4.816760676064193, 5.450018272274784, 5.092548598142811, 5.339783512517201, 2.6011572928116995, 1.8441086805083868, 1.0734667853799098, 0.0, 13.376694022332964, 11.808134639179006, 9.220543402541933, 7.803471878435097, 10.679567025034402, 7.1295680373999355, 5.450018272274784, 3.440543340045852, 4.887063725405088, 4.087357611321502, 2.2845407359047996, 1.2110805593670158, 0.0), # 16 (13.529505793601107, 13.538296002744264, 11.608259129299412, 12.46130148404622, 9.936033139119584, 4.895019069341334, 5.538506896811498, 5.17513126926881, 5.426522183436193, 2.643387009504314, 1.874076324931487, 1.09090239368414, 0.0, 13.594065769033982, 11.999926330525538, 9.370381624657433, 7.9301610285129405, 10.853044366872385, 7.245183776976335, 5.538506896811498, 3.496442192386667, 4.968016569559792, 4.153767161348741, 2.3216518258598824, 1.2307541820676606, 0.0), # 17 (13.724352137230287, 13.723249471557619, 11.766842698694862, 12.631570550370744, 10.07516405626135, 4.961901675435895, 5.6141333431629965, 5.245709248030569, 5.500652328488845, 2.6794785524652385, 1.8996879609261188, 1.1058035977688838, 0.0, 13.779840310613086, 12.163839575457718, 9.498439804630594, 8.038435657395715, 11.00130465697769, 7.343992947242797, 5.6141333431629965, 3.5442154824542103, 5.037582028130675, 4.210523516790249, 2.3533685397389728, 1.2475681337779656, 0.0), # 18 (13.88687700220898, 13.874896649883173, 11.896868370941842, 12.77117722641738, 10.190174484496875, 5.0167397253106545, 5.676141139657377, 5.30357693998081, 5.561432720997431, 2.7090708738302403, 1.9206874373712384, 1.1180213714734282, 0.0, 13.932159918983176, 12.298235086207708, 9.603437186856192, 8.12721262149072, 11.122865441994861, 7.425007715973134, 5.676141139657377, 3.5833855180790386, 5.095087242248438, 4.257059075472461, 2.379373674188369, 1.2613542408984704, 0.0), # 19 (14.015266889990915, 13.991387628126835, 11.996750129271838, 12.87841870566547, 10.279718706087547, 5.058864449928407, 5.723773814622755, 5.348028750672253, 5.608122134284226, 2.731802925735086, 1.936818603145802, 1.1274066886370624, 0.0, 14.049166866057154, 12.401473575007685, 9.68409301572901, 8.195408777205257, 11.216244268568452, 7.487240250941153, 5.723773814622755, 3.6134746070917196, 5.139859353043773, 4.292806235221825, 2.399350025854368, 1.2719443298297126, 0.0), # 20 (14.107708302029813, 14.070872496694552, 12.064901956916339, 12.951592181594311, 10.34245100329475, 5.087607080251938, 5.756274896387231, 5.378359085657614, 5.63997934167151, 2.747313660315545, 1.9478253071287643, 1.133810523099076, 0.0, 14.12900342374791, 12.471915754089835, 9.739126535643821, 8.241940980946634, 11.27995868334302, 7.529702719920659, 5.756274896387231, 3.634005057322813, 5.171225501647375, 4.317197393864771, 2.412980391383268, 1.279170226972232, 0.0), # 21 (14.162387739779412, 14.111501345992236, 12.099737837106835, 12.988994847683228, 10.377025658379871, 5.102298847244033, 5.77288791327892, 5.393862350489618, 5.656263116481561, 2.7552420297073854, 1.9534513981990798, 1.1370838486987573, 0.0, 14.16981186396836, 12.50792233568633, 9.7672569909954, 8.265726089122154, 11.312526232963123, 7.551407290685465, 5.77288791327892, 3.644499176602881, 5.188512829189936, 4.329664949227744, 2.419947567421367, 1.282863758726567, 0.0), # 22 (14.182550708679697, 14.116311945587563, 12.104077046181986, 12.993677353395064, 10.385883252297091, 5.104166666666667, 5.774862801581538, 5.395538065843622, 5.658298909465021, 2.7561772953818022, 1.9541568753377396, 1.1374880506020426, 0.0, 14.175, 12.512368556622466, 9.770784376688697, 8.268531886145405, 11.316597818930042, 7.553753292181072, 5.774862801581538, 3.6458333333333335, 5.192941626148546, 4.331225784465023, 2.4208154092363974, 1.283301085962506, 0.0), # 23 (14.197417378247815, 14.113505864197531, 12.10336728395062, 12.99310104166667, 10.390900439373862, 5.104166666666667, 5.773777668845317, 5.393208333333334, 5.658026111111111, 2.755602716049383, 1.9540790684624023, 1.1373934156378602, 0.0, 14.175, 12.51132757201646, 9.77039534231201, 8.266808148148147, 11.316052222222222, 7.550491666666668, 5.773777668845317, 3.6458333333333335, 5.195450219686931, 4.331033680555557, 2.4206734567901242, 1.2830459876543212, 0.0), # 24 (14.211970122296213, 14.10797467992684, 12.101966163694561, 12.991960841049384, 10.39580728255487, 5.104166666666667, 5.771639231824418, 5.388631687242799, 5.657487139917696, 2.754471593507088, 1.9539247931994848, 1.1372065996037193, 0.0, 14.175, 12.509272595640908, 9.769623965997424, 8.263414780521263, 11.314974279835392, 7.544084362139919, 5.771639231824418, 3.6458333333333335, 5.197903641277435, 4.330653613683129, 2.4203932327389124, 1.2825431527206221, 0.0), # 25 (14.226207826667249, 14.099802892089624, 12.099892889803387, 12.990269714506173, 10.400603610526364, 5.104166666666667, 5.768480702816105, 5.381894547325103, 5.65668890946502, 2.7528027480566992, 1.9536954462318665, 1.136930163084896, 0.0, 14.175, 12.506231793933855, 9.768477231159332, 8.258408244170097, 11.31337781893004, 7.534652366255146, 5.768480702816105, 3.6458333333333335, 5.200301805263182, 4.330089904835392, 2.4199785779606775, 1.2818002629172387, 0.0), # 26 (14.240129377203292, 14.089075, 12.097166666666668, 12.988040625, 10.405289251974601, 5.104166666666667, 5.7643352941176484, 5.3730833333333345, 5.655638333333333, 2.7506150000000003, 1.9533924242424245, 1.1365666666666672, 0.0, 14.175, 12.502233333333336, 9.766962121212122, 8.251845, 11.311276666666666, 7.5223166666666685, 5.7643352941176484, 3.6458333333333335, 5.2026446259873005, 4.329346875000001, 2.4194333333333335, 1.280825, 0.0), # 27 (14.253733659746702, 14.075875502972108, 12.093806698673983, 12.985286535493827, 10.40986403558584, 5.104166666666667, 5.759236218026306, 5.362284465020577, 5.654342325102881, 2.7479271696387753, 1.9530171239140377, 1.1361186709343092, 0.0, 14.175, 12.4973053802774, 9.765085619570188, 8.243781508916324, 11.308684650205763, 7.507198251028808, 5.759236218026306, 3.6458333333333335, 5.20493201779292, 4.32842884516461, 2.418761339734797, 1.2796250457247373, 0.0), # 28 (14.26701956013985, 14.060288900320074, 12.089832190214908, 12.982020408950618, 10.41432779004634, 5.104166666666667, 5.753216686839346, 5.349584362139918, 5.652807798353909, 2.7447580772748066, 1.952570941929584, 1.1355887364730988, 0.0, 14.175, 12.491476101204084, 9.76285470964792, 8.234274231824418, 11.305615596707819, 7.489418106995886, 5.753216686839346, 3.6458333333333335, 5.20716389502317, 4.327340136316874, 2.4179664380429817, 1.2782080818472796, 0.0), # 29 (14.279985964225098, 14.042399691358026, 12.085262345679013, 12.978255208333334, 10.418680344042354, 5.104166666666667, 5.746309912854031, 5.335069444444444, 5.651041666666666, 2.7411265432098775, 1.952055274971942, 1.1349794238683129, 0.0, 14.175, 12.48477366255144, 9.760276374859709, 8.223379629629632, 11.302083333333332, 7.469097222222222, 5.746309912854031, 3.6458333333333335, 5.209340172021177, 4.326085069444446, 2.4170524691358026, 1.276581790123457, 0.0), # 30 (14.292631757844802, 14.022292375400093, 12.080116369455878, 12.97400389660494, 10.422921526260142, 5.104166666666667, 5.7385491083676285, 5.318826131687244, 5.649050843621399, 2.737051387745771, 1.9514715197239891, 1.1342932937052284, 0.0, 14.175, 12.477226230757509, 9.757357598619945, 8.211154163237312, 11.298101687242799, 7.4463565843621415, 5.7385491083676285, 3.6458333333333335, 5.211460763130071, 4.324667965534981, 2.416023273891176, 1.2747538523090995, 0.0), # 31 (14.304955826841338, 14.000051451760402, 12.07441346593507, 12.969279436728398, 10.427051165385956, 5.104166666666667, 5.7299674856774, 5.3009408436214, 5.646842242798354, 2.7325514311842714, 1.950821072868604, 1.1335329065691209, 0.0, 14.175, 12.468861972260328, 9.754105364343019, 8.197654293552812, 11.293684485596708, 7.421317181069961, 5.7299674856774, 3.6458333333333335, 5.213525582692978, 4.3230931455761334, 2.4148826931870144, 1.272731950160037, 0.0), # 32 (14.316957057057056, 13.975761419753086, 12.068172839506175, 12.964094791666666, 10.431069090106059, 5.104166666666667, 5.720598257080611, 5.2815, 5.644422777777778, 2.7276454938271613, 1.9501053310886647, 1.1327008230452675, 0.0, 14.175, 12.459709053497942, 9.750526655443322, 8.182936481481482, 11.288845555555556, 7.394100000000001, 5.720598257080611, 3.6458333333333335, 5.215534545053029, 4.321364930555556, 2.413634567901235, 1.2705237654320989, 0.0), # 33 (14.328634334334335, 13.949506778692271, 12.061413694558757, 12.958462924382715, 10.434975129106702, 5.104166666666667, 5.710474634874527, 5.260590020576132, 5.641799362139919, 2.7223523959762237, 1.9493256910670491, 1.1317996037189455, 0.0, 14.175, 12.449795640908398, 9.746628455335244, 8.16705718792867, 11.283598724279837, 7.3648260288065845, 5.710474634874527, 3.6458333333333335, 5.217487564553351, 4.319487641460906, 2.4122827389117516, 1.2681369798811157, 0.0), # 34 (14.339986544515531, 13.92137202789209, 12.054155235482398, 12.952396797839505, 10.438769111074146, 5.104166666666667, 5.699629831356412, 5.238297325102881, 5.638978909465021, 2.7166909579332423, 1.9484835494866362, 1.1308318091754308, 0.0, 14.175, 12.439149900929737, 9.74241774743318, 8.150072873799726, 11.277957818930043, 7.333616255144034, 5.699629831356412, 3.6458333333333335, 5.219384555537073, 4.317465599279836, 2.41083104709648, 1.2655792752629174, 0.0), # 35 (14.35101257344301, 13.891441666666665, 12.04641666666667, 12.945909375, 10.442450864694647, 5.104166666666667, 5.68809705882353, 5.214708333333334, 5.635968333333333, 2.7106800000000004, 1.9475803030303034, 1.1298000000000004, 0.0, 14.175, 12.427800000000001, 9.737901515151515, 8.13204, 11.271936666666665, 7.300591666666668, 5.68809705882353, 3.6458333333333335, 5.221225432347324, 4.315303125000001, 2.409283333333334, 1.2628583333333334, 0.0), # 36 (14.361711306959135, 13.859800194330132, 12.038217192501145, 12.939013618827161, 10.44602021865446, 5.104166666666667, 5.675909529573146, 5.189909465020577, 5.632774547325103, 2.7043383424782816, 1.9466173483809293, 1.1287067367779304, 0.0, 14.175, 12.415774104557233, 9.733086741904645, 8.113015027434844, 11.265549094650206, 7.265873251028808, 5.675909529573146, 3.6458333333333335, 5.22301010932723, 4.313004539609055, 2.407643438500229, 1.259981835848194, 0.0), # 37 (14.372081630906267, 13.826532110196618, 12.029576017375401, 12.931722492283953, 10.449477001639845, 5.104166666666667, 5.663100455902526, 5.1639871399176975, 5.629404465020576, 2.6976848056698683, 1.9455960822213911, 1.1275545800944982, 0.0, 14.175, 12.403100381039478, 9.727980411106955, 8.093054417009604, 11.258808930041152, 7.229581995884776, 5.663100455902526, 3.6458333333333335, 5.224738500819923, 4.3105741640946516, 2.40591520347508, 1.2569574645633292, 0.0), # 38 (14.382122431126781, 13.791721913580247, 12.020512345679016, 12.924048958333334, 10.452821042337057, 5.104166666666667, 5.649703050108934, 5.137027777777778, 5.625865000000001, 2.690738209876544, 1.9445179012345684, 1.1263460905349796, 0.0, 14.175, 12.389806995884772, 9.722589506172842, 8.07221462962963, 11.251730000000002, 7.191838888888889, 5.649703050108934, 3.6458333333333335, 5.226410521168528, 4.308016319444445, 2.4041024691358035, 1.253792901234568, 0.0), # 39 (14.39183259346303, 13.755454103795152, 12.011045381801555, 12.916005979938273, 10.45605216943235, 5.104166666666667, 5.635750524489632, 5.1091177983539104, 5.622163065843623, 2.6835173754000925, 1.943384202103338, 1.125083828684652, 0.0, 14.175, 12.375922115531171, 9.71692101051669, 8.050552126200277, 11.244326131687245, 7.1527649176954755, 5.635750524489632, 3.6458333333333335, 5.228026084716175, 4.305335326646092, 2.4022090763603114, 1.2504958276177414, 0.0), # 40 (14.40121100375738, 13.717813180155463, 12.001194330132604, 12.90760652006173, 10.459170211611989, 5.104166666666667, 5.621276091341887, 5.080343621399178, 5.618305576131687, 2.676041122542296, 1.9421963815105796, 1.1237703551287916, 0.0, 14.175, 12.361473906416705, 9.710981907552897, 8.028123367626886, 11.236611152263373, 7.112481069958849, 5.621276091341887, 3.6458333333333335, 5.229585105805994, 4.302535506687244, 2.400238866026521, 1.2470739254686787, 0.0), # 41 (14.410256547852201, 13.678883641975311, 11.990978395061731, 12.89886354166667, 10.462174997562222, 5.104166666666667, 5.6063129629629636, 5.050791666666668, 5.614299444444446, 2.668328271604939, 1.9409558361391697, 1.122408230452675, 0.0, 14.175, 12.346490534979424, 9.704779180695848, 8.004984814814815, 11.228598888888891, 7.071108333333335, 5.6063129629629636, 3.6458333333333335, 5.231087498781111, 4.299621180555557, 2.3981956790123466, 1.2435348765432102, 0.0), # 42 (14.418968111589852, 13.638749988568819, 11.980416780978512, 12.889790007716051, 10.46506635596931, 5.104166666666667, 5.5908943516501255, 5.020548353909466, 5.61015158436214, 2.660397642889804, 1.9396639626719878, 1.1210000152415793, 0.0, 14.175, 12.331000167657372, 9.698319813359937, 7.981192928669412, 11.22030316872428, 7.0287676954732525, 5.5908943516501255, 3.6458333333333335, 5.232533177984655, 4.296596669238685, 2.3960833561957027, 1.2398863625971654, 0.0), # 43 (14.427344580812699, 13.597496719250115, 11.969528692272522, 12.880398881172843, 10.467844115519508, 5.104166666666667, 5.575053469700638, 4.98970010288066, 5.605868909465021, 2.652268056698675, 1.938322157791911, 1.1195482700807806, 0.0, 14.175, 12.315030970888586, 9.691610788959554, 7.9568041700960235, 11.211737818930041, 6.985580144032924, 5.575053469700638, 3.6458333333333335, 5.233922057759754, 4.293466293724282, 2.3939057384545044, 1.2361360653863744, 0.0), # 44 (14.435384841363105, 13.555208333333335, 11.958333333333336, 12.870703125000002, 10.470508104899077, 5.104166666666667, 5.558823529411765, 4.958333333333334, 5.601458333333333, 2.6439583333333343, 1.9369318181818187, 1.1180555555555556, 0.0, 14.175, 12.29861111111111, 9.684659090909092, 7.931875000000002, 11.202916666666667, 6.941666666666667, 5.558823529411765, 3.6458333333333335, 5.235254052449538, 4.290234375000002, 2.391666666666667, 1.232291666666667, 0.0), # 45 (14.443087779083434, 13.511969330132603, 11.946849908550526, 12.860715702160494, 10.47305815279427, 5.104166666666667, 5.542237743080772, 4.926534465020577, 5.596926769547324, 2.635487293095565, 1.9354943405245877, 1.1165244322511814, 0.0, 14.175, 12.281768754762993, 9.677471702622938, 7.906461879286693, 11.193853539094649, 6.897148251028808, 5.542237743080772, 3.6458333333333335, 5.236529076397135, 4.286905234053499, 2.3893699817101055, 1.228360848193873, 0.0), # 46 (14.45045227981605, 13.46786420896205, 11.935097622313673, 12.850449575617287, 10.475494087891343, 5.104166666666667, 5.525329323004923, 4.894389917695474, 5.592281131687244, 2.6268737562871523, 1.9340111215030973, 1.1149574607529342, 0.0, 14.175, 12.264532068282275, 9.670055607515485, 7.880621268861455, 11.184562263374488, 6.852145884773663, 5.525329323004923, 3.6458333333333335, 5.237747043945672, 4.283483191872429, 2.387019524462735, 1.2243512917238228, 0.0), # 47 (14.457477229403315, 13.422977469135803, 11.923095679012349, 12.839917708333335, 10.477815738876558, 5.104166666666667, 5.508131481481482, 4.861986111111112, 5.587528333333333, 2.618136543209877, 1.9324835578002246, 1.1133572016460909, 0.0, 14.175, 12.246929218106997, 9.662417789001124, 7.854409629629629, 11.175056666666666, 6.806780555555557, 5.508131481481482, 3.6458333333333335, 5.238907869438279, 4.279972569444446, 2.38461913580247, 1.2202706790123459, 0.0), # 48 (14.464161513687602, 13.377393609967992, 11.910863283036125, 12.829133063271607, 10.480022934436168, 5.104166666666667, 5.490677430807714, 4.829409465020577, 5.582675288065844, 2.6092944741655244, 1.930913046098849, 1.1117262155159278, 0.0, 14.175, 12.228988370675204, 9.654565230494246, 7.827883422496572, 11.165350576131688, 6.761173251028807, 5.490677430807714, 3.6458333333333335, 5.240011467218084, 4.276377687757203, 2.382172656607225, 1.2161266918152722, 0.0), # 49 (14.470504018511264, 13.33119713077275, 11.89841963877458, 12.81810860339506, 10.482115503256427, 5.104166666666667, 5.473000383280885, 4.796746399176955, 5.57772890946502, 2.6003663694558763, 1.9293009830818477, 1.1100670629477218, 0.0, 14.175, 12.210737692424937, 9.646504915409238, 7.8010991083676275, 11.15545781893004, 6.715444958847738, 5.473000383280885, 3.6458333333333335, 5.2410577516282135, 4.272702867798355, 2.379683927754916, 1.211927011888432, 0.0), # 50 (14.476503629716676, 13.284472530864198, 11.885783950617286, 12.806857291666669, 10.484093274023598, 5.104166666666667, 5.455133551198258, 4.764083333333335, 5.572696111111112, 2.5913710493827167, 1.9276487654320995, 1.1083823045267494, 0.0, 14.175, 12.192205349794241, 9.638243827160496, 7.774113148148149, 11.145392222222224, 6.669716666666668, 5.455133551198258, 3.6458333333333335, 5.242046637011799, 4.268952430555557, 2.377156790123457, 1.2076793209876546, 0.0), # 51 (14.482159233146191, 13.237304309556471, 11.87297542295382, 12.795392091049385, 10.485956075423934, 5.104166666666667, 5.437110146857097, 4.731506687242798, 5.567583806584363, 2.582327334247829, 1.9259577898324816, 1.1066745008382872, 0.0, 14.175, 12.173419509221157, 9.629788949162407, 7.746982002743485, 11.135167613168726, 6.624109362139918, 5.437110146857097, 3.6458333333333335, 5.242978037711967, 4.265130697016462, 2.3745950845907644, 1.2033913008687704, 0.0), # 52 (14.487469714642183, 13.189776966163697, 11.860013260173757, 12.783725964506175, 10.487703736143693, 5.104166666666667, 5.418963382554669, 4.699102880658437, 5.5623989094650215, 2.573254044352996, 1.9242294529658732, 1.104946212467612, 0.0, 14.175, 12.15440833714373, 9.621147264829364, 7.719762133058986, 11.124797818930043, 6.578744032921811, 5.418963382554669, 3.6458333333333335, 5.243851868071847, 4.261241988168726, 2.3720026520347517, 1.199070633287609, 0.0), # 53 (14.492433960047004, 13.141975000000002, 11.846916666666667, 12.771871875000002, 10.489336084869135, 5.104166666666667, 5.400726470588236, 4.6669583333333335, 5.557148333333334, 2.5641700000000007, 1.9224651515151516, 1.1032000000000002, 0.0, 14.175, 12.1352, 9.612325757575757, 7.69251, 11.114296666666668, 6.533741666666667, 5.400726470588236, 3.6458333333333335, 5.244668042434568, 4.257290625000001, 2.369383333333334, 1.1947250000000003, 0.0), # 54 (14.497050855203032, 13.093982910379516, 11.833704846822133, 12.759842785493827, 10.490852950286511, 5.104166666666667, 5.382432623255064, 4.6351594650205765, 5.551838991769547, 2.555094021490627, 1.9206662821631961, 1.101438424020729, 0.0, 14.175, 12.115822664228014, 9.603331410815981, 7.66528206447188, 11.103677983539095, 6.4892232510288075, 5.382432623255064, 3.6458333333333335, 5.2454264751432556, 4.253280928497944, 2.3667409693644266, 1.1903620827617745, 0.0), # 55 (14.501319285952622, 13.045885196616371, 11.820397005029724, 12.74765165895062, 10.492254161082082, 5.104166666666667, 5.3641150528524175, 4.603792695473252, 5.5464777983539095, 2.5460449291266585, 1.918834241592884, 1.099664045115074, 0.0, 14.175, 12.096304496265812, 9.59417120796442, 7.638134787379974, 11.092955596707819, 6.445309773662553, 5.3641150528524175, 3.6458333333333335, 5.246127080541041, 4.249217219650207, 2.3640794010059447, 1.1859895633287612, 0.0), # 56 (14.505238138138138, 12.997766358024693, 11.807012345679016, 12.735311458333335, 10.493539545942102, 5.104166666666667, 5.34580697167756, 4.572944444444445, 5.541071666666667, 2.5370415432098774, 1.9169704264870937, 1.097879423868313, 0.0, 14.175, 12.076673662551439, 9.584852132435467, 7.61112462962963, 11.082143333333335, 6.402122222222224, 5.34580697167756, 3.6458333333333335, 5.246769772971051, 4.245103819444446, 2.3614024691358035, 1.1816151234567904, 0.0), # 57 (14.508806297601952, 12.949710893918612, 11.79357007315958, 12.72283514660494, 10.494708933552829, 5.104166666666667, 5.3275415920277585, 4.5427011316872425, 5.535627510288066, 2.5281026840420675, 1.9150762335287033, 1.096087120865722, 0.0, 14.175, 12.05695832952294, 9.575381167643515, 7.584308052126201, 11.071255020576132, 6.35978158436214, 5.3275415920277585, 3.6458333333333335, 5.2473544667764145, 4.240945048868314, 2.3587140146319165, 1.1772464449016922, 0.0), # 58 (14.51202265018642, 12.901803303612255, 11.780089391860999, 12.710235686728396, 10.495762152600523, 5.104166666666667, 5.309352126200275, 4.513149176954733, 5.530152242798355, 2.5192471719250125, 1.9131530594005905, 1.0942896966925775, 0.0, 14.175, 12.037186663618352, 9.565765297002951, 7.557741515775036, 11.06030448559671, 6.3184088477366265, 5.309352126200275, 3.6458333333333335, 5.247881076300262, 4.2367452289094665, 2.3560178783722, 1.172891209419296, 0.0), # 59 (14.51488608173391, 12.854128086419754, 11.76658950617284, 12.697526041666668, 10.496699031771435, 5.104166666666667, 5.291271786492374, 4.484375000000001, 5.524652777777779, 2.5104938271604946, 1.9112023007856345, 1.0924897119341568, 0.0, 14.175, 12.017386831275722, 9.556011503928172, 7.5314814814814826, 11.049305555555557, 6.278125000000001, 5.291271786492374, 3.6458333333333335, 5.248349515885717, 4.232508680555557, 2.353317901234568, 1.1685570987654323, 0.0), # 60 (14.517395478086781, 12.806769741655238, 11.753089620484685, 12.684719174382717, 10.497519399751823, 5.104166666666667, 5.273333785201324, 4.4564650205761325, 5.519136028806585, 2.501861470050298, 1.9092253543667126, 1.0906897271757356, 0.0, 14.175, 11.997586998933091, 9.546126771833563, 7.5055844101508935, 11.03827205761317, 6.2390510288065855, 5.273333785201324, 3.6458333333333335, 5.248759699875912, 4.22823972479424, 2.350617924096937, 1.1642517946959308, 0.0), # 61 (14.519549725087407, 12.759812768632832, 11.739608939186102, 12.671828047839508, 10.498223085227952, 5.104166666666667, 5.255571334624385, 4.429505658436215, 5.513608909465021, 2.4933689208962058, 1.9072236168267036, 1.0888923030025914, 0.0, 14.175, 11.977815333028504, 9.536118084133516, 7.4801067626886155, 11.027217818930042, 6.201307921810701, 5.255571334624385, 3.6458333333333335, 5.249111542613976, 4.2239426826131705, 2.3479217878372207, 1.1599829789666212, 0.0), # 62 (14.521347708578144, 12.713341666666667, 11.72616666666667, 12.658865625, 10.498809916886067, 5.104166666666667, 5.238017647058824, 4.4035833333333345, 5.508078333333334, 2.4850350000000003, 1.9051984848484853, 1.0871000000000002, 0.0, 14.175, 11.9581, 9.525992424242425, 7.455105, 11.016156666666667, 6.165016666666668, 5.238017647058824, 3.6458333333333335, 5.249404958443034, 4.219621875000001, 2.345233333333334, 1.1557583333333337, 0.0), # 63 (14.522788314401359, 12.667440935070873, 11.712782007315958, 12.645844868827162, 10.499279723412432, 5.104166666666667, 5.220705934801905, 4.378784465020577, 5.50255121399177, 2.4768785276634664, 1.9031513551149353, 1.0853153787532392, 0.0, 14.175, 11.938469166285628, 9.515756775574676, 7.430635582990398, 11.00510242798354, 6.130298251028808, 5.220705934801905, 3.6458333333333335, 5.249639861706216, 4.215281622942388, 2.342556401463192, 1.151585539551898, 0.0), # 64 (14.523870428399414, 12.62219507315958, 11.69947416552355, 12.63277874228395, 10.499632333493302, 5.104166666666667, 5.2036694101508925, 4.35519547325103, 5.497034465020577, 2.4689183241883863, 1.9010836243089335, 1.0835409998475842, 0.0, 14.175, 11.918950998323425, 9.505418121544666, 7.406754972565158, 10.994068930041154, 6.097273662551442, 5.2036694101508925, 3.6458333333333335, 5.249816166746651, 4.2109262474279845, 2.3398948331047102, 1.1474722793781438, 0.0), # 65 (14.524592936414676, 12.577688580246916, 11.686262345679015, 12.619680208333333, 10.499867575814935, 5.104166666666667, 5.1869412854030505, 4.332902777777779, 5.491535000000001, 2.4611732098765438, 1.898996689113356, 1.0817794238683132, 0.0, 14.175, 11.899573662551441, 9.49498344556678, 7.38351962962963, 10.983070000000001, 6.06606388888889, 5.1869412854030505, 3.6458333333333335, 5.249933787907468, 4.206560069444445, 2.337252469135803, 1.1434262345679016, 0.0), # 66 (14.524954724289511, 12.534005955647004, 11.673165752171926, 12.606562229938273, 10.499985279063587, 5.104166666666667, 5.1705547728556445, 4.311992798353911, 5.486059732510288, 2.453662005029722, 1.8968919462110825, 1.0800332114007012, 0.0, 14.175, 11.88036532540771, 9.484459731055413, 7.360986015089164, 10.972119465020576, 6.036789917695475, 5.1705547728556445, 3.6458333333333335, 5.2499926395317935, 4.202187409979425, 2.3346331504343856, 1.1394550868770006, 0.0), # 67 (14.524708260273156, 12.491002420461081, 11.660140274919984, 12.593323827495976, 10.499886091610856, 5.104071942793273, 5.154460636380753, 4.292367245846671, 5.480574329370524, 2.446367154576509, 1.894733397326088, 1.078295169221637, 0.0, 14.174825210048013, 11.861246861438005, 9.47366698663044, 7.339101463729525, 10.961148658741047, 6.009314144185339, 5.154460636380753, 3.6457656734237665, 5.249943045805428, 4.197774609165326, 2.3320280549839967, 1.135545674587371, 0.0), # 68 (14.522398389694043, 12.44736508363202, 11.646819830246914, 12.579297690217391, 10.498983297022512, 5.1033231138545965, 5.13818772694263, 4.272974279835392, 5.474838991769548, 2.439082236746551, 1.8923013290802768, 1.0765088802252547, 0.0, 14.17344039351852, 11.8415976824778, 9.461506645401384, 7.317246710239651, 10.949677983539097, 5.982163991769549, 5.13818772694263, 3.6452307956104257, 5.249491648511256, 4.193099230072464, 2.329363966049383, 1.1315786439665476, 0.0), # 69 (14.517840102582454, 12.402893656798973, 11.633146504915409, 12.564391480475042, 10.49719935985368, 5.101848358989992, 5.121662094192959, 4.253638926992837, 5.468821349641823, 2.4317718335619576, 1.8895680735227522, 1.0746659888174948, 0.0, 14.170705268347055, 11.82132587699244, 9.447840367613761, 7.295315500685872, 10.937642699283646, 5.955094497789972, 5.121662094192959, 3.6441773992785653, 5.24859967992684, 4.188130493491681, 2.326629300983082, 1.127535786981725, 0.0), # 70 (14.511097524900102, 12.357614716359132, 11.619125100022863, 12.548627178945251, 10.49455687350386, 5.0996715769953775, 5.104891161677292, 4.234367588782199, 5.462530365035819, 2.4244361257699243, 1.8865437198495683, 1.072767842674817, 0.0, 14.166655842764062, 11.800446269422984, 9.43271859924784, 7.273308377309771, 10.925060730071637, 5.928114624295079, 5.104891161677292, 3.642622554996698, 5.24727843675193, 4.182875726315085, 2.323825020004573, 1.1234195196690122, 0.0), # 71 (14.502234782608697, 12.311554838709677, 11.604760416666666, 12.532026766304348, 10.49107843137255, 5.096816666666667, 5.087882352941177, 4.215166666666667, 5.4559750000000005, 2.4170752941176477, 1.8832383572567788, 1.0708157894736845, 0.0, 14.161328125, 11.778973684210527, 9.416191786283894, 7.251225882352942, 10.911950000000001, 5.901233333333334, 5.087882352941177, 3.6405833333333337, 5.245539215686275, 4.177342255434784, 2.3209520833333337, 1.1192322580645162, 0.0), # 72 (14.491316001669949, 12.264740600247798, 11.590057255944217, 12.514612223228664, 10.486786626859248, 5.0933075267997765, 5.070643091530164, 4.196042562109436, 5.4491642165828384, 2.409689519352323, 1.8796620749404376, 1.0688111768905575, 0.0, 14.154758123285324, 11.75692294579613, 9.398310374702186, 7.229068558056968, 10.898328433165677, 5.8744595869532095, 5.070643091530164, 3.638076804856983, 5.243393313429624, 4.171537407742889, 2.3180114511888434, 1.1149764182043456, 0.0), # 73 (14.478405308045566, 12.21719857737068, 11.575020418952905, 12.496405530394526, 10.481704053363458, 5.089168056190623, 5.053180800989806, 4.177001676573693, 5.4421069768328, 2.402278982221147, 1.8758249620965999, 1.0667553526018982, 0.0, 14.146981845850483, 11.734308878620878, 9.379124810482999, 7.20683694666344, 10.8842139536656, 5.84780234720317, 5.053180800989806, 3.635120040136159, 5.240852026681729, 4.165468510131509, 2.315004083790581, 1.1106544161246077, 0.0), # 74 (14.463566827697262, 12.168955346475506, 11.559654706790123, 12.477428668478263, 10.475853304284678, 5.084422153635118, 5.03550290486565, 4.158050411522635, 5.434812242798353, 2.394843863471315, 1.8717371079213185, 1.0646496642841674, 0.0, 14.138035300925928, 11.711146307125839, 9.358685539606592, 7.184531590413944, 10.869624485596706, 5.821270576131688, 5.03550290486565, 3.63173010973937, 5.237926652142339, 4.159142889492755, 2.311930941358025, 1.10626866786141, 0.0), # 75 (14.44686468658675, 12.12003748395947, 11.543964920553272, 12.457703618156202, 10.469256973022405, 5.079093717929179, 5.017616826703247, 4.139195168419449, 5.427288976527969, 2.3873843438500235, 1.8674086016106486, 1.0624954596138265, 0.0, 14.127954496742113, 11.68745005575209, 9.337043008053241, 7.162153031550069, 10.854577953055937, 5.794873235787229, 5.017616826703247, 3.6279240842351275, 5.234628486511203, 4.152567872718735, 2.3087929841106543, 1.101821589450861, 0.0), # 76 (14.428363010675731, 12.070471566219748, 11.527955861339734, 12.43725236010467, 10.461937652976141, 5.07320664786872, 4.9995299900481465, 4.120442348727329, 5.4195461400701115, 2.3799006041044684, 1.8628495323606438, 1.0602940862673376, 0.0, 14.116775441529496, 11.663234948940712, 9.314247661803218, 7.139701812313404, 10.839092280140223, 5.768619288218261, 4.9995299900481465, 3.623719034191943, 5.230968826488071, 4.145750786701558, 2.305591172267947, 1.0973155969290682, 0.0), # 77 (14.408125925925928, 12.020284169653527, 11.511632330246915, 12.416096875000001, 10.45391793754539, 5.066784842249657, 4.981249818445898, 4.101798353909466, 5.41159269547325, 2.372392824981845, 1.8580699893673582, 1.0580468919211612, 0.0, 14.10453414351852, 11.638515811132772, 9.29034994683679, 7.1171784749455345, 10.8231853909465, 5.742517695473253, 4.981249818445898, 3.6191320301783265, 5.226958968772695, 4.138698958333334, 2.3023264660493834, 1.092753106332139, 0.0), # 78 (14.386217558299041, 11.969501870657995, 11.494999128372202, 12.394259143518521, 10.445220420129644, 5.0598521998679065, 4.962783735442051, 4.0832695854290515, 5.403437604785855, 2.3648611872293506, 1.8530800618268455, 1.0557552242517592, 0.0, 14.091266610939643, 11.613307466769347, 9.265400309134227, 7.094583561688051, 10.80687520957171, 5.716577419600672, 4.962783735442051, 3.61418014276279, 5.222610210064822, 4.131419714506174, 2.2989998256744406, 1.0881365336961817, 0.0), # 79 (14.362702033756786, 11.918151245630337, 11.478061056812987, 12.371761146336556, 10.435867694128408, 5.052432619519382, 4.9441391645821575, 4.064862444749277, 5.395089830056394, 2.35730587159418, 1.847889838935161, 1.0534204309355928, 0.0, 14.07700885202332, 11.587624740291517, 9.239449194675805, 7.071917614782539, 10.790179660112788, 5.690807422648988, 4.9441391645821575, 3.6088804425138443, 5.217933847064204, 4.123920382112186, 2.2956122113625974, 1.0834682950573036, 0.0), # 80 (14.337643478260873, 11.866258870967743, 11.460822916666668, 12.348624864130437, 10.425882352941176, 5.04455, 4.925323529411765, 4.046583333333334, 5.386558333333333, 2.34972705882353, 1.8425094098883579, 1.0510438596491232, 0.0, 14.061796875, 11.561482456140352, 9.212547049441788, 7.049181176470589, 10.773116666666667, 5.665216666666669, 4.925323529411765, 3.60325, 5.212941176470588, 4.11620828804348, 2.2921645833333337, 1.0787508064516131, 0.0), # 81 (14.311106017773009, 11.813851323067393, 11.443289509030638, 12.32487227757649, 10.415286989967456, 5.036228240105676, 4.906344253476426, 4.0284386526444145, 5.3778520766651425, 2.342124929664596, 1.83694886388249, 1.048626858068812, 0.0, 14.045666688100141, 11.53489543875693, 9.18474431941245, 7.026374788993786, 10.755704153330285, 5.63981411370218, 4.906344253476426, 3.5973058857897686, 5.207643494983728, 4.1082907591921645, 2.2886579018061277, 1.0739864839152178, 0.0), # 82 (14.283153778254908, 11.760955178326475, 11.425465635002288, 12.300525367351046, 10.40410419860674, 5.027491238632323, 4.887208760321688, 4.01043480414571, 5.368980022100289, 2.3344996648645746, 1.8312182901136123, 1.0461707738711208, 0.0, 14.028654299554185, 11.507878512582325, 9.156091450568061, 7.0034989945937225, 10.737960044200578, 5.614608725803994, 4.887208760321688, 3.5910651704516594, 5.20205209930337, 4.1001751224503495, 2.2850931270004575, 1.0691777434842251, 0.0), # 83 (14.253850885668278, 11.707597013142175, 11.407356095679013, 12.275606114130436, 10.392356572258533, 5.0183628943758585, 4.867924473493101, 3.9925781893004118, 5.359951131687243, 2.3268514451706617, 1.825327777777778, 1.0436769547325107, 0.0, 14.010795717592593, 11.480446502057614, 9.12663888888889, 6.980554335511984, 10.719902263374486, 5.589609465020577, 4.867924473493101, 3.5845449245541845, 5.196178286129267, 4.091868704710146, 2.281471219135803, 1.0643270011947434, 0.0), # 84 (14.223261465974833, 11.653803403911677, 11.388965692158209, 12.250136498590983, 10.380066704322333, 5.008867106132196, 4.8484988165362175, 3.974875209571713, 5.35077436747447, 2.3191804513300527, 1.8192874160710422, 1.041146748329443, 0.0, 13.992126950445819, 11.452614231623869, 9.09643708035521, 6.957541353990157, 10.70154873494894, 5.564825293400398, 4.8484988165362175, 3.577762218665854, 5.190033352161167, 4.083378832863662, 2.2777931384316417, 1.05943667308288, 0.0), # 85 (14.191449645136279, 11.59960092703217, 11.370299225537268, 12.224138501409021, 10.367257188197637, 4.999027772697253, 4.828939212996585, 3.9573322664228017, 5.341458691510441, 2.311486864089944, 1.8131072941894584, 1.0385815023383795, 0.0, 13.97268400634431, 11.424396525722173, 9.065536470947292, 6.934460592269831, 10.682917383020882, 5.540265172991923, 4.828939212996585, 3.57073412335518, 5.183628594098819, 4.074712833803008, 2.274059845107454, 1.0545091751847429, 0.0), # 86 (14.15847954911433, 11.545016158900838, 11.35136149691358, 12.19763410326087, 10.353950617283953, 4.988868792866941, 4.809253086419753, 3.939955761316873, 5.332013065843622, 2.3037708641975314, 1.8067975013290805, 1.035982564435781, 0.0, 13.95250289351852, 11.39580820879359, 9.033987506645403, 6.9113125925925925, 10.664026131687244, 5.515938065843622, 4.809253086419753, 3.563477709190672, 5.1769753086419765, 4.065878034420291, 2.2702722993827162, 1.0495469235364399, 0.0), # 87 (14.124415303870702, 11.490075675914863, 11.332157307384547, 12.170645284822868, 10.340169584980769, 4.97841406543718, 4.789447860351274, 3.9227520957171165, 5.322446452522482, 2.296032632400011, 1.8003681266859632, 1.0333512822981095, 0.0, 13.931619620198905, 11.366864105279202, 9.001840633429817, 6.888097897200032, 10.644892905044964, 5.491852934003963, 4.789447860351274, 3.556010046740843, 5.1700847924903846, 4.056881761607624, 2.2664314614769094, 1.0445523341740786, 0.0), # 88 (14.089321035367092, 11.434806054471437, 11.312691458047555, 12.143194026771337, 10.325936684687594, 4.967687489203883, 4.769530958336696, 3.905727671086725, 5.312767813595489, 2.2882723494445796, 1.7938292594561607, 1.030689003601826, 0.0, 13.910070194615912, 11.337579039620083, 8.969146297280803, 6.864817048333737, 10.625535627190978, 5.4680187395214155, 4.769530958336696, 3.548348206574202, 5.162968342343797, 4.047731342257113, 2.2625382916095114, 1.0395278231337672, 0.0), # 89 (14.053260869565218, 11.379233870967743, 11.292968750000002, 12.115302309782612, 10.311274509803923, 4.956712962962964, 4.749509803921569, 3.8888888888888893, 5.302986111111112, 2.280490196078432, 1.787190988835726, 1.027997076023392, 0.0, 13.887890625, 11.30796783625731, 8.93595494417863, 6.841470588235294, 10.605972222222224, 5.4444444444444455, 4.749509803921569, 3.54050925925926, 5.155637254901961, 4.0384341032608715, 2.2585937500000006, 1.0344758064516133, 0.0), # 90 (14.016298932426789, 11.323385701800964, 11.272993984339278, 12.086992114533015, 10.296205653729254, 4.945514385510339, 4.729391820651443, 3.8722421505868017, 5.293110307117818, 2.2726863530487647, 1.7804634040207143, 1.025276847239269, 0.0, 13.865116919581618, 11.278045319631957, 8.902317020103572, 6.818059059146293, 10.586220614235636, 5.4211390108215225, 4.729391820651443, 3.5325102753645283, 5.148102826864627, 4.0289973715110055, 2.254598796867856, 1.0293987001637241, 0.0), # 91 (13.978499349913523, 11.267288123368292, 11.252771962162782, 12.058285421698875, 10.280752709863094, 4.934115655641925, 4.709184432071869, 3.8557938576436523, 5.2831493636640765, 2.2648610011027737, 1.7736565942071794, 1.0225296649259181, 0.0, 13.841785086591221, 11.247826314185097, 8.868282971035896, 6.79458300330832, 10.566298727328153, 5.398111400701113, 4.709184432071869, 3.524368325458518, 5.140376354931547, 4.019428473899626, 2.2505543924325564, 1.0242989203062085, 0.0), # 92 (13.939926247987117, 11.210967712066907, 11.232307484567903, 12.029204211956525, 10.264938271604938, 4.9225406721536356, 4.688895061728395, 3.839550411522634, 5.273112242798354, 2.2570143209876545, 1.7667806485911755, 1.019756876759801, 0.0, 13.81793113425926, 11.217325644357809, 8.833903242955877, 6.771042962962962, 10.546224485596708, 5.375370576131688, 4.688895061728395, 3.5161004801097393, 5.132469135802469, 4.009734737318842, 2.246461496913581, 1.0191788829151736, 0.0), # 93 (13.900643752609293, 11.154451044293994, 11.211605352652038, 11.999770465982289, 10.248784932354287, 4.910813333841387, 4.6685311331665735, 3.8235182136869392, 5.263007906569121, 2.2491464934506045, 1.7598456563687561, 1.016959830417379, 0.0, 13.793591070816188, 11.186558134591166, 8.79922828184378, 6.747439480351812, 10.526015813138242, 5.3529254991617155, 4.6685311331665735, 3.5077238098867047, 5.124392466177143, 3.9999234886607637, 2.2423210705304077, 1.014041004026727, 0.0), # 94 (13.860715989741754, 11.097764696446747, 11.190670367512576, 11.970006164452498, 10.232315285510639, 4.898957539501094, 4.648100069931951, 3.807703665599757, 5.252845317024844, 2.241257699238818, 1.752861706735976, 1.014139873575113, 0.0, 13.768800904492457, 11.155538609326241, 8.764308533679879, 6.723773097716453, 10.505690634049689, 5.33078513183966, 4.648100069931951, 3.499255385357924, 5.1161576427553195, 3.9900020548175, 2.2381340735025153, 1.0088876996769771, 0.0), # 95 (13.820207085346219, 11.040935244922345, 11.169507330246915, 11.93993328804348, 10.215551924473493, 4.88699718792867, 4.62760929557008, 3.7921131687242804, 5.242633436213992, 2.2333481190994924, 1.7458388888888892, 1.0112983539094653, 0.0, 13.74359664351852, 11.124281893004117, 8.729194444444445, 6.700044357298475, 10.485266872427983, 5.3089584362139925, 4.62760929557008, 3.490712277091907, 5.1077759622367465, 3.9799777626811608, 2.2339014660493834, 1.0037213859020315, 0.0), # 96 (13.779181165384388, 10.983989266117973, 11.148121041952448, 11.909573817431562, 10.198517442642354, 4.8749561779200326, 4.60706623362651, 3.7767531245237014, 5.2323812261850335, 2.2254179337798226, 1.7387872920235496, 1.0084366190968967, 0.0, 13.718014296124831, 11.09280281006586, 8.693936460117747, 6.676253801339467, 10.464762452370067, 5.287454374333182, 4.60706623362651, 3.482111555657166, 5.099258721321177, 3.969857939143855, 2.2296242083904896, 0.9985444787379977, 0.0), # 97 (13.737702355817978, 10.926953336430817, 11.126516303726566, 11.878949733293078, 10.181234433416716, 4.862858408271099, 4.58647830764679, 3.7616299344612103, 5.222097648986434, 2.2174673240270053, 1.7317170053360116, 1.0055560168138682, 0.0, 13.69208987054184, 11.06111618495255, 8.658585026680058, 6.652401972081014, 10.444195297972868, 5.266281908245695, 4.58647830764679, 3.4734702916222133, 5.090617216708358, 3.9596499110976935, 2.2253032607453136, 0.9933593942209834, 0.0), # 98 (13.695834782608697, 10.869854032258065, 11.10469791666667, 11.848083016304349, 10.163725490196079, 4.850727777777779, 4.5658529411764714, 3.7467500000000005, 5.211791666666667, 2.2094964705882356, 1.724638118022329, 1.0026578947368423, 0.0, 13.665859375000002, 11.029236842105265, 8.623190590111644, 6.628489411764706, 10.423583333333333, 5.245450000000001, 4.5658529411764714, 3.4648055555555564, 5.081862745098039, 3.949361005434784, 2.220939583333334, 0.988168548387097, 0.0), # 99 (13.653642571718258, 10.8127179299969, 11.082670681870143, 11.816995647141708, 10.146013206379946, 4.8385881852359915, 4.545197557761102, 3.732119722603262, 5.201472241274196, 2.201505554210711, 1.717560719278556, 0.9997436005422796, 0.0, 13.639358817729768, 10.997179605965075, 8.58780359639278, 6.6045166626321326, 10.402944482548392, 5.224967611644567, 4.545197557761102, 3.456134418025708, 5.073006603189973, 3.938998549047237, 2.2165341363740287, 0.9829743572724456, 0.0), # 100 (13.611189849108369, 10.755571606044516, 11.060439400434387, 11.785709606481484, 10.128120175367815, 4.82646352944165, 4.524519580946234, 3.7177455037341867, 5.191148334857491, 2.1934947556416264, 1.7104948983007466, 0.9968144819066413, 0.0, 13.612624206961591, 10.964959300973053, 8.552474491503732, 6.580484266924878, 10.382296669714982, 5.204843705227861, 4.524519580946234, 3.4474739496011786, 5.064060087683908, 3.928569868827162, 2.2120878800868775, 0.977779236913138, 0.0), # 101 (13.568540740740744, 10.698441636798089, 11.038008873456791, 11.754246875000002, 10.110068990559187, 4.814377709190674, 4.503826434277415, 3.7036337448559675, 5.180828909465021, 2.1854642556281783, 1.7034507442849551, 0.9938718865063897, 0.0, 13.585691550925928, 10.932590751570284, 8.517253721424776, 6.556392766884533, 10.361657818930041, 5.185087242798355, 4.503826434277415, 3.438841220850481, 5.055034495279593, 3.918082291666668, 2.207601774691358, 0.972585603345281, 0.0), # 102 (13.525759372577088, 10.641354598654807, 11.015383902034753, 11.722629433373593, 10.09188224535356, 4.802354623278973, 4.483125541300197, 3.689790847431795, 5.170522927145252, 2.1774142349175616, 1.696438346427236, 0.9909171620179854, 0.0, 13.558596857853223, 10.900088782197837, 8.482191732136178, 6.532242704752683, 10.341045854290504, 5.1657071864045125, 4.483125541300197, 3.4302533023421233, 5.04594112267678, 3.907543144457865, 2.2030767804069504, 0.9673958726049827, 0.0), # 103 (13.482909870579116, 10.58433706801186, 10.992569287265662, 11.690879262278584, 10.073582533150434, 4.790418170502465, 4.462424325560129, 3.6762232129248593, 5.160239349946655, 2.1693448742569736, 1.689467793923642, 0.9879516561178898, 0.0, 13.53137613597394, 10.867468217296787, 8.447338969618208, 6.50803462277092, 10.32047869989331, 5.146712498094804, 4.462424325560129, 3.421727264644618, 5.036791266575217, 3.896959754092862, 2.1985138574531327, 0.9622124607283511, 0.0), # 104 (13.440056360708535, 10.527415621266428, 10.969569830246915, 11.659018342391304, 10.05519244734931, 4.778592249657065, 4.441730210602761, 3.662937242798354, 5.1499871399176955, 2.1612563543936103, 1.682549175970229, 0.9849767164825647, 0.0, 13.50406539351852, 10.83474388130821, 8.412745879851144, 6.48376906318083, 10.299974279835391, 5.128112139917696, 4.441730210602761, 3.4132801783264752, 5.027596223674655, 3.886339447463769, 2.1939139660493834, 0.9570377837514936, 0.0), # 105 (13.39726296892706, 10.470616834815702, 10.946390332075904, 11.627068654388085, 10.036734581349688, 4.766900759538689, 4.4210506199736415, 3.6499393385154706, 5.139775259106843, 2.153148856074666, 1.67569258176305, 0.9819936907884712, 0.0, 13.476700638717421, 10.801930598673183, 8.378462908815248, 6.459446568223997, 10.279550518213686, 5.109915073921659, 4.4210506199736415, 3.4049291139562063, 5.018367290674844, 3.875689551462696, 2.189278066415181, 0.9518742577105185, 0.0), # 106 (13.3545938211964, 10.413967285056863, 10.923035593850026, 11.59505217894525, 10.018231528551063, 4.755367598943252, 4.400392977218323, 3.6372359015394005, 5.129612669562567, 2.145022560047339, 1.6689081004981592, 0.9790039267120707, 0.0, 13.449317879801098, 10.769043193832776, 8.344540502490794, 6.435067680142016, 10.259225339125134, 5.092130262155161, 4.400392977218323, 3.3966911421023225, 5.009115764275531, 3.865017392981751, 2.1846071187700056, 0.9467242986415331, 0.0), # 107 (13.312113043478263, 10.357493548387097, 10.899510416666669, 11.562990896739132, 9.999705882352941, 4.744016666666668, 4.379764705882353, 3.6248333333333345, 5.119508333333334, 2.1368776470588244, 1.662205821371611, 0.9760087719298248, 0.0, 13.421953125000002, 10.736096491228071, 8.311029106858054, 6.4106329411764715, 10.239016666666668, 5.074766666666668, 4.379764705882353, 3.3885833333333344, 4.999852941176471, 3.854330298913045, 2.179902083333334, 0.9415903225806455, 0.0), # 108 (13.26988476173436, 10.301222201203595, 10.87581960162323, 11.530906788446053, 9.98118023615482, 4.732871861504853, 4.359173229511284, 3.612738035360464, 5.109471212467612, 2.1287142978563174, 1.6555958335794598, 0.9730095741181947, 0.0, 13.394642382544584, 10.70310531530014, 8.277979167897298, 6.386142893568951, 10.218942424935223, 5.05783324950465, 4.359173229511284, 3.3806227582177515, 4.99059011807741, 3.8436355961486854, 2.1751639203246462, 0.9364747455639633, 0.0), # 109 (13.227973101926404, 10.245179819903537, 10.851967949817103, 11.498821834742351, 9.962677183356197, 4.721957082253722, 4.3386259716506625, 3.6009564090839814, 5.099510269013869, 2.1205326931870148, 1.6490882263177586, 0.9700076809536419, 0.0, 13.367421660665297, 10.670084490490058, 8.245441131588793, 6.361598079561043, 10.199020538027739, 5.041338972717574, 4.3386259716506625, 3.372826487324087, 4.981338591678099, 3.832940611580785, 2.170393589963421, 0.9313799836275944, 0.0), # 110 (13.186442190016104, 10.189392980884113, 10.827960262345682, 11.46675801630435, 9.944219317356573, 4.711296227709192, 4.318130355846042, 3.5894948559670787, 5.089634465020577, 2.1123330137981124, 1.6426930887825626, 0.9670044401126275, 0.0, 13.340326967592594, 10.6370488412389, 8.213465443912813, 6.336999041394336, 10.179268930041154, 5.02529279835391, 4.318130355846042, 3.3652115912208513, 4.972109658678287, 3.8222526721014507, 2.1655920524691368, 0.9263084528076467, 0.0), # 111 (13.14535615196517, 10.133888260542502, 10.803801340306359, 11.434737313808373, 9.925829231555449, 4.700913196667176, 4.297693805642971, 3.5783597774729468, 5.079852762536198, 2.1041154404368063, 1.6364205101699256, 0.9640011992716131, 0.0, 13.313394311556928, 10.604013191987741, 8.182102550849628, 6.312346321310418, 10.159705525072397, 5.0097036884621255, 4.297693805642971, 3.357795140476554, 4.962914615777724, 3.8115791046027923, 2.160760268061272, 0.9212625691402275, 0.0), # 112 (13.104705913184263, 10.078784894108638, 10.779554132960747, 11.402825576616644, 9.907497301495457, 4.690826978191853, 4.277368174559739, 3.5675806651220205, 5.07019931192069, 2.095906657814456, 1.6302822447690024, 0.9610058425921835, 0.0, 13.286621461180511, 10.571064268514016, 8.151411223845011, 6.287719973443367, 10.14039862384138, 4.9946129311708285, 4.277368174559739, 3.3505906987084666, 4.953748650747729, 3.8009418588722155, 2.15591082659215, 0.9162531721916946, 0.0), # 113 (13.064073257060091, 10.024626385524439, 10.755553287525224, 11.371278892341204, 9.88903379759524, 4.681014596966087, 4.257412745887406, 3.557289901377987, 5.060822216666095, 2.0878603087694745, 1.6242903453264128, 0.9580564200798471, 0.0, 13.25978557982405, 10.538620620878318, 8.121451726632063, 6.263580926308422, 10.12164443333219, 4.980205861929182, 4.257412745887406, 3.3435818549757763, 4.94451689879762, 3.790426297447069, 2.1511106575050447, 0.9113296714113127, 0.0), # 114 (13.023338864205595, 9.97143223830991, 10.731813088158539, 11.340088730440868, 9.870380499362694, 4.671450535207326, 4.2378417551340934, 3.547484881662581, 5.051724990045435, 2.0799888647958276, 1.6184360526663222, 0.9551543846318662, 0.0, 13.232809284324528, 10.506698230950526, 8.09218026333161, 6.239966594387481, 10.10344998009087, 4.966478834327614, 4.2378417551340934, 3.336750382290947, 4.935190249681347, 3.780029576813624, 2.146362617631708, 0.9064938398463556, 0.0), # 115 (12.982451822532688, 9.919124960991017, 10.708287554981187, 11.309199457779725, 9.851509291291528, 4.662112249784464, 4.218623372269525, 3.5381385158577467, 5.042884624972988, 2.072277675457342, 1.6127080506300124, 0.9522943730401906, 0.0, 13.205650163658248, 10.475238103442095, 8.063540253150062, 6.216833026372026, 10.085769249945976, 4.953393922200846, 4.218623372269525, 3.330080178417474, 4.925754645645764, 3.7697331525932425, 2.1416575109962372, 0.9017386328173653, 0.0), # 116 (12.941361219953283, 9.867627062093726, 10.68493070811365, 11.278555441221856, 9.832392057875436, 4.652977197566394, 4.199725767263427, 3.529223713845425, 5.034278114363028, 2.0647120903178457, 1.6070950230587664, 0.949471022096771, 0.0, 13.178265806801516, 10.44418124306448, 8.035475115293831, 6.1941362709535355, 10.068556228726056, 4.940913199383595, 4.199725767263427, 3.3235551411188533, 4.916196028937718, 3.7595184804072863, 2.1369861416227303, 0.8970570056448843, 0.0), # 117 (12.900016144379297, 9.816861050144, 10.66169656767643, 11.248101047631351, 9.81300068360812, 4.644022835422014, 4.181117110085521, 3.5207133855075567, 5.025882451129837, 2.0572774589411664, 1.6015856537938657, 0.9466789685935577, 0.0, 13.150613802730636, 10.413468654529133, 8.007928268969328, 6.171832376823498, 10.051764902259674, 4.92899873971058, 4.181117110085521, 3.317159168158581, 4.90650034180406, 3.7493670158771177, 2.132339313535286, 0.8924419136494547, 0.0), # 118 (12.858365683722639, 9.766749433667803, 10.638539153790012, 11.217780643872292, 9.793307052983273, 4.635226620220214, 4.162765570705529, 3.512580440726085, 5.017674628187687, 2.0499591308911307, 1.5961686266765933, 0.9439128493225009, 0.0, 13.122651740421906, 10.383041342547507, 7.980843133382966, 6.149877392673391, 10.035349256375374, 4.91761261701652, 4.162765570705529, 3.310876157300153, 4.896653526491637, 3.7392602146240983, 2.1277078307580024, 0.8878863121516185, 0.0), # 119 (12.816358925895228, 9.717214721191104, 10.61541248657489, 11.187538596808764, 9.773283050494598, 4.626566008829889, 4.144639319093177, 3.5047977893829505, 5.009631638450861, 2.0427424557315677, 1.5908326255482306, 0.9411673010755515, 0.0, 13.094337208851638, 10.352840311831065, 7.954163127741153, 6.128227367194702, 10.019263276901722, 4.906716905136131, 4.144639319093177, 3.3046900063070637, 4.886641525247299, 3.729179532269589, 2.1230824973149782, 0.8833831564719186, 0.0), # 120 (12.773944958808976, 9.668179421239865, 10.592270586151553, 11.157319273304857, 9.75290056063579, 4.618018458119934, 4.126706525218187, 3.4973383413600962, 5.001730474833633, 2.035612783026304, 1.5855663342500608, 0.9384369606446594, 0.0, 13.065627796996127, 10.322806567091252, 7.927831671250303, 6.106838349078911, 10.003460949667266, 4.8962736779041345, 4.126706525218187, 3.29858461294281, 4.876450280317895, 3.719106424434953, 2.118454117230311, 0.878925401930897, 0.0), # 121 (12.731072870375797, 9.61956604234005, 10.569067472640498, 11.127067040224649, 9.732131467900551, 4.609561424959241, 4.108935359050283, 3.490175006539462, 4.993948130250281, 2.0285554623391677, 1.5803584366233656, 0.9357164648217753, 0.0, 13.036481093831679, 10.292881113039527, 7.901792183116827, 6.085666387017502, 9.987896260500563, 4.886245009155247, 4.108935359050283, 3.2925438749708866, 4.8660657339502755, 3.7090223467415506, 2.1138134945280997, 0.8745060038490956, 0.0), # 122 (12.687691748507607, 9.571297093017627, 10.54575716616221, 11.09672626443223, 9.71094765678258, 4.601172366216706, 4.091293990559188, 3.4832806948029904, 4.986261597615085, 2.021555843233986, 1.5751976165094272, 0.9330004503988493, 0.0, 13.0068546883346, 10.263004954387341, 7.875988082547136, 6.064667529701957, 9.97252319523017, 4.876592972724187, 4.091293990559188, 3.28655169015479, 4.85547382839129, 3.698908754810744, 2.109151433232442, 0.8701179175470571, 0.0), # 123 (12.643750681116316, 9.523295081798558, 10.522293686837184, 11.066241312791686, 9.689321011775569, 4.592828738761221, 4.073750589714624, 3.476628316032624, 4.97864786984232, 2.014599275274587, 1.5700725577495283, 0.9302835541678323, 0.0, 12.976706169481197, 10.233119095846153, 7.85036278874764, 6.04379782582376, 9.95729573968464, 4.8672796424456735, 4.073750589714624, 3.280591956258015, 4.844660505887784, 3.6887471042638964, 2.104458737367437, 0.8657540983453236, 0.0), # 124 (12.599198756113843, 9.475482517208812, 10.498631054785912, 11.0355565521671, 9.667223417373222, 4.584507999461682, 4.056273326486318, 3.4701907801103036, 4.971083939846263, 2.0076711080247973, 1.5649719441849508, 0.927560412920674, 0.0, 12.94599312624776, 10.203164542127412, 7.824859720924753, 6.023013324074391, 9.942167879692526, 4.858267092154425, 4.056273326486318, 3.2746485710440583, 4.833611708686611, 3.678518850722367, 2.0997262109571824, 0.8614075015644376, 0.0), # 125 (12.553985061412101, 9.427781907774351, 10.474723290128884, 11.004616349422557, 9.644626758069233, 4.5761876051869805, 4.038830370843989, 3.463940996917971, 4.963546800541195, 2.0007566910484456, 1.5598844596569765, 0.9248256634493257, 0.0, 12.91467314761061, 10.173082297942582, 7.799422298284883, 6.002270073145335, 9.92709360108239, 4.849517395685159, 4.038830370843989, 3.268705432276415, 4.822313379034616, 3.66820544980752, 2.094944658025777, 0.8570710825249411, 0.0), # 126 (12.508058684923006, 9.380115762021138, 10.450524412986589, 10.973365071422144, 9.621502918357304, 4.567845012806012, 4.021389892757366, 3.4578518763375685, 4.95601344484139, 1.993841373909359, 1.5547987880068885, 0.9220739425457369, 0.0, 12.88270382254604, 10.142813368003106, 7.773993940034442, 5.981524121728076, 9.91202688968278, 4.8409926268725965, 4.021389892757366, 3.26274643771858, 4.810751459178652, 3.6577883571407157, 2.090104882597318, 0.8527377965473764, 0.0), # 127 (12.461368714558466, 9.332406588475143, 10.425988443479525, 10.941747085029949, 9.597823782731137, 4.5594576791876715, 4.003920062196168, 3.451896328251037, 4.948460865661126, 1.986910506171365, 1.5497036130759692, 0.9192998870018588, 0.0, 12.850042740030352, 10.112298757020445, 7.748518065379845, 5.960731518514094, 9.896921731322252, 4.832654859551452, 4.003920062196168, 3.2567554851340508, 4.798911891365568, 3.6472490283433174, 2.085197688695905, 0.8484005989522859, 0.0), # 128 (12.413864238230394, 9.284576895662326, 10.401069401728181, 10.909706757110053, 9.573561235684425, 4.551003061200851, 3.9863890491301195, 3.446047262540319, 4.9408660559146815, 1.9799494373982915, 1.5445876187055003, 0.916498133609641, 0.0, 12.816647489039854, 10.08147946970605, 7.7229380935275005, 5.939848312194873, 9.881732111829363, 4.824466167556446, 3.9863890491301195, 3.250716472286322, 4.786780617842212, 3.636568919036685, 2.0802138803456365, 0.8440524450602116, 0.0), # 129 (12.365494343850713, 9.236549192108656, 10.375721307853043, 10.877188454526541, 9.548687161710866, 4.542458615714445, 3.968765023528944, 3.440277589087355, 4.933206008516334, 1.9729435171539655, 1.539439488736764, 0.9136633191610346, 0.0, 12.78247565855085, 10.050296510771378, 7.697197443683819, 5.9188305514618955, 9.866412017032667, 4.816388624722297, 3.968765023528944, 3.244613296938889, 4.774343580855433, 3.6257294848421813, 2.075144261570609, 0.8396862901916962, 0.0), # 130 (12.316208119331334, 9.188245986340096, 10.349898181974611, 10.8441365441435, 9.523173445304161, 4.533801799597346, 3.9510161553623666, 3.4345602177740875, 4.92545771638036, 1.9658780950022154, 1.5342479070110426, 0.9107900804479897, 0.0, 12.747484837539638, 10.018690884927885, 7.671239535055213, 5.897634285006645, 9.85091543276072, 4.808384304883723, 3.9510161553623666, 3.238429856855247, 4.761586722652081, 3.614712181381168, 2.0699796363949226, 0.8352950896672816, 0.0), # 131 (12.265954652584163, 9.139589786882611, 10.32355404421337, 10.810495392825016, 9.49699197095801, 4.525010069718451, 3.9331106146001082, 3.4288680584824593, 4.917598172421039, 1.9587385205068681, 1.5290015573696185, 0.9078730542624567, 0.0, 12.711632614982527, 9.986603596887022, 7.645007786848092, 5.876215561520603, 9.835196344842078, 4.800415281875443, 3.9331106146001082, 3.2321500497988938, 4.748495985479005, 3.6034984642750065, 2.0647108088426744, 0.8308717988075103, 0.0), # 132 (12.21468303152113, 9.090503102262165, 10.296642914689816, 10.776209367435175, 9.470114623166108, 4.516060882946651, 3.915016571211893, 3.4231740210944106, 4.909604369552646, 1.9515101432317519, 1.5236891236537742, 0.904906877396386, 0.0, 12.674876579855821, 9.953975651360244, 7.618445618268871, 5.854530429695254, 9.819208739105292, 4.792443629532175, 3.915016571211893, 3.2257577735333225, 4.735057311583054, 3.5920697891450595, 2.059328582937963, 0.8264093729329243, 0.0), # 133 (12.162342344054133, 9.040908441004726, 10.26911881352444, 10.741222834838059, 9.442513286422153, 4.5069316961508425, 3.896702195167445, 3.4174510154918845, 4.90145330068946, 1.9441783127406937, 1.518299289704792, 0.9018861866417278, 0.0, 12.637174321135817, 9.920748053059004, 7.5914964485239596, 5.83253493822208, 9.80290660137892, 4.784431421688638, 3.896702195167445, 3.21923692582203, 4.721256643211077, 3.5804076116126873, 2.053823762704888, 0.8219007673640661, 0.0), # 134 (12.108881678095097, 8.990728311636257, 10.24093576083773, 10.705480161897759, 9.414159845219846, 4.4975999661999175, 3.8781356564364877, 3.4116719515568206, 4.893121958745757, 1.9367283785975222, 1.5128207393639534, 0.898805618790433, 0.0, 12.59848342779883, 9.88686180669476, 7.5641036968197675, 5.810185135792565, 9.786243917491515, 4.776340732179549, 3.8781356564364877, 3.212571404428512, 4.707079922609923, 3.5684933872992537, 2.048187152167546, 0.817338937421478, 0.0), # 135 (12.05425012155593, 8.93988522268272, 10.212047776750177, 10.668925715478352, 9.385026184052883, 4.488043149962771, 3.8592851249887445, 3.4058097391711617, 4.884587336635816, 1.9291456903660635, 1.5072421564725416, 0.8956598106344515, 0.0, 12.558761488821151, 9.852257916978965, 7.536210782362707, 5.787437071098189, 9.769174673271632, 4.768133634839627, 3.8592851249887445, 3.205745107116265, 4.6925130920264415, 3.556308571826118, 2.042409555350036, 0.812716838425702, 0.0), # 136 (11.998396762348548, 8.888301682670086, 10.18240888138228, 10.631503862443932, 9.355084187414965, 4.478238704308296, 3.8401187707939393, 3.399837288216851, 4.875826427273916, 1.9214155976101461, 1.5015522248718383, 0.8924433989657341, 0.0, 12.517966093179089, 9.816877388623073, 7.507761124359191, 5.764246792830437, 9.751652854547832, 4.759772203503592, 3.8401187707939393, 3.1987419316487826, 4.6775420937074825, 3.543834620814645, 2.036481776276456, 0.8080274256972807, 0.0), # 137 (11.941270688384867, 8.835900200124316, 10.15197309485452, 10.593158969658578, 9.32430573979979, 4.4681640861053875, 3.8206047638217933, 3.393727508575828, 4.8668162235743315, 1.913523449893597, 1.4957396284031257, 0.889151020576231, 0.0, 12.476054829848946, 9.78066122633854, 7.478698142015627, 5.740570349680789, 9.733632447148663, 4.751218512006159, 3.8206047638217933, 3.1915457757895624, 4.662152869899895, 3.5310529898861933, 2.0303946189709046, 0.8032636545567561, 0.0), # 138 (11.882820987576796, 8.782603283571376, 10.120694437287398, 10.553835403986378, 9.292662725701055, 4.457796752222938, 3.800711274042032, 3.3874533101300353, 4.85753371845134, 1.9054545967802445, 1.4897930509076862, 0.8857773122578926, 0.0, 12.432985287807028, 9.743550434836816, 7.448965254538431, 5.716363790340733, 9.71506743690268, 4.742434634182049, 3.800711274042032, 3.184140537302099, 4.646331362850527, 3.517945134662127, 2.0241388874574797, 0.7984184803246707, 0.0), # 139 (11.822996747836257, 8.72833344153723, 10.088526928801404, 10.513477532291418, 9.26012702961246, 4.447114159529844, 3.780406471424378, 3.3809876027614147, 4.847955904819222, 1.8971943878339157, 1.4837011762268022, 0.8823169108026693, 0.0, 12.38871505602964, 9.70548601882936, 7.41850588113401, 5.691583163501746, 9.695911809638444, 4.733382643865981, 3.780406471424378, 3.176510113949888, 4.63006351480623, 3.5044925107638067, 2.017705385760281, 0.7934848583215663, 0.0), # 140 (11.761747057075162, 8.673013182547843, 10.055424589517022, 10.472029721437782, 9.226670536027703, 4.436093764894997, 3.7596585259385567, 3.374303296351908, 4.838059775592251, 1.8887281726184386, 1.477452688201756, 0.8787644530025115, 0.0, 12.34320172349308, 9.666408983027624, 7.38726344100878, 5.6661845178553145, 9.676119551184502, 4.724024614892672, 3.7596585259385567, 3.168638403496426, 4.613335268013851, 3.490676573812595, 2.0110849179034047, 0.7884557438679859, 0.0), # 141 (11.69902100320542, 8.616565015129181, 10.02134143955475, 10.429436338289557, 9.192265129440482, 4.424713025187291, 3.7384356075542886, 3.367373300783457, 4.827822323684707, 1.8800413006976404, 1.4710362706738296, 0.8751145756493696, 0.0, 12.296402879173653, 9.626260332143064, 7.355181353369148, 5.64012390209292, 9.655644647369414, 4.71432262109684, 3.7384356075542886, 3.160509303705208, 4.596132564720241, 3.4764787794298533, 2.0042682879109504, 0.7833240922844712, 0.0), # 142 (11.634767674138946, 8.558911447807208, 9.986231499035082, 10.385641749710825, 9.156882694344494, 4.412949397275621, 3.7167058862412983, 3.360170525938002, 4.817220542010869, 1.871119121635349, 1.4644406074843055, 0.8713619155351939, 0.0, 12.248276112047666, 9.584981070887132, 7.322203037421526, 5.6133573649060455, 9.634441084021738, 4.704238736313203, 3.7167058862412983, 3.1521067123397293, 4.578441347172247, 3.4618805832369426, 1.9972462998070164, 0.7780828588915646, 0.0), # 143 (11.56893615778766, 8.499974989107892, 9.950048788078501, 10.340590322565676, 9.12049511523344, 4.400780338028881, 3.6944375319693092, 3.3526678816974873, 4.806231423485011, 1.8619469849953916, 1.4576543824744654, 0.867501109451935, 0.0, 12.198779011091421, 9.542512203971285, 7.288271912372326, 5.585840954986173, 9.612462846970022, 4.693735034376482, 3.6944375319693092, 3.1434145271634857, 4.56024755761672, 3.446863440855226, 1.9900097576157, 0.7727249990098085, 0.0), # 144 (11.501475542063469, 8.439678147557194, 9.912747326805505, 10.294226423718191, 9.083074276601018, 4.388183304315964, 3.6715987147080456, 3.344838277943853, 4.794831961021412, 1.8525102403415963, 1.4506662794855925, 0.8635267941915434, 0.0, 12.14786916528122, 9.498794736106976, 7.253331397427962, 5.557530721024787, 9.589663922042824, 4.682773589121394, 3.6715987147080456, 3.1344166459399743, 4.541537138300509, 3.4314088079060645, 1.9825494653611013, 0.7672434679597451, 0.0), # 145 (11.432334914878291, 8.377943431681082, 9.874281135336586, 10.246494420032459, 9.044592062940927, 4.375135753005765, 3.6481576044272312, 3.336654624559041, 4.782999147534349, 1.8427942372377903, 1.4434649823589683, 0.8594336065459691, 0.0, 12.095504163593366, 9.453769672005658, 7.21732491179484, 5.52838271171337, 9.565998295068699, 4.671316474382658, 3.6481576044272312, 3.125096966432689, 4.522296031470463, 3.41549814001082, 1.9748562270673173, 0.7616312210619166, 0.0), # 146 (11.361463364144042, 8.314693350005518, 9.83460423379223, 10.19733867837256, 9.005020358746862, 4.361615140967176, 3.6240823710965873, 3.3280898314249927, 4.770709975938102, 1.8327843252478015, 1.4360391749358754, 0.855216183307163, 0.0, 12.041641595004167, 9.407378016378791, 7.180195874679377, 5.498352975743403, 9.541419951876204, 4.65932576399499, 3.6240823710965873, 3.1154393864051255, 4.502510179373431, 3.3991128927908543, 1.966920846758446, 0.7558812136368653, 0.0), # 147 (11.288809977772631, 8.24985041105647, 9.793670642292932, 10.146703565602587, 8.964331048512523, 4.347598925069094, 3.599341184685839, 3.3191168084236504, 4.757941439146947, 1.822465853935457, 1.428377541057596, 0.8508691612670749, 0.0, 11.986239048489919, 9.359560773937822, 7.141887705287981, 5.4673975618063695, 9.515882878293894, 4.646763531793111, 3.599341184685839, 3.105427803620781, 4.482165524256262, 3.38223452186753, 1.9587341284585866, 0.7499864010051337, 0.0), # 148 (11.214323843675977, 8.1833371233599, 9.751434380959186, 10.094533448586619, 8.922496016731612, 4.33306456218041, 3.573902215164709, 3.3097084654369557, 4.744670530075158, 1.8118241728645852, 1.4204687645654126, 0.8463871772176558, 0.0, 11.929254113026934, 9.310258949394212, 7.102343822827062, 5.4354725185937545, 9.489341060150316, 4.6335918516117385, 3.573902215164709, 3.09504611584315, 4.461248008365806, 3.3648444828622073, 1.950286876191837, 0.7439397384872637, 0.0), # 149 (11.137954049765991, 8.115075995441773, 9.707849469911476, 10.040772694188746, 8.879487147897825, 4.317989509170021, 3.5477336325029207, 3.29983771234685, 4.730874241637018, 1.8008446315990123, 1.412301529300607, 0.8417648679508558, 0.0, 11.870644377591507, 9.259413547459413, 7.061507646503035, 5.402533894797036, 9.461748483274036, 4.61977279728559, 3.5477336325029207, 3.084278220835729, 4.439743573948912, 3.3469242313962493, 1.9415698939822956, 0.7377341814037977, 0.0), # 150 (11.059649683954586, 8.044989535828057, 9.6628699292703, 9.985365669273047, 8.835276326504857, 4.302351222906816, 3.5208036066701984, 3.2894774590352758, 4.716529566746802, 1.789512579702568, 1.4038645191044614, 0.8369968702586252, 0.0, 11.810367431159946, 9.206965572844876, 7.019322595522306, 5.368537739107703, 9.433059133493604, 4.605268442649386, 3.5208036066701984, 3.0731080163620117, 4.417638163252429, 3.3284552230910167, 1.9325739858540603, 0.731362685075278, 0.0), # 151 (10.979359834153682, 7.973000253044715, 9.616449779156152, 9.928256740703617, 8.789835437046412, 4.286127160259694, 3.4930803076362653, 3.2786006153841747, 4.701613498318786, 1.7778133667390779, 1.3951464178182584, 0.8320778209329146, 0.0, 11.748380862708558, 9.15285603026206, 6.975732089091292, 5.333440100217232, 9.403226996637573, 4.590040861537845, 3.4930803076362653, 3.061519400185496, 4.394917718523206, 3.309418913567873, 1.9232899558312306, 0.7248182048222469, 0.0), # 152 (10.897033588275185, 7.899030655617714, 9.568543039689514, 9.86939027534453, 8.743136364016186, 4.269294778097547, 3.4645319053708437, 3.2671800912754865, 4.686103029267251, 1.7657323422723707, 1.3861359092832806, 0.8270023567656742, 0.0, 11.68464226121364, 9.097025924422415, 6.930679546416402, 5.297197026817111, 9.372206058534502, 4.574052127785681, 3.4645319053708437, 3.049496270069676, 4.371568182008093, 3.2897967584481775, 1.9137086079379029, 0.7180936959652467, 0.0), # 153 (10.81262003423102, 7.823003252073014, 9.519103730990887, 9.80871064005988, 8.695150991907875, 4.251831533289268, 3.43512656984366, 3.2551887965911552, 4.6699751525064706, 1.7532548558662742, 1.3768216773408095, 0.8217651145488547, 0.0, 11.6191092156515, 9.0394162600374, 6.884108386704048, 5.259764567598821, 9.339950305012941, 4.557264315227617, 3.43512656984366, 3.037022523778049, 4.347575495953937, 3.2695702133532945, 1.9038207461981775, 0.7111821138248196, 0.0), # 154 (10.72606825993309, 7.744840550936584, 9.468085873180756, 9.746162201713748, 8.645851205215184, 4.233714882703753, 3.404832471024433, 3.2425996412131215, 4.653206860950727, 1.7403662570846146, 1.3671924058321279, 0.8163607310744064, 0.0, 11.551739314998438, 8.97996804181847, 6.8359620291606396, 5.221098771253843, 9.306413721901453, 4.53963949769837, 3.404832471024433, 3.0240820590741087, 4.322925602607592, 3.2487207339045834, 1.8936171746361512, 0.7040764137215078, 0.0), # 155 (10.637327353293314, 7.664465060734389, 9.415443486379615, 9.68168932717022, 8.595208888431804, 4.214922283209894, 3.37361777888289, 3.2293855350233276, 4.635775147514292, 1.727051895491221, 1.357236778598518, 0.8107838431342794, 0.0, 11.48249014823076, 8.918622274477073, 6.7861838929925895, 5.181155686473662, 9.271550295028584, 4.521139749032659, 3.37361777888289, 3.0106587737213526, 4.297604444215902, 3.2272297757234076, 1.8830886972759233, 0.6967695509758537, 0.0), # 156 (10.546346402223609, 7.581799289992394, 9.361130590707957, 9.615236383293386, 8.543195926051439, 4.195431191676585, 3.3414506633887537, 3.215519387903715, 4.6176570051114485, 1.7132971206499201, 1.3469434794812618, 0.8050290875204243, 0.0, 11.411319304324769, 8.855319962724668, 6.734717397406309, 5.1398913619497595, 9.235314010222897, 4.501727143065201, 3.3414506633887537, 2.996736565483275, 4.2715979630257195, 3.205078794431129, 1.8722261181415913, 0.6892544809083996, 0.0), # 157 (10.450553324967336, 7.495248171657732, 9.302523946219415, 9.544258060733807, 8.48743569881293, 4.174003322325641, 3.3075747046495003, 3.200048222203801, 4.597442309412912, 1.698678070701901, 1.335972342259087, 0.7988866158226731, 0.0, 11.335080203181485, 8.787752774049402, 6.679861711295434, 5.096034212105701, 9.194884618825824, 4.480067511085322, 3.3075747046495003, 2.9814309445183147, 4.243717849406465, 3.1814193535779363, 1.8605047892438833, 0.6813861974234302, 0.0), # 158 (10.335201473769764, 7.395933826819331, 9.224527454803487, 9.454176016727876, 8.414178555796186, 4.143513212539135, 3.2677489343700015, 3.17754122744589, 4.566999388570334, 1.6807983479345614, 1.3223972849777657, 0.7911589610963629, 0.0, 11.235598705688274, 8.70274857205999, 6.611986424888827, 5.042395043803683, 9.133998777140668, 4.448557718424246, 3.2677489343700015, 2.9596522946708106, 4.207089277898093, 3.1513920055759597, 1.8449054909606977, 0.6723576206199392, 0.0), # 159 (10.198820932866035, 7.28304080162725, 9.125574450948537, 9.343506385929302, 8.321992122590341, 4.103212058438943, 3.221570623868649, 3.147432860557619, 4.525465106040038, 1.6594219781520132, 1.3060272186755595, 0.7817252273702489, 0.0, 11.110988852451014, 8.598977501072737, 6.530136093377798, 4.978265934456038, 9.050930212080075, 4.406406004780667, 3.221570623868649, 2.9308657560278157, 4.160996061295171, 3.114502128643102, 1.8251148901897079, 0.6620946183297501, 0.0), # 160 (10.042510876420344, 7.1573051140366015, 9.006721467228694, 9.213301128944565, 8.211833582663305, 4.053588080615757, 3.1693770122048135, 3.1101003109807053, 4.473387224599541, 1.6347303676098288, 1.2870063860732652, 0.77067287137255, 0.0, 10.962523662746737, 8.477401585098049, 6.435031930366326, 4.904191102829485, 8.946774449199083, 4.354140435372988, 3.1693770122048135, 2.8954200575826836, 4.105916791331652, 3.071100376314856, 1.801344293445739, 0.6506641012760548, 0.0), # 161 (9.8673704785969, 7.01946278200249, 8.86902503621808, 9.064612206380144, 8.08466011948299, 3.9951294996602726, 3.1115053384378664, 3.0659207681568685, 4.411313507026364, 1.6069049225635816, 1.2654790298916783, 0.7580893498314843, 0.0, 10.791476155852466, 8.338982848146326, 6.3273951494583915, 4.820714767690744, 8.822627014052728, 4.292289075419616, 3.1115053384378664, 2.8536639283287664, 4.042330059741495, 3.0215374021267154, 1.773805007243616, 0.6381329801820447, 0.0), # 162 (9.674498913559898, 6.870249823480022, 8.71354169049082, 8.898491578842531, 7.941428916517308, 3.928324536163185, 3.048292841627181, 3.015271421527823, 4.339791716098023, 1.5761270492688444, 1.2415893928515955, 0.7440621194752707, 0.0, 10.599119351045232, 8.184683314227977, 6.207946964257977, 4.728381147806532, 8.679583432196045, 4.221379990138953, 3.048292841627181, 2.8059460972594175, 3.970714458258654, 2.9661638596141775, 1.742708338098164, 0.6245681657709112, 0.0), # 163 (9.464995355473539, 6.710402256424303, 8.54132796262104, 8.71599120693821, 7.783097157234176, 3.853661410715189, 2.9800767608321266, 2.9585294605352903, 4.259369614592037, 1.5425781539811894, 1.2154817176738126, 0.7286786370321272, 0.0, 10.386726267602059, 8.015465007353399, 6.077408588369063, 4.627734461943566, 8.518739229184074, 4.141941244749407, 2.9800767608321266, 2.752615293367992, 3.891548578617088, 2.905330402312737, 1.7082655925242083, 0.6100365687658459, 0.0), # 164 (9.239958978502024, 6.5406560987904445, 8.353440385182864, 8.518163051273666, 7.610622025101502, 3.771628343906979, 2.9071943351120755, 2.8960720746209856, 4.1705949652859235, 1.5064396429561904, 1.1873002470791263, 0.7120263592302724, 0.0, 10.155569924799979, 7.832289951532995, 5.936501235395631, 4.51931892886857, 8.341189930571847, 4.05450090446938, 2.9071943351120755, 2.694020245647842, 3.805311012550751, 2.839387683757889, 1.670688077036573, 0.5946050998900405, 0.0), # 165 (9.000488956809557, 6.361747368533551, 8.150935490750417, 8.306059072455376, 7.4249607035872005, 3.682713556329251, 2.8299828035264003, 2.8282764532266285, 4.074015530957201, 1.4678929224494195, 1.157189223788332, 0.6941927427979253, 0.0, 9.906923341916015, 7.636120170777177, 5.78594611894166, 4.403678767348258, 8.148031061914402, 3.95958703451728, 2.8299828035264003, 2.630509683092322, 3.7124803517936003, 2.768686357485126, 1.6301870981500834, 0.5783406698666865, 0.0), # 166 (8.747684464560333, 6.174412083608727, 7.934869811897824, 8.080731231089835, 7.2270703761591815, 3.5874052685726983, 2.7487794051344725, 2.7555197857939366, 3.9701790743833865, 1.4271193987164503, 1.1252928905222266, 0.6752652444633036, 0.0, 9.642059538227196, 7.427917689096338, 5.626464452611132, 4.28135819614935, 7.940358148766773, 3.8577277001115116, 2.7487794051344725, 2.562432334694784, 3.6135351880795907, 2.693577077029946, 1.5869739623795647, 0.5613101894189753, 0.0), # 167 (8.482644675918554, 5.979386261971081, 7.706299881199207, 7.843231487783524, 7.017908226285359, 3.4861917012280164, 2.663921378995663, 2.6781792617646265, 3.8596333583419993, 1.3843004780128556, 1.0917554900016058, 0.6553313209546264, 0.0, 9.362251533010546, 7.20864453050089, 5.458777450008029, 4.152901434038566, 7.7192667166839986, 3.7494509664704774, 2.663921378995663, 2.490136929448583, 3.5089541131426794, 2.614410495927842, 1.5412599762398416, 0.5435805692700985, 0.0), # 168 (8.206468765048422, 5.777405921575724, 7.466282231228694, 7.594611803142927, 6.798431437433646, 3.3795610748859013, 2.5757459641693443, 2.5966320705804184, 3.7429261456105576, 1.339617566594208, 1.0567212649472661, 0.6344784290001119, 0.0, 9.0687723455431, 6.9792627190012295, 5.28360632473633, 4.018852699782624, 7.485852291221115, 3.635284898812586, 2.5757459641693443, 2.413972196347072, 3.399215718716823, 2.5315372677143095, 1.493256446245739, 0.5252187201432478, 0.0), # 169 (7.9202559061141375, 5.569207080377758, 7.215873394560408, 7.335924137774526, 6.569597193071951, 3.268001610137046, 2.4845903997148873, 2.5112554016830275, 3.620605198966578, 1.2932520707160806, 1.020334458080004, 0.6127940253279787, 0.0, 8.762894995101878, 6.740734278607764, 5.101672290400019, 3.879756212148241, 7.241210397933156, 3.5157575623562387, 2.4845903997148873, 2.3342868643836043, 3.2847985965359756, 2.4453080459248424, 1.4431746789120816, 0.5062915527616144, 0.0), # 170 (7.6251052732799005, 5.355525756332291, 6.956129903768475, 7.068220452284813, 6.3323626766681915, 3.152001527572146, 2.390791924691664, 2.4224264445141737, 3.4932182811875796, 1.2453853966340462, 0.9827393121206148, 0.5903655666664452, 0.0, 8.445892500963913, 6.494021233330896, 4.913696560603074, 3.736156189902138, 6.986436562375159, 3.3913970223198433, 2.390791924691664, 2.2514296625515327, 3.1661813383340958, 2.356073484094938, 1.391225980753695, 0.4868659778483902, 0.0), # 171 (7.322116040709912, 5.137097967394431, 6.688108291427019, 6.792552707280267, 6.087685071690277, 3.0320490477818964, 2.2946877781590462, 2.3305223885155746, 3.3613131550510804, 1.1961989506036783, 0.9440800697898953, 0.56728050974373, 0.0, 8.119037882406225, 6.24008560718103, 4.720400348949476, 3.588596851811034, 6.722626310102161, 3.2627313439218044, 2.2946877781590462, 2.165749319844212, 3.0438425358451386, 2.2641842357600894, 1.337621658285404, 0.4670089061267665, 0.0), # 172 (7.012387382568372, 4.914659731519285, 6.412865090110164, 6.509972863367375, 5.836521561606121, 2.9086323913569916, 2.196615199176405, 2.235920423128947, 3.225437583334597, 1.145874138880549, 0.9045009738086416, 0.5436263112880514, 0.0, 7.783604158705848, 5.979889424168563, 4.522504869043208, 3.437622416641646, 6.450875166669194, 3.130288592380526, 2.196615199176405, 2.077594565254994, 2.9182607808030605, 2.169990954455792, 1.282573018022033, 0.446787248319935, 0.0), # 173 (6.697018473019482, 4.6889470666619575, 6.131456832392036, 6.221532881152618, 5.579829329883635, 2.7822397788881266, 2.096911426803113, 2.1389977377960108, 3.08613932881565, 1.0945923677202316, 0.8641462668976501, 0.519490428027628, 0.0, 7.440864349139807, 5.7143947083039075, 4.32073133448825, 3.283777103160694, 6.1722786576313, 2.994596832914415, 2.096911426803113, 1.9873141277772333, 2.7899146649418176, 2.07384429371754, 1.2262913664784072, 0.42626791515108714, 0.0), # 174 (6.377108486227438, 4.460695990777558, 5.84494005084676, 5.928284721242486, 5.318565559990731, 2.653359430965997, 1.9959137000985407, 2.040131521958481, 2.943966154271756, 1.0425350433782987, 0.8231601917777163, 0.49496031669067847, 0.0, 7.092091472985131, 5.444563483597462, 4.115800958888581, 3.1276051301348957, 5.887932308543512, 2.8561841307418736, 1.9959137000985407, 1.8952567364042836, 2.6592827799953653, 1.9760949070808291, 1.1689880101693522, 0.40551781734341447, 0.0), # 175 (6.053756596356447, 4.230642521821194, 5.554371278048459, 5.631280344243462, 5.053687435395322, 2.5224795681812964, 1.8939592581220606, 1.9396989650580787, 2.7994658224804327, 0.9898835721103237, 0.781686991169637, 0.470123434005421, 0.0, 6.738558549518844, 5.17135777405963, 3.9084349558481852, 2.9696507163309707, 5.5989316449608655, 2.71557855108131, 1.8939592581220606, 1.8017711201294973, 2.526843717697661, 1.8770934480811543, 1.1108742556096918, 0.38460386562010856, 0.0), # 176 (5.7280619775707065, 3.9995226777479713, 5.260807046571258, 5.331571710762027, 4.786152139565322, 2.3900884111247205, 1.791385339933044, 1.8380772565365193, 2.6531860962191995, 0.9368193601718788, 0.7398709077942084, 0.4450672367000743, 0.0, 6.381538598017975, 4.895739603700816, 3.699354538971042, 2.8104580805156356, 5.306372192438399, 2.5733081591511273, 1.791385339933044, 1.707206007946229, 2.393076069782661, 1.7771905702540096, 1.0521614093142517, 0.3635929707043611, 0.0), # 177 (5.401123804034416, 3.7680724765129963, 4.9653038889892835, 5.030210781404673, 4.516916855968639, 2.2566741803869648, 1.6885291845908623, 1.7356435858355217, 2.505674738265573, 0.8835238138185378, 0.6978561843722264, 0.41987918150285664, 0.0, 6.022304637759553, 4.618670996531422, 3.489280921861132, 2.6505714414556127, 5.011349476531146, 2.4299010201697304, 1.6885291845908623, 1.611910128847832, 2.2584584279843196, 1.6767369271348913, 0.9930607777978567, 0.34255204331936334, 0.0), # 178 (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 179 ) passenger_allighting_rate = ( (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 0 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 1 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 2 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 3 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 4 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 5 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 6 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 7 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 8 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 9 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 10 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 11 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 12 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 13 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 14 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 15 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 16 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 17 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 18 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 19 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 20 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 21 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 22 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 23 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 24 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 25 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 26 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 27 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 28 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 29 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 30 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 31 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 32 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 33 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 34 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 35 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 36 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 37 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 38 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 39 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 40 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 41 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 42 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 43 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 44 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 45 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 46 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 47 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 48 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 49 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 50 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 51 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 52 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 53 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 54 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 55 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 56 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 57 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 58 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 59 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 60 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 61 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 62 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 63 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 64 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 65 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 66 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 67 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 68 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 69 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 70 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 71 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 72 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 73 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 74 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 75 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 76 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 77 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 78 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 79 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 80 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 81 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 82 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 83 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 84 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 85 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 86 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 87 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 88 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 89 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 90 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 91 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 92 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 93 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 94 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 95 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 96 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 97 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 98 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 99 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 100 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 101 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 102 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 103 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 104 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 105 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 106 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 107 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 108 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 109 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 110 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 111 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 112 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 113 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 114 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 115 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 116 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 117 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 118 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 119 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 120 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 121 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 122 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 123 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 124 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 125 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 126 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 127 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 128 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 129 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 130 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 131 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 132 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 133 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 134 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 135 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 136 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 137 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 138 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 139 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 140 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 141 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 142 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 143 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 144 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 145 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 146 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 147 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 148 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 149 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 150 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 151 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 152 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 153 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 154 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 155 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 156 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 157 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 158 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 159 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 160 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 161 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 162 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 163 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 164 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 165 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 166 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 167 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 168 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 169 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 170 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 171 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 172 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 173 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 174 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 175 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 176 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 177 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 178 (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 179 ) """ parameters for reproducibiliy. More information: https://numpy.org/doc/stable/reference/random/parallel.html """ #initial entropy entropy = 8991598675325360468762009371570610170 #index for seed sequence child child_seed_index = ( 1, # 0 47, # 1 )
278.913369
492
0.77175
numPassengers = 26645 passenger_arriving = ( (9, 10, 5, 5, 3, 2, 2, 3, 3, 1, 1, 0, 0, 6, 9, 0, 8, 12, 3, 4, 1, 0, 2, 2, 2, 0), (5, 10, 9, 11, 6, 2, 0, 5, 1, 1, 1, 0, 0, 11, 5, 5, 6, 6, 1, 2, 2, 1, 4, 0, 0, 0), (7, 9, 3, 3, 3, 3, 3, 5, 4, 4, 2, 0, 0, 9, 6, 5, 7, 9, 1, 5, 4, 2, 2, 2, 2, 0), (5, 10, 11, 9, 12, 3, 6, 6, 4, 1, 0, 0, 0, 6, 10, 2, 8, 8, 8, 2, 2, 3, 2, 2, 0, 0), (11, 9, 6, 8, 7, 3, 4, 5, 4, 1, 0, 0, 0, 8, 12, 3, 5, 10, 3, 0, 4, 1, 1, 0, 3, 0), (11, 9, 9, 13, 3, 3, 7, 7, 4, 2, 0, 2, 0, 7, 13, 7, 8, 9, 5, 5, 1, 2, 5, 1, 1, 0), (12, 13, 8, 8, 8, 4, 1, 4, 3, 4, 3, 2, 0, 9, 8, 7, 9, 6, 2, 7, 3, 6, 3, 0, 1, 0), (12, 8, 8, 11, 13, 3, 3, 1, 4, 1, 1, 0, 0, 12, 7, 11, 4, 9, 4, 3, 2, 3, 2, 1, 1, 0), (14, 11, 17, 10, 8, 3, 3, 2, 3, 1, 3, 0, 0, 11, 7, 9, 6, 11, 2, 7, 4, 1, 3, 1, 0, 0), (11, 10, 7, 9, 8, 8, 7, 5, 5, 0, 3, 3, 0, 17, 12, 9, 6, 10, 9, 4, 2, 3, 2, 4, 1, 0), (10, 12, 11, 10, 7, 3, 6, 3, 7, 3, 2, 2, 0, 18, 13, 12, 9, 12, 6, 2, 3, 6, 2, 3, 2, 0), (15, 11, 10, 11, 12, 7, 4, 3, 3, 1, 3, 2, 0, 10, 5, 13, 8, 12, 6, 6, 3, 1, 1, 4, 1, 0), (11, 16, 10, 11, 9, 2, 7, 4, 3, 3, 1, 2, 0, 17, 8, 9, 5, 8, 5, 5, 0, 6, 4, 1, 1, 0), (11, 17, 10, 10, 6, 7, 4, 2, 6, 1, 3, 1, 0, 14, 12, 4, 3, 5, 6, 4, 5, 3, 7, 3, 1, 0), (12, 21, 12, 12, 11, 7, 4, 4, 4, 3, 5, 0, 0, 10, 12, 6, 7, 12, 6, 7, 1, 4, 4, 0, 0, 0), (6, 12, 9, 21, 12, 3, 3, 4, 6, 2, 1, 2, 0, 9, 19, 8, 3, 6, 7, 7, 6, 8, 0, 0, 2, 0), (7, 12, 10, 13, 12, 7, 5, 4, 4, 3, 2, 3, 0, 12, 8, 4, 6, 14, 10, 4, 2, 4, 4, 1, 1, 0), (15, 15, 18, 15, 7, 9, 4, 3, 5, 6, 3, 1, 0, 12, 10, 7, 11, 10, 6, 2, 5, 7, 3, 1, 0, 0), (14, 14, 16, 17, 15, 4, 6, 4, 4, 1, 2, 1, 0, 16, 17, 7, 4, 7, 7, 9, 5, 6, 4, 2, 2, 0), (23, 16, 12, 13, 6, 6, 6, 3, 7, 0, 1, 1, 0, 17, 18, 11, 11, 15, 13, 6, 3, 5, 6, 4, 2, 0), (12, 12, 13, 13, 10, 7, 6, 4, 6, 2, 2, 1, 0, 10, 17, 13, 7, 11, 7, 5, 5, 6, 5, 4, 1, 0), (16, 18, 12, 13, 8, 6, 2, 6, 11, 2, 1, 1, 0, 7, 12, 10, 10, 16, 4, 4, 7, 4, 3, 1, 2, 0), (14, 13, 8, 11, 7, 7, 2, 3, 9, 4, 2, 0, 0, 18, 9, 6, 12, 12, 7, 3, 3, 3, 8, 0, 3, 0), (16, 9, 10, 8, 14, 9, 6, 2, 9, 3, 2, 1, 0, 16, 21, 9, 4, 5, 7, 6, 6, 1, 4, 1, 1, 0), (11, 13, 11, 10, 6, 4, 10, 6, 6, 1, 5, 1, 0, 18, 17, 16, 3, 12, 13, 8, 2, 4, 1, 4, 1, 0), (11, 16, 17, 7, 12, 5, 8, 5, 6, 2, 0, 2, 0, 10, 14, 10, 7, 20, 5, 12, 4, 3, 3, 3, 2, 0), (18, 15, 18, 8, 12, 4, 14, 2, 7, 1, 1, 1, 0, 9, 10, 10, 9, 16, 3, 4, 2, 4, 4, 1, 1, 0), (9, 9, 8, 9, 5, 7, 11, 5, 8, 2, 3, 1, 0, 10, 13, 9, 8, 12, 13, 3, 1, 3, 4, 1, 1, 0), (18, 14, 17, 16, 17, 2, 7, 7, 7, 7, 2, 2, 0, 20, 13, 12, 8, 7, 1, 4, 2, 6, 1, 2, 2, 0), (16, 16, 9, 15, 6, 4, 4, 7, 5, 3, 8, 1, 0, 12, 14, 11, 9, 11, 7, 2, 7, 2, 7, 6, 0, 0), (13, 12, 17, 14, 12, 7, 9, 4, 2, 1, 3, 0, 0, 22, 14, 9, 9, 20, 6, 9, 3, 11, 3, 0, 2, 0), (17, 9, 10, 22, 14, 6, 4, 2, 3, 5, 3, 0, 0, 19, 13, 9, 7, 15, 3, 2, 3, 5, 2, 1, 1, 0), (12, 14, 16, 12, 11, 11, 5, 5, 6, 1, 2, 1, 0, 15, 12, 13, 7, 8, 13, 4, 5, 4, 7, 1, 2, 0), (11, 16, 15, 17, 3, 7, 1, 6, 6, 1, 4, 1, 0, 18, 10, 9, 8, 14, 2, 3, 3, 5, 8, 1, 1, 0), (8, 11, 12, 15, 18, 9, 4, 6, 5, 2, 4, 0, 0, 13, 13, 5, 4, 11, 7, 6, 5, 2, 2, 1, 0, 0), (23, 16, 11, 5, 13, 3, 4, 4, 4, 3, 3, 1, 0, 13, 12, 8, 6, 9, 7, 4, 5, 6, 6, 6, 1, 0), (13, 12, 17, 16, 14, 3, 4, 4, 5, 3, 1, 0, 0, 11, 5, 6, 11, 6, 9, 6, 3, 6, 5, 1, 1, 0), (15, 9, 13, 12, 8, 5, 9, 8, 8, 1, 1, 1, 0, 22, 18, 11, 7, 14, 11, 8, 2, 5, 7, 3, 0, 0), (15, 14, 16, 13, 8, 4, 4, 4, 4, 6, 1, 1, 0, 13, 8, 16, 3, 4, 7, 7, 3, 7, 6, 2, 1, 0), (16, 17, 8, 14, 9, 4, 4, 3, 6, 0, 4, 0, 0, 17, 15, 11, 7, 13, 6, 4, 3, 5, 6, 0, 0, 0), (11, 13, 11, 7, 9, 3, 1, 6, 8, 3, 3, 0, 0, 15, 7, 6, 12, 11, 6, 5, 7, 5, 6, 3, 1, 0), (15, 11, 11, 7, 10, 5, 6, 3, 8, 5, 1, 1, 0, 9, 9, 13, 7, 9, 12, 6, 3, 3, 3, 3, 1, 0), (21, 12, 14, 12, 7, 0, 4, 5, 4, 0, 0, 2, 0, 22, 14, 7, 4, 14, 13, 6, 5, 7, 6, 1, 0, 0), (17, 16, 8, 12, 13, 1, 7, 4, 6, 1, 2, 0, 0, 15, 5, 9, 8, 13, 4, 9, 4, 1, 3, 2, 1, 0), (11, 17, 16, 10, 7, 5, 7, 4, 4, 3, 1, 4, 0, 18, 14, 8, 8, 15, 7, 5, 7, 4, 4, 0, 3, 0), (12, 14, 12, 14, 10, 4, 4, 4, 3, 2, 1, 2, 0, 13, 13, 13, 8, 6, 5, 5, 2, 4, 2, 4, 1, 0), (18, 21, 10, 16, 12, 4, 4, 6, 6, 3, 1, 0, 0, 8, 5, 7, 7, 13, 8, 5, 4, 10, 2, 0, 3, 0), (7, 10, 11, 16, 9, 8, 5, 3, 8, 0, 3, 1, 0, 20, 17, 8, 3, 7, 12, 6, 4, 7, 4, 2, 3, 0), (19, 12, 8, 5, 7, 4, 3, 3, 5, 3, 1, 1, 0, 9, 7, 12, 11, 19, 9, 8, 4, 8, 2, 3, 1, 0), (9, 7, 14, 20, 17, 2, 7, 3, 4, 3, 4, 3, 0, 13, 11, 10, 9, 13, 7, 4, 3, 3, 6, 1, 1, 0), (15, 21, 13, 12, 7, 6, 7, 4, 4, 1, 1, 2, 0, 18, 12, 11, 8, 13, 10, 7, 2, 4, 6, 3, 2, 0), (11, 9, 13, 15, 9, 2, 6, 2, 4, 7, 1, 2, 0, 21, 18, 9, 9, 14, 5, 5, 1, 5, 3, 3, 3, 0), (15, 15, 11, 10, 8, 4, 3, 5, 6, 1, 1, 1, 0, 7, 7, 12, 11, 14, 5, 5, 2, 4, 0, 1, 3, 0), (11, 11, 8, 13, 9, 4, 5, 5, 2, 3, 3, 1, 0, 13, 15, 8, 4, 16, 5, 6, 6, 5, 3, 2, 1, 0), (17, 18, 6, 15, 9, 4, 5, 6, 10, 4, 2, 2, 0, 21, 17, 14, 8, 16, 6, 4, 6, 6, 3, 1, 1, 0), (10, 12, 18, 10, 11, 7, 1, 7, 7, 3, 1, 0, 0, 14, 7, 15, 7, 7, 7, 5, 3, 1, 10, 0, 0, 0), (6, 12, 13, 14, 15, 2, 4, 4, 4, 1, 3, 1, 0, 21, 16, 11, 6, 15, 4, 7, 7, 5, 4, 4, 1, 0), (6, 16, 19, 17, 4, 4, 7, 6, 8, 2, 0, 0, 0, 19, 14, 6, 2, 13, 10, 6, 4, 4, 0, 2, 1, 0), (15, 13, 15, 19, 8, 3, 6, 6, 5, 0, 2, 2, 0, 14, 9, 8, 6, 14, 3, 9, 6, 7, 4, 4, 1, 0), (13, 4, 10, 14, 7, 4, 7, 3, 7, 6, 0, 2, 0, 10, 12, 9, 10, 11, 6, 3, 5, 7, 4, 2, 0, 0), (14, 24, 6, 17, 14, 6, 4, 1, 1, 2, 1, 3, 0, 14, 10, 12, 12, 19, 5, 9, 1, 6, 6, 1, 0, 0), (13, 20, 9, 10, 11, 7, 5, 9, 9, 1, 1, 2, 0, 16, 12, 11, 7, 16, 13, 3, 6, 6, 4, 0, 1, 0), (17, 7, 12, 12, 8, 5, 5, 4, 6, 3, 1, 0, 0, 13, 8, 10, 10, 11, 4, 4, 5, 3, 6, 4, 3, 0), (8, 14, 19, 12, 9, 5, 5, 5, 2, 0, 7, 0, 0, 12, 13, 3, 7, 10, 5, 1, 4, 3, 1, 1, 0, 0), (16, 10, 11, 8, 12, 2, 7, 8, 5, 1, 4, 0, 0, 14, 16, 8, 11, 14, 7, 5, 4, 8, 4, 1, 1, 0), (7, 13, 15, 14, 9, 2, 4, 4, 3, 1, 2, 0, 0, 16, 12, 19, 4, 13, 6, 5, 1, 11, 4, 1, 1, 0), (18, 14, 11, 11, 11, 2, 0, 5, 6, 6, 1, 1, 0, 15, 10, 7, 8, 14, 10, 2, 2, 5, 4, 0, 1, 0), (15, 17, 9, 12, 15, 4, 7, 7, 8, 0, 2, 3, 0, 17, 10, 6, 11, 9, 4, 12, 2, 1, 8, 3, 0, 0), (10, 11, 6, 11, 12, 4, 7, 4, 8, 2, 2, 1, 0, 10, 8, 9, 7, 11, 3, 8, 3, 4, 4, 5, 0, 0), (14, 10, 9, 16, 6, 4, 8, 7, 3, 1, 0, 4, 0, 12, 10, 9, 5, 12, 7, 9, 3, 4, 4, 2, 0, 0), (19, 11, 8, 18, 13, 6, 7, 4, 4, 0, 5, 1, 0, 16, 8, 10, 6, 11, 6, 6, 2, 6, 4, 1, 2, 0), (17, 6, 13, 11, 15, 9, 2, 1, 9, 4, 2, 0, 0, 11, 10, 8, 4, 7, 5, 9, 4, 6, 5, 0, 0, 0), (15, 9, 19, 17, 10, 5, 9, 6, 7, 3, 1, 0, 0, 16, 11, 12, 17, 9, 2, 8, 7, 7, 4, 2, 3, 0), (17, 11, 11, 15, 9, 6, 3, 7, 9, 2, 2, 0, 0, 16, 9, 5, 5, 16, 6, 7, 5, 2, 1, 2, 0, 0), (9, 8, 8, 14, 12, 11, 3, 2, 3, 3, 0, 0, 0, 18, 17, 13, 4, 13, 5, 5, 1, 5, 4, 4, 0, 0), (11, 13, 14, 11, 13, 7, 6, 3, 7, 3, 2, 1, 0, 14, 14, 9, 9, 7, 5, 6, 1, 8, 4, 3, 1, 0), (19, 12, 16, 10, 11, 5, 8, 3, 3, 6, 1, 0, 0, 7, 12, 10, 8, 19, 9, 7, 2, 5, 6, 4, 0, 0), (10, 8, 14, 12, 13, 5, 9, 5, 5, 1, 3, 0, 0, 18, 21, 9, 11, 6, 2, 2, 4, 8, 2, 3, 1, 0), (12, 14, 6, 17, 15, 6, 4, 4, 6, 2, 2, 0, 0, 11, 12, 9, 5, 11, 6, 4, 2, 5, 7, 0, 0, 0), (12, 8, 10, 13, 10, 6, 4, 6, 6, 3, 2, 0, 0, 16, 7, 7, 8, 5, 4, 5, 6, 9, 2, 1, 0, 0), (17, 17, 12, 9, 15, 8, 2, 3, 5, 1, 1, 1, 0, 10, 15, 13, 5, 13, 4, 6, 4, 7, 3, 1, 0, 0), (13, 11, 12, 8, 12, 6, 8, 6, 8, 2, 3, 0, 0, 19, 9, 12, 10, 12, 4, 5, 2, 5, 1, 1, 1, 0), (13, 13, 7, 15, 11, 7, 6, 6, 5, 2, 0, 7, 0, 18, 14, 7, 12, 7, 3, 3, 8, 3, 6, 3, 2, 0), (12, 6, 13, 6, 6, 5, 8, 3, 6, 4, 2, 0, 0, 17, 9, 8, 8, 12, 7, 5, 3, 7, 4, 2, 0, 0), (11, 13, 14, 16, 11, 7, 8, 7, 6, 2, 1, 1, 0, 7, 16, 8, 5, 5, 3, 6, 4, 5, 3, 2, 0, 0), (12, 14, 21, 14, 14, 7, 6, 3, 8, 4, 1, 1, 0, 9, 15, 10, 2, 13, 3, 6, 4, 6, 3, 3, 0, 0), (16, 11, 11, 11, 15, 4, 4, 4, 6, 1, 2, 1, 0, 11, 7, 8, 11, 10, 8, 3, 3, 5, 8, 2, 0, 0), (17, 7, 11, 12, 6, 3, 4, 2, 5, 2, 1, 0, 0, 11, 16, 8, 10, 7, 8, 5, 6, 7, 9, 1, 0, 0), (11, 17, 10, 9, 10, 6, 6, 2, 3, 4, 5, 0, 0, 21, 12, 9, 10, 13, 1, 2, 5, 6, 5, 2, 1, 0), (15, 9, 14, 15, 7, 4, 4, 5, 4, 1, 3, 1, 0, 18, 14, 9, 4, 9, 6, 9, 4, 5, 4, 2, 0, 0), (13, 8, 9, 11, 11, 9, 7, 2, 3, 2, 0, 0, 0, 13, 13, 7, 3, 6, 9, 4, 4, 6, 1, 3, 1, 0), (18, 13, 7, 14, 9, 4, 4, 0, 8, 2, 2, 0, 0, 14, 10, 11, 5, 7, 4, 10, 3, 2, 2, 5, 2, 0), (12, 12, 7, 13, 13, 7, 1, 8, 5, 4, 5, 1, 0, 14, 17, 8, 8, 11, 4, 5, 3, 5, 5, 2, 1, 0), (11, 5, 12, 12, 4, 4, 3, 4, 10, 3, 1, 0, 0, 13, 10, 10, 6, 21, 6, 4, 3, 2, 3, 2, 1, 0), (14, 13, 12, 13, 13, 2, 4, 7, 3, 2, 2, 1, 0, 12, 13, 4, 7, 15, 6, 5, 1, 6, 5, 0, 0, 0), (9, 19, 11, 11, 7, 5, 2, 4, 3, 4, 0, 3, 0, 12, 17, 7, 11, 11, 6, 5, 2, 3, 3, 0, 2, 0), (9, 8, 14, 10, 7, 6, 8, 7, 9, 3, 1, 2, 0, 10, 10, 9, 8, 7, 6, 3, 9, 9, 5, 5, 0, 0), (13, 10, 8, 14, 10, 4, 2, 10, 5, 2, 2, 3, 0, 11, 3, 8, 8, 12, 7, 5, 1, 8, 1, 2, 1, 0), (17, 8, 12, 12, 12, 7, 4, 2, 4, 4, 0, 2, 0, 8, 9, 5, 6, 10, 5, 3, 1, 7, 4, 4, 2, 0), (14, 10, 11, 15, 12, 4, 5, 3, 4, 1, 0, 2, 0, 14, 13, 13, 7, 9, 4, 4, 0, 2, 6, 4, 2, 0), (9, 9, 11, 10, 11, 5, 2, 5, 8, 1, 0, 5, 0, 12, 8, 12, 8, 12, 2, 7, 3, 10, 4, 4, 1, 0), (16, 11, 10, 7, 12, 3, 2, 3, 6, 1, 1, 1, 0, 13, 12, 4, 5, 10, 9, 6, 3, 6, 4, 2, 0, 0), (17, 12, 8, 14, 5, 6, 5, 5, 4, 2, 1, 0, 0, 15, 7, 5, 12, 9, 6, 2, 5, 3, 7, 3, 3, 0), (14, 12, 8, 12, 8, 5, 4, 5, 7, 2, 1, 0, 0, 20, 14, 10, 8, 6, 4, 4, 2, 8, 3, 0, 1, 0), (14, 6, 11, 14, 11, 4, 4, 5, 5, 3, 1, 1, 0, 10, 6, 14, 6, 8, 9, 4, 5, 2, 3, 1, 0, 0), (16, 11, 9, 13, 12, 5, 8, 5, 8, 2, 2, 0, 0, 17, 10, 15, 8, 10, 3, 6, 1, 6, 4, 3, 0, 0), (8, 12, 13, 10, 6, 5, 5, 2, 8, 2, 1, 1, 0, 19, 14, 7, 4, 12, 4, 3, 4, 5, 3, 1, 1, 0), (11, 12, 16, 5, 3, 9, 3, 2, 7, 2, 0, 2, 0, 15, 13, 3, 3, 8, 5, 7, 4, 6, 4, 3, 1, 0), (12, 9, 7, 9, 7, 5, 4, 3, 2, 1, 2, 3, 0, 24, 10, 11, 9, 9, 5, 6, 2, 6, 4, 1, 4, 0), (10, 15, 14, 10, 7, 7, 9, 5, 8, 2, 1, 2, 0, 17, 9, 6, 5, 9, 9, 3, 5, 9, 1, 3, 0, 0), (15, 7, 10, 8, 8, 4, 4, 4, 5, 0, 0, 0, 0, 13, 9, 13, 9, 9, 6, 5, 5, 5, 4, 0, 2, 0), (19, 13, 9, 13, 16, 2, 2, 2, 9, 4, 1, 0, 0, 8, 8, 11, 4, 10, 1, 5, 2, 6, 2, 3, 0, 0), (15, 18, 10, 14, 4, 2, 3, 2, 9, 0, 1, 0, 0, 12, 10, 6, 11, 7, 2, 2, 3, 10, 3, 2, 0, 0), (9, 7, 13, 17, 5, 2, 0, 1, 8, 1, 3, 1, 0, 18, 9, 11, 6, 9, 11, 2, 2, 5, 5, 4, 1, 0), (14, 4, 12, 10, 8, 7, 2, 2, 6, 2, 2, 0, 0, 13, 11, 9, 6, 10, 1, 6, 3, 4, 3, 2, 1, 0), (15, 7, 9, 13, 10, 3, 7, 1, 4, 0, 2, 2, 0, 11, 11, 15, 4, 12, 4, 3, 3, 4, 5, 4, 3, 0), (4, 14, 12, 13, 12, 6, 1, 6, 4, 0, 0, 1, 0, 11, 9, 9, 4, 7, 11, 3, 2, 4, 5, 1, 1, 0), (15, 9, 13, 10, 9, 6, 4, 3, 9, 5, 1, 2, 0, 10, 10, 9, 9, 12, 1, 3, 4, 5, 2, 1, 0, 0), (10, 10, 13, 17, 10, 6, 3, 3, 4, 1, 2, 2, 0, 12, 15, 10, 9, 5, 4, 3, 3, 6, 4, 0, 1, 0), (5, 8, 8, 7, 11, 3, 3, 5, 5, 2, 4, 1, 0, 10, 9, 11, 3, 11, 7, 3, 3, 3, 2, 4, 3, 0), (9, 9, 9, 9, 11, 4, 4, 2, 5, 3, 1, 0, 0, 11, 12, 7, 8, 8, 8, 3, 3, 8, 2, 4, 2, 0), (10, 15, 17, 15, 15, 5, 4, 4, 10, 3, 3, 0, 0, 17, 9, 6, 7, 4, 4, 2, 3, 4, 5, 4, 0, 0), (23, 10, 9, 8, 11, 4, 2, 3, 9, 1, 2, 0, 0, 17, 12, 6, 7, 8, 5, 2, 3, 8, 3, 3, 0, 0), (16, 5, 5, 14, 10, 3, 4, 1, 4, 3, 2, 1, 0, 17, 11, 11, 4, 9, 3, 5, 5, 3, 2, 4, 1, 0), (10, 19, 10, 15, 5, 6, 5, 2, 5, 2, 0, 0, 0, 7, 11, 6, 6, 10, 6, 2, 4, 7, 3, 0, 1, 0), (7, 8, 9, 6, 11, 4, 5, 2, 4, 3, 1, 0, 0, 13, 11, 11, 10, 11, 6, 7, 4, 5, 2, 4, 0, 0), (15, 13, 6, 12, 4, 5, 6, 2, 0, 3, 1, 1, 0, 19, 6, 6, 6, 8, 4, 4, 3, 4, 3, 1, 1, 0), (7, 8, 9, 11, 12, 4, 4, 2, 6, 2, 0, 0, 0, 8, 7, 4, 3, 9, 5, 2, 2, 6, 1, 5, 1, 0), (15, 12, 9, 9, 4, 7, 4, 2, 8, 5, 1, 2, 0, 11, 5, 9, 5, 11, 3, 4, 3, 3, 3, 4, 1, 0), (13, 9, 14, 9, 10, 5, 4, 1, 6, 1, 1, 1, 0, 14, 10, 6, 5, 10, 9, 5, 2, 1, 8, 0, 0, 0), (8, 12, 10, 11, 11, 5, 2, 6, 5, 1, 2, 1, 0, 8, 5, 5, 6, 9, 3, 7, 1, 2, 2, 3, 0, 0), (5, 6, 19, 7, 5, 2, 1, 4, 6, 1, 0, 0, 0, 9, 10, 9, 5, 8, 7, 3, 4, 3, 1, 2, 0, 0), (12, 10, 10, 5, 10, 6, 4, 7, 2, 1, 1, 0, 0, 17, 9, 5, 10, 13, 3, 2, 3, 1, 4, 7, 1, 0), (6, 10, 12, 11, 5, 4, 4, 4, 3, 1, 2, 3, 0, 9, 11, 6, 4, 14, 4, 6, 4, 10, 5, 3, 1, 0), (15, 8, 11, 16, 9, 5, 2, 3, 7, 2, 1, 1, 0, 11, 5, 12, 5, 12, 1, 5, 5, 5, 4, 2, 0, 0), (12, 11, 13, 13, 13, 2, 0, 2, 4, 2, 3, 0, 0, 10, 11, 7, 5, 15, 7, 6, 2, 3, 3, 1, 3, 0), (17, 7, 13, 15, 7, 6, 5, 2, 5, 1, 0, 1, 0, 10, 7, 8, 4, 14, 4, 4, 4, 5, 1, 2, 0, 0), (10, 11, 12, 12, 12, 5, 2, 3, 2, 2, 2, 0, 0, 18, 11, 8, 6, 12, 4, 7, 2, 6, 3, 3, 1, 0), (17, 4, 5, 12, 11, 3, 7, 2, 6, 6, 0, 1, 0, 11, 11, 6, 5, 8, 2, 3, 3, 7, 6, 3, 1, 0), (16, 12, 12, 8, 8, 6, 6, 3, 4, 1, 3, 1, 0, 13, 8, 8, 7, 9, 8, 2, 4, 4, 4, 5, 1, 0), (13, 9, 5, 14, 8, 5, 3, 5, 6, 2, 3, 1, 0, 6, 9, 7, 3, 11, 6, 5, 7, 5, 6, 3, 1, 0), (16, 6, 11, 8, 7, 6, 6, 2, 6, 0, 1, 1, 0, 14, 13, 8, 7, 10, 2, 4, 1, 5, 2, 1, 0, 0), (7, 5, 9, 11, 8, 5, 2, 6, 5, 2, 0, 2, 0, 12, 5, 4, 2, 10, 6, 5, 3, 3, 4, 0, 3, 0), (17, 14, 13, 10, 15, 4, 5, 5, 7, 0, 3, 4, 0, 13, 10, 6, 6, 15, 5, 6, 3, 2, 5, 1, 1, 0), (11, 11, 15, 13, 5, 4, 6, 6, 1, 4, 5, 0, 0, 11, 11, 7, 4, 11, 4, 4, 8, 7, 3, 1, 0, 0), (6, 13, 11, 4, 7, 6, 2, 7, 7, 1, 1, 1, 0, 9, 7, 13, 5, 8, 11, 6, 8, 5, 5, 2, 3, 0), (15, 12, 8, 10, 9, 5, 4, 5, 4, 0, 1, 1, 0, 11, 9, 13, 5, 11, 4, 5, 2, 3, 3, 1, 0, 0), (12, 12, 9, 8, 7, 4, 2, 5, 2, 1, 2, 1, 0, 16, 12, 6, 5, 9, 4, 3, 3, 4, 3, 2, 2, 0), (10, 9, 15, 12, 8, 7, 6, 6, 4, 2, 1, 2, 0, 14, 8, 9, 6, 8, 4, 4, 3, 2, 4, 2, 0, 0), (18, 13, 6, 15, 12, 4, 6, 2, 5, 4, 2, 0, 0, 10, 7, 8, 5, 8, 2, 3, 4, 7, 2, 3, 2, 0), (18, 3, 10, 10, 4, 5, 2, 3, 2, 1, 2, 0, 0, 9, 11, 4, 5, 18, 3, 7, 4, 6, 3, 2, 2, 0), (9, 5, 4, 3, 7, 5, 3, 3, 5, 0, 3, 0, 0, 10, 12, 8, 6, 10, 5, 1, 1, 1, 3, 1, 1, 0), (9, 3, 9, 12, 8, 3, 1, 1, 4, 3, 1, 0, 0, 14, 6, 3, 4, 9, 4, 3, 7, 3, 5, 0, 0, 0), (7, 5, 7, 12, 5, 6, 3, 3, 4, 3, 2, 0, 0, 10, 11, 5, 8, 9, 5, 2, 4, 7, 3, 2, 1, 0), (7, 10, 8, 8, 8, 3, 3, 0, 2, 2, 1, 1, 0, 9, 11, 10, 7, 14, 4, 4, 2, 3, 2, 1, 2, 0), (17, 6, 10, 13, 6, 1, 5, 2, 1, 0, 1, 0, 0, 14, 3, 5, 3, 7, 3, 2, 4, 5, 4, 1, 0, 0), (4, 5, 4, 8, 4, 6, 3, 4, 3, 0, 1, 1, 0, 10, 9, 5, 4, 7, 10, 3, 7, 4, 5, 1, 0, 0), (3, 7, 6, 5, 14, 6, 3, 1, 2, 2, 1, 2, 0, 13, 8, 6, 5, 11, 2, 4, 3, 3, 5, 4, 0, 0), (9, 5, 16, 8, 8, 4, 6, 4, 7, 3, 2, 0, 0, 5, 9, 1, 8, 12, 5, 4, 2, 3, 1, 4, 0, 0), (7, 6, 10, 5, 8, 5, 4, 5, 6, 1, 1, 0, 0, 6, 13, 7, 6, 7, 6, 3, 4, 4, 1, 1, 0, 0), (13, 5, 12, 5, 6, 4, 1, 5, 2, 2, 2, 0, 0, 11, 7, 6, 5, 7, 4, 1, 5, 5, 1, 1, 0, 0), (11, 6, 9, 7, 4, 2, 1, 6, 7, 2, 0, 0, 0, 6, 11, 7, 3, 6, 7, 7, 3, 6, 3, 2, 1, 0), (12, 10, 5, 6, 9, 6, 2, 5, 7, 1, 1, 0, 0, 10, 5, 10, 4, 13, 3, 1, 1, 7, 2, 3, 0, 0), (9, 6, 12, 8, 4, 3, 2, 3, 7, 2, 3, 0, 0, 12, 6, 7, 1, 5, 2, 3, 6, 3, 4, 2, 0, 0), (9, 5, 7, 9, 8, 3, 2, 3, 6, 1, 0, 0, 0, 9, 5, 4, 2, 8, 3, 3, 4, 5, 3, 1, 1, 0), (11, 8, 12, 7, 5, 4, 6, 1, 6, 3, 1, 1, 0, 6, 9, 3, 1, 4, 5, 2, 3, 2, 4, 0, 0, 0), (5, 3, 13, 9, 4, 2, 1, 4, 5, 1, 1, 0, 0, 12, 5, 5, 5, 9, 6, 2, 1, 2, 4, 1, 0, 0), (6, 7, 8, 8, 4, 3, 6, 5, 6, 1, 3, 0, 0, 13, 6, 10, 5, 5, 4, 1, 3, 5, 1, 0, 1, 0), (9, 5, 11, 11, 5, 3, 3, 3, 2, 2, 1, 2, 0, 8, 8, 6, 3, 8, 3, 3, 1, 1, 2, 1, 0, 0), (5, 5, 8, 10, 3, 2, 5, 3, 4, 0, 2, 0, 0, 13, 6, 4, 2, 6, 2, 2, 3, 0, 2, 3, 0, 0), (11, 5, 5, 6, 5, 2, 3, 3, 3, 0, 2, 1, 0, 9, 6, 9, 6, 7, 3, 3, 4, 6, 1, 2, 2, 0), (10, 4, 5, 4, 11, 4, 1, 4, 2, 1, 1, 1, 0, 7, 6, 11, 4, 13, 7, 0, 0, 2, 4, 0, 0, 0), (9, 2, 4, 6, 3, 5, 1, 1, 2, 3, 2, 0, 0, 4, 5, 4, 3, 8, 2, 2, 3, 1, 1, 3, 0, 0), (8, 6, 2, 4, 6, 3, 2, 0, 2, 1, 0, 0, 0, 8, 7, 9, 5, 4, 1, 3, 2, 3, 6, 0, 1, 0), (6, 5, 6, 6, 7, 3, 2, 0, 2, 2, 0, 0, 0, 8, 6, 3, 2, 6, 4, 0, 2, 4, 2, 0, 0, 0), (8, 3, 5, 7, 5, 1, 2, 0, 2, 2, 3, 1, 0, 6, 3, 1, 5, 5, 1, 0, 3, 2, 2, 2, 2, 0), (5, 5, 4, 7, 8, 4, 2, 1, 2, 1, 1, 2, 0, 5, 0, 2, 2, 5, 3, 1, 1, 2, 3, 0, 0, 0), (11, 4, 9, 6, 5, 3, 3, 2, 1, 2, 0, 1, 0, 8, 1, 4, 3, 5, 1, 3, 0, 3, 1, 0, 0, 0), (5, 4, 4, 3, 6, 2, 1, 3, 5, 1, 0, 2, 0, 9, 1, 1, 2, 4, 0, 2, 0, 5, 2, 2, 1, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), ) station_arriving_intensity = ( (7.029211809720476, 7.735403983570434, 7.29579652145751, 8.700534883408807, 7.776559850653457, 4.394116904852274, 5.804449861523481, 6.514446642171193, 8.52613868703521, 5.541221021731318, 5.887371229439844, 6.857081109628643, 7.117432297609708), (7.496058012827964, 8.246084971802663, 7.777485227862214, 9.275201954587263, 8.291486472463932, 4.684377017659578, 6.187256517769172, 6.943319212067992, 9.089143456866074, 5.90657296918801, 6.2763345903385845, 7.309703325140097, 7.587708306415797), (7.9614122125716245, 8.754739239247371, 8.257259199766379, 9.847582786530712, 8.804548163249642, 4.9734791603174235, 6.568545911144986, 7.370475347066188, 9.64990152962857, 6.270479285028765, 6.663752408286839, 7.760525712874277, 8.056110759493567), (8.423460910405188, 9.259348702711026, 8.733215217047796, 10.415406970544904, 9.313726346402664, 5.260276871619158, 6.946805098307138, 7.79422162049231, 10.206189225289531, 6.631495777796654, 7.0480877765583365, 8.207759958902646, 8.520781928755916), (8.880390607782374, 9.757895279000085, 9.203450059584252, 10.976404097935598, 9.81700244531509, 5.543623690358135, 7.320521135911843, 8.212864605672882, 10.75578286381579, 6.988178256034751, 7.4278037884268056, 8.64961774929667, 8.979864086115745), (9.330387806156915, 10.248360884921025, 9.666060507253526, 11.528303760008551, 10.312357883378994, 5.822373155327701, 7.688181080615314, 8.62471087593443, 11.296458765174183, 7.339082528286129, 7.801363537165986, 9.084310770127807, 9.43149950348596), (9.771639006982534, 10.728727437280302, 10.119143339933412, 12.068835548069513, 10.79777408398646, 6.09537880532121, 8.048271989073768, 9.028067004603484, 11.825993249331543, 7.682764403093862, 8.167230116049597, 9.510050707467531, 9.87383045277945), (10.202330711712957, 11.196976852884385, 10.56079533750169, 12.595729053424249, 11.271232470529577, 6.36149417913201, 8.39928091794342, 9.421239565006573, 12.342162636254702, 8.017779689001022, 8.523866618351377, 9.925049247387301, 10.304999205909127), (10.62064942180191, 11.651091048539739, 10.989113279836156, 13.1067138673785, 11.730714466400421, 6.619572815553446, 8.739694923880478, 9.802535130470215, 12.842743245910489, 8.342684194550685, 8.86973613734505, 10.327518075958585, 10.723148034787885), (11.02478163870312, 12.089051941052832, 11.402193946814586, 13.599519581238038, 12.174201494991074, 6.868468253378878, 9.068001063541168, 10.170260274320949, 13.325511398265744, 8.65603372828592, 9.20330176630435, 10.71566887925284, 11.126419211328628), (11.412913863870306, 12.508841447230123, 11.798134118314776, 14.071875786308604, 12.599674979693622, 7.107034031401651, 9.382686393581697, 10.522721569885295, 13.7882434132873, 8.956384098749801, 9.523026598503003, 11.087713343341534, 11.512955007444255), (11.783232598757209, 12.90844148387809, 12.175030574214501, 14.521512073895957, 13.005116343900148, 7.334123688415116, 9.682237970658283, 10.85822559048978, 14.228715610941991, 9.242291114485408, 9.82737372721475, 11.441863154296136, 11.880897695047656), (12.133924344817538, 13.285833967803178, 12.530980094391557, 14.946158035305858, 13.38850701100273, 7.5485907632126175, 9.965142851427137, 11.17507890946093, 14.644704311196652, 9.512310584035802, 10.114806245713309, 11.776329998188096, 12.22838954605175), (12.463175603505027, 13.639000815811869, 12.864079458723728, 15.343543261844063, 13.747828404393443, 7.749288794587514, 10.22988809254448, 11.471588100125276, 15.033985834018106, 9.764998315944066, 10.383787247272418, 12.08932556108889, 12.55357283236943), (12.769172876273403, 13.965923944710624, 13.172425447088806, 15.71139734481631, 14.081061947464386, 7.935071321333148, 10.474960750666526, 11.746059735809345, 15.39433649937319, 9.998910118753269, 10.6327798251658, 12.379061529069986, 12.85458982591359), (13.050102664576398, 14.264585271305906, 13.45411483936456, 16.047449875528383, 14.386189063607633, 8.104791882242878, 10.698847882449478, 11.99680038983966, 15.723532627228748, 10.212601801006487, 10.860247072667189, 12.64374958820284, 13.129582798597134), (13.30415146986772, 14.532966712404187, 13.707244415428796, 16.349430445286004, 14.661191176215267, 8.257304016110044, 10.900036544549568, 12.222116635542745, 16.019350537551603, 10.404629171246796, 11.06465208305032, 12.881601424558916, 13.376694022332964), (13.529505793601107, 14.769050184811926, 13.929910955159293, 16.61506864539496, 14.904049708679375, 8.391461261728, 11.077013793622996, 12.420315046245145, 16.27956655030858, 10.573548038017254, 11.24445794958892, 13.090828724209679, 13.594065769033982), (13.724352137230287, 14.970817605335585, 14.120211238433834, 16.842094067160993, 15.112746084392025, 8.506117157890104, 11.228266686325993, 12.589702195273366, 16.501956985466535, 10.717914209860952, 11.398127765556712, 13.269643173226603, 13.779840310613086), (13.88687700220898, 15.136250890781643, 14.27624204513021, 17.02823630188984, 15.285261726745313, 8.600125243389693, 11.352282279314753, 12.728584655953943, 16.68429816299229, 10.83628349532096, 11.52412462422743, 13.416256457681136, 13.932159918983176), (14.015266889990915, 15.263331957956549, 14.396100155126206, 17.171224940887296, 15.419578059131322, 8.672339057020126, 11.44754762924551, 12.835269001613405, 16.82436640285268, 10.927211702940342, 11.62091161887481, 13.528880263644748, 14.049166866057154), (14.107708302029813, 15.350042723666784, 14.477882348299607, 17.26878957545908, 15.513676504942126, 8.72161213757475, 11.512549792774463, 12.908061805578273, 16.91993802501453, 10.989254641262178, 11.686951842772585, 13.60572627718891, 14.12900342374791), (14.162387739779412, 15.394365104718803, 14.5196854045282, 17.31865979691097, 15.565538487569807, 8.746798023846914, 11.54577582655784, 12.945269641175082, 16.968789349444684, 11.02096811882954, 11.720708389194478, 13.645006184385087, 14.16981186396836), (14.182550708679697, 15.39961303155007, 14.524892455418383, 17.324903137860087, 15.578824878445637, 8.75, 11.549725603163076, 12.949291358024693, 16.974896728395063, 11.024709181527207, 11.724941252026436, 13.649856607224509, 14.175), (14.197417378247815, 15.396551851851854, 14.524040740740743, 17.324134722222226, 15.586350659060795, 8.75, 11.547555337690634, 12.943700000000002, 16.974078333333335, 11.02241086419753, 11.724474410774413, 13.648720987654322, 14.175), (14.211970122296213, 15.390517832647463, 14.522359396433473, 17.322614454732513, 15.593710923832306, 8.75, 11.543278463648836, 12.932716049382718, 16.97246141975309, 11.01788637402835, 11.723548759196907, 13.646479195244629, 14.175), (14.226207826667249, 15.381603155006863, 14.519871467764064, 17.320359619341563, 15.600905415789548, 8.75, 11.53696140563221, 12.916546913580248, 16.97006672839506, 11.011210992226795, 11.722172677391198, 13.643161957018751, 14.175), (14.240129377203292, 15.3699, 14.5166, 17.3173875, 15.607933877961901, 8.75, 11.528670588235297, 12.895400000000002, 16.966915, 11.00246, 11.720354545454546, 13.638800000000003, 14.175), (14.253733659746702, 15.355500548696845, 14.51256803840878, 17.313715380658437, 15.614796053378763, 8.75, 11.518472436052612, 12.869482716049385, 16.963026975308644, 10.9917086785551, 11.718102743484225, 13.633424051211708, 14.175), (14.26701956013985, 15.338496982167355, 14.50779862825789, 17.30936054526749, 15.62149168506951, 8.75, 11.506433373678693, 12.839002469135803, 16.95842339506173, 10.979032309099225, 11.715425651577503, 13.627064837677183, 14.175), (14.279985964225098, 15.318981481481483, 14.502314814814815, 17.30434027777778, 15.628020516063533, 8.75, 11.492619825708061, 12.804166666666665, 16.953125, 10.964506172839508, 11.71233164983165, 13.619753086419752, 14.175), (14.292631757844802, 15.297046227709194, 14.496139643347053, 17.29867186213992, 15.634382289390214, 8.75, 11.477098216735257, 12.765182716049384, 16.947152530864198, 10.948205550983083, 11.708829118343933, 13.611519524462738, 14.175), (14.304955826841338, 15.27278340192044, 14.489296159122084, 17.29237258230453, 15.640576748078935, 8.75, 11.4599349713548, 12.72225802469136, 16.940526728395064, 10.930205724737084, 11.704926437211622, 13.602394878829449, 14.175), (14.316957057057056, 15.246285185185185, 14.481807407407409, 17.28545972222222, 15.646603635159089, 8.75, 11.441196514161222, 12.675600000000001, 16.933268333333334, 10.910581975308643, 11.700631986531986, 13.59240987654321, 14.175), (14.328634334334335, 15.217643758573388, 14.473696433470508, 17.27795056584362, 15.652462693660054, 8.75, 11.420949269749054, 12.625416049382716, 16.925398086419758, 10.889409583904893, 11.695954146402293, 13.581595244627344, 14.175), (14.339986544515531, 15.186951303155007, 14.464986282578877, 17.26986239711934, 15.65815366661122, 8.75, 11.399259662712824, 12.571913580246914, 16.916936728395065, 10.866763831732968, 11.690901296919815, 13.569981710105168, 14.175), (14.35101257344301, 15.1543, 14.455700000000002, 17.2612125, 15.663676297041972, 8.75, 11.37619411764706, 12.515300000000002, 16.907905, 10.84272, 11.685481818181819, 13.557600000000003, 14.175), (14.361711306959135, 15.119782030178326, 14.445860631001374, 17.252018158436215, 15.669030327981691, 8.75, 11.351819059146292, 12.455782716049384, 16.89832364197531, 10.817353369913125, 11.679704090285574, 13.544480841335163, 14.175), (14.372081630906267, 15.083489574759948, 14.43549122085048, 17.242296656378603, 15.674215502459768, 8.75, 11.326200911805053, 12.393569135802473, 16.88821339506173, 10.790739222679472, 11.673576493328346, 13.530654961133976, 14.175), (14.382122431126781, 15.045514814814815, 14.424614814814818, 17.232065277777778, 15.679231563505585, 8.75, 11.299406100217867, 12.328866666666666, 16.877595000000003, 10.762952839506175, 11.667107407407409, 13.516153086419752, 14.175), (14.39183259346303, 15.005949931412895, 14.413254458161866, 17.221341306584364, 15.684078254148528, 8.75, 11.271501048979264, 12.261882716049385, 16.866489197530868, 10.734069501600368, 11.660305212620028, 13.501005944215823, 14.175), (14.40121100375738, 14.964887105624143, 14.401433196159124, 17.210142026748972, 15.688755317417984, 8.75, 11.242552182683774, 12.192824691358027, 16.85491672839506, 10.704164490169182, 11.653178289063476, 13.485244261545498, 14.175), (14.410256547852201, 14.922418518518521, 14.389174074074077, 17.198484722222226, 15.693262496343333, 8.75, 11.212625925925927, 12.121900000000002, 16.842898333333338, 10.673313086419753, 11.645735016835017, 13.4688987654321, 14.175), (14.418968111589852, 14.878636351165984, 14.376500137174213, 17.186386676954736, 15.697599533953966, 8.75, 11.181788703300251, 12.049316049382718, 16.83045475308642, 10.641590571559215, 11.637983776031925, 13.452000182898951, 14.175), (14.427344580812699, 14.83363278463649, 14.363434430727025, 17.173865174897124, 15.701766173279264, 8.75, 11.150106939401276, 11.975280246913583, 16.817606728395063, 10.609072226794698, 11.629932946751465, 13.434579240969367, 14.175), (14.435384841363105, 14.787500000000001, 14.350000000000001, 17.160937500000003, 15.705762157348616, 8.75, 11.11764705882353, 11.9, 16.804375, 10.575833333333335, 11.62159090909091, 13.416666666666666, 14.175), (14.443087779083434, 14.740330178326476, 14.336219890260631, 17.147620936213993, 15.709587229191404, 8.75, 11.084475486161544, 11.823682716049385, 16.790780308641974, 10.541949172382258, 11.612966043147525, 13.398293187014175, 14.175), (14.45045227981605, 14.692215500685872, 14.322117146776408, 17.133932767489714, 15.713241131837016, 8.75, 11.050658646009847, 11.746535802469136, 16.776843395061732, 10.507495025148607, 11.604066729018582, 13.37948952903521, 14.175), (14.457477229403315, 14.64324814814815, 14.307714814814817, 17.11989027777778, 15.716723608314837, 8.75, 11.016262962962964, 11.668766666666668, 16.762585, 10.472546172839506, 11.594901346801347, 13.360286419753088, 14.175), (14.464161513687602, 14.593520301783265, 14.29303593964335, 17.10551075102881, 15.720034401654251, 8.75, 10.981354861615428, 11.590582716049383, 16.748025864197533, 10.437177896662096, 11.585478276593093, 13.340714586191131, 14.175), (14.470504018511264, 14.543124142661183, 14.278103566529495, 17.090811471193415, 15.723173254884642, 8.75, 10.94600076656177, 11.512191358024692, 16.73318672839506, 10.401465477823503, 11.575805898491085, 13.32080475537266, 14.175), (14.476503629716676, 14.492151851851853, 14.262940740740742, 17.075809722222225, 15.726139911035398, 8.75, 10.910267102396515, 11.433800000000002, 16.718088333333338, 10.365484197530865, 11.565892592592595, 13.30058765432099, 14.175), (14.482159233146191, 14.440695610425243, 14.247570507544584, 17.060522788065846, 15.728934113135901, 8.75, 10.874220293714194, 11.355616049382716, 16.70275141975309, 10.329309336991313, 11.555746738994888, 13.280094010059445, 14.175), (14.487469714642183, 14.388847599451307, 14.232015912208508, 17.0449679526749, 15.731555604215542, 8.75, 10.837926765109337, 11.277846913580248, 16.687196728395065, 10.293016177411982, 11.545376717795238, 13.259354549611341, 14.175), (14.492433960047004, 14.336700000000002, 14.2163, 17.0291625, 15.734004127303704, 8.75, 10.801452941176471, 11.2007, 16.671445000000002, 10.256680000000001, 11.534790909090908, 13.2384, 14.175), (14.497050855203032, 14.284344993141291, 14.200445816186559, 17.01312371399177, 15.736279425429768, 8.75, 10.764865246510128, 11.124382716049384, 16.655516975308643, 10.220376085962506, 11.523997692979176, 13.217261088248744, 14.175), (14.501319285952622, 14.231874759945132, 14.184476406035667, 16.996868878600825, 15.738381241623124, 8.75, 10.728230105704835, 11.049102469135804, 16.63943339506173, 10.184179716506632, 11.513005449557303, 13.195968541380887, 14.175), (14.505238138138138, 14.179381481481483, 14.168414814814819, 16.98041527777778, 15.740309318913155, 8.75, 10.69161394335512, 10.975066666666669, 16.623215000000002, 10.148166172839508, 11.50182255892256, 13.174553086419753, 14.175), (14.508806297601952, 14.126957338820304, 14.152284087791497, 16.96378019547325, 15.742063400329245, 8.75, 10.655083184055517, 10.902482716049382, 16.606882530864198, 10.112410736168268, 11.490457401172218, 13.153045450388662, 14.175), (14.51202265018642, 14.07469451303155, 14.136107270233198, 16.946980915637862, 15.743643228900785, 8.75, 10.61870425240055, 10.83155802469136, 16.590456728395065, 10.076988687700048, 11.478918356403542, 13.131476360310929, 14.175), (14.51488608173391, 14.022685185185187, 14.119907407407407, 16.930034722222224, 15.745048547657152, 8.75, 10.582543572984749, 10.762500000000001, 16.573958333333337, 10.041975308641977, 11.467213804713806, 13.109876543209879, 14.175), (14.517395478086781, 13.971021536351168, 14.10370754458162, 16.912958899176957, 15.746279099627737, 8.75, 10.546667570402647, 10.695516049382718, 16.557408086419755, 10.00744588020119, 11.455352126200275, 13.088276726108827, 14.175), (14.519549725087407, 13.919795747599453, 14.087530727023323, 16.89577073045268, 15.74733462784193, 8.75, 10.51114266924877, 10.630813580246915, 16.540826728395064, 9.973475683584821, 11.44334170096022, 13.066707636031095, 14.175), (14.521347708578144, 13.869100000000001, 14.071400000000002, 16.878487500000002, 15.7482148753291, 8.75, 10.476035294117647, 10.568600000000002, 16.524235, 9.94014, 11.43119090909091, 13.045200000000001, 14.175), (14.522788314401359, 13.819026474622772, 14.05533840877915, 16.86112649176955, 15.74891958511865, 8.75, 10.44141186960381, 10.509082716049384, 16.50765364197531, 9.907514110653864, 11.41890813068961, 13.023784545038868, 14.175), (14.523870428399414, 13.769667352537724, 14.03936899862826, 16.843704989711934, 15.749448500239955, 8.75, 10.407338820301785, 10.45246913580247, 16.49110339506173, 9.875673296753543, 11.4065017458536, 13.00249199817101, 14.175), (14.524592936414676, 13.721114814814818, 14.023514814814817, 16.826240277777778, 15.749801363722403, 8.75, 10.373882570806101, 10.398966666666668, 16.474605000000004, 9.844692839506173, 11.393980134680135, 12.981353086419755, 14.175), (14.524954724289511, 13.673461042524005, 14.00779890260631, 16.808749639917696, 15.749977918595382, 8.75, 10.341109545711289, 10.348782716049385, 16.458179197530864, 9.814648020118886, 11.381351677266494, 12.960398536808412, 14.175), (14.524708260273156, 13.626548095048452, 13.99216832990398, 16.7910984366613, 15.749829137416285, 8.74983761621704, 10.308921272761506, 10.301681390032009, 16.44172298811157, 9.785468618306034, 11.368400383956526, 12.939542030659641, 14.174825210048013), (14.522398389694043, 13.578943727598569, 13.976183796296295, 16.772396920289854, 15.748474945533768, 8.748553909465022, 10.27637545388526, 10.25513827160494, 16.424516975308645, 9.756328946986201, 11.35380797448166, 12.918106562703056, 14.17344039351852), (14.517840102582454, 13.5304294437807, 13.95977580589849, 16.752521973966722, 15.74579903978052, 8.746025758268557, 10.243324188385918, 10.208733424782809, 16.40646404892547, 9.727087334247829, 11.337408441136512, 12.895991865809934, 14.170705268347055), (14.511097524900102, 13.481034236028144, 13.942950120027435, 16.731502905260335, 15.74183531025579, 8.742294131992075, 10.209782323354585, 10.162482213077277, 16.387591095107457, 9.697744503079695, 11.319262319097408, 12.873214112097802, 14.166655842764062), (14.502234782608697, 13.430787096774193, 13.9257125, 16.709369021739132, 15.736617647058825, 8.737400000000001, 10.175764705882354, 10.1164, 16.367925000000003, 9.668301176470589, 11.299430143540672, 12.849789473684211, 14.161328125), (14.491316001669949, 13.379717018452144, 13.90806870713306, 16.686149630971553, 15.730179940288872, 8.73138433165676, 10.141286183060329, 10.070502149062644, 16.347492649748517, 9.63875807740929, 11.277972449642624, 12.825734122686688, 14.154758123285324), (14.478405308045566, 13.32785299349529, 13.890024502743485, 16.661874040526033, 15.722556080045187, 8.72428809632678, 10.106361601979613, 10.024804023776863, 16.3263209304984, 9.609115928884586, 11.254949772579598, 12.801064231222776, 14.146981845850483), (14.463566827697262, 13.275224014336917, 13.871585648148148, 16.636571557971017, 15.713779956427018, 8.716152263374488, 10.0710058097313, 9.979320987654322, 16.30443672839506, 9.579375453885259, 11.23042264752791, 12.775795971410007, 14.138035300925928), (14.44686468658675, 13.22185907341033, 13.852757904663925, 16.610271490874936, 15.703885459533609, 8.707017802164305, 10.035233653406493, 9.934068404206677, 16.281866929583906, 9.549537375400092, 11.20445160966389, 12.749945515365916, 14.127954496742113), (14.428363010675731, 13.167787163148816, 13.833547033607681, 16.583003146806227, 15.692906479464213, 8.696925682060662, 9.999059980096293, 9.88906163694559, 16.258638420210335, 9.519602416417872, 11.177097194163862, 12.723529035208049, 14.116775441529496), (14.408125925925928, 13.113037275985667, 13.813958796296298, 16.554795833333333, 15.680876906318085, 8.685916872427983, 9.962499636891796, 9.844316049382718, 16.23477808641975, 9.489571299927379, 11.148419936204148, 12.696562703053933, 14.10453414351852), (14.386217558299041, 13.057638404354178, 13.793998954046641, 16.525678858024694, 15.667830630194468, 8.674032342630696, 9.925567470884102, 9.799847005029722, 16.210312814357568, 9.4594447489174, 11.118480370961072, 12.669062691021107, 14.091266610939643), (14.362702033756786, 13.001619540687642, 13.773673268175584, 16.495681528448742, 15.653801541192612, 8.661313062033226, 9.888278329164315, 9.755669867398264, 16.185269490169183, 9.429223486376719, 11.087339033610965, 12.64104517122711, 14.07700885202332), (14.337643478260873, 12.945009677419357, 13.752987500000001, 16.464833152173917, 15.638823529411765, 8.6478, 9.85064705882353, 9.711800000000002, 16.159675, 9.398908235294119, 11.055056459330146, 12.612526315789475, 14.061796875), (14.311106017773009, 12.887837806982612, 13.731947410836765, 16.433163036768654, 15.622930484951183, 8.633534125895444, 9.812688506952853, 9.668252766346594, 16.133556229995428, 9.368499718658382, 11.02169318329494, 12.583522296825743, 14.045666688100141), (14.283153778254908, 12.8301329218107, 13.710558762002744, 16.400700489801395, 15.606156297910111, 8.618556409083983, 9.774417520643375, 9.625043529949703, 16.10694006630087, 9.337998659458297, 10.987309740681672, 12.554049286453447, 14.028654299554185), (14.253850885668278, 12.77192401433692, 13.688827314814816, 16.36747481884058, 15.588534858387801, 8.602907818930042, 9.735848946986202, 9.582187654320988, 16.07985339506173, 9.307405780682645, 10.951966666666667, 12.524123456790125, 14.010795717592593), (14.223261465974833, 12.713240076994557, 13.666758830589849, 16.333515331454645, 15.5701000564835, 8.58662932479805, 9.696997633072435, 9.53970050297211, 16.05232310242341, 9.276721805320209, 10.915724496426252, 12.493760979953313, 13.992126950445819), (14.191449645136279, 12.654110102216913, 13.644359070644722, 16.298851335212028, 15.550885782296458, 8.569761896052432, 9.65787842599317, 9.497597439414724, 16.024376074531325, 9.245947456359774, 10.878643765136749, 12.462978028060553, 13.97268400634431), (14.15847954911433, 12.594563082437277, 13.621633796296296, 16.26351213768116, 15.53092592592593, 8.552346502057613, 9.618506172839506, 9.455893827160494, 15.996039197530868, 9.215083456790124, 10.840785007974482, 12.43179077322937, 13.95250289351852), (14.124415303870702, 12.534628010088941, 13.598588768861456, 16.22752704643049, 15.510254377471155, 8.534424112178023, 9.578895720702548, 9.414605029721079, 15.967339357567447, 9.184130529600042, 10.802208760115779, 12.400215387577312, 13.931619620198905), (14.089321035367092, 12.474333877605204, 13.575229749657066, 16.19092536902845, 15.488905027031391, 8.516035695778085, 9.539061916673392, 9.37374641060814, 15.938303440786468, 9.153089397778317, 10.762975556736963, 12.36826804322191, 13.910070194615912), (14.053260869565218, 12.413709677419357, 13.551562500000001, 16.153736413043482, 15.466911764705886, 8.497222222222224, 9.499019607843138, 9.333333333333334, 15.908958333333336, 9.121960784313726, 10.723145933014354, 12.335964912280703, 13.887890625), (14.016298932426789, 12.352784401964689, 13.527592781207133, 16.11598948604402, 15.444308480593882, 8.478024660874867, 9.458783641302887, 9.293381161408323, 15.879330921353455, 9.090745412195057, 10.682780424124285, 12.303322166871226, 13.865116919581618), (13.978499349913523, 12.2915870436745, 13.503326354595337, 16.0777138955985, 15.421129064794641, 8.458483981100443, 9.418368864143739, 9.253905258344766, 15.84944809099223, 9.059444004411093, 10.641939565243074, 12.270355979111017, 13.841785086591221), (13.939926247987117, 12.230146594982081, 13.478768981481483, 16.038938949275366, 15.397407407407409, 8.438641152263374, 9.37779012345679, 9.214920987654322, 15.819336728395063, 9.028057283950616, 10.600683891547051, 12.23708252111761, 13.81793113425926), (13.900643752609293, 12.168492048320722, 13.453926423182445, 15.999693954643051, 15.37317739853143, 8.418537143728091, 9.337062266333147, 9.176443712848654, 15.789023719707364, 8.996585973802416, 10.559073938212535, 12.203517965008546, 13.793591070816188), (13.860715989741754, 12.106652396123724, 13.42880444101509, 15.960008219269996, 15.34847292826596, 8.398212924859017, 9.296200139863902, 9.138488797439416, 15.758535951074533, 8.96503079695527, 10.517170240415854, 12.169678482901354, 13.768800904492457), (13.820207085346219, 12.044656630824377, 13.403408796296299, 15.91991105072464, 15.32332788671024, 8.377709465020576, 9.25521859114016, 9.101071604938273, 15.727900308641976, 8.933392476397968, 10.475033333333334, 12.135580246913582, 13.74359664351852), (13.779181165384388, 11.98253374485597, 13.377745250342937, 15.879431756575416, 15.297776163963531, 8.357067733577198, 9.21413246725302, 9.064207498856883, 15.6971436785551, 8.901671735119288, 10.432723752141296, 12.101239429162758, 13.718014296124831), (13.737702355817978, 11.9203127306518, 13.35181956447188, 15.83859964439077, 15.271851650125074, 8.336328699893311, 9.17295661529358, 9.027911842706905, 15.666292946959304, 8.86986929610802, 10.390302032016068, 12.066672201766417, 13.69208987054184), (13.695834782608697, 11.858022580645162, 13.325637500000003, 15.797444021739132, 15.24558823529412, 8.315533333333335, 9.131705882352943, 8.9922, 15.635375000000002, 8.83798588235294, 10.347828708133973, 12.031894736842107, 13.665859375000002), (13.653642571718258, 11.795692287269347, 13.29920481824417, 15.755994196188944, 15.21901980956992, 8.294722603261699, 9.090395115522204, 8.957087334247829, 15.60441672382259, 8.806022216842843, 10.305364315671335, 11.996923206507354, 13.639358817729768), (13.611189849108369, 11.733350842957654, 13.272527280521263, 15.714279475308645, 15.192180263051725, 8.273937479042829, 9.049039161892468, 8.922589208962048, 15.573445004572475, 8.773979022566504, 10.262969389804478, 11.961773782879694, 13.612624206961591), (13.568540740740744, 11.67102724014337, 13.245610648148148, 15.67232916666667, 15.165103485838781, 8.253218930041154, 9.00765286855483, 8.888720987654322, 15.542486728395062, 8.741857022512711, 10.22070446570973, 11.926462638076675, 13.585691550925928), (13.525759372577088, 11.60875047125979, 13.218460682441702, 15.630172577831457, 15.137823368030341, 8.232607925621096, 8.966251082600394, 8.855498033836307, 15.511568781435757, 8.709656939670245, 10.178630078563414, 11.891005944215824, 13.558596857853223), (13.482909870579116, 11.546549528740211, 13.191083144718794, 15.587839016371445, 15.110373799725652, 8.212145435147082, 8.924848651120257, 8.822935711019662, 15.480718049839965, 8.677379497027893, 10.13680676354185, 11.855419873414677, 13.53137613597394), (13.440056360708535, 11.484453405017922, 13.163483796296298, 15.545357789855073, 15.082788671023966, 8.19187242798354, 8.883460421205521, 8.79104938271605, 15.449961419753087, 8.64502541757444, 10.095295055821373, 11.819720597790775, 13.50406539351852), (13.39726296892706, 11.42249109252622, 13.135668398491084, 15.50275820585078, 15.055101872024531, 8.171829873494895, 8.842101239947283, 8.759854412437129, 15.41932577732053, 8.612595424298663, 10.054155490578298, 11.783924289461654, 13.476700638717421), (13.3545938211964, 11.360691583698395, 13.10764271262003, 15.460069571927, 15.027347292826596, 8.152058741045574, 8.800785954436646, 8.72936616369456, 15.388838008687703, 8.580090240189355, 10.013448602988953, 11.748047120544847, 13.449317879801098), (13.312113043478263, 11.299083870967744, 13.079412500000002, 15.417321195652177, 14.999558823529412, 8.132600000000002, 8.759529411764706, 8.699600000000002, 15.358525000000002, 8.547510588235296, 9.973234928229665, 11.712105263157897, 13.421953125000002), (13.26988476173436, 11.237696946767558, 13.050983521947876, 15.374542384594738, 14.97177035423223, 8.113494619722603, 8.718346459022568, 8.670571284865114, 15.328413637402836, 8.514857191425268, 9.933575001476758, 11.676114889418335, 13.394642382544584), (13.227973101926404, 11.176559803531132, 13.022361539780524, 15.331762446323136, 14.944015775034297, 8.094783569577809, 8.677251943301325, 8.642295381801555, 15.29853080704161, 8.482130772748057, 9.894529357906551, 11.640092171443701, 13.367421660665297), (13.186442190016104, 11.11570143369176, 12.993552314814819, 15.2890106884058, 14.91632897603486, 8.076507818930043, 8.636260711692085, 8.614787654320988, 15.26890339506173, 8.449332055192448, 9.856158532695375, 11.60405328135153, 13.340326967592594), (13.14535615196517, 11.055150829682729, 12.96456160836763, 15.246316418411165, 14.888743847333174, 8.05870833714373, 8.595387611285942, 8.588063465935072, 15.239558287608595, 8.416461761747223, 9.818523061019553, 11.568014391259355, 13.313394311556928), (13.104705913184263, 10.995038066300333, 12.935464959552897, 15.203767435488858, 14.861245952243188, 8.04141767690032, 8.554736349119478, 8.562193596292849, 15.21059793576207, 8.383626631257822, 9.781693468614014, 11.5320701111062, 13.286621461180511), (13.064073257060091, 10.935956056935751, 12.906663945030267, 15.161705189788272, 14.833550696392859, 8.024596451941862, 8.514825491774811, 8.537495763307168, 15.182466649998286, 8.351441235077896, 9.745742071958476, 11.496677040958165, 13.25978557982405), (13.023338864205595, 10.877926078156266, 12.878175705790246, 15.120118307254492, 14.805570749044042, 8.008200917498272, 8.475683510268187, 8.513963715990194, 15.155174970136306, 8.319955459183308, 9.710616315997932, 11.461852615582393, 13.232809284324528), (12.982451822532688, 10.820863593808383, 12.849945065977423, 15.078932610372966, 14.777263936937292, 7.992192428201937, 8.43724674453905, 8.491532438058591, 15.128653874918964, 8.289110701829367, 9.676248303780074, 11.427532476482286, 13.205650163658248), (12.941361219953283, 10.76468406773861, 12.82191684973638, 15.038073921629142, 14.748588086813156, 7.976532338685248, 8.399451534526854, 8.47013691322902, 15.102834343089086, 8.258848361271381, 9.642570138352598, 11.39365226516125, 13.178265806801516), (12.900016144379297, 10.709302963793455, 12.794035881211714, 14.997468063508467, 14.71950102541218, 7.9611820035805945, 8.362234220171041, 8.449712125218136, 15.07764735338951, 8.229109835764664, 9.609513922763194, 11.36014762312269, 13.150613802730636), (12.858365683722639, 10.654635745819421, 12.766246984548014, 14.95704085849639, 14.689960579474912, 7.946102777520366, 8.325531141411059, 8.430193057742605, 15.053023884563062, 8.199836523564521, 9.577011760059559, 11.326954191870009, 13.122651740421906), (12.816358925895228, 10.600597877663022, 12.738494983889867, 14.916718129078353, 14.659924575741897, 7.931256015136952, 8.289278638186355, 8.41151469451908, 15.028894915352582, 8.170969822926269, 9.544995753289383, 11.294007612906617, 13.094337208851638), (12.773944958808976, 10.547104823170763, 12.710724703381864, 14.876425697739808, 14.629350840953688, 7.9166030710627435, 8.253413050436373, 8.39361201926423, 15.0051914245009, 8.142451132105215, 9.513398005500363, 11.261243527735912, 13.065627796996127), (12.731072870375797, 10.494072046189146, 12.682880967168597, 14.836089386966199, 14.598197201850828, 7.902105299930128, 8.217870718100565, 8.376420015694709, 14.981844390750846, 8.11422184935667, 9.482150619740192, 11.228597577861303, 13.036481093831679), (12.687691748507607, 10.441415010564684, 12.65490859939465, 14.795635019242972, 14.56642148517387, 7.887724056371495, 8.182587981118376, 8.359873667527177, 14.958784792845258, 8.086223372935942, 9.451185699056563, 11.19600540478619, 13.0068546883346), (12.643750681116316, 10.389049180143882, 12.62675242420462, 14.754988417055582, 14.533981517663353, 7.873420695019235, 8.147501179429248, 8.343907958478297, 14.935943609526962, 8.058397101098347, 9.420435346497168, 11.163402650013985, 12.976706169481197), (12.599198756113843, 10.33689001877325, 12.598357265743093, 14.714075402889465, 14.500835126059833, 7.859156570505739, 8.112546652972636, 8.328457872264728, 14.913251819538791, 8.030684432099187, 9.389831665109703, 11.130724955048088, 12.94599312624776), (12.553985061412101, 10.284852990299292, 12.56966794815466, 14.672821799230077, 14.466940137103851, 7.844893037463395, 8.077660741687978, 8.31345839260313, 14.890640401623585, 8.00302676419378, 9.359306757941859, 11.097907961391908, 12.91467314761061), (12.508058684923006, 10.232853558568515, 12.540629295583907, 14.63115342856286, 14.432254377535958, 7.830591450524592, 8.042779785514732, 8.298844503210164, 14.86804033452417, 7.975365495637434, 9.32879272804133, 11.064887310548842, 12.88270382254604), (12.461368714558466, 10.18080718742743, 12.51118613217543, 14.588996113373266, 14.396735674096707, 7.816213164321722, 8.007840124392336, 8.284551187802489, 14.845382596983379, 7.947642024685458, 9.298221678455814, 11.031598644022305, 12.850042740030352), (12.413864238230394, 10.128629340722538, 12.481283282073816, 14.546275676146736, 14.360341853526638, 7.801719533487173, 7.972778098260239, 8.270513430096765, 14.822598167744045, 7.919797749593164, 9.267525712233, 10.997977603315691, 12.816647489039854), (12.365494343850713, 10.076235482300353, 12.450865569423652, 14.502917939368722, 14.3230307425663, 7.7870719126533325, 7.937530047057888, 8.256666213809652, 14.799618025549002, 7.89177406861586, 9.236636932420582, 10.963959829932413, 12.78247565855085), (12.316208119331334, 10.023541076007378, 12.419877818369534, 14.458848725524668, 14.284760167956243, 7.772231656452593, 7.902032310724733, 8.24294452265781, 14.776373149141081, 7.86351238000886, 9.205487442066255, 10.929480965375875, 12.747484837539638), (12.265954652584163, 9.970461585690122, 12.388264853056045, 14.413993857100023, 14.245487956437017, 7.757160119517344, 7.8662212292002165, 8.229283340357902, 14.752794517263117, 7.834954082027471, 9.17400934421771, 10.894476651149478, 12.711632614982527), (12.21468303152113, 9.91691247519509, 12.355971497627777, 14.368279156580234, 14.205171934749162, 7.741818656479974, 7.830033142423786, 8.215617650626585, 14.728813108657938, 7.806040572927006, 9.142134741922645, 10.85888252875663, 12.674876579855821), (12.162342344054133, 9.862809208368793, 12.322942576229327, 14.321630446450746, 14.163769929633231, 7.726168621972872, 7.79340439033489, 8.201882437180522, 14.704359902068381, 7.776713250962773, 9.109795738228751, 10.822634239700733, 12.637174321135817), (12.108881678095097, 9.808067249057736, 12.289122913005274, 14.273973549197011, 14.12123976782977, 7.710171370628429, 7.756271312872975, 8.18801268373637, 14.679365876237274, 7.746913514390087, 9.07692443618372, 10.785667425485194, 12.59848342779883), (12.05425012155593, 9.752602061108423, 12.254457332100213, 14.225234287304469, 14.077539276079325, 7.693788257079036, 7.718570249977489, 8.173943374010788, 14.65376200990745, 7.716582761464252, 9.043452938835248, 10.747917727613418, 12.558761488821151), (11.998396762348548, 9.696329108367367, 12.218890657658735, 14.175338483258576, 14.032626281122448, 7.6769806359570785, 7.6802375415878785, 8.159609491720442, 14.627479281821747, 7.685662390440583, 9.009313349231029, 10.709320787588808, 12.517966093179089), (11.941270688384867, 9.639163854681073, 12.182367713825425, 14.12421195954477, 13.986458609699687, 7.6597098618949495, 7.6412095276435865, 8.144946020581987, 14.600448670722995, 7.654093799574386, 8.974437770418753, 10.66981224691477, 12.476054829848946), (11.882820987576796, 9.581021763896047, 12.144833324744877, 14.071780538648504, 13.938994088551583, 7.641937289525037, 7.601422548084064, 8.129887944312085, 14.572601155354022, 7.621818387120976, 8.938758305446116, 10.62932774709471, 12.432985287807028), (11.822996747836257, 9.521818299858795, 12.106232314561684, 14.017970043055223, 13.890190544418692, 7.623624273479732, 7.560812942848756, 8.114370246627395, 14.543867714457667, 7.588777551335661, 8.902207057360812, 10.58780292963203, 12.38871505602964), (11.761747057075162, 9.46146892641583, 12.066509507420426, 13.962706295250376, 13.840005804041555, 7.604732168391422, 7.519317051877113, 8.09832791124458, 14.514179326776754, 7.554912690473753, 8.864716129210535, 10.545173436030137, 12.34320172349308), (11.69902100320542, 9.399889107413653, 12.0256097274657, 13.90591511771941, 13.788397694160723, 7.585222328892499, 7.476871215108577, 8.081695921880296, 14.48346697105412, 7.52016520279056, 8.826217624042977, 10.501374907792433, 12.296402879173653), (11.634767674138946, 9.336994306698774, 11.983477798842097, 13.847522332947767, 13.735324041516742, 7.56505610961535, 7.4334117724825965, 8.064409262251205, 14.451661626032607, 7.484476486541395, 8.786643644905832, 10.456342986422326, 12.248276112047666), (11.56893615778766, 9.2726999881177, 11.9400585456942, 13.787453763420901, 13.680742672850162, 7.544194865192366, 7.3888750639386185, 8.04640291607397, 14.418694270455035, 7.4477879399815645, 8.745926294846791, 10.41001331342322, 12.198779011091421), (11.501475542063469, 9.20692161551694, 11.895296792166606, 13.725635231624254, 13.624611414901528, 7.5225999502559375, 7.343197429416091, 8.027611867065247, 14.384495883064238, 7.410040961366383, 8.703997676913554, 10.36232153029852, 12.14786916528122), (11.432334914878291, 9.139574652742999, 11.849137362403903, 13.661992560043277, 13.566888094411391, 7.500232719438453, 7.2963152088544625, 8.007971098941699, 14.34899744260305, 7.37117694895116, 8.660789894153808, 10.313203278551628, 12.095504163593366), (11.361463364144042, 9.070574563642383, 11.801525080550675, 13.596451571163414, 13.507530538120294, 7.477054527372301, 7.2481647421931745, 7.987415595419982, 14.312129927814308, 7.331137300991204, 8.616235049615252, 10.262594199685955, 12.041641595004167), (11.288809977772631, 8.999836812061604, 11.752404770751518, 13.528938087470117, 13.446496572768787, 7.453026728689875, 7.198682369371678, 7.965880340216761, 14.273824317440841, 7.289863415741826, 8.570265246345576, 10.210429935204898, 11.986239048489919), (11.214323843675977, 8.927276861847163, 11.701721257151021, 13.459377931448826, 13.38374402509742, 7.42811067802356, 7.147804430329418, 7.943300317048694, 14.234011590225474, 7.247296691458339, 8.522812587392474, 10.156646126611868, 11.929254113026934), (11.137954049765991, 8.852810176845571, 11.649419363893772, 13.387696925584994, 13.319230721846738, 7.402267730005749, 7.0954672650058415, 7.91961050963244, 14.192622724911054, 7.2033785263960475, 8.473809175803641, 10.101178415410269, 11.870644377591507), (11.059649683954586, 8.776352220903336, 11.59544391512436, 13.313820892364063, 13.252914489757288, 7.375459239268828, 7.041607213340397, 7.8947459016846615, 14.149588700240406, 7.15805031881027, 8.423187114626767, 10.043962443103501, 11.810367431159946), (10.979359834153682, 8.697818457866962, 11.539739734987382, 13.237675654271488, 13.184753155569618, 7.34764656044519, 6.986160615272531, 7.8686414769220185, 14.10484049495636, 7.11125346695631, 8.37087850690955, 9.984933851194974, 11.748380862708558), (10.897033588275185, 8.61712435158296, 11.482251647627416, 13.159187033792707, 13.11470454602428, 7.318791048167222, 6.929063810741687, 7.841232219061167, 14.058309087801755, 7.062929369089481, 8.316815455699683, 9.92402828118809, 11.68464226121364), (10.81262003423102, 8.534185365897834, 11.422924477189063, 13.078280853413174, 13.042726487861813, 7.288854057067317, 6.87025313968732, 7.8124531118187726, 14.009925457519413, 7.013019423465095, 8.260930064044857, 9.861181374586256, 11.6191092156515), (10.72606825993309, 8.448916964658093, 11.361703047816906, 12.99488293561833, 12.968776807822776, 7.257796941777861, 6.809664942048866, 7.782239138911491, 13.95962058285218, 6.9614650283384565, 8.203154434992767, 9.796328772892876, 11.551739314998438), (10.637327353293314, 8.361234611710243, 11.298532183655539, 12.908919102893627, 12.892813332647707, 7.225581056931246, 6.74723555776578, 7.750525284055986, 13.907325442542877, 6.9082075819648825, 8.143420671591107, 9.729406117611353, 11.48249014823076), (10.546346402223609, 8.271053770900794, 11.233356708849547, 12.820315177724513, 12.81479388907716, 7.19216775715986, 6.6829013267775075, 7.717246530968915, 13.852971015334345, 6.853188482599679, 8.08166087688757, 9.660349050245092, 11.411319304324769), (10.450553324967336, 8.176634369081162, 11.163028735463298, 12.725677414311741, 12.731153548219398, 7.155434266843955, 6.615149409299001, 7.680115733289122, 13.792326928238738, 6.794712282807602, 8.01583405355452, 9.586639389872076, 11.335080203181485), (10.335201473769764, 8.06829144743927, 11.069432945764184, 12.605568022303835, 12.62126783369428, 7.103165507209945, 6.535497868740003, 7.626098945870136, 13.700998165711002, 6.723193391738244, 7.934383709866593, 9.493907533156353, 11.235598705688274), (10.198820932866035, 7.945135419957, 10.950689341138245, 12.458008514572404, 12.482988183885514, 7.034077814466758, 6.443141247737298, 7.553838865338286, 13.576395318120113, 6.637687912608051, 7.8361633120533565, 9.380702728442985, 11.110988852451014), (10.042510876420344, 7.8079692153126565, 10.808065760674433, 12.28440150525942, 12.317750373994958, 6.94900813819844, 6.338754024409627, 7.464240746353693, 13.420161673798626, 6.5389214704393135, 7.7220383164395905, 9.248074456470599, 10.962523662746737), (9.8673704785969, 7.657595762184535, 10.642830043461695, 12.086149608506858, 12.126990179224487, 6.848793427989039, 6.223010676875733, 7.358209843576484, 13.233940521079093, 6.427619690254325, 7.592874179350069, 9.09707219797781, 10.791476155852466), (9.674498913559898, 7.494817989250934, 10.456250028588983, 11.864655438456708, 11.912143374775964, 6.734270633422602, 6.096585683254362, 7.2366514116667755, 13.019375148294069, 6.304508197075376, 7.449536357109572, 8.928745433703247, 10.599119351045232), (9.464995355473539, 7.320438825190149, 10.249593555145248, 11.621321609250947, 11.674645735851264, 6.606276704083181, 5.960153521664253, 7.100470705284697, 12.778108843776113, 6.170312615924756, 7.292890306042875, 8.744143644385526, 10.386726267602059), (9.239958978502024, 7.135261198680485, 10.024128462219437, 11.357550735031554, 11.415933037652254, 6.465648589554821, 5.814388670224151, 6.950572979090365, 12.511784895857772, 6.02575857182476, 7.123801482474756, 8.544316310763268, 10.155569924799979), (9.000488956809557, 6.940088038400237, 9.7811225889005, 11.074745429940503, 11.137441055380801, 6.313223239421572, 5.659965607052801, 6.787863487743908, 12.222046592871603, 5.871571689797677, 6.943135342729992, 8.330312913575103, 9.906923341916015), (8.747684464560333, 6.735722273027703, 9.521843774277388, 10.774308308119782, 10.840605564238773, 6.149837603267482, 5.497558810268945, 6.613247485905448, 11.91053722315016, 5.7084775948658, 6.751757343133359, 8.103182933559642, 9.642059538227196), (8.482644675918554, 6.52296683124118, 9.247559857439049, 10.457641983711365, 10.526862339428039, 5.9763286306765995, 5.327842757991326, 6.427630228235103, 11.578900075025999, 5.5372019120514215, 6.550532940009634, 7.863975851455517, 9.362251533010546), (8.206468765048422, 6.302624641718972, 8.959538677474432, 10.126149070857236, 10.197647156150468, 5.793533271232973, 5.151491928338689, 6.231916969393004, 11.228778436831673, 5.358470266376831, 6.3403275896835956, 7.613741148001342, 9.0687723455431), (7.9202559061141375, 6.0754986331393726, 8.659048073472489, 9.781232183699368, 9.854395789607928, 5.60228847452065, 4.9691807994297745, 6.027012964039266, 10.861815596899735, 5.173008282864322, 6.122006748480023, 7.353528303935743, 8.762894995101878), (7.6251052732799005, 5.842391734180682, 8.34735588452217, 9.424293936379751, 9.498544015002288, 5.403431190123678, 4.781583849383328, 5.813823466834017, 10.47965484356274, 4.981541586536184, 5.896435872723688, 7.0843867999973416, 8.445892500963913), (7.322116040709912, 5.604106873521197, 8.025729949712423, 9.056736943040356, 9.131527607535416, 5.197798367626108, 4.5893755563180925, 5.593253732437379, 10.083939465153241, 4.784795802414712, 5.664480418739371, 6.80736611692476, 8.119037882406225), (7.012387382568372, 5.3614469798392195, 7.695438108132197, 8.679963817823166, 8.754782342409182, 4.9862269566119855, 4.39323039835281, 5.366209015509473, 9.676312750003792, 4.583496555522195, 5.427005842851849, 6.523515735456615, 7.783604158705848), (6.697018473019482, 5.115214981813045, 7.357748198870443, 8.295377174870158, 8.369743994825454, 4.76955390666536, 4.193822853606226, 5.133594570710425, 9.25841798644695, 4.3783694708809255, 5.1848776013858995, 6.233885136331535, 7.440864349139807), (6.377108486227438, 4.866213808120973, 7.013928061016112, 7.904379628323315, 7.977848339986097, 4.54861616737028, 3.9918274001970815, 4.896315652700355, 8.831898462815268, 4.170140173513194, 4.938961150666297, 5.939523800288141, 7.092091472985131), (6.053756596356447, 4.615246387441302, 6.66524553365815, 7.508373792324615, 7.580531153092983, 4.324250688310793, 3.787918516244121, 4.655277516139389, 8.3983974674413, 3.959534288441294, 4.690121947017822, 5.641481208065051, 6.738558549518844), (5.7280619775707065, 4.363115648452332, 6.3129684558855095, 7.108762281016037, 7.179228209347984, 4.097294419070949, 3.582770679866088, 4.411385415687646, 7.959558288657599, 3.7472774406875144, 4.43922544676525, 5.340806840400891, 6.381538598017975), (5.401123804034416, 4.11062451983236, 5.95836466678714, 6.7069477085395635, 6.775375283952959, 3.8685843092347962, 3.3770583691817246, 4.165544606005252, 7.51702421479672, 3.5340952552741505, 4.187137106233358, 5.038550178034279, 6.022304637759553), (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), ) passenger_arriving_acc = ( (9, 10, 5, 5, 3, 2, 2, 3, 3, 1, 1, 0, 0, 6, 9, 0, 8, 12, 3, 4, 1, 0, 2, 2, 2, 0), (14, 20, 14, 16, 9, 4, 2, 8, 4, 2, 2, 0, 0, 17, 14, 5, 14, 18, 4, 6, 3, 1, 6, 2, 2, 0), (21, 29, 17, 19, 12, 7, 5, 13, 8, 6, 4, 0, 0, 26, 20, 10, 21, 27, 5, 11, 7, 3, 8, 4, 4, 0), (26, 39, 28, 28, 24, 10, 11, 19, 12, 7, 4, 0, 0, 32, 30, 12, 29, 35, 13, 13, 9, 6, 10, 6, 4, 0), (37, 48, 34, 36, 31, 13, 15, 24, 16, 8, 4, 0, 0, 40, 42, 15, 34, 45, 16, 13, 13, 7, 11, 6, 7, 0), (48, 57, 43, 49, 34, 16, 22, 31, 20, 10, 4, 2, 0, 47, 55, 22, 42, 54, 21, 18, 14, 9, 16, 7, 8, 0), (60, 70, 51, 57, 42, 20, 23, 35, 23, 14, 7, 4, 0, 56, 63, 29, 51, 60, 23, 25, 17, 15, 19, 7, 9, 0), (72, 78, 59, 68, 55, 23, 26, 36, 27, 15, 8, 4, 0, 68, 70, 40, 55, 69, 27, 28, 19, 18, 21, 8, 10, 0), (86, 89, 76, 78, 63, 26, 29, 38, 30, 16, 11, 4, 0, 79, 77, 49, 61, 80, 29, 35, 23, 19, 24, 9, 10, 0), (97, 99, 83, 87, 71, 34, 36, 43, 35, 16, 14, 7, 0, 96, 89, 58, 67, 90, 38, 39, 25, 22, 26, 13, 11, 0), (107, 111, 94, 97, 78, 37, 42, 46, 42, 19, 16, 9, 0, 114, 102, 70, 76, 102, 44, 41, 28, 28, 28, 16, 13, 0), (122, 122, 104, 108, 90, 44, 46, 49, 45, 20, 19, 11, 0, 124, 107, 83, 84, 114, 50, 47, 31, 29, 29, 20, 14, 0), (133, 138, 114, 119, 99, 46, 53, 53, 48, 23, 20, 13, 0, 141, 115, 92, 89, 122, 55, 52, 31, 35, 33, 21, 15, 0), (144, 155, 124, 129, 105, 53, 57, 55, 54, 24, 23, 14, 0, 155, 127, 96, 92, 127, 61, 56, 36, 38, 40, 24, 16, 0), (156, 176, 136, 141, 116, 60, 61, 59, 58, 27, 28, 14, 0, 165, 139, 102, 99, 139, 67, 63, 37, 42, 44, 24, 16, 0), (162, 188, 145, 162, 128, 63, 64, 63, 64, 29, 29, 16, 0, 174, 158, 110, 102, 145, 74, 70, 43, 50, 44, 24, 18, 0), (169, 200, 155, 175, 140, 70, 69, 67, 68, 32, 31, 19, 0, 186, 166, 114, 108, 159, 84, 74, 45, 54, 48, 25, 19, 0), (184, 215, 173, 190, 147, 79, 73, 70, 73, 38, 34, 20, 0, 198, 176, 121, 119, 169, 90, 76, 50, 61, 51, 26, 19, 0), (198, 229, 189, 207, 162, 83, 79, 74, 77, 39, 36, 21, 0, 214, 193, 128, 123, 176, 97, 85, 55, 67, 55, 28, 21, 0), (221, 245, 201, 220, 168, 89, 85, 77, 84, 39, 37, 22, 0, 231, 211, 139, 134, 191, 110, 91, 58, 72, 61, 32, 23, 0), (233, 257, 214, 233, 178, 96, 91, 81, 90, 41, 39, 23, 0, 241, 228, 152, 141, 202, 117, 96, 63, 78, 66, 36, 24, 0), (249, 275, 226, 246, 186, 102, 93, 87, 101, 43, 40, 24, 0, 248, 240, 162, 151, 218, 121, 100, 70, 82, 69, 37, 26, 0), (263, 288, 234, 257, 193, 109, 95, 90, 110, 47, 42, 24, 0, 266, 249, 168, 163, 230, 128, 103, 73, 85, 77, 37, 29, 0), (279, 297, 244, 265, 207, 118, 101, 92, 119, 50, 44, 25, 0, 282, 270, 177, 167, 235, 135, 109, 79, 86, 81, 38, 30, 0), (290, 310, 255, 275, 213, 122, 111, 98, 125, 51, 49, 26, 0, 300, 287, 193, 170, 247, 148, 117, 81, 90, 82, 42, 31, 0), (301, 326, 272, 282, 225, 127, 119, 103, 131, 53, 49, 28, 0, 310, 301, 203, 177, 267, 153, 129, 85, 93, 85, 45, 33, 0), (319, 341, 290, 290, 237, 131, 133, 105, 138, 54, 50, 29, 0, 319, 311, 213, 186, 283, 156, 133, 87, 97, 89, 46, 34, 0), (328, 350, 298, 299, 242, 138, 144, 110, 146, 56, 53, 30, 0, 329, 324, 222, 194, 295, 169, 136, 88, 100, 93, 47, 35, 0), (346, 364, 315, 315, 259, 140, 151, 117, 153, 63, 55, 32, 0, 349, 337, 234, 202, 302, 170, 140, 90, 106, 94, 49, 37, 0), (362, 380, 324, 330, 265, 144, 155, 124, 158, 66, 63, 33, 0, 361, 351, 245, 211, 313, 177, 142, 97, 108, 101, 55, 37, 0), (375, 392, 341, 344, 277, 151, 164, 128, 160, 67, 66, 33, 0, 383, 365, 254, 220, 333, 183, 151, 100, 119, 104, 55, 39, 0), (392, 401, 351, 366, 291, 157, 168, 130, 163, 72, 69, 33, 0, 402, 378, 263, 227, 348, 186, 153, 103, 124, 106, 56, 40, 0), (404, 415, 367, 378, 302, 168, 173, 135, 169, 73, 71, 34, 0, 417, 390, 276, 234, 356, 199, 157, 108, 128, 113, 57, 42, 0), (415, 431, 382, 395, 305, 175, 174, 141, 175, 74, 75, 35, 0, 435, 400, 285, 242, 370, 201, 160, 111, 133, 121, 58, 43, 0), (423, 442, 394, 410, 323, 184, 178, 147, 180, 76, 79, 35, 0, 448, 413, 290, 246, 381, 208, 166, 116, 135, 123, 59, 43, 0), (446, 458, 405, 415, 336, 187, 182, 151, 184, 79, 82, 36, 0, 461, 425, 298, 252, 390, 215, 170, 121, 141, 129, 65, 44, 0), (459, 470, 422, 431, 350, 190, 186, 155, 189, 82, 83, 36, 0, 472, 430, 304, 263, 396, 224, 176, 124, 147, 134, 66, 45, 0), (474, 479, 435, 443, 358, 195, 195, 163, 197, 83, 84, 37, 0, 494, 448, 315, 270, 410, 235, 184, 126, 152, 141, 69, 45, 0), (489, 493, 451, 456, 366, 199, 199, 167, 201, 89, 85, 38, 0, 507, 456, 331, 273, 414, 242, 191, 129, 159, 147, 71, 46, 0), (505, 510, 459, 470, 375, 203, 203, 170, 207, 89, 89, 38, 0, 524, 471, 342, 280, 427, 248, 195, 132, 164, 153, 71, 46, 0), (516, 523, 470, 477, 384, 206, 204, 176, 215, 92, 92, 38, 0, 539, 478, 348, 292, 438, 254, 200, 139, 169, 159, 74, 47, 0), (531, 534, 481, 484, 394, 211, 210, 179, 223, 97, 93, 39, 0, 548, 487, 361, 299, 447, 266, 206, 142, 172, 162, 77, 48, 0), (552, 546, 495, 496, 401, 211, 214, 184, 227, 97, 93, 41, 0, 570, 501, 368, 303, 461, 279, 212, 147, 179, 168, 78, 48, 0), (569, 562, 503, 508, 414, 212, 221, 188, 233, 98, 95, 41, 0, 585, 506, 377, 311, 474, 283, 221, 151, 180, 171, 80, 49, 0), (580, 579, 519, 518, 421, 217, 228, 192, 237, 101, 96, 45, 0, 603, 520, 385, 319, 489, 290, 226, 158, 184, 175, 80, 52, 0), (592, 593, 531, 532, 431, 221, 232, 196, 240, 103, 97, 47, 0, 616, 533, 398, 327, 495, 295, 231, 160, 188, 177, 84, 53, 0), (610, 614, 541, 548, 443, 225, 236, 202, 246, 106, 98, 47, 0, 624, 538, 405, 334, 508, 303, 236, 164, 198, 179, 84, 56, 0), (617, 624, 552, 564, 452, 233, 241, 205, 254, 106, 101, 48, 0, 644, 555, 413, 337, 515, 315, 242, 168, 205, 183, 86, 59, 0), (636, 636, 560, 569, 459, 237, 244, 208, 259, 109, 102, 49, 0, 653, 562, 425, 348, 534, 324, 250, 172, 213, 185, 89, 60, 0), (645, 643, 574, 589, 476, 239, 251, 211, 263, 112, 106, 52, 0, 666, 573, 435, 357, 547, 331, 254, 175, 216, 191, 90, 61, 0), (660, 664, 587, 601, 483, 245, 258, 215, 267, 113, 107, 54, 0, 684, 585, 446, 365, 560, 341, 261, 177, 220, 197, 93, 63, 0), (671, 673, 600, 616, 492, 247, 264, 217, 271, 120, 108, 56, 0, 705, 603, 455, 374, 574, 346, 266, 178, 225, 200, 96, 66, 0), (686, 688, 611, 626, 500, 251, 267, 222, 277, 121, 109, 57, 0, 712, 610, 467, 385, 588, 351, 271, 180, 229, 200, 97, 69, 0), (697, 699, 619, 639, 509, 255, 272, 227, 279, 124, 112, 58, 0, 725, 625, 475, 389, 604, 356, 277, 186, 234, 203, 99, 70, 0), (714, 717, 625, 654, 518, 259, 277, 233, 289, 128, 114, 60, 0, 746, 642, 489, 397, 620, 362, 281, 192, 240, 206, 100, 71, 0), (724, 729, 643, 664, 529, 266, 278, 240, 296, 131, 115, 60, 0, 760, 649, 504, 404, 627, 369, 286, 195, 241, 216, 100, 71, 0), (730, 741, 656, 678, 544, 268, 282, 244, 300, 132, 118, 61, 0, 781, 665, 515, 410, 642, 373, 293, 202, 246, 220, 104, 72, 0), (736, 757, 675, 695, 548, 272, 289, 250, 308, 134, 118, 61, 0, 800, 679, 521, 412, 655, 383, 299, 206, 250, 220, 106, 73, 0), (751, 770, 690, 714, 556, 275, 295, 256, 313, 134, 120, 63, 0, 814, 688, 529, 418, 669, 386, 308, 212, 257, 224, 110, 74, 0), (764, 774, 700, 728, 563, 279, 302, 259, 320, 140, 120, 65, 0, 824, 700, 538, 428, 680, 392, 311, 217, 264, 228, 112, 74, 0), (778, 798, 706, 745, 577, 285, 306, 260, 321, 142, 121, 68, 0, 838, 710, 550, 440, 699, 397, 320, 218, 270, 234, 113, 74, 0), (791, 818, 715, 755, 588, 292, 311, 269, 330, 143, 122, 70, 0, 854, 722, 561, 447, 715, 410, 323, 224, 276, 238, 113, 75, 0), (808, 825, 727, 767, 596, 297, 316, 273, 336, 146, 123, 70, 0, 867, 730, 571, 457, 726, 414, 327, 229, 279, 244, 117, 78, 0), (816, 839, 746, 779, 605, 302, 321, 278, 338, 146, 130, 70, 0, 879, 743, 574, 464, 736, 419, 328, 233, 282, 245, 118, 78, 0), (832, 849, 757, 787, 617, 304, 328, 286, 343, 147, 134, 70, 0, 893, 759, 582, 475, 750, 426, 333, 237, 290, 249, 119, 79, 0), (839, 862, 772, 801, 626, 306, 332, 290, 346, 148, 136, 70, 0, 909, 771, 601, 479, 763, 432, 338, 238, 301, 253, 120, 80, 0), (857, 876, 783, 812, 637, 308, 332, 295, 352, 154, 137, 71, 0, 924, 781, 608, 487, 777, 442, 340, 240, 306, 257, 120, 81, 0), (872, 893, 792, 824, 652, 312, 339, 302, 360, 154, 139, 74, 0, 941, 791, 614, 498, 786, 446, 352, 242, 307, 265, 123, 81, 0), (882, 904, 798, 835, 664, 316, 346, 306, 368, 156, 141, 75, 0, 951, 799, 623, 505, 797, 449, 360, 245, 311, 269, 128, 81, 0), (896, 914, 807, 851, 670, 320, 354, 313, 371, 157, 141, 79, 0, 963, 809, 632, 510, 809, 456, 369, 248, 315, 273, 130, 81, 0), (915, 925, 815, 869, 683, 326, 361, 317, 375, 157, 146, 80, 0, 979, 817, 642, 516, 820, 462, 375, 250, 321, 277, 131, 83, 0), (932, 931, 828, 880, 698, 335, 363, 318, 384, 161, 148, 80, 0, 990, 827, 650, 520, 827, 467, 384, 254, 327, 282, 131, 83, 0), (947, 940, 847, 897, 708, 340, 372, 324, 391, 164, 149, 80, 0, 1006, 838, 662, 537, 836, 469, 392, 261, 334, 286, 133, 86, 0), (964, 951, 858, 912, 717, 346, 375, 331, 400, 166, 151, 80, 0, 1022, 847, 667, 542, 852, 475, 399, 266, 336, 287, 135, 86, 0), (973, 959, 866, 926, 729, 357, 378, 333, 403, 169, 151, 80, 0, 1040, 864, 680, 546, 865, 480, 404, 267, 341, 291, 139, 86, 0), (984, 972, 880, 937, 742, 364, 384, 336, 410, 172, 153, 81, 0, 1054, 878, 689, 555, 872, 485, 410, 268, 349, 295, 142, 87, 0), (1003, 984, 896, 947, 753, 369, 392, 339, 413, 178, 154, 81, 0, 1061, 890, 699, 563, 891, 494, 417, 270, 354, 301, 146, 87, 0), (1013, 992, 910, 959, 766, 374, 401, 344, 418, 179, 157, 81, 0, 1079, 911, 708, 574, 897, 496, 419, 274, 362, 303, 149, 88, 0), (1025, 1006, 916, 976, 781, 380, 405, 348, 424, 181, 159, 81, 0, 1090, 923, 717, 579, 908, 502, 423, 276, 367, 310, 149, 88, 0), (1037, 1014, 926, 989, 791, 386, 409, 354, 430, 184, 161, 81, 0, 1106, 930, 724, 587, 913, 506, 428, 282, 376, 312, 150, 88, 0), (1054, 1031, 938, 998, 806, 394, 411, 357, 435, 185, 162, 82, 0, 1116, 945, 737, 592, 926, 510, 434, 286, 383, 315, 151, 88, 0), (1067, 1042, 950, 1006, 818, 400, 419, 363, 443, 187, 165, 82, 0, 1135, 954, 749, 602, 938, 514, 439, 288, 388, 316, 152, 89, 0), (1080, 1055, 957, 1021, 829, 407, 425, 369, 448, 189, 165, 89, 0, 1153, 968, 756, 614, 945, 517, 442, 296, 391, 322, 155, 91, 0), (1092, 1061, 970, 1027, 835, 412, 433, 372, 454, 193, 167, 89, 0, 1170, 977, 764, 622, 957, 524, 447, 299, 398, 326, 157, 91, 0), (1103, 1074, 984, 1043, 846, 419, 441, 379, 460, 195, 168, 90, 0, 1177, 993, 772, 627, 962, 527, 453, 303, 403, 329, 159, 91, 0), (1115, 1088, 1005, 1057, 860, 426, 447, 382, 468, 199, 169, 91, 0, 1186, 1008, 782, 629, 975, 530, 459, 307, 409, 332, 162, 91, 0), (1131, 1099, 1016, 1068, 875, 430, 451, 386, 474, 200, 171, 92, 0, 1197, 1015, 790, 640, 985, 538, 462, 310, 414, 340, 164, 91, 0), (1148, 1106, 1027, 1080, 881, 433, 455, 388, 479, 202, 172, 92, 0, 1208, 1031, 798, 650, 992, 546, 467, 316, 421, 349, 165, 91, 0), (1159, 1123, 1037, 1089, 891, 439, 461, 390, 482, 206, 177, 92, 0, 1229, 1043, 807, 660, 1005, 547, 469, 321, 427, 354, 167, 92, 0), (1174, 1132, 1051, 1104, 898, 443, 465, 395, 486, 207, 180, 93, 0, 1247, 1057, 816, 664, 1014, 553, 478, 325, 432, 358, 169, 92, 0), (1187, 1140, 1060, 1115, 909, 452, 472, 397, 489, 209, 180, 93, 0, 1260, 1070, 823, 667, 1020, 562, 482, 329, 438, 359, 172, 93, 0), (1205, 1153, 1067, 1129, 918, 456, 476, 397, 497, 211, 182, 93, 0, 1274, 1080, 834, 672, 1027, 566, 492, 332, 440, 361, 177, 95, 0), (1217, 1165, 1074, 1142, 931, 463, 477, 405, 502, 215, 187, 94, 0, 1288, 1097, 842, 680, 1038, 570, 497, 335, 445, 366, 179, 96, 0), (1228, 1170, 1086, 1154, 935, 467, 480, 409, 512, 218, 188, 94, 0, 1301, 1107, 852, 686, 1059, 576, 501, 338, 447, 369, 181, 97, 0), (1242, 1183, 1098, 1167, 948, 469, 484, 416, 515, 220, 190, 95, 0, 1313, 1120, 856, 693, 1074, 582, 506, 339, 453, 374, 181, 97, 0), (1251, 1202, 1109, 1178, 955, 474, 486, 420, 518, 224, 190, 98, 0, 1325, 1137, 863, 704, 1085, 588, 511, 341, 456, 377, 181, 99, 0), (1260, 1210, 1123, 1188, 962, 480, 494, 427, 527, 227, 191, 100, 0, 1335, 1147, 872, 712, 1092, 594, 514, 350, 465, 382, 186, 99, 0), (1273, 1220, 1131, 1202, 972, 484, 496, 437, 532, 229, 193, 103, 0, 1346, 1150, 880, 720, 1104, 601, 519, 351, 473, 383, 188, 100, 0), (1290, 1228, 1143, 1214, 984, 491, 500, 439, 536, 233, 193, 105, 0, 1354, 1159, 885, 726, 1114, 606, 522, 352, 480, 387, 192, 102, 0), (1304, 1238, 1154, 1229, 996, 495, 505, 442, 540, 234, 193, 107, 0, 1368, 1172, 898, 733, 1123, 610, 526, 352, 482, 393, 196, 104, 0), (1313, 1247, 1165, 1239, 1007, 500, 507, 447, 548, 235, 193, 112, 0, 1380, 1180, 910, 741, 1135, 612, 533, 355, 492, 397, 200, 105, 0), (1329, 1258, 1175, 1246, 1019, 503, 509, 450, 554, 236, 194, 113, 0, 1393, 1192, 914, 746, 1145, 621, 539, 358, 498, 401, 202, 105, 0), (1346, 1270, 1183, 1260, 1024, 509, 514, 455, 558, 238, 195, 113, 0, 1408, 1199, 919, 758, 1154, 627, 541, 363, 501, 408, 205, 108, 0), (1360, 1282, 1191, 1272, 1032, 514, 518, 460, 565, 240, 196, 113, 0, 1428, 1213, 929, 766, 1160, 631, 545, 365, 509, 411, 205, 109, 0), (1374, 1288, 1202, 1286, 1043, 518, 522, 465, 570, 243, 197, 114, 0, 1438, 1219, 943, 772, 1168, 640, 549, 370, 511, 414, 206, 109, 0), (1390, 1299, 1211, 1299, 1055, 523, 530, 470, 578, 245, 199, 114, 0, 1455, 1229, 958, 780, 1178, 643, 555, 371, 517, 418, 209, 109, 0), (1398, 1311, 1224, 1309, 1061, 528, 535, 472, 586, 247, 200, 115, 0, 1474, 1243, 965, 784, 1190, 647, 558, 375, 522, 421, 210, 110, 0), (1409, 1323, 1240, 1314, 1064, 537, 538, 474, 593, 249, 200, 117, 0, 1489, 1256, 968, 787, 1198, 652, 565, 379, 528, 425, 213, 111, 0), (1421, 1332, 1247, 1323, 1071, 542, 542, 477, 595, 250, 202, 120, 0, 1513, 1266, 979, 796, 1207, 657, 571, 381, 534, 429, 214, 115, 0), (1431, 1347, 1261, 1333, 1078, 549, 551, 482, 603, 252, 203, 122, 0, 1530, 1275, 985, 801, 1216, 666, 574, 386, 543, 430, 217, 115, 0), (1446, 1354, 1271, 1341, 1086, 553, 555, 486, 608, 252, 203, 122, 0, 1543, 1284, 998, 810, 1225, 672, 579, 391, 548, 434, 217, 117, 0), (1465, 1367, 1280, 1354, 1102, 555, 557, 488, 617, 256, 204, 122, 0, 1551, 1292, 1009, 814, 1235, 673, 584, 393, 554, 436, 220, 117, 0), (1480, 1385, 1290, 1368, 1106, 557, 560, 490, 626, 256, 205, 122, 0, 1563, 1302, 1015, 825, 1242, 675, 586, 396, 564, 439, 222, 117, 0), (1489, 1392, 1303, 1385, 1111, 559, 560, 491, 634, 257, 208, 123, 0, 1581, 1311, 1026, 831, 1251, 686, 588, 398, 569, 444, 226, 118, 0), (1503, 1396, 1315, 1395, 1119, 566, 562, 493, 640, 259, 210, 123, 0, 1594, 1322, 1035, 837, 1261, 687, 594, 401, 573, 447, 228, 119, 0), (1518, 1403, 1324, 1408, 1129, 569, 569, 494, 644, 259, 212, 125, 0, 1605, 1333, 1050, 841, 1273, 691, 597, 404, 577, 452, 232, 122, 0), (1522, 1417, 1336, 1421, 1141, 575, 570, 500, 648, 259, 212, 126, 0, 1616, 1342, 1059, 845, 1280, 702, 600, 406, 581, 457, 233, 123, 0), (1537, 1426, 1349, 1431, 1150, 581, 574, 503, 657, 264, 213, 128, 0, 1626, 1352, 1068, 854, 1292, 703, 603, 410, 586, 459, 234, 123, 0), (1547, 1436, 1362, 1448, 1160, 587, 577, 506, 661, 265, 215, 130, 0, 1638, 1367, 1078, 863, 1297, 707, 606, 413, 592, 463, 234, 124, 0), (1552, 1444, 1370, 1455, 1171, 590, 580, 511, 666, 267, 219, 131, 0, 1648, 1376, 1089, 866, 1308, 714, 609, 416, 595, 465, 238, 127, 0), (1561, 1453, 1379, 1464, 1182, 594, 584, 513, 671, 270, 220, 131, 0, 1659, 1388, 1096, 874, 1316, 722, 612, 419, 603, 467, 242, 129, 0), (1571, 1468, 1396, 1479, 1197, 599, 588, 517, 681, 273, 223, 131, 0, 1676, 1397, 1102, 881, 1320, 726, 614, 422, 607, 472, 246, 129, 0), (1594, 1478, 1405, 1487, 1208, 603, 590, 520, 690, 274, 225, 131, 0, 1693, 1409, 1108, 888, 1328, 731, 616, 425, 615, 475, 249, 129, 0), (1610, 1483, 1410, 1501, 1218, 606, 594, 521, 694, 277, 227, 132, 0, 1710, 1420, 1119, 892, 1337, 734, 621, 430, 618, 477, 253, 130, 0), (1620, 1502, 1420, 1516, 1223, 612, 599, 523, 699, 279, 227, 132, 0, 1717, 1431, 1125, 898, 1347, 740, 623, 434, 625, 480, 253, 131, 0), (1627, 1510, 1429, 1522, 1234, 616, 604, 525, 703, 282, 228, 132, 0, 1730, 1442, 1136, 908, 1358, 746, 630, 438, 630, 482, 257, 131, 0), (1642, 1523, 1435, 1534, 1238, 621, 610, 527, 703, 285, 229, 133, 0, 1749, 1448, 1142, 914, 1366, 750, 634, 441, 634, 485, 258, 132, 0), (1649, 1531, 1444, 1545, 1250, 625, 614, 529, 709, 287, 229, 133, 0, 1757, 1455, 1146, 917, 1375, 755, 636, 443, 640, 486, 263, 133, 0), (1664, 1543, 1453, 1554, 1254, 632, 618, 531, 717, 292, 230, 135, 0, 1768, 1460, 1155, 922, 1386, 758, 640, 446, 643, 489, 267, 134, 0), (1677, 1552, 1467, 1563, 1264, 637, 622, 532, 723, 293, 231, 136, 0, 1782, 1470, 1161, 927, 1396, 767, 645, 448, 644, 497, 267, 134, 0), (1685, 1564, 1477, 1574, 1275, 642, 624, 538, 728, 294, 233, 137, 0, 1790, 1475, 1166, 933, 1405, 770, 652, 449, 646, 499, 270, 134, 0), (1690, 1570, 1496, 1581, 1280, 644, 625, 542, 734, 295, 233, 137, 0, 1799, 1485, 1175, 938, 1413, 777, 655, 453, 649, 500, 272, 134, 0), (1702, 1580, 1506, 1586, 1290, 650, 629, 549, 736, 296, 234, 137, 0, 1816, 1494, 1180, 948, 1426, 780, 657, 456, 650, 504, 279, 135, 0), (1708, 1590, 1518, 1597, 1295, 654, 633, 553, 739, 297, 236, 140, 0, 1825, 1505, 1186, 952, 1440, 784, 663, 460, 660, 509, 282, 136, 0), (1723, 1598, 1529, 1613, 1304, 659, 635, 556, 746, 299, 237, 141, 0, 1836, 1510, 1198, 957, 1452, 785, 668, 465, 665, 513, 284, 136, 0), (1735, 1609, 1542, 1626, 1317, 661, 635, 558, 750, 301, 240, 141, 0, 1846, 1521, 1205, 962, 1467, 792, 674, 467, 668, 516, 285, 139, 0), (1752, 1616, 1555, 1641, 1324, 667, 640, 560, 755, 302, 240, 142, 0, 1856, 1528, 1213, 966, 1481, 796, 678, 471, 673, 517, 287, 139, 0), (1762, 1627, 1567, 1653, 1336, 672, 642, 563, 757, 304, 242, 142, 0, 1874, 1539, 1221, 972, 1493, 800, 685, 473, 679, 520, 290, 140, 0), (1779, 1631, 1572, 1665, 1347, 675, 649, 565, 763, 310, 242, 143, 0, 1885, 1550, 1227, 977, 1501, 802, 688, 476, 686, 526, 293, 141, 0), (1795, 1643, 1584, 1673, 1355, 681, 655, 568, 767, 311, 245, 144, 0, 1898, 1558, 1235, 984, 1510, 810, 690, 480, 690, 530, 298, 142, 0), (1808, 1652, 1589, 1687, 1363, 686, 658, 573, 773, 313, 248, 145, 0, 1904, 1567, 1242, 987, 1521, 816, 695, 487, 695, 536, 301, 143, 0), (1824, 1658, 1600, 1695, 1370, 692, 664, 575, 779, 313, 249, 146, 0, 1918, 1580, 1250, 994, 1531, 818, 699, 488, 700, 538, 302, 143, 0), (1831, 1663, 1609, 1706, 1378, 697, 666, 581, 784, 315, 249, 148, 0, 1930, 1585, 1254, 996, 1541, 824, 704, 491, 703, 542, 302, 146, 0), (1848, 1677, 1622, 1716, 1393, 701, 671, 586, 791, 315, 252, 152, 0, 1943, 1595, 1260, 1002, 1556, 829, 710, 494, 705, 547, 303, 147, 0), (1859, 1688, 1637, 1729, 1398, 705, 677, 592, 792, 319, 257, 152, 0, 1954, 1606, 1267, 1006, 1567, 833, 714, 502, 712, 550, 304, 147, 0), (1865, 1701, 1648, 1733, 1405, 711, 679, 599, 799, 320, 258, 153, 0, 1963, 1613, 1280, 1011, 1575, 844, 720, 510, 717, 555, 306, 150, 0), (1880, 1713, 1656, 1743, 1414, 716, 683, 604, 803, 320, 259, 154, 0, 1974, 1622, 1293, 1016, 1586, 848, 725, 512, 720, 558, 307, 150, 0), (1892, 1725, 1665, 1751, 1421, 720, 685, 609, 805, 321, 261, 155, 0, 1990, 1634, 1299, 1021, 1595, 852, 728, 515, 724, 561, 309, 152, 0), (1902, 1734, 1680, 1763, 1429, 727, 691, 615, 809, 323, 262, 157, 0, 2004, 1642, 1308, 1027, 1603, 856, 732, 518, 726, 565, 311, 152, 0), (1920, 1747, 1686, 1778, 1441, 731, 697, 617, 814, 327, 264, 157, 0, 2014, 1649, 1316, 1032, 1611, 858, 735, 522, 733, 567, 314, 154, 0), (1938, 1750, 1696, 1788, 1445, 736, 699, 620, 816, 328, 266, 157, 0, 2023, 1660, 1320, 1037, 1629, 861, 742, 526, 739, 570, 316, 156, 0), (1947, 1755, 1700, 1791, 1452, 741, 702, 623, 821, 328, 269, 157, 0, 2033, 1672, 1328, 1043, 1639, 866, 743, 527, 740, 573, 317, 157, 0), (1956, 1758, 1709, 1803, 1460, 744, 703, 624, 825, 331, 270, 157, 0, 2047, 1678, 1331, 1047, 1648, 870, 746, 534, 743, 578, 317, 157, 0), (1963, 1763, 1716, 1815, 1465, 750, 706, 627, 829, 334, 272, 157, 0, 2057, 1689, 1336, 1055, 1657, 875, 748, 538, 750, 581, 319, 158, 0), (1970, 1773, 1724, 1823, 1473, 753, 709, 627, 831, 336, 273, 158, 0, 2066, 1700, 1346, 1062, 1671, 879, 752, 540, 753, 583, 320, 160, 0), (1987, 1779, 1734, 1836, 1479, 754, 714, 629, 832, 336, 274, 158, 0, 2080, 1703, 1351, 1065, 1678, 882, 754, 544, 758, 587, 321, 160, 0), (1991, 1784, 1738, 1844, 1483, 760, 717, 633, 835, 336, 275, 159, 0, 2090, 1712, 1356, 1069, 1685, 892, 757, 551, 762, 592, 322, 160, 0), (1994, 1791, 1744, 1849, 1497, 766, 720, 634, 837, 338, 276, 161, 0, 2103, 1720, 1362, 1074, 1696, 894, 761, 554, 765, 597, 326, 160, 0), (2003, 1796, 1760, 1857, 1505, 770, 726, 638, 844, 341, 278, 161, 0, 2108, 1729, 1363, 1082, 1708, 899, 765, 556, 768, 598, 330, 160, 0), (2010, 1802, 1770, 1862, 1513, 775, 730, 643, 850, 342, 279, 161, 0, 2114, 1742, 1370, 1088, 1715, 905, 768, 560, 772, 599, 331, 160, 0), (2023, 1807, 1782, 1867, 1519, 779, 731, 648, 852, 344, 281, 161, 0, 2125, 1749, 1376, 1093, 1722, 909, 769, 565, 777, 600, 332, 160, 0), (2034, 1813, 1791, 1874, 1523, 781, 732, 654, 859, 346, 281, 161, 0, 2131, 1760, 1383, 1096, 1728, 916, 776, 568, 783, 603, 334, 161, 0), (2046, 1823, 1796, 1880, 1532, 787, 734, 659, 866, 347, 282, 161, 0, 2141, 1765, 1393, 1100, 1741, 919, 777, 569, 790, 605, 337, 161, 0), (2055, 1829, 1808, 1888, 1536, 790, 736, 662, 873, 349, 285, 161, 0, 2153, 1771, 1400, 1101, 1746, 921, 780, 575, 793, 609, 339, 161, 0), (2064, 1834, 1815, 1897, 1544, 793, 738, 665, 879, 350, 285, 161, 0, 2162, 1776, 1404, 1103, 1754, 924, 783, 579, 798, 612, 340, 162, 0), (2075, 1842, 1827, 1904, 1549, 797, 744, 666, 885, 353, 286, 162, 0, 2168, 1785, 1407, 1104, 1758, 929, 785, 582, 800, 616, 340, 162, 0), (2080, 1845, 1840, 1913, 1553, 799, 745, 670, 890, 354, 287, 162, 0, 2180, 1790, 1412, 1109, 1767, 935, 787, 583, 802, 620, 341, 162, 0), (2086, 1852, 1848, 1921, 1557, 802, 751, 675, 896, 355, 290, 162, 0, 2193, 1796, 1422, 1114, 1772, 939, 788, 586, 807, 621, 341, 163, 0), (2095, 1857, 1859, 1932, 1562, 805, 754, 678, 898, 357, 291, 164, 0, 2201, 1804, 1428, 1117, 1780, 942, 791, 587, 808, 623, 342, 163, 0), (2100, 1862, 1867, 1942, 1565, 807, 759, 681, 902, 357, 293, 164, 0, 2214, 1810, 1432, 1119, 1786, 944, 793, 590, 808, 625, 345, 163, 0), (2111, 1867, 1872, 1948, 1570, 809, 762, 684, 905, 357, 295, 165, 0, 2223, 1816, 1441, 1125, 1793, 947, 796, 594, 814, 626, 347, 165, 0), (2121, 1871, 1877, 1952, 1581, 813, 763, 688, 907, 358, 296, 166, 0, 2230, 1822, 1452, 1129, 1806, 954, 796, 594, 816, 630, 347, 165, 0), (2130, 1873, 1881, 1958, 1584, 818, 764, 689, 909, 361, 298, 166, 0, 2234, 1827, 1456, 1132, 1814, 956, 798, 597, 817, 631, 350, 165, 0), (2138, 1879, 1883, 1962, 1590, 821, 766, 689, 911, 362, 298, 166, 0, 2242, 1834, 1465, 1137, 1818, 957, 801, 599, 820, 637, 350, 166, 0), (2144, 1884, 1889, 1968, 1597, 824, 768, 689, 913, 364, 298, 166, 0, 2250, 1840, 1468, 1139, 1824, 961, 801, 601, 824, 639, 350, 166, 0), (2152, 1887, 1894, 1975, 1602, 825, 770, 689, 915, 366, 301, 167, 0, 2256, 1843, 1469, 1144, 1829, 962, 801, 604, 826, 641, 352, 168, 0), (2157, 1892, 1898, 1982, 1610, 829, 772, 690, 917, 367, 302, 169, 0, 2261, 1843, 1471, 1146, 1834, 965, 802, 605, 828, 644, 352, 168, 0), (2168, 1896, 1907, 1988, 1615, 832, 775, 692, 918, 369, 302, 170, 0, 2269, 1844, 1475, 1149, 1839, 966, 805, 605, 831, 645, 352, 168, 0), (2173, 1900, 1911, 1991, 1621, 834, 776, 695, 923, 370, 302, 172, 0, 2278, 1845, 1476, 1151, 1843, 966, 807, 605, 836, 647, 354, 169, 0), (2173, 1900, 1911, 1991, 1621, 834, 776, 695, 923, 370, 302, 172, 0, 2278, 1845, 1476, 1151, 1843, 966, 807, 605, 836, 647, 354, 169, 0), ) passenger_arriving_rate = ( (7.029211809720476, 7.090786984939564, 6.079830434547925, 6.525401162556605, 5.184373233768971, 2.563234861163827, 2.9022249307617405, 2.7143527675713304, 2.8420462290117365, 1.3853052554328298, 0.9812285382399741, 0.571423425802387, 0.0, 7.117432297609708, 6.285657683826256, 4.90614269119987, 4.155915766298489, 5.684092458023473, 3.8000938745998627, 2.9022249307617405, 1.8308820436884476, 2.5921866168844856, 2.175133720852202, 1.2159660869095852, 0.6446169986308695, 0.0), (7.496058012827964, 7.558911224152441, 6.4812376898851785, 6.956401465940448, 5.527657648309288, 2.7325532603014207, 3.093628258884586, 2.893049671694997, 3.0297144856220246, 1.4766432422970026, 1.0460557650564308, 0.6091419437616749, 0.0, 7.587708306415797, 6.700561381378422, 5.230278825282154, 4.429929726891007, 6.059428971244049, 4.050269540372995, 3.093628258884586, 1.9518237573581576, 2.763828824154644, 2.3188004886468163, 1.2962475379770357, 0.687173747650222, 0.0), (7.9614122125716245, 8.025177635976757, 6.881049333138649, 7.385687089898034, 5.869698775499761, 2.9011961768518306, 3.284272955572493, 3.071031394610912, 3.2166338432095234, 1.5676198212571917, 1.1106254013811399, 0.6467104760728565, 0.0, 8.056110759493567, 7.113815236801421, 5.553127006905699, 4.702859463771574, 6.433267686419047, 4.2994439524552766, 3.284272955572493, 2.0722829834655934, 2.9348493877498805, 2.4618956966326784, 1.37620986662773, 0.7295616032706144, 0.0), (8.423460910405188, 8.487736310818441, 7.277679347539831, 7.811555227908678, 6.209150897601775, 3.0684948417778424, 3.473402549153569, 3.2475923418717962, 3.4020630750965104, 1.657873944449164, 1.1746812960930562, 0.6839799965752206, 0.0, 8.520781928755916, 7.523779962327425, 5.873406480465281, 4.97362183334749, 6.804126150193021, 4.5466292786205145, 3.473402549153569, 2.191782029841316, 3.1045754488008876, 2.6038517426362264, 1.455535869507966, 0.7716123918925856, 0.0), (8.880390607782374, 8.94473733908341, 7.669541716320211, 8.232303073451698, 6.5446682968767265, 3.233780486042246, 3.6602605679559215, 3.4220269190303676, 3.585260954605263, 1.7470445640086882, 1.2379672980711345, 0.7208014791080559, 0.0, 8.979864086115745, 7.928816270188614, 6.189836490355671, 5.241133692026064, 7.170521909210526, 4.790837686642515, 3.6602605679559215, 2.30984320431589, 3.2723341484383632, 2.7441010244839, 1.5339083432640421, 0.8131579399166738, 0.0), (9.330387806156915, 9.394330811177607, 8.055050422711272, 8.646227820006413, 6.874905255585995, 3.396384340607826, 3.844090540307657, 3.593629531639346, 3.765486255058061, 1.8347706320715327, 1.300227256194331, 0.7570258975106506, 0.0, 9.43149950348596, 8.327284872617156, 6.501136280971655, 5.504311896214597, 7.530972510116122, 5.031081344295084, 3.844090540307657, 2.4259888147198754, 3.4374526277929975, 2.8820759400021383, 1.6110100845422546, 0.8540300737434189, 0.0), (9.771639006982534, 9.834666817506942, 8.43261944994451, 9.051626661052135, 7.198516055990973, 3.5556376364373725, 4.024135994536884, 3.7616945852514516, 3.9419977497771805, 1.920691100773466, 1.3612050193415997, 0.7925042256222944, 0.0, 9.87383045277945, 8.717546481845236, 6.806025096707997, 5.762073302320396, 7.883995499554361, 5.266372419352033, 4.024135994536884, 2.5397411688838374, 3.5992580279954867, 3.017208887017379, 1.6865238899889023, 0.8940606197733586, 0.0), (10.202330711712957, 10.263895448477353, 8.800662781251408, 9.446796790068186, 7.514154980353052, 3.710871604493673, 4.19964045897171, 3.9255164854194056, 4.1140542120849, 2.004444922250256, 1.4206444363918964, 0.8270874372822752, 0.0, 10.304999205909127, 9.097961810105026, 7.103222181959481, 6.013334766750766, 8.2281084241698, 5.495723079587168, 4.19964045897171, 2.6506225746383376, 3.757077490176526, 3.148932263356063, 1.7601325562502819, 0.9330814044070321, 0.0), (10.62064942180191, 10.68016679449476, 9.157594399863463, 9.830035400533875, 7.820476310933614, 3.8614174757395103, 4.369847461940239, 4.0843896376959234, 4.280914415303496, 2.0856710486376717, 1.4782893562241752, 0.8606265063298821, 0.0, 10.723148034787885, 9.466891569628702, 7.391446781120876, 6.257013145913014, 8.561828830606991, 5.718145492774292, 4.369847461940239, 2.758155339813936, 3.910238155466807, 3.276678466844626, 1.831518879972693, 0.9709242540449783, 0.0), (11.02478163870312, 11.081630945965095, 9.501828289012156, 10.199639685928528, 8.116134329994049, 4.006606481137679, 4.534000531770584, 4.237608447633729, 4.441837132755248, 2.1640084320714803, 1.5338836277173917, 0.8929724066044035, 0.0, 11.126419211328628, 9.822696472648436, 7.669418138586958, 6.49202529621444, 8.883674265510496, 5.932651826687221, 4.534000531770584, 2.861861772241199, 4.058067164997024, 3.3998798953095104, 1.9003656578024313, 1.0074209950877362, 0.0), (11.412913863870306, 11.46643799329428, 9.83177843192898, 10.553906839731454, 8.399783319795748, 4.145769851650964, 4.691343196790848, 4.38446732078554, 4.596081137762433, 2.2390960246874507, 1.5871710997505006, 0.923976111945128, 0.0, 11.512955007444255, 10.163737231396405, 7.935855498752503, 6.717288074062351, 9.192162275524867, 6.138254249099756, 4.691343196790848, 2.961264179750688, 4.199891659897874, 3.517968946577152, 1.9663556863857963, 1.0424034539358438, 0.0), (11.783232598757209, 11.832738026888249, 10.145858811845418, 10.891134055421968, 8.670077562600099, 4.278238818242151, 4.841118985329142, 4.524260662704076, 4.7429052036473305, 2.3105727786213524, 1.6378956212024585, 0.9534885961913449, 0.0, 11.880897695047656, 10.488374558104791, 8.189478106012292, 6.931718335864056, 9.485810407294661, 6.333964927785706, 4.841118985329142, 3.055884870172965, 4.3350387813000495, 3.63037801847399, 2.0291717623690837, 1.075703456989841, 0.0), (12.133924344817538, 12.178681137152912, 10.442483411992965, 11.209618526479394, 8.925671340668487, 4.403344611874027, 4.9825714257135685, 4.656282878942054, 4.881568103732217, 2.378077646008951, 1.6858010409522184, 0.9813608331823415, 0.0, 12.22838954605175, 10.794969165005755, 8.429005204761092, 7.134232938026852, 9.763136207464434, 6.518796030518876, 4.9825714257135685, 3.1452461513385908, 4.462835670334243, 3.7365395088264655, 2.0884966823985933, 1.107152830650265, 0.0), (12.463175603505027, 12.502417414494213, 10.720066215603106, 11.507657446383048, 9.165218936262296, 4.520418463509383, 5.11494404627224, 4.779828375052198, 5.011328611339368, 2.441249578986017, 1.7306312078787365, 1.0074437967574077, 0.0, 12.55357283236943, 11.08188176433148, 8.653156039393682, 7.323748736958049, 10.022657222678736, 6.691759725073078, 5.11494404627224, 3.228870331078131, 4.582609468131148, 3.8358858154610167, 2.1440132431206216, 1.136583401317656, 0.0), (12.769172876273403, 12.802096949318072, 10.977021205907338, 11.783548008612232, 9.387374631642924, 4.6287916041110035, 5.237480375333263, 4.894191556587227, 5.131445499791063, 2.4997275296883177, 1.7721299708609668, 1.0315884607558323, 0.0, 12.85458982591359, 11.347473068314153, 8.860649854304834, 7.499182589064952, 10.262890999582126, 6.8518681792221185, 5.237480375333263, 3.306279717222145, 4.693687315821462, 3.9278493362040785, 2.195404241181468, 1.1638269953925522, 0.0), (13.050102664576398, 13.075869832030413, 11.211762366137135, 12.035587406646286, 9.590792709071755, 4.72779526464168, 5.349423941224739, 4.998666829099858, 5.241177542409583, 2.5531504502516222, 1.810041178777865, 1.0536457990169035, 0.0, 13.129582798597134, 11.590103789185937, 9.050205893889325, 7.659451350754866, 10.482355084819165, 6.998133560739801, 5.349423941224739, 3.3769966176011996, 4.795396354535877, 4.0118624688820965, 2.242352473227427, 1.1887154392754924, 0.0), (13.30415146986772, 13.321886153037171, 11.422703679523998, 12.262072833964503, 9.774127450810177, 4.816760676064193, 5.450018272274784, 5.092548598142811, 5.339783512517201, 2.6011572928116995, 1.8441086805083868, 1.0734667853799098, 0.0, 13.376694022332964, 11.808134639179006, 9.220543402541933, 7.803471878435097, 10.679567025034402, 7.1295680373999355, 5.450018272274784, 3.440543340045852, 4.887063725405088, 4.087357611321502, 2.2845407359047996, 1.2110805593670158, 0.0), (13.529505793601107, 13.538296002744264, 11.608259129299412, 12.46130148404622, 9.936033139119584, 4.895019069341334, 5.538506896811498, 5.17513126926881, 5.426522183436193, 2.643387009504314, 1.874076324931487, 1.09090239368414, 0.0, 13.594065769033982, 11.999926330525538, 9.370381624657433, 7.9301610285129405, 10.853044366872385, 7.245183776976335, 5.538506896811498, 3.496442192386667, 4.968016569559792, 4.153767161348741, 2.3216518258598824, 1.2307541820676606, 0.0), (13.724352137230287, 13.723249471557619, 11.766842698694862, 12.631570550370744, 10.07516405626135, 4.961901675435895, 5.6141333431629965, 5.245709248030569, 5.500652328488845, 2.6794785524652385, 1.8996879609261188, 1.1058035977688838, 0.0, 13.779840310613086, 12.163839575457718, 9.498439804630594, 8.038435657395715, 11.00130465697769, 7.343992947242797, 5.6141333431629965, 3.5442154824542103, 5.037582028130675, 4.210523516790249, 2.3533685397389728, 1.2475681337779656, 0.0), (13.88687700220898, 13.874896649883173, 11.896868370941842, 12.77117722641738, 10.190174484496875, 5.0167397253106545, 5.676141139657377, 5.30357693998081, 5.561432720997431, 2.7090708738302403, 1.9206874373712384, 1.1180213714734282, 0.0, 13.932159918983176, 12.298235086207708, 9.603437186856192, 8.12721262149072, 11.122865441994861, 7.425007715973134, 5.676141139657377, 3.5833855180790386, 5.095087242248438, 4.257059075472461, 2.379373674188369, 1.2613542408984704, 0.0), (14.015266889990915, 13.991387628126835, 11.996750129271838, 12.87841870566547, 10.279718706087547, 5.058864449928407, 5.723773814622755, 5.348028750672253, 5.608122134284226, 2.731802925735086, 1.936818603145802, 1.1274066886370624, 0.0, 14.049166866057154, 12.401473575007685, 9.68409301572901, 8.195408777205257, 11.216244268568452, 7.487240250941153, 5.723773814622755, 3.6134746070917196, 5.139859353043773, 4.292806235221825, 2.399350025854368, 1.2719443298297126, 0.0), (14.107708302029813, 14.070872496694552, 12.064901956916339, 12.951592181594311, 10.34245100329475, 5.087607080251938, 5.756274896387231, 5.378359085657614, 5.63997934167151, 2.747313660315545, 1.9478253071287643, 1.133810523099076, 0.0, 14.12900342374791, 12.471915754089835, 9.739126535643821, 8.241940980946634, 11.27995868334302, 7.529702719920659, 5.756274896387231, 3.634005057322813, 5.171225501647375, 4.317197393864771, 2.412980391383268, 1.279170226972232, 0.0), (14.162387739779412, 14.111501345992236, 12.099737837106835, 12.988994847683228, 10.377025658379871, 5.102298847244033, 5.77288791327892, 5.393862350489618, 5.656263116481561, 2.7552420297073854, 1.9534513981990798, 1.1370838486987573, 0.0, 14.16981186396836, 12.50792233568633, 9.7672569909954, 8.265726089122154, 11.312526232963123, 7.551407290685465, 5.77288791327892, 3.644499176602881, 5.188512829189936, 4.329664949227744, 2.419947567421367, 1.282863758726567, 0.0), (14.182550708679697, 14.116311945587563, 12.104077046181986, 12.993677353395064, 10.385883252297091, 5.104166666666667, 5.774862801581538, 5.395538065843622, 5.658298909465021, 2.7561772953818022, 1.9541568753377396, 1.1374880506020426, 0.0, 14.175, 12.512368556622466, 9.770784376688697, 8.268531886145405, 11.316597818930042, 7.553753292181072, 5.774862801581538, 3.6458333333333335, 5.192941626148546, 4.331225784465023, 2.4208154092363974, 1.283301085962506, 0.0), (14.197417378247815, 14.113505864197531, 12.10336728395062, 12.99310104166667, 10.390900439373862, 5.104166666666667, 5.773777668845317, 5.393208333333334, 5.658026111111111, 2.755602716049383, 1.9540790684624023, 1.1373934156378602, 0.0, 14.175, 12.51132757201646, 9.77039534231201, 8.266808148148147, 11.316052222222222, 7.550491666666668, 5.773777668845317, 3.6458333333333335, 5.195450219686931, 4.331033680555557, 2.4206734567901242, 1.2830459876543212, 0.0), (14.211970122296213, 14.10797467992684, 12.101966163694561, 12.991960841049384, 10.39580728255487, 5.104166666666667, 5.771639231824418, 5.388631687242799, 5.657487139917696, 2.754471593507088, 1.9539247931994848, 1.1372065996037193, 0.0, 14.175, 12.509272595640908, 9.769623965997424, 8.263414780521263, 11.314974279835392, 7.544084362139919, 5.771639231824418, 3.6458333333333335, 5.197903641277435, 4.330653613683129, 2.4203932327389124, 1.2825431527206221, 0.0), (14.226207826667249, 14.099802892089624, 12.099892889803387, 12.990269714506173, 10.400603610526364, 5.104166666666667, 5.768480702816105, 5.381894547325103, 5.65668890946502, 2.7528027480566992, 1.9536954462318665, 1.136930163084896, 0.0, 14.175, 12.506231793933855, 9.768477231159332, 8.258408244170097, 11.31337781893004, 7.534652366255146, 5.768480702816105, 3.6458333333333335, 5.200301805263182, 4.330089904835392, 2.4199785779606775, 1.2818002629172387, 0.0), (14.240129377203292, 14.089075, 12.097166666666668, 12.988040625, 10.405289251974601, 5.104166666666667, 5.7643352941176484, 5.3730833333333345, 5.655638333333333, 2.7506150000000003, 1.9533924242424245, 1.1365666666666672, 0.0, 14.175, 12.502233333333336, 9.766962121212122, 8.251845, 11.311276666666666, 7.5223166666666685, 5.7643352941176484, 3.6458333333333335, 5.2026446259873005, 4.329346875000001, 2.4194333333333335, 1.280825, 0.0), (14.253733659746702, 14.075875502972108, 12.093806698673983, 12.985286535493827, 10.40986403558584, 5.104166666666667, 5.759236218026306, 5.362284465020577, 5.654342325102881, 2.7479271696387753, 1.9530171239140377, 1.1361186709343092, 0.0, 14.175, 12.4973053802774, 9.765085619570188, 8.243781508916324, 11.308684650205763, 7.507198251028808, 5.759236218026306, 3.6458333333333335, 5.20493201779292, 4.32842884516461, 2.418761339734797, 1.2796250457247373, 0.0), (14.26701956013985, 14.060288900320074, 12.089832190214908, 12.982020408950618, 10.41432779004634, 5.104166666666667, 5.753216686839346, 5.349584362139918, 5.652807798353909, 2.7447580772748066, 1.952570941929584, 1.1355887364730988, 0.0, 14.175, 12.491476101204084, 9.76285470964792, 8.234274231824418, 11.305615596707819, 7.489418106995886, 5.753216686839346, 3.6458333333333335, 5.20716389502317, 4.327340136316874, 2.4179664380429817, 1.2782080818472796, 0.0), (14.279985964225098, 14.042399691358026, 12.085262345679013, 12.978255208333334, 10.418680344042354, 5.104166666666667, 5.746309912854031, 5.335069444444444, 5.651041666666666, 2.7411265432098775, 1.952055274971942, 1.1349794238683129, 0.0, 14.175, 12.48477366255144, 9.760276374859709, 8.223379629629632, 11.302083333333332, 7.469097222222222, 5.746309912854031, 3.6458333333333335, 5.209340172021177, 4.326085069444446, 2.4170524691358026, 1.276581790123457, 0.0), (14.292631757844802, 14.022292375400093, 12.080116369455878, 12.97400389660494, 10.422921526260142, 5.104166666666667, 5.7385491083676285, 5.318826131687244, 5.649050843621399, 2.737051387745771, 1.9514715197239891, 1.1342932937052284, 0.0, 14.175, 12.477226230757509, 9.757357598619945, 8.211154163237312, 11.298101687242799, 7.4463565843621415, 5.7385491083676285, 3.6458333333333335, 5.211460763130071, 4.324667965534981, 2.416023273891176, 1.2747538523090995, 0.0), (14.304955826841338, 14.000051451760402, 12.07441346593507, 12.969279436728398, 10.427051165385956, 5.104166666666667, 5.7299674856774, 5.3009408436214, 5.646842242798354, 2.7325514311842714, 1.950821072868604, 1.1335329065691209, 0.0, 14.175, 12.468861972260328, 9.754105364343019, 8.197654293552812, 11.293684485596708, 7.421317181069961, 5.7299674856774, 3.6458333333333335, 5.213525582692978, 4.3230931455761334, 2.4148826931870144, 1.272731950160037, 0.0), (14.316957057057056, 13.975761419753086, 12.068172839506175, 12.964094791666666, 10.431069090106059, 5.104166666666667, 5.720598257080611, 5.2815, 5.644422777777778, 2.7276454938271613, 1.9501053310886647, 1.1327008230452675, 0.0, 14.175, 12.459709053497942, 9.750526655443322, 8.182936481481482, 11.288845555555556, 7.394100000000001, 5.720598257080611, 3.6458333333333335, 5.215534545053029, 4.321364930555556, 2.413634567901235, 1.2705237654320989, 0.0), (14.328634334334335, 13.949506778692271, 12.061413694558757, 12.958462924382715, 10.434975129106702, 5.104166666666667, 5.710474634874527, 5.260590020576132, 5.641799362139919, 2.7223523959762237, 1.9493256910670491, 1.1317996037189455, 0.0, 14.175, 12.449795640908398, 9.746628455335244, 8.16705718792867, 11.283598724279837, 7.3648260288065845, 5.710474634874527, 3.6458333333333335, 5.217487564553351, 4.319487641460906, 2.4122827389117516, 1.2681369798811157, 0.0), (14.339986544515531, 13.92137202789209, 12.054155235482398, 12.952396797839505, 10.438769111074146, 5.104166666666667, 5.699629831356412, 5.238297325102881, 5.638978909465021, 2.7166909579332423, 1.9484835494866362, 1.1308318091754308, 0.0, 14.175, 12.439149900929737, 9.74241774743318, 8.150072873799726, 11.277957818930043, 7.333616255144034, 5.699629831356412, 3.6458333333333335, 5.219384555537073, 4.317465599279836, 2.41083104709648, 1.2655792752629174, 0.0), (14.35101257344301, 13.891441666666665, 12.04641666666667, 12.945909375, 10.442450864694647, 5.104166666666667, 5.68809705882353, 5.214708333333334, 5.635968333333333, 2.7106800000000004, 1.9475803030303034, 1.1298000000000004, 0.0, 14.175, 12.427800000000001, 9.737901515151515, 8.13204, 11.271936666666665, 7.300591666666668, 5.68809705882353, 3.6458333333333335, 5.221225432347324, 4.315303125000001, 2.409283333333334, 1.2628583333333334, 0.0), (14.361711306959135, 13.859800194330132, 12.038217192501145, 12.939013618827161, 10.44602021865446, 5.104166666666667, 5.675909529573146, 5.189909465020577, 5.632774547325103, 2.7043383424782816, 1.9466173483809293, 1.1287067367779304, 0.0, 14.175, 12.415774104557233, 9.733086741904645, 8.113015027434844, 11.265549094650206, 7.265873251028808, 5.675909529573146, 3.6458333333333335, 5.22301010932723, 4.313004539609055, 2.407643438500229, 1.259981835848194, 0.0), (14.372081630906267, 13.826532110196618, 12.029576017375401, 12.931722492283953, 10.449477001639845, 5.104166666666667, 5.663100455902526, 5.1639871399176975, 5.629404465020576, 2.6976848056698683, 1.9455960822213911, 1.1275545800944982, 0.0, 14.175, 12.403100381039478, 9.727980411106955, 8.093054417009604, 11.258808930041152, 7.229581995884776, 5.663100455902526, 3.6458333333333335, 5.224738500819923, 4.3105741640946516, 2.40591520347508, 1.2569574645633292, 0.0), (14.382122431126781, 13.791721913580247, 12.020512345679016, 12.924048958333334, 10.452821042337057, 5.104166666666667, 5.649703050108934, 5.137027777777778, 5.625865000000001, 2.690738209876544, 1.9445179012345684, 1.1263460905349796, 0.0, 14.175, 12.389806995884772, 9.722589506172842, 8.07221462962963, 11.251730000000002, 7.191838888888889, 5.649703050108934, 3.6458333333333335, 5.226410521168528, 4.308016319444445, 2.4041024691358035, 1.253792901234568, 0.0), (14.39183259346303, 13.755454103795152, 12.011045381801555, 12.916005979938273, 10.45605216943235, 5.104166666666667, 5.635750524489632, 5.1091177983539104, 5.622163065843623, 2.6835173754000925, 1.943384202103338, 1.125083828684652, 0.0, 14.175, 12.375922115531171, 9.71692101051669, 8.050552126200277, 11.244326131687245, 7.1527649176954755, 5.635750524489632, 3.6458333333333335, 5.228026084716175, 4.305335326646092, 2.4022090763603114, 1.2504958276177414, 0.0), (14.40121100375738, 13.717813180155463, 12.001194330132604, 12.90760652006173, 10.459170211611989, 5.104166666666667, 5.621276091341887, 5.080343621399178, 5.618305576131687, 2.676041122542296, 1.9421963815105796, 1.1237703551287916, 0.0, 14.175, 12.361473906416705, 9.710981907552897, 8.028123367626886, 11.236611152263373, 7.112481069958849, 5.621276091341887, 3.6458333333333335, 5.229585105805994, 4.302535506687244, 2.400238866026521, 1.2470739254686787, 0.0), (14.410256547852201, 13.678883641975311, 11.990978395061731, 12.89886354166667, 10.462174997562222, 5.104166666666667, 5.6063129629629636, 5.050791666666668, 5.614299444444446, 2.668328271604939, 1.9409558361391697, 1.122408230452675, 0.0, 14.175, 12.346490534979424, 9.704779180695848, 8.004984814814815, 11.228598888888891, 7.071108333333335, 5.6063129629629636, 3.6458333333333335, 5.231087498781111, 4.299621180555557, 2.3981956790123466, 1.2435348765432102, 0.0), (14.418968111589852, 13.638749988568819, 11.980416780978512, 12.889790007716051, 10.46506635596931, 5.104166666666667, 5.5908943516501255, 5.020548353909466, 5.61015158436214, 2.660397642889804, 1.9396639626719878, 1.1210000152415793, 0.0, 14.175, 12.331000167657372, 9.698319813359937, 7.981192928669412, 11.22030316872428, 7.0287676954732525, 5.5908943516501255, 3.6458333333333335, 5.232533177984655, 4.296596669238685, 2.3960833561957027, 1.2398863625971654, 0.0), (14.427344580812699, 13.597496719250115, 11.969528692272522, 12.880398881172843, 10.467844115519508, 5.104166666666667, 5.575053469700638, 4.98970010288066, 5.605868909465021, 2.652268056698675, 1.938322157791911, 1.1195482700807806, 0.0, 14.175, 12.315030970888586, 9.691610788959554, 7.9568041700960235, 11.211737818930041, 6.985580144032924, 5.575053469700638, 3.6458333333333335, 5.233922057759754, 4.293466293724282, 2.3939057384545044, 1.2361360653863744, 0.0), (14.435384841363105, 13.555208333333335, 11.958333333333336, 12.870703125000002, 10.470508104899077, 5.104166666666667, 5.558823529411765, 4.958333333333334, 5.601458333333333, 2.6439583333333343, 1.9369318181818187, 1.1180555555555556, 0.0, 14.175, 12.29861111111111, 9.684659090909092, 7.931875000000002, 11.202916666666667, 6.941666666666667, 5.558823529411765, 3.6458333333333335, 5.235254052449538, 4.290234375000002, 2.391666666666667, 1.232291666666667, 0.0), (14.443087779083434, 13.511969330132603, 11.946849908550526, 12.860715702160494, 10.47305815279427, 5.104166666666667, 5.542237743080772, 4.926534465020577, 5.596926769547324, 2.635487293095565, 1.9354943405245877, 1.1165244322511814, 0.0, 14.175, 12.281768754762993, 9.677471702622938, 7.906461879286693, 11.193853539094649, 6.897148251028808, 5.542237743080772, 3.6458333333333335, 5.236529076397135, 4.286905234053499, 2.3893699817101055, 1.228360848193873, 0.0), (14.45045227981605, 13.46786420896205, 11.935097622313673, 12.850449575617287, 10.475494087891343, 5.104166666666667, 5.525329323004923, 4.894389917695474, 5.592281131687244, 2.6268737562871523, 1.9340111215030973, 1.1149574607529342, 0.0, 14.175, 12.264532068282275, 9.670055607515485, 7.880621268861455, 11.184562263374488, 6.852145884773663, 5.525329323004923, 3.6458333333333335, 5.237747043945672, 4.283483191872429, 2.387019524462735, 1.2243512917238228, 0.0), (14.457477229403315, 13.422977469135803, 11.923095679012349, 12.839917708333335, 10.477815738876558, 5.104166666666667, 5.508131481481482, 4.861986111111112, 5.587528333333333, 2.618136543209877, 1.9324835578002246, 1.1133572016460909, 0.0, 14.175, 12.246929218106997, 9.662417789001124, 7.854409629629629, 11.175056666666666, 6.806780555555557, 5.508131481481482, 3.6458333333333335, 5.238907869438279, 4.279972569444446, 2.38461913580247, 1.2202706790123459, 0.0), (14.464161513687602, 13.377393609967992, 11.910863283036125, 12.829133063271607, 10.480022934436168, 5.104166666666667, 5.490677430807714, 4.829409465020577, 5.582675288065844, 2.6092944741655244, 1.930913046098849, 1.1117262155159278, 0.0, 14.175, 12.228988370675204, 9.654565230494246, 7.827883422496572, 11.165350576131688, 6.761173251028807, 5.490677430807714, 3.6458333333333335, 5.240011467218084, 4.276377687757203, 2.382172656607225, 1.2161266918152722, 0.0), (14.470504018511264, 13.33119713077275, 11.89841963877458, 12.81810860339506, 10.482115503256427, 5.104166666666667, 5.473000383280885, 4.796746399176955, 5.57772890946502, 2.6003663694558763, 1.9293009830818477, 1.1100670629477218, 0.0, 14.175, 12.210737692424937, 9.646504915409238, 7.8010991083676275, 11.15545781893004, 6.715444958847738, 5.473000383280885, 3.6458333333333335, 5.2410577516282135, 4.272702867798355, 2.379683927754916, 1.211927011888432, 0.0), (14.476503629716676, 13.284472530864198, 11.885783950617286, 12.806857291666669, 10.484093274023598, 5.104166666666667, 5.455133551198258, 4.764083333333335, 5.572696111111112, 2.5913710493827167, 1.9276487654320995, 1.1083823045267494, 0.0, 14.175, 12.192205349794241, 9.638243827160496, 7.774113148148149, 11.145392222222224, 6.669716666666668, 5.455133551198258, 3.6458333333333335, 5.242046637011799, 4.268952430555557, 2.377156790123457, 1.2076793209876546, 0.0), (14.482159233146191, 13.237304309556471, 11.87297542295382, 12.795392091049385, 10.485956075423934, 5.104166666666667, 5.437110146857097, 4.731506687242798, 5.567583806584363, 2.582327334247829, 1.9259577898324816, 1.1066745008382872, 0.0, 14.175, 12.173419509221157, 9.629788949162407, 7.746982002743485, 11.135167613168726, 6.624109362139918, 5.437110146857097, 3.6458333333333335, 5.242978037711967, 4.265130697016462, 2.3745950845907644, 1.2033913008687704, 0.0), (14.487469714642183, 13.189776966163697, 11.860013260173757, 12.783725964506175, 10.487703736143693, 5.104166666666667, 5.418963382554669, 4.699102880658437, 5.5623989094650215, 2.573254044352996, 1.9242294529658732, 1.104946212467612, 0.0, 14.175, 12.15440833714373, 9.621147264829364, 7.719762133058986, 11.124797818930043, 6.578744032921811, 5.418963382554669, 3.6458333333333335, 5.243851868071847, 4.261241988168726, 2.3720026520347517, 1.199070633287609, 0.0), (14.492433960047004, 13.141975000000002, 11.846916666666667, 12.771871875000002, 10.489336084869135, 5.104166666666667, 5.400726470588236, 4.6669583333333335, 5.557148333333334, 2.5641700000000007, 1.9224651515151516, 1.1032000000000002, 0.0, 14.175, 12.1352, 9.612325757575757, 7.69251, 11.114296666666668, 6.533741666666667, 5.400726470588236, 3.6458333333333335, 5.244668042434568, 4.257290625000001, 2.369383333333334, 1.1947250000000003, 0.0), (14.497050855203032, 13.093982910379516, 11.833704846822133, 12.759842785493827, 10.490852950286511, 5.104166666666667, 5.382432623255064, 4.6351594650205765, 5.551838991769547, 2.555094021490627, 1.9206662821631961, 1.101438424020729, 0.0, 14.175, 12.115822664228014, 9.603331410815981, 7.66528206447188, 11.103677983539095, 6.4892232510288075, 5.382432623255064, 3.6458333333333335, 5.2454264751432556, 4.253280928497944, 2.3667409693644266, 1.1903620827617745, 0.0), (14.501319285952622, 13.045885196616371, 11.820397005029724, 12.74765165895062, 10.492254161082082, 5.104166666666667, 5.3641150528524175, 4.603792695473252, 5.5464777983539095, 2.5460449291266585, 1.918834241592884, 1.099664045115074, 0.0, 14.175, 12.096304496265812, 9.59417120796442, 7.638134787379974, 11.092955596707819, 6.445309773662553, 5.3641150528524175, 3.6458333333333335, 5.246127080541041, 4.249217219650207, 2.3640794010059447, 1.1859895633287612, 0.0), (14.505238138138138, 12.997766358024693, 11.807012345679016, 12.735311458333335, 10.493539545942102, 5.104166666666667, 5.34580697167756, 4.572944444444445, 5.541071666666667, 2.5370415432098774, 1.9169704264870937, 1.097879423868313, 0.0, 14.175, 12.076673662551439, 9.584852132435467, 7.61112462962963, 11.082143333333335, 6.402122222222224, 5.34580697167756, 3.6458333333333335, 5.246769772971051, 4.245103819444446, 2.3614024691358035, 1.1816151234567904, 0.0), (14.508806297601952, 12.949710893918612, 11.79357007315958, 12.72283514660494, 10.494708933552829, 5.104166666666667, 5.3275415920277585, 4.5427011316872425, 5.535627510288066, 2.5281026840420675, 1.9150762335287033, 1.096087120865722, 0.0, 14.175, 12.05695832952294, 9.575381167643515, 7.584308052126201, 11.071255020576132, 6.35978158436214, 5.3275415920277585, 3.6458333333333335, 5.2473544667764145, 4.240945048868314, 2.3587140146319165, 1.1772464449016922, 0.0), (14.51202265018642, 12.901803303612255, 11.780089391860999, 12.710235686728396, 10.495762152600523, 5.104166666666667, 5.309352126200275, 4.513149176954733, 5.530152242798355, 2.5192471719250125, 1.9131530594005905, 1.0942896966925775, 0.0, 14.175, 12.037186663618352, 9.565765297002951, 7.557741515775036, 11.06030448559671, 6.3184088477366265, 5.309352126200275, 3.6458333333333335, 5.247881076300262, 4.2367452289094665, 2.3560178783722, 1.172891209419296, 0.0), (14.51488608173391, 12.854128086419754, 11.76658950617284, 12.697526041666668, 10.496699031771435, 5.104166666666667, 5.291271786492374, 4.484375000000001, 5.524652777777779, 2.5104938271604946, 1.9112023007856345, 1.0924897119341568, 0.0, 14.175, 12.017386831275722, 9.556011503928172, 7.5314814814814826, 11.049305555555557, 6.278125000000001, 5.291271786492374, 3.6458333333333335, 5.248349515885717, 4.232508680555557, 2.353317901234568, 1.1685570987654323, 0.0), (14.517395478086781, 12.806769741655238, 11.753089620484685, 12.684719174382717, 10.497519399751823, 5.104166666666667, 5.273333785201324, 4.4564650205761325, 5.519136028806585, 2.501861470050298, 1.9092253543667126, 1.0906897271757356, 0.0, 14.175, 11.997586998933091, 9.546126771833563, 7.5055844101508935, 11.03827205761317, 6.2390510288065855, 5.273333785201324, 3.6458333333333335, 5.248759699875912, 4.22823972479424, 2.350617924096937, 1.1642517946959308, 0.0), (14.519549725087407, 12.759812768632832, 11.739608939186102, 12.671828047839508, 10.498223085227952, 5.104166666666667, 5.255571334624385, 4.429505658436215, 5.513608909465021, 2.4933689208962058, 1.9072236168267036, 1.0888923030025914, 0.0, 14.175, 11.977815333028504, 9.536118084133516, 7.4801067626886155, 11.027217818930042, 6.201307921810701, 5.255571334624385, 3.6458333333333335, 5.249111542613976, 4.2239426826131705, 2.3479217878372207, 1.1599829789666212, 0.0), (14.521347708578144, 12.713341666666667, 11.72616666666667, 12.658865625, 10.498809916886067, 5.104166666666667, 5.238017647058824, 4.4035833333333345, 5.508078333333334, 2.4850350000000003, 1.9051984848484853, 1.0871000000000002, 0.0, 14.175, 11.9581, 9.525992424242425, 7.455105, 11.016156666666667, 6.165016666666668, 5.238017647058824, 3.6458333333333335, 5.249404958443034, 4.219621875000001, 2.345233333333334, 1.1557583333333337, 0.0), (14.522788314401359, 12.667440935070873, 11.712782007315958, 12.645844868827162, 10.499279723412432, 5.104166666666667, 5.220705934801905, 4.378784465020577, 5.50255121399177, 2.4768785276634664, 1.9031513551149353, 1.0853153787532392, 0.0, 14.175, 11.938469166285628, 9.515756775574676, 7.430635582990398, 11.00510242798354, 6.130298251028808, 5.220705934801905, 3.6458333333333335, 5.249639861706216, 4.215281622942388, 2.342556401463192, 1.151585539551898, 0.0), (14.523870428399414, 12.62219507315958, 11.69947416552355, 12.63277874228395, 10.499632333493302, 5.104166666666667, 5.2036694101508925, 4.35519547325103, 5.497034465020577, 2.4689183241883863, 1.9010836243089335, 1.0835409998475842, 0.0, 14.175, 11.918950998323425, 9.505418121544666, 7.406754972565158, 10.994068930041154, 6.097273662551442, 5.2036694101508925, 3.6458333333333335, 5.249816166746651, 4.2109262474279845, 2.3398948331047102, 1.1474722793781438, 0.0), (14.524592936414676, 12.577688580246916, 11.686262345679015, 12.619680208333333, 10.499867575814935, 5.104166666666667, 5.1869412854030505, 4.332902777777779, 5.491535000000001, 2.4611732098765438, 1.898996689113356, 1.0817794238683132, 0.0, 14.175, 11.899573662551441, 9.49498344556678, 7.38351962962963, 10.983070000000001, 6.06606388888889, 5.1869412854030505, 3.6458333333333335, 5.249933787907468, 4.206560069444445, 2.337252469135803, 1.1434262345679016, 0.0), (14.524954724289511, 12.534005955647004, 11.673165752171926, 12.606562229938273, 10.499985279063587, 5.104166666666667, 5.1705547728556445, 4.311992798353911, 5.486059732510288, 2.453662005029722, 1.8968919462110825, 1.0800332114007012, 0.0, 14.175, 11.88036532540771, 9.484459731055413, 7.360986015089164, 10.972119465020576, 6.036789917695475, 5.1705547728556445, 3.6458333333333335, 5.2499926395317935, 4.202187409979425, 2.3346331504343856, 1.1394550868770006, 0.0), (14.524708260273156, 12.491002420461081, 11.660140274919984, 12.593323827495976, 10.499886091610856, 5.104071942793273, 5.154460636380753, 4.292367245846671, 5.480574329370524, 2.446367154576509, 1.894733397326088, 1.078295169221637, 0.0, 14.174825210048013, 11.861246861438005, 9.47366698663044, 7.339101463729525, 10.961148658741047, 6.009314144185339, 5.154460636380753, 3.6457656734237665, 5.249943045805428, 4.197774609165326, 2.3320280549839967, 1.135545674587371, 0.0), (14.522398389694043, 12.44736508363202, 11.646819830246914, 12.579297690217391, 10.498983297022512, 5.1033231138545965, 5.13818772694263, 4.272974279835392, 5.474838991769548, 2.439082236746551, 1.8923013290802768, 1.0765088802252547, 0.0, 14.17344039351852, 11.8415976824778, 9.461506645401384, 7.317246710239651, 10.949677983539097, 5.982163991769549, 5.13818772694263, 3.6452307956104257, 5.249491648511256, 4.193099230072464, 2.329363966049383, 1.1315786439665476, 0.0), (14.517840102582454, 12.402893656798973, 11.633146504915409, 12.564391480475042, 10.49719935985368, 5.101848358989992, 5.121662094192959, 4.253638926992837, 5.468821349641823, 2.4317718335619576, 1.8895680735227522, 1.0746659888174948, 0.0, 14.170705268347055, 11.82132587699244, 9.447840367613761, 7.295315500685872, 10.937642699283646, 5.955094497789972, 5.121662094192959, 3.6441773992785653, 5.24859967992684, 4.188130493491681, 2.326629300983082, 1.127535786981725, 0.0), (14.511097524900102, 12.357614716359132, 11.619125100022863, 12.548627178945251, 10.49455687350386, 5.0996715769953775, 5.104891161677292, 4.234367588782199, 5.462530365035819, 2.4244361257699243, 1.8865437198495683, 1.072767842674817, 0.0, 14.166655842764062, 11.800446269422984, 9.43271859924784, 7.273308377309771, 10.925060730071637, 5.928114624295079, 5.104891161677292, 3.642622554996698, 5.24727843675193, 4.182875726315085, 2.323825020004573, 1.1234195196690122, 0.0), (14.502234782608697, 12.311554838709677, 11.604760416666666, 12.532026766304348, 10.49107843137255, 5.096816666666667, 5.087882352941177, 4.215166666666667, 5.4559750000000005, 2.4170752941176477, 1.8832383572567788, 1.0708157894736845, 0.0, 14.161328125, 11.778973684210527, 9.416191786283894, 7.251225882352942, 10.911950000000001, 5.901233333333334, 5.087882352941177, 3.6405833333333337, 5.245539215686275, 4.177342255434784, 2.3209520833333337, 1.1192322580645162, 0.0), (14.491316001669949, 12.264740600247798, 11.590057255944217, 12.514612223228664, 10.486786626859248, 5.0933075267997765, 5.070643091530164, 4.196042562109436, 5.4491642165828384, 2.409689519352323, 1.8796620749404376, 1.0688111768905575, 0.0, 14.154758123285324, 11.75692294579613, 9.398310374702186, 7.229068558056968, 10.898328433165677, 5.8744595869532095, 5.070643091530164, 3.638076804856983, 5.243393313429624, 4.171537407742889, 2.3180114511888434, 1.1149764182043456, 0.0), (14.478405308045566, 12.21719857737068, 11.575020418952905, 12.496405530394526, 10.481704053363458, 5.089168056190623, 5.053180800989806, 4.177001676573693, 5.4421069768328, 2.402278982221147, 1.8758249620965999, 1.0667553526018982, 0.0, 14.146981845850483, 11.734308878620878, 9.379124810482999, 7.20683694666344, 10.8842139536656, 5.84780234720317, 5.053180800989806, 3.635120040136159, 5.240852026681729, 4.165468510131509, 2.315004083790581, 1.1106544161246077, 0.0), (14.463566827697262, 12.168955346475506, 11.559654706790123, 12.477428668478263, 10.475853304284678, 5.084422153635118, 5.03550290486565, 4.158050411522635, 5.434812242798353, 2.394843863471315, 1.8717371079213185, 1.0646496642841674, 0.0, 14.138035300925928, 11.711146307125839, 9.358685539606592, 7.184531590413944, 10.869624485596706, 5.821270576131688, 5.03550290486565, 3.63173010973937, 5.237926652142339, 4.159142889492755, 2.311930941358025, 1.10626866786141, 0.0), (14.44686468658675, 12.12003748395947, 11.543964920553272, 12.457703618156202, 10.469256973022405, 5.079093717929179, 5.017616826703247, 4.139195168419449, 5.427288976527969, 2.3873843438500235, 1.8674086016106486, 1.0624954596138265, 0.0, 14.127954496742113, 11.68745005575209, 9.337043008053241, 7.162153031550069, 10.854577953055937, 5.794873235787229, 5.017616826703247, 3.6279240842351275, 5.234628486511203, 4.152567872718735, 2.3087929841106543, 1.101821589450861, 0.0), (14.428363010675731, 12.070471566219748, 11.527955861339734, 12.43725236010467, 10.461937652976141, 5.07320664786872, 4.9995299900481465, 4.120442348727329, 5.4195461400701115, 2.3799006041044684, 1.8628495323606438, 1.0602940862673376, 0.0, 14.116775441529496, 11.663234948940712, 9.314247661803218, 7.139701812313404, 10.839092280140223, 5.768619288218261, 4.9995299900481465, 3.623719034191943, 5.230968826488071, 4.145750786701558, 2.305591172267947, 1.0973155969290682, 0.0), (14.408125925925928, 12.020284169653527, 11.511632330246915, 12.416096875000001, 10.45391793754539, 5.066784842249657, 4.981249818445898, 4.101798353909466, 5.41159269547325, 2.372392824981845, 1.8580699893673582, 1.0580468919211612, 0.0, 14.10453414351852, 11.638515811132772, 9.29034994683679, 7.1171784749455345, 10.8231853909465, 5.742517695473253, 4.981249818445898, 3.6191320301783265, 5.226958968772695, 4.138698958333334, 2.3023264660493834, 1.092753106332139, 0.0), (14.386217558299041, 11.969501870657995, 11.494999128372202, 12.394259143518521, 10.445220420129644, 5.0598521998679065, 4.962783735442051, 4.0832695854290515, 5.403437604785855, 2.3648611872293506, 1.8530800618268455, 1.0557552242517592, 0.0, 14.091266610939643, 11.613307466769347, 9.265400309134227, 7.094583561688051, 10.80687520957171, 5.716577419600672, 4.962783735442051, 3.61418014276279, 5.222610210064822, 4.131419714506174, 2.2989998256744406, 1.0881365336961817, 0.0), (14.362702033756786, 11.918151245630337, 11.478061056812987, 12.371761146336556, 10.435867694128408, 5.052432619519382, 4.9441391645821575, 4.064862444749277, 5.395089830056394, 2.35730587159418, 1.847889838935161, 1.0534204309355928, 0.0, 14.07700885202332, 11.587624740291517, 9.239449194675805, 7.071917614782539, 10.790179660112788, 5.690807422648988, 4.9441391645821575, 3.6088804425138443, 5.217933847064204, 4.123920382112186, 2.2956122113625974, 1.0834682950573036, 0.0), (14.337643478260873, 11.866258870967743, 11.460822916666668, 12.348624864130437, 10.425882352941176, 5.04455, 4.925323529411765, 4.046583333333334, 5.386558333333333, 2.34972705882353, 1.8425094098883579, 1.0510438596491232, 0.0, 14.061796875, 11.561482456140352, 9.212547049441788, 7.049181176470589, 10.773116666666667, 5.665216666666669, 4.925323529411765, 3.60325, 5.212941176470588, 4.11620828804348, 2.2921645833333337, 1.0787508064516131, 0.0), (14.311106017773009, 11.813851323067393, 11.443289509030638, 12.32487227757649, 10.415286989967456, 5.036228240105676, 4.906344253476426, 4.0284386526444145, 5.3778520766651425, 2.342124929664596, 1.83694886388249, 1.048626858068812, 0.0, 14.045666688100141, 11.53489543875693, 9.18474431941245, 7.026374788993786, 10.755704153330285, 5.63981411370218, 4.906344253476426, 3.5973058857897686, 5.207643494983728, 4.1082907591921645, 2.2886579018061277, 1.0739864839152178, 0.0), (14.283153778254908, 11.760955178326475, 11.425465635002288, 12.300525367351046, 10.40410419860674, 5.027491238632323, 4.887208760321688, 4.01043480414571, 5.368980022100289, 2.3344996648645746, 1.8312182901136123, 1.0461707738711208, 0.0, 14.028654299554185, 11.507878512582325, 9.156091450568061, 7.0034989945937225, 10.737960044200578, 5.614608725803994, 4.887208760321688, 3.5910651704516594, 5.20205209930337, 4.1001751224503495, 2.2850931270004575, 1.0691777434842251, 0.0), (14.253850885668278, 11.707597013142175, 11.407356095679013, 12.275606114130436, 10.392356572258533, 5.0183628943758585, 4.867924473493101, 3.9925781893004118, 5.359951131687243, 2.3268514451706617, 1.825327777777778, 1.0436769547325107, 0.0, 14.010795717592593, 11.480446502057614, 9.12663888888889, 6.980554335511984, 10.719902263374486, 5.589609465020577, 4.867924473493101, 3.5845449245541845, 5.196178286129267, 4.091868704710146, 2.281471219135803, 1.0643270011947434, 0.0), (14.223261465974833, 11.653803403911677, 11.388965692158209, 12.250136498590983, 10.380066704322333, 5.008867106132196, 4.8484988165362175, 3.974875209571713, 5.35077436747447, 2.3191804513300527, 1.8192874160710422, 1.041146748329443, 0.0, 13.992126950445819, 11.452614231623869, 9.09643708035521, 6.957541353990157, 10.70154873494894, 5.564825293400398, 4.8484988165362175, 3.577762218665854, 5.190033352161167, 4.083378832863662, 2.2777931384316417, 1.05943667308288, 0.0), (14.191449645136279, 11.59960092703217, 11.370299225537268, 12.224138501409021, 10.367257188197637, 4.999027772697253, 4.828939212996585, 3.9573322664228017, 5.341458691510441, 2.311486864089944, 1.8131072941894584, 1.0385815023383795, 0.0, 13.97268400634431, 11.424396525722173, 9.065536470947292, 6.934460592269831, 10.682917383020882, 5.540265172991923, 4.828939212996585, 3.57073412335518, 5.183628594098819, 4.074712833803008, 2.274059845107454, 1.0545091751847429, 0.0), (14.15847954911433, 11.545016158900838, 11.35136149691358, 12.19763410326087, 10.353950617283953, 4.988868792866941, 4.809253086419753, 3.939955761316873, 5.332013065843622, 2.3037708641975314, 1.8067975013290805, 1.035982564435781, 0.0, 13.95250289351852, 11.39580820879359, 9.033987506645403, 6.9113125925925925, 10.664026131687244, 5.515938065843622, 4.809253086419753, 3.563477709190672, 5.1769753086419765, 4.065878034420291, 2.2702722993827162, 1.0495469235364399, 0.0), (14.124415303870702, 11.490075675914863, 11.332157307384547, 12.170645284822868, 10.340169584980769, 4.97841406543718, 4.789447860351274, 3.9227520957171165, 5.322446452522482, 2.296032632400011, 1.8003681266859632, 1.0333512822981095, 0.0, 13.931619620198905, 11.366864105279202, 9.001840633429817, 6.888097897200032, 10.644892905044964, 5.491852934003963, 4.789447860351274, 3.556010046740843, 5.1700847924903846, 4.056881761607624, 2.2664314614769094, 1.0445523341740786, 0.0), (14.089321035367092, 11.434806054471437, 11.312691458047555, 12.143194026771337, 10.325936684687594, 4.967687489203883, 4.769530958336696, 3.905727671086725, 5.312767813595489, 2.2882723494445796, 1.7938292594561607, 1.030689003601826, 0.0, 13.910070194615912, 11.337579039620083, 8.969146297280803, 6.864817048333737, 10.625535627190978, 5.4680187395214155, 4.769530958336696, 3.548348206574202, 5.162968342343797, 4.047731342257113, 2.2625382916095114, 1.0395278231337672, 0.0), (14.053260869565218, 11.379233870967743, 11.292968750000002, 12.115302309782612, 10.311274509803923, 4.956712962962964, 4.749509803921569, 3.8888888888888893, 5.302986111111112, 2.280490196078432, 1.787190988835726, 1.027997076023392, 0.0, 13.887890625, 11.30796783625731, 8.93595494417863, 6.841470588235294, 10.605972222222224, 5.4444444444444455, 4.749509803921569, 3.54050925925926, 5.155637254901961, 4.0384341032608715, 2.2585937500000006, 1.0344758064516133, 0.0), (14.016298932426789, 11.323385701800964, 11.272993984339278, 12.086992114533015, 10.296205653729254, 4.945514385510339, 4.729391820651443, 3.8722421505868017, 5.293110307117818, 2.2726863530487647, 1.7804634040207143, 1.025276847239269, 0.0, 13.865116919581618, 11.278045319631957, 8.902317020103572, 6.818059059146293, 10.586220614235636, 5.4211390108215225, 4.729391820651443, 3.5325102753645283, 5.148102826864627, 4.0289973715110055, 2.254598796867856, 1.0293987001637241, 0.0), (13.978499349913523, 11.267288123368292, 11.252771962162782, 12.058285421698875, 10.280752709863094, 4.934115655641925, 4.709184432071869, 3.8557938576436523, 5.2831493636640765, 2.2648610011027737, 1.7736565942071794, 1.0225296649259181, 0.0, 13.841785086591221, 11.247826314185097, 8.868282971035896, 6.79458300330832, 10.566298727328153, 5.398111400701113, 4.709184432071869, 3.524368325458518, 5.140376354931547, 4.019428473899626, 2.2505543924325564, 1.0242989203062085, 0.0), (13.939926247987117, 11.210967712066907, 11.232307484567903, 12.029204211956525, 10.264938271604938, 4.9225406721536356, 4.688895061728395, 3.839550411522634, 5.273112242798354, 2.2570143209876545, 1.7667806485911755, 1.019756876759801, 0.0, 13.81793113425926, 11.217325644357809, 8.833903242955877, 6.771042962962962, 10.546224485596708, 5.375370576131688, 4.688895061728395, 3.5161004801097393, 5.132469135802469, 4.009734737318842, 2.246461496913581, 1.0191788829151736, 0.0), (13.900643752609293, 11.154451044293994, 11.211605352652038, 11.999770465982289, 10.248784932354287, 4.910813333841387, 4.6685311331665735, 3.8235182136869392, 5.263007906569121, 2.2491464934506045, 1.7598456563687561, 1.016959830417379, 0.0, 13.793591070816188, 11.186558134591166, 8.79922828184378, 6.747439480351812, 10.526015813138242, 5.3529254991617155, 4.6685311331665735, 3.5077238098867047, 5.124392466177143, 3.9999234886607637, 2.2423210705304077, 1.014041004026727, 0.0), (13.860715989741754, 11.097764696446747, 11.190670367512576, 11.970006164452498, 10.232315285510639, 4.898957539501094, 4.648100069931951, 3.807703665599757, 5.252845317024844, 2.241257699238818, 1.752861706735976, 1.014139873575113, 0.0, 13.768800904492457, 11.155538609326241, 8.764308533679879, 6.723773097716453, 10.505690634049689, 5.33078513183966, 4.648100069931951, 3.499255385357924, 5.1161576427553195, 3.9900020548175, 2.2381340735025153, 1.0088876996769771, 0.0), (13.820207085346219, 11.040935244922345, 11.169507330246915, 11.93993328804348, 10.215551924473493, 4.88699718792867, 4.62760929557008, 3.7921131687242804, 5.242633436213992, 2.2333481190994924, 1.7458388888888892, 1.0112983539094653, 0.0, 13.74359664351852, 11.124281893004117, 8.729194444444445, 6.700044357298475, 10.485266872427983, 5.3089584362139925, 4.62760929557008, 3.490712277091907, 5.1077759622367465, 3.9799777626811608, 2.2339014660493834, 1.0037213859020315, 0.0), (13.779181165384388, 10.983989266117973, 11.148121041952448, 11.909573817431562, 10.198517442642354, 4.8749561779200326, 4.60706623362651, 3.7767531245237014, 5.2323812261850335, 2.2254179337798226, 1.7387872920235496, 1.0084366190968967, 0.0, 13.718014296124831, 11.09280281006586, 8.693936460117747, 6.676253801339467, 10.464762452370067, 5.287454374333182, 4.60706623362651, 3.482111555657166, 5.099258721321177, 3.969857939143855, 2.2296242083904896, 0.9985444787379977, 0.0), (13.737702355817978, 10.926953336430817, 11.126516303726566, 11.878949733293078, 10.181234433416716, 4.862858408271099, 4.58647830764679, 3.7616299344612103, 5.222097648986434, 2.2174673240270053, 1.7317170053360116, 1.0055560168138682, 0.0, 13.69208987054184, 11.06111618495255, 8.658585026680058, 6.652401972081014, 10.444195297972868, 5.266281908245695, 4.58647830764679, 3.4734702916222133, 5.090617216708358, 3.9596499110976935, 2.2253032607453136, 0.9933593942209834, 0.0), (13.695834782608697, 10.869854032258065, 11.10469791666667, 11.848083016304349, 10.163725490196079, 4.850727777777779, 4.5658529411764714, 3.7467500000000005, 5.211791666666667, 2.2094964705882356, 1.724638118022329, 1.0026578947368423, 0.0, 13.665859375000002, 11.029236842105265, 8.623190590111644, 6.628489411764706, 10.423583333333333, 5.245450000000001, 4.5658529411764714, 3.4648055555555564, 5.081862745098039, 3.949361005434784, 2.220939583333334, 0.988168548387097, 0.0), (13.653642571718258, 10.8127179299969, 11.082670681870143, 11.816995647141708, 10.146013206379946, 4.8385881852359915, 4.545197557761102, 3.732119722603262, 5.201472241274196, 2.201505554210711, 1.717560719278556, 0.9997436005422796, 0.0, 13.639358817729768, 10.997179605965075, 8.58780359639278, 6.6045166626321326, 10.402944482548392, 5.224967611644567, 4.545197557761102, 3.456134418025708, 5.073006603189973, 3.938998549047237, 2.2165341363740287, 0.9829743572724456, 0.0), (13.611189849108369, 10.755571606044516, 11.060439400434387, 11.785709606481484, 10.128120175367815, 4.82646352944165, 4.524519580946234, 3.7177455037341867, 5.191148334857491, 2.1934947556416264, 1.7104948983007466, 0.9968144819066413, 0.0, 13.612624206961591, 10.964959300973053, 8.552474491503732, 6.580484266924878, 10.382296669714982, 5.204843705227861, 4.524519580946234, 3.4474739496011786, 5.064060087683908, 3.928569868827162, 2.2120878800868775, 0.977779236913138, 0.0), (13.568540740740744, 10.698441636798089, 11.038008873456791, 11.754246875000002, 10.110068990559187, 4.814377709190674, 4.503826434277415, 3.7036337448559675, 5.180828909465021, 2.1854642556281783, 1.7034507442849551, 0.9938718865063897, 0.0, 13.585691550925928, 10.932590751570284, 8.517253721424776, 6.556392766884533, 10.361657818930041, 5.185087242798355, 4.503826434277415, 3.438841220850481, 5.055034495279593, 3.918082291666668, 2.207601774691358, 0.972585603345281, 0.0), (13.525759372577088, 10.641354598654807, 11.015383902034753, 11.722629433373593, 10.09188224535356, 4.802354623278973, 4.483125541300197, 3.689790847431795, 5.170522927145252, 2.1774142349175616, 1.696438346427236, 0.9909171620179854, 0.0, 13.558596857853223, 10.900088782197837, 8.482191732136178, 6.532242704752683, 10.341045854290504, 5.1657071864045125, 4.483125541300197, 3.4302533023421233, 5.04594112267678, 3.907543144457865, 2.2030767804069504, 0.9673958726049827, 0.0), (13.482909870579116, 10.58433706801186, 10.992569287265662, 11.690879262278584, 10.073582533150434, 4.790418170502465, 4.462424325560129, 3.6762232129248593, 5.160239349946655, 2.1693448742569736, 1.689467793923642, 0.9879516561178898, 0.0, 13.53137613597394, 10.867468217296787, 8.447338969618208, 6.50803462277092, 10.32047869989331, 5.146712498094804, 4.462424325560129, 3.421727264644618, 5.036791266575217, 3.896959754092862, 2.1985138574531327, 0.9622124607283511, 0.0), (13.440056360708535, 10.527415621266428, 10.969569830246915, 11.659018342391304, 10.05519244734931, 4.778592249657065, 4.441730210602761, 3.662937242798354, 5.1499871399176955, 2.1612563543936103, 1.682549175970229, 0.9849767164825647, 0.0, 13.50406539351852, 10.83474388130821, 8.412745879851144, 6.48376906318083, 10.299974279835391, 5.128112139917696, 4.441730210602761, 3.4132801783264752, 5.027596223674655, 3.886339447463769, 2.1939139660493834, 0.9570377837514936, 0.0), (13.39726296892706, 10.470616834815702, 10.946390332075904, 11.627068654388085, 10.036734581349688, 4.766900759538689, 4.4210506199736415, 3.6499393385154706, 5.139775259106843, 2.153148856074666, 1.67569258176305, 0.9819936907884712, 0.0, 13.476700638717421, 10.801930598673183, 8.378462908815248, 6.459446568223997, 10.279550518213686, 5.109915073921659, 4.4210506199736415, 3.4049291139562063, 5.018367290674844, 3.875689551462696, 2.189278066415181, 0.9518742577105185, 0.0), (13.3545938211964, 10.413967285056863, 10.923035593850026, 11.59505217894525, 10.018231528551063, 4.755367598943252, 4.400392977218323, 3.6372359015394005, 5.129612669562567, 2.145022560047339, 1.6689081004981592, 0.9790039267120707, 0.0, 13.449317879801098, 10.769043193832776, 8.344540502490794, 6.435067680142016, 10.259225339125134, 5.092130262155161, 4.400392977218323, 3.3966911421023225, 5.009115764275531, 3.865017392981751, 2.1846071187700056, 0.9467242986415331, 0.0), (13.312113043478263, 10.357493548387097, 10.899510416666669, 11.562990896739132, 9.999705882352941, 4.744016666666668, 4.379764705882353, 3.6248333333333345, 5.119508333333334, 2.1368776470588244, 1.662205821371611, 0.9760087719298248, 0.0, 13.421953125000002, 10.736096491228071, 8.311029106858054, 6.4106329411764715, 10.239016666666668, 5.074766666666668, 4.379764705882353, 3.3885833333333344, 4.999852941176471, 3.854330298913045, 2.179902083333334, 0.9415903225806455, 0.0), (13.26988476173436, 10.301222201203595, 10.87581960162323, 11.530906788446053, 9.98118023615482, 4.732871861504853, 4.359173229511284, 3.612738035360464, 5.109471212467612, 2.1287142978563174, 1.6555958335794598, 0.9730095741181947, 0.0, 13.394642382544584, 10.70310531530014, 8.277979167897298, 6.386142893568951, 10.218942424935223, 5.05783324950465, 4.359173229511284, 3.3806227582177515, 4.99059011807741, 3.8436355961486854, 2.1751639203246462, 0.9364747455639633, 0.0), (13.227973101926404, 10.245179819903537, 10.851967949817103, 11.498821834742351, 9.962677183356197, 4.721957082253722, 4.3386259716506625, 3.6009564090839814, 5.099510269013869, 2.1205326931870148, 1.6490882263177586, 0.9700076809536419, 0.0, 13.367421660665297, 10.670084490490058, 8.245441131588793, 6.361598079561043, 10.199020538027739, 5.041338972717574, 4.3386259716506625, 3.372826487324087, 4.981338591678099, 3.832940611580785, 2.170393589963421, 0.9313799836275944, 0.0), (13.186442190016104, 10.189392980884113, 10.827960262345682, 11.46675801630435, 9.944219317356573, 4.711296227709192, 4.318130355846042, 3.5894948559670787, 5.089634465020577, 2.1123330137981124, 1.6426930887825626, 0.9670044401126275, 0.0, 13.340326967592594, 10.6370488412389, 8.213465443912813, 6.336999041394336, 10.179268930041154, 5.02529279835391, 4.318130355846042, 3.3652115912208513, 4.972109658678287, 3.8222526721014507, 2.1655920524691368, 0.9263084528076467, 0.0), (13.14535615196517, 10.133888260542502, 10.803801340306359, 11.434737313808373, 9.925829231555449, 4.700913196667176, 4.297693805642971, 3.5783597774729468, 5.079852762536198, 2.1041154404368063, 1.6364205101699256, 0.9640011992716131, 0.0, 13.313394311556928, 10.604013191987741, 8.182102550849628, 6.312346321310418, 10.159705525072397, 5.0097036884621255, 4.297693805642971, 3.357795140476554, 4.962914615777724, 3.8115791046027923, 2.160760268061272, 0.9212625691402275, 0.0), (13.104705913184263, 10.078784894108638, 10.779554132960747, 11.402825576616644, 9.907497301495457, 4.690826978191853, 4.277368174559739, 3.5675806651220205, 5.07019931192069, 2.095906657814456, 1.6302822447690024, 0.9610058425921835, 0.0, 13.286621461180511, 10.571064268514016, 8.151411223845011, 6.287719973443367, 10.14039862384138, 4.9946129311708285, 4.277368174559739, 3.3505906987084666, 4.953748650747729, 3.8009418588722155, 2.15591082659215, 0.9162531721916946, 0.0), (13.064073257060091, 10.024626385524439, 10.755553287525224, 11.371278892341204, 9.88903379759524, 4.681014596966087, 4.257412745887406, 3.557289901377987, 5.060822216666095, 2.0878603087694745, 1.6242903453264128, 0.9580564200798471, 0.0, 13.25978557982405, 10.538620620878318, 8.121451726632063, 6.263580926308422, 10.12164443333219, 4.980205861929182, 4.257412745887406, 3.3435818549757763, 4.94451689879762, 3.790426297447069, 2.1511106575050447, 0.9113296714113127, 0.0), (13.023338864205595, 9.97143223830991, 10.731813088158539, 11.340088730440868, 9.870380499362694, 4.671450535207326, 4.2378417551340934, 3.547484881662581, 5.051724990045435, 2.0799888647958276, 1.6184360526663222, 0.9551543846318662, 0.0, 13.232809284324528, 10.506698230950526, 8.09218026333161, 6.239966594387481, 10.10344998009087, 4.966478834327614, 4.2378417551340934, 3.336750382290947, 4.935190249681347, 3.780029576813624, 2.146362617631708, 0.9064938398463556, 0.0), (12.982451822532688, 9.919124960991017, 10.708287554981187, 11.309199457779725, 9.851509291291528, 4.662112249784464, 4.218623372269525, 3.5381385158577467, 5.042884624972988, 2.072277675457342, 1.6127080506300124, 0.9522943730401906, 0.0, 13.205650163658248, 10.475238103442095, 8.063540253150062, 6.216833026372026, 10.085769249945976, 4.953393922200846, 4.218623372269525, 3.330080178417474, 4.925754645645764, 3.7697331525932425, 2.1416575109962372, 0.9017386328173653, 0.0), (12.941361219953283, 9.867627062093726, 10.68493070811365, 11.278555441221856, 9.832392057875436, 4.652977197566394, 4.199725767263427, 3.529223713845425, 5.034278114363028, 2.0647120903178457, 1.6070950230587664, 0.949471022096771, 0.0, 13.178265806801516, 10.44418124306448, 8.035475115293831, 6.1941362709535355, 10.068556228726056, 4.940913199383595, 4.199725767263427, 3.3235551411188533, 4.916196028937718, 3.7595184804072863, 2.1369861416227303, 0.8970570056448843, 0.0), (12.900016144379297, 9.816861050144, 10.66169656767643, 11.248101047631351, 9.81300068360812, 4.644022835422014, 4.181117110085521, 3.5207133855075567, 5.025882451129837, 2.0572774589411664, 1.6015856537938657, 0.9466789685935577, 0.0, 13.150613802730636, 10.413468654529133, 8.007928268969328, 6.171832376823498, 10.051764902259674, 4.92899873971058, 4.181117110085521, 3.317159168158581, 4.90650034180406, 3.7493670158771177, 2.132339313535286, 0.8924419136494547, 0.0), (12.858365683722639, 9.766749433667803, 10.638539153790012, 11.217780643872292, 9.793307052983273, 4.635226620220214, 4.162765570705529, 3.512580440726085, 5.017674628187687, 2.0499591308911307, 1.5961686266765933, 0.9439128493225009, 0.0, 13.122651740421906, 10.383041342547507, 7.980843133382966, 6.149877392673391, 10.035349256375374, 4.91761261701652, 4.162765570705529, 3.310876157300153, 4.896653526491637, 3.7392602146240983, 2.1277078307580024, 0.8878863121516185, 0.0), (12.816358925895228, 9.717214721191104, 10.61541248657489, 11.187538596808764, 9.773283050494598, 4.626566008829889, 4.144639319093177, 3.5047977893829505, 5.009631638450861, 2.0427424557315677, 1.5908326255482306, 0.9411673010755515, 0.0, 13.094337208851638, 10.352840311831065, 7.954163127741153, 6.128227367194702, 10.019263276901722, 4.906716905136131, 4.144639319093177, 3.3046900063070637, 4.886641525247299, 3.729179532269589, 2.1230824973149782, 0.8833831564719186, 0.0), (12.773944958808976, 9.668179421239865, 10.592270586151553, 11.157319273304857, 9.75290056063579, 4.618018458119934, 4.126706525218187, 3.4973383413600962, 5.001730474833633, 2.035612783026304, 1.5855663342500608, 0.9384369606446594, 0.0, 13.065627796996127, 10.322806567091252, 7.927831671250303, 6.106838349078911, 10.003460949667266, 4.8962736779041345, 4.126706525218187, 3.29858461294281, 4.876450280317895, 3.719106424434953, 2.118454117230311, 0.878925401930897, 0.0), (12.731072870375797, 9.61956604234005, 10.569067472640498, 11.127067040224649, 9.732131467900551, 4.609561424959241, 4.108935359050283, 3.490175006539462, 4.993948130250281, 2.0285554623391677, 1.5803584366233656, 0.9357164648217753, 0.0, 13.036481093831679, 10.292881113039527, 7.901792183116827, 6.085666387017502, 9.987896260500563, 4.886245009155247, 4.108935359050283, 3.2925438749708866, 4.8660657339502755, 3.7090223467415506, 2.1138134945280997, 0.8745060038490956, 0.0), (12.687691748507607, 9.571297093017627, 10.54575716616221, 11.09672626443223, 9.71094765678258, 4.601172366216706, 4.091293990559188, 3.4832806948029904, 4.986261597615085, 2.021555843233986, 1.5751976165094272, 0.9330004503988493, 0.0, 13.0068546883346, 10.263004954387341, 7.875988082547136, 6.064667529701957, 9.97252319523017, 4.876592972724187, 4.091293990559188, 3.28655169015479, 4.85547382839129, 3.698908754810744, 2.109151433232442, 0.8701179175470571, 0.0), (12.643750681116316, 9.523295081798558, 10.522293686837184, 11.066241312791686, 9.689321011775569, 4.592828738761221, 4.073750589714624, 3.476628316032624, 4.97864786984232, 2.014599275274587, 1.5700725577495283, 0.9302835541678323, 0.0, 12.976706169481197, 10.233119095846153, 7.85036278874764, 6.04379782582376, 9.95729573968464, 4.8672796424456735, 4.073750589714624, 3.280591956258015, 4.844660505887784, 3.6887471042638964, 2.104458737367437, 0.8657540983453236, 0.0), (12.599198756113843, 9.475482517208812, 10.498631054785912, 11.0355565521671, 9.667223417373222, 4.584507999461682, 4.056273326486318, 3.4701907801103036, 4.971083939846263, 2.0076711080247973, 1.5649719441849508, 0.927560412920674, 0.0, 12.94599312624776, 10.203164542127412, 7.824859720924753, 6.023013324074391, 9.942167879692526, 4.858267092154425, 4.056273326486318, 3.2746485710440583, 4.833611708686611, 3.678518850722367, 2.0997262109571824, 0.8614075015644376, 0.0), (12.553985061412101, 9.427781907774351, 10.474723290128884, 11.004616349422557, 9.644626758069233, 4.5761876051869805, 4.038830370843989, 3.463940996917971, 4.963546800541195, 2.0007566910484456, 1.5598844596569765, 0.9248256634493257, 0.0, 12.91467314761061, 10.173082297942582, 7.799422298284883, 6.002270073145335, 9.92709360108239, 4.849517395685159, 4.038830370843989, 3.268705432276415, 4.822313379034616, 3.66820544980752, 2.094944658025777, 0.8570710825249411, 0.0), (12.508058684923006, 9.380115762021138, 10.450524412986589, 10.973365071422144, 9.621502918357304, 4.567845012806012, 4.021389892757366, 3.4578518763375685, 4.95601344484139, 1.993841373909359, 1.5547987880068885, 0.9220739425457369, 0.0, 12.88270382254604, 10.142813368003106, 7.773993940034442, 5.981524121728076, 9.91202688968278, 4.8409926268725965, 4.021389892757366, 3.26274643771858, 4.810751459178652, 3.6577883571407157, 2.090104882597318, 0.8527377965473764, 0.0), (12.461368714558466, 9.332406588475143, 10.425988443479525, 10.941747085029949, 9.597823782731137, 4.5594576791876715, 4.003920062196168, 3.451896328251037, 4.948460865661126, 1.986910506171365, 1.5497036130759692, 0.9192998870018588, 0.0, 12.850042740030352, 10.112298757020445, 7.748518065379845, 5.960731518514094, 9.896921731322252, 4.832654859551452, 4.003920062196168, 3.2567554851340508, 4.798911891365568, 3.6472490283433174, 2.085197688695905, 0.8484005989522859, 0.0), (12.413864238230394, 9.284576895662326, 10.401069401728181, 10.909706757110053, 9.573561235684425, 4.551003061200851, 3.9863890491301195, 3.446047262540319, 4.9408660559146815, 1.9799494373982915, 1.5445876187055003, 0.916498133609641, 0.0, 12.816647489039854, 10.08147946970605, 7.7229380935275005, 5.939848312194873, 9.881732111829363, 4.824466167556446, 3.9863890491301195, 3.250716472286322, 4.786780617842212, 3.636568919036685, 2.0802138803456365, 0.8440524450602116, 0.0), (12.365494343850713, 9.236549192108656, 10.375721307853043, 10.877188454526541, 9.548687161710866, 4.542458615714445, 3.968765023528944, 3.440277589087355, 4.933206008516334, 1.9729435171539655, 1.539439488736764, 0.9136633191610346, 0.0, 12.78247565855085, 10.050296510771378, 7.697197443683819, 5.9188305514618955, 9.866412017032667, 4.816388624722297, 3.968765023528944, 3.244613296938889, 4.774343580855433, 3.6257294848421813, 2.075144261570609, 0.8396862901916962, 0.0), (12.316208119331334, 9.188245986340096, 10.349898181974611, 10.8441365441435, 9.523173445304161, 4.533801799597346, 3.9510161553623666, 3.4345602177740875, 4.92545771638036, 1.9658780950022154, 1.5342479070110426, 0.9107900804479897, 0.0, 12.747484837539638, 10.018690884927885, 7.671239535055213, 5.897634285006645, 9.85091543276072, 4.808384304883723, 3.9510161553623666, 3.238429856855247, 4.761586722652081, 3.614712181381168, 2.0699796363949226, 0.8352950896672816, 0.0), (12.265954652584163, 9.139589786882611, 10.32355404421337, 10.810495392825016, 9.49699197095801, 4.525010069718451, 3.9331106146001082, 3.4288680584824593, 4.917598172421039, 1.9587385205068681, 1.5290015573696185, 0.9078730542624567, 0.0, 12.711632614982527, 9.986603596887022, 7.645007786848092, 5.876215561520603, 9.835196344842078, 4.800415281875443, 3.9331106146001082, 3.2321500497988938, 4.748495985479005, 3.6034984642750065, 2.0647108088426744, 0.8308717988075103, 0.0), (12.21468303152113, 9.090503102262165, 10.296642914689816, 10.776209367435175, 9.470114623166108, 4.516060882946651, 3.915016571211893, 3.4231740210944106, 4.909604369552646, 1.9515101432317519, 1.5236891236537742, 0.904906877396386, 0.0, 12.674876579855821, 9.953975651360244, 7.618445618268871, 5.854530429695254, 9.819208739105292, 4.792443629532175, 3.915016571211893, 3.2257577735333225, 4.735057311583054, 3.5920697891450595, 2.059328582937963, 0.8264093729329243, 0.0), (12.162342344054133, 9.040908441004726, 10.26911881352444, 10.741222834838059, 9.442513286422153, 4.5069316961508425, 3.896702195167445, 3.4174510154918845, 4.90145330068946, 1.9441783127406937, 1.518299289704792, 0.9018861866417278, 0.0, 12.637174321135817, 9.920748053059004, 7.5914964485239596, 5.83253493822208, 9.80290660137892, 4.784431421688638, 3.896702195167445, 3.21923692582203, 4.721256643211077, 3.5804076116126873, 2.053823762704888, 0.8219007673640661, 0.0), (12.108881678095097, 8.990728311636257, 10.24093576083773, 10.705480161897759, 9.414159845219846, 4.4975999661999175, 3.8781356564364877, 3.4116719515568206, 4.893121958745757, 1.9367283785975222, 1.5128207393639534, 0.898805618790433, 0.0, 12.59848342779883, 9.88686180669476, 7.5641036968197675, 5.810185135792565, 9.786243917491515, 4.776340732179549, 3.8781356564364877, 3.212571404428512, 4.707079922609923, 3.5684933872992537, 2.048187152167546, 0.817338937421478, 0.0), (12.05425012155593, 8.93988522268272, 10.212047776750177, 10.668925715478352, 9.385026184052883, 4.488043149962771, 3.8592851249887445, 3.4058097391711617, 4.884587336635816, 1.9291456903660635, 1.5072421564725416, 0.8956598106344515, 0.0, 12.558761488821151, 9.852257916978965, 7.536210782362707, 5.787437071098189, 9.769174673271632, 4.768133634839627, 3.8592851249887445, 3.205745107116265, 4.6925130920264415, 3.556308571826118, 2.042409555350036, 0.812716838425702, 0.0), (11.998396762348548, 8.888301682670086, 10.18240888138228, 10.631503862443932, 9.355084187414965, 4.478238704308296, 3.8401187707939393, 3.399837288216851, 4.875826427273916, 1.9214155976101461, 1.5015522248718383, 0.8924433989657341, 0.0, 12.517966093179089, 9.816877388623073, 7.507761124359191, 5.764246792830437, 9.751652854547832, 4.759772203503592, 3.8401187707939393, 3.1987419316487826, 4.6775420937074825, 3.543834620814645, 2.036481776276456, 0.8080274256972807, 0.0), (11.941270688384867, 8.835900200124316, 10.15197309485452, 10.593158969658578, 9.32430573979979, 4.4681640861053875, 3.8206047638217933, 3.393727508575828, 4.8668162235743315, 1.913523449893597, 1.4957396284031257, 0.889151020576231, 0.0, 12.476054829848946, 9.78066122633854, 7.478698142015627, 5.740570349680789, 9.733632447148663, 4.751218512006159, 3.8206047638217933, 3.1915457757895624, 4.662152869899895, 3.5310529898861933, 2.0303946189709046, 0.8032636545567561, 0.0), (11.882820987576796, 8.782603283571376, 10.120694437287398, 10.553835403986378, 9.292662725701055, 4.457796752222938, 3.800711274042032, 3.3874533101300353, 4.85753371845134, 1.9054545967802445, 1.4897930509076862, 0.8857773122578926, 0.0, 12.432985287807028, 9.743550434836816, 7.448965254538431, 5.716363790340733, 9.71506743690268, 4.742434634182049, 3.800711274042032, 3.184140537302099, 4.646331362850527, 3.517945134662127, 2.0241388874574797, 0.7984184803246707, 0.0), (11.822996747836257, 8.72833344153723, 10.088526928801404, 10.513477532291418, 9.26012702961246, 4.447114159529844, 3.780406471424378, 3.3809876027614147, 4.847955904819222, 1.8971943878339157, 1.4837011762268022, 0.8823169108026693, 0.0, 12.38871505602964, 9.70548601882936, 7.41850588113401, 5.691583163501746, 9.695911809638444, 4.733382643865981, 3.780406471424378, 3.176510113949888, 4.63006351480623, 3.5044925107638067, 2.017705385760281, 0.7934848583215663, 0.0), (11.761747057075162, 8.673013182547843, 10.055424589517022, 10.472029721437782, 9.226670536027703, 4.436093764894997, 3.7596585259385567, 3.374303296351908, 4.838059775592251, 1.8887281726184386, 1.477452688201756, 0.8787644530025115, 0.0, 12.34320172349308, 9.666408983027624, 7.38726344100878, 5.6661845178553145, 9.676119551184502, 4.724024614892672, 3.7596585259385567, 3.168638403496426, 4.613335268013851, 3.490676573812595, 2.0110849179034047, 0.7884557438679859, 0.0), (11.69902100320542, 8.616565015129181, 10.02134143955475, 10.429436338289557, 9.192265129440482, 4.424713025187291, 3.7384356075542886, 3.367373300783457, 4.827822323684707, 1.8800413006976404, 1.4710362706738296, 0.8751145756493696, 0.0, 12.296402879173653, 9.626260332143064, 7.355181353369148, 5.64012390209292, 9.655644647369414, 4.71432262109684, 3.7384356075542886, 3.160509303705208, 4.596132564720241, 3.4764787794298533, 2.0042682879109504, 0.7833240922844712, 0.0), (11.634767674138946, 8.558911447807208, 9.986231499035082, 10.385641749710825, 9.156882694344494, 4.412949397275621, 3.7167058862412983, 3.360170525938002, 4.817220542010869, 1.871119121635349, 1.4644406074843055, 0.8713619155351939, 0.0, 12.248276112047666, 9.584981070887132, 7.322203037421526, 5.6133573649060455, 9.634441084021738, 4.704238736313203, 3.7167058862412983, 3.1521067123397293, 4.578441347172247, 3.4618805832369426, 1.9972462998070164, 0.7780828588915646, 0.0), (11.56893615778766, 8.499974989107892, 9.950048788078501, 10.340590322565676, 9.12049511523344, 4.400780338028881, 3.6944375319693092, 3.3526678816974873, 4.806231423485011, 1.8619469849953916, 1.4576543824744654, 0.867501109451935, 0.0, 12.198779011091421, 9.542512203971285, 7.288271912372326, 5.585840954986173, 9.612462846970022, 4.693735034376482, 3.6944375319693092, 3.1434145271634857, 4.56024755761672, 3.446863440855226, 1.9900097576157, 0.7727249990098085, 0.0), (11.501475542063469, 8.439678147557194, 9.912747326805505, 10.294226423718191, 9.083074276601018, 4.388183304315964, 3.6715987147080456, 3.344838277943853, 4.794831961021412, 1.8525102403415963, 1.4506662794855925, 0.8635267941915434, 0.0, 12.14786916528122, 9.498794736106976, 7.253331397427962, 5.557530721024787, 9.589663922042824, 4.682773589121394, 3.6715987147080456, 3.1344166459399743, 4.541537138300509, 3.4314088079060645, 1.9825494653611013, 0.7672434679597451, 0.0), (11.432334914878291, 8.377943431681082, 9.874281135336586, 10.246494420032459, 9.044592062940927, 4.375135753005765, 3.6481576044272312, 3.336654624559041, 4.782999147534349, 1.8427942372377903, 1.4434649823589683, 0.8594336065459691, 0.0, 12.095504163593366, 9.453769672005658, 7.21732491179484, 5.52838271171337, 9.565998295068699, 4.671316474382658, 3.6481576044272312, 3.125096966432689, 4.522296031470463, 3.41549814001082, 1.9748562270673173, 0.7616312210619166, 0.0), (11.361463364144042, 8.314693350005518, 9.83460423379223, 10.19733867837256, 9.005020358746862, 4.361615140967176, 3.6240823710965873, 3.3280898314249927, 4.770709975938102, 1.8327843252478015, 1.4360391749358754, 0.855216183307163, 0.0, 12.041641595004167, 9.407378016378791, 7.180195874679377, 5.498352975743403, 9.541419951876204, 4.65932576399499, 3.6240823710965873, 3.1154393864051255, 4.502510179373431, 3.3991128927908543, 1.966920846758446, 0.7558812136368653, 0.0), (11.288809977772631, 8.24985041105647, 9.793670642292932, 10.146703565602587, 8.964331048512523, 4.347598925069094, 3.599341184685839, 3.3191168084236504, 4.757941439146947, 1.822465853935457, 1.428377541057596, 0.8508691612670749, 0.0, 11.986239048489919, 9.359560773937822, 7.141887705287981, 5.4673975618063695, 9.515882878293894, 4.646763531793111, 3.599341184685839, 3.105427803620781, 4.482165524256262, 3.38223452186753, 1.9587341284585866, 0.7499864010051337, 0.0), (11.214323843675977, 8.1833371233599, 9.751434380959186, 10.094533448586619, 8.922496016731612, 4.33306456218041, 3.573902215164709, 3.3097084654369557, 4.744670530075158, 1.8118241728645852, 1.4204687645654126, 0.8463871772176558, 0.0, 11.929254113026934, 9.310258949394212, 7.102343822827062, 5.4354725185937545, 9.489341060150316, 4.6335918516117385, 3.573902215164709, 3.09504611584315, 4.461248008365806, 3.3648444828622073, 1.950286876191837, 0.7439397384872637, 0.0), (11.137954049765991, 8.115075995441773, 9.707849469911476, 10.040772694188746, 8.879487147897825, 4.317989509170021, 3.5477336325029207, 3.29983771234685, 4.730874241637018, 1.8008446315990123, 1.412301529300607, 0.8417648679508558, 0.0, 11.870644377591507, 9.259413547459413, 7.061507646503035, 5.402533894797036, 9.461748483274036, 4.61977279728559, 3.5477336325029207, 3.084278220835729, 4.439743573948912, 3.3469242313962493, 1.9415698939822956, 0.7377341814037977, 0.0), (11.059649683954586, 8.044989535828057, 9.6628699292703, 9.985365669273047, 8.835276326504857, 4.302351222906816, 3.5208036066701984, 3.2894774590352758, 4.716529566746802, 1.789512579702568, 1.4038645191044614, 0.8369968702586252, 0.0, 11.810367431159946, 9.206965572844876, 7.019322595522306, 5.368537739107703, 9.433059133493604, 4.605268442649386, 3.5208036066701984, 3.0731080163620117, 4.417638163252429, 3.3284552230910167, 1.9325739858540603, 0.731362685075278, 0.0), (10.979359834153682, 7.973000253044715, 9.616449779156152, 9.928256740703617, 8.789835437046412, 4.286127160259694, 3.4930803076362653, 3.2786006153841747, 4.701613498318786, 1.7778133667390779, 1.3951464178182584, 0.8320778209329146, 0.0, 11.748380862708558, 9.15285603026206, 6.975732089091292, 5.333440100217232, 9.403226996637573, 4.590040861537845, 3.4930803076362653, 3.061519400185496, 4.394917718523206, 3.309418913567873, 1.9232899558312306, 0.7248182048222469, 0.0), (10.897033588275185, 7.899030655617714, 9.568543039689514, 9.86939027534453, 8.743136364016186, 4.269294778097547, 3.4645319053708437, 3.2671800912754865, 4.686103029267251, 1.7657323422723707, 1.3861359092832806, 0.8270023567656742, 0.0, 11.68464226121364, 9.097025924422415, 6.930679546416402, 5.297197026817111, 9.372206058534502, 4.574052127785681, 3.4645319053708437, 3.049496270069676, 4.371568182008093, 3.2897967584481775, 1.9137086079379029, 0.7180936959652467, 0.0), (10.81262003423102, 7.823003252073014, 9.519103730990887, 9.80871064005988, 8.695150991907875, 4.251831533289268, 3.43512656984366, 3.2551887965911552, 4.6699751525064706, 1.7532548558662742, 1.3768216773408095, 0.8217651145488547, 0.0, 11.6191092156515, 9.0394162600374, 6.884108386704048, 5.259764567598821, 9.339950305012941, 4.557264315227617, 3.43512656984366, 3.037022523778049, 4.347575495953937, 3.2695702133532945, 1.9038207461981775, 0.7111821138248196, 0.0), (10.72606825993309, 7.744840550936584, 9.468085873180756, 9.746162201713748, 8.645851205215184, 4.233714882703753, 3.404832471024433, 3.2425996412131215, 4.653206860950727, 1.7403662570846146, 1.3671924058321279, 0.8163607310744064, 0.0, 11.551739314998438, 8.97996804181847, 6.8359620291606396, 5.221098771253843, 9.306413721901453, 4.53963949769837, 3.404832471024433, 3.0240820590741087, 4.322925602607592, 3.2487207339045834, 1.8936171746361512, 0.7040764137215078, 0.0), (10.637327353293314, 7.664465060734389, 9.415443486379615, 9.68168932717022, 8.595208888431804, 4.214922283209894, 3.37361777888289, 3.2293855350233276, 4.635775147514292, 1.727051895491221, 1.357236778598518, 0.8107838431342794, 0.0, 11.48249014823076, 8.918622274477073, 6.7861838929925895, 5.181155686473662, 9.271550295028584, 4.521139749032659, 3.37361777888289, 3.0106587737213526, 4.297604444215902, 3.2272297757234076, 1.8830886972759233, 0.6967695509758537, 0.0), (10.546346402223609, 7.581799289992394, 9.361130590707957, 9.615236383293386, 8.543195926051439, 4.195431191676585, 3.3414506633887537, 3.215519387903715, 4.6176570051114485, 1.7132971206499201, 1.3469434794812618, 0.8050290875204243, 0.0, 11.411319304324769, 8.855319962724668, 6.734717397406309, 5.1398913619497595, 9.235314010222897, 4.501727143065201, 3.3414506633887537, 2.996736565483275, 4.2715979630257195, 3.205078794431129, 1.8722261181415913, 0.6892544809083996, 0.0), (10.450553324967336, 7.495248171657732, 9.302523946219415, 9.544258060733807, 8.48743569881293, 4.174003322325641, 3.3075747046495003, 3.200048222203801, 4.597442309412912, 1.698678070701901, 1.335972342259087, 0.7988866158226731, 0.0, 11.335080203181485, 8.787752774049402, 6.679861711295434, 5.096034212105701, 9.194884618825824, 4.480067511085322, 3.3075747046495003, 2.9814309445183147, 4.243717849406465, 3.1814193535779363, 1.8605047892438833, 0.6813861974234302, 0.0), (10.335201473769764, 7.395933826819331, 9.224527454803487, 9.454176016727876, 8.414178555796186, 4.143513212539135, 3.2677489343700015, 3.17754122744589, 4.566999388570334, 1.6807983479345614, 1.3223972849777657, 0.7911589610963629, 0.0, 11.235598705688274, 8.70274857205999, 6.611986424888827, 5.042395043803683, 9.133998777140668, 4.448557718424246, 3.2677489343700015, 2.9596522946708106, 4.207089277898093, 3.1513920055759597, 1.8449054909606977, 0.6723576206199392, 0.0), (10.198820932866035, 7.28304080162725, 9.125574450948537, 9.343506385929302, 8.321992122590341, 4.103212058438943, 3.221570623868649, 3.147432860557619, 4.525465106040038, 1.6594219781520132, 1.3060272186755595, 0.7817252273702489, 0.0, 11.110988852451014, 8.598977501072737, 6.530136093377798, 4.978265934456038, 9.050930212080075, 4.406406004780667, 3.221570623868649, 2.9308657560278157, 4.160996061295171, 3.114502128643102, 1.8251148901897079, 0.6620946183297501, 0.0), (10.042510876420344, 7.1573051140366015, 9.006721467228694, 9.213301128944565, 8.211833582663305, 4.053588080615757, 3.1693770122048135, 3.1101003109807053, 4.473387224599541, 1.6347303676098288, 1.2870063860732652, 0.77067287137255, 0.0, 10.962523662746737, 8.477401585098049, 6.435031930366326, 4.904191102829485, 8.946774449199083, 4.354140435372988, 3.1693770122048135, 2.8954200575826836, 4.105916791331652, 3.071100376314856, 1.801344293445739, 0.6506641012760548, 0.0), (9.8673704785969, 7.01946278200249, 8.86902503621808, 9.064612206380144, 8.08466011948299, 3.9951294996602726, 3.1115053384378664, 3.0659207681568685, 4.411313507026364, 1.6069049225635816, 1.2654790298916783, 0.7580893498314843, 0.0, 10.791476155852466, 8.338982848146326, 6.3273951494583915, 4.820714767690744, 8.822627014052728, 4.292289075419616, 3.1115053384378664, 2.8536639283287664, 4.042330059741495, 3.0215374021267154, 1.773805007243616, 0.6381329801820447, 0.0), (9.674498913559898, 6.870249823480022, 8.71354169049082, 8.898491578842531, 7.941428916517308, 3.928324536163185, 3.048292841627181, 3.015271421527823, 4.339791716098023, 1.5761270492688444, 1.2415893928515955, 0.7440621194752707, 0.0, 10.599119351045232, 8.184683314227977, 6.207946964257977, 4.728381147806532, 8.679583432196045, 4.221379990138953, 3.048292841627181, 2.8059460972594175, 3.970714458258654, 2.9661638596141775, 1.742708338098164, 0.6245681657709112, 0.0), (9.464995355473539, 6.710402256424303, 8.54132796262104, 8.71599120693821, 7.783097157234176, 3.853661410715189, 2.9800767608321266, 2.9585294605352903, 4.259369614592037, 1.5425781539811894, 1.2154817176738126, 0.7286786370321272, 0.0, 10.386726267602059, 8.015465007353399, 6.077408588369063, 4.627734461943566, 8.518739229184074, 4.141941244749407, 2.9800767608321266, 2.752615293367992, 3.891548578617088, 2.905330402312737, 1.7082655925242083, 0.6100365687658459, 0.0), (9.239958978502024, 6.5406560987904445, 8.353440385182864, 8.518163051273666, 7.610622025101502, 3.771628343906979, 2.9071943351120755, 2.8960720746209856, 4.1705949652859235, 1.5064396429561904, 1.1873002470791263, 0.7120263592302724, 0.0, 10.155569924799979, 7.832289951532995, 5.936501235395631, 4.51931892886857, 8.341189930571847, 4.05450090446938, 2.9071943351120755, 2.694020245647842, 3.805311012550751, 2.839387683757889, 1.670688077036573, 0.5946050998900405, 0.0), (9.000488956809557, 6.361747368533551, 8.150935490750417, 8.306059072455376, 7.4249607035872005, 3.682713556329251, 2.8299828035264003, 2.8282764532266285, 4.074015530957201, 1.4678929224494195, 1.157189223788332, 0.6941927427979253, 0.0, 9.906923341916015, 7.636120170777177, 5.78594611894166, 4.403678767348258, 8.148031061914402, 3.95958703451728, 2.8299828035264003, 2.630509683092322, 3.7124803517936003, 2.768686357485126, 1.6301870981500834, 0.5783406698666865, 0.0), (8.747684464560333, 6.174412083608727, 7.934869811897824, 8.080731231089835, 7.2270703761591815, 3.5874052685726983, 2.7487794051344725, 2.7555197857939366, 3.9701790743833865, 1.4271193987164503, 1.1252928905222266, 0.6752652444633036, 0.0, 9.642059538227196, 7.427917689096338, 5.626464452611132, 4.28135819614935, 7.940358148766773, 3.8577277001115116, 2.7487794051344725, 2.562432334694784, 3.6135351880795907, 2.693577077029946, 1.5869739623795647, 0.5613101894189753, 0.0), (8.482644675918554, 5.979386261971081, 7.706299881199207, 7.843231487783524, 7.017908226285359, 3.4861917012280164, 2.663921378995663, 2.6781792617646265, 3.8596333583419993, 1.3843004780128556, 1.0917554900016058, 0.6553313209546264, 0.0, 9.362251533010546, 7.20864453050089, 5.458777450008029, 4.152901434038566, 7.7192667166839986, 3.7494509664704774, 2.663921378995663, 2.490136929448583, 3.5089541131426794, 2.614410495927842, 1.5412599762398416, 0.5435805692700985, 0.0), (8.206468765048422, 5.777405921575724, 7.466282231228694, 7.594611803142927, 6.798431437433646, 3.3795610748859013, 2.5757459641693443, 2.5966320705804184, 3.7429261456105576, 1.339617566594208, 1.0567212649472661, 0.6344784290001119, 0.0, 9.0687723455431, 6.9792627190012295, 5.28360632473633, 4.018852699782624, 7.485852291221115, 3.635284898812586, 2.5757459641693443, 2.413972196347072, 3.399215718716823, 2.5315372677143095, 1.493256446245739, 0.5252187201432478, 0.0), (7.9202559061141375, 5.569207080377758, 7.215873394560408, 7.335924137774526, 6.569597193071951, 3.268001610137046, 2.4845903997148873, 2.5112554016830275, 3.620605198966578, 1.2932520707160806, 1.020334458080004, 0.6127940253279787, 0.0, 8.762894995101878, 6.740734278607764, 5.101672290400019, 3.879756212148241, 7.241210397933156, 3.5157575623562387, 2.4845903997148873, 2.3342868643836043, 3.2847985965359756, 2.4453080459248424, 1.4431746789120816, 0.5062915527616144, 0.0), (7.6251052732799005, 5.355525756332291, 6.956129903768475, 7.068220452284813, 6.3323626766681915, 3.152001527572146, 2.390791924691664, 2.4224264445141737, 3.4932182811875796, 1.2453853966340462, 0.9827393121206148, 0.5903655666664452, 0.0, 8.445892500963913, 6.494021233330896, 4.913696560603074, 3.736156189902138, 6.986436562375159, 3.3913970223198433, 2.390791924691664, 2.2514296625515327, 3.1661813383340958, 2.356073484094938, 1.391225980753695, 0.4868659778483902, 0.0), (7.322116040709912, 5.137097967394431, 6.688108291427019, 6.792552707280267, 6.087685071690277, 3.0320490477818964, 2.2946877781590462, 2.3305223885155746, 3.3613131550510804, 1.1961989506036783, 0.9440800697898953, 0.56728050974373, 0.0, 8.119037882406225, 6.24008560718103, 4.720400348949476, 3.588596851811034, 6.722626310102161, 3.2627313439218044, 2.2946877781590462, 2.165749319844212, 3.0438425358451386, 2.2641842357600894, 1.337621658285404, 0.4670089061267665, 0.0), (7.012387382568372, 4.914659731519285, 6.412865090110164, 6.509972863367375, 5.836521561606121, 2.9086323913569916, 2.196615199176405, 2.235920423128947, 3.225437583334597, 1.145874138880549, 0.9045009738086416, 0.5436263112880514, 0.0, 7.783604158705848, 5.979889424168563, 4.522504869043208, 3.437622416641646, 6.450875166669194, 3.130288592380526, 2.196615199176405, 2.077594565254994, 2.9182607808030605, 2.169990954455792, 1.282573018022033, 0.446787248319935, 0.0), (6.697018473019482, 4.6889470666619575, 6.131456832392036, 6.221532881152618, 5.579829329883635, 2.7822397788881266, 2.096911426803113, 2.1389977377960108, 3.08613932881565, 1.0945923677202316, 0.8641462668976501, 0.519490428027628, 0.0, 7.440864349139807, 5.7143947083039075, 4.32073133448825, 3.283777103160694, 6.1722786576313, 2.994596832914415, 2.096911426803113, 1.9873141277772333, 2.7899146649418176, 2.07384429371754, 1.2262913664784072, 0.42626791515108714, 0.0), (6.377108486227438, 4.460695990777558, 5.84494005084676, 5.928284721242486, 5.318565559990731, 2.653359430965997, 1.9959137000985407, 2.040131521958481, 2.943966154271756, 1.0425350433782987, 0.8231601917777163, 0.49496031669067847, 0.0, 7.092091472985131, 5.444563483597462, 4.115800958888581, 3.1276051301348957, 5.887932308543512, 2.8561841307418736, 1.9959137000985407, 1.8952567364042836, 2.6592827799953653, 1.9760949070808291, 1.1689880101693522, 0.40551781734341447, 0.0), (6.053756596356447, 4.230642521821194, 5.554371278048459, 5.631280344243462, 5.053687435395322, 2.5224795681812964, 1.8939592581220606, 1.9396989650580787, 2.7994658224804327, 0.9898835721103237, 0.781686991169637, 0.470123434005421, 0.0, 6.738558549518844, 5.17135777405963, 3.9084349558481852, 2.9696507163309707, 5.5989316449608655, 2.71557855108131, 1.8939592581220606, 1.8017711201294973, 2.526843717697661, 1.8770934480811543, 1.1108742556096918, 0.38460386562010856, 0.0), (5.7280619775707065, 3.9995226777479713, 5.260807046571258, 5.331571710762027, 4.786152139565322, 2.3900884111247205, 1.791385339933044, 1.8380772565365193, 2.6531860962191995, 0.9368193601718788, 0.7398709077942084, 0.4450672367000743, 0.0, 6.381538598017975, 4.895739603700816, 3.699354538971042, 2.8104580805156356, 5.306372192438399, 2.5733081591511273, 1.791385339933044, 1.707206007946229, 2.393076069782661, 1.7771905702540096, 1.0521614093142517, 0.3635929707043611, 0.0), (5.401123804034416, 3.7680724765129963, 4.9653038889892835, 5.030210781404673, 4.516916855968639, 2.2566741803869648, 1.6885291845908623, 1.7356435858355217, 2.505674738265573, 0.8835238138185378, 0.6978561843722264, 0.41987918150285664, 0.0, 6.022304637759553, 4.618670996531422, 3.489280921861132, 2.6505714414556127, 5.011349476531146, 2.4299010201697304, 1.6885291845908623, 1.611910128847832, 2.2584584279843196, 1.6767369271348913, 0.9930607777978567, 0.34255204331936334, 0.0), (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), ) passenger_allighting_rate = ( (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), (0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), ) entropy = 8991598675325360468762009371570610170 child_seed_index = ( 1, 47, )
true
true
f716a1a5f632f06075f249c2221bcd21beac3b38
657
py
Python
odc_gee/setup.py
admariner/data_cube_notebooks
984a84b2f92114040e36a533d3f476dcf384695e
[ "Apache-2.0" ]
null
null
null
odc_gee/setup.py
admariner/data_cube_notebooks
984a84b2f92114040e36a533d3f476dcf384695e
[ "Apache-2.0" ]
null
null
null
odc_gee/setup.py
admariner/data_cube_notebooks
984a84b2f92114040e36a533d3f476dcf384695e
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='odc-gee', version='2.24', description='Google Earth Engine indexing tools for Open Data Cube', author='Andrew Lubawy', author_email='andrew.m.lubawy@ama-inc.com', install_requires=[ "google-auth>=1.11.0,<=1.32.0" "click-plugins>=1.1.1", "click>=7.1.2", "datacube>=1.8.3", "earthengine-api>=0.1.24", "numpy>=1.18.4", "rasterio>=1.1.8", "google-api-core==1.31.2" ], packages=find_packages(), scripts=['scripts/index_gee', 'scripts/new_product'],)
29.863636
74
0.564688
from setuptools import setup, find_packages setup(name='odc-gee', version='2.24', description='Google Earth Engine indexing tools for Open Data Cube', author='Andrew Lubawy', author_email='andrew.m.lubawy@ama-inc.com', install_requires=[ "google-auth>=1.11.0,<=1.32.0" "click-plugins>=1.1.1", "click>=7.1.2", "datacube>=1.8.3", "earthengine-api>=0.1.24", "numpy>=1.18.4", "rasterio>=1.1.8", "google-api-core==1.31.2" ], packages=find_packages(), scripts=['scripts/index_gee', 'scripts/new_product'],)
true
true
f716a22900c092bb89fd4f6f98a63d9202ab5429
7,980
py
Python
client/deploy_kafka.py
jzmq/minos
510b6e30758f4900a72fee1a5e6258bdc7c83f17
[ "Apache-2.0" ]
365
2015-01-26T13:56:42.000Z
2022-03-28T06:36:31.000Z
client/deploy_kafka.py
jzmq/minos
510b6e30758f4900a72fee1a5e6258bdc7c83f17
[ "Apache-2.0" ]
3
2015-12-29T07:44:24.000Z
2021-03-18T06:13:07.000Z
client/deploy_kafka.py
jzmq/minos
510b6e30758f4900a72fee1a5e6258bdc7c83f17
[ "Apache-2.0" ]
135
2015-01-31T00:46:51.000Z
2022-03-03T06:31:09.000Z
#!/usr/bin/env python import argparse import os import parallel_deploy import service_config import subprocess import sys import urlparse import deploy_utils from log import Log ALL_JOBS = ["kafka", "kafkascribe"] def _get_kafka_service_config(args): args.kafka_config = deploy_utils.get_service_config(args) def generate_configs(args, job_name, host_id, instance_id): kafka_cfg_dict = args.kafka_config.configuration.generated_files["kafka.cfg"] hosts = args.kafka_config.jobs[job_name].hosts kafka_cfg_dict["broker.id"] = deploy_utils.get_task_id(hosts, host_id, instance_id) kafka_cfg = deploy_utils.generate_properties_file(args, kafka_cfg_dict) kafka_scribe_cfg_dict = args.kafka_config.configuration.generated_files["kafka-scribe.cfg"] kafka_job = args.kafka_config.jobs["kafka"] kafka_scribe_cfg_dict["metadata.broker.list"] = ",".join( service_config.get_job_host_port_list(kafka_job)) kafka_scribe_cfg = deploy_utils.generate_properties_file(args, kafka_scribe_cfg_dict) config_files = { "kafka.cfg": kafka_cfg, "kafka-scribe.cfg": kafka_scribe_cfg, } config_files.update(args.kafka_config.configuration.raw_files) return config_files def generate_run_scripts_params(args, host, job_name, host_id, instance_id): job = args.kafka_config.jobs[job_name] supervisor_client = deploy_utils.get_supervisor_client(host, "kafka", args.kafka_config.cluster.name, job_name, instance_id=instance_id) artifact_and_version = "kafka-" + args.kafka_config.cluster.version jar_dirs = "$package_dir/*" log_level = deploy_utils.get_service_log_level(args, args.kafka_config) params = job.get_arguments(args, args.kafka_config.cluster, args.kafka_config.jobs, args.kafka_config.arguments_dict, job_name, host_id, instance_id) script_dict = { "artifact": artifact_and_version, "job_name": job_name, "jar_dirs": jar_dirs, "run_dir": supervisor_client.get_run_dir(), "params": params, } return script_dict def generate_start_script(args, host, job_name, host_id, instance_id): script_params = generate_run_scripts_params(args, host, job_name, host_id, instance_id) return deploy_utils.create_run_script( "%s/start.sh.tmpl" % deploy_utils.get_template_dir(), script_params) def install(args): _get_kafka_service_config(args) deploy_utils.install_service(args, "kafka", args.kafka_config, "kafka") def cleanup_job(args, host, job_name, host_id, instance_id, cleanup_token, active): deploy_utils.cleanup_job("kafka", args.kafka_config, host, job_name, instance_id, cleanup_token) def cleanup(args): _get_kafka_service_config(args) cleanup_token = deploy_utils.confirm_cleanup(args, "kafka", args.kafka_config) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'cleanup', cleanup_token=cleanup_token) parallel_deploy.start_deploy_threads(cleanup_job, task_list) def bootstrap_job(args, host, job_name, host_id, instance_id, cleanup_token, active): # parse the service_config according to the instance_id args.kafka_config.parse_generated_config_files(args, job_name, host_id, instance_id) deploy_utils.bootstrap_job(args, "kafka", "kafka", args.kafka_config, host, job_name, instance_id, cleanup_token, '0') start_job(args, host, job_name, host_id, instance_id) def bootstrap(args): _get_kafka_service_config(args) cleanup_token = deploy_utils.confirm_bootstrap("kafka", args.kafka_config) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'bootstrap', cleanup_token=cleanup_token) parallel_deploy.start_deploy_threads(bootstrap_job, task_list) def start_job(args, host, job_name, host_id, instance_id, is_wait=False): if is_wait: deploy_utils.wait_for_job_stopping("kafka", args.kafka_config.cluster.name, job_name, host, instance_id) # parse the service_config according to the instance_id args.kafka_config.parse_generated_config_files(args, job_name, host_id, instance_id) config_files = generate_configs(args, job_name, host_id, instance_id) start_script = generate_start_script(args, host, job_name, host_id, instance_id) http_url = deploy_utils.get_http_service_uri(host, args.kafka_config.jobs[job_name].base_port, instance_id) deploy_utils.start_job(args, "kafka", "kafka", args.kafka_config, host, job_name, instance_id, start_script, http_url, **config_files) def start(args): if not args.skip_confirm: deploy_utils.confirm_start(args) _get_kafka_service_config(args) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'start') parallel_deploy.start_deploy_threads(start_job, task_list) def stop_job(args, host, job_name, instance_id): deploy_utils.stop_job("kafka", args.kafka_config, host, job_name, instance_id) def stop(args): if not args.skip_confirm: deploy_utils.confirm_stop(args) _get_kafka_service_config(args) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'stop') parallel_deploy.start_deploy_threads(stop_job, task_list) def restart(args): if not args.skip_confirm: deploy_utils.confirm_restart(args) _get_kafka_service_config(args) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'stop') parallel_deploy.start_deploy_threads(stop_job, task_list) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'start', is_wait=True) parallel_deploy.start_deploy_threads(start_job, task_list) def show_job(args, host, job_name, instance_id): deploy_utils.show_job("kafka", args.kafka_config, host, job_name, instance_id) def show(args): _get_kafka_service_config(args) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'show') parallel_deploy.start_deploy_threads(show_job, task_list) def run_shell(args): Log.print_critical("'shell' command is not supported!") def pack(args): Log.print_critical("'pack' command is not supported!") def rolling_update(args): if not args.job: Log.print_critical("You must specify the job name to do rolling update") _get_kafka_service_config(args) job_name = args.job[0] if not args.skip_confirm: deploy_utils.confirm_action(args, "rolling_update") Log.print_info("Rolling updating %s" % job_name) hosts = args.kafka_config.jobs[job_name].hosts wait_time = 0 args.task_map = deploy_utils.parse_args_host_and_task(args, hosts) for host_id in args.task_map.keys() or hosts.iterkeys(): for instance_id in args.task_map.get(host_id) or range(hosts[host_id].instance_num): instance_id = -1 if not deploy_utils.is_multiple_instances(host_id, hosts) else instance_id deploy_utils.confirm_rolling_update(host_id, instance_id, wait_time) stop_job(args, hosts[host_id].ip, job_name, instance_id) deploy_utils.wait_for_job_stopping("kafka", args.kafka_config.cluster.name, job_name, hosts[host_id].ip, instance_id) start_job(args, hosts[host_id].ip, job_name, host_id, instance_id) deploy_utils.wait_for_job_starting("kafka", args.kafka_config.cluster.name, job_name, hosts[host_id].ip, instance_id) wait_time = args.time_interval Log.print_success("Rolling updating %s success" % job_name) if __name__ == '__main__': test()
38.550725
97
0.773308
import argparse import os import parallel_deploy import service_config import subprocess import sys import urlparse import deploy_utils from log import Log ALL_JOBS = ["kafka", "kafkascribe"] def _get_kafka_service_config(args): args.kafka_config = deploy_utils.get_service_config(args) def generate_configs(args, job_name, host_id, instance_id): kafka_cfg_dict = args.kafka_config.configuration.generated_files["kafka.cfg"] hosts = args.kafka_config.jobs[job_name].hosts kafka_cfg_dict["broker.id"] = deploy_utils.get_task_id(hosts, host_id, instance_id) kafka_cfg = deploy_utils.generate_properties_file(args, kafka_cfg_dict) kafka_scribe_cfg_dict = args.kafka_config.configuration.generated_files["kafka-scribe.cfg"] kafka_job = args.kafka_config.jobs["kafka"] kafka_scribe_cfg_dict["metadata.broker.list"] = ",".join( service_config.get_job_host_port_list(kafka_job)) kafka_scribe_cfg = deploy_utils.generate_properties_file(args, kafka_scribe_cfg_dict) config_files = { "kafka.cfg": kafka_cfg, "kafka-scribe.cfg": kafka_scribe_cfg, } config_files.update(args.kafka_config.configuration.raw_files) return config_files def generate_run_scripts_params(args, host, job_name, host_id, instance_id): job = args.kafka_config.jobs[job_name] supervisor_client = deploy_utils.get_supervisor_client(host, "kafka", args.kafka_config.cluster.name, job_name, instance_id=instance_id) artifact_and_version = "kafka-" + args.kafka_config.cluster.version jar_dirs = "$package_dir/*" log_level = deploy_utils.get_service_log_level(args, args.kafka_config) params = job.get_arguments(args, args.kafka_config.cluster, args.kafka_config.jobs, args.kafka_config.arguments_dict, job_name, host_id, instance_id) script_dict = { "artifact": artifact_and_version, "job_name": job_name, "jar_dirs": jar_dirs, "run_dir": supervisor_client.get_run_dir(), "params": params, } return script_dict def generate_start_script(args, host, job_name, host_id, instance_id): script_params = generate_run_scripts_params(args, host, job_name, host_id, instance_id) return deploy_utils.create_run_script( "%s/start.sh.tmpl" % deploy_utils.get_template_dir(), script_params) def install(args): _get_kafka_service_config(args) deploy_utils.install_service(args, "kafka", args.kafka_config, "kafka") def cleanup_job(args, host, job_name, host_id, instance_id, cleanup_token, active): deploy_utils.cleanup_job("kafka", args.kafka_config, host, job_name, instance_id, cleanup_token) def cleanup(args): _get_kafka_service_config(args) cleanup_token = deploy_utils.confirm_cleanup(args, "kafka", args.kafka_config) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'cleanup', cleanup_token=cleanup_token) parallel_deploy.start_deploy_threads(cleanup_job, task_list) def bootstrap_job(args, host, job_name, host_id, instance_id, cleanup_token, active): args.kafka_config.parse_generated_config_files(args, job_name, host_id, instance_id) deploy_utils.bootstrap_job(args, "kafka", "kafka", args.kafka_config, host, job_name, instance_id, cleanup_token, '0') start_job(args, host, job_name, host_id, instance_id) def bootstrap(args): _get_kafka_service_config(args) cleanup_token = deploy_utils.confirm_bootstrap("kafka", args.kafka_config) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'bootstrap', cleanup_token=cleanup_token) parallel_deploy.start_deploy_threads(bootstrap_job, task_list) def start_job(args, host, job_name, host_id, instance_id, is_wait=False): if is_wait: deploy_utils.wait_for_job_stopping("kafka", args.kafka_config.cluster.name, job_name, host, instance_id) args.kafka_config.parse_generated_config_files(args, job_name, host_id, instance_id) config_files = generate_configs(args, job_name, host_id, instance_id) start_script = generate_start_script(args, host, job_name, host_id, instance_id) http_url = deploy_utils.get_http_service_uri(host, args.kafka_config.jobs[job_name].base_port, instance_id) deploy_utils.start_job(args, "kafka", "kafka", args.kafka_config, host, job_name, instance_id, start_script, http_url, **config_files) def start(args): if not args.skip_confirm: deploy_utils.confirm_start(args) _get_kafka_service_config(args) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'start') parallel_deploy.start_deploy_threads(start_job, task_list) def stop_job(args, host, job_name, instance_id): deploy_utils.stop_job("kafka", args.kafka_config, host, job_name, instance_id) def stop(args): if not args.skip_confirm: deploy_utils.confirm_stop(args) _get_kafka_service_config(args) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'stop') parallel_deploy.start_deploy_threads(stop_job, task_list) def restart(args): if not args.skip_confirm: deploy_utils.confirm_restart(args) _get_kafka_service_config(args) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'stop') parallel_deploy.start_deploy_threads(stop_job, task_list) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'start', is_wait=True) parallel_deploy.start_deploy_threads(start_job, task_list) def show_job(args, host, job_name, instance_id): deploy_utils.show_job("kafka", args.kafka_config, host, job_name, instance_id) def show(args): _get_kafka_service_config(args) for job_name in args.job or ALL_JOBS: hosts = args.kafka_config.jobs[job_name].hosts task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'show') parallel_deploy.start_deploy_threads(show_job, task_list) def run_shell(args): Log.print_critical("'shell' command is not supported!") def pack(args): Log.print_critical("'pack' command is not supported!") def rolling_update(args): if not args.job: Log.print_critical("You must specify the job name to do rolling update") _get_kafka_service_config(args) job_name = args.job[0] if not args.skip_confirm: deploy_utils.confirm_action(args, "rolling_update") Log.print_info("Rolling updating %s" % job_name) hosts = args.kafka_config.jobs[job_name].hosts wait_time = 0 args.task_map = deploy_utils.parse_args_host_and_task(args, hosts) for host_id in args.task_map.keys() or hosts.iterkeys(): for instance_id in args.task_map.get(host_id) or range(hosts[host_id].instance_num): instance_id = -1 if not deploy_utils.is_multiple_instances(host_id, hosts) else instance_id deploy_utils.confirm_rolling_update(host_id, instance_id, wait_time) stop_job(args, hosts[host_id].ip, job_name, instance_id) deploy_utils.wait_for_job_stopping("kafka", args.kafka_config.cluster.name, job_name, hosts[host_id].ip, instance_id) start_job(args, hosts[host_id].ip, job_name, host_id, instance_id) deploy_utils.wait_for_job_starting("kafka", args.kafka_config.cluster.name, job_name, hosts[host_id].ip, instance_id) wait_time = args.time_interval Log.print_success("Rolling updating %s success" % job_name) if __name__ == '__main__': test()
true
true
f716a2954dca50e0e1254eb1298f66d92f7eacbe
2,317
py
Python
scripts/sanity_chk/scl.py
cinlyooi-intel/zephyr
193fb971c24f827464982307b5b3bb34de0fa98d
[ "Apache-2.0" ]
null
null
null
scripts/sanity_chk/scl.py
cinlyooi-intel/zephyr
193fb971c24f827464982307b5b3bb34de0fa98d
[ "Apache-2.0" ]
null
null
null
scripts/sanity_chk/scl.py
cinlyooi-intel/zephyr
193fb971c24f827464982307b5b3bb34de0fa98d
[ "Apache-2.0" ]
null
null
null
#! /usr/bin/python # # Zephyr's Sanity Check library # # Set of code that other projects can also import to do things on # Zephyr's sanity check testcases. import logging import yaml log = logging.getLogger("scl") # # def yaml_load(filename): """ Safely load a YAML document Follows recomendations from https://security.openstack.org/guidelines/dg_avoid-dangerous-input-parsing-libraries.html. :param str filename: filename to load :raises yaml.scanner: On YAML scan issues :raises: any other exception on file access erors :return: dictionary representing the YAML document """ try: with open(filename, 'r') as f: return yaml.safe_load(f) except yaml.scanner.ScannerError as e: # For errors parsing schema.yaml mark = e.problem_mark cmark = e.context_mark log.error("%s:%d:%d: error: %s (note %s context @%s:%d:%d %s)", mark.name, mark.line, mark.column, e.problem, e.note, cmark.name, cmark.line, cmark.column, e.context) raise # If pykwalify is installed, then the validate functionw ill work -- # otherwise, it is a stub and we'd warn about it. try: import pykwalify.core # Don't print error messages yourself, let us do it logging.getLogger("pykwalify.core").setLevel(50) def _yaml_validate(data, schema): if not schema: return c = pykwalify.core.Core(source_data = data, schema_data = schema) c.validate(raise_exception = True) except ImportError as e: log.warning("can't import pykwalify; won't validate YAML (%s)", e) def _yaml_validate(data, schema): pass def yaml_load_verify(filename, schema): """ Safely load a testcase/sample yaml document and validate it against the YAML schema, returing in case of success the YAML data. :param str filename: name of the file to load and process :param dict schema: loaded YAML schema (can load with :func:`yaml_load`) # 'document.yaml' contains a single YAML document. :raises yaml.scanner.ScannerError: on YAML parsing error :raises pykwalify.errors.SchemaError: on Schema violation error """ # 'document.yaml' contains a single YAML document. y = yaml_load(filename) _yaml_validate(y, schema) return y
32.180556
94
0.678032
# # Set of code that other projects can also import to do things on # Zephyr's sanity check testcases. import logging import yaml log = logging.getLogger("scl") def yaml_load(filename): try: with open(filename, 'r') as f: return yaml.safe_load(f) except yaml.scanner.ScannerError as e: mark = e.problem_mark cmark = e.context_mark log.error("%s:%d:%d: error: %s (note %s context @%s:%d:%d %s)", mark.name, mark.line, mark.column, e.problem, e.note, cmark.name, cmark.line, cmark.column, e.context) raise try: import pykwalify.core # Don't print error messages yourself, let us do it logging.getLogger("pykwalify.core").setLevel(50) def _yaml_validate(data, schema): if not schema: return c = pykwalify.core.Core(source_data = data, schema_data = schema) c.validate(raise_exception = True) except ImportError as e: log.warning("can't import pykwalify; won't validate YAML (%s)", e) def _yaml_validate(data, schema): pass def yaml_load_verify(filename, schema): y = yaml_load(filename) _yaml_validate(y, schema) return y
true
true
f716a3a44cd54534078de417bc370bb62502718a
68,239
py
Python
pandas/tests/groupby/test_groupby.py
gurukiran07/pandas
67c9385787c4d854b75a6f2c04fdf6886fdb1a06
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause" ]
2
2017-12-14T19:50:52.000Z
2020-04-07T16:47:23.000Z
pandas/tests/groupby/test_groupby.py
zoehuang7/pandas
3cce96f515917170ea9bce731ffcc913750464b8
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause" ]
null
null
null
pandas/tests/groupby/test_groupby.py
zoehuang7/pandas
3cce96f515917170ea9bce731ffcc913750464b8
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause" ]
1
2018-01-26T08:33:54.000Z
2018-01-26T08:33:54.000Z
from datetime import datetime from decimal import Decimal from io import StringIO import numpy as np import pytest from pandas.compat import IS64 from pandas.errors import PerformanceWarning import pandas as pd from pandas import ( Categorical, DataFrame, Grouper, Index, MultiIndex, Series, Timestamp, date_range, read_csv, to_datetime, ) import pandas._testing as tm from pandas.core.base import SpecificationError import pandas.core.common as com def test_repr(): # GH18203 result = repr(Grouper(key="A", level="B")) expected = "Grouper(key='A', level='B', axis=0, sort=False)" assert result == expected @pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"]) def test_basic(dtype): data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype) index = np.arange(9) np.random.shuffle(index) data = data.reindex(index) grouped = data.groupby(lambda x: x // 3) for k, v in grouped: assert len(v) == 3 agged = grouped.aggregate(np.mean) assert agged[1] == 1 tm.assert_series_equal(agged, grouped.agg(np.mean)) # shorthand tm.assert_series_equal(agged, grouped.mean()) tm.assert_series_equal(grouped.agg(np.sum), grouped.sum()) expected = grouped.apply(lambda x: x * x.sum()) transformed = grouped.transform(lambda x: x * x.sum()) assert transformed[7] == 12 tm.assert_series_equal(transformed, expected) value_grouped = data.groupby(data) tm.assert_series_equal( value_grouped.aggregate(np.mean), agged, check_index_type=False ) # complex agg agged = grouped.aggregate([np.mean, np.std]) msg = r"nested renamer is not supported" with pytest.raises(SpecificationError, match=msg): grouped.aggregate({"one": np.mean, "two": np.std}) group_constants = {0: 10, 1: 20, 2: 30} agged = grouped.agg(lambda x: group_constants[x.name] + x.mean()) assert agged[1] == 21 # corner cases msg = "Must produce aggregated value" # exception raised is type Exception with pytest.raises(Exception, match=msg): grouped.aggregate(lambda x: x * 2) def test_groupby_nonobject_dtype(mframe, df_mixed_floats): key = mframe.index.codes[0] grouped = mframe.groupby(key) result = grouped.sum() expected = mframe.groupby(key.astype("O")).sum() tm.assert_frame_equal(result, expected) # GH 3911, mixed frame non-conversion df = df_mixed_floats.copy() df["value"] = range(len(df)) def max_value(group): return group.loc[group["value"].idxmax()] applied = df.groupby("A").apply(max_value) result = applied.dtypes expected = df.dtypes tm.assert_series_equal(result, expected) def test_groupby_return_type(): # GH2893, return a reduced type df1 = DataFrame( [ {"val1": 1, "val2": 20}, {"val1": 1, "val2": 19}, {"val1": 2, "val2": 27}, {"val1": 2, "val2": 12}, ] ) def func(dataf): return dataf["val2"] - dataf["val2"].mean() with tm.assert_produces_warning(FutureWarning): result = df1.groupby("val1", squeeze=True).apply(func) assert isinstance(result, Series) df2 = DataFrame( [ {"val1": 1, "val2": 20}, {"val1": 1, "val2": 19}, {"val1": 1, "val2": 27}, {"val1": 1, "val2": 12}, ] ) def func(dataf): return dataf["val2"] - dataf["val2"].mean() with tm.assert_produces_warning(FutureWarning): result = df2.groupby("val1", squeeze=True).apply(func) assert isinstance(result, Series) # GH3596, return a consistent type (regression in 0.11 from 0.10.1) df = DataFrame([[1, 1], [1, 1]], columns=["X", "Y"]) with tm.assert_produces_warning(FutureWarning): result = df.groupby("X", squeeze=False).count() assert isinstance(result, DataFrame) def test_inconsistent_return_type(): # GH5592 # inconsistent return type df = DataFrame( { "A": ["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"], "B": Series(np.arange(7), dtype="int64"), "C": date_range("20130101", periods=7), } ) def f(grp): return grp.iloc[0] expected = df.groupby("A").first()[["B"]] result = df.groupby("A").apply(f)[["B"]] tm.assert_frame_equal(result, expected) def f(grp): if grp.name == "Tiger": return None return grp.iloc[0] result = df.groupby("A").apply(f)[["B"]] e = expected.copy() e.loc["Tiger"] = np.nan tm.assert_frame_equal(result, e) def f(grp): if grp.name == "Pony": return None return grp.iloc[0] result = df.groupby("A").apply(f)[["B"]] e = expected.copy() e.loc["Pony"] = np.nan tm.assert_frame_equal(result, e) # 5592 revisited, with datetimes def f(grp): if grp.name == "Pony": return None return grp.iloc[0] result = df.groupby("A").apply(f)[["C"]] e = df.groupby("A").first()[["C"]] e.loc["Pony"] = pd.NaT tm.assert_frame_equal(result, e) # scalar outputs def f(grp): if grp.name == "Pony": return None return grp.iloc[0].loc["C"] result = df.groupby("A").apply(f) e = df.groupby("A").first()["C"].copy() e.loc["Pony"] = np.nan e.name = None tm.assert_series_equal(result, e) def test_pass_args_kwargs(ts, tsframe): def f(x, q=None, axis=0): return np.percentile(x, q, axis=axis) g = lambda x: np.percentile(x, 80, axis=0) # Series ts_grouped = ts.groupby(lambda x: x.month) agg_result = ts_grouped.agg(np.percentile, 80, axis=0) apply_result = ts_grouped.apply(np.percentile, 80, axis=0) trans_result = ts_grouped.transform(np.percentile, 80, axis=0) agg_expected = ts_grouped.quantile(0.8) trans_expected = ts_grouped.transform(g) tm.assert_series_equal(apply_result, agg_expected) tm.assert_series_equal(agg_result, agg_expected) tm.assert_series_equal(trans_result, trans_expected) agg_result = ts_grouped.agg(f, q=80) apply_result = ts_grouped.apply(f, q=80) trans_result = ts_grouped.transform(f, q=80) tm.assert_series_equal(agg_result, agg_expected) tm.assert_series_equal(apply_result, agg_expected) tm.assert_series_equal(trans_result, trans_expected) # DataFrame df_grouped = tsframe.groupby(lambda x: x.month) agg_result = df_grouped.agg(np.percentile, 80, axis=0) apply_result = df_grouped.apply(DataFrame.quantile, 0.8) expected = df_grouped.quantile(0.8) tm.assert_frame_equal(apply_result, expected, check_names=False) tm.assert_frame_equal(agg_result, expected) agg_result = df_grouped.agg(f, q=80) apply_result = df_grouped.apply(DataFrame.quantile, q=0.8) tm.assert_frame_equal(agg_result, expected) tm.assert_frame_equal(apply_result, expected, check_names=False) def test_len(): df = tm.makeTimeDataFrame() grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) assert len(grouped) == len(df) grouped = df.groupby([lambda x: x.year, lambda x: x.month]) expected = len({(x.year, x.month) for x in df.index}) assert len(grouped) == expected # issue 11016 df = DataFrame({"a": [np.nan] * 3, "b": [1, 2, 3]}) assert len(df.groupby("a")) == 0 assert len(df.groupby("b")) == 3 assert len(df.groupby(["a", "b"])) == 3 def test_basic_regression(): # regression result = Series([1.0 * x for x in list(range(1, 10)) * 10]) data = np.random.random(1100) * 10.0 groupings = Series(data) grouped = result.groupby(groupings) grouped.mean() @pytest.mark.parametrize( "dtype", ["float64", "float32", "int64", "int32", "int16", "int8"] ) def test_with_na_groups(dtype): index = Index(np.arange(10)) values = Series(np.ones(10), index, dtype=dtype) labels = Series( [np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"], index=index, ) # this SHOULD be an int grouped = values.groupby(labels) agged = grouped.agg(len) expected = Series([4, 2], index=["bar", "foo"]) tm.assert_series_equal(agged, expected, check_dtype=False) # assert issubclass(agged.dtype.type, np.integer) # explicitly return a float from my function def f(x): return float(len(x)) agged = grouped.agg(f) expected = Series([4.0, 2.0], index=["bar", "foo"]) tm.assert_series_equal(agged, expected) def test_indices_concatenation_order(): # GH 2808 def f1(x): y = x[(x.b % 2) == 1] ** 2 if y.empty: multiindex = MultiIndex(levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"]) res = DataFrame(columns=["a"], index=multiindex) return res else: y = y.set_index(["b", "c"]) return y def f2(x): y = x[(x.b % 2) == 1] ** 2 if y.empty: return DataFrame() else: y = y.set_index(["b", "c"]) return y def f3(x): y = x[(x.b % 2) == 1] ** 2 if y.empty: multiindex = MultiIndex( levels=[[]] * 2, codes=[[]] * 2, names=["foo", "bar"] ) res = DataFrame(columns=["a", "b"], index=multiindex) return res else: return y df = DataFrame({"a": [1, 2, 2, 2], "b": range(4), "c": range(5, 9)}) df2 = DataFrame({"a": [3, 2, 2, 2], "b": range(4), "c": range(5, 9)}) # correct result result1 = df.groupby("a").apply(f1) result2 = df2.groupby("a").apply(f1) tm.assert_frame_equal(result1, result2) # should fail (not the same number of levels) msg = "Cannot concat indices that do not have the same number of levels" with pytest.raises(AssertionError, match=msg): df.groupby("a").apply(f2) with pytest.raises(AssertionError, match=msg): df2.groupby("a").apply(f2) # should fail (incorrect shape) with pytest.raises(AssertionError, match=msg): df.groupby("a").apply(f3) with pytest.raises(AssertionError, match=msg): df2.groupby("a").apply(f3) def test_attr_wrapper(ts): grouped = ts.groupby(lambda x: x.weekday()) result = grouped.std() expected = grouped.agg(lambda x: np.std(x, ddof=1)) tm.assert_series_equal(result, expected) # this is pretty cool result = grouped.describe() expected = {name: gp.describe() for name, gp in grouped} expected = DataFrame(expected).T tm.assert_frame_equal(result, expected) # get attribute result = grouped.dtype expected = grouped.agg(lambda x: x.dtype) tm.assert_series_equal(result, expected) # make sure raises error msg = "'SeriesGroupBy' object has no attribute 'foo'" with pytest.raises(AttributeError, match=msg): getattr(grouped, "foo") def test_frame_groupby(tsframe): grouped = tsframe.groupby(lambda x: x.weekday()) # aggregate aggregated = grouped.aggregate(np.mean) assert len(aggregated) == 5 assert len(aggregated.columns) == 4 # by string tscopy = tsframe.copy() tscopy["weekday"] = [x.weekday() for x in tscopy.index] stragged = tscopy.groupby("weekday").aggregate(np.mean) tm.assert_frame_equal(stragged, aggregated, check_names=False) # transform grouped = tsframe.head(30).groupby(lambda x: x.weekday()) transformed = grouped.transform(lambda x: x - x.mean()) assert len(transformed) == 30 assert len(transformed.columns) == 4 # transform propagate transformed = grouped.transform(lambda x: x.mean()) for name, group in grouped: mean = group.mean() for idx in group.index: tm.assert_series_equal(transformed.xs(idx), mean, check_names=False) # iterate for weekday, group in grouped: assert group.index[0].weekday() == weekday # groups / group_indices groups = grouped.groups indices = grouped.indices for k, v in groups.items(): samething = tsframe.index.take(indices[k]) assert (samething == v).all() def test_frame_groupby_columns(tsframe): mapping = {"A": 0, "B": 0, "C": 1, "D": 1} grouped = tsframe.groupby(mapping, axis=1) # aggregate aggregated = grouped.aggregate(np.mean) assert len(aggregated) == len(tsframe) assert len(aggregated.columns) == 2 # transform tf = lambda x: x - x.mean() groupedT = tsframe.T.groupby(mapping, axis=0) tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf)) # iterate for k, v in grouped: assert len(v.columns) == 2 def test_frame_set_name_single(df): grouped = df.groupby("A") result = grouped.mean() assert result.index.name == "A" result = df.groupby("A", as_index=False).mean() assert result.index.name != "A" result = grouped.agg(np.mean) assert result.index.name == "A" result = grouped.agg({"C": np.mean, "D": np.std}) assert result.index.name == "A" result = grouped["C"].mean() assert result.index.name == "A" result = grouped["C"].agg(np.mean) assert result.index.name == "A" result = grouped["C"].agg([np.mean, np.std]) assert result.index.name == "A" msg = r"nested renamer is not supported" with pytest.raises(SpecificationError, match=msg): grouped["C"].agg({"foo": np.mean, "bar": np.std}) def test_multi_func(df): col1 = df["A"] col2 = df["B"] grouped = df.groupby([col1.get, col2.get]) agged = grouped.mean() expected = df.groupby(["A", "B"]).mean() # TODO groupby get drops names tm.assert_frame_equal( agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names=False ) # some "groups" with no data df = DataFrame( { "v1": np.random.randn(6), "v2": np.random.randn(6), "k1": np.array(["b", "b", "b", "a", "a", "a"]), "k2": np.array(["1", "1", "1", "2", "2", "2"]), }, index=["one", "two", "three", "four", "five", "six"], ) # only verify that it works for now grouped = df.groupby(["k1", "k2"]) grouped.agg(np.sum) def test_multi_key_multiple_functions(df): grouped = df.groupby(["A", "B"])["C"] agged = grouped.agg([np.mean, np.std]) expected = DataFrame({"mean": grouped.agg(np.mean), "std": grouped.agg(np.std)}) tm.assert_frame_equal(agged, expected) def test_frame_multi_key_function_list(): data = DataFrame( { "A": [ "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar", "foo", "foo", "foo", ], "B": [ "one", "one", "one", "two", "one", "one", "one", "two", "two", "two", "one", ], "C": [ "dull", "dull", "shiny", "dull", "dull", "shiny", "shiny", "dull", "shiny", "shiny", "shiny", ], "D": np.random.randn(11), "E": np.random.randn(11), "F": np.random.randn(11), } ) grouped = data.groupby(["A", "B"]) funcs = [np.mean, np.std] agged = grouped.agg(funcs) expected = pd.concat( [grouped["D"].agg(funcs), grouped["E"].agg(funcs), grouped["F"].agg(funcs)], keys=["D", "E", "F"], axis=1, ) assert isinstance(agged.index, MultiIndex) assert isinstance(expected.index, MultiIndex) tm.assert_frame_equal(agged, expected) @pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()]) def test_groupby_multiple_columns(df, op): data = df grouped = data.groupby(["A", "B"]) result1 = op(grouped) keys = [] values = [] for n1, gp1 in data.groupby("A"): for n2, gp2 in gp1.groupby("B"): keys.append((n1, n2)) values.append(op(gp2.loc[:, ["C", "D"]])) mi = MultiIndex.from_tuples(keys, names=["A", "B"]) expected = pd.concat(values, axis=1).T expected.index = mi # a little bit crude for col in ["C", "D"]: result_col = op(grouped[col]) pivoted = result1[col] exp = expected[col] tm.assert_series_equal(result_col, exp) tm.assert_series_equal(pivoted, exp) # test single series works the same result = data["C"].groupby([data["A"], data["B"]]).mean() expected = data.groupby(["A", "B"]).mean()["C"] tm.assert_series_equal(result, expected) def test_as_index_select_column(): # GH 5764 df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"]) result = df.groupby("A", as_index=False)["B"].get_group(1) expected = Series([2, 4], name="B") tm.assert_series_equal(result, expected) result = df.groupby("A", as_index=False)["B"].apply(lambda x: x.cumsum()) expected = Series( [2, 6, 6], name="B", index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)]) ) tm.assert_series_equal(result, expected) def test_groupby_as_index_select_column_sum_empty_df(): # GH 35246 df = DataFrame(columns=["A", "B", "C"]) left = df.groupby(by="A", as_index=False)["B"].sum() assert type(left) is DataFrame assert left.to_dict() == {"A": {}, "B": {}} def test_groupby_as_index_agg(df): grouped = df.groupby("A", as_index=False) # single-key result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) result2 = grouped.agg({"C": np.mean, "D": np.sum}) expected2 = grouped.mean() expected2["D"] = grouped.sum()["D"] tm.assert_frame_equal(result2, expected2) grouped = df.groupby("A", as_index=True) msg = r"nested renamer is not supported" with pytest.raises(SpecificationError, match=msg): grouped["C"].agg({"Q": np.sum}) # multi-key grouped = df.groupby(["A", "B"], as_index=False) result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) result2 = grouped.agg({"C": np.mean, "D": np.sum}) expected2 = grouped.mean() expected2["D"] = grouped.sum()["D"] tm.assert_frame_equal(result2, expected2) expected3 = grouped["C"].sum() expected3 = DataFrame(expected3).rename(columns={"C": "Q"}) result3 = grouped["C"].agg({"Q": np.sum}) tm.assert_frame_equal(result3, expected3) # GH7115 & GH8112 & GH8582 df = DataFrame(np.random.randint(0, 100, (50, 3)), columns=["jim", "joe", "jolie"]) ts = Series(np.random.randint(5, 10, 50), name="jim") gr = df.groupby(ts) gr.nth(0) # invokes set_selection_from_grouper internally tm.assert_frame_equal(gr.apply(sum), df.groupby(ts).apply(sum)) for attr in ["mean", "max", "count", "idxmax", "cumsum", "all"]: gr = df.groupby(ts, as_index=False) left = getattr(gr, attr)() gr = df.groupby(ts.values, as_index=True) right = getattr(gr, attr)().reset_index(drop=True) tm.assert_frame_equal(left, right) def test_ops_not_as_index(reduction_func): # GH 10355, 21090 # Using as_index=False should not modify grouped column if reduction_func in ("corrwith",): pytest.skip("Test not applicable") if reduction_func in ("nth", "ngroup"): pytest.skip("Skip until behavior is determined (GH #5755)") df = DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=["a", "b"]) expected = getattr(df.groupby("a"), reduction_func)() if reduction_func == "size": expected = expected.rename("size") expected = expected.reset_index() g = df.groupby("a", as_index=False) result = getattr(g, reduction_func)() tm.assert_frame_equal(result, expected) result = g.agg(reduction_func) tm.assert_frame_equal(result, expected) result = getattr(g["b"], reduction_func)() tm.assert_frame_equal(result, expected) result = g["b"].agg(reduction_func) tm.assert_frame_equal(result, expected) def test_as_index_series_return_frame(df): grouped = df.groupby("A", as_index=False) grouped2 = df.groupby(["A", "B"], as_index=False) result = grouped["C"].agg(np.sum) expected = grouped.agg(np.sum).loc[:, ["A", "C"]] assert isinstance(result, DataFrame) tm.assert_frame_equal(result, expected) result2 = grouped2["C"].agg(np.sum) expected2 = grouped2.agg(np.sum).loc[:, ["A", "B", "C"]] assert isinstance(result2, DataFrame) tm.assert_frame_equal(result2, expected2) result = grouped["C"].sum() expected = grouped.sum().loc[:, ["A", "C"]] assert isinstance(result, DataFrame) tm.assert_frame_equal(result, expected) result2 = grouped2["C"].sum() expected2 = grouped2.sum().loc[:, ["A", "B", "C"]] assert isinstance(result2, DataFrame) tm.assert_frame_equal(result2, expected2) def test_as_index_series_column_slice_raises(df): # GH15072 grouped = df.groupby("A", as_index=False) msg = r"Column\(s\) C already selected" with pytest.raises(IndexError, match=msg): grouped["C"].__getitem__("D") def test_groupby_as_index_cython(df): data = df # single-key grouped = data.groupby("A", as_index=False) result = grouped.mean() expected = data.groupby(["A"]).mean() expected.insert(0, "A", expected.index) expected.index = np.arange(len(expected)) tm.assert_frame_equal(result, expected) # multi-key grouped = data.groupby(["A", "B"], as_index=False) result = grouped.mean() expected = data.groupby(["A", "B"]).mean() arrays = list(zip(*expected.index.values)) expected.insert(0, "A", arrays[0]) expected.insert(1, "B", arrays[1]) expected.index = np.arange(len(expected)) tm.assert_frame_equal(result, expected) def test_groupby_as_index_series_scalar(df): grouped = df.groupby(["A", "B"], as_index=False) # GH #421 result = grouped["C"].agg(len) expected = grouped.agg(len).loc[:, ["A", "B", "C"]] tm.assert_frame_equal(result, expected) def test_groupby_as_index_corner(df, ts): msg = "as_index=False only valid with DataFrame" with pytest.raises(TypeError, match=msg): ts.groupby(lambda x: x.weekday(), as_index=False) msg = "as_index=False only valid for axis=0" with pytest.raises(ValueError, match=msg): df.groupby(lambda x: x.lower(), as_index=False, axis=1) def test_groupby_multiple_key(df): df = tm.makeTimeDataFrame() grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) agged = grouped.sum() tm.assert_almost_equal(df.values, agged.values) grouped = df.T.groupby( [lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1 ) agged = grouped.agg(lambda x: x.sum()) tm.assert_index_equal(agged.index, df.columns) tm.assert_almost_equal(df.T.values, agged.values) agged = grouped.agg(lambda x: x.sum()) tm.assert_almost_equal(df.T.values, agged.values) def test_groupby_multi_corner(df): # test that having an all-NA column doesn't mess you up df = df.copy() df["bad"] = np.nan agged = df.groupby(["A", "B"]).mean() expected = df.groupby(["A", "B"]).mean() expected["bad"] = np.nan tm.assert_frame_equal(agged, expected) def test_omit_nuisance(df): grouped = df.groupby("A") result = grouped.mean() expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean() tm.assert_frame_equal(result, expected) agged = grouped.agg(np.mean) exp = grouped.mean() tm.assert_frame_equal(agged, exp) df = df.loc[:, ["A", "C", "D"]] df["E"] = datetime.now() grouped = df.groupby("A") result = grouped.agg(np.sum) expected = grouped.sum() tm.assert_frame_equal(result, expected) # won't work with axis = 1 grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1) msg = "'DatetimeArray' does not implement reduction 'sum'" with pytest.raises(TypeError, match=msg): grouped.agg(lambda x: x.sum(0, numeric_only=False)) def test_omit_nuisance_sem(df): # GH 38774 - sem should work with nuisance columns grouped = df.groupby("A") result = grouped.sem() expected = df.loc[:, ["A", "C", "D"]].groupby("A").sem() tm.assert_frame_equal(result, expected) def test_omit_nuisance_python_multiple(three_group): grouped = three_group.groupby(["A", "B"]) agged = grouped.agg(np.mean) exp = grouped.mean() tm.assert_frame_equal(agged, exp) def test_empty_groups_corner(mframe): # handle empty groups df = DataFrame( { "k1": np.array(["b", "b", "b", "a", "a", "a"]), "k2": np.array(["1", "1", "1", "2", "2", "2"]), "k3": ["foo", "bar"] * 3, "v1": np.random.randn(6), "v2": np.random.randn(6), } ) grouped = df.groupby(["k1", "k2"]) result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) grouped = mframe[3:5].groupby(level=0) agged = grouped.apply(lambda x: x.mean()) agged_A = grouped["A"].apply(np.mean) tm.assert_series_equal(agged["A"], agged_A) assert agged.index.name == "first" def test_nonsense_func(): df = DataFrame([0]) msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'" with pytest.raises(TypeError, match=msg): df.groupby(lambda x: x + "foo") def test_wrap_aggregated_output_multindex(mframe): df = mframe.T df["baz", "two"] = "peekaboo" keys = [np.array([0, 0, 1]), np.array([0, 0, 1])] agged = df.groupby(keys).agg(np.mean) assert isinstance(agged.columns, MultiIndex) def aggfun(ser): if ser.name == ("foo", "one"): raise TypeError else: return ser.sum() agged2 = df.groupby(keys).aggregate(aggfun) assert len(agged2.columns) + 1 == len(df.columns) def test_groupby_level_apply(mframe): result = mframe.groupby(level=0).count() assert result.index.name == "first" result = mframe.groupby(level=1).count() assert result.index.name == "second" result = mframe["A"].groupby(level=0).count() assert result.index.name == "first" def test_groupby_level_mapper(mframe): deleveled = mframe.reset_index() mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1} mapper1 = {"one": 0, "two": 0, "three": 1} result0 = mframe.groupby(mapper0, level=0).sum() result1 = mframe.groupby(mapper1, level=1).sum() mapped_level0 = np.array([mapper0.get(x) for x in deleveled["first"]]) mapped_level1 = np.array([mapper1.get(x) for x in deleveled["second"]]) expected0 = mframe.groupby(mapped_level0).sum() expected1 = mframe.groupby(mapped_level1).sum() expected0.index.name, expected1.index.name = "first", "second" tm.assert_frame_equal(result0, expected0) tm.assert_frame_equal(result1, expected1) def test_groupby_level_nonmulti(): # GH 1313, GH 13901 s = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo")) expected = Series([11, 22, 3, 4, 5, 6], Index(range(1, 7), name="foo")) result = s.groupby(level=0).sum() tm.assert_series_equal(result, expected) result = s.groupby(level=[0]).sum() tm.assert_series_equal(result, expected) result = s.groupby(level=-1).sum() tm.assert_series_equal(result, expected) result = s.groupby(level=[-1]).sum() tm.assert_series_equal(result, expected) msg = "level > 0 or level < -1 only valid with MultiIndex" with pytest.raises(ValueError, match=msg): s.groupby(level=1) with pytest.raises(ValueError, match=msg): s.groupby(level=-2) msg = "No group keys passed!" with pytest.raises(ValueError, match=msg): s.groupby(level=[]) msg = "multiple levels only valid with MultiIndex" with pytest.raises(ValueError, match=msg): s.groupby(level=[0, 0]) with pytest.raises(ValueError, match=msg): s.groupby(level=[0, 1]) msg = "level > 0 or level < -1 only valid with MultiIndex" with pytest.raises(ValueError, match=msg): s.groupby(level=[1]) def test_groupby_complex(): # GH 12902 a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1]) expected = Series((1 + 2j, 5 + 10j)) result = a.groupby(level=0).sum() tm.assert_series_equal(result, expected) with tm.assert_produces_warning(FutureWarning): result = a.sum(level=0) tm.assert_series_equal(result, expected) def test_groupby_series_indexed_differently(): s1 = Series( [5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7], index=Index(["a", "b", "c", "d", "e", "f", "g"]), ) s2 = Series( [1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"]) ) grouped = s1.groupby(s2) agged = grouped.mean() exp = s1.groupby(s2.reindex(s1.index).get).mean() tm.assert_series_equal(agged, exp) def test_groupby_with_hier_columns(): tuples = list( zip( *[ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], ["one", "two", "one", "two", "one", "two", "one", "two"], ] ) ) index = MultiIndex.from_tuples(tuples) columns = MultiIndex.from_tuples( [("A", "cat"), ("B", "dog"), ("B", "cat"), ("A", "dog")] ) df = DataFrame(np.random.randn(8, 4), index=index, columns=columns) result = df.groupby(level=0).mean() tm.assert_index_equal(result.columns, columns) result = df.groupby(level=0, axis=1).mean() tm.assert_index_equal(result.index, df.index) result = df.groupby(level=0).agg(np.mean) tm.assert_index_equal(result.columns, columns) result = df.groupby(level=0).apply(lambda x: x.mean()) tm.assert_index_equal(result.columns, columns) result = df.groupby(level=0, axis=1).agg(lambda x: x.mean(1)) tm.assert_index_equal(result.columns, Index(["A", "B"])) tm.assert_index_equal(result.index, df.index) # add a nuisance column sorted_columns, _ = columns.sortlevel(0) df["A", "foo"] = "bar" result = df.groupby(level=0).mean() tm.assert_index_equal(result.columns, df.columns[:-1]) def test_grouping_ndarray(df): grouped = df.groupby(df["A"].values) result = grouped.sum() expected = df.groupby("A").sum() tm.assert_frame_equal( result, expected, check_names=False ) # Note: no names when grouping by value def test_groupby_wrong_multi_labels(): data = """index,foo,bar,baz,spam,data 0,foo1,bar1,baz1,spam2,20 1,foo1,bar2,baz1,spam3,30 2,foo2,bar2,baz1,spam2,40 3,foo1,bar1,baz2,spam1,50 4,foo3,bar1,baz2,spam1,60""" data = read_csv(StringIO(data), index_col=0) grouped = data.groupby(["foo", "bar", "baz", "spam"]) result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) def test_groupby_series_with_name(df): result = df.groupby(df["A"]).mean() result2 = df.groupby(df["A"], as_index=False).mean() assert result.index.name == "A" assert "A" in result2 result = df.groupby([df["A"], df["B"]]).mean() result2 = df.groupby([df["A"], df["B"]], as_index=False).mean() assert result.index.names == ("A", "B") assert "A" in result2 assert "B" in result2 def test_seriesgroupby_name_attr(df): # GH 6265 result = df.groupby("A")["C"] assert result.count().name == "C" assert result.mean().name == "C" testFunc = lambda x: np.sum(x) * 2 assert result.agg(testFunc).name == "C" def test_consistency_name(): # GH 12363 df = DataFrame( { "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], "B": ["one", "one", "two", "two", "two", "two", "one", "two"], "C": np.random.randn(8) + 1.0, "D": np.arange(8), } ) expected = df.groupby(["A"]).B.count() result = df.B.groupby(df.A).count() tm.assert_series_equal(result, expected) def test_groupby_name_propagation(df): # GH 6124 def summarize(df, name=None): return Series({"count": 1, "mean": 2, "omissions": 3}, name=name) def summarize_random_name(df): # Provide a different name for each Series. In this case, groupby # should not attempt to propagate the Series name since they are # inconsistent. return Series({"count": 1, "mean": 2, "omissions": 3}, name=df.iloc[0]["A"]) metrics = df.groupby("A").apply(summarize) assert metrics.columns.name is None metrics = df.groupby("A").apply(summarize, "metrics") assert metrics.columns.name == "metrics" metrics = df.groupby("A").apply(summarize_random_name) assert metrics.columns.name is None def test_groupby_nonstring_columns(): df = DataFrame([np.arange(10) for x in range(10)]) grouped = df.groupby(0) result = grouped.mean() expected = df.groupby(df[0]).mean() tm.assert_frame_equal(result, expected) def test_groupby_mixed_type_columns(): # GH 13432, unorderable types in py3 df = DataFrame([[0, 1, 2]], columns=["A", "B", 0]) expected = DataFrame([[1, 2]], columns=["B", 0], index=Index([0], name="A")) result = df.groupby("A").first() tm.assert_frame_equal(result, expected) result = df.groupby("A").sum() tm.assert_frame_equal(result, expected) # TODO: Ensure warning isn't emitted in the first place @pytest.mark.filterwarnings("ignore:Mean of:RuntimeWarning") def test_cython_grouper_series_bug_noncontig(): arr = np.empty((100, 100)) arr.fill(np.nan) obj = Series(arr[:, 0]) inds = np.tile(range(10), 10) result = obj.groupby(inds).agg(Series.median) assert result.isna().all() def test_series_grouper_noncontig_index(): index = Index(tm.rands_array(10, 100)) values = Series(np.random.randn(50), index=index[::2]) labels = np.random.randint(0, 5, 50) # it works! grouped = values.groupby(labels) # accessing the index elements causes segfault f = lambda x: len(set(map(id, x.index))) grouped.agg(f) def test_convert_objects_leave_decimal_alone(): s = Series(range(5)) labels = np.array(["a", "b", "c", "d", "e"], dtype="O") def convert_fast(x): return Decimal(str(x.mean())) def convert_force_pure(x): # base will be length 0 assert len(x.values.base) > 0 return Decimal(str(x.mean())) grouped = s.groupby(labels) result = grouped.agg(convert_fast) assert result.dtype == np.object_ assert isinstance(result[0], Decimal) result = grouped.agg(convert_force_pure) assert result.dtype == np.object_ assert isinstance(result[0], Decimal) def test_groupby_dtype_inference_empty(): # GH 6733 df = DataFrame({"x": [], "range": np.arange(0, dtype="int64")}) assert df["x"].dtype == np.float64 result = df.groupby("x").first() exp_index = Index([], name="x", dtype=np.float64) expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")}) tm.assert_frame_equal(result, expected, by_blocks=True) def test_groupby_unit64_float_conversion(): #  GH: 30859 groupby converts unit64 to floats sometimes df = DataFrame({"first": [1], "second": [1], "value": [16148277970000000000]}) result = df.groupby(["first", "second"])["value"].max() expected = Series( [16148277970000000000], MultiIndex.from_product([[1], [1]], names=["first", "second"]), name="value", ) tm.assert_series_equal(result, expected) def test_groupby_list_infer_array_like(df): result = df.groupby(list(df["A"])).mean() expected = df.groupby(df["A"]).mean() tm.assert_frame_equal(result, expected, check_names=False) with pytest.raises(KeyError, match=r"^'foo'$"): df.groupby(list(df["A"][:-1])) # pathological case of ambiguity df = DataFrame({"foo": [0, 1], "bar": [3, 4], "val": np.random.randn(2)}) result = df.groupby(["foo", "bar"]).mean() expected = df.groupby([df["foo"], df["bar"]]).mean()[["val"]] def test_groupby_keys_same_size_as_index(): # GH 11185 freq = "s" index = date_range( start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq ) df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index) result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean() expected = df.set_index([df.index, "metric"]) tm.assert_frame_equal(result, expected) def test_groupby_one_row(): # GH 11741 msg = r"^'Z'$" df1 = DataFrame(np.random.randn(1, 4), columns=list("ABCD")) with pytest.raises(KeyError, match=msg): df1.groupby("Z") df2 = DataFrame(np.random.randn(2, 4), columns=list("ABCD")) with pytest.raises(KeyError, match=msg): df2.groupby("Z") def test_groupby_nat_exclude(): # GH 6992 df = DataFrame( { "values": np.random.randn(8), "dt": [ np.nan, Timestamp("2013-01-01"), np.nan, Timestamp("2013-02-01"), np.nan, Timestamp("2013-02-01"), np.nan, Timestamp("2013-01-01"), ], "str": [np.nan, "a", np.nan, "a", np.nan, "a", np.nan, "b"], } ) grouped = df.groupby("dt") expected = [Index([1, 7]), Index([3, 5])] keys = sorted(grouped.groups.keys()) assert len(keys) == 2 for k, e in zip(keys, expected): # grouped.groups keys are np.datetime64 with system tz # not to be affected by tz, only compare values tm.assert_index_equal(grouped.groups[k], e) # confirm obj is not filtered tm.assert_frame_equal(grouped.grouper.groupings[0].obj, df) assert grouped.ngroups == 2 expected = { Timestamp("2013-01-01 00:00:00"): np.array([1, 7], dtype=np.intp), Timestamp("2013-02-01 00:00:00"): np.array([3, 5], dtype=np.intp), } for k in grouped.indices: tm.assert_numpy_array_equal(grouped.indices[k], expected[k]) tm.assert_frame_equal(grouped.get_group(Timestamp("2013-01-01")), df.iloc[[1, 7]]) tm.assert_frame_equal(grouped.get_group(Timestamp("2013-02-01")), df.iloc[[3, 5]]) with pytest.raises(KeyError, match=r"^NaT$"): grouped.get_group(pd.NaT) nan_df = DataFrame( {"nan": [np.nan, np.nan, np.nan], "nat": [pd.NaT, pd.NaT, pd.NaT]} ) assert nan_df["nan"].dtype == "float64" assert nan_df["nat"].dtype == "datetime64[ns]" for key in ["nan", "nat"]: grouped = nan_df.groupby(key) assert grouped.groups == {} assert grouped.ngroups == 0 assert grouped.indices == {} with pytest.raises(KeyError, match=r"^nan$"): grouped.get_group(np.nan) with pytest.raises(KeyError, match=r"^NaT$"): grouped.get_group(pd.NaT) def test_groupby_two_group_keys_all_nan(): # GH #36842: Grouping over two group keys shouldn't raise an error df = DataFrame({"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 2]}) result = df.groupby(["a", "b"]).indices assert result == {} def test_groupby_2d_malformed(): d = DataFrame(index=range(2)) d["group"] = ["g1", "g2"] d["zeros"] = [0, 0] d["ones"] = [1, 1] d["label"] = ["l1", "l2"] tmp = d.groupby(["group"]).mean() res_values = np.array([[0, 1], [0, 1]], dtype=np.int64) tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"])) tm.assert_numpy_array_equal(tmp.values, res_values) def test_int32_overflow(): B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000))) A = np.arange(25000) df = DataFrame({"A": A, "B": B, "C": A, "D": B, "E": np.random.randn(25000)}) left = df.groupby(["A", "B", "C", "D"]).sum() right = df.groupby(["D", "C", "B", "A"]).sum() assert len(left) == len(right) def test_groupby_sort_multi(): df = DataFrame( { "a": ["foo", "bar", "baz"], "b": [3, 2, 1], "c": [0, 1, 2], "d": np.random.randn(3), } ) tups = [tuple(row) for row in df[["a", "b", "c"]].values] tups = com.asarray_tuplesafe(tups) result = df.groupby(["a", "b", "c"], sort=True).sum() tm.assert_numpy_array_equal(result.index.values, tups[[1, 2, 0]]) tups = [tuple(row) for row in df[["c", "a", "b"]].values] tups = com.asarray_tuplesafe(tups) result = df.groupby(["c", "a", "b"], sort=True).sum() tm.assert_numpy_array_equal(result.index.values, tups) tups = [tuple(x) for x in df[["b", "c", "a"]].values] tups = com.asarray_tuplesafe(tups) result = df.groupby(["b", "c", "a"], sort=True).sum() tm.assert_numpy_array_equal(result.index.values, tups[[2, 1, 0]]) df = DataFrame( {"a": [0, 1, 2, 0, 1, 2], "b": [0, 0, 0, 1, 1, 1], "d": np.random.randn(6)} ) grouped = df.groupby(["a", "b"])["d"] result = grouped.sum() def _check_groupby(df, result, keys, field, f=lambda x: x.sum()): tups = [tuple(row) for row in df[keys].values] tups = com.asarray_tuplesafe(tups) expected = f(df.groupby(tups)[field]) for k, v in expected.items(): assert result[k] == v _check_groupby(df, result, ["a", "b"], "d") def test_dont_clobber_name_column(): df = DataFrame( {"key": ["a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2} ) result = df.groupby("key").apply(lambda x: x) tm.assert_frame_equal(result, df) def test_skip_group_keys(): tsf = tm.makeTimeDataFrame() grouped = tsf.groupby(lambda x: x.month, group_keys=False) result = grouped.apply(lambda x: x.sort_values(by="A")[:3]) pieces = [group.sort_values(by="A")[:3] for key, group in grouped] expected = pd.concat(pieces) tm.assert_frame_equal(result, expected) grouped = tsf["A"].groupby(lambda x: x.month, group_keys=False) result = grouped.apply(lambda x: x.sort_values()[:3]) pieces = [group.sort_values()[:3] for key, group in grouped] expected = pd.concat(pieces) tm.assert_series_equal(result, expected) def test_no_nonsense_name(float_frame): # GH #995 s = float_frame["C"].copy() s.name = None result = s.groupby(float_frame["A"]).agg(np.sum) assert result.name is None def test_multifunc_sum_bug(): # GH #1065 x = DataFrame(np.arange(9).reshape(3, 3)) x["test"] = 0 x["fl"] = [1.3, 1.5, 1.6] grouped = x.groupby("test") result = grouped.agg({"fl": "sum", 2: "size"}) assert result["fl"].dtype == np.float64 def test_handle_dict_return_value(df): def f(group): return {"max": group.max(), "min": group.min()} def g(group): return Series({"max": group.max(), "min": group.min()}) result = df.groupby("A")["C"].apply(f) expected = df.groupby("A")["C"].apply(g) assert isinstance(result, Series) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("grouper", ["A", ["A", "B"]]) def test_set_group_name(df, grouper): def f(group): assert group.name is not None return group def freduce(group): assert group.name is not None return group.sum() def foo(x): return freduce(x) grouped = df.groupby(grouper) # make sure all these work grouped.apply(f) grouped.aggregate(freduce) grouped.aggregate({"C": freduce, "D": freduce}) grouped.transform(f) grouped["C"].apply(f) grouped["C"].aggregate(freduce) grouped["C"].aggregate([freduce, foo]) grouped["C"].transform(f) def test_group_name_available_in_inference_pass(): # gh-15062 df = DataFrame({"a": [0, 0, 1, 1, 2, 2], "b": np.arange(6)}) names = [] def f(group): names.append(group.name) return group.copy() df.groupby("a", sort=False, group_keys=False).apply(f) expected_names = [0, 1, 2] assert names == expected_names def test_no_dummy_key_names(df): # see gh-1291 result = df.groupby(df["A"].values).sum() assert result.index.name is None result = df.groupby([df["A"].values, df["B"].values]).sum() assert result.index.names == (None, None) def test_groupby_sort_multiindex_series(): # series multiindex groupby sort argument was not being passed through # _compress_group_index # GH 9444 index = MultiIndex( levels=[[1, 2], [1, 2]], codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]], names=["a", "b"], ) mseries = Series([0, 1, 2, 3, 4, 5], index=index) index = MultiIndex( levels=[[1, 2], [1, 2]], codes=[[0, 0, 1], [1, 0, 0]], names=["a", "b"] ) mseries_result = Series([0, 2, 4], index=index) result = mseries.groupby(level=["a", "b"], sort=False).first() tm.assert_series_equal(result, mseries_result) result = mseries.groupby(level=["a", "b"], sort=True).first() tm.assert_series_equal(result, mseries_result.sort_index()) def test_groupby_reindex_inside_function(): periods = 1000 ind = date_range(start="2012/1/1", freq="5min", periods=periods) df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind) def agg_before(func, fix=False): """ Run an aggregate func on the subset of data. """ def _func(data): d = data.loc[data.index.map(lambda x: x.hour < 11)].dropna() if fix: data[data.index[0]] if len(d) == 0: return None return func(d) return _func grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day)) closure_bad = grouped.agg({"high": agg_before(np.max)}) closure_good = grouped.agg({"high": agg_before(np.max, True)}) tm.assert_frame_equal(closure_bad, closure_good) def test_groupby_multiindex_missing_pair(): # GH9049 df = DataFrame( { "group1": ["a", "a", "a", "b"], "group2": ["c", "c", "d", "c"], "value": [1, 1, 1, 5], } ) df = df.set_index(["group1", "group2"]) df_grouped = df.groupby(level=["group1", "group2"], sort=True) res = df_grouped.agg("sum") idx = MultiIndex.from_tuples( [("a", "c"), ("a", "d"), ("b", "c")], names=["group1", "group2"] ) exp = DataFrame([[2], [1], [5]], index=idx, columns=["value"]) tm.assert_frame_equal(res, exp) def test_groupby_multiindex_not_lexsorted(): # GH 11640 # define the lexsorted version lexsorted_mi = MultiIndex.from_tuples( [("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"] ) lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi) assert lexsorted_df.columns._is_lexsorted() # define the non-lexsorted version not_lexsorted_df = DataFrame( columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]] ) not_lexsorted_df = not_lexsorted_df.pivot_table( index="a", columns=["b", "c"], values="d" ) not_lexsorted_df = not_lexsorted_df.reset_index() assert not not_lexsorted_df.columns._is_lexsorted() # compare the results tm.assert_frame_equal(lexsorted_df, not_lexsorted_df) expected = lexsorted_df.groupby("a").mean() with tm.assert_produces_warning(PerformanceWarning): result = not_lexsorted_df.groupby("a").mean() tm.assert_frame_equal(expected, result) # a transforming function should work regardless of sort # GH 14776 df = DataFrame( {"x": ["a", "a", "b", "a"], "y": [1, 1, 2, 2], "z": [1, 2, 3, 4]} ).set_index(["x", "y"]) assert not df.index._is_lexsorted() for level in [0, 1, [0, 1]]: for sort in [False, True]: result = df.groupby(level=level, sort=sort).apply(DataFrame.drop_duplicates) expected = df tm.assert_frame_equal(expected, result) result = ( df.sort_index() .groupby(level=level, sort=sort) .apply(DataFrame.drop_duplicates) ) expected = df.sort_index() tm.assert_frame_equal(expected, result) def test_index_label_overlaps_location(): # checking we don't have any label/location confusion in the # wake of GH5375 df = DataFrame(list("ABCDE"), index=[2, 0, 2, 1, 1]) g = df.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = df.iloc[[1, 3, 4]] tm.assert_frame_equal(actual, expected) ser = df[0] g = ser.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = ser.take([1, 3, 4]) tm.assert_series_equal(actual, expected) # ... and again, with a generic Index of floats df.index = df.index.astype(float) g = df.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = df.iloc[[1, 3, 4]] tm.assert_frame_equal(actual, expected) ser = df[0] g = ser.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = ser.take([1, 3, 4]) tm.assert_series_equal(actual, expected) def test_transform_doesnt_clobber_ints(): # GH 7972 n = 6 x = np.arange(n) df = DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x}) df2 = DataFrame({"a": x // 2 * 1.0, "b": 2.0 * x, "c": 3.0 * x}) gb = df.groupby("a") result = gb.transform("mean") gb2 = df2.groupby("a") expected = gb2.transform("mean") tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "sort_column", ["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]], ) @pytest.mark.parametrize( "group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]] ) def test_groupby_preserves_sort(sort_column, group_column): # Test to ensure that groupby always preserves sort order of original # object. Issue #8588 and #9651 df = DataFrame( { "int_groups": [3, 1, 0, 1, 0, 3, 3, 3], "string_groups": ["z", "a", "z", "a", "a", "g", "g", "g"], "ints": [8, 7, 4, 5, 2, 9, 1, 1], "floats": [2.3, 5.3, 6.2, -2.4, 2.2, 1.1, 1.1, 5], "strings": ["z", "d", "a", "e", "word", "word2", "42", "47"], } ) # Try sorting on different types and with different group types df = df.sort_values(by=sort_column) g = df.groupby(group_column) def test_sort(x): tm.assert_frame_equal(x, x.sort_values(by=sort_column)) g.apply(test_sort) def test_pivot_table_values_key_error(): # This test is designed to replicate the error in issue #14938 df = DataFrame( { "eventDate": date_range(datetime.today(), periods=20, freq="M").tolist(), "thename": range(0, 20), } ) df["year"] = df.set_index("eventDate").index.year df["month"] = df.set_index("eventDate").index.month with pytest.raises(KeyError, match="'badname'"): df.reset_index().pivot_table( index="year", columns="month", values="badname", aggfunc="count" ) @pytest.mark.parametrize("columns", ["C", ["C"]]) @pytest.mark.parametrize("keys", [["A"], ["A", "B"]]) @pytest.mark.parametrize( "values", [ [True], [0], [0.0], ["a"], Categorical([0]), [to_datetime(0)], date_range(0, 1, 1, tz="US/Eastern"), pd.array([0], dtype="Int64"), pd.array([0], dtype="Float64"), pd.array([False], dtype="boolean"), ], ) @pytest.mark.parametrize("method", ["attr", "agg", "apply"]) @pytest.mark.parametrize( "op", ["idxmax", "idxmin", "mad", "min", "max", "sum", "prod", "skew"] ) def test_empty_groupby(columns, keys, values, method, op, request): # GH8093 & GH26411 if isinstance(values, Categorical) and len(keys) == 1 and method == "apply": mark = pytest.mark.xfail(raises=TypeError, match="'str' object is not callable") request.node.add_marker(mark) elif ( isinstance(values, Categorical) and len(keys) == 1 and op in ["idxmax", "idxmin"] ): mark = pytest.mark.xfail( raises=ValueError, match="attempt to get arg(min|max) of an empty sequence" ) request.node.add_marker(mark) elif ( isinstance(values, Categorical) and len(keys) == 1 and not isinstance(columns, list) ): mark = pytest.mark.xfail( raises=TypeError, match="'Categorical' does not implement" ) request.node.add_marker(mark) elif ( isinstance(values, Categorical) and len(keys) == 1 and op in ["mad", "min", "max", "sum", "prod", "skew"] ): mark = pytest.mark.xfail( raises=AssertionError, match="(DataFrame|Series) are different" ) request.node.add_marker(mark) elif ( isinstance(values, Categorical) and len(keys) == 2 and op in ["min", "max", "sum"] and method != "apply" ): mark = pytest.mark.xfail( raises=AssertionError, match="(DataFrame|Series) are different" ) request.node.add_marker(mark) elif ( isinstance(values, pd.core.arrays.BooleanArray) and op in ["sum", "prod"] and method != "apply" ): mark = pytest.mark.xfail( raises=AssertionError, match="(DataFrame|Series) are different" ) request.node.add_marker(mark) override_dtype = None if isinstance(values[0], bool) and op in ("prod", "sum") and method != "apply": # sum/product of bools is an integer override_dtype = "int64" df = DataFrame({"A": values, "B": values, "C": values}, columns=list("ABC")) if hasattr(values, "dtype"): # check that we did the construction right assert (df.dtypes == values.dtype).all() df = df.iloc[:0] gb = df.groupby(keys)[columns] if method == "attr": result = getattr(gb, op)() else: result = getattr(gb, method)(op) expected = df.set_index(keys)[columns] if override_dtype is not None: expected = expected.astype(override_dtype) if len(keys) == 1: expected.index.name = keys[0] tm.assert_equal(result, expected) def test_tuple_as_grouping(): # https://github.com/pandas-dev/pandas/issues/18314 df = DataFrame( { ("a", "b"): [1, 1, 1, 1], "a": [2, 2, 2, 2], "b": [2, 2, 2, 2], "c": [1, 1, 1, 1], } ) with pytest.raises(KeyError, match=r"('a', 'b')"): df[["a", "b", "c"]].groupby(("a", "b")) result = df.groupby(("a", "b"))["c"].sum() expected = Series([4], name="c", index=Index([1], name=("a", "b"))) tm.assert_series_equal(result, expected) def test_tuple_correct_keyerror(): # https://github.com/pandas-dev/pandas/issues/18798 df = DataFrame(1, index=range(3), columns=MultiIndex.from_product([[1, 2], [3, 4]])) with pytest.raises(KeyError, match=r"^\(7, 8\)$"): df.groupby((7, 8)).mean() def test_groupby_agg_ohlc_non_first(): # GH 21716 df = DataFrame( [[1], [1]], columns=["foo"], index=date_range("2018-01-01", periods=2, freq="D"), ) expected = DataFrame( [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], columns=MultiIndex.from_tuples( ( ("foo", "sum", "foo"), ("foo", "ohlc", "open"), ("foo", "ohlc", "high"), ("foo", "ohlc", "low"), ("foo", "ohlc", "close"), ) ), index=date_range("2018-01-01", periods=2, freq="D"), ) result = df.groupby(Grouper(freq="D")).agg(["sum", "ohlc"]) tm.assert_frame_equal(result, expected) def test_groupby_multiindex_nat(): # GH 9236 values = [ (pd.NaT, "a"), (datetime(2012, 1, 2), "a"), (datetime(2012, 1, 2), "b"), (datetime(2012, 1, 3), "a"), ] mi = MultiIndex.from_tuples(values, names=["date", None]) ser = Series([3, 2, 2.5, 4], index=mi) result = ser.groupby(level=1).mean() expected = Series([3.0, 2.5], index=["a", "b"]) tm.assert_series_equal(result, expected) def test_groupby_empty_list_raises(): # GH 5289 values = zip(range(10), range(10)) df = DataFrame(values, columns=["apple", "b"]) msg = "Grouper and axis must be same length" with pytest.raises(ValueError, match=msg): df.groupby([[]]) def test_groupby_multiindex_series_keys_len_equal_group_axis(): # GH 25704 index_array = [["x", "x"], ["a", "b"], ["k", "k"]] index_names = ["first", "second", "third"] ri = MultiIndex.from_arrays(index_array, names=index_names) s = Series(data=[1, 2], index=ri) result = s.groupby(["first", "third"]).sum() index_array = [["x"], ["k"]] index_names = ["first", "third"] ei = MultiIndex.from_arrays(index_array, names=index_names) expected = Series([3], index=ei) tm.assert_series_equal(result, expected) def test_groupby_groups_in_BaseGrouper(): # GH 26326 # Test if DataFrame grouped with a pandas.Grouper has correct groups mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"]) df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi) result = df.groupby([Grouper(level="alpha"), "beta"]) expected = df.groupby(["alpha", "beta"]) assert result.groups == expected.groups result = df.groupby(["beta", Grouper(level="alpha")]) expected = df.groupby(["beta", "alpha"]) assert result.groups == expected.groups @pytest.mark.parametrize("group_name", ["x", ["x"]]) def test_groupby_axis_1(group_name): # GH 27614 df = DataFrame( np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20] ) df.index.name = "y" df.columns.name = "x" results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T tm.assert_frame_equal(results, expected) # test on MI column iterables = [["bar", "baz", "foo"], ["one", "two"]] mi = MultiIndex.from_product(iterables=iterables, names=["x", "x1"]) df = DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi) results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T tm.assert_frame_equal(results, expected) @pytest.mark.parametrize( "op, expected", [ ( "shift", { "time": [ None, None, Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), None, None, ] }, ), ( "bfill", { "time": [ Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), Timestamp("2019-01-01 14:00:00"), Timestamp("2019-01-01 14:30:00"), Timestamp("2019-01-01 14:00:00"), Timestamp("2019-01-01 14:30:00"), ] }, ), ( "ffill", { "time": [ Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), Timestamp("2019-01-01 14:00:00"), Timestamp("2019-01-01 14:30:00"), ] }, ), ], ) def test_shift_bfill_ffill_tz(tz_naive_fixture, op, expected): # GH19995, GH27992: Check that timezone does not drop in shift, bfill, and ffill tz = tz_naive_fixture data = { "id": ["A", "B", "A", "B", "A", "B"], "time": [ Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), None, None, Timestamp("2019-01-01 14:00:00"), Timestamp("2019-01-01 14:30:00"), ], } df = DataFrame(data).assign(time=lambda x: x.time.dt.tz_localize(tz)) grouped = df.groupby("id") result = getattr(grouped, op)() expected = DataFrame(expected).assign(time=lambda x: x.time.dt.tz_localize(tz)) tm.assert_frame_equal(result, expected) def test_groupby_only_none_group(): # see GH21624 # this was crashing with "ValueError: Length of passed values is 1, index implies 0" df = DataFrame({"g": [None], "x": 1}) actual = df.groupby("g")["x"].transform("sum") expected = Series([np.nan], name="x") tm.assert_series_equal(actual, expected) def test_groupby_duplicate_index(): # GH#29189 the groupby call here used to raise ser = Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0]) gb = ser.groupby(level=0) result = gb.mean() expected = Series([2, 5.5, 8], index=[2.0, 4.0, 5.0]) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "idx", [Index(["a", "a"]), MultiIndex.from_tuples((("a", "a"), ("a", "a")))] ) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_dup_labels_output_shape(groupby_func, idx): if groupby_func in {"size", "ngroup", "cumcount"}: pytest.skip("Not applicable") df = DataFrame([[1, 1]], columns=idx) grp_by = df.groupby([0]) args = [] if groupby_func in {"fillna", "nth"}: args.append(0) elif groupby_func == "corrwith": args.append(df) elif groupby_func == "tshift": df.index = [Timestamp("today")] args.extend([1, "D"]) result = getattr(grp_by, groupby_func)(*args) assert result.shape == (1, 2) tm.assert_index_equal(result.columns, idx) def test_groupby_crash_on_nunique(axis): # Fix following 30253 df = DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]}) axis_number = df._get_axis_number(axis) if not axis_number: df = df.T result = df.groupby(axis=axis_number, level=0).nunique() expected = DataFrame({"A": [1, 2], "D": [1, 1]}) if not axis_number: expected = expected.T tm.assert_frame_equal(result, expected) # same thing, but empty columns gb = df[[]].groupby(axis=axis_number, level=0) res = gb.nunique() exp = expected[[]] tm.assert_frame_equal(res, exp) def test_groupby_list_level(): # GH 9790 expected = DataFrame(np.arange(0, 9).reshape(3, 3)) result = expected.groupby(level=[0]).mean() tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "max_seq_items, expected", [ (5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"), (4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"), (1, "{0: [0], ...}"), ], ) def test_groups_repr_truncates(max_seq_items, expected): # GH 1135 df = DataFrame(np.random.randn(5, 1)) df["a"] = df.index with pd.option_context("display.max_seq_items", max_seq_items): result = df.groupby("a").groups.__repr__() assert result == expected result = df.groupby(np.array(df.a)).groups.__repr__() assert result == expected def test_group_on_two_row_multiindex_returns_one_tuple_key(): # GH 18451 df = DataFrame([{"a": 1, "b": 2, "c": 99}, {"a": 1, "b": 2, "c": 88}]) df = df.set_index(["a", "b"]) grp = df.groupby(["a", "b"]) result = grp.indices expected = {(1, 2): np.array([0, 1], dtype=np.int64)} assert len(result) == 1 key = (1, 2) assert (result[key] == expected[key]).all() @pytest.mark.parametrize( "klass, attr, value", [ (DataFrame, "level", "a"), (DataFrame, "as_index", False), (DataFrame, "sort", False), (DataFrame, "group_keys", False), (DataFrame, "squeeze", True), (DataFrame, "observed", True), (DataFrame, "dropna", False), pytest.param( Series, "axis", 1, marks=pytest.mark.xfail( reason="GH 35443: Attribute currently not passed on to series" ), ), (Series, "level", "a"), (Series, "as_index", False), (Series, "sort", False), (Series, "group_keys", False), (Series, "squeeze", True), (Series, "observed", True), (Series, "dropna", False), ], ) @pytest.mark.filterwarnings( "ignore:The `squeeze` parameter is deprecated:FutureWarning" ) def test_subsetting_columns_keeps_attrs(klass, attr, value): # GH 9959 - When subsetting columns, don't drop attributes df = DataFrame({"a": [1], "b": [2], "c": [3]}) if attr != "axis": df = df.set_index("a") expected = df.groupby("a", **{attr: value}) result = expected[["b"]] if klass is DataFrame else expected["b"] assert getattr(result, attr) == getattr(expected, attr) def test_subsetting_columns_axis_1(): # GH 37725 g = DataFrame({"A": [1], "B": [2], "C": [3]}).groupby([0, 0, 1], axis=1) match = "Cannot subset columns when using axis=1" with pytest.raises(ValueError, match=match): g[["A", "B"]].sum() @pytest.mark.parametrize("func", ["sum", "any", "shift"]) def test_groupby_column_index_name_lost(func): # GH: 29764 groupby loses index sometimes expected = Index(["a"], name="idx") df = DataFrame([[1]], columns=expected) df_grouped = df.groupby([1]) result = getattr(df_grouped, func)().columns tm.assert_index_equal(result, expected) def test_groupby_duplicate_columns(): # GH: 31735 df = DataFrame( {"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]} ).astype(object) df.columns = ["A", "B", "B"] result = df.groupby([0, 0, 0, 0]).min() expected = DataFrame([["e", "a", 1]], columns=["A", "B", "B"]) tm.assert_frame_equal(result, expected) def test_groupby_series_with_tuple_name(): # GH 37755 ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a")) ser.index.name = ("b", "b") result = ser.groupby(level=0).last() expected = Series([2, 4], index=[1, 2], name=("a", "a")) expected.index.name = ("b", "b") tm.assert_series_equal(result, expected) @pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system") @pytest.mark.parametrize( "func, values", [("sum", [97.0, 98.0]), ("mean", [24.25, 24.5])] ) def test_groupby_numerical_stability_sum_mean(func, values): # GH#38778 data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15] df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) result = getattr(df.groupby("group"), func)() expected = DataFrame({"a": values, "b": values}, index=Index([1, 2], name="group")) tm.assert_frame_equal(result, expected) @pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system") def test_groupby_numerical_stability_cumsum(): # GH#38934 data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15] df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) result = df.groupby("group").cumsum() exp_data = ( [1e16] * 2 + [1e16 + 96, 1e16 + 98] + [5e15 + 97, 5e15 + 98] + [97.0, 98.0] ) expected = DataFrame({"a": exp_data, "b": exp_data}) tm.assert_frame_equal(result, expected, check_exact=True) def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex): dups = rand_series_with_duplicate_datetimeindex result = dups.groupby(level=0).mean() expected = dups.groupby(dups.index).mean() tm.assert_series_equal(result, expected)
30.504694
88
0.587201
from datetime import datetime from decimal import Decimal from io import StringIO import numpy as np import pytest from pandas.compat import IS64 from pandas.errors import PerformanceWarning import pandas as pd from pandas import ( Categorical, DataFrame, Grouper, Index, MultiIndex, Series, Timestamp, date_range, read_csv, to_datetime, ) import pandas._testing as tm from pandas.core.base import SpecificationError import pandas.core.common as com def test_repr(): result = repr(Grouper(key="A", level="B")) expected = "Grouper(key='A', level='B', axis=0, sort=False)" assert result == expected @pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"]) def test_basic(dtype): data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype) index = np.arange(9) np.random.shuffle(index) data = data.reindex(index) grouped = data.groupby(lambda x: x // 3) for k, v in grouped: assert len(v) == 3 agged = grouped.aggregate(np.mean) assert agged[1] == 1 tm.assert_series_equal(agged, grouped.agg(np.mean)) tm.assert_series_equal(agged, grouped.mean()) tm.assert_series_equal(grouped.agg(np.sum), grouped.sum()) expected = grouped.apply(lambda x: x * x.sum()) transformed = grouped.transform(lambda x: x * x.sum()) assert transformed[7] == 12 tm.assert_series_equal(transformed, expected) value_grouped = data.groupby(data) tm.assert_series_equal( value_grouped.aggregate(np.mean), agged, check_index_type=False ) agged = grouped.aggregate([np.mean, np.std]) msg = r"nested renamer is not supported" with pytest.raises(SpecificationError, match=msg): grouped.aggregate({"one": np.mean, "two": np.std}) group_constants = {0: 10, 1: 20, 2: 30} agged = grouped.agg(lambda x: group_constants[x.name] + x.mean()) assert agged[1] == 21 msg = "Must produce aggregated value" with pytest.raises(Exception, match=msg): grouped.aggregate(lambda x: x * 2) def test_groupby_nonobject_dtype(mframe, df_mixed_floats): key = mframe.index.codes[0] grouped = mframe.groupby(key) result = grouped.sum() expected = mframe.groupby(key.astype("O")).sum() tm.assert_frame_equal(result, expected) df = df_mixed_floats.copy() df["value"] = range(len(df)) def max_value(group): return group.loc[group["value"].idxmax()] applied = df.groupby("A").apply(max_value) result = applied.dtypes expected = df.dtypes tm.assert_series_equal(result, expected) def test_groupby_return_type(): df1 = DataFrame( [ {"val1": 1, "val2": 20}, {"val1": 1, "val2": 19}, {"val1": 2, "val2": 27}, {"val1": 2, "val2": 12}, ] ) def func(dataf): return dataf["val2"] - dataf["val2"].mean() with tm.assert_produces_warning(FutureWarning): result = df1.groupby("val1", squeeze=True).apply(func) assert isinstance(result, Series) df2 = DataFrame( [ {"val1": 1, "val2": 20}, {"val1": 1, "val2": 19}, {"val1": 1, "val2": 27}, {"val1": 1, "val2": 12}, ] ) def func(dataf): return dataf["val2"] - dataf["val2"].mean() with tm.assert_produces_warning(FutureWarning): result = df2.groupby("val1", squeeze=True).apply(func) assert isinstance(result, Series) df = DataFrame([[1, 1], [1, 1]], columns=["X", "Y"]) with tm.assert_produces_warning(FutureWarning): result = df.groupby("X", squeeze=False).count() assert isinstance(result, DataFrame) def test_inconsistent_return_type(): df = DataFrame( { "A": ["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"], "B": Series(np.arange(7), dtype="int64"), "C": date_range("20130101", periods=7), } ) def f(grp): return grp.iloc[0] expected = df.groupby("A").first()[["B"]] result = df.groupby("A").apply(f)[["B"]] tm.assert_frame_equal(result, expected) def f(grp): if grp.name == "Tiger": return None return grp.iloc[0] result = df.groupby("A").apply(f)[["B"]] e = expected.copy() e.loc["Tiger"] = np.nan tm.assert_frame_equal(result, e) def f(grp): if grp.name == "Pony": return None return grp.iloc[0] result = df.groupby("A").apply(f)[["B"]] e = expected.copy() e.loc["Pony"] = np.nan tm.assert_frame_equal(result, e) def f(grp): if grp.name == "Pony": return None return grp.iloc[0] result = df.groupby("A").apply(f)[["C"]] e = df.groupby("A").first()[["C"]] e.loc["Pony"] = pd.NaT tm.assert_frame_equal(result, e) def f(grp): if grp.name == "Pony": return None return grp.iloc[0].loc["C"] result = df.groupby("A").apply(f) e = df.groupby("A").first()["C"].copy() e.loc["Pony"] = np.nan e.name = None tm.assert_series_equal(result, e) def test_pass_args_kwargs(ts, tsframe): def f(x, q=None, axis=0): return np.percentile(x, q, axis=axis) g = lambda x: np.percentile(x, 80, axis=0) ts_grouped = ts.groupby(lambda x: x.month) agg_result = ts_grouped.agg(np.percentile, 80, axis=0) apply_result = ts_grouped.apply(np.percentile, 80, axis=0) trans_result = ts_grouped.transform(np.percentile, 80, axis=0) agg_expected = ts_grouped.quantile(0.8) trans_expected = ts_grouped.transform(g) tm.assert_series_equal(apply_result, agg_expected) tm.assert_series_equal(agg_result, agg_expected) tm.assert_series_equal(trans_result, trans_expected) agg_result = ts_grouped.agg(f, q=80) apply_result = ts_grouped.apply(f, q=80) trans_result = ts_grouped.transform(f, q=80) tm.assert_series_equal(agg_result, agg_expected) tm.assert_series_equal(apply_result, agg_expected) tm.assert_series_equal(trans_result, trans_expected) df_grouped = tsframe.groupby(lambda x: x.month) agg_result = df_grouped.agg(np.percentile, 80, axis=0) apply_result = df_grouped.apply(DataFrame.quantile, 0.8) expected = df_grouped.quantile(0.8) tm.assert_frame_equal(apply_result, expected, check_names=False) tm.assert_frame_equal(agg_result, expected) agg_result = df_grouped.agg(f, q=80) apply_result = df_grouped.apply(DataFrame.quantile, q=0.8) tm.assert_frame_equal(agg_result, expected) tm.assert_frame_equal(apply_result, expected, check_names=False) def test_len(): df = tm.makeTimeDataFrame() grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) assert len(grouped) == len(df) grouped = df.groupby([lambda x: x.year, lambda x: x.month]) expected = len({(x.year, x.month) for x in df.index}) assert len(grouped) == expected df = DataFrame({"a": [np.nan] * 3, "b": [1, 2, 3]}) assert len(df.groupby("a")) == 0 assert len(df.groupby("b")) == 3 assert len(df.groupby(["a", "b"])) == 3 def test_basic_regression(): result = Series([1.0 * x for x in list(range(1, 10)) * 10]) data = np.random.random(1100) * 10.0 groupings = Series(data) grouped = result.groupby(groupings) grouped.mean() @pytest.mark.parametrize( "dtype", ["float64", "float32", "int64", "int32", "int16", "int8"] ) def test_with_na_groups(dtype): index = Index(np.arange(10)) values = Series(np.ones(10), index, dtype=dtype) labels = Series( [np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"], index=index, ) grouped = values.groupby(labels) agged = grouped.agg(len) expected = Series([4, 2], index=["bar", "foo"]) tm.assert_series_equal(agged, expected, check_dtype=False) def f(x): return float(len(x)) agged = grouped.agg(f) expected = Series([4.0, 2.0], index=["bar", "foo"]) tm.assert_series_equal(agged, expected) def test_indices_concatenation_order(): def f1(x): y = x[(x.b % 2) == 1] ** 2 if y.empty: multiindex = MultiIndex(levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"]) res = DataFrame(columns=["a"], index=multiindex) return res else: y = y.set_index(["b", "c"]) return y def f2(x): y = x[(x.b % 2) == 1] ** 2 if y.empty: return DataFrame() else: y = y.set_index(["b", "c"]) return y def f3(x): y = x[(x.b % 2) == 1] ** 2 if y.empty: multiindex = MultiIndex( levels=[[]] * 2, codes=[[]] * 2, names=["foo", "bar"] ) res = DataFrame(columns=["a", "b"], index=multiindex) return res else: return y df = DataFrame({"a": [1, 2, 2, 2], "b": range(4), "c": range(5, 9)}) df2 = DataFrame({"a": [3, 2, 2, 2], "b": range(4), "c": range(5, 9)}) result1 = df.groupby("a").apply(f1) result2 = df2.groupby("a").apply(f1) tm.assert_frame_equal(result1, result2) msg = "Cannot concat indices that do not have the same number of levels" with pytest.raises(AssertionError, match=msg): df.groupby("a").apply(f2) with pytest.raises(AssertionError, match=msg): df2.groupby("a").apply(f2) with pytest.raises(AssertionError, match=msg): df.groupby("a").apply(f3) with pytest.raises(AssertionError, match=msg): df2.groupby("a").apply(f3) def test_attr_wrapper(ts): grouped = ts.groupby(lambda x: x.weekday()) result = grouped.std() expected = grouped.agg(lambda x: np.std(x, ddof=1)) tm.assert_series_equal(result, expected) result = grouped.describe() expected = {name: gp.describe() for name, gp in grouped} expected = DataFrame(expected).T tm.assert_frame_equal(result, expected) result = grouped.dtype expected = grouped.agg(lambda x: x.dtype) tm.assert_series_equal(result, expected) msg = "'SeriesGroupBy' object has no attribute 'foo'" with pytest.raises(AttributeError, match=msg): getattr(grouped, "foo") def test_frame_groupby(tsframe): grouped = tsframe.groupby(lambda x: x.weekday()) aggregated = grouped.aggregate(np.mean) assert len(aggregated) == 5 assert len(aggregated.columns) == 4 tscopy = tsframe.copy() tscopy["weekday"] = [x.weekday() for x in tscopy.index] stragged = tscopy.groupby("weekday").aggregate(np.mean) tm.assert_frame_equal(stragged, aggregated, check_names=False) grouped = tsframe.head(30).groupby(lambda x: x.weekday()) transformed = grouped.transform(lambda x: x - x.mean()) assert len(transformed) == 30 assert len(transformed.columns) == 4 transformed = grouped.transform(lambda x: x.mean()) for name, group in grouped: mean = group.mean() for idx in group.index: tm.assert_series_equal(transformed.xs(idx), mean, check_names=False) for weekday, group in grouped: assert group.index[0].weekday() == weekday groups = grouped.groups indices = grouped.indices for k, v in groups.items(): samething = tsframe.index.take(indices[k]) assert (samething == v).all() def test_frame_groupby_columns(tsframe): mapping = {"A": 0, "B": 0, "C": 1, "D": 1} grouped = tsframe.groupby(mapping, axis=1) aggregated = grouped.aggregate(np.mean) assert len(aggregated) == len(tsframe) assert len(aggregated.columns) == 2 tf = lambda x: x - x.mean() groupedT = tsframe.T.groupby(mapping, axis=0) tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf)) for k, v in grouped: assert len(v.columns) == 2 def test_frame_set_name_single(df): grouped = df.groupby("A") result = grouped.mean() assert result.index.name == "A" result = df.groupby("A", as_index=False).mean() assert result.index.name != "A" result = grouped.agg(np.mean) assert result.index.name == "A" result = grouped.agg({"C": np.mean, "D": np.std}) assert result.index.name == "A" result = grouped["C"].mean() assert result.index.name == "A" result = grouped["C"].agg(np.mean) assert result.index.name == "A" result = grouped["C"].agg([np.mean, np.std]) assert result.index.name == "A" msg = r"nested renamer is not supported" with pytest.raises(SpecificationError, match=msg): grouped["C"].agg({"foo": np.mean, "bar": np.std}) def test_multi_func(df): col1 = df["A"] col2 = df["B"] grouped = df.groupby([col1.get, col2.get]) agged = grouped.mean() expected = df.groupby(["A", "B"]).mean() tm.assert_frame_equal( agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names=False ) df = DataFrame( { "v1": np.random.randn(6), "v2": np.random.randn(6), "k1": np.array(["b", "b", "b", "a", "a", "a"]), "k2": np.array(["1", "1", "1", "2", "2", "2"]), }, index=["one", "two", "three", "four", "five", "six"], ) grouped = df.groupby(["k1", "k2"]) grouped.agg(np.sum) def test_multi_key_multiple_functions(df): grouped = df.groupby(["A", "B"])["C"] agged = grouped.agg([np.mean, np.std]) expected = DataFrame({"mean": grouped.agg(np.mean), "std": grouped.agg(np.std)}) tm.assert_frame_equal(agged, expected) def test_frame_multi_key_function_list(): data = DataFrame( { "A": [ "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar", "foo", "foo", "foo", ], "B": [ "one", "one", "one", "two", "one", "one", "one", "two", "two", "two", "one", ], "C": [ "dull", "dull", "shiny", "dull", "dull", "shiny", "shiny", "dull", "shiny", "shiny", "shiny", ], "D": np.random.randn(11), "E": np.random.randn(11), "F": np.random.randn(11), } ) grouped = data.groupby(["A", "B"]) funcs = [np.mean, np.std] agged = grouped.agg(funcs) expected = pd.concat( [grouped["D"].agg(funcs), grouped["E"].agg(funcs), grouped["F"].agg(funcs)], keys=["D", "E", "F"], axis=1, ) assert isinstance(agged.index, MultiIndex) assert isinstance(expected.index, MultiIndex) tm.assert_frame_equal(agged, expected) @pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()]) def test_groupby_multiple_columns(df, op): data = df grouped = data.groupby(["A", "B"]) result1 = op(grouped) keys = [] values = [] for n1, gp1 in data.groupby("A"): for n2, gp2 in gp1.groupby("B"): keys.append((n1, n2)) values.append(op(gp2.loc[:, ["C", "D"]])) mi = MultiIndex.from_tuples(keys, names=["A", "B"]) expected = pd.concat(values, axis=1).T expected.index = mi for col in ["C", "D"]: result_col = op(grouped[col]) pivoted = result1[col] exp = expected[col] tm.assert_series_equal(result_col, exp) tm.assert_series_equal(pivoted, exp) result = data["C"].groupby([data["A"], data["B"]]).mean() expected = data.groupby(["A", "B"]).mean()["C"] tm.assert_series_equal(result, expected) def test_as_index_select_column(): df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"]) result = df.groupby("A", as_index=False)["B"].get_group(1) expected = Series([2, 4], name="B") tm.assert_series_equal(result, expected) result = df.groupby("A", as_index=False)["B"].apply(lambda x: x.cumsum()) expected = Series( [2, 6, 6], name="B", index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)]) ) tm.assert_series_equal(result, expected) def test_groupby_as_index_select_column_sum_empty_df(): df = DataFrame(columns=["A", "B", "C"]) left = df.groupby(by="A", as_index=False)["B"].sum() assert type(left) is DataFrame assert left.to_dict() == {"A": {}, "B": {}} def test_groupby_as_index_agg(df): grouped = df.groupby("A", as_index=False) result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) result2 = grouped.agg({"C": np.mean, "D": np.sum}) expected2 = grouped.mean() expected2["D"] = grouped.sum()["D"] tm.assert_frame_equal(result2, expected2) grouped = df.groupby("A", as_index=True) msg = r"nested renamer is not supported" with pytest.raises(SpecificationError, match=msg): grouped["C"].agg({"Q": np.sum}) grouped = df.groupby(["A", "B"], as_index=False) result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) result2 = grouped.agg({"C": np.mean, "D": np.sum}) expected2 = grouped.mean() expected2["D"] = grouped.sum()["D"] tm.assert_frame_equal(result2, expected2) expected3 = grouped["C"].sum() expected3 = DataFrame(expected3).rename(columns={"C": "Q"}) result3 = grouped["C"].agg({"Q": np.sum}) tm.assert_frame_equal(result3, expected3) df = DataFrame(np.random.randint(0, 100, (50, 3)), columns=["jim", "joe", "jolie"]) ts = Series(np.random.randint(5, 10, 50), name="jim") gr = df.groupby(ts) gr.nth(0) tm.assert_frame_equal(gr.apply(sum), df.groupby(ts).apply(sum)) for attr in ["mean", "max", "count", "idxmax", "cumsum", "all"]: gr = df.groupby(ts, as_index=False) left = getattr(gr, attr)() gr = df.groupby(ts.values, as_index=True) right = getattr(gr, attr)().reset_index(drop=True) tm.assert_frame_equal(left, right) def test_ops_not_as_index(reduction_func): if reduction_func in ("corrwith",): pytest.skip("Test not applicable") if reduction_func in ("nth", "ngroup"): pytest.skip("Skip until behavior is determined (GH #5755)") df = DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=["a", "b"]) expected = getattr(df.groupby("a"), reduction_func)() if reduction_func == "size": expected = expected.rename("size") expected = expected.reset_index() g = df.groupby("a", as_index=False) result = getattr(g, reduction_func)() tm.assert_frame_equal(result, expected) result = g.agg(reduction_func) tm.assert_frame_equal(result, expected) result = getattr(g["b"], reduction_func)() tm.assert_frame_equal(result, expected) result = g["b"].agg(reduction_func) tm.assert_frame_equal(result, expected) def test_as_index_series_return_frame(df): grouped = df.groupby("A", as_index=False) grouped2 = df.groupby(["A", "B"], as_index=False) result = grouped["C"].agg(np.sum) expected = grouped.agg(np.sum).loc[:, ["A", "C"]] assert isinstance(result, DataFrame) tm.assert_frame_equal(result, expected) result2 = grouped2["C"].agg(np.sum) expected2 = grouped2.agg(np.sum).loc[:, ["A", "B", "C"]] assert isinstance(result2, DataFrame) tm.assert_frame_equal(result2, expected2) result = grouped["C"].sum() expected = grouped.sum().loc[:, ["A", "C"]] assert isinstance(result, DataFrame) tm.assert_frame_equal(result, expected) result2 = grouped2["C"].sum() expected2 = grouped2.sum().loc[:, ["A", "B", "C"]] assert isinstance(result2, DataFrame) tm.assert_frame_equal(result2, expected2) def test_as_index_series_column_slice_raises(df): grouped = df.groupby("A", as_index=False) msg = r"Column\(s\) C already selected" with pytest.raises(IndexError, match=msg): grouped["C"].__getitem__("D") def test_groupby_as_index_cython(df): data = df grouped = data.groupby("A", as_index=False) result = grouped.mean() expected = data.groupby(["A"]).mean() expected.insert(0, "A", expected.index) expected.index = np.arange(len(expected)) tm.assert_frame_equal(result, expected) grouped = data.groupby(["A", "B"], as_index=False) result = grouped.mean() expected = data.groupby(["A", "B"]).mean() arrays = list(zip(*expected.index.values)) expected.insert(0, "A", arrays[0]) expected.insert(1, "B", arrays[1]) expected.index = np.arange(len(expected)) tm.assert_frame_equal(result, expected) def test_groupby_as_index_series_scalar(df): grouped = df.groupby(["A", "B"], as_index=False) result = grouped["C"].agg(len) expected = grouped.agg(len).loc[:, ["A", "B", "C"]] tm.assert_frame_equal(result, expected) def test_groupby_as_index_corner(df, ts): msg = "as_index=False only valid with DataFrame" with pytest.raises(TypeError, match=msg): ts.groupby(lambda x: x.weekday(), as_index=False) msg = "as_index=False only valid for axis=0" with pytest.raises(ValueError, match=msg): df.groupby(lambda x: x.lower(), as_index=False, axis=1) def test_groupby_multiple_key(df): df = tm.makeTimeDataFrame() grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) agged = grouped.sum() tm.assert_almost_equal(df.values, agged.values) grouped = df.T.groupby( [lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1 ) agged = grouped.agg(lambda x: x.sum()) tm.assert_index_equal(agged.index, df.columns) tm.assert_almost_equal(df.T.values, agged.values) agged = grouped.agg(lambda x: x.sum()) tm.assert_almost_equal(df.T.values, agged.values) def test_groupby_multi_corner(df): df = df.copy() df["bad"] = np.nan agged = df.groupby(["A", "B"]).mean() expected = df.groupby(["A", "B"]).mean() expected["bad"] = np.nan tm.assert_frame_equal(agged, expected) def test_omit_nuisance(df): grouped = df.groupby("A") result = grouped.mean() expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean() tm.assert_frame_equal(result, expected) agged = grouped.agg(np.mean) exp = grouped.mean() tm.assert_frame_equal(agged, exp) df = df.loc[:, ["A", "C", "D"]] df["E"] = datetime.now() grouped = df.groupby("A") result = grouped.agg(np.sum) expected = grouped.sum() tm.assert_frame_equal(result, expected) # won't work with axis = 1 grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1) msg = "'DatetimeArray' does not implement reduction 'sum'" with pytest.raises(TypeError, match=msg): grouped.agg(lambda x: x.sum(0, numeric_only=False)) def test_omit_nuisance_sem(df): grouped = df.groupby("A") result = grouped.sem() expected = df.loc[:, ["A", "C", "D"]].groupby("A").sem() tm.assert_frame_equal(result, expected) def test_omit_nuisance_python_multiple(three_group): grouped = three_group.groupby(["A", "B"]) agged = grouped.agg(np.mean) exp = grouped.mean() tm.assert_frame_equal(agged, exp) def test_empty_groups_corner(mframe): df = DataFrame( { "k1": np.array(["b", "b", "b", "a", "a", "a"]), "k2": np.array(["1", "1", "1", "2", "2", "2"]), "k3": ["foo", "bar"] * 3, "v1": np.random.randn(6), "v2": np.random.randn(6), } ) grouped = df.groupby(["k1", "k2"]) result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) grouped = mframe[3:5].groupby(level=0) agged = grouped.apply(lambda x: x.mean()) agged_A = grouped["A"].apply(np.mean) tm.assert_series_equal(agged["A"], agged_A) assert agged.index.name == "first" def test_nonsense_func(): df = DataFrame([0]) msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'" with pytest.raises(TypeError, match=msg): df.groupby(lambda x: x + "foo") def test_wrap_aggregated_output_multindex(mframe): df = mframe.T df["baz", "two"] = "peekaboo" keys = [np.array([0, 0, 1]), np.array([0, 0, 1])] agged = df.groupby(keys).agg(np.mean) assert isinstance(agged.columns, MultiIndex) def aggfun(ser): if ser.name == ("foo", "one"): raise TypeError else: return ser.sum() agged2 = df.groupby(keys).aggregate(aggfun) assert len(agged2.columns) + 1 == len(df.columns) def test_groupby_level_apply(mframe): result = mframe.groupby(level=0).count() assert result.index.name == "first" result = mframe.groupby(level=1).count() assert result.index.name == "second" result = mframe["A"].groupby(level=0).count() assert result.index.name == "first" def test_groupby_level_mapper(mframe): deleveled = mframe.reset_index() mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1} mapper1 = {"one": 0, "two": 0, "three": 1} result0 = mframe.groupby(mapper0, level=0).sum() result1 = mframe.groupby(mapper1, level=1).sum() mapped_level0 = np.array([mapper0.get(x) for x in deleveled["first"]]) mapped_level1 = np.array([mapper1.get(x) for x in deleveled["second"]]) expected0 = mframe.groupby(mapped_level0).sum() expected1 = mframe.groupby(mapped_level1).sum() expected0.index.name, expected1.index.name = "first", "second" tm.assert_frame_equal(result0, expected0) tm.assert_frame_equal(result1, expected1) def test_groupby_level_nonmulti(): s = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo")) expected = Series([11, 22, 3, 4, 5, 6], Index(range(1, 7), name="foo")) result = s.groupby(level=0).sum() tm.assert_series_equal(result, expected) result = s.groupby(level=[0]).sum() tm.assert_series_equal(result, expected) result = s.groupby(level=-1).sum() tm.assert_series_equal(result, expected) result = s.groupby(level=[-1]).sum() tm.assert_series_equal(result, expected) msg = "level > 0 or level < -1 only valid with MultiIndex" with pytest.raises(ValueError, match=msg): s.groupby(level=1) with pytest.raises(ValueError, match=msg): s.groupby(level=-2) msg = "No group keys passed!" with pytest.raises(ValueError, match=msg): s.groupby(level=[]) msg = "multiple levels only valid with MultiIndex" with pytest.raises(ValueError, match=msg): s.groupby(level=[0, 0]) with pytest.raises(ValueError, match=msg): s.groupby(level=[0, 1]) msg = "level > 0 or level < -1 only valid with MultiIndex" with pytest.raises(ValueError, match=msg): s.groupby(level=[1]) def test_groupby_complex(): a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1]) expected = Series((1 + 2j, 5 + 10j)) result = a.groupby(level=0).sum() tm.assert_series_equal(result, expected) with tm.assert_produces_warning(FutureWarning): result = a.sum(level=0) tm.assert_series_equal(result, expected) def test_groupby_series_indexed_differently(): s1 = Series( [5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7], index=Index(["a", "b", "c", "d", "e", "f", "g"]), ) s2 = Series( [1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"]) ) grouped = s1.groupby(s2) agged = grouped.mean() exp = s1.groupby(s2.reindex(s1.index).get).mean() tm.assert_series_equal(agged, exp) def test_groupby_with_hier_columns(): tuples = list( zip( *[ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], ["one", "two", "one", "two", "one", "two", "one", "two"], ] ) ) index = MultiIndex.from_tuples(tuples) columns = MultiIndex.from_tuples( [("A", "cat"), ("B", "dog"), ("B", "cat"), ("A", "dog")] ) df = DataFrame(np.random.randn(8, 4), index=index, columns=columns) result = df.groupby(level=0).mean() tm.assert_index_equal(result.columns, columns) result = df.groupby(level=0, axis=1).mean() tm.assert_index_equal(result.index, df.index) result = df.groupby(level=0).agg(np.mean) tm.assert_index_equal(result.columns, columns) result = df.groupby(level=0).apply(lambda x: x.mean()) tm.assert_index_equal(result.columns, columns) result = df.groupby(level=0, axis=1).agg(lambda x: x.mean(1)) tm.assert_index_equal(result.columns, Index(["A", "B"])) tm.assert_index_equal(result.index, df.index) sorted_columns, _ = columns.sortlevel(0) df["A", "foo"] = "bar" result = df.groupby(level=0).mean() tm.assert_index_equal(result.columns, df.columns[:-1]) def test_grouping_ndarray(df): grouped = df.groupby(df["A"].values) result = grouped.sum() expected = df.groupby("A").sum() tm.assert_frame_equal( result, expected, check_names=False ) def test_groupby_wrong_multi_labels(): data = """index,foo,bar,baz,spam,data 0,foo1,bar1,baz1,spam2,20 1,foo1,bar2,baz1,spam3,30 2,foo2,bar2,baz1,spam2,40 3,foo1,bar1,baz2,spam1,50 4,foo3,bar1,baz2,spam1,60""" data = read_csv(StringIO(data), index_col=0) grouped = data.groupby(["foo", "bar", "baz", "spam"]) result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) def test_groupby_series_with_name(df): result = df.groupby(df["A"]).mean() result2 = df.groupby(df["A"], as_index=False).mean() assert result.index.name == "A" assert "A" in result2 result = df.groupby([df["A"], df["B"]]).mean() result2 = df.groupby([df["A"], df["B"]], as_index=False).mean() assert result.index.names == ("A", "B") assert "A" in result2 assert "B" in result2 def test_seriesgroupby_name_attr(df): result = df.groupby("A")["C"] assert result.count().name == "C" assert result.mean().name == "C" testFunc = lambda x: np.sum(x) * 2 assert result.agg(testFunc).name == "C" def test_consistency_name(): df = DataFrame( { "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], "B": ["one", "one", "two", "two", "two", "two", "one", "two"], "C": np.random.randn(8) + 1.0, "D": np.arange(8), } ) expected = df.groupby(["A"]).B.count() result = df.B.groupby(df.A).count() tm.assert_series_equal(result, expected) def test_groupby_name_propagation(df): def summarize(df, name=None): return Series({"count": 1, "mean": 2, "omissions": 3}, name=name) def summarize_random_name(df): return Series({"count": 1, "mean": 2, "omissions": 3}, name=df.iloc[0]["A"]) metrics = df.groupby("A").apply(summarize) assert metrics.columns.name is None metrics = df.groupby("A").apply(summarize, "metrics") assert metrics.columns.name == "metrics" metrics = df.groupby("A").apply(summarize_random_name) assert metrics.columns.name is None def test_groupby_nonstring_columns(): df = DataFrame([np.arange(10) for x in range(10)]) grouped = df.groupby(0) result = grouped.mean() expected = df.groupby(df[0]).mean() tm.assert_frame_equal(result, expected) def test_groupby_mixed_type_columns(): df = DataFrame([[0, 1, 2]], columns=["A", "B", 0]) expected = DataFrame([[1, 2]], columns=["B", 0], index=Index([0], name="A")) result = df.groupby("A").first() tm.assert_frame_equal(result, expected) result = df.groupby("A").sum() tm.assert_frame_equal(result, expected) @pytest.mark.filterwarnings("ignore:Mean of:RuntimeWarning") def test_cython_grouper_series_bug_noncontig(): arr = np.empty((100, 100)) arr.fill(np.nan) obj = Series(arr[:, 0]) inds = np.tile(range(10), 10) result = obj.groupby(inds).agg(Series.median) assert result.isna().all() def test_series_grouper_noncontig_index(): index = Index(tm.rands_array(10, 100)) values = Series(np.random.randn(50), index=index[::2]) labels = np.random.randint(0, 5, 50) # it works! grouped = values.groupby(labels) # accessing the index elements causes segfault f = lambda x: len(set(map(id, x.index))) grouped.agg(f) def test_convert_objects_leave_decimal_alone(): s = Series(range(5)) labels = np.array(["a", "b", "c", "d", "e"], dtype="O") def convert_fast(x): return Decimal(str(x.mean())) def convert_force_pure(x): # base will be length 0 assert len(x.values.base) > 0 return Decimal(str(x.mean())) grouped = s.groupby(labels) result = grouped.agg(convert_fast) assert result.dtype == np.object_ assert isinstance(result[0], Decimal) result = grouped.agg(convert_force_pure) assert result.dtype == np.object_ assert isinstance(result[0], Decimal) def test_groupby_dtype_inference_empty(): # GH 6733 df = DataFrame({"x": [], "range": np.arange(0, dtype="int64")}) assert df["x"].dtype == np.float64 result = df.groupby("x").first() exp_index = Index([], name="x", dtype=np.float64) expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")}) tm.assert_frame_equal(result, expected, by_blocks=True) def test_groupby_unit64_float_conversion(): #  GH: 30859 groupby converts unit64 to floats sometimes df = DataFrame({"first": [1], "second": [1], "value": [16148277970000000000]}) result = df.groupby(["first", "second"])["value"].max() expected = Series( [16148277970000000000], MultiIndex.from_product([[1], [1]], names=["first", "second"]), name="value", ) tm.assert_series_equal(result, expected) def test_groupby_list_infer_array_like(df): result = df.groupby(list(df["A"])).mean() expected = df.groupby(df["A"]).mean() tm.assert_frame_equal(result, expected, check_names=False) with pytest.raises(KeyError, match=r"^'foo'$"): df.groupby(list(df["A"][:-1])) # pathological case of ambiguity df = DataFrame({"foo": [0, 1], "bar": [3, 4], "val": np.random.randn(2)}) result = df.groupby(["foo", "bar"]).mean() expected = df.groupby([df["foo"], df["bar"]]).mean()[["val"]] def test_groupby_keys_same_size_as_index(): # GH 11185 freq = "s" index = date_range( start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq ) df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index) result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean() expected = df.set_index([df.index, "metric"]) tm.assert_frame_equal(result, expected) def test_groupby_one_row(): # GH 11741 msg = r"^'Z'$" df1 = DataFrame(np.random.randn(1, 4), columns=list("ABCD")) with pytest.raises(KeyError, match=msg): df1.groupby("Z") df2 = DataFrame(np.random.randn(2, 4), columns=list("ABCD")) with pytest.raises(KeyError, match=msg): df2.groupby("Z") def test_groupby_nat_exclude(): # GH 6992 df = DataFrame( { "values": np.random.randn(8), "dt": [ np.nan, Timestamp("2013-01-01"), np.nan, Timestamp("2013-02-01"), np.nan, Timestamp("2013-02-01"), np.nan, Timestamp("2013-01-01"), ], "str": [np.nan, "a", np.nan, "a", np.nan, "a", np.nan, "b"], } ) grouped = df.groupby("dt") expected = [Index([1, 7]), Index([3, 5])] keys = sorted(grouped.groups.keys()) assert len(keys) == 2 for k, e in zip(keys, expected): # grouped.groups keys are np.datetime64 with system tz # not to be affected by tz, only compare values tm.assert_index_equal(grouped.groups[k], e) # confirm obj is not filtered tm.assert_frame_equal(grouped.grouper.groupings[0].obj, df) assert grouped.ngroups == 2 expected = { Timestamp("2013-01-01 00:00:00"): np.array([1, 7], dtype=np.intp), Timestamp("2013-02-01 00:00:00"): np.array([3, 5], dtype=np.intp), } for k in grouped.indices: tm.assert_numpy_array_equal(grouped.indices[k], expected[k]) tm.assert_frame_equal(grouped.get_group(Timestamp("2013-01-01")), df.iloc[[1, 7]]) tm.assert_frame_equal(grouped.get_group(Timestamp("2013-02-01")), df.iloc[[3, 5]]) with pytest.raises(KeyError, match=r"^NaT$"): grouped.get_group(pd.NaT) nan_df = DataFrame( {"nan": [np.nan, np.nan, np.nan], "nat": [pd.NaT, pd.NaT, pd.NaT]} ) assert nan_df["nan"].dtype == "float64" assert nan_df["nat"].dtype == "datetime64[ns]" for key in ["nan", "nat"]: grouped = nan_df.groupby(key) assert grouped.groups == {} assert grouped.ngroups == 0 assert grouped.indices == {} with pytest.raises(KeyError, match=r"^nan$"): grouped.get_group(np.nan) with pytest.raises(KeyError, match=r"^NaT$"): grouped.get_group(pd.NaT) def test_groupby_two_group_keys_all_nan(): # GH #36842: Grouping over two group keys shouldn't raise an error df = DataFrame({"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 2]}) result = df.groupby(["a", "b"]).indices assert result == {} def test_groupby_2d_malformed(): d = DataFrame(index=range(2)) d["group"] = ["g1", "g2"] d["zeros"] = [0, 0] d["ones"] = [1, 1] d["label"] = ["l1", "l2"] tmp = d.groupby(["group"]).mean() res_values = np.array([[0, 1], [0, 1]], dtype=np.int64) tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"])) tm.assert_numpy_array_equal(tmp.values, res_values) def test_int32_overflow(): B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000))) A = np.arange(25000) df = DataFrame({"A": A, "B": B, "C": A, "D": B, "E": np.random.randn(25000)}) left = df.groupby(["A", "B", "C", "D"]).sum() right = df.groupby(["D", "C", "B", "A"]).sum() assert len(left) == len(right) def test_groupby_sort_multi(): df = DataFrame( { "a": ["foo", "bar", "baz"], "b": [3, 2, 1], "c": [0, 1, 2], "d": np.random.randn(3), } ) tups = [tuple(row) for row in df[["a", "b", "c"]].values] tups = com.asarray_tuplesafe(tups) result = df.groupby(["a", "b", "c"], sort=True).sum() tm.assert_numpy_array_equal(result.index.values, tups[[1, 2, 0]]) tups = [tuple(row) for row in df[["c", "a", "b"]].values] tups = com.asarray_tuplesafe(tups) result = df.groupby(["c", "a", "b"], sort=True).sum() tm.assert_numpy_array_equal(result.index.values, tups) tups = [tuple(x) for x in df[["b", "c", "a"]].values] tups = com.asarray_tuplesafe(tups) result = df.groupby(["b", "c", "a"], sort=True).sum() tm.assert_numpy_array_equal(result.index.values, tups[[2, 1, 0]]) df = DataFrame( {"a": [0, 1, 2, 0, 1, 2], "b": [0, 0, 0, 1, 1, 1], "d": np.random.randn(6)} ) grouped = df.groupby(["a", "b"])["d"] result = grouped.sum() def _check_groupby(df, result, keys, field, f=lambda x: x.sum()): tups = [tuple(row) for row in df[keys].values] tups = com.asarray_tuplesafe(tups) expected = f(df.groupby(tups)[field]) for k, v in expected.items(): assert result[k] == v _check_groupby(df, result, ["a", "b"], "d") def test_dont_clobber_name_column(): df = DataFrame( {"key": ["a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2} ) result = df.groupby("key").apply(lambda x: x) tm.assert_frame_equal(result, df) def test_skip_group_keys(): tsf = tm.makeTimeDataFrame() grouped = tsf.groupby(lambda x: x.month, group_keys=False) result = grouped.apply(lambda x: x.sort_values(by="A")[:3]) pieces = [group.sort_values(by="A")[:3] for key, group in grouped] expected = pd.concat(pieces) tm.assert_frame_equal(result, expected) grouped = tsf["A"].groupby(lambda x: x.month, group_keys=False) result = grouped.apply(lambda x: x.sort_values()[:3]) pieces = [group.sort_values()[:3] for key, group in grouped] expected = pd.concat(pieces) tm.assert_series_equal(result, expected) def test_no_nonsense_name(float_frame): s = float_frame["C"].copy() s.name = None result = s.groupby(float_frame["A"]).agg(np.sum) assert result.name is None def test_multifunc_sum_bug(): x = DataFrame(np.arange(9).reshape(3, 3)) x["test"] = 0 x["fl"] = [1.3, 1.5, 1.6] grouped = x.groupby("test") result = grouped.agg({"fl": "sum", 2: "size"}) assert result["fl"].dtype == np.float64 def test_handle_dict_return_value(df): def f(group): return {"max": group.max(), "min": group.min()} def g(group): return Series({"max": group.max(), "min": group.min()}) result = df.groupby("A")["C"].apply(f) expected = df.groupby("A")["C"].apply(g) assert isinstance(result, Series) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("grouper", ["A", ["A", "B"]]) def test_set_group_name(df, grouper): def f(group): assert group.name is not None return group def freduce(group): assert group.name is not None return group.sum() def foo(x): return freduce(x) grouped = df.groupby(grouper) grouped.apply(f) grouped.aggregate(freduce) grouped.aggregate({"C": freduce, "D": freduce}) grouped.transform(f) grouped["C"].apply(f) grouped["C"].aggregate(freduce) grouped["C"].aggregate([freduce, foo]) grouped["C"].transform(f) def test_group_name_available_in_inference_pass(): df = DataFrame({"a": [0, 0, 1, 1, 2, 2], "b": np.arange(6)}) names = [] def f(group): names.append(group.name) return group.copy() df.groupby("a", sort=False, group_keys=False).apply(f) expected_names = [0, 1, 2] assert names == expected_names def test_no_dummy_key_names(df): result = df.groupby(df["A"].values).sum() assert result.index.name is None result = df.groupby([df["A"].values, df["B"].values]).sum() assert result.index.names == (None, None) def test_groupby_sort_multiindex_series(): index = MultiIndex( levels=[[1, 2], [1, 2]], codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]], names=["a", "b"], ) mseries = Series([0, 1, 2, 3, 4, 5], index=index) index = MultiIndex( levels=[[1, 2], [1, 2]], codes=[[0, 0, 1], [1, 0, 0]], names=["a", "b"] ) mseries_result = Series([0, 2, 4], index=index) result = mseries.groupby(level=["a", "b"], sort=False).first() tm.assert_series_equal(result, mseries_result) result = mseries.groupby(level=["a", "b"], sort=True).first() tm.assert_series_equal(result, mseries_result.sort_index()) def test_groupby_reindex_inside_function(): periods = 1000 ind = date_range(start="2012/1/1", freq="5min", periods=periods) df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind) def agg_before(func, fix=False): def _func(data): d = data.loc[data.index.map(lambda x: x.hour < 11)].dropna() if fix: data[data.index[0]] if len(d) == 0: return None return func(d) return _func grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day)) closure_bad = grouped.agg({"high": agg_before(np.max)}) closure_good = grouped.agg({"high": agg_before(np.max, True)}) tm.assert_frame_equal(closure_bad, closure_good) def test_groupby_multiindex_missing_pair(): df = DataFrame( { "group1": ["a", "a", "a", "b"], "group2": ["c", "c", "d", "c"], "value": [1, 1, 1, 5], } ) df = df.set_index(["group1", "group2"]) df_grouped = df.groupby(level=["group1", "group2"], sort=True) res = df_grouped.agg("sum") idx = MultiIndex.from_tuples( [("a", "c"), ("a", "d"), ("b", "c")], names=["group1", "group2"] ) exp = DataFrame([[2], [1], [5]], index=idx, columns=["value"]) tm.assert_frame_equal(res, exp) def test_groupby_multiindex_not_lexsorted(): lexsorted_mi = MultiIndex.from_tuples( [("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"] ) lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi) assert lexsorted_df.columns._is_lexsorted() not_lexsorted_df = DataFrame( columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]] ) not_lexsorted_df = not_lexsorted_df.pivot_table( index="a", columns=["b", "c"], values="d" ) not_lexsorted_df = not_lexsorted_df.reset_index() assert not not_lexsorted_df.columns._is_lexsorted() tm.assert_frame_equal(lexsorted_df, not_lexsorted_df) expected = lexsorted_df.groupby("a").mean() with tm.assert_produces_warning(PerformanceWarning): result = not_lexsorted_df.groupby("a").mean() tm.assert_frame_equal(expected, result) df = DataFrame( {"x": ["a", "a", "b", "a"], "y": [1, 1, 2, 2], "z": [1, 2, 3, 4]} ).set_index(["x", "y"]) assert not df.index._is_lexsorted() for level in [0, 1, [0, 1]]: for sort in [False, True]: result = df.groupby(level=level, sort=sort).apply(DataFrame.drop_duplicates) expected = df tm.assert_frame_equal(expected, result) result = ( df.sort_index() .groupby(level=level, sort=sort) .apply(DataFrame.drop_duplicates) ) expected = df.sort_index() tm.assert_frame_equal(expected, result) def test_index_label_overlaps_location(): # wake of GH5375 df = DataFrame(list("ABCDE"), index=[2, 0, 2, 1, 1]) g = df.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = df.iloc[[1, 3, 4]] tm.assert_frame_equal(actual, expected) ser = df[0] g = ser.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = ser.take([1, 3, 4]) tm.assert_series_equal(actual, expected) # ... and again, with a generic Index of floats df.index = df.index.astype(float) g = df.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = df.iloc[[1, 3, 4]] tm.assert_frame_equal(actual, expected) ser = df[0] g = ser.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = ser.take([1, 3, 4]) tm.assert_series_equal(actual, expected) def test_transform_doesnt_clobber_ints(): # GH 7972 n = 6 x = np.arange(n) df = DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x}) df2 = DataFrame({"a": x // 2 * 1.0, "b": 2.0 * x, "c": 3.0 * x}) gb = df.groupby("a") result = gb.transform("mean") gb2 = df2.groupby("a") expected = gb2.transform("mean") tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "sort_column", ["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]], ) @pytest.mark.parametrize( "group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]] ) def test_groupby_preserves_sort(sort_column, group_column): # Test to ensure that groupby always preserves sort order of original # object. Issue #8588 and #9651 df = DataFrame( { "int_groups": [3, 1, 0, 1, 0, 3, 3, 3], "string_groups": ["z", "a", "z", "a", "a", "g", "g", "g"], "ints": [8, 7, 4, 5, 2, 9, 1, 1], "floats": [2.3, 5.3, 6.2, -2.4, 2.2, 1.1, 1.1, 5], "strings": ["z", "d", "a", "e", "word", "word2", "42", "47"], } ) # Try sorting on different types and with different group types df = df.sort_values(by=sort_column) g = df.groupby(group_column) def test_sort(x): tm.assert_frame_equal(x, x.sort_values(by=sort_column)) g.apply(test_sort) def test_pivot_table_values_key_error(): # This test is designed to replicate the error in issue #14938 df = DataFrame( { "eventDate": date_range(datetime.today(), periods=20, freq="M").tolist(), "thename": range(0, 20), } ) df["year"] = df.set_index("eventDate").index.year df["month"] = df.set_index("eventDate").index.month with pytest.raises(KeyError, match="'badname'"): df.reset_index().pivot_table( index="year", columns="month", values="badname", aggfunc="count" ) @pytest.mark.parametrize("columns", ["C", ["C"]]) @pytest.mark.parametrize("keys", [["A"], ["A", "B"]]) @pytest.mark.parametrize( "values", [ [True], [0], [0.0], ["a"], Categorical([0]), [to_datetime(0)], date_range(0, 1, 1, tz="US/Eastern"), pd.array([0], dtype="Int64"), pd.array([0], dtype="Float64"), pd.array([False], dtype="boolean"), ], ) @pytest.mark.parametrize("method", ["attr", "agg", "apply"]) @pytest.mark.parametrize( "op", ["idxmax", "idxmin", "mad", "min", "max", "sum", "prod", "skew"] ) def test_empty_groupby(columns, keys, values, method, op, request): # GH8093 & GH26411 if isinstance(values, Categorical) and len(keys) == 1 and method == "apply": mark = pytest.mark.xfail(raises=TypeError, match="'str' object is not callable") request.node.add_marker(mark) elif ( isinstance(values, Categorical) and len(keys) == 1 and op in ["idxmax", "idxmin"] ): mark = pytest.mark.xfail( raises=ValueError, match="attempt to get arg(min|max) of an empty sequence" ) request.node.add_marker(mark) elif ( isinstance(values, Categorical) and len(keys) == 1 and not isinstance(columns, list) ): mark = pytest.mark.xfail( raises=TypeError, match="'Categorical' does not implement" ) request.node.add_marker(mark) elif ( isinstance(values, Categorical) and len(keys) == 1 and op in ["mad", "min", "max", "sum", "prod", "skew"] ): mark = pytest.mark.xfail( raises=AssertionError, match="(DataFrame|Series) are different" ) request.node.add_marker(mark) elif ( isinstance(values, Categorical) and len(keys) == 2 and op in ["min", "max", "sum"] and method != "apply" ): mark = pytest.mark.xfail( raises=AssertionError, match="(DataFrame|Series) are different" ) request.node.add_marker(mark) elif ( isinstance(values, pd.core.arrays.BooleanArray) and op in ["sum", "prod"] and method != "apply" ): mark = pytest.mark.xfail( raises=AssertionError, match="(DataFrame|Series) are different" ) request.node.add_marker(mark) override_dtype = None if isinstance(values[0], bool) and op in ("prod", "sum") and method != "apply": # sum/product of bools is an integer override_dtype = "int64" df = DataFrame({"A": values, "B": values, "C": values}, columns=list("ABC")) if hasattr(values, "dtype"): # check that we did the construction right assert (df.dtypes == values.dtype).all() df = df.iloc[:0] gb = df.groupby(keys)[columns] if method == "attr": result = getattr(gb, op)() else: result = getattr(gb, method)(op) expected = df.set_index(keys)[columns] if override_dtype is not None: expected = expected.astype(override_dtype) if len(keys) == 1: expected.index.name = keys[0] tm.assert_equal(result, expected) def test_tuple_as_grouping(): # https://github.com/pandas-dev/pandas/issues/18314 df = DataFrame( { ("a", "b"): [1, 1, 1, 1], "a": [2, 2, 2, 2], "b": [2, 2, 2, 2], "c": [1, 1, 1, 1], } ) with pytest.raises(KeyError, match=r"('a', 'b')"): df[["a", "b", "c"]].groupby(("a", "b")) result = df.groupby(("a", "b"))["c"].sum() expected = Series([4], name="c", index=Index([1], name=("a", "b"))) tm.assert_series_equal(result, expected) def test_tuple_correct_keyerror(): # https://github.com/pandas-dev/pandas/issues/18798 df = DataFrame(1, index=range(3), columns=MultiIndex.from_product([[1, 2], [3, 4]])) with pytest.raises(KeyError, match=r"^\(7, 8\)$"): df.groupby((7, 8)).mean() def test_groupby_agg_ohlc_non_first(): # GH 21716 df = DataFrame( [[1], [1]], columns=["foo"], index=date_range("2018-01-01", periods=2, freq="D"), ) expected = DataFrame( [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], columns=MultiIndex.from_tuples( ( ("foo", "sum", "foo"), ("foo", "ohlc", "open"), ("foo", "ohlc", "high"), ("foo", "ohlc", "low"), ("foo", "ohlc", "close"), ) ), index=date_range("2018-01-01", periods=2, freq="D"), ) result = df.groupby(Grouper(freq="D")).agg(["sum", "ohlc"]) tm.assert_frame_equal(result, expected) def test_groupby_multiindex_nat(): # GH 9236 values = [ (pd.NaT, "a"), (datetime(2012, 1, 2), "a"), (datetime(2012, 1, 2), "b"), (datetime(2012, 1, 3), "a"), ] mi = MultiIndex.from_tuples(values, names=["date", None]) ser = Series([3, 2, 2.5, 4], index=mi) result = ser.groupby(level=1).mean() expected = Series([3.0, 2.5], index=["a", "b"]) tm.assert_series_equal(result, expected) def test_groupby_empty_list_raises(): # GH 5289 values = zip(range(10), range(10)) df = DataFrame(values, columns=["apple", "b"]) msg = "Grouper and axis must be same length" with pytest.raises(ValueError, match=msg): df.groupby([[]]) def test_groupby_multiindex_series_keys_len_equal_group_axis(): # GH 25704 index_array = [["x", "x"], ["a", "b"], ["k", "k"]] index_names = ["first", "second", "third"] ri = MultiIndex.from_arrays(index_array, names=index_names) s = Series(data=[1, 2], index=ri) result = s.groupby(["first", "third"]).sum() index_array = [["x"], ["k"]] index_names = ["first", "third"] ei = MultiIndex.from_arrays(index_array, names=index_names) expected = Series([3], index=ei) tm.assert_series_equal(result, expected) def test_groupby_groups_in_BaseGrouper(): # GH 26326 # Test if DataFrame grouped with a pandas.Grouper has correct groups mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"]) df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi) result = df.groupby([Grouper(level="alpha"), "beta"]) expected = df.groupby(["alpha", "beta"]) assert result.groups == expected.groups result = df.groupby(["beta", Grouper(level="alpha")]) expected = df.groupby(["beta", "alpha"]) assert result.groups == expected.groups @pytest.mark.parametrize("group_name", ["x", ["x"]]) def test_groupby_axis_1(group_name): # GH 27614 df = DataFrame( np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20] ) df.index.name = "y" df.columns.name = "x" results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T tm.assert_frame_equal(results, expected) # test on MI column iterables = [["bar", "baz", "foo"], ["one", "two"]] mi = MultiIndex.from_product(iterables=iterables, names=["x", "x1"]) df = DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi) results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T tm.assert_frame_equal(results, expected) @pytest.mark.parametrize( "op, expected", [ ( "shift", { "time": [ None, None, Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), None, None, ] }, ), ( "bfill", { "time": [ Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), Timestamp("2019-01-01 14:00:00"), Timestamp("2019-01-01 14:30:00"), Timestamp("2019-01-01 14:00:00"), Timestamp("2019-01-01 14:30:00"), ] }, ), ( "ffill", { "time": [ Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), Timestamp("2019-01-01 14:00:00"), Timestamp("2019-01-01 14:30:00"), ] }, ), ], ) def test_shift_bfill_ffill_tz(tz_naive_fixture, op, expected): # GH19995, GH27992: Check that timezone does not drop in shift, bfill, and ffill tz = tz_naive_fixture data = { "id": ["A", "B", "A", "B", "A", "B"], "time": [ Timestamp("2019-01-01 12:00:00"), Timestamp("2019-01-01 12:30:00"), None, None, Timestamp("2019-01-01 14:00:00"), Timestamp("2019-01-01 14:30:00"), ], } df = DataFrame(data).assign(time=lambda x: x.time.dt.tz_localize(tz)) grouped = df.groupby("id") result = getattr(grouped, op)() expected = DataFrame(expected).assign(time=lambda x: x.time.dt.tz_localize(tz)) tm.assert_frame_equal(result, expected) def test_groupby_only_none_group(): # see GH21624 # this was crashing with "ValueError: Length of passed values is 1, index implies 0" df = DataFrame({"g": [None], "x": 1}) actual = df.groupby("g")["x"].transform("sum") expected = Series([np.nan], name="x") tm.assert_series_equal(actual, expected) def test_groupby_duplicate_index(): # GH#29189 the groupby call here used to raise ser = Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0]) gb = ser.groupby(level=0) result = gb.mean() expected = Series([2, 5.5, 8], index=[2.0, 4.0, 5.0]) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "idx", [Index(["a", "a"]), MultiIndex.from_tuples((("a", "a"), ("a", "a")))] ) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_dup_labels_output_shape(groupby_func, idx): if groupby_func in {"size", "ngroup", "cumcount"}: pytest.skip("Not applicable") df = DataFrame([[1, 1]], columns=idx) grp_by = df.groupby([0]) args = [] if groupby_func in {"fillna", "nth"}: args.append(0) elif groupby_func == "corrwith": args.append(df) elif groupby_func == "tshift": df.index = [Timestamp("today")] args.extend([1, "D"]) result = getattr(grp_by, groupby_func)(*args) assert result.shape == (1, 2) tm.assert_index_equal(result.columns, idx) def test_groupby_crash_on_nunique(axis): # Fix following 30253 df = DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]}) axis_number = df._get_axis_number(axis) if not axis_number: df = df.T result = df.groupby(axis=axis_number, level=0).nunique() expected = DataFrame({"A": [1, 2], "D": [1, 1]}) if not axis_number: expected = expected.T tm.assert_frame_equal(result, expected) # same thing, but empty columns gb = df[[]].groupby(axis=axis_number, level=0) res = gb.nunique() exp = expected[[]] tm.assert_frame_equal(res, exp) def test_groupby_list_level(): # GH 9790 expected = DataFrame(np.arange(0, 9).reshape(3, 3)) result = expected.groupby(level=[0]).mean() tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "max_seq_items, expected", [ (5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"), (4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"), (1, "{0: [0], ...}"), ], ) def test_groups_repr_truncates(max_seq_items, expected): # GH 1135 df = DataFrame(np.random.randn(5, 1)) df["a"] = df.index with pd.option_context("display.max_seq_items", max_seq_items): result = df.groupby("a").groups.__repr__() assert result == expected result = df.groupby(np.array(df.a)).groups.__repr__() assert result == expected def test_group_on_two_row_multiindex_returns_one_tuple_key(): # GH 18451 df = DataFrame([{"a": 1, "b": 2, "c": 99}, {"a": 1, "b": 2, "c": 88}]) df = df.set_index(["a", "b"]) grp = df.groupby(["a", "b"]) result = grp.indices expected = {(1, 2): np.array([0, 1], dtype=np.int64)} assert len(result) == 1 key = (1, 2) assert (result[key] == expected[key]).all() @pytest.mark.parametrize( "klass, attr, value", [ (DataFrame, "level", "a"), (DataFrame, "as_index", False), (DataFrame, "sort", False), (DataFrame, "group_keys", False), (DataFrame, "squeeze", True), (DataFrame, "observed", True), (DataFrame, "dropna", False), pytest.param( Series, "axis", 1, marks=pytest.mark.xfail( reason="GH 35443: Attribute currently not passed on to series" ), ), (Series, "level", "a"), (Series, "as_index", False), (Series, "sort", False), (Series, "group_keys", False), (Series, "squeeze", True), (Series, "observed", True), (Series, "dropna", False), ], ) @pytest.mark.filterwarnings( "ignore:The `squeeze` parameter is deprecated:FutureWarning" ) def test_subsetting_columns_keeps_attrs(klass, attr, value): # GH 9959 - When subsetting columns, don't drop attributes df = DataFrame({"a": [1], "b": [2], "c": [3]}) if attr != "axis": df = df.set_index("a") expected = df.groupby("a", **{attr: value}) result = expected[["b"]] if klass is DataFrame else expected["b"] assert getattr(result, attr) == getattr(expected, attr) def test_subsetting_columns_axis_1(): g = DataFrame({"A": [1], "B": [2], "C": [3]}).groupby([0, 0, 1], axis=1) match = "Cannot subset columns when using axis=1" with pytest.raises(ValueError, match=match): g[["A", "B"]].sum() @pytest.mark.parametrize("func", ["sum", "any", "shift"]) def test_groupby_column_index_name_lost(func): expected = Index(["a"], name="idx") df = DataFrame([[1]], columns=expected) df_grouped = df.groupby([1]) result = getattr(df_grouped, func)().columns tm.assert_index_equal(result, expected) def test_groupby_duplicate_columns(): df = DataFrame( {"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]} ).astype(object) df.columns = ["A", "B", "B"] result = df.groupby([0, 0, 0, 0]).min() expected = DataFrame([["e", "a", 1]], columns=["A", "B", "B"]) tm.assert_frame_equal(result, expected) def test_groupby_series_with_tuple_name(): ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a")) ser.index.name = ("b", "b") result = ser.groupby(level=0).last() expected = Series([2, 4], index=[1, 2], name=("a", "a")) expected.index.name = ("b", "b") tm.assert_series_equal(result, expected) @pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system") @pytest.mark.parametrize( "func, values", [("sum", [97.0, 98.0]), ("mean", [24.25, 24.5])] ) def test_groupby_numerical_stability_sum_mean(func, values): ata = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15] df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) result = getattr(df.groupby("group"), func)() expected = DataFrame({"a": values, "b": values}, index=Index([1, 2], name="group")) tm.assert_frame_equal(result, expected) @pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system") def test_groupby_numerical_stability_cumsum(): ata = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15] df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) result = df.groupby("group").cumsum() exp_data = ( [1e16] * 2 + [1e16 + 96, 1e16 + 98] + [5e15 + 97, 5e15 + 98] + [97.0, 98.0] ) expected = DataFrame({"a": exp_data, "b": exp_data}) tm.assert_frame_equal(result, expected, check_exact=True) def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex): dups = rand_series_with_duplicate_datetimeindex result = dups.groupby(level=0).mean() expected = dups.groupby(dups.index).mean() tm.assert_series_equal(result, expected)
true
true
f716a3b6932792541e61b438e6424ea8e3b6dd6f
5,536
py
Python
src/modules/site/base/views/tools/heritability.py
AndersenLab/CAENDR
ce4cdb74db736db8226ffc90988959b71b0d5ff5
[ "MIT" ]
3
2022-02-09T07:04:37.000Z
2022-03-11T02:46:35.000Z
src/modules/site/base/views/tools/heritability.py
AndersenLab/CAENDR
ce4cdb74db736db8226ffc90988959b71b0d5ff5
[ "MIT" ]
4
2022-01-28T22:28:08.000Z
2022-02-11T21:47:15.000Z
src/modules/site/base/views/tools/heritability.py
AndersenLab/CAENDR
ce4cdb74db736db8226ffc90988959b71b0d5ff5
[ "MIT" ]
1
2022-01-11T03:39:02.000Z
2022-01-11T03:39:02.000Z
import io import pandas as pd import json from flask import (flash, request, redirect, url_for, jsonify, render_template, Blueprint, abort) from logzero import logger from datetime import datetime from base.forms import HeritabilityForm from base.utils.auth import jwt_required, admin_required, get_jwt, get_current_user from caendr.api.strain import get_strains from caendr.services.heritability_report import get_all_heritability_results, get_user_heritability_results, create_new_heritability_report, get_heritability_report from caendr.utils.data import unique_id, convert_data_table_to_tsv, get_object_hash from caendr.services.cloud.storage import get_blob, generate_blob_url # ================== # # heritability # # ================== # # Tools blueprint heritability_bp = Blueprint('heritability', __name__) @heritability_bp.route('/heritability') def heritability(): title = "Heritability Calculator" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} form = HeritabilityForm() hide_form = True strain_list = [] return render_template('tools/heritability/submit.html', **locals()) @heritability_bp.route('/heritability/create', methods=["GET"]) @jwt_required() def heritability_create(): """ This endpoint is used to create a heritability job. """ title = "Heritability Calculator" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} jwt_csrf_token = (get_jwt() or {}).get("csrf") form = HeritabilityForm() strain_data = get_strains() strain_list = [] for x in strain_data: strain_list.append(x.strain) hide_form = False id = unique_id() return render_template('tools/heritability/submit.html', **locals()) @heritability_bp.route("/heritability/all-results") @admin_required() def heritability_all_results(): title = "All Heritability Results" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} user = get_current_user() items = get_all_heritability_results() return render_template('tools/heritability/list-all.html', **locals()) @heritability_bp.route("/heritability/my-results") @jwt_required() def heritability_user_results(): title = "My Heritability Results" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} user = get_current_user() items = get_user_heritability_results(user.name) return render_template('tools/heritability/list-user.html', **locals()) @heritability_bp.route('/heritability/submit', methods=["POST"]) @jwt_required() def submit_h2(): user = get_current_user() label = request.values['label'] columns = ["AssayNumber", "Strain", "TraitName", "Replicate", "Value"] # Extract table data data = json.loads(request.values['table_data']) data = [x for x in data[1:] if x[0] is not None] trait = data[0][2] data_tsv = convert_data_table_to_tsv(data, columns) # Generate an ID for the data based on its hash data_hash = get_object_hash(data, length=32) logger.debug(data_hash) id = unique_id() try: h = create_new_heritability_report(id, user.name, label, data_hash, trait, data_tsv) except Exception as ex: if str(type(ex).__name__) == 'DuplicateDataError': flash('It looks like you submitted that data already - redirecting to your list of Heritability Reports', 'danger') return jsonify({'duplicate': True, 'data_hash': data_hash, 'id': id}) if str(type(ex).__name__) == 'CachedDataError': flash('It looks like that data has already been submitted - redirecting to the saved results', 'danger') return jsonify({'cached': True, 'data_hash': data_hash, 'id': id}) return jsonify({'started': True, 'data_hash': data_hash, 'id': id}) # TODO: Move this into a separate service @heritability_bp.route("/heritability/h2/<id>") @jwt_required() def heritability_result(id): title = "Heritability Results" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} user = get_current_user() hr = get_heritability_report(id) ready = False data_url = generate_blob_url(hr.get_bucket_name(), hr.get_data_blob_path()) if (not hr._exists) or (hr.username != user.name): flash('You do not have access to that report', 'danger') abort(401) data_hash = hr.data_hash data_blob = hr.get_data_blob_path() result_blob = hr.get_result_blob_path() data = get_blob(hr.get_bucket_name(), hr.get_data_blob_path()) result = get_blob(hr.get_bucket_name(), hr.get_result_blob_path()) if data is None: return abort(404, description="Heritability report not found") data = data.download_as_string().decode('utf-8') data = pd.read_csv(io.StringIO(data), sep="\t") data['AssayNumber'] = data['AssayNumber'].astype(str) data['label'] = data.apply(lambda x: f"{x['AssayNumber']}: {x['Value']}", 1) data = data.to_dict('records') trait = data[0]['TraitName'] # Get trait and set title subtitle = trait if result: hr.status = 'COMPLETE' hr.save() result = result.download_as_string().decode('utf-8') result = pd.read_csv(io.StringIO(result), sep="\t") result = result.to_dict('records')[0] fnam=datetime.today().strftime('%Y%m%d.')+trait ready = True return render_template("tools/heritability/view.html", **locals())
33.756098
164
0.684429
import io import pandas as pd import json from flask import (flash, request, redirect, url_for, jsonify, render_template, Blueprint, abort) from logzero import logger from datetime import datetime from base.forms import HeritabilityForm from base.utils.auth import jwt_required, admin_required, get_jwt, get_current_user from caendr.api.strain import get_strains from caendr.services.heritability_report import get_all_heritability_results, get_user_heritability_results, create_new_heritability_report, get_heritability_report from caendr.utils.data import unique_id, convert_data_table_to_tsv, get_object_hash from caendr.services.cloud.storage import get_blob, generate_blob_url heritability_bp = Blueprint('heritability', __name__) @heritability_bp.route('/heritability') def heritability(): title = "Heritability Calculator" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} form = HeritabilityForm() hide_form = True strain_list = [] return render_template('tools/heritability/submit.html', **locals()) @heritability_bp.route('/heritability/create', methods=["GET"]) @jwt_required() def heritability_create(): title = "Heritability Calculator" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} jwt_csrf_token = (get_jwt() or {}).get("csrf") form = HeritabilityForm() strain_data = get_strains() strain_list = [] for x in strain_data: strain_list.append(x.strain) hide_form = False id = unique_id() return render_template('tools/heritability/submit.html', **locals()) @heritability_bp.route("/heritability/all-results") @admin_required() def heritability_all_results(): title = "All Heritability Results" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} user = get_current_user() items = get_all_heritability_results() return render_template('tools/heritability/list-all.html', **locals()) @heritability_bp.route("/heritability/my-results") @jwt_required() def heritability_user_results(): title = "My Heritability Results" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} user = get_current_user() items = get_user_heritability_results(user.name) return render_template('tools/heritability/list-user.html', **locals()) @heritability_bp.route('/heritability/submit', methods=["POST"]) @jwt_required() def submit_h2(): user = get_current_user() label = request.values['label'] columns = ["AssayNumber", "Strain", "TraitName", "Replicate", "Value"] data = json.loads(request.values['table_data']) data = [x for x in data[1:] if x[0] is not None] trait = data[0][2] data_tsv = convert_data_table_to_tsv(data, columns) data_hash = get_object_hash(data, length=32) logger.debug(data_hash) id = unique_id() try: h = create_new_heritability_report(id, user.name, label, data_hash, trait, data_tsv) except Exception as ex: if str(type(ex).__name__) == 'DuplicateDataError': flash('It looks like you submitted that data already - redirecting to your list of Heritability Reports', 'danger') return jsonify({'duplicate': True, 'data_hash': data_hash, 'id': id}) if str(type(ex).__name__) == 'CachedDataError': flash('It looks like that data has already been submitted - redirecting to the saved results', 'danger') return jsonify({'cached': True, 'data_hash': data_hash, 'id': id}) return jsonify({'started': True, 'data_hash': data_hash, 'id': id}) @heritability_bp.route("/heritability/h2/<id>") @jwt_required() def heritability_result(id): title = "Heritability Results" alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')} user = get_current_user() hr = get_heritability_report(id) ready = False data_url = generate_blob_url(hr.get_bucket_name(), hr.get_data_blob_path()) if (not hr._exists) or (hr.username != user.name): flash('You do not have access to that report', 'danger') abort(401) data_hash = hr.data_hash data_blob = hr.get_data_blob_path() result_blob = hr.get_result_blob_path() data = get_blob(hr.get_bucket_name(), hr.get_data_blob_path()) result = get_blob(hr.get_bucket_name(), hr.get_result_blob_path()) if data is None: return abort(404, description="Heritability report not found") data = data.download_as_string().decode('utf-8') data = pd.read_csv(io.StringIO(data), sep="\t") data['AssayNumber'] = data['AssayNumber'].astype(str) data['label'] = data.apply(lambda x: f"{x['AssayNumber']}: {x['Value']}", 1) data = data.to_dict('records') trait = data[0]['TraitName'] subtitle = trait if result: hr.status = 'COMPLETE' hr.save() result = result.download_as_string().decode('utf-8') result = pd.read_csv(io.StringIO(result), sep="\t") result = result.to_dict('records')[0] fnam=datetime.today().strftime('%Y%m%d.')+trait ready = True return render_template("tools/heritability/view.html", **locals())
true
true
f716a488f4da02f72691c1194f86e83d967d3e2b
45,335
py
Python
test/test_sort_and_select.py
kbrose/pytorch
fc0b8e60337ae46b90ed5d2f6d1f623f0f8d6581
[ "Intel" ]
null
null
null
test/test_sort_and_select.py
kbrose/pytorch
fc0b8e60337ae46b90ed5d2f6d1f623f0f8d6581
[ "Intel" ]
null
null
null
test/test_sort_and_select.py
kbrose/pytorch
fc0b8e60337ae46b90ed5d2f6d1f623f0f8d6581
[ "Intel" ]
null
null
null
import torch import numpy as np import random from torch._six import nan from itertools import permutations, product from torch.testing import all_types, all_types_and from torch.testing._internal.common_utils import \ (TEST_WITH_ROCM, TestCase, run_tests, make_tensor, slowTest) from torch.testing._internal.common_device_type import \ (instantiate_device_type_tests, dtypes, onlyOnCPUAndCUDA, skipCUDAIfRocm, onlyCUDA, dtypesIfCUDA, dtypesIfCPU, onlyCPU, largeTensorTest) # TODO: remove this SIZE = 100 class TestSortAndSelect(TestCase): def assertIsOrdered(self, order, x, mxx, ixx, task): SIZE = x.size(1) if order == 'descending': def check_order(a, b): # `a != a` because we put NaNs # at the end of ascending sorted lists, # and the beginning of descending ones. return ((a != a) | (a >= b)).all().item() elif order == 'ascending': def check_order(a, b): # see above return ((b != b) | (a <= b)).all().item() else: error('unknown order "{}", must be "ascending" or "descending"'.format(order)) are_ordered = True for k in range(1, SIZE): self.assertTrue(check_order(mxx[:, k - 1], mxx[:, k]), 'torch.sort ({}) values unordered for {}'.format(order, task)) seen = set() indicesCorrect = True size0 = x.size(0) size = x.size(x.dim() - 1) x = x.tolist() mxx = mxx.tolist() ixx = ixx.tolist() for k in range(size0): seen.clear() for j in range(size): self.assertEqual(x[k][ixx[k][j]], mxx[k][j], msg='torch.sort ({}) indices wrong for {}'.format(order, task)) seen.add(ixx[k][j]) self.assertEqual(len(seen), size) def test_sort(self, device): # on CUDA 2048 vs >2048 have different code path for the dim being sorted for SIZE in (4, 2049): x = torch.rand(4, SIZE, device=device) res1val, res1ind = torch.sort(x) # Test inplace y = x.clone() y_inds = torch.tensor((), dtype=torch.int64, device=device) torch.sort(y, out=(y, y_inds)) x_vals, x_inds = torch.sort(x) self.assertEqual(x_vals, y) self.assertEqual(x_inds, y_inds) # Test use of result tensor res2val = torch.tensor((), device=device) res2ind = torch.tensor((), device=device, dtype=torch.long) torch.sort(x, out=(res2val, res2ind)) self.assertEqual(res1val, res2val, atol=0, rtol=0) self.assertEqual(res1ind, res2ind, atol=0, rtol=0) self.assertEqual(torch.argsort(x), res1ind) self.assertEqual(x.argsort(), res1ind) # Test sorting of random numbers self.assertIsOrdered('ascending', x, res2val, res2ind, 'random') # Test simple sort self.assertEqual( torch.sort(torch.tensor((50, 40, 30, 20, 10), device=device))[0], torch.tensor((10, 20, 30, 40, 50), device=device), atol=0, rtol=0 ) # Test that we still have proper sorting with duplicate keys x = torch.floor(torch.rand(4, SIZE, device=device) * 10) torch.sort(x, out=(res2val, res2ind)) self.assertIsOrdered('ascending', x, res2val, res2ind, 'random with duplicate keys') # DESCENDING SORT x = torch.rand(4, SIZE, device=device) res1val, res1ind = torch.sort(x, x.dim() - 1, True) # Test use of result tensor res2val = torch.tensor((), device=device) res2ind = torch.tensor((), device=device, dtype=torch.long) torch.sort(x, x.dim() - 1, True, out=(res2val, res2ind)) self.assertEqual(res1val, res2val, atol=0, rtol=0) self.assertEqual(res1ind, res2ind, atol=0, rtol=0) self.assertEqual(torch.argsort(x, x.dim() - 1, True), res1ind) self.assertEqual(x.argsort(x.dim() - 1, True), res1ind) # Test sorting of random numbers self.assertIsOrdered('descending', x, res2val, res2ind, 'random') # Test simple sort task self.assertEqual( torch.sort(torch.tensor((10, 20, 30, 40, 50), device=device), 0, True)[0], torch.tensor((50, 40, 30, 20, 10), device=device), atol=0, rtol=0 ) # Test that we still have proper sorting with duplicate keys self.assertIsOrdered('descending', x, res2val, res2ind, 'random with duplicate keys') # Test sorting with NaNs x = torch.rand(4, SIZE, device=device) x[1][2] = float('NaN') x[3][0] = float('NaN') torch.sort(x, out=(res2val, res2ind)) self.assertIsOrdered('ascending', x, res2val, res2ind, 'random with NaNs') torch.sort(x, out=(res2val, res2ind), descending=True) self.assertIsOrdered('descending', x, res2val, res2ind, 'random with NaNs') # FIXME: remove torch.bool from unsupported types once support is added for cub sort @dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bool, torch.complex64, torch.complex128}) def test_stable_sort(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return sizes = (100, 1000, 10000) for ncopies in sizes: x = torch.tensor([0, 1] * ncopies, dtype=dtype, device=device) _, idx = x.sort(stable=True) self.assertEqual( idx[:ncopies], torch.arange(start=0, end=2 * ncopies, step=2, device=device) ) self.assertEqual( idx[ncopies:], torch.arange(start=1, end=2 * ncopies, step=2, device=device) ) @onlyCUDA @dtypes(torch.uint8) @largeTensorTest('200GB') # Unfortunately 80GB A100 is not large enough def test_sort_large(self, device, dtype): t0 = torch.randperm(8192, device=device).to(dtype) t = t0.view(1, 8192).expand(2 ** 18 + 1, -1).contiguous() v, i = t.sort() del t iv, im = i.var_mean(dim=0) del i vv, vm = v.var_mean(dim=0) del v self.assertEqual(vv, torch.zeros_like(vv)) self.assertEqual(iv, torch.zeros_like(iv)) self.assertEqual(vm, torch.arange(255, dtype=dtype, device=device)) self.assertEqual(im, t0.sort().indices) def _test_sort_discontiguous(self, device, dtype): # on CUDA 2048 vs >2048 have different code path for the dim being sorted sizes = (5, 7, 2049) for shape in permutations(sizes): for perm in permutations((0, 1, 2)): for dim in range(3): t = torch.randn(shape, device=device, dtype=dtype).permute(perm) r1 = t.sort(dim=dim) r2 = t.contiguous().sort(dim=dim) self.assertEqual(r1, r2) n = t.size(dim) # assert ordered self.assertTrue((r1.values.narrow(dim, 1, n - 1) >= r1.values.narrow(dim, 0, n - 1)).all()) # assert that different segments does not mix, which can easily happen # if the stride is not handled correctly self.assertTrue((t.unsqueeze(-1).transpose(dim, -1) == r1.values.unsqueeze(-1)).any(dim=dim).any(dim=-1).all()) # assert stride is preserved if self.device_type == 'cuda': # FIXME: this behavior should be true for all cases, not # just the one specified in if condition self.assertEqual(r1.values.stride(), t.stride()) self.assertEqual(r1.indices.stride(), t.stride()) @onlyCUDA @dtypes(torch.float32) def test_sort_discontiguous(self, device, dtype): self._test_sort_discontiguous(device, dtype) @slowTest # this test is slow on CPU, but not on CUDA @onlyCPU @dtypes(torch.float32) def test_sort_discontiguous_slow(self, device, dtype): self._test_sort_discontiguous(device, dtype) # FIXME: remove torch.bool from unsupported types once support is added for cub sort @dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bool, torch.complex64, torch.complex128}) def test_stable_sort_against_numpy(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return if dtype in torch.testing.floating_types_and(torch.float16, torch.bfloat16): inf = float('inf') neg_inf = -float('inf') nan = float('nan') else: if dtype != torch.bool: # no torch.iinfo support for torch.bool inf = torch.iinfo(dtype).max neg_inf = torch.iinfo(dtype).min else: inf = True neg_inf = ~inf # no nan for integral types, we use inf instead for simplicity nan = inf def generate_samples(): from itertools import chain, combinations for sizes in [(1025,), (10000,)]: size = sizes[0] # binary strings yield (torch.tensor([0, 1] * size, dtype=dtype, device=device), 0) if self.device_type == 'cuda': return yield (torch.tensor([0, 1] * 100, dtype=dtype, device=device), 0) def repeated_index_fill(t, dim, idxs, vals): res = t for idx, val in zip(idxs, vals): res = res.index_fill(dim, idx, val) return res for sizes in [(1, 10), (10, 1), (10, 10), (10, 10, 10)]: size = min(*sizes) x = (torch.randn(*sizes, device=device) * size).to(dtype) yield (x, 0) # Generate tensors which are being filled at random locations # with values from the non-empty subsets of the set (inf, neg_inf, nan) # for each dimension. n_fill_vals = 3 # cardinality of (inf, neg_inf, nan) for dim in range(len(sizes)): idxs = (torch.randint(high=size, size=(size // 10,)) for i in range(n_fill_vals)) vals = (inf, neg_inf, nan) subsets = chain.from_iterable(combinations(list(zip(idxs, vals)), r) for r in range(1, n_fill_vals + 1)) for subset in subsets: idxs_subset, vals_subset = zip(*subset) yield (repeated_index_fill(x, dim, idxs_subset, vals_subset), dim) for sample, dim in generate_samples(): _, idx_torch = sample.sort(dim=dim, stable=True) if dtype is torch.bfloat16: sample_numpy = sample.float().cpu().numpy() else: sample_numpy = sample.cpu().numpy() idx_numpy = np.argsort(sample_numpy, axis=dim, kind='stable') self.assertEqual(idx_torch, idx_numpy) @dtypes(*(torch.testing.get_all_int_dtypes() + torch.testing.get_all_fp_dtypes())) def test_msort(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return def test(shape): tensor = make_tensor(shape, device, dtype, low=-9, high=9) if tensor.size() != torch.Size([]): if dtype is torch.bfloat16: expected = torch.from_numpy(np.msort(tensor.float().cpu().numpy())).bfloat16() else: expected = torch.from_numpy(np.msort(tensor.cpu().numpy())) else: expected = tensor # numpy.msort() does not support empty shapes tensor result = torch.msort(tensor) self.assertEqual(result, expected) out = torch.empty_like(result) torch.msort(tensor, out=out) self.assertEqual(out, expected) shapes = ( [], [0, ], [20, ], [1, 20], [30, 30], [10, 20, 30] ) for shape in shapes: test(shape) def test_topk(self, device): def topKViaSort(t, k, dim, dir): sorted, indices = t.sort(dim, dir) return sorted.narrow(dim, 0, k), indices.narrow(dim, 0, k) def compareTensors(t, res1, ind1, res2, ind2, dim): # Values should be exactly equivalent self.assertEqual(res1, res2, atol=0, rtol=0) # Indices might differ based on the implementation, since there is # no guarantee of the relative order of selection if not ind1.eq(ind2).all(): # To verify that the indices represent equivalent elements, # gather from the input using the topk indices and compare against # the sort indices vals = t.gather(dim, ind2) self.assertEqual(res1, vals, atol=0, rtol=0) def compare(t, k, dim, dir): topKVal, topKInd = t.topk(k, dim, dir, True) sortKVal, sortKInd = topKViaSort(t, k, dim, dir) compareTensors(t, sortKVal, sortKInd, topKVal, topKInd, dim) t = torch.rand(random.randint(1, SIZE), random.randint(1, SIZE), random.randint(1, SIZE), device=device) for _kTries in range(3): for _dimTries in range(3): for transpose in (True, False): for dir in (True, False): testTensor = t if transpose: dim1 = random.randrange(t.ndimension()) dim2 = dim1 while dim1 == dim2: dim2 = random.randrange(t.ndimension()) testTensor = t.transpose(dim1, dim2) dim = random.randrange(testTensor.ndimension()) k = random.randint(1, testTensor.size(dim)) compare(testTensor, k, dim, dir) def test_topk_arguments(self, device): q = torch.randn(10, 2, 10, device=device) # Make sure True isn't mistakenly taken as the 2nd dimension (interpreted as 1) self.assertRaises(TypeError, lambda: q.topk(4, True)) @skipCUDAIfRocm def test_unique_dim(self, device): self.assertFalse(hasattr(torch, 'unique_dim')) def run_test(device, dtype): x = torch.tensor([[[1., 1.], [0., 1.], [2., 1.], [0., 1.]], [[1., 1.], [0., 1.], [2., 1.], [0., 1.]]], dtype=dtype, device=device) x_empty = torch.empty(5, 0, dtype=dtype, device=device) x_ill_formed_empty = torch.empty(5, 0, 0, dtype=dtype, device=device) x_ill_formed_empty_another = torch.empty(5, 0, 5, dtype=dtype, device=device) expected_unique_dim0 = torch.tensor([[[1., 1.], [0., 1.], [2., 1.], [0., 1.]]], dtype=dtype, device=device) expected_inverse_dim0 = torch.tensor([0, 0]) expected_counts_dim0 = torch.tensor([2]) expected_unique_dim1 = torch.tensor([[[0., 1.], [1., 1.], [2., 1.]], [[0., 1.], [1., 1.], [2., 1.]]], dtype=dtype, device=device) expected_unique_dim1_bool = torch.tensor([[[False, True], [True, True]], [[False, True], [True, True]]], dtype=torch.bool, device=device) expected_inverse_dim1 = torch.tensor([1, 0, 2, 0]) expected_inverse_dim1_bool = torch.tensor([1, 0, 1, 0]) expected_counts_dim1 = torch.tensor([2, 1, 1]) expected_counts_dim1_bool = torch.tensor([2, 2]) expected_unique_dim2 = torch.tensor([[[1., 1.], [0., 1.], [2., 1.], [0., 1.]], [[1., 1.], [0., 1.], [2., 1.], [0., 1.]]], dtype=dtype, device=device) expected_inverse_dim2 = torch.tensor([0, 1]) expected_counts_dim2 = torch.tensor([1, 1]) expected_unique_empty = torch.tensor([], dtype=dtype, device=device) expected_inverse_empty = torch.tensor([], dtype=torch.long, device=device) expected_counts_empty = torch.tensor([], dtype=torch.long, device=device) # dim0 x_unique = torch.unique(x, dim=0) self.assertEqual(expected_unique_dim0, x_unique) x_unique, x_inverse = torch.unique( x, return_inverse=True, dim=0) self.assertEqual(expected_unique_dim0, x_unique) self.assertEqual(expected_inverse_dim0, x_inverse) x_unique, x_counts = torch.unique( x, return_inverse=False, return_counts=True, dim=0) self.assertEqual(expected_unique_dim0, x_unique) self.assertEqual(expected_counts_dim0, x_counts) x_unique, x_inverse, x_counts = torch.unique( x, return_inverse=True, return_counts=True, dim=0) self.assertEqual(expected_unique_dim0, x_unique) self.assertEqual(expected_inverse_dim0, x_inverse) self.assertEqual(expected_counts_dim0, x_counts) # dim1 x_unique = torch.unique(x, dim=1) if x.dtype == torch.bool: self.assertEqual(expected_unique_dim1_bool, x_unique) else: self.assertEqual(expected_unique_dim1, x_unique) x_unique, x_inverse = torch.unique( x, return_inverse=True, dim=1) if x.dtype == torch.bool: self.assertEqual(expected_unique_dim1_bool, x_unique) self.assertEqual(expected_inverse_dim1_bool, x_inverse) else: self.assertEqual(expected_unique_dim1, x_unique) self.assertEqual(expected_inverse_dim1, x_inverse) x_unique, x_counts = torch.unique( x, return_inverse=False, return_counts=True, dim=1) if x.dtype == torch.bool: self.assertEqual(expected_unique_dim1_bool, x_unique) self.assertEqual(expected_counts_dim1_bool, x_counts) else: self.assertEqual(expected_unique_dim1, x_unique) self.assertEqual(expected_counts_dim1, x_counts) x_unique, x_inverse, x_counts = torch.unique( x, return_inverse=True, return_counts=True, dim=1) if x.dtype == torch.bool: self.assertEqual(expected_unique_dim1_bool, x_unique) self.assertEqual(expected_inverse_dim1_bool, x_inverse) self.assertEqual(expected_counts_dim1_bool, x_counts) else: self.assertEqual(expected_unique_dim1, x_unique) self.assertEqual(expected_inverse_dim1, x_inverse) self.assertEqual(expected_counts_dim1, x_counts) # dim2 x_unique = torch.unique(x, dim=2) self.assertEqual(expected_unique_dim2, x_unique) x_unique, x_inverse = torch.unique( x, return_inverse=True, dim=2) self.assertEqual(expected_unique_dim2, x_unique) self.assertEqual(expected_inverse_dim2, x_inverse) x_unique, x_counts = torch.unique( x, return_inverse=False, return_counts=True, dim=2) self.assertEqual(expected_unique_dim2, x_unique) self.assertEqual(expected_counts_dim2, x_counts) x_unique, x_inverse, x_counts = torch.unique( x, return_inverse=True, return_counts=True, dim=2) self.assertEqual(expected_unique_dim2, x_unique) self.assertEqual(expected_inverse_dim2, x_inverse) self.assertEqual(expected_counts_dim2, x_counts) # test empty tensor x_unique, x_inverse, x_counts = torch.unique( x_empty, return_inverse=True, return_counts=True, dim=1) self.assertEqual(expected_unique_empty, x_unique) self.assertEqual(expected_inverse_empty, x_inverse) self.assertEqual(expected_counts_empty, x_counts) # test not a well formed tensor # Checking for runtime error, as this is the expected behaviour with self.assertRaises(RuntimeError): torch.unique( x_ill_formed_empty, return_inverse=True, return_counts=True, dim=1) # test along dim2 with self.assertRaises(RuntimeError): torch.unique( x_ill_formed_empty_another, return_inverse=True, return_counts=True, dim=2) # test consecutive version y = torch.tensor( [[0, 1], [0, 1], [0, 1], [1, 2], [1, 2], [3, 4], [0, 1], [0, 1], [3, 4], [1, 2]], dtype=dtype, device=device ) expected_y_unique = torch.tensor( [[0, 1], [1, 2], [3, 4], [0, 1], [3, 4], [1, 2]], dtype=dtype, device=device ) expected_y_inverse = torch.tensor([0, 0, 0, 1, 1, 2, 3, 3, 4, 5], dtype=torch.int64, device=device) expected_y_counts = torch.tensor([3, 2, 1, 2, 1, 1], dtype=torch.int64, device=device) expected_y_inverse_bool = torch.tensor([0, 0, 0, 1, 1, 1, 2, 2, 3, 3], dtype=torch.int64, device=device) expected_y_counts_bool = torch.tensor([3, 3, 2, 2], dtype=torch.int64, device=device) y_unique, y_inverse, y_counts = torch.unique_consecutive(y, return_inverse=True, return_counts=True, dim=0) if x.dtype == torch.bool: self.assertEqual(expected_y_inverse_bool, y_inverse) self.assertEqual(expected_y_counts_bool, y_counts) else: self.assertEqual(expected_y_inverse, y_inverse) self.assertEqual(expected_y_counts, y_counts) run_test(device, torch.float) run_test(device, torch.double) run_test(device, torch.long) run_test(device, torch.uint8) run_test(device, torch.bool) @onlyCUDA def test_topk_noncontiguous_gpu(self, device): t = torch.randn(20, device=device)[::2] top1, idx1 = t.topk(5) top2, idx2 = t.contiguous().topk(5) self.assertEqual(top1, top2) self.assertEqual(idx1, idx2) def _test_topk_dtype(self, device, dtype, integral, size): if integral: a = torch.randint(torch.iinfo(dtype).min, torch.iinfo(dtype).max, size=(size,), dtype=dtype, device=device) else: a = torch.randn(size=(size,), dtype=dtype, device=device) sort_topk = a.sort()[0][-(size // 2):].flip(0) topk = a.topk(size // 2) self.assertEqual(sort_topk, topk[0]) # check values self.assertEqual(sort_topk, a[topk[1]]) # check indices @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64) def test_topk_integral(self, device, dtype): small = 10 large = 4096 for curr_size in (small, large): self._test_topk_dtype(device, dtype, True, curr_size) @onlyCUDA @dtypes(torch.bfloat16) @skipCUDAIfRocm def test_topk_bfloat16(self, device, dtype): small = 10 large = 8192 for curr_size in (small, large): self._test_topk_dtype(device, dtype, False, curr_size) @dtypesIfCUDA(*torch.testing.get_all_fp_dtypes()) @dtypes(torch.float, torch.double, torch.bfloat16) def test_topk_nonfinite(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return x = torch.tensor([float('nan'), float('inf'), 1e4, 0, -1e4, -float('inf')], device=device, dtype=dtype) val, idx = x.topk(4) expect = torch.tensor([float('nan'), float('inf'), 1e4, 0], device=device, dtype=dtype) self.assertEqual(val, expect) self.assertEqual(idx, [0, 1, 2, 3]) val, idx = x.topk(4, largest=False) expect = torch.tensor([-float('inf'), -1e4, 0, 1e4], device=device, dtype=dtype) self.assertEqual(val, expect) self.assertEqual(idx, [5, 4, 3, 2]) def test_topk_4d(self, device): x = torch.ones(2, 3072, 2, 2, device=device) x[:, 1, :, :] *= 2. x[:, 10, :, :] *= 1.5 val, ind = torch.topk(x, k=2, dim=1) expected_ind = torch.ones(2, 2, 2, 2, dtype=torch.long, device=device) expected_ind[:, 1, :, :] = 10 expected_val = torch.ones(2, 2, 2, 2, device=device) expected_val[:, 0, :, :] *= 2. expected_val[:, 1, :, :] *= 1.5 self.assertEqual(val, expected_val, atol=0, rtol=0) self.assertEqual(ind, expected_ind, atol=0, rtol=0) @onlyOnCPUAndCUDA @dtypesIfCUDA(*(torch.testing.get_all_dtypes(include_complex=False, include_bool=False, include_half=False, include_bfloat16=True))) @dtypes(*(torch.testing.get_all_dtypes(include_complex=False, include_bool=False, include_half=False, include_bfloat16=False))) def test_topk_zero(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return # https://github.com/pytorch/pytorch/issues/49205 t = torch.rand(2, 2, device=device).to(dtype=dtype) val, idx = torch.topk(t, k=0, largest=False) self.assertEqual(val.size(), torch.Size([2, 0])) self.assertEqual(idx.size(), torch.Size([2, 0])) def _test_unique_scalar_empty(self, dtype, device, f): # test scalar x = torch.tensor(0, dtype=dtype, device=device) unique, inverse, counts = f(x, return_inverse=True, return_counts=True) expected_unique = torch.tensor([0], dtype=dtype, device=device) expected_inverse = torch.tensor(0, device=device) expected_counts = torch.tensor([1], device=device) self.assertEqual(unique, expected_unique) self.assertEqual(inverse, expected_inverse) self.assertEqual(counts, expected_counts) # test zero sized tensor x = torch.zeros((0, 0, 3), dtype=dtype, device=device) unique, inverse, counts = f(x, return_inverse=True, return_counts=True) expected_unique = torch.tensor([], dtype=dtype, device=device) expected_inverse = torch.empty((0, 0, 3), dtype=torch.long, device=device) expected_counts = torch.tensor([], dtype=torch.long, device=device) self.assertEqual(unique, expected_unique) self.assertEqual(inverse, expected_inverse) self.assertEqual(counts, expected_counts) def _test_unique_with_expects(self, device, dtype, f, x, expected_unique, expected_inverse, expected_counts, additional_shape): def ensure_tuple(x): if isinstance(x, torch.Tensor): return (x,) return x for return_inverse in [True, False]: for return_counts in [True, False]: # test with expected ret = ensure_tuple(f(x, return_inverse=return_inverse, return_counts=return_counts)) self.assertEqual(len(ret), 1 + int(return_inverse) + int(return_counts)) self.assertEqual(expected_unique, ret[0]) if return_inverse: self.assertEqual(expected_inverse, ret[1]) if return_counts: count_index = 1 + int(return_inverse) self.assertEqual(expected_counts, ret[count_index]) # tests per-element unique on a higher rank tensor. y = x.view(additional_shape) y_unique, y_inverse, y_counts = f(y, return_inverse=True, return_counts=True) self.assertEqual(expected_unique, y_unique) self.assertEqual(expected_inverse.view(additional_shape), y_inverse) self.assertEqual(expected_counts, y_counts) @dtypesIfCPU(*set(torch.testing.get_all_dtypes()) - {torch.complex64, torch.complex128}) @dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bfloat16, torch.complex64, torch.complex128}) def test_unique(self, device, dtype): if dtype is torch.half and self.device_type == 'cpu': return # CPU does not have half support def ensure_tuple(x): if isinstance(x, torch.Tensor): return (x,) return x if dtype is torch.bool: x = torch.tensor([True, False, False, False, True, False, True, False], dtype=torch.bool, device=device) expected_unique = torch.tensor([False, True], dtype=torch.bool, device=device) expected_inverse = torch.tensor([1, 0, 0, 0, 1, 0, 1, 0], dtype=torch.long, device=device) expected_counts = torch.tensor([5, 3], dtype=torch.long, device=device) else: x = torch.tensor([1, 2, 3, 2, 8, 5, 2, 3], dtype=dtype, device=device) expected_unique = torch.tensor([1, 2, 3, 5, 8], dtype=dtype, device=device) expected_inverse = torch.tensor([0, 1, 2, 1, 4, 3, 1, 2], device=device) expected_counts = torch.tensor([1, 3, 2, 1, 1], device=device) # test sorted unique fs = ( lambda x, **kwargs: torch.unique(x, sorted=True, **kwargs), lambda x, **kwargs: x.unique(sorted=True, **kwargs), ) x_sliced = torch.empty(x.size(0) * 2, dtype=dtype, device=device)[::2].copy_(x) xs = (x, x_sliced) for f, x in product(fs, xs): self._test_unique_with_expects(device, dtype, f, x, expected_unique, expected_inverse, expected_counts, (2, 2, 2)) self._test_unique_scalar_empty(dtype, device, f) # test unsorted unique fs = ( lambda x, **kwargs: torch.unique(x, sorted=False, **kwargs), lambda x, **kwargs: x.unique(sorted=False, **kwargs) ) for f, x in product(fs, xs): self._test_unique_scalar_empty(dtype, device, f) for return_inverse, return_counts in product((True, False), repeat=2): ret = ensure_tuple(f(x, return_inverse=return_inverse, return_counts=return_counts)) self.assertEqual(len(ret), 1 + int(return_inverse) + int(return_counts)) x_list = x.tolist() x_unique_list = ret[0].tolist() self.assertEqual(expected_unique.tolist(), sorted(x_unique_list)) if return_inverse: x_inverse_list = ret[1].tolist() for i, j in enumerate(x_inverse_list): self.assertEqual(x_list[i], x_unique_list[j]) if return_counts: count_index = 1 + int(return_inverse) x_counts_list = ret[count_index].tolist() for i, j in zip(x_unique_list, x_counts_list): count = 0 for k in x_list: if k == i: count += 1 self.assertEqual(j, count) @dtypesIfCPU(*set(torch.testing.get_all_dtypes()) - {torch.complex64, torch.complex128}) @dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bfloat16, torch.complex64, torch.complex128}) def test_unique_consecutive(self, device, dtype): if dtype is torch.half and self.device_type == 'cpu': return # CPU does not have half support if dtype is torch.bool: x = torch.tensor([True, False, False, False, True, True, False, False, False], dtype=torch.bool, device=device) expected_unique = torch.tensor([True, False, True, False], dtype=torch.bool, device=device) expected_inverse = torch.tensor([0, 1, 1, 1, 2, 2, 3, 3, 3], dtype=torch.long, device=device) expected_counts = torch.tensor([1, 3, 2, 3], dtype=torch.long, device=device) else: x = torch.tensor([1, 2, 2, 2, 5, 5, 2, 2, 3], dtype=dtype, device=device) expected_unique = torch.tensor([1, 2, 5, 2, 3], dtype=dtype, device=device) expected_inverse = torch.tensor([0, 1, 1, 1, 2, 2, 3, 3, 4], device=device) expected_counts = torch.tensor([1, 3, 2, 2, 1], device=device) for f in [torch.unique_consecutive, lambda x, **kwargs: x.unique_consecutive(**kwargs)]: self._test_unique_with_expects(device, dtype, f, x, expected_unique, expected_inverse, expected_counts, (3, 3)) self._test_unique_scalar_empty(dtype, device, f) @dtypes(torch.double) def test_kthvalue(self, device, dtype): SIZE = 50 x = torch.rand(SIZE, SIZE, SIZE, dtype=dtype, device=device) x0 = x.clone() k = random.randint(1, SIZE) res1val, res1ind = torch.kthvalue(x, k, keepdim=False) res2val, res2ind = torch.sort(x) self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0) self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0) # test use of result tensors k = random.randint(1, SIZE) res1val = torch.tensor([], dtype=dtype, device=device) res1ind = torch.tensor([], dtype=torch.long, device=device) torch.kthvalue(x, k, keepdim=False, out=(res1val, res1ind)) res2val, res2ind = torch.sort(x) self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0) self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0) # test non-default dim k = random.randint(1, SIZE) res1val, res1ind = torch.kthvalue(x, k, 0, keepdim=False) res2val, res2ind = torch.sort(x, 0) self.assertEqual(res1val, res2val[k - 1], atol=0, rtol=0) self.assertEqual(res1ind, res2ind[k - 1], atol=0, rtol=0) # non-contiguous y = x.narrow(1, 0, 1) y0 = y.contiguous() k = random.randint(1, SIZE) res1val, res1ind = torch.kthvalue(y, k) res2val, res2ind = torch.kthvalue(y0, k) self.assertEqual(res1val, res2val, atol=0, rtol=0) self.assertEqual(res1ind, res2ind, atol=0, rtol=0) # non-contiguous [Reference: https://github.com/pytorch/pytorch/issues/45721] non_contig_t = torch.tensor([0, -1, 1, -2, 2], dtype=dtype, device=device)[::2] expected_val, expected_ind = non_contig_t.contiguous().kthvalue(2) non_contig_cpu_t = non_contig_t.cpu() expected_val_cpu, expected_ind_cpu = non_contig_cpu_t.kthvalue(2) out_val, out_ind = non_contig_t.kthvalue(2) self.assertEqual(expected_val, out_val, atol=0, rtol=0) self.assertEqual(expected_ind, out_ind, atol=0, rtol=0) self.assertEqual(expected_val_cpu, out_val, atol=0, rtol=0) self.assertEqual(expected_ind_cpu, out_ind, atol=0, rtol=0) # check that the input wasn't modified self.assertEqual(x, x0, atol=0, rtol=0) # simple test case (with repetitions) y = torch.tensor((3., 5, 4, 1, 1, 5), dtype=dtype, device=device) self.assertEqual(torch.kthvalue(y, 3)[0], 3, atol=0, rtol=0) self.assertEqual(torch.kthvalue(y, 2)[0], 1, atol=0, rtol=0) # simple test case (with NaN) SIZE = 50 x = torch.rand(SIZE, SIZE, SIZE, dtype=dtype, device=device) x[torch.arange(SIZE), :, torch.randint(50, (50,))] = nan ks = [random.randint(1, SIZE), 1, SIZE, SIZE - 1] res2val, res2ind = torch.sort(x) for k in ks: res1val, res1ind = torch.kthvalue(x, k, keepdim=False) self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0) self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0) # test overlapping output @dtypes(torch.double) @onlyOnCPUAndCUDA # Fails on XLA def test_kthvalue_overlap(self, device, dtype): S = 10 k = 5 a = torch.randn(S, device=device) indices = torch.empty((), device=device, dtype=torch.long) with self.assertRaisesRegex(RuntimeError, "unsupported operation:"): torch.kthvalue(a, k, out=(a, indices)) @dtypes(torch.float) @onlyOnCPUAndCUDA # Fails on XLA def test_kthvalue_scalar(self, device, dtype): # Test scalar input (test case from https://github.com/pytorch/pytorch/issues/30818) # Tests that passing a scalar tensor or 1D tensor with 1 element work either way res = torch.tensor(2, device=device, dtype=dtype).kthvalue(1) ref = torch.tensor([2], device=device, dtype=dtype).kthvalue(1) self.assertEqual(res[0], ref[0].squeeze()) self.assertEqual(res[1], ref[1].squeeze()) @dtypes(*all_types()) @dtypesIfCUDA(*all_types_and(torch.half)) def test_isin(self, device, dtype): def assert_isin_equal(a, b): # Compare to the numpy reference implementation. x = torch.isin(a, b) a = a.cpu().numpy() if torch.is_tensor(a) else np.array(a) b = b.cpu().numpy() if torch.is_tensor(b) else np.array(b) y = np.isin(a, b) self.assertEqual(x, y) # multi-dim tensor, multi-dim tensor a = torch.arange(24, device=device, dtype=dtype).reshape([2, 3, 4]) b = torch.tensor([[10, 20, 30], [0, 1, 3], [11, 22, 33]], device=device, dtype=dtype) assert_isin_equal(a, b) # zero-dim tensor zero_d = torch.tensor(3, device=device, dtype=dtype) assert_isin_equal(zero_d, b) assert_isin_equal(a, zero_d) assert_isin_equal(zero_d, zero_d) # empty tensor empty = torch.tensor([], device=device, dtype=dtype) assert_isin_equal(empty, b) assert_isin_equal(a, empty) assert_isin_equal(empty, empty) # scalar assert_isin_equal(a, 6) assert_isin_equal(5, b) def define_expected(lst, invert=False): expected = torch.tensor(lst, device=device) if invert: expected = expected.logical_not() return expected # Adapted from numpy's in1d tests for mult in [1, 10]: for invert in [False, True]: a = torch.tensor([5, 7, 1, 2], device=device, dtype=dtype) b = torch.tensor([2, 4, 3, 1, 5] * mult, device=device, dtype=dtype) ec = define_expected([True, False, True, True], invert=invert) c = torch.isin(a, b, assume_unique=True, invert=invert) self.assertEqual(c, ec) a[0] = 8 ec = define_expected([False, False, True, True], invert=invert) c = torch.isin(a, b, assume_unique=True, invert=invert) self.assertEqual(c, ec) a[0], a[3] = 4, 8 ec = define_expected([True, False, True, False], invert=invert) c = torch.isin(a, b, assume_unique=True, invert=invert) self.assertEqual(c, ec) a = torch.tensor([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5], device=device, dtype=dtype) b = torch.tensor([2, 3, 4] * mult, device=device, dtype=dtype) ec = define_expected([False, True, False, True, True, True, True, True, True, False, True, False, False, False], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) b = torch.tensor([2, 3, 4] * mult + [5, 5, 4] * mult, device=device, dtype=dtype) ec = define_expected([True, True, True, True, True, True, True, True, True, True, True, False, True, True], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) a = torch.tensor([5, 7, 1, 2], device=device, dtype=dtype) b = torch.tensor([2, 4, 3, 1, 5] * mult, device=device, dtype=dtype) ec = define_expected([True, False, True, True], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) a = torch.tensor([5, 7, 1, 1, 2], device=device, dtype=dtype) b = torch.tensor([2, 4, 3, 3, 1, 5] * mult, device=device, dtype=dtype) ec = define_expected([True, False, True, True, True], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) a = torch.tensor([5, 5], device=device, dtype=dtype) b = torch.tensor([2, 2] * mult, device=device, dtype=dtype) ec = define_expected([False, False], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) # multi-dimensional input case using sort-based algo for assume_unique in [False, True]: a = torch.arange(6, device=device, dtype=dtype).reshape([2, 3]) b = torch.arange(3, 30, device=device, dtype=dtype) ec = define_expected([[False, False, False], [True, True, True]], invert=invert) c = torch.isin(a, b, invert=invert, assume_unique=assume_unique) self.assertEqual(c, ec) def test_isin_different_dtypes(self, device): supported_types = all_types() if device == 'cpu' else all_types_and(torch.half) for mult in [1, 10]: for assume_unique in [False, True]: for dtype1, dtype2 in product(supported_types, supported_types): a = torch.tensor([1, 2, 3], device=device, dtype=dtype1) b = torch.tensor([3, 4, 5] * mult, device=device, dtype=dtype2) ec = torch.tensor([False, False, True], device=device) c = torch.isin(a, b, assume_unique=assume_unique) self.assertEqual(c, ec) @onlyCUDA @dtypes(*all_types()) def test_isin_different_devices(self, device, dtype): a = torch.arange(6, device=device, dtype=dtype).reshape([2, 3]) b = torch.arange(3, 30, device='cpu', dtype=dtype) with self.assertRaises(RuntimeError): torch.isin(a, b) c = torch.arange(6, device='cpu', dtype=dtype).reshape([2, 3]) d = torch.arange(3, 30, device=device, dtype=dtype) with self.assertRaises(RuntimeError): torch.isin(c, d) instantiate_device_type_tests(TestSortAndSelect, globals()) if __name__ == '__main__': run_tests()
45.28971
131
0.543179
import torch import numpy as np import random from torch._six import nan from itertools import permutations, product from torch.testing import all_types, all_types_and from torch.testing._internal.common_utils import \ (TEST_WITH_ROCM, TestCase, run_tests, make_tensor, slowTest) from torch.testing._internal.common_device_type import \ (instantiate_device_type_tests, dtypes, onlyOnCPUAndCUDA, skipCUDAIfRocm, onlyCUDA, dtypesIfCUDA, dtypesIfCPU, onlyCPU, largeTensorTest) SIZE = 100 class TestSortAndSelect(TestCase): def assertIsOrdered(self, order, x, mxx, ixx, task): SIZE = x.size(1) if order == 'descending': def check_order(a, b): return ((a != a) | (a >= b)).all().item() elif order == 'ascending': def check_order(a, b): return ((b != b) | (a <= b)).all().item() else: error('unknown order "{}", must be "ascending" or "descending"'.format(order)) are_ordered = True for k in range(1, SIZE): self.assertTrue(check_order(mxx[:, k - 1], mxx[:, k]), 'torch.sort ({}) values unordered for {}'.format(order, task)) seen = set() indicesCorrect = True size0 = x.size(0) size = x.size(x.dim() - 1) x = x.tolist() mxx = mxx.tolist() ixx = ixx.tolist() for k in range(size0): seen.clear() for j in range(size): self.assertEqual(x[k][ixx[k][j]], mxx[k][j], msg='torch.sort ({}) indices wrong for {}'.format(order, task)) seen.add(ixx[k][j]) self.assertEqual(len(seen), size) def test_sort(self, device): for SIZE in (4, 2049): x = torch.rand(4, SIZE, device=device) res1val, res1ind = torch.sort(x) y = x.clone() y_inds = torch.tensor((), dtype=torch.int64, device=device) torch.sort(y, out=(y, y_inds)) x_vals, x_inds = torch.sort(x) self.assertEqual(x_vals, y) self.assertEqual(x_inds, y_inds) res2val = torch.tensor((), device=device) res2ind = torch.tensor((), device=device, dtype=torch.long) torch.sort(x, out=(res2val, res2ind)) self.assertEqual(res1val, res2val, atol=0, rtol=0) self.assertEqual(res1ind, res2ind, atol=0, rtol=0) self.assertEqual(torch.argsort(x), res1ind) self.assertEqual(x.argsort(), res1ind) self.assertIsOrdered('ascending', x, res2val, res2ind, 'random') self.assertEqual( torch.sort(torch.tensor((50, 40, 30, 20, 10), device=device))[0], torch.tensor((10, 20, 30, 40, 50), device=device), atol=0, rtol=0 ) x = torch.floor(torch.rand(4, SIZE, device=device) * 10) torch.sort(x, out=(res2val, res2ind)) self.assertIsOrdered('ascending', x, res2val, res2ind, 'random with duplicate keys') x = torch.rand(4, SIZE, device=device) res1val, res1ind = torch.sort(x, x.dim() - 1, True) res2val = torch.tensor((), device=device) res2ind = torch.tensor((), device=device, dtype=torch.long) torch.sort(x, x.dim() - 1, True, out=(res2val, res2ind)) self.assertEqual(res1val, res2val, atol=0, rtol=0) self.assertEqual(res1ind, res2ind, atol=0, rtol=0) self.assertEqual(torch.argsort(x, x.dim() - 1, True), res1ind) self.assertEqual(x.argsort(x.dim() - 1, True), res1ind) self.assertIsOrdered('descending', x, res2val, res2ind, 'random') self.assertEqual( torch.sort(torch.tensor((10, 20, 30, 40, 50), device=device), 0, True)[0], torch.tensor((50, 40, 30, 20, 10), device=device), atol=0, rtol=0 ) self.assertIsOrdered('descending', x, res2val, res2ind, 'random with duplicate keys') x = torch.rand(4, SIZE, device=device) x[1][2] = float('NaN') x[3][0] = float('NaN') torch.sort(x, out=(res2val, res2ind)) self.assertIsOrdered('ascending', x, res2val, res2ind, 'random with NaNs') torch.sort(x, out=(res2val, res2ind), descending=True) self.assertIsOrdered('descending', x, res2val, res2ind, 'random with NaNs') @dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bool, torch.complex64, torch.complex128}) def test_stable_sort(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return sizes = (100, 1000, 10000) for ncopies in sizes: x = torch.tensor([0, 1] * ncopies, dtype=dtype, device=device) _, idx = x.sort(stable=True) self.assertEqual( idx[:ncopies], torch.arange(start=0, end=2 * ncopies, step=2, device=device) ) self.assertEqual( idx[ncopies:], torch.arange(start=1, end=2 * ncopies, step=2, device=device) ) @onlyCUDA @dtypes(torch.uint8) @largeTensorTest('200GB') def test_sort_large(self, device, dtype): t0 = torch.randperm(8192, device=device).to(dtype) t = t0.view(1, 8192).expand(2 ** 18 + 1, -1).contiguous() v, i = t.sort() del t iv, im = i.var_mean(dim=0) del i vv, vm = v.var_mean(dim=0) del v self.assertEqual(vv, torch.zeros_like(vv)) self.assertEqual(iv, torch.zeros_like(iv)) self.assertEqual(vm, torch.arange(255, dtype=dtype, device=device)) self.assertEqual(im, t0.sort().indices) def _test_sort_discontiguous(self, device, dtype): sizes = (5, 7, 2049) for shape in permutations(sizes): for perm in permutations((0, 1, 2)): for dim in range(3): t = torch.randn(shape, device=device, dtype=dtype).permute(perm) r1 = t.sort(dim=dim) r2 = t.contiguous().sort(dim=dim) self.assertEqual(r1, r2) n = t.size(dim) self.assertTrue((r1.values.narrow(dim, 1, n - 1) >= r1.values.narrow(dim, 0, n - 1)).all()) self.assertTrue((t.unsqueeze(-1).transpose(dim, -1) == r1.values.unsqueeze(-1)).any(dim=dim).any(dim=-1).all()) if self.device_type == 'cuda': self.assertEqual(r1.values.stride(), t.stride()) self.assertEqual(r1.indices.stride(), t.stride()) @onlyCUDA @dtypes(torch.float32) def test_sort_discontiguous(self, device, dtype): self._test_sort_discontiguous(device, dtype) @slowTest @onlyCPU @dtypes(torch.float32) def test_sort_discontiguous_slow(self, device, dtype): self._test_sort_discontiguous(device, dtype) @dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bool, torch.complex64, torch.complex128}) def test_stable_sort_against_numpy(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return if dtype in torch.testing.floating_types_and(torch.float16, torch.bfloat16): inf = float('inf') neg_inf = -float('inf') nan = float('nan') else: if dtype != torch.bool: inf = torch.iinfo(dtype).max neg_inf = torch.iinfo(dtype).min else: inf = True neg_inf = ~inf nan = inf def generate_samples(): from itertools import chain, combinations for sizes in [(1025,), (10000,)]: size = sizes[0] yield (torch.tensor([0, 1] * size, dtype=dtype, device=device), 0) if self.device_type == 'cuda': return yield (torch.tensor([0, 1] * 100, dtype=dtype, device=device), 0) def repeated_index_fill(t, dim, idxs, vals): res = t for idx, val in zip(idxs, vals): res = res.index_fill(dim, idx, val) return res for sizes in [(1, 10), (10, 1), (10, 10), (10, 10, 10)]: size = min(*sizes) x = (torch.randn(*sizes, device=device) * size).to(dtype) yield (x, 0) n_fill_vals = 3 for dim in range(len(sizes)): idxs = (torch.randint(high=size, size=(size // 10,)) for i in range(n_fill_vals)) vals = (inf, neg_inf, nan) subsets = chain.from_iterable(combinations(list(zip(idxs, vals)), r) for r in range(1, n_fill_vals + 1)) for subset in subsets: idxs_subset, vals_subset = zip(*subset) yield (repeated_index_fill(x, dim, idxs_subset, vals_subset), dim) for sample, dim in generate_samples(): _, idx_torch = sample.sort(dim=dim, stable=True) if dtype is torch.bfloat16: sample_numpy = sample.float().cpu().numpy() else: sample_numpy = sample.cpu().numpy() idx_numpy = np.argsort(sample_numpy, axis=dim, kind='stable') self.assertEqual(idx_torch, idx_numpy) @dtypes(*(torch.testing.get_all_int_dtypes() + torch.testing.get_all_fp_dtypes())) def test_msort(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return def test(shape): tensor = make_tensor(shape, device, dtype, low=-9, high=9) if tensor.size() != torch.Size([]): if dtype is torch.bfloat16: expected = torch.from_numpy(np.msort(tensor.float().cpu().numpy())).bfloat16() else: expected = torch.from_numpy(np.msort(tensor.cpu().numpy())) else: expected = tensor result = torch.msort(tensor) self.assertEqual(result, expected) out = torch.empty_like(result) torch.msort(tensor, out=out) self.assertEqual(out, expected) shapes = ( [], [0, ], [20, ], [1, 20], [30, 30], [10, 20, 30] ) for shape in shapes: test(shape) def test_topk(self, device): def topKViaSort(t, k, dim, dir): sorted, indices = t.sort(dim, dir) return sorted.narrow(dim, 0, k), indices.narrow(dim, 0, k) def compareTensors(t, res1, ind1, res2, ind2, dim): self.assertEqual(res1, res2, atol=0, rtol=0) if not ind1.eq(ind2).all(): vals = t.gather(dim, ind2) self.assertEqual(res1, vals, atol=0, rtol=0) def compare(t, k, dim, dir): topKVal, topKInd = t.topk(k, dim, dir, True) sortKVal, sortKInd = topKViaSort(t, k, dim, dir) compareTensors(t, sortKVal, sortKInd, topKVal, topKInd, dim) t = torch.rand(random.randint(1, SIZE), random.randint(1, SIZE), random.randint(1, SIZE), device=device) for _kTries in range(3): for _dimTries in range(3): for transpose in (True, False): for dir in (True, False): testTensor = t if transpose: dim1 = random.randrange(t.ndimension()) dim2 = dim1 while dim1 == dim2: dim2 = random.randrange(t.ndimension()) testTensor = t.transpose(dim1, dim2) dim = random.randrange(testTensor.ndimension()) k = random.randint(1, testTensor.size(dim)) compare(testTensor, k, dim, dir) def test_topk_arguments(self, device): q = torch.randn(10, 2, 10, device=device) self.assertRaises(TypeError, lambda: q.topk(4, True)) @skipCUDAIfRocm def test_unique_dim(self, device): self.assertFalse(hasattr(torch, 'unique_dim')) def run_test(device, dtype): x = torch.tensor([[[1., 1.], [0., 1.], [2., 1.], [0., 1.]], [[1., 1.], [0., 1.], [2., 1.], [0., 1.]]], dtype=dtype, device=device) x_empty = torch.empty(5, 0, dtype=dtype, device=device) x_ill_formed_empty = torch.empty(5, 0, 0, dtype=dtype, device=device) x_ill_formed_empty_another = torch.empty(5, 0, 5, dtype=dtype, device=device) expected_unique_dim0 = torch.tensor([[[1., 1.], [0., 1.], [2., 1.], [0., 1.]]], dtype=dtype, device=device) expected_inverse_dim0 = torch.tensor([0, 0]) expected_counts_dim0 = torch.tensor([2]) expected_unique_dim1 = torch.tensor([[[0., 1.], [1., 1.], [2., 1.]], [[0., 1.], [1., 1.], [2., 1.]]], dtype=dtype, device=device) expected_unique_dim1_bool = torch.tensor([[[False, True], [True, True]], [[False, True], [True, True]]], dtype=torch.bool, device=device) expected_inverse_dim1 = torch.tensor([1, 0, 2, 0]) expected_inverse_dim1_bool = torch.tensor([1, 0, 1, 0]) expected_counts_dim1 = torch.tensor([2, 1, 1]) expected_counts_dim1_bool = torch.tensor([2, 2]) expected_unique_dim2 = torch.tensor([[[1., 1.], [0., 1.], [2., 1.], [0., 1.]], [[1., 1.], [0., 1.], [2., 1.], [0., 1.]]], dtype=dtype, device=device) expected_inverse_dim2 = torch.tensor([0, 1]) expected_counts_dim2 = torch.tensor([1, 1]) expected_unique_empty = torch.tensor([], dtype=dtype, device=device) expected_inverse_empty = torch.tensor([], dtype=torch.long, device=device) expected_counts_empty = torch.tensor([], dtype=torch.long, device=device) # dim0 x_unique = torch.unique(x, dim=0) self.assertEqual(expected_unique_dim0, x_unique) x_unique, x_inverse = torch.unique( x, return_inverse=True, dim=0) self.assertEqual(expected_unique_dim0, x_unique) self.assertEqual(expected_inverse_dim0, x_inverse) x_unique, x_counts = torch.unique( x, return_inverse=False, return_counts=True, dim=0) self.assertEqual(expected_unique_dim0, x_unique) self.assertEqual(expected_counts_dim0, x_counts) x_unique, x_inverse, x_counts = torch.unique( x, return_inverse=True, return_counts=True, dim=0) self.assertEqual(expected_unique_dim0, x_unique) self.assertEqual(expected_inverse_dim0, x_inverse) self.assertEqual(expected_counts_dim0, x_counts) # dim1 x_unique = torch.unique(x, dim=1) if x.dtype == torch.bool: self.assertEqual(expected_unique_dim1_bool, x_unique) else: self.assertEqual(expected_unique_dim1, x_unique) x_unique, x_inverse = torch.unique( x, return_inverse=True, dim=1) if x.dtype == torch.bool: self.assertEqual(expected_unique_dim1_bool, x_unique) self.assertEqual(expected_inverse_dim1_bool, x_inverse) else: self.assertEqual(expected_unique_dim1, x_unique) self.assertEqual(expected_inverse_dim1, x_inverse) x_unique, x_counts = torch.unique( x, return_inverse=False, return_counts=True, dim=1) if x.dtype == torch.bool: self.assertEqual(expected_unique_dim1_bool, x_unique) self.assertEqual(expected_counts_dim1_bool, x_counts) else: self.assertEqual(expected_unique_dim1, x_unique) self.assertEqual(expected_counts_dim1, x_counts) x_unique, x_inverse, x_counts = torch.unique( x, return_inverse=True, return_counts=True, dim=1) if x.dtype == torch.bool: self.assertEqual(expected_unique_dim1_bool, x_unique) self.assertEqual(expected_inverse_dim1_bool, x_inverse) self.assertEqual(expected_counts_dim1_bool, x_counts) else: self.assertEqual(expected_unique_dim1, x_unique) self.assertEqual(expected_inverse_dim1, x_inverse) self.assertEqual(expected_counts_dim1, x_counts) # dim2 x_unique = torch.unique(x, dim=2) self.assertEqual(expected_unique_dim2, x_unique) x_unique, x_inverse = torch.unique( x, return_inverse=True, dim=2) self.assertEqual(expected_unique_dim2, x_unique) self.assertEqual(expected_inverse_dim2, x_inverse) x_unique, x_counts = torch.unique( x, return_inverse=False, return_counts=True, dim=2) self.assertEqual(expected_unique_dim2, x_unique) self.assertEqual(expected_counts_dim2, x_counts) x_unique, x_inverse, x_counts = torch.unique( x, return_inverse=True, return_counts=True, dim=2) self.assertEqual(expected_unique_dim2, x_unique) self.assertEqual(expected_inverse_dim2, x_inverse) self.assertEqual(expected_counts_dim2, x_counts) # test empty tensor x_unique, x_inverse, x_counts = torch.unique( x_empty, return_inverse=True, return_counts=True, dim=1) self.assertEqual(expected_unique_empty, x_unique) self.assertEqual(expected_inverse_empty, x_inverse) self.assertEqual(expected_counts_empty, x_counts) # test not a well formed tensor # Checking for runtime error, as this is the expected behaviour with self.assertRaises(RuntimeError): torch.unique( x_ill_formed_empty, return_inverse=True, return_counts=True, dim=1) # test along dim2 with self.assertRaises(RuntimeError): torch.unique( x_ill_formed_empty_another, return_inverse=True, return_counts=True, dim=2) # test consecutive version y = torch.tensor( [[0, 1], [0, 1], [0, 1], [1, 2], [1, 2], [3, 4], [0, 1], [0, 1], [3, 4], [1, 2]], dtype=dtype, device=device ) expected_y_unique = torch.tensor( [[0, 1], [1, 2], [3, 4], [0, 1], [3, 4], [1, 2]], dtype=dtype, device=device ) expected_y_inverse = torch.tensor([0, 0, 0, 1, 1, 2, 3, 3, 4, 5], dtype=torch.int64, device=device) expected_y_counts = torch.tensor([3, 2, 1, 2, 1, 1], dtype=torch.int64, device=device) expected_y_inverse_bool = torch.tensor([0, 0, 0, 1, 1, 1, 2, 2, 3, 3], dtype=torch.int64, device=device) expected_y_counts_bool = torch.tensor([3, 3, 2, 2], dtype=torch.int64, device=device) y_unique, y_inverse, y_counts = torch.unique_consecutive(y, return_inverse=True, return_counts=True, dim=0) if x.dtype == torch.bool: self.assertEqual(expected_y_inverse_bool, y_inverse) self.assertEqual(expected_y_counts_bool, y_counts) else: self.assertEqual(expected_y_inverse, y_inverse) self.assertEqual(expected_y_counts, y_counts) run_test(device, torch.float) run_test(device, torch.double) run_test(device, torch.long) run_test(device, torch.uint8) run_test(device, torch.bool) @onlyCUDA def test_topk_noncontiguous_gpu(self, device): t = torch.randn(20, device=device)[::2] top1, idx1 = t.topk(5) top2, idx2 = t.contiguous().topk(5) self.assertEqual(top1, top2) self.assertEqual(idx1, idx2) def _test_topk_dtype(self, device, dtype, integral, size): if integral: a = torch.randint(torch.iinfo(dtype).min, torch.iinfo(dtype).max, size=(size,), dtype=dtype, device=device) else: a = torch.randn(size=(size,), dtype=dtype, device=device) sort_topk = a.sort()[0][-(size // 2):].flip(0) topk = a.topk(size // 2) self.assertEqual(sort_topk, topk[0]) # check values self.assertEqual(sort_topk, a[topk[1]]) # check indices @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64) def test_topk_integral(self, device, dtype): small = 10 large = 4096 for curr_size in (small, large): self._test_topk_dtype(device, dtype, True, curr_size) @onlyCUDA @dtypes(torch.bfloat16) @skipCUDAIfRocm def test_topk_bfloat16(self, device, dtype): small = 10 large = 8192 for curr_size in (small, large): self._test_topk_dtype(device, dtype, False, curr_size) @dtypesIfCUDA(*torch.testing.get_all_fp_dtypes()) @dtypes(torch.float, torch.double, torch.bfloat16) def test_topk_nonfinite(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return x = torch.tensor([float('nan'), float('inf'), 1e4, 0, -1e4, -float('inf')], device=device, dtype=dtype) val, idx = x.topk(4) expect = torch.tensor([float('nan'), float('inf'), 1e4, 0], device=device, dtype=dtype) self.assertEqual(val, expect) self.assertEqual(idx, [0, 1, 2, 3]) val, idx = x.topk(4, largest=False) expect = torch.tensor([-float('inf'), -1e4, 0, 1e4], device=device, dtype=dtype) self.assertEqual(val, expect) self.assertEqual(idx, [5, 4, 3, 2]) def test_topk_4d(self, device): x = torch.ones(2, 3072, 2, 2, device=device) x[:, 1, :, :] *= 2. x[:, 10, :, :] *= 1.5 val, ind = torch.topk(x, k=2, dim=1) expected_ind = torch.ones(2, 2, 2, 2, dtype=torch.long, device=device) expected_ind[:, 1, :, :] = 10 expected_val = torch.ones(2, 2, 2, 2, device=device) expected_val[:, 0, :, :] *= 2. expected_val[:, 1, :, :] *= 1.5 self.assertEqual(val, expected_val, atol=0, rtol=0) self.assertEqual(ind, expected_ind, atol=0, rtol=0) @onlyOnCPUAndCUDA @dtypesIfCUDA(*(torch.testing.get_all_dtypes(include_complex=False, include_bool=False, include_half=False, include_bfloat16=True))) @dtypes(*(torch.testing.get_all_dtypes(include_complex=False, include_bool=False, include_half=False, include_bfloat16=False))) def test_topk_zero(self, device, dtype): if TEST_WITH_ROCM and dtype == torch.bfloat16: return # https://github.com/pytorch/pytorch/issues/49205 t = torch.rand(2, 2, device=device).to(dtype=dtype) val, idx = torch.topk(t, k=0, largest=False) self.assertEqual(val.size(), torch.Size([2, 0])) self.assertEqual(idx.size(), torch.Size([2, 0])) def _test_unique_scalar_empty(self, dtype, device, f): # test scalar x = torch.tensor(0, dtype=dtype, device=device) unique, inverse, counts = f(x, return_inverse=True, return_counts=True) expected_unique = torch.tensor([0], dtype=dtype, device=device) expected_inverse = torch.tensor(0, device=device) expected_counts = torch.tensor([1], device=device) self.assertEqual(unique, expected_unique) self.assertEqual(inverse, expected_inverse) self.assertEqual(counts, expected_counts) # test zero sized tensor x = torch.zeros((0, 0, 3), dtype=dtype, device=device) unique, inverse, counts = f(x, return_inverse=True, return_counts=True) expected_unique = torch.tensor([], dtype=dtype, device=device) expected_inverse = torch.empty((0, 0, 3), dtype=torch.long, device=device) expected_counts = torch.tensor([], dtype=torch.long, device=device) self.assertEqual(unique, expected_unique) self.assertEqual(inverse, expected_inverse) self.assertEqual(counts, expected_counts) def _test_unique_with_expects(self, device, dtype, f, x, expected_unique, expected_inverse, expected_counts, additional_shape): def ensure_tuple(x): if isinstance(x, torch.Tensor): return (x,) return x for return_inverse in [True, False]: for return_counts in [True, False]: # test with expected ret = ensure_tuple(f(x, return_inverse=return_inverse, return_counts=return_counts)) self.assertEqual(len(ret), 1 + int(return_inverse) + int(return_counts)) self.assertEqual(expected_unique, ret[0]) if return_inverse: self.assertEqual(expected_inverse, ret[1]) if return_counts: count_index = 1 + int(return_inverse) self.assertEqual(expected_counts, ret[count_index]) # tests per-element unique on a higher rank tensor. y = x.view(additional_shape) y_unique, y_inverse, y_counts = f(y, return_inverse=True, return_counts=True) self.assertEqual(expected_unique, y_unique) self.assertEqual(expected_inverse.view(additional_shape), y_inverse) self.assertEqual(expected_counts, y_counts) @dtypesIfCPU(*set(torch.testing.get_all_dtypes()) - {torch.complex64, torch.complex128}) @dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bfloat16, torch.complex64, torch.complex128}) def test_unique(self, device, dtype): if dtype is torch.half and self.device_type == 'cpu': return # CPU does not have half support def ensure_tuple(x): if isinstance(x, torch.Tensor): return (x,) return x if dtype is torch.bool: x = torch.tensor([True, False, False, False, True, False, True, False], dtype=torch.bool, device=device) expected_unique = torch.tensor([False, True], dtype=torch.bool, device=device) expected_inverse = torch.tensor([1, 0, 0, 0, 1, 0, 1, 0], dtype=torch.long, device=device) expected_counts = torch.tensor([5, 3], dtype=torch.long, device=device) else: x = torch.tensor([1, 2, 3, 2, 8, 5, 2, 3], dtype=dtype, device=device) expected_unique = torch.tensor([1, 2, 3, 5, 8], dtype=dtype, device=device) expected_inverse = torch.tensor([0, 1, 2, 1, 4, 3, 1, 2], device=device) expected_counts = torch.tensor([1, 3, 2, 1, 1], device=device) # test sorted unique fs = ( lambda x, **kwargs: torch.unique(x, sorted=True, **kwargs), lambda x, **kwargs: x.unique(sorted=True, **kwargs), ) x_sliced = torch.empty(x.size(0) * 2, dtype=dtype, device=device)[::2].copy_(x) xs = (x, x_sliced) for f, x in product(fs, xs): self._test_unique_with_expects(device, dtype, f, x, expected_unique, expected_inverse, expected_counts, (2, 2, 2)) self._test_unique_scalar_empty(dtype, device, f) # test unsorted unique fs = ( lambda x, **kwargs: torch.unique(x, sorted=False, **kwargs), lambda x, **kwargs: x.unique(sorted=False, **kwargs) ) for f, x in product(fs, xs): self._test_unique_scalar_empty(dtype, device, f) for return_inverse, return_counts in product((True, False), repeat=2): ret = ensure_tuple(f(x, return_inverse=return_inverse, return_counts=return_counts)) self.assertEqual(len(ret), 1 + int(return_inverse) + int(return_counts)) x_list = x.tolist() x_unique_list = ret[0].tolist() self.assertEqual(expected_unique.tolist(), sorted(x_unique_list)) if return_inverse: x_inverse_list = ret[1].tolist() for i, j in enumerate(x_inverse_list): self.assertEqual(x_list[i], x_unique_list[j]) if return_counts: count_index = 1 + int(return_inverse) x_counts_list = ret[count_index].tolist() for i, j in zip(x_unique_list, x_counts_list): count = 0 for k in x_list: if k == i: count += 1 self.assertEqual(j, count) @dtypesIfCPU(*set(torch.testing.get_all_dtypes()) - {torch.complex64, torch.complex128}) @dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bfloat16, torch.complex64, torch.complex128}) def test_unique_consecutive(self, device, dtype): if dtype is torch.half and self.device_type == 'cpu': return # CPU does not have half support if dtype is torch.bool: x = torch.tensor([True, False, False, False, True, True, False, False, False], dtype=torch.bool, device=device) expected_unique = torch.tensor([True, False, True, False], dtype=torch.bool, device=device) expected_inverse = torch.tensor([0, 1, 1, 1, 2, 2, 3, 3, 3], dtype=torch.long, device=device) expected_counts = torch.tensor([1, 3, 2, 3], dtype=torch.long, device=device) else: x = torch.tensor([1, 2, 2, 2, 5, 5, 2, 2, 3], dtype=dtype, device=device) expected_unique = torch.tensor([1, 2, 5, 2, 3], dtype=dtype, device=device) expected_inverse = torch.tensor([0, 1, 1, 1, 2, 2, 3, 3, 4], device=device) expected_counts = torch.tensor([1, 3, 2, 2, 1], device=device) for f in [torch.unique_consecutive, lambda x, **kwargs: x.unique_consecutive(**kwargs)]: self._test_unique_with_expects(device, dtype, f, x, expected_unique, expected_inverse, expected_counts, (3, 3)) self._test_unique_scalar_empty(dtype, device, f) @dtypes(torch.double) def test_kthvalue(self, device, dtype): SIZE = 50 x = torch.rand(SIZE, SIZE, SIZE, dtype=dtype, device=device) x0 = x.clone() k = random.randint(1, SIZE) res1val, res1ind = torch.kthvalue(x, k, keepdim=False) res2val, res2ind = torch.sort(x) self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0) self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0) # test use of result tensors k = random.randint(1, SIZE) res1val = torch.tensor([], dtype=dtype, device=device) res1ind = torch.tensor([], dtype=torch.long, device=device) torch.kthvalue(x, k, keepdim=False, out=(res1val, res1ind)) res2val, res2ind = torch.sort(x) self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0) self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0) # test non-default dim k = random.randint(1, SIZE) res1val, res1ind = torch.kthvalue(x, k, 0, keepdim=False) res2val, res2ind = torch.sort(x, 0) self.assertEqual(res1val, res2val[k - 1], atol=0, rtol=0) self.assertEqual(res1ind, res2ind[k - 1], atol=0, rtol=0) # non-contiguous y = x.narrow(1, 0, 1) y0 = y.contiguous() k = random.randint(1, SIZE) res1val, res1ind = torch.kthvalue(y, k) res2val, res2ind = torch.kthvalue(y0, k) self.assertEqual(res1val, res2val, atol=0, rtol=0) self.assertEqual(res1ind, res2ind, atol=0, rtol=0) # non-contiguous [Reference: https://github.com/pytorch/pytorch/issues/45721] non_contig_t = torch.tensor([0, -1, 1, -2, 2], dtype=dtype, device=device)[::2] expected_val, expected_ind = non_contig_t.contiguous().kthvalue(2) non_contig_cpu_t = non_contig_t.cpu() expected_val_cpu, expected_ind_cpu = non_contig_cpu_t.kthvalue(2) out_val, out_ind = non_contig_t.kthvalue(2) self.assertEqual(expected_val, out_val, atol=0, rtol=0) self.assertEqual(expected_ind, out_ind, atol=0, rtol=0) self.assertEqual(expected_val_cpu, out_val, atol=0, rtol=0) self.assertEqual(expected_ind_cpu, out_ind, atol=0, rtol=0) # check that the input wasn't modified self.assertEqual(x, x0, atol=0, rtol=0) y = torch.tensor((3., 5, 4, 1, 1, 5), dtype=dtype, device=device) self.assertEqual(torch.kthvalue(y, 3)[0], 3, atol=0, rtol=0) self.assertEqual(torch.kthvalue(y, 2)[0], 1, atol=0, rtol=0) SIZE = 50 x = torch.rand(SIZE, SIZE, SIZE, dtype=dtype, device=device) x[torch.arange(SIZE), :, torch.randint(50, (50,))] = nan ks = [random.randint(1, SIZE), 1, SIZE, SIZE - 1] res2val, res2ind = torch.sort(x) for k in ks: res1val, res1ind = torch.kthvalue(x, k, keepdim=False) self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0) self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0) @dtypes(torch.double) @onlyOnCPUAndCUDA def test_kthvalue_overlap(self, device, dtype): S = 10 k = 5 a = torch.randn(S, device=device) indices = torch.empty((), device=device, dtype=torch.long) with self.assertRaisesRegex(RuntimeError, "unsupported operation:"): torch.kthvalue(a, k, out=(a, indices)) @dtypes(torch.float) @onlyOnCPUAndCUDA def test_kthvalue_scalar(self, device, dtype): res = torch.tensor(2, device=device, dtype=dtype).kthvalue(1) ref = torch.tensor([2], device=device, dtype=dtype).kthvalue(1) self.assertEqual(res[0], ref[0].squeeze()) self.assertEqual(res[1], ref[1].squeeze()) @dtypes(*all_types()) @dtypesIfCUDA(*all_types_and(torch.half)) def test_isin(self, device, dtype): def assert_isin_equal(a, b): x = torch.isin(a, b) a = a.cpu().numpy() if torch.is_tensor(a) else np.array(a) b = b.cpu().numpy() if torch.is_tensor(b) else np.array(b) y = np.isin(a, b) self.assertEqual(x, y) a = torch.arange(24, device=device, dtype=dtype).reshape([2, 3, 4]) b = torch.tensor([[10, 20, 30], [0, 1, 3], [11, 22, 33]], device=device, dtype=dtype) assert_isin_equal(a, b) zero_d = torch.tensor(3, device=device, dtype=dtype) assert_isin_equal(zero_d, b) assert_isin_equal(a, zero_d) assert_isin_equal(zero_d, zero_d) empty = torch.tensor([], device=device, dtype=dtype) assert_isin_equal(empty, b) assert_isin_equal(a, empty) assert_isin_equal(empty, empty) assert_isin_equal(a, 6) assert_isin_equal(5, b) def define_expected(lst, invert=False): expected = torch.tensor(lst, device=device) if invert: expected = expected.logical_not() return expected for mult in [1, 10]: for invert in [False, True]: a = torch.tensor([5, 7, 1, 2], device=device, dtype=dtype) b = torch.tensor([2, 4, 3, 1, 5] * mult, device=device, dtype=dtype) ec = define_expected([True, False, True, True], invert=invert) c = torch.isin(a, b, assume_unique=True, invert=invert) self.assertEqual(c, ec) a[0] = 8 ec = define_expected([False, False, True, True], invert=invert) c = torch.isin(a, b, assume_unique=True, invert=invert) self.assertEqual(c, ec) a[0], a[3] = 4, 8 ec = define_expected([True, False, True, False], invert=invert) c = torch.isin(a, b, assume_unique=True, invert=invert) self.assertEqual(c, ec) a = torch.tensor([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5], device=device, dtype=dtype) b = torch.tensor([2, 3, 4] * mult, device=device, dtype=dtype) ec = define_expected([False, True, False, True, True, True, True, True, True, False, True, False, False, False], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) b = torch.tensor([2, 3, 4] * mult + [5, 5, 4] * mult, device=device, dtype=dtype) ec = define_expected([True, True, True, True, True, True, True, True, True, True, True, False, True, True], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) a = torch.tensor([5, 7, 1, 2], device=device, dtype=dtype) b = torch.tensor([2, 4, 3, 1, 5] * mult, device=device, dtype=dtype) ec = define_expected([True, False, True, True], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) a = torch.tensor([5, 7, 1, 1, 2], device=device, dtype=dtype) b = torch.tensor([2, 4, 3, 3, 1, 5] * mult, device=device, dtype=dtype) ec = define_expected([True, False, True, True, True], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) a = torch.tensor([5, 5], device=device, dtype=dtype) b = torch.tensor([2, 2] * mult, device=device, dtype=dtype) ec = define_expected([False, False], invert=invert) c = torch.isin(a, b, invert=invert) self.assertEqual(c, ec) # multi-dimensional input case using sort-based algo for assume_unique in [False, True]: a = torch.arange(6, device=device, dtype=dtype).reshape([2, 3]) b = torch.arange(3, 30, device=device, dtype=dtype) ec = define_expected([[False, False, False], [True, True, True]], invert=invert) c = torch.isin(a, b, invert=invert, assume_unique=assume_unique) self.assertEqual(c, ec) def test_isin_different_dtypes(self, device): supported_types = all_types() if device == 'cpu' else all_types_and(torch.half) for mult in [1, 10]: for assume_unique in [False, True]: for dtype1, dtype2 in product(supported_types, supported_types): a = torch.tensor([1, 2, 3], device=device, dtype=dtype1) b = torch.tensor([3, 4, 5] * mult, device=device, dtype=dtype2) ec = torch.tensor([False, False, True], device=device) c = torch.isin(a, b, assume_unique=assume_unique) self.assertEqual(c, ec) @onlyCUDA @dtypes(*all_types()) def test_isin_different_devices(self, device, dtype): a = torch.arange(6, device=device, dtype=dtype).reshape([2, 3]) b = torch.arange(3, 30, device='cpu', dtype=dtype) with self.assertRaises(RuntimeError): torch.isin(a, b) c = torch.arange(6, device='cpu', dtype=dtype).reshape([2, 3]) d = torch.arange(3, 30, device=device, dtype=dtype) with self.assertRaises(RuntimeError): torch.isin(c, d) instantiate_device_type_tests(TestSortAndSelect, globals()) if __name__ == '__main__': run_tests()
true
true
f716a4e754c3e3f35917e5279cd691b574a49a9b
798
py
Python
tests/test_api_v1_services_sshd_stop.py
pincher95/pfsense-api
001a4b8a1ec39138668d6d92b3c9d0c89a7f1b45
[ "Apache-2.0" ]
null
null
null
tests/test_api_v1_services_sshd_stop.py
pincher95/pfsense-api
001a4b8a1ec39138668d6d92b3c9d0c89a7f1b45
[ "Apache-2.0" ]
null
null
null
tests/test_api_v1_services_sshd_stop.py
pincher95/pfsense-api
001a4b8a1ec39138668d6d92b3c9d0c89a7f1b45
[ "Apache-2.0" ]
null
null
null
# Copyright 2022 Jared Hendrickson # # 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 e2e_test_framework class APIE2ETestServicesSSHdStop(e2e_test_framework.APIE2ETest): uri = "/api/v1/services/sshd/stop" post_tests = [{"name": "Stop the SSHd service"}] APIE2ETestServicesSSHdStop()
33.25
74
0.764411
import e2e_test_framework class APIE2ETestServicesSSHdStop(e2e_test_framework.APIE2ETest): uri = "/api/v1/services/sshd/stop" post_tests = [{"name": "Stop the SSHd service"}] APIE2ETestServicesSSHdStop()
true
true
f716a628b677fa7e5aaed86bc610566d88632de5
1,598
py
Python
mySpider/spiders/wangyi.py
songw831/mySpider
04312701e891e14ba7e470c3f2c0aa9997074096
[ "MIT" ]
null
null
null
mySpider/spiders/wangyi.py
songw831/mySpider
04312701e891e14ba7e470c3f2c0aa9997074096
[ "MIT" ]
null
null
null
mySpider/spiders/wangyi.py
songw831/mySpider
04312701e891e14ba7e470c3f2c0aa9997074096
[ "MIT" ]
null
null
null
import scrapy from selenium import webdriver from mySpider.items import MyspiderItem class FundSpider(scrapy.Spider): name = 'wangyi' #allowed_domains = ['www.xxx.com'] start_urls = ['http://news.163.com/'] modules_url = [] #存放五个版块的url def __init__(self): self.bro = webdriver.Chrome(executable_path='D:\PyCharm\mySpider\chromedriver.exe') def parse(self, response): li_list = response.xpath('//*[@id="index2016_wrap"]/div[1]/div[2]/div[2]/div[2]/div[2]/div/ul') alist = [3,4,6,7,8] for index in alist: module_url = li_list[index].xpath('./a/@href').extract_first() self.modules_url.append(module_url) #依次对每一个版块进行请求 for url in self.module_url: yield scrapy.Request(url, callback= self.parse_module) def parse_module(self, response): div_list = response.xpath('/html/body/div/div[3]/div[4]/div[1]/div[1]/div/ul/li/div/div') for div in div_list: title = div.xpath('./div/div[1]/h3/a/text()').extract_fisrt() new_detail_url = div.xpath('./div/div[1]/h3/a/@href').extract_first() item = MyspiderItem() item.title = title yield scrapy.Request(url=new_detail_url, callback=self.parse_detail, meta={'item':item}) def parse_detail(self,response): content = response.xpath('//*[@id="content"]/div[2]//text()').extract() content = ''.join(content) item = response.meta('item') item['content'] = content yield item def closed(self, spider): self.bro.quit()
38.97561
103
0.61577
import scrapy from selenium import webdriver from mySpider.items import MyspiderItem class FundSpider(scrapy.Spider): name = 'wangyi' start_urls = ['http://news.163.com/'] modules_url = [] def __init__(self): self.bro = webdriver.Chrome(executable_path='D:\PyCharm\mySpider\chromedriver.exe') def parse(self, response): li_list = response.xpath('//*[@id="index2016_wrap"]/div[1]/div[2]/div[2]/div[2]/div[2]/div/ul') alist = [3,4,6,7,8] for index in alist: module_url = li_list[index].xpath('./a/@href').extract_first() self.modules_url.append(module_url) for url in self.module_url: yield scrapy.Request(url, callback= self.parse_module) def parse_module(self, response): div_list = response.xpath('/html/body/div/div[3]/div[4]/div[1]/div[1]/div/ul/li/div/div') for div in div_list: title = div.xpath('./div/div[1]/h3/a/text()').extract_fisrt() new_detail_url = div.xpath('./div/div[1]/h3/a/@href').extract_first() item = MyspiderItem() item.title = title yield scrapy.Request(url=new_detail_url, callback=self.parse_detail, meta={'item':item}) def parse_detail(self,response): content = response.xpath('//*[@id="content"]/div[2]//text()').extract() content = ''.join(content) item = response.meta('item') item['content'] = content yield item def closed(self, spider): self.bro.quit()
true
true
f716a6346eb2c4bb4c555f3cc80875549f7a88fc
1,780
py
Python
pandas_ta/performance/log_return.py
yssource/pandas-ta
0f975320684a91db3c04f6ea3dd739177dcb65aa
[ "MIT" ]
2
2021-03-30T01:23:14.000Z
2021-04-02T18:04:51.000Z
pandas_ta/performance/log_return.py
lukaszbinden/pandas-ta
98478f8bf049a4c8748d6f3c795f4f335ced05ca
[ "MIT" ]
null
null
null
pandas_ta/performance/log_return.py
lukaszbinden/pandas-ta
98478f8bf049a4c8748d6f3c795f4f335ced05ca
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from numpy import log as nplog from pandas_ta.utils import get_offset, verify_series def log_return(close, length=None, cumulative=False, offset=None, **kwargs): """Indicator: Log Return""" # Validate Arguments close = verify_series(close) length = int(length) if length and length > 0 else 1 offset = get_offset(offset) # Calculate Result log_return = nplog(close).diff(periods=length) if cumulative: log_return = log_return.cumsum() # Offset if offset != 0: log_return = log_return.shift(offset) # Handle fills if "fillna" in kwargs: log_return.fillna(kwargs["fillna"], inplace=True) if "fill_method" in kwargs: log_return.fillna(method=kwargs["fill_method"], inplace=True) # Name & Category log_return.name = f"{'CUM' if cumulative else ''}LOGRET_{length}" log_return.category = "performance" return log_return log_return.__doc__ = \ """Log Return Calculates the logarithmic return of a Series. See also: help(df.ta.log_return) for additional **kwargs a valid 'df'. Sources: https://stackoverflow.com/questions/31287552/logarithmic-returns-in-pandas-dataframe Calculation: Default Inputs: length=1, cumulative=False LOGRET = log( close.diff(periods=length) ) CUMLOGRET = LOGRET.cumsum() if cumulative Args: close (pd.Series): Series of 'close's length (int): It's period. Default: 20 cumulative (bool): If True, returns the cumulative returns. Default: False offset (int): How many periods to offset the result. Default: 0 Kwargs: fillna (value, optional): pd.DataFrame.fillna(value) fill_method (value, optional): Type of fill method Returns: pd.Series: New feature generated. """
27.8125
88
0.690449
from numpy import log as nplog from pandas_ta.utils import get_offset, verify_series def log_return(close, length=None, cumulative=False, offset=None, **kwargs): close = verify_series(close) length = int(length) if length and length > 0 else 1 offset = get_offset(offset) log_return = nplog(close).diff(periods=length) if cumulative: log_return = log_return.cumsum() if offset != 0: log_return = log_return.shift(offset) if "fillna" in kwargs: log_return.fillna(kwargs["fillna"], inplace=True) if "fill_method" in kwargs: log_return.fillna(method=kwargs["fill_method"], inplace=True) log_return.name = f"{'CUM' if cumulative else ''}LOGRET_{length}" log_return.category = "performance" return log_return log_return.__doc__ = \ """Log Return Calculates the logarithmic return of a Series. See also: help(df.ta.log_return) for additional **kwargs a valid 'df'. Sources: https://stackoverflow.com/questions/31287552/logarithmic-returns-in-pandas-dataframe Calculation: Default Inputs: length=1, cumulative=False LOGRET = log( close.diff(periods=length) ) CUMLOGRET = LOGRET.cumsum() if cumulative Args: close (pd.Series): Series of 'close's length (int): It's period. Default: 20 cumulative (bool): If True, returns the cumulative returns. Default: False offset (int): How many periods to offset the result. Default: 0 Kwargs: fillna (value, optional): pd.DataFrame.fillna(value) fill_method (value, optional): Type of fill method Returns: pd.Series: New feature generated. """
true
true
f716a738e6208427b79ad0f628bfff8e87f2f337
12,558
py
Python
recipe_modules/file/resources/fileutil.py
engeg/recipes-py
9dac536b55887262b4ce846f3db7a7f596542e5e
[ "Apache-2.0" ]
null
null
null
recipe_modules/file/resources/fileutil.py
engeg/recipes-py
9dac536b55887262b4ce846f3db7a7f596542e5e
[ "Apache-2.0" ]
null
null
null
recipe_modules/file/resources/fileutil.py
engeg/recipes-py
9dac536b55887262b4ce846f3db7a7f596542e5e
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2017 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Utility exporting basic filesystem operations. This file was cut from "scripts/common/chromium_utils.py" at: 91310531c31fa645256b4fb5d44b460c42b3e151 """ from __future__ import print_function import argparse import errno import fnmatch import glob import itertools import json import os import shutil import subprocess import sys import tempfile import time def _LocateFiles(pattern, root): """Yeilds files matching pattern found in root and its subdirectories. An exception is thrown if root doesn't exist.""" for path, _, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename) def _RmGlob(file_wildcard, root): """Removes files matching 'file_wildcard' in root and its subdirectories, if any exists. An exception is thrown if root doesn't exist.""" for item in _LocateFiles(file_wildcard, root): try: os.remove(item) except OSError, e: if e.errno != errno.ENOENT: raise def _RmContents(path): if os.path.exists(path): os.chmod(path, 0770) for p in (os.path.join(path, x) for x in os.listdir(path)): if os.path.isdir(p): _RmTree(p) else: os.unlink(p) def _RmTree(path): """Recursively removes a directory, even if it's marked read-only. Remove the directory located at path, if it exists. shutil.rmtree() doesn't work on Windows if any of the files or directories are read-only, which svn repositories and some .svn files are. We need to be able to force the files to be writable (i.e., deletable) as we traverse the tree. Even with all this, Windows still sometimes fails to delete a file, citing a permission error (maybe something to do with antivirus scans or disk indexing). The best suggestion any of the user forums had was to wait a bit and try again, so we do that too. It's hand-waving, but sometimes it works. :/ """ if not os.path.exists(path): print('WARNING: Failed to find %s during rmtree. Ignoring.\n' % path) return if sys.platform == 'win32': # Give up and use cmd.exe's rd command. cmd = ['cmd.exe', '/c', 'rd', '/q', '/s', os.path.normcase(path)] for _ in xrange(3): print('RemoveDirectory running %s' % (' '.join(cmd))) if not subprocess.call(cmd): break print(' Failed') time.sleep(3) return # If we call "rmtree" on a file, just delete it. if not os.path.isdir(path): os.remove(path) return def RemoveWithRetry_non_win(rmfunc, path): if os.path.islink(path): return os.remove(path) return rmfunc(path) remove_with_retry = RemoveWithRetry_non_win def RmTreeOnError(function, path, excinfo): r"""This works around a problem whereby python 2.x on Windows has no ability to check for symbolic links. os.path.islink always returns False. But shutil.rmtree will fail if invoked on a symbolic link whose target was deleted before the link. E.g., reproduce like this: > mkdir test > mkdir test\1 > mklink /D test\current test\1 > python -c "import chromium_utils; chromium_utils.RemoveDirectory('test')" To avoid this issue, we pass this error-handling function to rmtree. If we see the exact sort of failure, we ignore it. All other failures we re- raise. """ exception_type = excinfo[0] exception_value = excinfo[1] # If shutil.rmtree encounters a symbolic link on Windows, os.listdir will # fail with a WindowsError exception with an ENOENT errno (i.e., file not # found). We'll ignore that error. Note that WindowsError is not defined # for non-Windows platforms, so we use OSError (of which it is a subclass) # to avoid lint complaints about an undefined global on non-Windows # platforms. if (function is os.listdir) and issubclass(exception_type, OSError): if exception_value.errno == errno.ENOENT: # File does not exist, and we're trying to delete, so we can ignore the # failure. print('WARNING: Failed to list %s during rmtree. Ignoring.\n' % path) else: raise else: raise for root, dirs, files in os.walk(path, topdown=False): # For POSIX: making the directory writable guarantees removability. # Windows will ignore the non-read-only bits in the chmod value. os.chmod(root, 0770) for name in files: remove_with_retry(os.remove, os.path.join(root, name)) for name in dirs: remove_with_retry(lambda p: shutil.rmtree(p, onerror=RmTreeOnError), os.path.join(root, name)) remove_with_retry(os.rmdir, path) def _EnsureDir(mode, dest): if not os.path.isdir(dest): if os.path.exists(dest): raise OSError(errno.EEXIST, os.strerror(errno.EEXIST)) os.makedirs(dest, mode) def _Glob(base, pattern): cwd = os.getcwd() try: os.chdir(base) hits = glob.glob(pattern) if hits: print('\n'.join(sorted(hits))) finally: os.chdir(cwd) def _Remove(path): try: os.remove(path) except OSError as e: if e.errno != errno.ENOENT: raise def _Truncate(path, size_mb): with open(path, 'w') as f: f.truncate(size_mb * 1024 * 1024) def _FlattenSingleDirectories(path): assert os.path.isabs(path), 'nonabs path: %r' % (path,) assert os.path.isdir(path), 'nondir path: %r' % (path,) first_single_dir = None print('flattening single directories in %r' % (path,)) for root, dirs, files in os.walk(path): # if it's a single dir, we keep walking if len(dirs) == 1 and not files: if not first_single_dir: first_single_dir = os.path.join(path, dirs[0]) continue # otherwise we found some stuff! if not first_single_dir: # if we didn't find a first_single_dir, we're still in the base directory # and don't have anything to do. print('contents appears already flattened') return 0 print('found contents at: %r' % (os.path.relpath(root, path),)) # first move the first_single_dir out of the way, in case there's # a file/folder we need to move that has a conflicting name. tmpname = tempfile.mktemp(dir=path) print('moving root folder out of the way: %r -> %r' % (first_single_dir, tmpname)) os.rename(first_single_dir, tmpname) for name in itertools.chain(dirs, files): fullname = os.path.join(root, name).replace(first_single_dir, tmpname) to = os.path.join(path, name) print('mv %r %r' % (fullname, to)) os.rename(fullname, to) print('moved %d dirs and %d files' % (len(dirs), len(files))) print('rm -rf %r' % (tmpname,)) shutil.rmtree(tmpname) return 0 def main(args): parser = argparse.ArgumentParser() parser.add_argument('--json-output', required=True, type=argparse.FileType('w'), help="path to JSON output file") subparsers = parser.add_subparsers() # Subcommand: rmtree subparser = subparsers.add_parser('rmtree', help='Recursively remove a directory.') subparser.add_argument('source', help='A path to remove.') subparser.set_defaults(func=lambda opts: _RmTree(opts.source)) # Subcommand: rmcontents subparser = subparsers.add_parser('rmcontents', help='Recursively remove the contents of a directory.') subparser.add_argument('source', help='The target directory.') subparser.set_defaults(func=lambda opts: _RmContents(opts.source)) # Subcommand: rmwildcard subparser = subparsers.add_parser('rmglob', help='Recursively remove the contents of a directory.') subparser.add_argument('root', help='The directory to search through.') subparser.add_argument('wildcard', help='The wildcard expression to remove.') subparser.set_defaults(func=lambda opts: _RmGlob(opts.wildcard, opts.root)) # Subcommand: copy subparser = subparsers.add_parser('copy', help='Copy one file to another. Behaves like shutil.copy().') subparser.add_argument('source', help='The file to copy.') subparser.add_argument('dest', help='The destination to copy to.') subparser.set_defaults(func=lambda opts: shutil.copy(opts.source, opts.dest)) # Subcommand: copytree subparser = subparsers.add_parser('copytree', help='Recursively copy a file tree. Behaves like shutil.copytree().') subparser.add_argument('--symlinks', action='store_true', help='Copy symlinks as symlinks.') subparser.add_argument('source', help='The directory to copy.') subparser.add_argument('dest', help='The destination directory to copy to.') subparser.set_defaults( func=lambda opts: shutil.copytree(opts.source, opts.dest, opts.symlinks)) # Subcommand: move subparser = subparsers.add_parser('move', help='Moves/renames a file. Behaves like shutil.move().') subparser.add_argument('source', help='The item to move.') subparser.add_argument('dest', help='The destination name.') subparser.set_defaults( func=lambda opts: shutil.move(opts.source, opts.dest)) # Subcommand: glob subparser = subparsers.add_parser('glob', help='Prints a list of absolute paths with match the pattern.') subparser.add_argument('base', help='The directory to glob in.') subparser.add_argument('pattern', help='The glob patern to expand.') subparser.set_defaults(func=lambda opts: _Glob(opts.base, opts.pattern)) # Subcommand: remove subparser = subparsers.add_parser('remove', help='Remove a file') subparser.add_argument('source', help='The file to remove.') subparser.set_defaults(func=lambda opts: _Remove(opts.source)) # Subcommand: listdir subparser = subparsers.add_parser('listdir', help='Print all entries in the given folder to stdout.') subparser.add_argument('source', help='The dir to list.') subparser.set_defaults( func=lambda opts: print('\n'.join(sorted(os.listdir(opts.source))), end='')) # Subcommand: ensure-directory subparser = subparsers.add_parser('ensure-directory', help='Ensures that the given path is a directory.') subparser.add_argument('--mode', help='The octal mode of the directory.', type=lambda s: int(s, 8)) subparser.add_argument('dest', help='The dir to ensure.') subparser.set_defaults(func=lambda opts: _EnsureDir(opts.mode, opts.dest)) # Subcommand: filesizes subparser = subparsers.add_parser('filesizes', help='Prints a list for sizes in bytes (1 per line) for each given file') subparser.add_argument('file', nargs='+', help='Path to a file') subparser.set_defaults( func=lambda opts: print('\n'.join(str(os.stat(f).st_size) for f in opts.file))) # Subcommand: filesizes subparser = subparsers.add_parser('symlink', help='Creates a symlink. Behaves like os.symlink.') subparser.add_argument('source', help='The thing to link to.') subparser.add_argument('link', help='The link to create.') subparser.set_defaults( func=lambda opts: os.symlink(opts.source, opts.link)) # Subcommand: truncate subparser = subparsers.add_parser( 'truncate', help='Creates an empty file with specified size.') subparser.add_argument('path', help='The path to the file.') subparser.add_argument('size_mb', help='The size of the file in megabytes.', type=int) subparser.set_defaults(func=lambda opts: _Truncate(opts.path, opts.size_mb)) # Subcommand: flatten_single_directories subparser = subparsers.add_parser( 'flatten_single_directories', help=('Moves contents of single/dir/with/contents to the top level ' 'directory.')) subparser.add_argument('path', help='The path to flatten from.') subparser.set_defaults(func=lambda opts: _FlattenSingleDirectories(opts.path)) # Parse arguments. opts = parser.parse_args(args) # Actually do the thing. data = { 'ok': False, 'errno_name': '', 'message': '', } try: opts.func(opts) data['ok'] = True except OSError as e: data['errno_name'] = errno.errorcode[e.errno] data['message'] = str(e) except shutil.Error as e: data['message'] = e.message except Exception as e: data['message'] = 'UNKNOWN: %s' % e with opts.json_output: json.dump(data, opts.json_output) return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
35.078212
86
0.686495
"""Utility exporting basic filesystem operations. This file was cut from "scripts/common/chromium_utils.py" at: 91310531c31fa645256b4fb5d44b460c42b3e151 """ from __future__ import print_function import argparse import errno import fnmatch import glob import itertools import json import os import shutil import subprocess import sys import tempfile import time def _LocateFiles(pattern, root): """Yeilds files matching pattern found in root and its subdirectories. An exception is thrown if root doesn't exist.""" for path, _, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename) def _RmGlob(file_wildcard, root): """Removes files matching 'file_wildcard' in root and its subdirectories, if any exists. An exception is thrown if root doesn't exist.""" for item in _LocateFiles(file_wildcard, root): try: os.remove(item) except OSError, e: if e.errno != errno.ENOENT: raise def _RmContents(path): if os.path.exists(path): os.chmod(path, 0770) for p in (os.path.join(path, x) for x in os.listdir(path)): if os.path.isdir(p): _RmTree(p) else: os.unlink(p) def _RmTree(path): """Recursively removes a directory, even if it's marked read-only. Remove the directory located at path, if it exists. shutil.rmtree() doesn't work on Windows if any of the files or directories are read-only, which svn repositories and some .svn files are. We need to be able to force the files to be writable (i.e., deletable) as we traverse the tree. Even with all this, Windows still sometimes fails to delete a file, citing a permission error (maybe something to do with antivirus scans or disk indexing). The best suggestion any of the user forums had was to wait a bit and try again, so we do that too. It's hand-waving, but sometimes it works. :/ """ if not os.path.exists(path): print('WARNING: Failed to find %s during rmtree. Ignoring.\n' % path) return if sys.platform == 'win32': # Give up and use cmd.exe's rd command. cmd = ['cmd.exe', '/c', 'rd', '/q', '/s', os.path.normcase(path)] for _ in xrange(3): print('RemoveDirectory running %s' % (' '.join(cmd))) if not subprocess.call(cmd): break print(' Failed') time.sleep(3) return if not os.path.isdir(path): os.remove(path) return def RemoveWithRetry_non_win(rmfunc, path): if os.path.islink(path): return os.remove(path) return rmfunc(path) remove_with_retry = RemoveWithRetry_non_win def RmTreeOnError(function, path, excinfo): r"""This works around a problem whereby python 2.x on Windows has no ability to check for symbolic links. os.path.islink always returns False. But shutil.rmtree will fail if invoked on a symbolic link whose target was deleted before the link. E.g., reproduce like this: > mkdir test > mkdir test\1 > mklink /D test\current test\1 > python -c "import chromium_utils; chromium_utils.RemoveDirectory('test')" To avoid this issue, we pass this error-handling function to rmtree. If we see the exact sort of failure, we ignore it. All other failures we re- raise. """ exception_type = excinfo[0] exception_value = excinfo[1] # for non-Windows platforms, so we use OSError (of which it is a subclass) # to avoid lint complaints about an undefined global on non-Windows # platforms. if (function is os.listdir) and issubclass(exception_type, OSError): if exception_value.errno == errno.ENOENT: # File does not exist, and we're trying to delete, so we can ignore the print('WARNING: Failed to list %s during rmtree. Ignoring.\n' % path) else: raise else: raise for root, dirs, files in os.walk(path, topdown=False): os.chmod(root, 0770) for name in files: remove_with_retry(os.remove, os.path.join(root, name)) for name in dirs: remove_with_retry(lambda p: shutil.rmtree(p, onerror=RmTreeOnError), os.path.join(root, name)) remove_with_retry(os.rmdir, path) def _EnsureDir(mode, dest): if not os.path.isdir(dest): if os.path.exists(dest): raise OSError(errno.EEXIST, os.strerror(errno.EEXIST)) os.makedirs(dest, mode) def _Glob(base, pattern): cwd = os.getcwd() try: os.chdir(base) hits = glob.glob(pattern) if hits: print('\n'.join(sorted(hits))) finally: os.chdir(cwd) def _Remove(path): try: os.remove(path) except OSError as e: if e.errno != errno.ENOENT: raise def _Truncate(path, size_mb): with open(path, 'w') as f: f.truncate(size_mb * 1024 * 1024) def _FlattenSingleDirectories(path): assert os.path.isabs(path), 'nonabs path: %r' % (path,) assert os.path.isdir(path), 'nondir path: %r' % (path,) first_single_dir = None print('flattening single directories in %r' % (path,)) for root, dirs, files in os.walk(path): if len(dirs) == 1 and not files: if not first_single_dir: first_single_dir = os.path.join(path, dirs[0]) continue # otherwise we found some stuff! if not first_single_dir: # if we didn't find a first_single_dir, we're still in the base directory # and don't have anything to do. print('contents appears already flattened') return 0 print('found contents at: %r' % (os.path.relpath(root, path),)) # a file/folder we need to move that has a conflicting name. tmpname = tempfile.mktemp(dir=path) print('moving root folder out of the way: %r -> %r' % (first_single_dir, tmpname)) os.rename(first_single_dir, tmpname) for name in itertools.chain(dirs, files): fullname = os.path.join(root, name).replace(first_single_dir, tmpname) to = os.path.join(path, name) print('mv %r %r' % (fullname, to)) os.rename(fullname, to) print('moved %d dirs and %d files' % (len(dirs), len(files))) print('rm -rf %r' % (tmpname,)) shutil.rmtree(tmpname) return 0 def main(args): parser = argparse.ArgumentParser() parser.add_argument('--json-output', required=True, type=argparse.FileType('w'), help="path to JSON output file") subparsers = parser.add_subparsers() # Subcommand: rmtree subparser = subparsers.add_parser('rmtree', help='Recursively remove a directory.') subparser.add_argument('source', help='A path to remove.') subparser.set_defaults(func=lambda opts: _RmTree(opts.source)) # Subcommand: rmcontents subparser = subparsers.add_parser('rmcontents', help='Recursively remove the contents of a directory.') subparser.add_argument('source', help='The target directory.') subparser.set_defaults(func=lambda opts: _RmContents(opts.source)) # Subcommand: rmwildcard subparser = subparsers.add_parser('rmglob', help='Recursively remove the contents of a directory.') subparser.add_argument('root', help='The directory to search through.') subparser.add_argument('wildcard', help='The wildcard expression to remove.') subparser.set_defaults(func=lambda opts: _RmGlob(opts.wildcard, opts.root)) # Subcommand: copy subparser = subparsers.add_parser('copy', help='Copy one file to another. Behaves like shutil.copy().') subparser.add_argument('source', help='The file to copy.') subparser.add_argument('dest', help='The destination to copy to.') subparser.set_defaults(func=lambda opts: shutil.copy(opts.source, opts.dest)) # Subcommand: copytree subparser = subparsers.add_parser('copytree', help='Recursively copy a file tree. Behaves like shutil.copytree().') subparser.add_argument('--symlinks', action='store_true', help='Copy symlinks as symlinks.') subparser.add_argument('source', help='The directory to copy.') subparser.add_argument('dest', help='The destination directory to copy to.') subparser.set_defaults( func=lambda opts: shutil.copytree(opts.source, opts.dest, opts.symlinks)) # Subcommand: move subparser = subparsers.add_parser('move', help='Moves/renames a file. Behaves like shutil.move().') subparser.add_argument('source', help='The item to move.') subparser.add_argument('dest', help='The destination name.') subparser.set_defaults( func=lambda opts: shutil.move(opts.source, opts.dest)) # Subcommand: glob subparser = subparsers.add_parser('glob', help='Prints a list of absolute paths with match the pattern.') subparser.add_argument('base', help='The directory to glob in.') subparser.add_argument('pattern', help='The glob patern to expand.') subparser.set_defaults(func=lambda opts: _Glob(opts.base, opts.pattern)) # Subcommand: remove subparser = subparsers.add_parser('remove', help='Remove a file') subparser.add_argument('source', help='The file to remove.') subparser.set_defaults(func=lambda opts: _Remove(opts.source)) # Subcommand: listdir subparser = subparsers.add_parser('listdir', help='Print all entries in the given folder to stdout.') subparser.add_argument('source', help='The dir to list.') subparser.set_defaults( func=lambda opts: print('\n'.join(sorted(os.listdir(opts.source))), end='')) # Subcommand: ensure-directory subparser = subparsers.add_parser('ensure-directory', help='Ensures that the given path is a directory.') subparser.add_argument('--mode', help='The octal mode of the directory.', type=lambda s: int(s, 8)) subparser.add_argument('dest', help='The dir to ensure.') subparser.set_defaults(func=lambda opts: _EnsureDir(opts.mode, opts.dest)) # Subcommand: filesizes subparser = subparsers.add_parser('filesizes', help='Prints a list for sizes in bytes (1 per line) for each given file') subparser.add_argument('file', nargs='+', help='Path to a file') subparser.set_defaults( func=lambda opts: print('\n'.join(str(os.stat(f).st_size) for f in opts.file))) # Subcommand: filesizes subparser = subparsers.add_parser('symlink', help='Creates a symlink. Behaves like os.symlink.') subparser.add_argument('source', help='The thing to link to.') subparser.add_argument('link', help='The link to create.') subparser.set_defaults( func=lambda opts: os.symlink(opts.source, opts.link)) # Subcommand: truncate subparser = subparsers.add_parser( 'truncate', help='Creates an empty file with specified size.') subparser.add_argument('path', help='The path to the file.') subparser.add_argument('size_mb', help='The size of the file in megabytes.', type=int) subparser.set_defaults(func=lambda opts: _Truncate(opts.path, opts.size_mb)) # Subcommand: flatten_single_directories subparser = subparsers.add_parser( 'flatten_single_directories', help=('Moves contents of single/dir/with/contents to the top level ' 'directory.')) subparser.add_argument('path', help='The path to flatten from.') subparser.set_defaults(func=lambda opts: _FlattenSingleDirectories(opts.path)) # Parse arguments. opts = parser.parse_args(args) # Actually do the thing. data = { 'ok': False, 'errno_name': '', 'message': '', } try: opts.func(opts) data['ok'] = True except OSError as e: data['errno_name'] = errno.errorcode[e.errno] data['message'] = str(e) except shutil.Error as e: data['message'] = e.message except Exception as e: data['message'] = 'UNKNOWN: %s' % e with opts.json_output: json.dump(data, opts.json_output) return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
false
true
f716a9d014c49a805a816c403771d17f603d78f9
5,119
py
Python
resolwe_bio/tools/basespace_download.py
JureZmrzlikar/resolwe-bio
54cde9b293abebad2db0564c9fefa33d6d2fe835
[ "Apache-2.0" ]
null
null
null
resolwe_bio/tools/basespace_download.py
JureZmrzlikar/resolwe-bio
54cde9b293abebad2db0564c9fefa33d6d2fe835
[ "Apache-2.0" ]
null
null
null
resolwe_bio/tools/basespace_download.py
JureZmrzlikar/resolwe-bio
54cde9b293abebad2db0564c9fefa33d6d2fe835
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 """Tool to download files from BaseSpace.""" import sys import traceback import atexit import argparse import requests class BaseSpaceDownloadError(Exception): """BaseSpace download error.""" pass def main(): """Entry point.""" session = requests.Session() atexit.register(on_exit, session) parser = argparse.ArgumentParser(description='Download file from Illumina BaseSpace.') parser.add_argument('--file-id', dest='file_ids', action='append', required=True, help="BaseSpace file ID. This argument can be repeated to specify multiple files.") parser.add_argument('--access-token-secret-path', dest='access_token_secret_path', required=True, help="BaseSpace access token secret path.") parser.add_argument('--output', dest='output', type=str, choices=['full', 'filename'], default='full', help="Sets what is printed to standard output. " "Argument 'full' outputs everything, " "argument 'filename' outputs only file names of downloaded files.") parser.add_argument('--verbose', dest='verbose', action='store_true', default=False, help="Print detailed exception information when error occurs. " "Output argument had no effect on this argument.") args = parser.parse_args() try: file_ids = args.file_ids access_token = get_token_from_secret_file(args.access_token_secret_path) headers = {'x-access-token': access_token} for file_id in file_ids: file_name = get_file_name(session, file_id, headers) download_file(session, file_id, file_name, headers) output(args.output, 'filename={}'.format(file_name)) except: if args.verbose: traceback.print_exc() else: print("An error occurred while processing the Basespace download request. Use --verbose to see details.") sys.exit(1) def on_exit(session): """Clean up function called on exit.""" session.close() def output(output_option, value): """ Print to standard output. This function should be used instead of ``print`` function. Printing errors is exempted and can be printed without using this function. """ if output_option == 'full': print(value) elif output_option == 'filename': if value.startswith('filename='): print(value[len('filename='):]) else: print("Internal error: output argument {} handling not implemented".format(output_option)) sys.exit(1) def get_token_from_secret_file(secret_file_path): """Read secret file to obtain access token.""" try: with open(secret_file_path, 'r') as f: return f.readline() except FileNotFoundError: raise BaseSpaceDownloadError('Secret file not found') except PermissionError: raise BaseSpaceDownloadError('No permissions to read secret file') def make_get_request(session, url, headers, stream=False): """Make a get request.""" response = session.get(url, headers=headers, stream=stream) if response.status_code == 401: raise BaseSpaceDownloadError('Authentication failed on URL {}'.format(url)) elif response.status_code == 404: raise BaseSpaceDownloadError('BaseSpace file {} not found'.format(url)) return response def get_basespace_api_url(): """Get base BaseSpace API URL.""" return 'https://api.basespace.illumina.com/v1pre3' def get_basespace_api_file_url(file_id): """Get BaseSpace API file URL.""" return '{}/files/{}'.format(get_basespace_api_url(), file_id) def get_basespace_api_file_content_url(file_id): """Get BaseSpace API file contents URL.""" return '{}/content'.format(get_basespace_api_file_url(file_id)) def get_file_name(session, file_id, request_headers): """Get file name.""" response = make_get_request(session, get_basespace_api_file_url(file_id), request_headers) return response.json()['Response']['Name'] def download_file(session, file_id, file_name, request_headers): """Download BaseSpace file.""" response = make_get_request(session, get_basespace_api_file_content_url(file_id), request_headers, True) try: with open(file_name, 'wb') as f: for chunk in response.iter_content(chunk_size=1024): f.write(chunk) except FileNotFoundError: raise BaseSpaceDownloadError('Could not save file to {}, due to directory not being found'.format(file_name)) except PermissionError: raise BaseSpaceDownloadError('Could not save file to {}, due to insufficient permissions'.format(file_name)) if __name__ == "__main__": main()
34.126667
117
0.632936
import sys import traceback import atexit import argparse import requests class BaseSpaceDownloadError(Exception): pass def main(): session = requests.Session() atexit.register(on_exit, session) parser = argparse.ArgumentParser(description='Download file from Illumina BaseSpace.') parser.add_argument('--file-id', dest='file_ids', action='append', required=True, help="BaseSpace file ID. This argument can be repeated to specify multiple files.") parser.add_argument('--access-token-secret-path', dest='access_token_secret_path', required=True, help="BaseSpace access token secret path.") parser.add_argument('--output', dest='output', type=str, choices=['full', 'filename'], default='full', help="Sets what is printed to standard output. " "Argument 'full' outputs everything, " "argument 'filename' outputs only file names of downloaded files.") parser.add_argument('--verbose', dest='verbose', action='store_true', default=False, help="Print detailed exception information when error occurs. " "Output argument had no effect on this argument.") args = parser.parse_args() try: file_ids = args.file_ids access_token = get_token_from_secret_file(args.access_token_secret_path) headers = {'x-access-token': access_token} for file_id in file_ids: file_name = get_file_name(session, file_id, headers) download_file(session, file_id, file_name, headers) output(args.output, 'filename={}'.format(file_name)) except: if args.verbose: traceback.print_exc() else: print("An error occurred while processing the Basespace download request. Use --verbose to see details.") sys.exit(1) def on_exit(session): session.close() def output(output_option, value): if output_option == 'full': print(value) elif output_option == 'filename': if value.startswith('filename='): print(value[len('filename='):]) else: print("Internal error: output argument {} handling not implemented".format(output_option)) sys.exit(1) def get_token_from_secret_file(secret_file_path): try: with open(secret_file_path, 'r') as f: return f.readline() except FileNotFoundError: raise BaseSpaceDownloadError('Secret file not found') except PermissionError: raise BaseSpaceDownloadError('No permissions to read secret file') def make_get_request(session, url, headers, stream=False): response = session.get(url, headers=headers, stream=stream) if response.status_code == 401: raise BaseSpaceDownloadError('Authentication failed on URL {}'.format(url)) elif response.status_code == 404: raise BaseSpaceDownloadError('BaseSpace file {} not found'.format(url)) return response def get_basespace_api_url(): return 'https://api.basespace.illumina.com/v1pre3' def get_basespace_api_file_url(file_id): return '{}/files/{}'.format(get_basespace_api_url(), file_id) def get_basespace_api_file_content_url(file_id): return '{}/content'.format(get_basespace_api_file_url(file_id)) def get_file_name(session, file_id, request_headers): response = make_get_request(session, get_basespace_api_file_url(file_id), request_headers) return response.json()['Response']['Name'] def download_file(session, file_id, file_name, request_headers): response = make_get_request(session, get_basespace_api_file_content_url(file_id), request_headers, True) try: with open(file_name, 'wb') as f: for chunk in response.iter_content(chunk_size=1024): f.write(chunk) except FileNotFoundError: raise BaseSpaceDownloadError('Could not save file to {}, due to directory not being found'.format(file_name)) except PermissionError: raise BaseSpaceDownloadError('Could not save file to {}, due to insufficient permissions'.format(file_name)) if __name__ == "__main__": main()
true
true
f716aa1fd41279e8e408620b6f55302402277111
26,185
py
Python
tests/test_sdb.py
peppelinux/pyoidc
2e751ed84039259a2b138148eae204c877518950
[ "Apache-2.0" ]
1
2020-09-30T13:08:14.000Z
2020-09-30T13:08:14.000Z
tests/test_sdb.py
peppelinux/pyoidc
2e751ed84039259a2b138148eae204c877518950
[ "Apache-2.0" ]
null
null
null
tests/test_sdb.py
peppelinux/pyoidc
2e751ed84039259a2b138148eae204c877518950
[ "Apache-2.0" ]
null
null
null
import base64 import datetime import hashlib import hmac import json import random import time from unittest import TestCase import pytest from freezegun import freeze_time from oic.oic.message import AuthorizationRequest from oic.oic.message import OpenIDRequest from oic.utils.sdb import AccessCodeUsed from oic.utils.sdb import AuthnEvent from oic.utils.sdb import Crypt from oic.utils.sdb import DefaultToken from oic.utils.sdb import DictRefreshDB from oic.utils.sdb import DictSessionBackend from oic.utils.sdb import ExpiredToken from oic.utils.sdb import WrongTokenType from oic.utils.sdb import create_session_db __author__ = "rohe0002" AREQ = AuthorizationRequest( response_type="code", client_id="client1", redirect_uri="http://example.com/authz", scope=["openid"], state="state000", ) AREQN = AuthorizationRequest( response_type="code", client_id="client1", redirect_uri="http://example.com/authz", scope=["openid"], state="state000", nonce="something", ) AREQO = AuthorizationRequest( response_type="code", client_id="client1", redirect_uri="http://example.com/authz", scope=["openid", "offlien_access"], prompt="consent", state="state000", ) OIDR = OpenIDRequest( response_type="code", client_id="client1", redirect_uri="http://example.com/authz", scope=["openid"], state="state000", ) def _eq(l1, l2): return set(l1) == set(l2) class TestAuthnEvent(object): """Tests for AuthnEvent class.""" def test_from_json(self): dic = {"uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500} ae = AuthnEvent.from_json(json.dumps(dic)) assert ae.uid == "uid" assert ae.salt == "salt" assert ae.authn_time == 1000 assert ae.valid_until == 1500 def test_to_json(self): ae = AuthnEvent("uid", "salt", authn_time=1000, valid_until=1500) json_repr = ae.to_json() assert json.loads(json_repr) == { "uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500, "authn_info": None, } class TestDictRefreshDB(object): @pytest.fixture(autouse=True) def create_rdb(self): self.rdb = DictRefreshDB() def test_verify_token(self): token = self.rdb.create_token( "client1", "uid", "openid", "sub1", "authzreq", "sid" ) assert self.rdb.verify_token("client1", token) assert self.rdb.verify_token("client2", token) is False def test_revoke_token(self): token = self.rdb.create_token( "client1", "uid", "openid", "sub1", "authzreq", "sid" ) self.rdb.remove(token) assert self.rdb.verify_token("client1", token) is False with pytest.raises(KeyError): self.rdb.get(token) def test_get_token(self): with pytest.raises(KeyError): self.rdb.get("token") token = self.rdb.create_token( "client1", "uid", ["openid"], "sub1", "authzreq", "sid" ) assert self.rdb.get(token) == { "client_id": "client1", "sub": "sub1", "scope": ["openid"], "uid": "uid", "authzreq": "authzreq", "sid": "sid", } class TestToken(object): @pytest.fixture(autouse=True) def create_token(self): self.token = DefaultToken("secret", "password", lifetime=60) def test_token(self): sid = self.token.key(areq=AREQ) assert len(sid) == 56 def test_new_token(self): sid = self.token.key(areq=AREQ) assert len(sid) == 56 self.token(sid=sid, ttype="T") assert len(sid) == 56 sid2 = self.token.key(areq=AREQ, user="jones") assert len(sid2) == 56 assert sid != sid2 def test_type_and_key(self): sid = self.token.key(areq=AREQ) code = self.token(sid=sid) part = self.token.type_and_key(code) assert part[0] == "A" assert part[1] == sid def test_expired_fresh(self): factory = DefaultToken("secret", "password", lifetime=60) token = factory(sid="abc", ttype="T") assert factory.is_expired(token) is False def test_expired_stale(self): initial_datetime = datetime.datetime(2018, 2, 5, 10, 0, 0, 0) final_datetime = datetime.datetime(2018, 2, 5, 10, 1, 0, 0) factory = DefaultToken("secret", "password", lifetime=2) with freeze_time(initial_datetime) as frozen: token = factory(sid="abc", ttype="T") frozen.move_to(final_datetime) assert factory.is_expired(token) is True def test_expired_when(self): factory = DefaultToken("secret", "password", lifetime=2) token = factory(sid="abc", ttype="T") when = time.time() + 5 # 5 seconds from now assert factory.is_expired(token, when=when) is True class TestSessionBackend(TestCase): """Unittests for SessionBackend - using the DictSessionBackend.""" def setUp(self): self.backend = DictSessionBackend() def test_setitem(self): self.backend["key"] = "value" self.assertEqual(self.backend.storage["key"], "value") self.backend["key"] = "new_value" self.assertEqual(self.backend.storage["key"], "new_value") def test_getitem(self): self.backend.storage = {"key": "value"} self.assertEqual(self.backend["key"], "value") with self.assertRaises(KeyError): self.backend["missing"] def test_delitem(self): self.backend.storage = {"key": "value"} del self.backend["key"] self.assertEqual(self.backend.storage, {}) def test_contains(self): self.backend["key"] = "value" self.assertTrue("key" in self.backend) self.assertFalse("missing" in self.backend) def test_get_by_sub(self): self.backend.storage = {"session_id": {"sub": "my_sub"}} self.assertEqual(set(self.backend.get_by_sub("my_sub")), {"session_id"}) self.assertEqual(set(self.backend.get_by_sub("missing")), set()) def test_get_by_sub_multiple(self): self.backend.storage = { "session_id1": {"sub": "my_sub"}, "session_id2": {"sub": "my_sub"}, } self.assertEqual( set(self.backend.get_by_sub("my_sub")), {"session_id1", "session_id2"} ) def test_get_by_uid(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = {"session_id": {"authn_event": aevent}} self.assertEqual(set(self.backend.get_by_uid("my_uid")), {"session_id"}) self.assertEqual(set(self.backend.get_by_uid("missing")), set()) def test_get_by_uid_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": {"authn_event": aevent1}, "session_id2": {"authn_event": aevent2}, } self.assertEqual( set(self.backend.get_by_uid("my_uid")), {"session_id1", "session_id2"} ) def test_get_client_ids_for_uid(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id": {"authn_event": aevent, "client_id": "my_client"} } self.assertEqual( set(self.backend.get_client_ids_for_uid("my_uid")), {"my_client"} ) self.assertEqual(set(self.backend.get_client_ids_for_uid("missing")), set()) def test_get_client_ids_for_uid_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": {"authn_event": aevent1, "client_id": "my_client"}, "session_id2": {"authn_event": aevent2, "client_id": "my_other"}, } self.assertEqual( set(self.backend.get_client_ids_for_uid("my_uid")), {"my_client", "my_other"}, ) def test_get_verified_logout(self): aevent1 = AuthnEvent("my_uid1", "some_salt").to_json() aevent2 = AuthnEvent("my_uid2", "some_salt").to_json() self.backend.storage = { "session_id": { "authn_event": aevent1, "verified_logout": "verification key", }, "session_id2": {"authn_event": aevent2}, } self.assertEqual( self.backend.get_verified_logout("my_uid1"), "verification key" ) self.assertIsNone(self.backend.get_verified_logout("my_uid2")) self.assertIsNone(self.backend.get_verified_logout("missing")) def test_get_verified_logout_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": { "authn_event": aevent1, "verified_logout": "verification key", }, "session_id2": { "authn_event": aevent2, "verified_logout": "verification key", }, } self.assertEqual(self.backend.get_verified_logout("my_uid"), "verification key") def test_get_token_ids(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id": {"authn_event": aevent, "id_token": "Id token"} } self.assertEqual(set(self.backend.get_token_ids("my_uid")), {"Id token"}) self.assertEqual(set(self.backend.get_token_ids("missing")), set()) def test_get_token_ids_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": {"authn_event": aevent1, "id_token": "Id token 1"}, "session_id2": {"authn_event": aevent2, "id_token": "Id token 2"}, } self.assertEqual( set(self.backend.get_token_ids("my_uid")), {"Id token 1", "Id token 2"} ) def test_is_revoke_uid_false(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = {"session_id": {"authn_event": aevent, "revoked": False}} self.assertFalse(self.backend.is_revoke_uid("my_uid")) def test_is_revoke_uid_true(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = {"session_id": {"authn_event": aevent, "revoked": True}} self.assertTrue(self.backend.is_revoke_uid("my_uid")) def test_is_revoke_uid_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": {"authn_event": aevent1, "revoked": True}, "session_id2": {"authn_event": aevent2, "revoked": False}, } self.assertTrue(self.backend.is_revoke_uid("my_uid")) class TestSessionDB(object): @pytest.fixture(autouse=True) def create_sdb(self, session_db_factory): self.sdb = session_db_factory("https://example.com/") def test_create_authz_session(self): ae = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae, AREQ) self.sdb.do_sub(sid, "client_salt") info = self.sdb[sid] assert info["oauth_state"] == "authz" def test_create_authz_session_without_nonce(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQ) info = self.sdb[sid] assert info["oauth_state"] == "authz" def test_create_authz_session_with_nonce(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQN) info = self.sdb[sid] assert info["nonce"] == "something" def test_create_authz_session_with_id_token(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQN, id_token="id_token") info = self.sdb[sid] assert info["id_token"] == "id_token" def test_create_authz_session_with_oidreq(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQN, oidreq=OIDR) info = self.sdb[sid] assert "id_token" not in info assert "oidreq" in info def test_create_authz_session_with_sector_id(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQN, oidreq=OIDR) self.sdb.do_sub(sid, "client_salt", "http://example.com/si.jwt", "pairwise") info_1 = self.sdb[sid].copy() assert "id_token" not in info_1 assert "oidreq" in info_1 assert info_1["sub"] != "sub" self.sdb.do_sub(sid, "client_salt", "http://example.net/si.jwt", "pairwise") info_2 = self.sdb[sid] assert info_2["sub"] != "sub" assert info_2["sub"] != info_1["sub"] def test_upgrade_to_token(self): ae1 = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae1, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] _dict = self.sdb.upgrade_to_token(grant) print(_dict.keys()) assert _eq( list(_dict.keys()), [ "authn_event", "code", "authzreq", "revoked", "access_token", "token_type", "state", "redirect_uri", "code_used", "client_id", "scope", "oauth_state", "access_token_scope", "sub", "response_type", ], ) # can't update again with pytest.raises(AccessCodeUsed): self.sdb.upgrade_to_token(grant) self.sdb.upgrade_to_token(_dict["access_token"]) def test_upgrade_to_token_refresh(self): ae1 = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae1, AREQO) self.sdb.do_sub(sid, ae1.salt) grant = self.sdb[sid]["code"] _dict = self.sdb.upgrade_to_token(grant, issue_refresh=True) print(_dict.keys()) assert _eq( _dict.keys(), [ "authn_event", "code", "authzreq", "revoked", "access_token", "response_type", "token_type", "state", "redirect_uri", "code_used", "client_id", "scope", "oauth_state", "access_token_scope", "refresh_token", "sub", ], ) # can't update again with pytest.raises(AccessCodeUsed): self.sdb.upgrade_to_token(grant) self.sdb.upgrade_to_token(_dict["access_token"]) def test_upgrade_to_token_with_id_token_and_oidreq(self): ae2 = AuthnEvent("another_user_id", "salt") sid = self.sdb.create_authz_session(ae2, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] _dict = self.sdb.upgrade_to_token(grant, id_token="id_token", oidreq=OIDR) print(_dict.keys()) assert _eq( list(_dict.keys()), [ "authn_event", "code", "authzreq", "revoked", "oidreq", "access_token", "id_token", "response_type", "token_type", "state", "redirect_uri", "code_used", "client_id", "scope", "oauth_state", "access_token_scope", "sub", ], ) assert _dict["id_token"] == "id_token" assert isinstance(_dict["oidreq"], OpenIDRequest) def test_refresh_token(self): ae = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] dict1 = self.sdb.upgrade_to_token(grant, issue_refresh=True).copy() rtoken = dict1["refresh_token"] dict2 = self.sdb.refresh_token(rtoken, AREQ["client_id"]) assert dict1["access_token"] != dict2["access_token"] with pytest.raises(WrongTokenType): self.sdb.refresh_token(dict2["access_token"], AREQ["client_id"]) def test_refresh_token_cleared_session(self): ae = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] dict1 = self.sdb.upgrade_to_token(grant, issue_refresh=True) ac1 = dict1["access_token"] # Purge the SessionDB self.sdb._db = {} rtoken = dict1["refresh_token"] dict2 = self.sdb.refresh_token(rtoken, AREQ["client_id"]) assert ac1 != dict2["access_token"] assert self.sdb.is_valid(dict2["access_token"]) def test_is_valid(self): ae1 = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae1, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] assert self.sdb.is_valid(grant) sinfo = self.sdb.upgrade_to_token(grant, issue_refresh=True) assert not self.sdb.is_valid(grant) access_token = sinfo["access_token"] assert self.sdb.access_token.valid(access_token) refresh_token = sinfo["refresh_token"] sinfo = self.sdb.refresh_token(refresh_token, AREQ["client_id"]) access_token2 = sinfo["access_token"] assert self.sdb.is_valid(access_token2) # The old access code should be invalid try: self.sdb.is_valid(access_token) except KeyError: pass def test_valid_grant(self): ae = AuthnEvent("another:user", "salt") sid = self.sdb.create_authz_session(ae, AREQ) grant = self.sdb[sid]["code"] assert self.sdb.is_valid(grant) def test_revoke_token(self): ae1 = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae1, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] tokens = self.sdb.upgrade_to_token(grant, issue_refresh=True) access_token = tokens["access_token"] refresh_token = tokens["refresh_token"] assert self.sdb.is_valid(access_token) self.sdb.revoke_token(access_token) assert not self.sdb.is_valid(access_token) sinfo = self.sdb.refresh_token(refresh_token, AREQ["client_id"]) access_token = sinfo["access_token"] assert self.sdb.is_valid(access_token) self.sdb.revoke_refresh_token(refresh_token) assert not self.sdb.is_valid(refresh_token) try: self.sdb.refresh_token(refresh_token, AREQ["client_id"]) except ExpiredToken: pass assert self.sdb.is_valid(access_token) ae2 = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae2, AREQ) grant = self.sdb[sid]["code"] self.sdb.revoke_token(grant) assert not self.sdb.is_valid(grant) def test_revoke_all_tokens(self): ae1 = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae1, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] tokens = self.sdb.upgrade_to_token(grant, issue_refresh=True) access_token = tokens["access_token"] refresh_token = tokens["refresh_token"] self.sdb.revoke_all_tokens(access_token) assert not self.sdb.is_valid(access_token) assert not self.sdb.is_valid(refresh_token) def test_sub_to_authn_event(self): ae = AuthnEvent("sub", "salt", time_stamp=time.time()) sid = self.sdb.create_authz_session(ae, AREQ) sub = self.sdb.do_sub(sid, "client_salt") # given the sub find out whether the authn event is still valid sids = self.sdb.get_sids_by_sub(sub) ae = self.sdb[sids[0]]["authn_event"] assert AuthnEvent.from_json(ae).valid() def test_do_sub_deterministic(self): ae = AuthnEvent("tester", "random_value") sid = self.sdb.create_authz_session(ae, AREQ) self.sdb.do_sub(sid, "other_random_value") info = self.sdb[sid] assert ( info["sub"] == "179670cdee6375c48e577317b2abd7d5cd26a5cdb1cfb7ef84af3d703c71d013" ) self.sdb.do_sub( sid, "other_random_value", sector_id="http://example.com", subject_type="pairwise", ) info2 = self.sdb[sid] assert ( info2["sub"] == "aaa50d80f8780cf1c4beb39e8e126556292f5091b9e39596424fefa2b99d9c53" ) self.sdb.do_sub( sid, "another_random_value", sector_id="http://other.example.com", subject_type="pairwise", ) info2 = self.sdb[sid] assert ( info2["sub"] == "62fb630e29f0d41b88e049ac0ef49a9c3ac5418c029d6e4f5417df7e9443976b" ) def test_get_authentication_event_dict(self): self.sdb._db["123"] = {} self.sdb._db["123"]["authn_event"] = { "uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500, } ae = self.sdb.get_authentication_event("123") assert ae.uid == "uid" assert ae.salt == "salt" assert ae.authn_time == 1000 assert ae.valid_until == 1500 def test_get_authentication_event_json(self): self.sdb._db["123"] = {} self.sdb._db["123"]["authn_event"] = json.dumps( {"uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500} ) ae = self.sdb.get_authentication_event("123") assert ae.uid == "uid" assert ae.salt == "salt" assert ae.authn_time == 1000 assert ae.valid_until == 1500 def test_get_sids_from_uid_distributed(self): db = DictSessionBackend() sdb1 = create_session_db("https://example.com/1", "secret", "password", db=db) sdb2 = create_session_db("https://example.com/2", "secret", "password", db=db) ae = AuthnEvent("sub", "salt", time_stamp=time.time()) sid1 = sdb1.create_authz_session(ae, AREQ) sdb1.do_sub(sid1, "salt") sid2 = sdb2.create_authz_session(ae, AREQ) sdb2.do_sub(sid2, "salt") sdb1sids = sdb1.get_sids_from_uid("sub") sdb2sids = sdb2.get_sids_from_uid("sub") assert sdb1sids == sdb2sids def test_get_client_ids_for_uid(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}), "client_id": "my_client", } assert self.sdb.get_client_ids_for_uid("my_uid") == ["my_client"] def test_get_verify_logout(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}), "verified_logout": "something", } assert self.sdb.get_verify_logout("my_uid") == "something" def test_set_verify_logout(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}) } self.sdb.set_verify_logout("my_uid") assert self.sdb.get_verify_logout("my_uid") is not None def test_set_verify_logout_multiple(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}) } self.sdb._db["321"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}) } self.sdb.set_verify_logout("my_uid") assert self.sdb.get_verify_logout("my_uid") is not None assert ( self.sdb._db["123"]["verified_logout"] == self.sdb._db["321"]["verified_logout"] ) def test_get_token_ids(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}), "id_token": "Id token", } assert set(self.sdb.get_token_ids("my_uid")) == {"Id token"} def test_get_is_revoke_uid(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}), "revoked": True, } assert self.sdb.is_revoke_uid("my_uid") def test_revoke_uid(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}) } self.sdb.revoke_uid("my_uid") assert self.sdb.is_revoke_uid("my_uid") class TestCrypt(object): @pytest.fixture(autouse=True) def create_crypt(self): self.crypt = Crypt("4-amino-1H-pyrimidine-2-one") def test_encrypt_decrypt(self): ctext = self.crypt.encrypt("Cytosine") plain = self.crypt.decrypt(ctext).decode("utf-8") assert plain == "Cytosine " ctext = self.crypt.encrypt("cytidinetriphosp") plain = self.crypt.decrypt(ctext).decode("utf-8") assert plain == "cytidinetriphosp" def test_crypt_with_b64(self): db = {} msg = "secret{}{}".format(time.time(), random.random()) csum = hmac.new(msg.encode("utf-8"), digestmod=hashlib.sha224) txt = csum.digest() # 28 bytes long, 224 bits db[txt] = "foobar" txt = txt + b"aces" # another 4 bytes ctext = self.crypt.encrypt(txt) onthewire = base64.b64encode(ctext) plain = self.crypt.decrypt(base64.b64decode(onthewire)) assert plain.endswith(b"aces") assert db[plain[:-4]] == "foobar"
34.228758
88
0.586901
import base64 import datetime import hashlib import hmac import json import random import time from unittest import TestCase import pytest from freezegun import freeze_time from oic.oic.message import AuthorizationRequest from oic.oic.message import OpenIDRequest from oic.utils.sdb import AccessCodeUsed from oic.utils.sdb import AuthnEvent from oic.utils.sdb import Crypt from oic.utils.sdb import DefaultToken from oic.utils.sdb import DictRefreshDB from oic.utils.sdb import DictSessionBackend from oic.utils.sdb import ExpiredToken from oic.utils.sdb import WrongTokenType from oic.utils.sdb import create_session_db __author__ = "rohe0002" AREQ = AuthorizationRequest( response_type="code", client_id="client1", redirect_uri="http://example.com/authz", scope=["openid"], state="state000", ) AREQN = AuthorizationRequest( response_type="code", client_id="client1", redirect_uri="http://example.com/authz", scope=["openid"], state="state000", nonce="something", ) AREQO = AuthorizationRequest( response_type="code", client_id="client1", redirect_uri="http://example.com/authz", scope=["openid", "offlien_access"], prompt="consent", state="state000", ) OIDR = OpenIDRequest( response_type="code", client_id="client1", redirect_uri="http://example.com/authz", scope=["openid"], state="state000", ) def _eq(l1, l2): return set(l1) == set(l2) class TestAuthnEvent(object): def test_from_json(self): dic = {"uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500} ae = AuthnEvent.from_json(json.dumps(dic)) assert ae.uid == "uid" assert ae.salt == "salt" assert ae.authn_time == 1000 assert ae.valid_until == 1500 def test_to_json(self): ae = AuthnEvent("uid", "salt", authn_time=1000, valid_until=1500) json_repr = ae.to_json() assert json.loads(json_repr) == { "uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500, "authn_info": None, } class TestDictRefreshDB(object): @pytest.fixture(autouse=True) def create_rdb(self): self.rdb = DictRefreshDB() def test_verify_token(self): token = self.rdb.create_token( "client1", "uid", "openid", "sub1", "authzreq", "sid" ) assert self.rdb.verify_token("client1", token) assert self.rdb.verify_token("client2", token) is False def test_revoke_token(self): token = self.rdb.create_token( "client1", "uid", "openid", "sub1", "authzreq", "sid" ) self.rdb.remove(token) assert self.rdb.verify_token("client1", token) is False with pytest.raises(KeyError): self.rdb.get(token) def test_get_token(self): with pytest.raises(KeyError): self.rdb.get("token") token = self.rdb.create_token( "client1", "uid", ["openid"], "sub1", "authzreq", "sid" ) assert self.rdb.get(token) == { "client_id": "client1", "sub": "sub1", "scope": ["openid"], "uid": "uid", "authzreq": "authzreq", "sid": "sid", } class TestToken(object): @pytest.fixture(autouse=True) def create_token(self): self.token = DefaultToken("secret", "password", lifetime=60) def test_token(self): sid = self.token.key(areq=AREQ) assert len(sid) == 56 def test_new_token(self): sid = self.token.key(areq=AREQ) assert len(sid) == 56 self.token(sid=sid, ttype="T") assert len(sid) == 56 sid2 = self.token.key(areq=AREQ, user="jones") assert len(sid2) == 56 assert sid != sid2 def test_type_and_key(self): sid = self.token.key(areq=AREQ) code = self.token(sid=sid) part = self.token.type_and_key(code) assert part[0] == "A" assert part[1] == sid def test_expired_fresh(self): factory = DefaultToken("secret", "password", lifetime=60) token = factory(sid="abc", ttype="T") assert factory.is_expired(token) is False def test_expired_stale(self): initial_datetime = datetime.datetime(2018, 2, 5, 10, 0, 0, 0) final_datetime = datetime.datetime(2018, 2, 5, 10, 1, 0, 0) factory = DefaultToken("secret", "password", lifetime=2) with freeze_time(initial_datetime) as frozen: token = factory(sid="abc", ttype="T") frozen.move_to(final_datetime) assert factory.is_expired(token) is True def test_expired_when(self): factory = DefaultToken("secret", "password", lifetime=2) token = factory(sid="abc", ttype="T") when = time.time() + 5 assert factory.is_expired(token, when=when) is True class TestSessionBackend(TestCase): def setUp(self): self.backend = DictSessionBackend() def test_setitem(self): self.backend["key"] = "value" self.assertEqual(self.backend.storage["key"], "value") self.backend["key"] = "new_value" self.assertEqual(self.backend.storage["key"], "new_value") def test_getitem(self): self.backend.storage = {"key": "value"} self.assertEqual(self.backend["key"], "value") with self.assertRaises(KeyError): self.backend["missing"] def test_delitem(self): self.backend.storage = {"key": "value"} del self.backend["key"] self.assertEqual(self.backend.storage, {}) def test_contains(self): self.backend["key"] = "value" self.assertTrue("key" in self.backend) self.assertFalse("missing" in self.backend) def test_get_by_sub(self): self.backend.storage = {"session_id": {"sub": "my_sub"}} self.assertEqual(set(self.backend.get_by_sub("my_sub")), {"session_id"}) self.assertEqual(set(self.backend.get_by_sub("missing")), set()) def test_get_by_sub_multiple(self): self.backend.storage = { "session_id1": {"sub": "my_sub"}, "session_id2": {"sub": "my_sub"}, } self.assertEqual( set(self.backend.get_by_sub("my_sub")), {"session_id1", "session_id2"} ) def test_get_by_uid(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = {"session_id": {"authn_event": aevent}} self.assertEqual(set(self.backend.get_by_uid("my_uid")), {"session_id"}) self.assertEqual(set(self.backend.get_by_uid("missing")), set()) def test_get_by_uid_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": {"authn_event": aevent1}, "session_id2": {"authn_event": aevent2}, } self.assertEqual( set(self.backend.get_by_uid("my_uid")), {"session_id1", "session_id2"} ) def test_get_client_ids_for_uid(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id": {"authn_event": aevent, "client_id": "my_client"} } self.assertEqual( set(self.backend.get_client_ids_for_uid("my_uid")), {"my_client"} ) self.assertEqual(set(self.backend.get_client_ids_for_uid("missing")), set()) def test_get_client_ids_for_uid_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": {"authn_event": aevent1, "client_id": "my_client"}, "session_id2": {"authn_event": aevent2, "client_id": "my_other"}, } self.assertEqual( set(self.backend.get_client_ids_for_uid("my_uid")), {"my_client", "my_other"}, ) def test_get_verified_logout(self): aevent1 = AuthnEvent("my_uid1", "some_salt").to_json() aevent2 = AuthnEvent("my_uid2", "some_salt").to_json() self.backend.storage = { "session_id": { "authn_event": aevent1, "verified_logout": "verification key", }, "session_id2": {"authn_event": aevent2}, } self.assertEqual( self.backend.get_verified_logout("my_uid1"), "verification key" ) self.assertIsNone(self.backend.get_verified_logout("my_uid2")) self.assertIsNone(self.backend.get_verified_logout("missing")) def test_get_verified_logout_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": { "authn_event": aevent1, "verified_logout": "verification key", }, "session_id2": { "authn_event": aevent2, "verified_logout": "verification key", }, } self.assertEqual(self.backend.get_verified_logout("my_uid"), "verification key") def test_get_token_ids(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id": {"authn_event": aevent, "id_token": "Id token"} } self.assertEqual(set(self.backend.get_token_ids("my_uid")), {"Id token"}) self.assertEqual(set(self.backend.get_token_ids("missing")), set()) def test_get_token_ids_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": {"authn_event": aevent1, "id_token": "Id token 1"}, "session_id2": {"authn_event": aevent2, "id_token": "Id token 2"}, } self.assertEqual( set(self.backend.get_token_ids("my_uid")), {"Id token 1", "Id token 2"} ) def test_is_revoke_uid_false(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = {"session_id": {"authn_event": aevent, "revoked": False}} self.assertFalse(self.backend.is_revoke_uid("my_uid")) def test_is_revoke_uid_true(self): aevent = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = {"session_id": {"authn_event": aevent, "revoked": True}} self.assertTrue(self.backend.is_revoke_uid("my_uid")) def test_is_revoke_uid_multiple(self): aevent1 = AuthnEvent("my_uid", "some_salt").to_json() aevent2 = AuthnEvent("my_uid", "some_salt").to_json() self.backend.storage = { "session_id1": {"authn_event": aevent1, "revoked": True}, "session_id2": {"authn_event": aevent2, "revoked": False}, } self.assertTrue(self.backend.is_revoke_uid("my_uid")) class TestSessionDB(object): @pytest.fixture(autouse=True) def create_sdb(self, session_db_factory): self.sdb = session_db_factory("https://example.com/") def test_create_authz_session(self): ae = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae, AREQ) self.sdb.do_sub(sid, "client_salt") info = self.sdb[sid] assert info["oauth_state"] == "authz" def test_create_authz_session_without_nonce(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQ) info = self.sdb[sid] assert info["oauth_state"] == "authz" def test_create_authz_session_with_nonce(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQN) info = self.sdb[sid] assert info["nonce"] == "something" def test_create_authz_session_with_id_token(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQN, id_token="id_token") info = self.sdb[sid] assert info["id_token"] == "id_token" def test_create_authz_session_with_oidreq(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQN, oidreq=OIDR) info = self.sdb[sid] assert "id_token" not in info assert "oidreq" in info def test_create_authz_session_with_sector_id(self): ae = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae, AREQN, oidreq=OIDR) self.sdb.do_sub(sid, "client_salt", "http://example.com/si.jwt", "pairwise") info_1 = self.sdb[sid].copy() assert "id_token" not in info_1 assert "oidreq" in info_1 assert info_1["sub"] != "sub" self.sdb.do_sub(sid, "client_salt", "http://example.net/si.jwt", "pairwise") info_2 = self.sdb[sid] assert info_2["sub"] != "sub" assert info_2["sub"] != info_1["sub"] def test_upgrade_to_token(self): ae1 = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae1, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] _dict = self.sdb.upgrade_to_token(grant) print(_dict.keys()) assert _eq( list(_dict.keys()), [ "authn_event", "code", "authzreq", "revoked", "access_token", "token_type", "state", "redirect_uri", "code_used", "client_id", "scope", "oauth_state", "access_token_scope", "sub", "response_type", ], ) with pytest.raises(AccessCodeUsed): self.sdb.upgrade_to_token(grant) self.sdb.upgrade_to_token(_dict["access_token"]) def test_upgrade_to_token_refresh(self): ae1 = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae1, AREQO) self.sdb.do_sub(sid, ae1.salt) grant = self.sdb[sid]["code"] _dict = self.sdb.upgrade_to_token(grant, issue_refresh=True) print(_dict.keys()) assert _eq( _dict.keys(), [ "authn_event", "code", "authzreq", "revoked", "access_token", "response_type", "token_type", "state", "redirect_uri", "code_used", "client_id", "scope", "oauth_state", "access_token_scope", "refresh_token", "sub", ], ) # can't update again with pytest.raises(AccessCodeUsed): self.sdb.upgrade_to_token(grant) self.sdb.upgrade_to_token(_dict["access_token"]) def test_upgrade_to_token_with_id_token_and_oidreq(self): ae2 = AuthnEvent("another_user_id", "salt") sid = self.sdb.create_authz_session(ae2, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] _dict = self.sdb.upgrade_to_token(grant, id_token="id_token", oidreq=OIDR) print(_dict.keys()) assert _eq( list(_dict.keys()), [ "authn_event", "code", "authzreq", "revoked", "oidreq", "access_token", "id_token", "response_type", "token_type", "state", "redirect_uri", "code_used", "client_id", "scope", "oauth_state", "access_token_scope", "sub", ], ) assert _dict["id_token"] == "id_token" assert isinstance(_dict["oidreq"], OpenIDRequest) def test_refresh_token(self): ae = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] dict1 = self.sdb.upgrade_to_token(grant, issue_refresh=True).copy() rtoken = dict1["refresh_token"] dict2 = self.sdb.refresh_token(rtoken, AREQ["client_id"]) assert dict1["access_token"] != dict2["access_token"] with pytest.raises(WrongTokenType): self.sdb.refresh_token(dict2["access_token"], AREQ["client_id"]) def test_refresh_token_cleared_session(self): ae = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] dict1 = self.sdb.upgrade_to_token(grant, issue_refresh=True) ac1 = dict1["access_token"] self.sdb._db = {} rtoken = dict1["refresh_token"] dict2 = self.sdb.refresh_token(rtoken, AREQ["client_id"]) assert ac1 != dict2["access_token"] assert self.sdb.is_valid(dict2["access_token"]) def test_is_valid(self): ae1 = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae1, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] assert self.sdb.is_valid(grant) sinfo = self.sdb.upgrade_to_token(grant, issue_refresh=True) assert not self.sdb.is_valid(grant) access_token = sinfo["access_token"] assert self.sdb.access_token.valid(access_token) refresh_token = sinfo["refresh_token"] sinfo = self.sdb.refresh_token(refresh_token, AREQ["client_id"]) access_token2 = sinfo["access_token"] assert self.sdb.is_valid(access_token2) try: self.sdb.is_valid(access_token) except KeyError: pass def test_valid_grant(self): ae = AuthnEvent("another:user", "salt") sid = self.sdb.create_authz_session(ae, AREQ) grant = self.sdb[sid]["code"] assert self.sdb.is_valid(grant) def test_revoke_token(self): ae1 = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae1, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] tokens = self.sdb.upgrade_to_token(grant, issue_refresh=True) access_token = tokens["access_token"] refresh_token = tokens["refresh_token"] assert self.sdb.is_valid(access_token) self.sdb.revoke_token(access_token) assert not self.sdb.is_valid(access_token) sinfo = self.sdb.refresh_token(refresh_token, AREQ["client_id"]) access_token = sinfo["access_token"] assert self.sdb.is_valid(access_token) self.sdb.revoke_refresh_token(refresh_token) assert not self.sdb.is_valid(refresh_token) try: self.sdb.refresh_token(refresh_token, AREQ["client_id"]) except ExpiredToken: pass assert self.sdb.is_valid(access_token) ae2 = AuthnEvent("sub", "salt") sid = self.sdb.create_authz_session(ae2, AREQ) grant = self.sdb[sid]["code"] self.sdb.revoke_token(grant) assert not self.sdb.is_valid(grant) def test_revoke_all_tokens(self): ae1 = AuthnEvent("uid", "salt") sid = self.sdb.create_authz_session(ae1, AREQ) self.sdb[sid]["sub"] = "sub" grant = self.sdb[sid]["code"] tokens = self.sdb.upgrade_to_token(grant, issue_refresh=True) access_token = tokens["access_token"] refresh_token = tokens["refresh_token"] self.sdb.revoke_all_tokens(access_token) assert not self.sdb.is_valid(access_token) assert not self.sdb.is_valid(refresh_token) def test_sub_to_authn_event(self): ae = AuthnEvent("sub", "salt", time_stamp=time.time()) sid = self.sdb.create_authz_session(ae, AREQ) sub = self.sdb.do_sub(sid, "client_salt") sids = self.sdb.get_sids_by_sub(sub) ae = self.sdb[sids[0]]["authn_event"] assert AuthnEvent.from_json(ae).valid() def test_do_sub_deterministic(self): ae = AuthnEvent("tester", "random_value") sid = self.sdb.create_authz_session(ae, AREQ) self.sdb.do_sub(sid, "other_random_value") info = self.sdb[sid] assert ( info["sub"] == "179670cdee6375c48e577317b2abd7d5cd26a5cdb1cfb7ef84af3d703c71d013" ) self.sdb.do_sub( sid, "other_random_value", sector_id="http://example.com", subject_type="pairwise", ) info2 = self.sdb[sid] assert ( info2["sub"] == "aaa50d80f8780cf1c4beb39e8e126556292f5091b9e39596424fefa2b99d9c53" ) self.sdb.do_sub( sid, "another_random_value", sector_id="http://other.example.com", subject_type="pairwise", ) info2 = self.sdb[sid] assert ( info2["sub"] == "62fb630e29f0d41b88e049ac0ef49a9c3ac5418c029d6e4f5417df7e9443976b" ) def test_get_authentication_event_dict(self): self.sdb._db["123"] = {} self.sdb._db["123"]["authn_event"] = { "uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500, } ae = self.sdb.get_authentication_event("123") assert ae.uid == "uid" assert ae.salt == "salt" assert ae.authn_time == 1000 assert ae.valid_until == 1500 def test_get_authentication_event_json(self): self.sdb._db["123"] = {} self.sdb._db["123"]["authn_event"] = json.dumps( {"uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500} ) ae = self.sdb.get_authentication_event("123") assert ae.uid == "uid" assert ae.salt == "salt" assert ae.authn_time == 1000 assert ae.valid_until == 1500 def test_get_sids_from_uid_distributed(self): db = DictSessionBackend() sdb1 = create_session_db("https://example.com/1", "secret", "password", db=db) sdb2 = create_session_db("https://example.com/2", "secret", "password", db=db) ae = AuthnEvent("sub", "salt", time_stamp=time.time()) sid1 = sdb1.create_authz_session(ae, AREQ) sdb1.do_sub(sid1, "salt") sid2 = sdb2.create_authz_session(ae, AREQ) sdb2.do_sub(sid2, "salt") sdb1sids = sdb1.get_sids_from_uid("sub") sdb2sids = sdb2.get_sids_from_uid("sub") assert sdb1sids == sdb2sids def test_get_client_ids_for_uid(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}), "client_id": "my_client", } assert self.sdb.get_client_ids_for_uid("my_uid") == ["my_client"] def test_get_verify_logout(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}), "verified_logout": "something", } assert self.sdb.get_verify_logout("my_uid") == "something" def test_set_verify_logout(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}) } self.sdb.set_verify_logout("my_uid") assert self.sdb.get_verify_logout("my_uid") is not None def test_set_verify_logout_multiple(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}) } self.sdb._db["321"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}) } self.sdb.set_verify_logout("my_uid") assert self.sdb.get_verify_logout("my_uid") is not None assert ( self.sdb._db["123"]["verified_logout"] == self.sdb._db["321"]["verified_logout"] ) def test_get_token_ids(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}), "id_token": "Id token", } assert set(self.sdb.get_token_ids("my_uid")) == {"Id token"} def test_get_is_revoke_uid(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}), "revoked": True, } assert self.sdb.is_revoke_uid("my_uid") def test_revoke_uid(self): self.sdb._db["123"] = { "authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}) } self.sdb.revoke_uid("my_uid") assert self.sdb.is_revoke_uid("my_uid") class TestCrypt(object): @pytest.fixture(autouse=True) def create_crypt(self): self.crypt = Crypt("4-amino-1H-pyrimidine-2-one") def test_encrypt_decrypt(self): ctext = self.crypt.encrypt("Cytosine") plain = self.crypt.decrypt(ctext).decode("utf-8") assert plain == "Cytosine " ctext = self.crypt.encrypt("cytidinetriphosp") plain = self.crypt.decrypt(ctext).decode("utf-8") assert plain == "cytidinetriphosp" def test_crypt_with_b64(self): db = {} msg = "secret{}{}".format(time.time(), random.random()) csum = hmac.new(msg.encode("utf-8"), digestmod=hashlib.sha224) txt = csum.digest() db[txt] = "foobar" txt = txt + b"aces" ctext = self.crypt.encrypt(txt) onthewire = base64.b64encode(ctext) plain = self.crypt.decrypt(base64.b64decode(onthewire)) assert plain.endswith(b"aces") assert db[plain[:-4]] == "foobar"
true
true
f716aa23ec2670b3b6679f13ad0859e223f380ff
309
py
Python
dataset/proxies.py
unknown/reddit-aita
557fd67120e529db8b014b74a71e3b926b0ed528
[ "MIT" ]
null
null
null
dataset/proxies.py
unknown/reddit-aita
557fd67120e529db8b014b74a71e3b926b0ed528
[ "MIT" ]
null
null
null
dataset/proxies.py
unknown/reddit-aita
557fd67120e529db8b014b74a71e3b926b0ed528
[ "MIT" ]
null
null
null
import random proxy_list = [ 'http://p.webshare.io:19999' ] def random_proxy(): i = random.randint(0, len(proxy_list) - 1) p = { 'http': proxy_list[i] } return p def remove_proxy(proxy): proxy_list.remove(proxy) print(f'Removed {proxy}-- {len(proxy_list)} proxies left')
19.3125
62
0.621359
import random proxy_list = [ 'http://p.webshare.io:19999' ] def random_proxy(): i = random.randint(0, len(proxy_list) - 1) p = { 'http': proxy_list[i] } return p def remove_proxy(proxy): proxy_list.remove(proxy) print(f'Removed {proxy}-- {len(proxy_list)} proxies left')
true
true
f716ab6b8551b5a9bf03bfb3d99382d22fe6e166
30,230
py
Python
Scripts/simulation/interactions/utils/creation.py
velocist/TS4CheatsInfo
b59ea7e5f4bd01d3b3bd7603843d525a9c179867
[ "Apache-2.0" ]
null
null
null
Scripts/simulation/interactions/utils/creation.py
velocist/TS4CheatsInfo
b59ea7e5f4bd01d3b3bd7603843d525a9c179867
[ "Apache-2.0" ]
null
null
null
Scripts/simulation/interactions/utils/creation.py
velocist/TS4CheatsInfo
b59ea7e5f4bd01d3b3bd7603843d525a9c179867
[ "Apache-2.0" ]
null
null
null
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\interactions\utils\creation.py # Compiled at: 2019-12-03 21:37:40 # Size of source mod 2**32: 42011 bytes from animation.animation_utils import flush_all_animations from carry.carry_elements import enter_carry_while_holding from element_utils import build_critical_section from event_testing.resolver import SingleSimResolver from filters.sim_template import TunableSimTemplate from filters.tunable import TunableSimFilter from interactions import ParticipantType, ParticipantTypeActorTargetSim, ParticipantTypeSingleSim, ParticipantTypeSingle from interactions.interaction_finisher import FinishingType from interactions.utils.interaction_elements import XevtTriggeredElement from objects import VisibilityState from objects.object_creation import ObjectCreationMixin from objects.slots import RuntimeSlot from sims.genealogy_tracker import genealogy_caching, FamilyRelationshipIndex from sims.pregnancy.pregnancy_tracker import PregnancyTracker from sims.sim_info_lod import SimInfoLODLevel from sims.sim_spawner import SimSpawner, SimCreator from sims4.tuning.geometric import TunableDistanceSquared from sims4.tuning.tunable import TunableList, OptionalTunable, Tunable, TunableEnumEntry, TunableVariant, TunableFactory, TunableReference, HasTunableSingletonFactory, AutoFactoryInit from singletons import EMPTY_SET, DEFAULT from tag import Tag from venues.venue_constants import NPCSummoningPurpose from world.spawn_actions import TunableSpawnActionVariant import element_utils, id_generator, interactions, services, sims.ghost, sims4.log, sims4.math, sims4.telemetry, telemetry_helper logger = sims4.log.Logger('Creation') TELEMETRY_GROUP_OBJECT = 'OBJC' TELEMETRY_HOOK_OBJECT_CREATE_BSCEXTRA = 'CRBE' TELEMETRY_FIELD_OBJECT_INTERACTION = 'intr' TELEMETRY_FIELD_OBJECT_DEFINITION = 'objc' writer = sims4.telemetry.TelemetryWriter(TELEMETRY_GROUP_OBJECT) class ObjectCreationElement(XevtTriggeredElement, ObjectCreationMixin): FACTORY_TUNABLES = {'cancel_on_destroy':Tunable(description='\n If checked, the interaction will be canceled if object is destroyed\n due to placement failure or if destroy on placement failure is\n unchecked and the fallback fails.\n ', tunable_type=bool, default=True), 'transient':Tunable(description='\n If checked, the created object will be destroyed when the interaction ends.\n ', tunable_type=bool, default=False), 'set_to_invisible':Tunable(description='\n If checked, the created object will be set to invisible when the \n interaction ends.\n ', tunable_type=bool, default=False)} def __init__(self, interaction, *args, sequence=(), **kwargs): (super().__init__)(interaction, *args, sequence=sequence, **kwargs) self._definition_cache = None self._placement_failed = False self.initialize_helper(interaction.get_resolver()) if self.transient: self.require_claim = True @property def definition(self): if self._definition_cache is None: self._definition_cache = super().definition return self._definition_cache @property def placement_failed(self): return self._placement_failed def create_object_in_sequence(self): self._place_object(self._object_helper.object) if self._placement_failed: if self.cancel_on_destroy: self.interaction.cancel((FinishingType.FAILED_TESTS), cancel_reason_msg='Cannot place object') return False return True if not self.transient: self._object_helper.claim() if self.set_to_invisible: self._object_helper.object.visibility = VisibilityState(False) with telemetry_helper.begin_hook(writer, TELEMETRY_HOOK_OBJECT_CREATE_BSCEXTRA) as (hook): hook.write_enum(TELEMETRY_FIELD_OBJECT_INTERACTION, self.interaction.guid64) hook.write_guid(TELEMETRY_FIELD_OBJECT_DEFINITION, self._object_helper.object.definition.id) return True def _setup_created_object(self, created_object): self.interaction.object_create_helper = self._object_helper super()._setup_created_object(created_object) def _place_object(self, created_object): place_object = super()._place_object(created_object) if not place_object: self._placement_failed = True return place_object def _build_outer_elements(self, sequence): def set_carry_target(_): self.interaction.track = DEFAULT self.interaction.map_create_target(self.interaction.created_target) def enter_carry(timeline): result = yield from element_utils.run_child(timeline, enter_carry_while_holding((self.interaction), obj=(self.interaction.created_target), carry_track_override=(self.location.carry_track_override), owning_affordance=None, sequence=(build_critical_section(sequence, flush_all_animations)))) return result if False: yield None location_type = getattr(self.location, 'location', None) if location_type == self.CARRY: return self._object_helper.create(set_carry_target, enter_carry) return self._object_helper.create(sequence) def _do_behavior(self): self.create_object_in_sequence() class SimCreationElement(XevtTriggeredElement): class _ActiveHouseholdFactory(TunableFactory): @staticmethod def factory(_): return services.active_household() FACTORY_TYPE = factory class _ParticipantHouseholdFactory(TunableFactory): @staticmethod def factory(interaction, participant): sim = interaction.get_participant(participant) if sim is None: logger.error('_ParticipantHouseholdFactory: {} does not have participant {}', interaction, participant, owner='jjacobson') return return sim.household FACTORY_TYPE = factory def __init__(self, *args, **kwargs): (super().__init__)(participant=TunableEnumEntry(description='\n The participant that will have their household used to put the\n sim into.\n ', tunable_type=ParticipantTypeActorTargetSim, default=(ParticipantTypeActorTargetSim.Actor)), **kwargs) class _NoHousheoldFactory(TunableFactory): @staticmethod def factory(_): pass FACTORY_TYPE = factory class _HiddenHouseholdFactory(TunableFactory): @staticmethod def factory(_): household = services.household_manager().create_household(services.get_first_client().account) household.set_to_hidden(family_funds=0) return household FACTORY_TYPE = factory class _BaseSimInfoSource(HasTunableSingletonFactory, AutoFactoryInit): def get_sim_infos_and_positions(self, resolver): raise NotImplementedError('Attempting to use the _BaseSimInfoSource base class, use sub-classes instead.') def _try_add_sim_info_to_household(self, sim_info, resolver, household, skip_household_check=False): if household is not None: if skip_household_check or household is not sim_info.household: if not household.can_add_sim_info(sim_info): logger.warn('create_sim_from_sim_info element on the interaction: {} could not add a new sim to the tuned household.', resolver.interaction) return False if sim_info.household is not household: sim_info.household.remove_sim_info(sim_info) household.add_sim_info_to_household(sim_info) return True def do_pre_spawn_behavior(self, sim_info, resolver, household): self._try_add_sim_info_to_household(sim_info, resolver, household) def do_post_spawn_behavior(self, sim_info, resolver, client_manager): client = client_manager.get_client_by_household_id(sim_info.household_id) if client is not None: client.add_selectable_sim_info(sim_info) class _TargetedObjectResurrection(_BaseSimInfoSource): FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant of the interaction against whom any relationship\n and genealogy tunables are applied.\n ', tunable_type=ParticipantType, default=ParticipantType.Actor), 'sim_info_subject':TunableEnumEntry(description='\n The subject from which the Sim Info used to create the new Sim\n should be fetched.\n ', tunable_type=ParticipantType, default=ParticipantType.Object), 'resurrect':Tunable(description='\n If checked, all Ghost traits are removed from the created Sim\n and its death type is cleared.\n \n If unchecked, this is a simple spawn operation.\n ', tunable_type=bool, default=True)} def get_sim_infos_and_positions(self, resolver, household): use_fgl = True stored_sim_info_object = resolver.get_participant(self.sim_info_subject) if stored_sim_info_object is None: return () sim_info = stored_sim_info_object.get_stored_sim_info() if sim_info is None: return () return ( ( sim_info, stored_sim_info_object.position, None, use_fgl),) def do_pre_spawn_behavior(self, sim_info, resolver, household): super().do_pre_spawn_behavior(sim_info, resolver, household) if self.resurrect: sims.ghost.Ghost.remove_ghost_from_sim(sim_info) class _MassObjectResurrection(_BaseSimInfoSource): FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant of the interaction that will have sims resurrected\n around their position.\n ', tunable_type=ParticipantType, default=ParticipantType.Actor), 'radius':TunableDistanceSquared(description='\n The distance around a participant that will resurrect all of the\n dead sim objects.\n ', default=1), 'tag':TunableEnumEntry(description='\n Tag the delineates an object that we want to resurrect sims\n from.\n ', tunable_type=Tag, default=Tag.INVALID)} def get_sim_infos_and_positions(self, resolver, household): use_fgl = True sim_infos_and_positions = [] participant = resolver.get_participant(self.participant) position = participant.position for obj in services.object_manager().get_objects_with_tag_gen(self.tag): obj_position = obj.position distance_from_pos = obj_position - position if distance_from_pos.magnitude_squared() > self.radius: continue sim_info = obj.get_stored_sim_info() if sim_info is None: continue sim_infos_and_positions.append((sim_info, obj_position, None, use_fgl)) return tuple(sim_infos_and_positions) def do_pre_spawn_behavior(self, sim_info, resolver, household): super().do_pre_spawn_behavior(sim_info, resolver, household) sims.ghost.Ghost.remove_ghost_from_sim(sim_info) class _SlotSpawningSimInfoSource(_BaseSimInfoSource): class _SlotByName(HasTunableSingletonFactory, AutoFactoryInit): FACTORY_TUNABLES = {'slot_name': Tunable(description='\n The exact name of a slot on the parent object.\n ', tunable_type=str, default='_ctnm_')} def get_slot_type_and_hash(self): return ( None, sims4.hash_util.hash32(self.slot_name)) class _SlotByType(HasTunableSingletonFactory, AutoFactoryInit): FACTORY_TUNABLES = {'slot_type': TunableReference(description='\n A particular slot type in which the should spawn.\n ', manager=(services.get_instance_manager(sims4.resources.Types.SLOT_TYPE)))} def get_slot_type_and_hash(self): return ( self.slot_type, None) FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant that is a sim that will be cloned\n Note: MUST be a sim. Use create object - clone object for non-sim objects.\n ', tunable_type=ParticipantTypeSingleSim, default=ParticipantTypeSingleSim.Actor), 'sim_spawn_slot':TunableVariant(description="\n The slot on the parent object where the sim should spawn. This\n may be either the exact name of a bone on the parent object or a\n slot type, in which case the first empty slot of the specified type\n will be used. If None is chosen, then the sim will at or near\n the interaction target's location.\n ", by_name=_SlotByName.TunableFactory(), by_type=_SlotByType.TunableFactory()), 'spawn_location_participant':TunableEnumEntry(description='\n The participant used for finding where to spawn the Sim. Typically you want to leave this as object.\n \n Special cases include:\n - For self-interactions, Object will resolve to None. This can be set to Actor if you want to spawn\n near the Sim running the interaction.\n ', tunable_type=ParticipantTypeSingle, default=ParticipantTypeSingle.Object)} def __init__(self, sim_spawn_slot=None, **kwargs): (super().__init__)(sim_spawn_slot=sim_spawn_slot, **kwargs) self._slot_type = None self._bone_name_hash = None if sim_spawn_slot is not None: self._slot_type, self._bone_name_hash = sim_spawn_slot.get_slot_type_and_hash() def _get_position_and_location(self, spawning_object, resolver): position, location = (None, None) if self._slot_type is not None: for runtime_slot in spawning_object.get_runtime_slots_gen(slot_types={self._slot_type}, bone_name_hash=(self._bone_name_hash)): location = runtime_slot.location else: if self._bone_name_hash is not None: runtime_slot = RuntimeSlot(spawning_object, self._bone_name_hash, EMPTY_SET) if runtime_slot is not None: location = runtime_slot.location else: location = spawning_object.location if location is not None: location = sims4.math.Location((location.world_transform), (spawning_object.routing_surface), slot_hash=(location.slot_hash)) position = location.transform.translation return (position, location) def _get_spawning_object(self, resolver): spawning_object = resolver.get_participant(self.spawn_location_participant) if spawning_object.is_sim: spawning_object = spawning_object.get_sim_instance() return spawning_object class _CloneSimInfoSource(_SlotSpawningSimInfoSource): FACTORY_TUNABLES = {'force_fgl': Tunable(description="\n Normally, FGL will only be invoked if no spawning position is found. Use this tunable to force\n FGL to run. e.g. Cloning spell uses caster Sim's position as a spawning position. In that case,\n we still want to force FGL so the clone spawns near that Sim rather than directly on top of the Sim. \n ", tunable_type=bool, default=False)} def _ensure_parental_lineage_exists(self, source_sim_info, clone_sim_info): with genealogy_caching(): if any(source_sim_info.genealogy.get_parent_sim_ids_gen()): return mom_id = id_generator.generate_object_id() source_sim_info.genealogy.set_family_relation(FamilyRelationshipIndex.MOTHER, mom_id) clone_sim_info.genealogy.set_family_relation(FamilyRelationshipIndex.MOTHER, mom_id) sim_info_manager = services.sim_info_manager() for child_sim_id in source_sim_info.genealogy.get_children_sim_ids_gen(): child_sim_info = sim_info_manager.get(child_sim_id) if child_sim_info is not None: grandparent_relation = FamilyRelationshipIndex.MOTHERS_MOM if source_sim_info.is_female else FamilyRelationshipIndex.FATHERS_MOM child_sim_info.genealogy.set_family_relation(grandparent_relation, mom_id) def _create_clone_sim_info(self, source_sim_info, resolver, household): sim_creator = SimCreator(gender=(source_sim_info.gender), age=(source_sim_info.age), first_name=(SimSpawner.get_random_first_name(source_sim_info.gender, source_sim_info.species)), last_name=(source_sim_info._base.last_name), traits=(source_sim_info.trait_tracker.equipped_traits)) sim_info_list, _ = SimSpawner.create_sim_infos((sim_creator,), household=household, account=(source_sim_info.account), generate_deterministic_sim=True, creation_source='cloning', skip_adding_to_household=True) clone_sim_info = sim_info_list[0] source_sim_proto = source_sim_info.save_sim(for_cloning=True) clone_sim_id = clone_sim_info.sim_id clone_first_name = clone_sim_info._base.first_name clone_last_name = clone_sim_info._base.last_name clone_breed_name = clone_sim_info._base.breed_name clone_first_name_key = clone_sim_info._base.first_name_key clone_last_name_key = clone_sim_info._base.last_name_key clone_full_name_key = clone_sim_info._base.full_name_key clone_breed_name_key = clone_sim_info._base.breed_name_key clone_sim_info.load_sim_info(source_sim_proto, is_clone=True, default_lod=(SimInfoLODLevel.FULL)) clone_sim_info.sim_id = clone_sim_id clone_sim_info._base.first_name = clone_first_name clone_sim_info._base.last_name = clone_last_name clone_sim_info._base.breed_name = clone_breed_name clone_sim_info._base.first_name_key = clone_first_name_key clone_sim_info._base.last_name_key = clone_last_name_key clone_sim_info._base.full_name_key = clone_full_name_key clone_sim_info._base.breed_name_key = clone_breed_name_key clone_sim_info._household_id = household.id if not self._try_add_sim_info_to_household(clone_sim_info, resolver, household, skip_household_check=True): return source_trait_tracker = source_sim_info.trait_tracker clone_trait_tracker = clone_sim_info.trait_tracker for trait in clone_trait_tracker.personality_traits: if not source_trait_tracker.has_trait(trait): clone_sim_info.remove_trait(trait) for trait in clone_trait_tracker.gender_option_traits: if not source_trait_tracker.has_trait(trait): clone_sim_info.remove_trait(trait) correct_aspiration_trait = clone_sim_info.primary_aspiration.primary_trait for trait in tuple(clone_trait_tracker.aspiration_traits): if trait is not correct_aspiration_trait: clone_sim_info.remove_trait(trait) source_sim_info.relationship_tracker.create_relationship(clone_sim_info.sim_id) source_sim_info.relationship_tracker.add_relationship_score(clone_sim_info.sim_id, 1) self._ensure_parental_lineage_exists(source_sim_info, clone_sim_info) services.sim_info_manager().set_default_genealogy(sim_infos=(clone_sim_info,)) clone_sim_info.set_default_data() clone_sim_info.save_sim() household.save_data() if not household.is_active_household: clone_sim_info.request_lod(SimInfoLODLevel.BASE) clone_sim_info.resend_physical_attributes() clone_sim_info.relationship_tracker.clean_and_send_remaining_relationship_info() return clone_sim_info def do_pre_spawn_behavior(self, sim_info, resolver, household): pass def get_sim_infos_and_positions(self, resolver, household): use_fgl = False sim_info = resolver.get_participant(self.participant) clone_sim_info = self._create_clone_sim_info(sim_info, resolver, household) if clone_sim_info is None: return () position, location = (None, None) spawning_object = self._get_spawning_object(resolver) if spawning_object is not None: position, location = self._get_position_and_location(spawning_object, resolver) use_fgl = self.force_fgl or position is None return ((clone_sim_info, position, location, use_fgl),) def do_post_spawn_behavior(self, sim_info, resolver, client_manager): super().do_post_spawn_behavior(sim_info, resolver, client_manager) sim_info.commodity_tracker.set_all_commodities_to_best_value(visible_only=True) class _SimFilterSimInfoSource(_SlotSpawningSimInfoSource): FACTORY_TUNABLES = {'filter': TunableSimFilter.TunableReference(description='\n Sim filter that is used to create or find a Sim that matches\n this filter request.\n ')} def get_sim_filter_gsi_name(self): return str(self) def get_sim_infos_and_positions(self, resolver, household): use_fgl = True sim_info = resolver.get_participant(self.participant) filter_result = services.sim_filter_service().submit_matching_filter(sim_filter=(self.filter), requesting_sim_info=sim_info, allow_yielding=False, gsi_source_fn=(self.get_sim_filter_gsi_name)) if not filter_result: return () position, location = (None, None) spawning_object = self._get_spawning_object(resolver) if spawning_object is not None: position, location = self._get_position_and_location(spawning_object, resolver) use_fgl = position is None return ((filter_result[0].sim_info, position, location, use_fgl),) class _SimTemplateSimInfoSource(_SlotSpawningSimInfoSource): FACTORY_TUNABLES = {'template': TunableSimTemplate.TunableReference(description='\n The template to use.\n ')} def get_sim_infos_and_positions(self, resolver, household): sim_creator = self.template.sim_creator sim_info_list, _ = SimSpawner.create_sim_infos((sim_creator,), sim_name_type=(sim_creator.sim_name_type), household=household) self.template.add_template_data_to_sim((sim_info_list[0]), sim_creator=sim_creator) position, location = (None, None) spawning_object = self._get_spawning_object(resolver) if spawning_object is not None: position, location = self._get_position_and_location(spawning_object, resolver) use_fgl = position is None return ((sim_info_list[0], position, location, use_fgl),) class _GenalogySetAsChild(HasTunableSingletonFactory): def __call__(self, actor_sim_info, created_sim_info): created_sim_info.last_name = SimSpawner.get_last_name(actor_sim_info.last_name, created_sim_info.gender, created_sim_info.species) parent_a = actor_sim_info parent_b = services.sim_info_manager().get(parent_a.spouse_sim_id) created_sim_info.relationship_tracker.destroy_all_relationships() for relation in FamilyRelationshipIndex: relation_id = created_sim_info.get_relation(relation) relation_info = services.sim_info_manager().get(relation_id) if relation_info is not None: created_sim_info.genealogy.remove_family_link(relation) family_relation = relation_info.genealogy.get_family_relationship_bit(created_sim_info.sim_id) relation_info.genealogy.clear_family_relation(family_relation) relation_info.relationship_tracker.destroy_relationship(created_sim_info.sim_id) created_sim_info.genealogy.clear_family_relation(relation) PregnancyTracker.initialize_sim_info(created_sim_info, parent_a, parent_b) FACTORY_TUNABLES = {'sim_info_source':TunableVariant(description='\n The source of the sim_info and position data for the sims to be\n created.\n ', targeted=_TargetedObjectResurrection.TunableFactory(), mass_object=_MassObjectResurrection.TunableFactory(), clone_a_sim=_CloneSimInfoSource.TunableFactory(), sim_filter=_SimFilterSimInfoSource.TunableFactory(), sim_template=_SimTemplateSimInfoSource.TunableFactory(), default='targeted'), 'household_option':TunableVariant(description='\n The household that the created sim should be put into.\n ', active_household=_ActiveHouseholdFactory(), participant_household=_ParticipantHouseholdFactory(), no_household=_NoHousheoldFactory(), hidden_household=_HiddenHouseholdFactory(), default='participant_household'), 'spawn_action':TunableSpawnActionVariant(description='\n Define the methods to show the Sim after spawning on the lot. This\n defaults to fading the Sim in, but can be a specific interaction or\n an animation.\n '), 'relationship_bits_to_add':TunableList(description='\n A list of relationship bits to add between the source sim\n and the created sim.\n ', tunable=TunableReference(manager=(services.get_instance_manager(sims4.resources.Types.RELATIONSHIP_BIT)))), 'set_summoning_purpose':OptionalTunable(description="\n If enabled this will trigger the summon NPC situation depending\n on the summoning purpose type set. This should be tuned when\n we create Sims and don't add them into the active household.\n ", tunable=TunableEnumEntry(description='\n The purpose that is used to summon the sim to the lot. \n Defined in venue tuning.\n ', tunable_type=NPCSummoningPurpose, default=(NPCSummoningPurpose.DEFAULT))), 'set_genealogy':TunableVariant(description='\n Genealogy option to set on the created Sim. \n Example: Setting a child of a family.\n ', set_as_child=_GenalogySetAsChild.TunableFactory(), locked_args={'no_action': None}, default='no_action'), 'pre_spawn_loot':TunableList(description='\n List of loot actions to apply to the created sim info before it is\n spawned.\n ', tunable=TunableReference(manager=(services.get_instance_manager(sims4.resources.Types.ACTION)), class_restrictions=('LootActions', )))} def _apply_relationship_bits(self, actor_sim_info, created_sim_info): for rel_bit in self.relationship_bits_to_add: actor_sim_info.relationship_tracker.add_relationship_bit((created_sim_info.sim_id), rel_bit, force_add=True) def _do_behavior(self): resolver = self.interaction.get_resolver() target_participant = resolver.get_participant(self.sim_info_source.participant) household = self.household_option(self.interaction) client_manager = services.client_manager() for sim_info, position, location, use_fgl in self.sim_info_source.get_sim_infos_and_positions(resolver, household): if target_participant is not None: self._apply_relationship_bits(target_participant, sim_info) else: single_sim_resolver = SingleSimResolver(sim_info) for loot in self.pre_spawn_loot: loot.apply_to_resolver(single_sim_resolver) self.sim_info_source.do_pre_spawn_behavior(sim_info, resolver, household) SimSpawner.spawn_sim(sim_info, position, spawn_action=(self.spawn_action), sim_location=location, use_fgl=use_fgl) if self.set_summoning_purpose is not None: services.current_zone().venue_service.active_venue.summon_npcs((sim_info,), self.set_summoning_purpose) if self.set_genealogy is not None and target_participant is not None: self.set_genealogy(target_participant, sim_info) self.sim_info_source.do_post_spawn_behavior(sim_info, resolver, client_manager) return True
58.927875
452
0.673139
from animation.animation_utils import flush_all_animations from carry.carry_elements import enter_carry_while_holding from element_utils import build_critical_section from event_testing.resolver import SingleSimResolver from filters.sim_template import TunableSimTemplate from filters.tunable import TunableSimFilter from interactions import ParticipantType, ParticipantTypeActorTargetSim, ParticipantTypeSingleSim, ParticipantTypeSingle from interactions.interaction_finisher import FinishingType from interactions.utils.interaction_elements import XevtTriggeredElement from objects import VisibilityState from objects.object_creation import ObjectCreationMixin from objects.slots import RuntimeSlot from sims.genealogy_tracker import genealogy_caching, FamilyRelationshipIndex from sims.pregnancy.pregnancy_tracker import PregnancyTracker from sims.sim_info_lod import SimInfoLODLevel from sims.sim_spawner import SimSpawner, SimCreator from sims4.tuning.geometric import TunableDistanceSquared from sims4.tuning.tunable import TunableList, OptionalTunable, Tunable, TunableEnumEntry, TunableVariant, TunableFactory, TunableReference, HasTunableSingletonFactory, AutoFactoryInit from singletons import EMPTY_SET, DEFAULT from tag import Tag from venues.venue_constants import NPCSummoningPurpose from world.spawn_actions import TunableSpawnActionVariant import element_utils, id_generator, interactions, services, sims.ghost, sims4.log, sims4.math, sims4.telemetry, telemetry_helper logger = sims4.log.Logger('Creation') TELEMETRY_GROUP_OBJECT = 'OBJC' TELEMETRY_HOOK_OBJECT_CREATE_BSCEXTRA = 'CRBE' TELEMETRY_FIELD_OBJECT_INTERACTION = 'intr' TELEMETRY_FIELD_OBJECT_DEFINITION = 'objc' writer = sims4.telemetry.TelemetryWriter(TELEMETRY_GROUP_OBJECT) class ObjectCreationElement(XevtTriggeredElement, ObjectCreationMixin): FACTORY_TUNABLES = {'cancel_on_destroy':Tunable(description='\n If checked, the interaction will be canceled if object is destroyed\n due to placement failure or if destroy on placement failure is\n unchecked and the fallback fails.\n ', tunable_type=bool, default=True), 'transient':Tunable(description='\n If checked, the created object will be destroyed when the interaction ends.\n ', tunable_type=bool, default=False), 'set_to_invisible':Tunable(description='\n If checked, the created object will be set to invisible when the \n interaction ends.\n ', tunable_type=bool, default=False)} def __init__(self, interaction, *args, sequence=(), **kwargs): (super().__init__)(interaction, *args, sequence=sequence, **kwargs) self._definition_cache = None self._placement_failed = False self.initialize_helper(interaction.get_resolver()) if self.transient: self.require_claim = True @property def definition(self): if self._definition_cache is None: self._definition_cache = super().definition return self._definition_cache @property def placement_failed(self): return self._placement_failed def create_object_in_sequence(self): self._place_object(self._object_helper.object) if self._placement_failed: if self.cancel_on_destroy: self.interaction.cancel((FinishingType.FAILED_TESTS), cancel_reason_msg='Cannot place object') return False return True if not self.transient: self._object_helper.claim() if self.set_to_invisible: self._object_helper.object.visibility = VisibilityState(False) with telemetry_helper.begin_hook(writer, TELEMETRY_HOOK_OBJECT_CREATE_BSCEXTRA) as (hook): hook.write_enum(TELEMETRY_FIELD_OBJECT_INTERACTION, self.interaction.guid64) hook.write_guid(TELEMETRY_FIELD_OBJECT_DEFINITION, self._object_helper.object.definition.id) return True def _setup_created_object(self, created_object): self.interaction.object_create_helper = self._object_helper super()._setup_created_object(created_object) def _place_object(self, created_object): place_object = super()._place_object(created_object) if not place_object: self._placement_failed = True return place_object def _build_outer_elements(self, sequence): def set_carry_target(_): self.interaction.track = DEFAULT self.interaction.map_create_target(self.interaction.created_target) def enter_carry(timeline): result = yield from element_utils.run_child(timeline, enter_carry_while_holding((self.interaction), obj=(self.interaction.created_target), carry_track_override=(self.location.carry_track_override), owning_affordance=None, sequence=(build_critical_section(sequence, flush_all_animations)))) return result if False: yield None location_type = getattr(self.location, 'location', None) if location_type == self.CARRY: return self._object_helper.create(set_carry_target, enter_carry) return self._object_helper.create(sequence) def _do_behavior(self): self.create_object_in_sequence() class SimCreationElement(XevtTriggeredElement): class _ActiveHouseholdFactory(TunableFactory): @staticmethod def factory(_): return services.active_household() FACTORY_TYPE = factory class _ParticipantHouseholdFactory(TunableFactory): @staticmethod def factory(interaction, participant): sim = interaction.get_participant(participant) if sim is None: logger.error('_ParticipantHouseholdFactory: {} does not have participant {}', interaction, participant, owner='jjacobson') return return sim.household FACTORY_TYPE = factory def __init__(self, *args, **kwargs): (super().__init__)(participant=TunableEnumEntry(description='\n The participant that will have their household used to put the\n sim into.\n ', tunable_type=ParticipantTypeActorTargetSim, default=(ParticipantTypeActorTargetSim.Actor)), **kwargs) class _NoHousheoldFactory(TunableFactory): @staticmethod def factory(_): pass FACTORY_TYPE = factory class _HiddenHouseholdFactory(TunableFactory): @staticmethod def factory(_): household = services.household_manager().create_household(services.get_first_client().account) household.set_to_hidden(family_funds=0) return household FACTORY_TYPE = factory class _BaseSimInfoSource(HasTunableSingletonFactory, AutoFactoryInit): def get_sim_infos_and_positions(self, resolver): raise NotImplementedError('Attempting to use the _BaseSimInfoSource base class, use sub-classes instead.') def _try_add_sim_info_to_household(self, sim_info, resolver, household, skip_household_check=False): if household is not None: if skip_household_check or household is not sim_info.household: if not household.can_add_sim_info(sim_info): logger.warn('create_sim_from_sim_info element on the interaction: {} could not add a new sim to the tuned household.', resolver.interaction) return False if sim_info.household is not household: sim_info.household.remove_sim_info(sim_info) household.add_sim_info_to_household(sim_info) return True def do_pre_spawn_behavior(self, sim_info, resolver, household): self._try_add_sim_info_to_household(sim_info, resolver, household) def do_post_spawn_behavior(self, sim_info, resolver, client_manager): client = client_manager.get_client_by_household_id(sim_info.household_id) if client is not None: client.add_selectable_sim_info(sim_info) class _TargetedObjectResurrection(_BaseSimInfoSource): FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant of the interaction against whom any relationship\n and genealogy tunables are applied.\n ', tunable_type=ParticipantType, default=ParticipantType.Actor), 'sim_info_subject':TunableEnumEntry(description='\n The subject from which the Sim Info used to create the new Sim\n should be fetched.\n ', tunable_type=ParticipantType, default=ParticipantType.Object), 'resurrect':Tunable(description='\n If checked, all Ghost traits are removed from the created Sim\n and its death type is cleared.\n \n If unchecked, this is a simple spawn operation.\n ', tunable_type=bool, default=True)} def get_sim_infos_and_positions(self, resolver, household): use_fgl = True stored_sim_info_object = resolver.get_participant(self.sim_info_subject) if stored_sim_info_object is None: return () sim_info = stored_sim_info_object.get_stored_sim_info() if sim_info is None: return () return ( ( sim_info, stored_sim_info_object.position, None, use_fgl),) def do_pre_spawn_behavior(self, sim_info, resolver, household): super().do_pre_spawn_behavior(sim_info, resolver, household) if self.resurrect: sims.ghost.Ghost.remove_ghost_from_sim(sim_info) class _MassObjectResurrection(_BaseSimInfoSource): FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant of the interaction that will have sims resurrected\n around their position.\n ', tunable_type=ParticipantType, default=ParticipantType.Actor), 'radius':TunableDistanceSquared(description='\n The distance around a participant that will resurrect all of the\n dead sim objects.\n ', default=1), 'tag':TunableEnumEntry(description='\n Tag the delineates an object that we want to resurrect sims\n from.\n ', tunable_type=Tag, default=Tag.INVALID)} def get_sim_infos_and_positions(self, resolver, household): use_fgl = True sim_infos_and_positions = [] participant = resolver.get_participant(self.participant) position = participant.position for obj in services.object_manager().get_objects_with_tag_gen(self.tag): obj_position = obj.position distance_from_pos = obj_position - position if distance_from_pos.magnitude_squared() > self.radius: continue sim_info = obj.get_stored_sim_info() if sim_info is None: continue sim_infos_and_positions.append((sim_info, obj_position, None, use_fgl)) return tuple(sim_infos_and_positions) def do_pre_spawn_behavior(self, sim_info, resolver, household): super().do_pre_spawn_behavior(sim_info, resolver, household) sims.ghost.Ghost.remove_ghost_from_sim(sim_info) class _SlotSpawningSimInfoSource(_BaseSimInfoSource): class _SlotByName(HasTunableSingletonFactory, AutoFactoryInit): FACTORY_TUNABLES = {'slot_name': Tunable(description='\n The exact name of a slot on the parent object.\n ', tunable_type=str, default='_ctnm_')} def get_slot_type_and_hash(self): return ( None, sims4.hash_util.hash32(self.slot_name)) class _SlotByType(HasTunableSingletonFactory, AutoFactoryInit): FACTORY_TUNABLES = {'slot_type': TunableReference(description='\n A particular slot type in which the should spawn.\n ', manager=(services.get_instance_manager(sims4.resources.Types.SLOT_TYPE)))} def get_slot_type_and_hash(self): return ( self.slot_type, None) FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant that is a sim that will be cloned\n Note: MUST be a sim. Use create object - clone object for non-sim objects.\n ', tunable_type=ParticipantTypeSingleSim, default=ParticipantTypeSingleSim.Actor), 'sim_spawn_slot':TunableVariant(description="\n The slot on the parent object where the sim should spawn. This\n may be either the exact name of a bone on the parent object or a\n slot type, in which case the first empty slot of the specified type\n will be used. If None is chosen, then the sim will at or near\n the interaction target's location.\n ", by_name=_SlotByName.TunableFactory(), by_type=_SlotByType.TunableFactory()), 'spawn_location_participant':TunableEnumEntry(description='\n The participant used for finding where to spawn the Sim. Typically you want to leave this as object.\n \n Special cases include:\n - For self-interactions, Object will resolve to None. This can be set to Actor if you want to spawn\n near the Sim running the interaction.\n ', tunable_type=ParticipantTypeSingle, default=ParticipantTypeSingle.Object)} def __init__(self, sim_spawn_slot=None, **kwargs): (super().__init__)(sim_spawn_slot=sim_spawn_slot, **kwargs) self._slot_type = None self._bone_name_hash = None if sim_spawn_slot is not None: self._slot_type, self._bone_name_hash = sim_spawn_slot.get_slot_type_and_hash() def _get_position_and_location(self, spawning_object, resolver): position, location = (None, None) if self._slot_type is not None: for runtime_slot in spawning_object.get_runtime_slots_gen(slot_types={self._slot_type}, bone_name_hash=(self._bone_name_hash)): location = runtime_slot.location else: if self._bone_name_hash is not None: runtime_slot = RuntimeSlot(spawning_object, self._bone_name_hash, EMPTY_SET) if runtime_slot is not None: location = runtime_slot.location else: location = spawning_object.location if location is not None: location = sims4.math.Location((location.world_transform), (spawning_object.routing_surface), slot_hash=(location.slot_hash)) position = location.transform.translation return (position, location) def _get_spawning_object(self, resolver): spawning_object = resolver.get_participant(self.spawn_location_participant) if spawning_object.is_sim: spawning_object = spawning_object.get_sim_instance() return spawning_object class _CloneSimInfoSource(_SlotSpawningSimInfoSource): FACTORY_TUNABLES = {'force_fgl': Tunable(description="\n Normally, FGL will only be invoked if no spawning position is found. Use this tunable to force\n FGL to run. e.g. Cloning spell uses caster Sim's position as a spawning position. In that case,\n we still want to force FGL so the clone spawns near that Sim rather than directly on top of the Sim. \n ", tunable_type=bool, default=False)} def _ensure_parental_lineage_exists(self, source_sim_info, clone_sim_info): with genealogy_caching(): if any(source_sim_info.genealogy.get_parent_sim_ids_gen()): return mom_id = id_generator.generate_object_id() source_sim_info.genealogy.set_family_relation(FamilyRelationshipIndex.MOTHER, mom_id) clone_sim_info.genealogy.set_family_relation(FamilyRelationshipIndex.MOTHER, mom_id) sim_info_manager = services.sim_info_manager() for child_sim_id in source_sim_info.genealogy.get_children_sim_ids_gen(): child_sim_info = sim_info_manager.get(child_sim_id) if child_sim_info is not None: grandparent_relation = FamilyRelationshipIndex.MOTHERS_MOM if source_sim_info.is_female else FamilyRelationshipIndex.FATHERS_MOM child_sim_info.genealogy.set_family_relation(grandparent_relation, mom_id) def _create_clone_sim_info(self, source_sim_info, resolver, household): sim_creator = SimCreator(gender=(source_sim_info.gender), age=(source_sim_info.age), first_name=(SimSpawner.get_random_first_name(source_sim_info.gender, source_sim_info.species)), last_name=(source_sim_info._base.last_name), traits=(source_sim_info.trait_tracker.equipped_traits)) sim_info_list, _ = SimSpawner.create_sim_infos((sim_creator,), household=household, account=(source_sim_info.account), generate_deterministic_sim=True, creation_source='cloning', skip_adding_to_household=True) clone_sim_info = sim_info_list[0] source_sim_proto = source_sim_info.save_sim(for_cloning=True) clone_sim_id = clone_sim_info.sim_id clone_first_name = clone_sim_info._base.first_name clone_last_name = clone_sim_info._base.last_name clone_breed_name = clone_sim_info._base.breed_name clone_first_name_key = clone_sim_info._base.first_name_key clone_last_name_key = clone_sim_info._base.last_name_key clone_full_name_key = clone_sim_info._base.full_name_key clone_breed_name_key = clone_sim_info._base.breed_name_key clone_sim_info.load_sim_info(source_sim_proto, is_clone=True, default_lod=(SimInfoLODLevel.FULL)) clone_sim_info.sim_id = clone_sim_id clone_sim_info._base.first_name = clone_first_name clone_sim_info._base.last_name = clone_last_name clone_sim_info._base.breed_name = clone_breed_name clone_sim_info._base.first_name_key = clone_first_name_key clone_sim_info._base.last_name_key = clone_last_name_key clone_sim_info._base.full_name_key = clone_full_name_key clone_sim_info._base.breed_name_key = clone_breed_name_key clone_sim_info._household_id = household.id if not self._try_add_sim_info_to_household(clone_sim_info, resolver, household, skip_household_check=True): return source_trait_tracker = source_sim_info.trait_tracker clone_trait_tracker = clone_sim_info.trait_tracker for trait in clone_trait_tracker.personality_traits: if not source_trait_tracker.has_trait(trait): clone_sim_info.remove_trait(trait) for trait in clone_trait_tracker.gender_option_traits: if not source_trait_tracker.has_trait(trait): clone_sim_info.remove_trait(trait) correct_aspiration_trait = clone_sim_info.primary_aspiration.primary_trait for trait in tuple(clone_trait_tracker.aspiration_traits): if trait is not correct_aspiration_trait: clone_sim_info.remove_trait(trait) source_sim_info.relationship_tracker.create_relationship(clone_sim_info.sim_id) source_sim_info.relationship_tracker.add_relationship_score(clone_sim_info.sim_id, 1) self._ensure_parental_lineage_exists(source_sim_info, clone_sim_info) services.sim_info_manager().set_default_genealogy(sim_infos=(clone_sim_info,)) clone_sim_info.set_default_data() clone_sim_info.save_sim() household.save_data() if not household.is_active_household: clone_sim_info.request_lod(SimInfoLODLevel.BASE) clone_sim_info.resend_physical_attributes() clone_sim_info.relationship_tracker.clean_and_send_remaining_relationship_info() return clone_sim_info def do_pre_spawn_behavior(self, sim_info, resolver, household): pass def get_sim_infos_and_positions(self, resolver, household): use_fgl = False sim_info = resolver.get_participant(self.participant) clone_sim_info = self._create_clone_sim_info(sim_info, resolver, household) if clone_sim_info is None: return () position, location = (None, None) spawning_object = self._get_spawning_object(resolver) if spawning_object is not None: position, location = self._get_position_and_location(spawning_object, resolver) use_fgl = self.force_fgl or position is None return ((clone_sim_info, position, location, use_fgl),) def do_post_spawn_behavior(self, sim_info, resolver, client_manager): super().do_post_spawn_behavior(sim_info, resolver, client_manager) sim_info.commodity_tracker.set_all_commodities_to_best_value(visible_only=True) class _SimFilterSimInfoSource(_SlotSpawningSimInfoSource): FACTORY_TUNABLES = {'filter': TunableSimFilter.TunableReference(description='\n Sim filter that is used to create or find a Sim that matches\n this filter request.\n ')} def get_sim_filter_gsi_name(self): return str(self) def get_sim_infos_and_positions(self, resolver, household): use_fgl = True sim_info = resolver.get_participant(self.participant) filter_result = services.sim_filter_service().submit_matching_filter(sim_filter=(self.filter), requesting_sim_info=sim_info, allow_yielding=False, gsi_source_fn=(self.get_sim_filter_gsi_name)) if not filter_result: return () position, location = (None, None) spawning_object = self._get_spawning_object(resolver) if spawning_object is not None: position, location = self._get_position_and_location(spawning_object, resolver) use_fgl = position is None return ((filter_result[0].sim_info, position, location, use_fgl),) class _SimTemplateSimInfoSource(_SlotSpawningSimInfoSource): FACTORY_TUNABLES = {'template': TunableSimTemplate.TunableReference(description='\n The template to use.\n ')} def get_sim_infos_and_positions(self, resolver, household): sim_creator = self.template.sim_creator sim_info_list, _ = SimSpawner.create_sim_infos((sim_creator,), sim_name_type=(sim_creator.sim_name_type), household=household) self.template.add_template_data_to_sim((sim_info_list[0]), sim_creator=sim_creator) position, location = (None, None) spawning_object = self._get_spawning_object(resolver) if spawning_object is not None: position, location = self._get_position_and_location(spawning_object, resolver) use_fgl = position is None return ((sim_info_list[0], position, location, use_fgl),) class _GenalogySetAsChild(HasTunableSingletonFactory): def __call__(self, actor_sim_info, created_sim_info): created_sim_info.last_name = SimSpawner.get_last_name(actor_sim_info.last_name, created_sim_info.gender, created_sim_info.species) parent_a = actor_sim_info parent_b = services.sim_info_manager().get(parent_a.spouse_sim_id) created_sim_info.relationship_tracker.destroy_all_relationships() for relation in FamilyRelationshipIndex: relation_id = created_sim_info.get_relation(relation) relation_info = services.sim_info_manager().get(relation_id) if relation_info is not None: created_sim_info.genealogy.remove_family_link(relation) family_relation = relation_info.genealogy.get_family_relationship_bit(created_sim_info.sim_id) relation_info.genealogy.clear_family_relation(family_relation) relation_info.relationship_tracker.destroy_relationship(created_sim_info.sim_id) created_sim_info.genealogy.clear_family_relation(relation) PregnancyTracker.initialize_sim_info(created_sim_info, parent_a, parent_b) FACTORY_TUNABLES = {'sim_info_source':TunableVariant(description='\n The source of the sim_info and position data for the sims to be\n created.\n ', targeted=_TargetedObjectResurrection.TunableFactory(), mass_object=_MassObjectResurrection.TunableFactory(), clone_a_sim=_CloneSimInfoSource.TunableFactory(), sim_filter=_SimFilterSimInfoSource.TunableFactory(), sim_template=_SimTemplateSimInfoSource.TunableFactory(), default='targeted'), 'household_option':TunableVariant(description='\n The household that the created sim should be put into.\n ', active_household=_ActiveHouseholdFactory(), participant_household=_ParticipantHouseholdFactory(), no_household=_NoHousheoldFactory(), hidden_household=_HiddenHouseholdFactory(), default='participant_household'), 'spawn_action':TunableSpawnActionVariant(description='\n Define the methods to show the Sim after spawning on the lot. This\n defaults to fading the Sim in, but can be a specific interaction or\n an animation.\n '), 'relationship_bits_to_add':TunableList(description='\n A list of relationship bits to add between the source sim\n and the created sim.\n ', tunable=TunableReference(manager=(services.get_instance_manager(sims4.resources.Types.RELATIONSHIP_BIT)))), 'set_summoning_purpose':OptionalTunable(description="\n If enabled this will trigger the summon NPC situation depending\n on the summoning purpose type set. This should be tuned when\n we create Sims and don't add them into the active household.\n ", tunable=TunableEnumEntry(description='\n The purpose that is used to summon the sim to the lot. \n Defined in venue tuning.\n ', tunable_type=NPCSummoningPurpose, default=(NPCSummoningPurpose.DEFAULT))), 'set_genealogy':TunableVariant(description='\n Genealogy option to set on the created Sim. \n Example: Setting a child of a family.\n ', set_as_child=_GenalogySetAsChild.TunableFactory(), locked_args={'no_action': None}, default='no_action'), 'pre_spawn_loot':TunableList(description='\n List of loot actions to apply to the created sim info before it is\n spawned.\n ', tunable=TunableReference(manager=(services.get_instance_manager(sims4.resources.Types.ACTION)), class_restrictions=('LootActions', )))} def _apply_relationship_bits(self, actor_sim_info, created_sim_info): for rel_bit in self.relationship_bits_to_add: actor_sim_info.relationship_tracker.add_relationship_bit((created_sim_info.sim_id), rel_bit, force_add=True) def _do_behavior(self): resolver = self.interaction.get_resolver() target_participant = resolver.get_participant(self.sim_info_source.participant) household = self.household_option(self.interaction) client_manager = services.client_manager() for sim_info, position, location, use_fgl in self.sim_info_source.get_sim_infos_and_positions(resolver, household): if target_participant is not None: self._apply_relationship_bits(target_participant, sim_info) else: single_sim_resolver = SingleSimResolver(sim_info) for loot in self.pre_spawn_loot: loot.apply_to_resolver(single_sim_resolver) self.sim_info_source.do_pre_spawn_behavior(sim_info, resolver, household) SimSpawner.spawn_sim(sim_info, position, spawn_action=(self.spawn_action), sim_location=location, use_fgl=use_fgl) if self.set_summoning_purpose is not None: services.current_zone().venue_service.active_venue.summon_npcs((sim_info,), self.set_summoning_purpose) if self.set_genealogy is not None and target_participant is not None: self.set_genealogy(target_participant, sim_info) self.sim_info_source.do_post_spawn_behavior(sim_info, resolver, client_manager) return True
true
true
f716ac0e3959c71c4d5608a0af8d5faae868b677
93
py
Python
src/bot.py
amirsafiee/template_telegram_bot
2dfaba93de6ff6066a8b2ac64e1ee95be19c1548
[ "MIT" ]
null
null
null
src/bot.py
amirsafiee/template_telegram_bot
2dfaba93de6ff6066a8b2ac64e1ee95be19c1548
[ "MIT" ]
null
null
null
src/bot.py
amirsafiee/template_telegram_bot
2dfaba93de6ff6066a8b2ac64e1ee95be19c1548
[ "MIT" ]
1
2022-01-24T12:59:19.000Z
2022-01-24T12:59:19.000Z
import os import telebot bot = telebot.TeleBot(os.environ['BOT_TOKEN'], parse_mode='HTML')
15.5
65
0.752688
import os import telebot bot = telebot.TeleBot(os.environ['BOT_TOKEN'], parse_mode='HTML')
true
true
f716ac52c89aa1029f08962d2e19db4bbf190274
796
py
Python
util/plaintext.py
seounghwan-oh/homomorphic_encryption
be700505547b81671c37026e55c4eefbd44dcaae
[ "MIT" ]
25
2020-11-06T13:54:33.000Z
2022-03-18T18:53:37.000Z
util/plaintext.py
seounghwan-oh/homomorphic_encryption
be700505547b81671c37026e55c4eefbd44dcaae
[ "MIT" ]
1
2021-04-04T17:49:00.000Z
2021-04-05T13:46:21.000Z
util/plaintext.py
seounghwan-oh/homomorphic_encryption
be700505547b81671c37026e55c4eefbd44dcaae
[ "MIT" ]
6
2021-04-04T17:26:09.000Z
2022-03-28T19:26:29.000Z
"""A module to keep track of a plaintext.""" class Plaintext: """An instance of a plaintext. This is a wrapper class for a plaintext, which consists of one polynomial. Attributes: poly (Polynomial): Plaintext polynomial. scaling_factor (float): Scaling factor. """ def __init__(self, poly, scaling_factor=None): """Sets plaintext to given polynomial. Args: poly (Polynomial): Plaintext polynomial. scaling_factor (float): Scaling factor. """ self.poly = poly self.scaling_factor = scaling_factor def __str__(self): """Represents plaintext as a readable string. Returns: A string which represents the Plaintext. """ return str(self.poly)
25.677419
59
0.614322
class Plaintext: def __init__(self, poly, scaling_factor=None): self.poly = poly self.scaling_factor = scaling_factor def __str__(self): return str(self.poly)
true
true
f716acb54b4962beca238b19ba8258573c3ffe65
766
py
Python
tst/util/chain_utils.py
TST-Group-BE/flax-blockchain
ed850df4f28ef4b6f71c175c8b6d07d27f7b3cd5
[ "Apache-2.0" ]
null
null
null
tst/util/chain_utils.py
TST-Group-BE/flax-blockchain
ed850df4f28ef4b6f71c175c8b6d07d27f7b3cd5
[ "Apache-2.0" ]
null
null
null
tst/util/chain_utils.py
TST-Group-BE/flax-blockchain
ed850df4f28ef4b6f71c175c8b6d07d27f7b3cd5
[ "Apache-2.0" ]
null
null
null
from typing import List from tst.types.blockchain_format.coin import Coin from tst.types.blockchain_format.program import SerializedProgram from tst.types.blockchain_format.sized_bytes import bytes32 from tst.util.condition_tools import ( conditions_dict_for_solution, created_outputs_for_conditions_dict, ) def additions_for_solution( coin_name: bytes32, puzzle_reveal: SerializedProgram, solution: SerializedProgram, max_cost: int ) -> List[Coin]: """ Checks the conditions created by CoinSolution and returns the list of all coins created """ err, dic, cost = conditions_dict_for_solution(puzzle_reveal, solution, max_cost) if err or dic is None: return [] return created_outputs_for_conditions_dict(dic, coin_name)
34.818182
100
0.784595
from typing import List from tst.types.blockchain_format.coin import Coin from tst.types.blockchain_format.program import SerializedProgram from tst.types.blockchain_format.sized_bytes import bytes32 from tst.util.condition_tools import ( conditions_dict_for_solution, created_outputs_for_conditions_dict, ) def additions_for_solution( coin_name: bytes32, puzzle_reveal: SerializedProgram, solution: SerializedProgram, max_cost: int ) -> List[Coin]: err, dic, cost = conditions_dict_for_solution(puzzle_reveal, solution, max_cost) if err or dic is None: return [] return created_outputs_for_conditions_dict(dic, coin_name)
true
true
f716ada0abc16a0476ced0d0b57cf8389076e57f
7,206
py
Python
ABA_PY/CHK_2D_postp_part_A_v4.4.py
SunilAnandatheertha/ABAPYMAT
48d4d178de38c1f3c4510ad7f06fe1647ae6227c
[ "BSD-3-Clause" ]
1
2021-01-13T14:06:34.000Z
2021-01-13T14:06:34.000Z
ABA_PY/CHK_2D_postp_part_A_v4.4.py
SunilAnandatheertha/ABAPYMAT
48d4d178de38c1f3c4510ad7f06fe1647ae6227c
[ "BSD-3-Clause" ]
5
2020-12-21T14:51:57.000Z
2021-01-21T13:42:44.000Z
ABA_PY/CHK_2D_postp_part_A_v4.4.py
SunilAnandatheertha/ABAPYMAT-PXTAL-2D
48d4d178de38c1f3c4510ad7f06fe1647ae6227c
[ "BSD-3-Clause" ]
1
2022-02-25T20:03:18.000Z
2022-02-25T20:03:18.000Z
""" COMPLETE DESCRIPTION HERE """ #----------------------------------------------------------------- #1. Seperate this file for calibration models # MAKE THE PYTHON PRE, MATLAB AND PYTHON POST and SPYDER pipelines ready for calibrations # Set up the required folders # Set up the excel file where to store the file numbers and model numbers #2. Seperate this file for residual stress induce model #3. Seperate this file for residual stress induce and relaxation model #----------------------------------------------------------------- # ANYTHING TO AID DEVELOPEMENT GOES HERE # Snippet: to get strain atv centroids and SOLUTION DEPENDENT VARIABLES AT THE CENTROIDAL POSITIONS # Strain = lastFrame.fieldOutputs['LE'].getSubset(region=polyI) # Strain = myOdb.steps['Step-1'].frames[1].fieldOutputs['LE' ].getSubset(region=polyI, position=CENTROID) # p01 = myOdb.steps['Step-1'].frames[1].fieldOutputs['SDV7' ].getSubset(region=polyI, position=CENTROID) #----------------------------------------------------------------- # Compatibility listing # 1. CPS4, CPS4R #----------------------------------------------------------------- from abaqus import * from abaqusConstants import * from caeModules import * from driverUtils import executeOnCaeStartup import os import visualization import time import numpy as np #----------------------------------------------------------------- executeOnCaeStartup() Mdb() #----------------------------------------------------------------- # model and basic element dimensions # GET USER REQUIREMENTS FOR UPPER CAPPING AND LOWER CAPPING THE CONTOUR DISPLAY LEGEND LEVELS from abaqus import getInputs fields = (('Model_origin_x:', '0'), ('Model_origin_y:', '0'), ('Model_enddim_x:', '100'), ('Model_enddim_y:', '6'), ('Model_enddim_z:', '1'), ) Model_origin_x, Model_origin_y, Model_enddim_x,\ Model_enddim_y, Model_enddim_z, \ = getInputs(fields = fields, label = 'Specify Checkerboard model dimsnions:', dialogTitle = 'Keep origin at (0, 0) for now', ) Model_origin_x = float(Model_origin_x) Model_origin_y = float(Model_origin_y) Model_enddim_x = float(Model_enddim_x) Model_enddim_y = float(Model_enddim_y) Model_enddim_z = float(Model_enddim_z) del fields #----------------------------------------------------------------- # Acquire level 0 solution metadata odbinfo = (('Location', 'B'), ('Calibration iteration number(as: 00n, 0mn, mno', '009'), ('ODB_FileName (enter without the .odb):', 'Loc_B_009'), ('# of frames:', '16'), ('# of grains along x:', '24'), ('# of grains along y:', '4'), ('Element factor used:', '1'), ('SolutionInstance_metadata_Num (keep unchanged for now)', '1'), ('SolutionInstance_folder_path', 'C:\\Users\\anandats\\OneDrive - Coventry University\\coventry-thesis\\Chapter7\\ABAQUS_CAL_DATA_FILES\\LocationB\\'), ) Cal_Location, Calib_Iteration_Num, This_ODB_FILENAME, NumOfFrames, NumGrains_X,\ NumGrains_Y, Elem_Factor_Used, SolInst_metadata_Num, SolInst_folder_path\ = getInputs(fields = odbinfo, label = 'Specify details of solution file', dialogTitle = 'Level 0 solution metadata', ) del odbinfo MODEL_INFORMATION = {1:['ODBfilename', This_ODB_FILENAME, 'frames', NumOfFrames, 'Ngx', NumGrains_X, 'Ngy', NumGrains_Y, 'ElemFacUSED', Elem_Factor_Used], 2:[SolInst_folder_path],} # only enter odd number IDs for ODB_ID, i.e. only line number containing meta-data and not folder address ODB_ID = 1 ODB_FileName = MODEL_INFORMATION[ODB_ID][1] TotalNumFrames = int(MODEL_INFORMATION[ODB_ID][3]) NumPartitions_x = int(MODEL_INFORMATION[ODB_ID][5]) NumPartitions_y = int(MODEL_INFORMATION[ODB_ID][7]) factorUSED = float(MODEL_INFORMATION[ODB_ID][9]) ElementSize = (Model_enddim_y/NumPartitions_y)/factorUSED # frame incerements needed # texture id value # Elements per grain value # elemebnt type value frincr = 1 TEXIDVALUE = '02' EPGValue = '003' ElementType = 'CPS4' #----------------------------------------------------------------- # generate variable values needed to re-create element set names Num_DatumPlanes_x = NumPartitions_x - 1 Num_DatumPlanes_y = NumPartitions_y - 1 #-------------------------------------------------------- # should the elemental results at centrouids be extracted? If extracted, they will be written to file Extract_S11_ELCEN = 0 Extract_S22_ELCEN = 0 Extract_S12_ELCEN = 0 #-------------------------------------------------------- # defining filenames import random RandomNumber_START_MATLAB_OUTPUT = str(random.randint(10, 99)) RandomNumber_END_MATLAB_OUTPUT = str(random.randint(10, 99)) #-------------------------------------------------------- # GET USER REQUIREMENTS FOR UPPER CAPPING AND LOWER CAPPING THE CONTOUR DISPLAY LEGEND LEVELS from abaqus import getInputs fields = (('S11_contour_label_max_MPa:', '+0500'), ('S11_contour_label_min_MPa:', '+0000'), ('S22_contour_label_max_MPa:', '+0100'), ('S22_contour_label_min_MPa:', '-0100'), ('S12_contour_label_max_MPa:', '+0050'), ('S12_contour_label_min_MPa:', '-0050'), ) S11_contour_label_max_MPa, S11_contour_label_min_MPa,\ S22_contour_label_max_MPa, S22_contour_label_min_MPa,\ S12_contour_label_max_MPa, S12_contour_label_min_MPa, \ = getInputs(fields = fields, label = 'Specify UPPER AND LOWER CAPPING LEVELS FOR CONTOUR LEGEND:', dialogTitle = 'Legend limits: STRESS', ) S11_contour_label_max_MPa = float(S11_contour_label_max_MPa) S11_contour_label_min_MPa = float(S11_contour_label_min_MPa) S22_contour_label_max_MPa = float(S22_contour_label_max_MPa) S22_contour_label_min_MPa = float(S22_contour_label_min_MPa) S12_contour_label_max_MPa = float(S12_contour_label_max_MPa) S12_contour_label_min_MPa = float(S12_contour_label_min_MPa) del fields #-------------------------------------------------------- # PRINT FLAGS TO SPECIFY WHTHER IMAGES ARE TO BE PRINTED TO PNG FILES fields = (('Print_S11_Contours_File:', '0'), ('Print_S22_Contours_File:', '0'), ('Print_S12_Contours_File:', '0'), ) Print_S11_Contours_File, Print_S22_Contours_File,\ Print_S12_Contours_File,\ = getInputs(fields = fields, label = 'Enter 1(print) and 0(dont print)', dialogTitle = 'Set print to .png file requirements', ) Print_S11_Contours_File = float(Print_S11_Contours_File) del fields #----------------------------------------------------------------- # VIEWPORT - 1 VP_num = 1 VP_name = 'Viewport: ' + str(VP_num) #VP_ODB_PathName = 'C:/Temp/CalibrationModels/Cal_100ng/' VP_ODB_PathName = MODEL_INFORMATION[ODB_ID+1][0] #VP_ODB_FileName = ODB_FileName + '.odb' VP_ODB_FileName = MODEL_INFORMATION[ODB_ID][1] VP_ODB_FullPathName = VP_ODB_PathName + VP_ODB_FileName + '.odb' VP_UpGraded_ODB_FullPathName = VP_ODB_PathName + VP_ODB_FileName + '_UpGraded' + '.odb' MVPport = session.Viewport(name = VP_name, origin = (0.0, 0.0), width = 150, height = 100) SESS_VP = session.viewports[VP_name] SESS_VP.makeCurrent() SESS_VP.maximize() SESS_VP.partDisplay.geometryOptions.setValues(referenceRepresentation = ON) SESS_VP.setValues(displayedObject = None) import os.path import odbAccess import visualization import abaqus
44.481481
156
0.664585
from abaqus import * from abaqusConstants import * from caeModules import * from driverUtils import executeOnCaeStartup import os import visualization import time import numpy as np executeOnCaeStartup() Mdb() from abaqus import getInputs fields = (('Model_origin_x:', '0'), ('Model_origin_y:', '0'), ('Model_enddim_x:', '100'), ('Model_enddim_y:', '6'), ('Model_enddim_z:', '1'), ) Model_origin_x, Model_origin_y, Model_enddim_x,\ Model_enddim_y, Model_enddim_z, \ = getInputs(fields = fields, label = 'Specify Checkerboard model dimsnions:', dialogTitle = 'Keep origin at (0, 0) for now', ) Model_origin_x = float(Model_origin_x) Model_origin_y = float(Model_origin_y) Model_enddim_x = float(Model_enddim_x) Model_enddim_y = float(Model_enddim_y) Model_enddim_z = float(Model_enddim_z) del fields odbinfo = (('Location', 'B'), ('Calibration iteration number(as: 00n, 0mn, mno', '009'), ('ODB_FileName (enter without the .odb):', 'Loc_B_009'), ('# of frames:', '16'), ('# of grains along x:', '24'), ('# of grains along y:', '4'), ('Element factor used:', '1'), ('SolutionInstance_metadata_Num (keep unchanged for now)', '1'), ('SolutionInstance_folder_path', 'C:\\Users\\anandats\\OneDrive - Coventry University\\coventry-thesis\\Chapter7\\ABAQUS_CAL_DATA_FILES\\LocationB\\'), ) Cal_Location, Calib_Iteration_Num, This_ODB_FILENAME, NumOfFrames, NumGrains_X,\ NumGrains_Y, Elem_Factor_Used, SolInst_metadata_Num, SolInst_folder_path\ = getInputs(fields = odbinfo, label = 'Specify details of solution file', dialogTitle = 'Level 0 solution metadata', ) del odbinfo MODEL_INFORMATION = {1:['ODBfilename', This_ODB_FILENAME, 'frames', NumOfFrames, 'Ngx', NumGrains_X, 'Ngy', NumGrains_Y, 'ElemFacUSED', Elem_Factor_Used], 2:[SolInst_folder_path],} ODB_ID = 1 ODB_FileName = MODEL_INFORMATION[ODB_ID][1] TotalNumFrames = int(MODEL_INFORMATION[ODB_ID][3]) NumPartitions_x = int(MODEL_INFORMATION[ODB_ID][5]) NumPartitions_y = int(MODEL_INFORMATION[ODB_ID][7]) factorUSED = float(MODEL_INFORMATION[ODB_ID][9]) ElementSize = (Model_enddim_y/NumPartitions_y)/factorUSED frincr = 1 TEXIDVALUE = '02' EPGValue = '003' ElementType = 'CPS4' Num_DatumPlanes_x = NumPartitions_x - 1 Num_DatumPlanes_y = NumPartitions_y - 1 Extract_S11_ELCEN = 0 Extract_S22_ELCEN = 0 Extract_S12_ELCEN = 0 import random RandomNumber_START_MATLAB_OUTPUT = str(random.randint(10, 99)) RandomNumber_END_MATLAB_OUTPUT = str(random.randint(10, 99)) from abaqus import getInputs fields = (('S11_contour_label_max_MPa:', '+0500'), ('S11_contour_label_min_MPa:', '+0000'), ('S22_contour_label_max_MPa:', '+0100'), ('S22_contour_label_min_MPa:', '-0100'), ('S12_contour_label_max_MPa:', '+0050'), ('S12_contour_label_min_MPa:', '-0050'), ) S11_contour_label_max_MPa, S11_contour_label_min_MPa,\ S22_contour_label_max_MPa, S22_contour_label_min_MPa,\ S12_contour_label_max_MPa, S12_contour_label_min_MPa, \ = getInputs(fields = fields, label = 'Specify UPPER AND LOWER CAPPING LEVELS FOR CONTOUR LEGEND:', dialogTitle = 'Legend limits: STRESS', ) S11_contour_label_max_MPa = float(S11_contour_label_max_MPa) S11_contour_label_min_MPa = float(S11_contour_label_min_MPa) S22_contour_label_max_MPa = float(S22_contour_label_max_MPa) S22_contour_label_min_MPa = float(S22_contour_label_min_MPa) S12_contour_label_max_MPa = float(S12_contour_label_max_MPa) S12_contour_label_min_MPa = float(S12_contour_label_min_MPa) del fields fields = (('Print_S11_Contours_File:', '0'), ('Print_S22_Contours_File:', '0'), ('Print_S12_Contours_File:', '0'), ) Print_S11_Contours_File, Print_S22_Contours_File,\ Print_S12_Contours_File,\ = getInputs(fields = fields, label = 'Enter 1(print) and 0(dont print)', dialogTitle = 'Set print to .png file requirements', ) Print_S11_Contours_File = float(Print_S11_Contours_File) del fields VP_num = 1 VP_name = 'Viewport: ' + str(VP_num) VP_ODB_PathName = MODEL_INFORMATION[ODB_ID+1][0] VP_ODB_FileName = MODEL_INFORMATION[ODB_ID][1] VP_ODB_FullPathName = VP_ODB_PathName + VP_ODB_FileName + '.odb' VP_UpGraded_ODB_FullPathName = VP_ODB_PathName + VP_ODB_FileName + '_UpGraded' + '.odb' MVPport = session.Viewport(name = VP_name, origin = (0.0, 0.0), width = 150, height = 100) SESS_VP = session.viewports[VP_name] SESS_VP.makeCurrent() SESS_VP.maximize() SESS_VP.partDisplay.geometryOptions.setValues(referenceRepresentation = ON) SESS_VP.setValues(displayedObject = None) import os.path import odbAccess import visualization import abaqus
true
true
f716adfe3834f0888422f74ed1401389c19dd141
21,995
py
Python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_vpn_connections_operations.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
3
2020-06-23T02:25:27.000Z
2021-09-07T18:48:11.000Z
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_vpn_connections_operations.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
510
2019-07-17T16:11:19.000Z
2021-08-02T08:38:32.000Z
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_vpn_connections_operations.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
5
2019-09-04T12:51:37.000Z
2020-09-16T07:28:40.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class VpnConnectionsOperations: """VpnConnectionsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2018_06_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def get( self, resource_group_name: str, gateway_name: str, connection_name: str, **kwargs ) -> "_models.VpnConnection": """Retrieves the details of a vpn connection. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :param connection_name: The name of the vpn connection. :type connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: VpnConnection, or the result of cls(response) :rtype: ~azure.mgmt.network.v2018_06_01.models.VpnConnection :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-06-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('VpnConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, gateway_name: str, connection_name: str, vpn_connection_parameters: "_models.VpnConnection", **kwargs ) -> "_models.VpnConnection": cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-06-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(vpn_connection_parameters, 'VpnConnection') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('VpnConnection', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('VpnConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, gateway_name: str, connection_name: str, vpn_connection_parameters: "_models.VpnConnection", **kwargs ) -> AsyncLROPoller["_models.VpnConnection"]: """Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :param connection_name: The name of the connection. :type connection_name: str :param vpn_connection_parameters: Parameters supplied to create or Update a VPN Connection. :type vpn_connection_parameters: ~azure.mgmt.network.v2018_06_01.models.VpnConnection :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either VpnConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2018_06_01.models.VpnConnection] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, gateway_name=gateway_name, connection_name=connection_name, vpn_connection_parameters=vpn_connection_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('VpnConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, gateway_name: str, connection_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-06-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore async def begin_delete( self, resource_group_name: str, gateway_name: str, connection_name: str, **kwargs ) -> AsyncLROPoller[None]: """Deletes a vpn connection. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :param connection_name: The name of the connection. :type connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, gateway_name=gateway_name, connection_name=connection_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore def list_by_vpn_gateway( self, resource_group_name: str, gateway_name: str, **kwargs ) -> AsyncIterable["_models.ListVpnConnectionsResult"]: """Retrieves all vpn connections for a particular virtual wan vpn gateway. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListVpnConnectionsResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_06_01.models.ListVpnConnectionsResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnConnectionsResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-06-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_vpn_gateway.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListVpnConnectionsResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize.failsafe_deserialize(_models.Error, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections'} # type: ignore
50.447248
220
0.672926
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class VpnConnectionsOperations: models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def get( self, resource_group_name: str, gateway_name: str, connection_name: str, **kwargs ) -> "_models.VpnConnection": cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-06-01" accept = "application/json" url = self.get.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('VpnConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} async def _create_or_update_initial( self, resource_group_name: str, gateway_name: str, connection_name: str, vpn_connection_parameters: "_models.VpnConnection", **kwargs ) -> "_models.VpnConnection": cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-06-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" url = self._create_or_update_initial.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} body_content = self._serialize.body(vpn_connection_parameters, 'VpnConnection') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('VpnConnection', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('VpnConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} async def begin_create_or_update( self, resource_group_name: str, gateway_name: str, connection_name: str, vpn_connection_parameters: "_models.VpnConnection", **kwargs ) -> AsyncLROPoller["_models.VpnConnection"]: polling = kwargs.pop('polling', True) cls = kwargs.pop('cls', None) lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, gateway_name=gateway_name, connection_name=connection_name, vpn_connection_parameters=vpn_connection_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('VpnConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} async def _delete_initial( self, resource_group_name: str, gateway_name: str, connection_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-06-01" accept = "application/json" url = self._delete_initial.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} async def begin_delete( self, resource_group_name: str, gateway_name: str, connection_name: str, **kwargs ) -> AsyncLROPoller[None]: polling = kwargs.pop('polling', True) cls = kwargs.pop('cls', None) lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, gateway_name=gateway_name, connection_name=connection_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} def list_by_vpn_gateway( self, resource_group_name: str, gateway_name: str, **kwargs ) -> AsyncIterable["_models.ListVpnConnectionsResult"]: cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-06-01" accept = "application/json" def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: url = self.list_by_vpn_gateway.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListVpnConnectionsResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize.failsafe_deserialize(_models.Error, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections'}
true
true
f716ae18f7020711ec64646291e557f4c140c538
51
py
Python
temp.py
Ziggareto/hackerrank_python
02875e9677d74f397d75577b8f3b38b584f31506
[ "MIT" ]
null
null
null
temp.py
Ziggareto/hackerrank_python
02875e9677d74f397d75577b8f3b38b584f31506
[ "MIT" ]
null
null
null
temp.py
Ziggareto/hackerrank_python
02875e9677d74f397d75577b8f3b38b584f31506
[ "MIT" ]
null
null
null
if __name__ == '__main__': print('hi there!!')
25.5
27
0.588235
if __name__ == '__main__': print('hi there!!')
true
true
f716ae2b03112cbb59f032b586e1bf0f10e6bd85
11,973
py
Python
cbt/views.py
belloshehu/multiple-choice-questions
abfb7ac8cc24bc3f9ee34e9505bc6c6944786ac0
[ "MIT" ]
null
null
null
cbt/views.py
belloshehu/multiple-choice-questions
abfb7ac8cc24bc3f9ee34e9505bc6c6944786ac0
[ "MIT" ]
2
2020-09-03T21:48:33.000Z
2020-09-22T08:51:14.000Z
cbt/views.py
belloshehu/multiple-choice-questions
abfb7ac8cc24bc3f9ee34e9505bc6c6944786ac0
[ "MIT" ]
null
null
null
from django.shortcuts import ( render, redirect, reverse, get_object_or_404, get_list_or_404, ) from django.db.models import Q from django.urls import reverse_lazy from django.contrib.auth import authenticate, login, logout from django.contrib import messages from cbt.forms import ( IndividualAssessmentForm, InstitutionForm, InstitutionAssessmentForm ) from multiple_choices.forms import UserRegistration, UserLogin from .models import ( InstitutionAssessment, IndividualAssessment, Institution ) from account.forms import UserLoginForm, UserCreationForm from choice.models import IndividualChoice, InstitutionChoice from question.models import IndividualQuestion, InstitutionQuestion from django.core.mail import send_mail from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordResetForm from django.http import HttpResponse from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode from django.contrib.auth.tokens import default_token_generator from django.utils.encoding import force_bytes from django.views.generic import( CreateView, DeleteView, DetailView, ListView, UpdateView, TemplateView, View ) from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. def home(request): return render (request, 'cbt/home.html', {'form':UserLoginForm}) def cbt_type(request): '''Renders Assessment types template''' return render (request, 'cbt/assessment_types.html') class AssessmentHelpView(TemplateView): template_name = 'cbt/partials/assessment_help.html' ############### # Institution Assessment type CRUD, list and details views: ############## class InstitutionAssessmentCreateView(LoginRequiredMixin ,CreateView): ''' View to create Assessment by organisation. ''' model = InstitutionAssessment form_class = InstitutionAssessmentForm template_name = 'cbt/institution/assessment_form.html' success_url = reverse_lazy('cbt:institution-assessment-list') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class InstitutionAssessmentListView(LoginRequiredMixin, ListView): model = InstitutionAssessment template_name = 'cbt/institution/assessment_list.html' context_object_name = 'assessments' class InstitutionAssessmentDetailView(LoginRequiredMixin, DetailView): model = InstitutionAssessment template_name = 'cbt/institution/assessment_detail.html' context_object_name = 'assessment' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) try: context['choices'] = InstitutionChoice.objects.all() context['questions'] = InstitutionQuestion.objects.filter( assessment_id=self.kwargs.get('pk') ) except InstitutionChoice.DoesNotExist: context['choices'] = None except InstitutionQuestion.DoesNotExist: context['questions'] = None return context class InstitutionAssessmentUpdateView(LoginRequiredMixin, UpdateView): model = InstitutionAssessment form_class = InstitutionAssessmentForm template_name = 'cbt/institution/assessment_update_form.html' success_url = reverse_lazy('cbt:institution-assessment-list') context_object_name = 'assessment' class InstitutionAssessmentDeleteView(LoginRequiredMixin, DeleteView): model = InstitutionAssessment form_class = InstitutionAssessmentForm template_name = 'cbt/institution/assessment_delete_confirm.html' success_url = reverse_lazy('cbt:institution-assessment-list') context_object_name = 'assessment' # #################### # Individual assessment CRUD, details and list views: ###################### class IndividualAssessmentCreateView(LoginRequiredMixin ,CreateView): ''' View to create Assessment by individuals. ''' model = IndividualAssessment form_class = IndividualAssessmentForm template_name = 'cbt/individual/individual_assessment.html' success_url = reverse_lazy('cbt:individual-assessment-list') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class IndividualAssessmentListView(LoginRequiredMixin, ListView): model = IndividualAssessment template_name = 'cbt/individual/individual_assessment_list.html' context_object_name = 'assessments' def get_queryset(self): try: queryset = IndividualAssessment.objects.filter( user=self.request.user ) except IndividualAssessment.DoesNotExist: pass return queryset class IndividualAssessmentDetailView(LoginRequiredMixin, DetailView): model = IndividualAssessment template_name = 'cbt/individual/individual_assessment_detail.html' context_object_name = 'assessment' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) try: context['choices'] = IndividualChoice.objects.filter( question__assessment__user=self.request.user ) context['questions'] = IndividualQuestion.objects.filter( assessment_id=self.kwargs.get('pk'), assessment__user=self.request.user ) except IndividualChoice.DoesNotExist: context['choices'] = None except IndividualQuestion.DoesNotExist: context['questions'] = None return context def get_question_with_passage(self): Q1 = Q(passage__title=None) Q2 = Q(passage__body=None) Q3 = Q(passage__no_of_questions=None) question_with_passage = None try: question_with_passage = IndividualQuestion.objects.filter( Q1&Q2&Q3 ) except IndividualQuestion.DoesNotExist: pass return question_with_passage class IndividualAssessmentDeleteView(LoginRequiredMixin, DeleteView): model = IndividualAssessment form_class = IndividualAssessmentForm template_name = 'cbt/individual/assessment_confirm_delete.html' success_url = reverse_lazy('cbt:individual-assessment-list') context_object_name = 'assessment' class IndividualAssessmentUpdateView(LoginRequiredMixin, UpdateView): model = IndividualAssessment form_class = IndividualAssessmentForm template_name = 'cbt/individual/assessment_update_form.html' success_url = reverse_lazy('cbt:individual-assessment-list') context_object_name = 'assessment' #================================ # Sample Assessments #=============================== class SampleAssessmentListView(LoginRequiredMixin, ListView): model = IndividualAssessment template_name = 'cbt/sample/sample_list.html' context_object_name = 'assessments' def get_queryset(self): try: queryset = IndividualAssessment.objects.filter( user__is_superuser=True, is_sample=True ) except IndividualAssessment.DoesNotExist: pass return queryset #========================= # Institution CRUD, list and details views #========================== class InstitutionListView(LoginRequiredMixin, ListView): model = Institution template_name = 'cbt/institution_list.html' context_object_name = 'institutions' def get_queryset(self): try: queryset = Institution.objects.filter( user=self.request.user ) except Institution.DoesNotExist: pass return queryset class InstitutionDetailView(LoginRequiredMixin, DetailView): pass class InstitutionDeleteView(LoginRequiredMixin, DeleteView): model = Institution template_name = 'cbt/institution_confirm_delete.html' success_url = reverse_lazy('cbt:institution-list') class InstitutionUpdateView(LoginRequiredMixin, UpdateView): model = Institution form_class = InstitutionForm template_name = 'cbt/institution_update_form.html' success_url = reverse_lazy('cbt:institution-list') class InstitutionCreateView(LoginRequiredMixin, CreateView): ''' View to create instance of Institution.''' model = Institution form_class = InstitutionForm template_name = 'cbt/institution_form.html' success_url = reverse_lazy('cbt:institution-list') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def user_login(request): form = UserLogin() if request.method == 'POST': user = authenticate(username=request.POST['username'], password=request.POST['password']) if user: login(request, user) return redirect('cbt:cbt_list') messages.error(request, 'Login credentials error!') return redirect(reverse('cbt:login')) return render(request, 'cbt/login.html', {'form':form} ) def user_signup(request): form = UserRegistration() if request.method == 'POST': form = UserRegistration(request.POST) if form.is_valid: if User.objects.filter(email=request.POST['email']).exists(): messages.error(request, 'Username is already taken') return render(request, 'cbt/signup.html', {'form':form}) form.save() user_detail = request.POST email_subject = 'Welcome to CBTMaker' message = f'''Hi {user_detail.get('username')}, \n Thank you for registering with CBTMaker. \n\n Enjoy CBTMaker. \n\n CBTMaker team.''' email_sender = settings.EMAIL_HOST_USER recipient_list = [user_detail.get('email')] send_mail(email_subject, message, email_sender, recipient_list) print('Email sent') return redirect('cbt:home') else: return redirect(reverse('cbt:signup')) return render(request, 'cbt/signup.html', {'form':form}) def user_logout(request): logout(request) return redirect('cbt:home') def password_reset(request): ''' View for resetting user's password. ''' if request.method == 'POST': password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid: email = request.POST['email'] associated_users = User.objects.filter(email=email) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "cbt/password/password_email.txt" c = { "email":user.email, 'domain':'127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'admin@example.com' , [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('password_reset_done') password_reset_form = PasswordResetForm() context = {'password_reset_form':password_reset_form} return render(request, 'cbt/password/password_reset.html', context)
35.633929
106
0.664662
from django.shortcuts import ( render, redirect, reverse, get_object_or_404, get_list_or_404, ) from django.db.models import Q from django.urls import reverse_lazy from django.contrib.auth import authenticate, login, logout from django.contrib import messages from cbt.forms import ( IndividualAssessmentForm, InstitutionForm, InstitutionAssessmentForm ) from multiple_choices.forms import UserRegistration, UserLogin from .models import ( InstitutionAssessment, IndividualAssessment, Institution ) from account.forms import UserLoginForm, UserCreationForm from choice.models import IndividualChoice, InstitutionChoice from question.models import IndividualQuestion, InstitutionQuestion from django.core.mail import send_mail from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordResetForm from django.http import HttpResponse from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode from django.contrib.auth.tokens import default_token_generator from django.utils.encoding import force_bytes from django.views.generic import( CreateView, DeleteView, DetailView, ListView, UpdateView, TemplateView, View ) from django.contrib.auth.mixins import LoginRequiredMixin def home(request): return render (request, 'cbt/home.html', {'form':UserLoginForm}) def cbt_type(request): return render (request, 'cbt/assessment_types.html') class AssessmentHelpView(TemplateView): template_name = 'cbt/partials/assessment_help.html' ment_form.html' success_url = reverse_lazy('cbt:institution-assessment-list') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class InstitutionAssessmentListView(LoginRequiredMixin, ListView): model = InstitutionAssessment template_name = 'cbt/institution/assessment_list.html' context_object_name = 'assessments' class InstitutionAssessmentDetailView(LoginRequiredMixin, DetailView): model = InstitutionAssessment template_name = 'cbt/institution/assessment_detail.html' context_object_name = 'assessment' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) try: context['choices'] = InstitutionChoice.objects.all() context['questions'] = InstitutionQuestion.objects.filter( assessment_id=self.kwargs.get('pk') ) except InstitutionChoice.DoesNotExist: context['choices'] = None except InstitutionQuestion.DoesNotExist: context['questions'] = None return context class InstitutionAssessmentUpdateView(LoginRequiredMixin, UpdateView): model = InstitutionAssessment form_class = InstitutionAssessmentForm template_name = 'cbt/institution/assessment_update_form.html' success_url = reverse_lazy('cbt:institution-assessment-list') context_object_name = 'assessment' class InstitutionAssessmentDeleteView(LoginRequiredMixin, DeleteView): model = InstitutionAssessment form_class = InstitutionAssessmentForm template_name = 'cbt/institution/assessment_delete_confirm.html' success_url = reverse_lazy('cbt:institution-assessment-list') context_object_name = 'assessment' equiredMixin, ListView): model = IndividualAssessment template_name = 'cbt/individual/individual_assessment_list.html' context_object_name = 'assessments' def get_queryset(self): try: queryset = IndividualAssessment.objects.filter( user=self.request.user ) except IndividualAssessment.DoesNotExist: pass return queryset class IndividualAssessmentDetailView(LoginRequiredMixin, DetailView): model = IndividualAssessment template_name = 'cbt/individual/individual_assessment_detail.html' context_object_name = 'assessment' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) try: context['choices'] = IndividualChoice.objects.filter( question__assessment__user=self.request.user ) context['questions'] = IndividualQuestion.objects.filter( assessment_id=self.kwargs.get('pk'), assessment__user=self.request.user ) except IndividualChoice.DoesNotExist: context['choices'] = None except IndividualQuestion.DoesNotExist: context['questions'] = None return context def get_question_with_passage(self): Q1 = Q(passage__title=None) Q2 = Q(passage__body=None) Q3 = Q(passage__no_of_questions=None) question_with_passage = None try: question_with_passage = IndividualQuestion.objects.filter( Q1&Q2&Q3 ) except IndividualQuestion.DoesNotExist: pass return question_with_passage class IndividualAssessmentDeleteView(LoginRequiredMixin, DeleteView): model = IndividualAssessment form_class = IndividualAssessmentForm template_name = 'cbt/individual/assessment_confirm_delete.html' success_url = reverse_lazy('cbt:individual-assessment-list') context_object_name = 'assessment' class IndividualAssessmentUpdateView(LoginRequiredMixin, UpdateView): model = IndividualAssessment form_class = IndividualAssessmentForm template_name = 'cbt/individual/assessment_update_form.html' success_url = reverse_lazy('cbt:individual-assessment-list') context_object_name = 'assessment' class SampleAssessmentListView(LoginRequiredMixin, ListView): model = IndividualAssessment template_name = 'cbt/sample/sample_list.html' context_object_name = 'assessments' def get_queryset(self): try: queryset = IndividualAssessment.objects.filter( user__is_superuser=True, is_sample=True ) except IndividualAssessment.DoesNotExist: pass return queryset class InstitutionListView(LoginRequiredMixin, ListView): model = Institution template_name = 'cbt/institution_list.html' context_object_name = 'institutions' def get_queryset(self): try: queryset = Institution.objects.filter( user=self.request.user ) except Institution.DoesNotExist: pass return queryset class InstitutionDetailView(LoginRequiredMixin, DetailView): pass class InstitutionDeleteView(LoginRequiredMixin, DeleteView): model = Institution template_name = 'cbt/institution_confirm_delete.html' success_url = reverse_lazy('cbt:institution-list') class InstitutionUpdateView(LoginRequiredMixin, UpdateView): model = Institution form_class = InstitutionForm template_name = 'cbt/institution_update_form.html' success_url = reverse_lazy('cbt:institution-list') class InstitutionCreateView(LoginRequiredMixin, CreateView): model = Institution form_class = InstitutionForm template_name = 'cbt/institution_form.html' success_url = reverse_lazy('cbt:institution-list') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def user_login(request): form = UserLogin() if request.method == 'POST': user = authenticate(username=request.POST['username'], password=request.POST['password']) if user: login(request, user) return redirect('cbt:cbt_list') messages.error(request, 'Login credentials error!') return redirect(reverse('cbt:login')) return render(request, 'cbt/login.html', {'form':form} ) def user_signup(request): form = UserRegistration() if request.method == 'POST': form = UserRegistration(request.POST) if form.is_valid: if User.objects.filter(email=request.POST['email']).exists(): messages.error(request, 'Username is already taken') return render(request, 'cbt/signup.html', {'form':form}) form.save() user_detail = request.POST email_subject = 'Welcome to CBTMaker' message = f'''Hi {user_detail.get('username')}, \n Thank you for registering with CBTMaker. \n\n Enjoy CBTMaker. \n\n CBTMaker team.''' email_sender = settings.EMAIL_HOST_USER recipient_list = [user_detail.get('email')] send_mail(email_subject, message, email_sender, recipient_list) print('Email sent') return redirect('cbt:home') else: return redirect(reverse('cbt:signup')) return render(request, 'cbt/signup.html', {'form':form}) def user_logout(request): logout(request) return redirect('cbt:home') def password_reset(request): if request.method == 'POST': password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid: email = request.POST['email'] associated_users = User.objects.filter(email=email) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "cbt/password/password_email.txt" c = { "email":user.email, 'domain':'127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'admin@example.com' , [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('password_reset_done') password_reset_form = PasswordResetForm() context = {'password_reset_form':password_reset_form} return render(request, 'cbt/password/password_reset.html', context)
true
true
f716af95472fe7d7e24b2543ce0d6861fcc6249f
6,087
py
Python
src/main/resources/rally/RallyClient.py
xebialabs-community/xlr-rally-plugin
d513cf8253457ee540dd3fc714891f33f302ea77
[ "MIT" ]
null
null
null
src/main/resources/rally/RallyClient.py
xebialabs-community/xlr-rally-plugin
d513cf8253457ee540dd3fc714891f33f302ea77
[ "MIT" ]
8
2015-06-02T10:55:04.000Z
2020-11-19T12:47:47.000Z
src/main/resources/rally/RallyClient.py
xebialabs-community/xlr-rally-plugin
d513cf8253457ee540dd3fc714891f33f302ea77
[ "MIT" ]
4
2015-06-02T09:53:43.000Z
2020-02-13T04:38:19.000Z
# # Copyright 2021 XEBIALABS # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # import ast import os import logging from pyral import Rally from xlrelease.CredentialsFallback import CredentialsFallback from java.net import URI import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) class RallyClient(object): def __init__(self, rally_server, username, password, oauth_key): print "Initializing RallyClient\n" self.rally_server = rally_server rally_url = self.rally_server['url'] credentials = CredentialsFallback(self.rally_server, username, password).getCredentials() self.rest_api = None self.configure_proxy() self.rest_api = Rally(URI(rally_url), credentials['username'], credentials['password'], apikey=oauth_key if oauth_key else self.rally_server['oAuthKey'], verify_ssl_cert=False) @staticmethod def create_client(rally_server, username, password, oauth_key): print "Executing create_client() in RallyClient class in RallyClient.py\n" return RallyClient(rally_server, username, password, oauth_key) def configure_proxy(self): if self.rally_server['proxyHost']: os.environ["HTTP_PROXY"] = "http://%s:%s" % (self.rally_server['proxyHost'], self.rally_server['proxyPort']) os.environ["HTTPS_PROXY"] = "https://%s:%s" % (self.rally_server['proxyHost'], self.rally_server['proxyPort']) if self.rally_server['proxyUsername']: os.environ["HTTP_PROXY"] = "http://%s:%s@%s:%s" % ( self.rally_server['proxyUsername'], self.rally_server['proxyPassword'], self.rally_server['proxyHost'], self.rally_server['proxyPort']) os.environ["HTTPS_PROXY"] = "https://%s:%s@%s:%s" % ( self.rally_server['proxyUsername'], self.rally_server['proxyPassword'], self.rally_server['proxyHost'], self.rally_server['proxyPort']) def lookup_item_by_formatted_id(self, workspace, project, type, formatted_id): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) response = self.rest_api.get(type, fetch="ObjectID", query="FormattedID = %s" % formatted_id) if not response.errors: print("Total results: %d\n" % response.resultCount) result = response.next() return result.ObjectID else: print("The following errors occurred: ") for err in response.errors: print("\t" + err) return None def create_sub_item(self, workspace, project, properties, user_story_formatted_id, user_story_type, property_type, item_type): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) story_ref = self.lookup_item_by_formatted_id(workspace, project, user_story_type, user_story_formatted_id) property_dict = dict(ast.literal_eval(properties)) property_dict[property_type] = story_ref return self.create_item(workspace, project, property_dict, item_type) def create_item(self, workspace, project, properties, item_type): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) logging.debug("About to create item in rally") item_create_response = self.rest_api.put(item_type, properties) logging.debug("Create Item response: %s" % (item_create_response.details())) print "Executed successful on Rally" return item_create_response.FormattedID def update_item(self, workspace, project, properties, item_formatted_id, item_type): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) item_object_id = self.lookup_item_by_formatted_id(workspace, project, item_type, item_formatted_id) property_dict = dict(ast.literal_eval(properties)) property_dict["ObjectID"] = item_object_id update_response = self.rest_api.post(item_type, property_dict) print "Executed successful on Rally" return update_response.FormattedID def query(self, workspace, project, item_type, query, fetch="True", rollupdata=False): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) response = self.rest_api.get(item_type, fetch=fetch, query=query, projectScopeDown=rollupdata) if not response.errors: print("Total results: %d\n" % response.resultCount) return response else: print("The following errors occurred: ") for err in response.errors: print("\t" + err) return None def get_user_object_id(self, owner_username=None, owner_name=None): response = self.rest_api.getUserInfo(username=owner_username, name=owner_name) return response[0].ObjectID
50.305785
462
0.693116
import ast import os import logging from pyral import Rally from xlrelease.CredentialsFallback import CredentialsFallback from java.net import URI import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) class RallyClient(object): def __init__(self, rally_server, username, password, oauth_key): print "Initializing RallyClient\n" self.rally_server = rally_server rally_url = self.rally_server['url'] credentials = CredentialsFallback(self.rally_server, username, password).getCredentials() self.rest_api = None self.configure_proxy() self.rest_api = Rally(URI(rally_url), credentials['username'], credentials['password'], apikey=oauth_key if oauth_key else self.rally_server['oAuthKey'], verify_ssl_cert=False) @staticmethod def create_client(rally_server, username, password, oauth_key): print "Executing create_client() in RallyClient class in RallyClient.py\n" return RallyClient(rally_server, username, password, oauth_key) def configure_proxy(self): if self.rally_server['proxyHost']: os.environ["HTTP_PROXY"] = "http://%s:%s" % (self.rally_server['proxyHost'], self.rally_server['proxyPort']) os.environ["HTTPS_PROXY"] = "https://%s:%s" % (self.rally_server['proxyHost'], self.rally_server['proxyPort']) if self.rally_server['proxyUsername']: os.environ["HTTP_PROXY"] = "http://%s:%s@%s:%s" % ( self.rally_server['proxyUsername'], self.rally_server['proxyPassword'], self.rally_server['proxyHost'], self.rally_server['proxyPort']) os.environ["HTTPS_PROXY"] = "https://%s:%s@%s:%s" % ( self.rally_server['proxyUsername'], self.rally_server['proxyPassword'], self.rally_server['proxyHost'], self.rally_server['proxyPort']) def lookup_item_by_formatted_id(self, workspace, project, type, formatted_id): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) response = self.rest_api.get(type, fetch="ObjectID", query="FormattedID = %s" % formatted_id) if not response.errors: print("Total results: %d\n" % response.resultCount) result = response.next() return result.ObjectID else: print("The following errors occurred: ") for err in response.errors: print("\t" + err) return None def create_sub_item(self, workspace, project, properties, user_story_formatted_id, user_story_type, property_type, item_type): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) story_ref = self.lookup_item_by_formatted_id(workspace, project, user_story_type, user_story_formatted_id) property_dict = dict(ast.literal_eval(properties)) property_dict[property_type] = story_ref return self.create_item(workspace, project, property_dict, item_type) def create_item(self, workspace, project, properties, item_type): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) logging.debug("About to create item in rally") item_create_response = self.rest_api.put(item_type, properties) logging.debug("Create Item response: %s" % (item_create_response.details())) print "Executed successful on Rally" return item_create_response.FormattedID def update_item(self, workspace, project, properties, item_formatted_id, item_type): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) item_object_id = self.lookup_item_by_formatted_id(workspace, project, item_type, item_formatted_id) property_dict = dict(ast.literal_eval(properties)) property_dict["ObjectID"] = item_object_id update_response = self.rest_api.post(item_type, property_dict) print "Executed successful on Rally" return update_response.FormattedID def query(self, workspace, project, item_type, query, fetch="True", rollupdata=False): self.rest_api.setWorkspace(workspace) self.rest_api.setProject(project) response = self.rest_api.get(item_type, fetch=fetch, query=query, projectScopeDown=rollupdata) if not response.errors: print("Total results: %d\n" % response.resultCount) return response else: print("The following errors occurred: ") for err in response.errors: print("\t" + err) return None def get_user_object_id(self, owner_username=None, owner_name=None): response = self.rest_api.getUserInfo(username=owner_username, name=owner_name) return response[0].ObjectID
false
true
f716af9d8b3eb607fff52cdc80c5efef400bad64
664
py
Python
exp/alto/tools/create_terminals_bi.py
Hollo1996/4lang
d167110f619e652a5cce723d211946baeae077ea
[ "MIT" ]
20
2016-03-01T07:34:17.000Z
2021-09-06T11:08:11.000Z
exp/alto/tools/create_terminals_bi.py
Hollo1996/4lang
d167110f619e652a5cce723d211946baeae077ea
[ "MIT" ]
103
2015-02-03T13:34:55.000Z
2020-07-13T11:21:22.000Z
exp/alto/tools/create_terminals_bi.py
Hollo1996/4lang
d167110f619e652a5cce723d211946baeae077ea
[ "MIT" ]
14
2015-02-03T09:00:17.000Z
2021-12-15T11:26:30.000Z
#!/usr/bin/env python import sys from hunmisc.corpustools.tsv_tools import sentence_iterator from common import sanitize_word TEMPLATE = ('{0} -> {1}_{0}\n[graph] "({1}<root> / {1})"\n' + '[fourlang] "({1}<root> / {1})"\n') def main(): seen = set() with open(sys.argv[1]) as stream: for sentence in sentence_iterator(stream, comment_tag='#'): for tok in sentence: word = sanitize_word(tok[1]) pos = tok[3] if (word, pos) not in seen: print(TEMPLATE.format(pos, word)) seen.add((word, pos)) if __name__ == "__main__": main()
24.592593
67
0.536145
import sys from hunmisc.corpustools.tsv_tools import sentence_iterator from common import sanitize_word TEMPLATE = ('{0} -> {1}_{0}\n[graph] "({1}<root> / {1})"\n' + '[fourlang] "({1}<root> / {1})"\n') def main(): seen = set() with open(sys.argv[1]) as stream: for sentence in sentence_iterator(stream, comment_tag='#'): for tok in sentence: word = sanitize_word(tok[1]) pos = tok[3] if (word, pos) not in seen: print(TEMPLATE.format(pos, word)) seen.add((word, pos)) if __name__ == "__main__": main()
true
true
f716afd528fd4bac2c2ee7f4d45b47e27b40ca16
1,143
py
Python
HDPython/tests/test_axi_fifo.py
HardwareDesignWithPython/HDPython
aade03aaa092b1684fa12bffd17674cf1c45f5ac
[ "MIT" ]
null
null
null
HDPython/tests/test_axi_fifo.py
HardwareDesignWithPython/HDPython
aade03aaa092b1684fa12bffd17674cf1c45f5ac
[ "MIT" ]
null
null
null
HDPython/tests/test_axi_fifo.py
HardwareDesignWithPython/HDPython
aade03aaa092b1684fa12bffd17674cf1c45f5ac
[ "MIT" ]
1
2021-10-20T20:08:16.000Z
2021-10-20T20:08:16.000Z
from HDPython import * from HDPython.examples import * from .helpers import Folders_isSame, vhdl_conversion, do_simulation,printf from HDPython.test_handler import add_test class test_bench_axi_fifo(v_entity): def __init__(self): super().__init__() self.architecture() def architecture(self): clkgen = clk_generator() maxCount = v_slv(32,20) pipe1 = rollingCounter(clkgen.clk,maxCount) \ | axiFifo(clkgen.clk) \ | axiFifo(clkgen.clk, depth = 5) \ | axiPrint(clkgen.clk) end_architecture() @do_simulation def test_bench_axi_fifo_sim(OutputPath, f= None): tb = test_bench_axi_fifo() return tb def test_test_bench_axi_fifo_sim(): return test_bench_axi_fifo_sim("tests/axi_fifo_sim/") add_test("axi_fifo_sim", test_test_bench_axi_fifo_sim) @vhdl_conversion def test_bench_axi_fifo_2vhdl(OutputPath, f= None): tb = test_bench_axi_fifo() return tb def test_test_bench_axi_fifo_2vhdl(): return test_bench_axi_fifo_2vhdl("tests/axi_fifo/") add_test("axi_fifo_2vhdl", test_test_bench_axi_fifo_2vhdl)
23.326531
74
0.707787
from HDPython import * from HDPython.examples import * from .helpers import Folders_isSame, vhdl_conversion, do_simulation,printf from HDPython.test_handler import add_test class test_bench_axi_fifo(v_entity): def __init__(self): super().__init__() self.architecture() def architecture(self): clkgen = clk_generator() maxCount = v_slv(32,20) pipe1 = rollingCounter(clkgen.clk,maxCount) \ | axiFifo(clkgen.clk) \ | axiFifo(clkgen.clk, depth = 5) \ | axiPrint(clkgen.clk) end_architecture() @do_simulation def test_bench_axi_fifo_sim(OutputPath, f= None): tb = test_bench_axi_fifo() return tb def test_test_bench_axi_fifo_sim(): return test_bench_axi_fifo_sim("tests/axi_fifo_sim/") add_test("axi_fifo_sim", test_test_bench_axi_fifo_sim) @vhdl_conversion def test_bench_axi_fifo_2vhdl(OutputPath, f= None): tb = test_bench_axi_fifo() return tb def test_test_bench_axi_fifo_2vhdl(): return test_bench_axi_fifo_2vhdl("tests/axi_fifo/") add_test("axi_fifo_2vhdl", test_test_bench_axi_fifo_2vhdl)
true
true
f716b0186a220c17477a6aa6ebacf35273a20db8
1,161
py
Python
test/geocoders/geonames.py
navidata/geopy
2c8e441cfb1a813fb2ab34fd41386204ad18f872
[ "MIT" ]
null
null
null
test/geocoders/geonames.py
navidata/geopy
2c8e441cfb1a813fb2ab34fd41386204ad18f872
[ "MIT" ]
null
null
null
test/geocoders/geonames.py
navidata/geopy
2c8e441cfb1a813fb2ab34fd41386204ad18f872
[ "MIT" ]
null
null
null
# -*- coding: UTF-8 -*- import unittest from geopy.compat import u from geopy.geocoders import GeoNames from test.geocoders.util import GeocoderTestBase, env @unittest.skipUnless( # pylint: disable=R0904,C0111 bool(env.get('GEONAMES_USERNAME')), "No GEONAMES_USERNAME env variable set" ) class GeoNamesTestCase(GeocoderTestBase): @classmethod def setUpClass(cls): cls.delta = 0.04 def test_unicode_name(self): """ GeoNames.geocode unicode """ # work around ConfigurationError raised in GeoNames init self.geocoder = GeoNames(username=env['GEONAMES_USERNAME']) self.geocode_run( {"query": "Mount Everest, Nepal"}, {"latitude": 27.987, "longitude": 86.925}, ) def test_reverse(self): """ GeoNames.reverse """ # work around ConfigurationError raised in GeoNames init self.geocoder = GeoNames(username=env['GEONAMES_USERNAME']) self.reverse_run( {"query": "40.75376406311989, -73.98489005863667"}, {"latitude": 40.75376406311989, "longitude": -73.98489005863667}, )
29.025
77
0.634798
import unittest from geopy.compat import u from geopy.geocoders import GeoNames from test.geocoders.util import GeocoderTestBase, env @unittest.skipUnless( bool(env.get('GEONAMES_USERNAME')), "No GEONAMES_USERNAME env variable set" ) class GeoNamesTestCase(GeocoderTestBase): @classmethod def setUpClass(cls): cls.delta = 0.04 def test_unicode_name(self): self.geocoder = GeoNames(username=env['GEONAMES_USERNAME']) self.geocode_run( {"query": "Mount Everest, Nepal"}, {"latitude": 27.987, "longitude": 86.925}, ) def test_reverse(self): self.geocoder = GeoNames(username=env['GEONAMES_USERNAME']) self.reverse_run( {"query": "40.75376406311989, -73.98489005863667"}, {"latitude": 40.75376406311989, "longitude": -73.98489005863667}, )
true
true
f716b2f64bf5f1efd19c1fea7576ec774a9a9154
532
py
Python
School/Average mark.py
Bamgm14/My-Random-Work
b9678a3a84dd8ff00efd638890cff76eb6967c1b
[ "MIT" ]
null
null
null
School/Average mark.py
Bamgm14/My-Random-Work
b9678a3a84dd8ff00efd638890cff76eb6967c1b
[ "MIT" ]
null
null
null
School/Average mark.py
Bamgm14/My-Random-Work
b9678a3a84dd8ff00efd638890cff76eb6967c1b
[ "MIT" ]
null
null
null
#To accepts marks in 5 subjects and displays the total and average mark #Above 90% Grade A* #90 - 80 % Grade A #70 – 80 % Grade B #60 – 70 % Grade C #Less than 60 Grade D a=float(input("Enter Mark(1):")) b=float(input("Enter Mark(2):")) c=float(input("Enter Mark(3):")) d=float(input("Enter Mark(4):")) e=float(input("Enter Mark(5):")) f=(a+b+c+d+e)/5 if f>=90: print ("A+") elif f<90 and f>=80: print ("A") elif f<80 and f>=70: print ("B") elif f<70 and f>=60: print ("C") else: print ("D")
22.166667
71
0.577068
a=float(input("Enter Mark(1):")) b=float(input("Enter Mark(2):")) c=float(input("Enter Mark(3):")) d=float(input("Enter Mark(4):")) e=float(input("Enter Mark(5):")) f=(a+b+c+d+e)/5 if f>=90: print ("A+") elif f<90 and f>=80: print ("A") elif f<80 and f>=70: print ("B") elif f<70 and f>=60: print ("C") else: print ("D")
true
true
f716b6b7fe18e32ba821b081861b3329d11d7a78
1,125
py
Python
csvObject/csvWriter.py
sbaker-dev/csvObject
e31668c9b71284c7e7f6516e61c9617ad7abb7b1
[ "MIT" ]
null
null
null
csvObject/csvWriter.py
sbaker-dev/csvObject
e31668c9b71284c7e7f6516e61c9617ad7abb7b1
[ "MIT" ]
null
null
null
csvObject/csvWriter.py
sbaker-dev/csvObject
e31668c9b71284c7e7f6516e61c9617ad7abb7b1
[ "MIT" ]
null
null
null
import csv def write_csv(write_out_path, name, headers, rows_to_write): """ Purpose ------- This writes out a csv file of row data with an optional header. If you don't want a header, pass None to headers Parameters ---------- :param name: The file name :type name: str :param write_out_path: The write directory :type write_out_path: str :param headers: The headers for the columns you want to write :type headers: list :param rows_to_write: A list of row data to write, each columns row should be an individual element of a list. :type rows_to_write: list :return: Nothing, just write out the file to the specified directory named the specified name :rtype: None """ if type(rows_to_write[0]) != list: rows_to_write = [[row] for row in rows_to_write] with open(f"{write_out_path}/{name}.csv", "w", newline="", encoding="utf-8") as csv_reader: csv_writer = csv.writer(csv_reader) if len(headers) > 0: csv_writer.writerow(headers) for row in rows_to_write: csv_writer.writerow(row)
28.846154
116
0.657778
import csv def write_csv(write_out_path, name, headers, rows_to_write): if type(rows_to_write[0]) != list: rows_to_write = [[row] for row in rows_to_write] with open(f"{write_out_path}/{name}.csv", "w", newline="", encoding="utf-8") as csv_reader: csv_writer = csv.writer(csv_reader) if len(headers) > 0: csv_writer.writerow(headers) for row in rows_to_write: csv_writer.writerow(row)
true
true
f716b763cbd4d44af6bf17e00908e21772e85af9
851
py
Python
service/test_service.py
theBraindonor/la-parking-tickets
9537900c54c0fb4a5ca27d2828621b9b8a5ede73
[ "CC-BY-4.0" ]
null
null
null
service/test_service.py
theBraindonor/la-parking-tickets
9537900c54c0fb4a5ca27d2828621b9b8a5ede73
[ "CC-BY-4.0" ]
9
2020-03-24T16:55:25.000Z
2022-02-17T21:56:35.000Z
service/test_service.py
theBraindonor/la-parking-tickets
9537900c54c0fb4a5ca27d2828621b9b8a5ede73
[ "CC-BY-4.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test the ticket model being serviced on localhost:8080 """ __author__ = "John Hoff" __email__ = "john.hoff@braindonor.net" __copyright__ = "Copyright 2019, John Hoff" __license__ = "Creative Commons Attribution-ShareAlike 4.0 International License" __version__ = "1.0.0" import json import requests from utility import use_project_path from model import load_sample_data_frame if __name__ == '__main__': use_project_path() for index, row in load_sample_data_frame().iterrows(): print(row.to_json()) headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = requests.post('http://127.0.0.1:8080/ticketPrediction', data=row.to_json(), headers=headers) print(json.loads(response.text)) if index > 100: break
26.59375
111
0.692127
__author__ = "John Hoff" __email__ = "john.hoff@braindonor.net" __copyright__ = "Copyright 2019, John Hoff" __license__ = "Creative Commons Attribution-ShareAlike 4.0 International License" __version__ = "1.0.0" import json import requests from utility import use_project_path from model import load_sample_data_frame if __name__ == '__main__': use_project_path() for index, row in load_sample_data_frame().iterrows(): print(row.to_json()) headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = requests.post('http://127.0.0.1:8080/ticketPrediction', data=row.to_json(), headers=headers) print(json.loads(response.text)) if index > 100: break
true
true
f716b8d03170ced406cf21f6d4db40052bbb480d
2,560
py
Python
notebooks/shared/nbconvert/exporters/script.py
leonbett/debuggingbook
ae1fa940c306160429232fbc93a7a7f14b44efb7
[ "MIT" ]
728
2018-09-21T03:51:04.000Z
2022-03-28T09:35:04.000Z
notebooks/shared/nbconvert/exporters/script.py
leonbett/debuggingbook
ae1fa940c306160429232fbc93a7a7f14b44efb7
[ "MIT" ]
103
2018-09-02T12:26:32.000Z
2022-02-09T07:19:08.000Z
notebooks/shared/nbconvert/exporters/script.py
leonbett/debuggingbook
ae1fa940c306160429232fbc93a7a7f14b44efb7
[ "MIT" ]
157
2018-09-02T08:00:50.000Z
2022-03-27T22:04:50.000Z
"""Generic script exporter class for any kernel language""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import entrypoints from .templateexporter import TemplateExporter from traitlets import Dict, default from .base import get_exporter class ScriptExporter(TemplateExporter): # Caches of already looked-up and instantiated exporters for delegation: _exporters = Dict() _lang_exporters = Dict() @default('template_file') def _template_file_default(self): return 'script.tpl' def _get_language_exporter(self, lang_name): """Find an exporter for the language name from notebook metadata. Uses the nbconvert.exporters.script group of entry points. Returns None if no exporter is found. """ if lang_name not in self._lang_exporters: try: Exporter = entrypoints.get_single( 'nbconvert.exporters.script', lang_name).load() except entrypoints.NoSuchEntryPoint: self._lang_exporters[lang_name] = None else: self._lang_exporters[lang_name] = Exporter(parent=self) return self._lang_exporters[lang_name] def from_notebook_node(self, nb, resources=None, **kw): langinfo = nb.metadata.get('language_info', {}) # delegate to custom exporter, if specified exporter_name = langinfo.get('nbconvert_exporter') if exporter_name and exporter_name != 'script': self.log.debug("Loading script exporter: %s", exporter_name) if exporter_name not in self._exporters: Exporter = get_exporter(exporter_name) self._exporters[exporter_name] = Exporter(parent=self) exporter = self._exporters[exporter_name] return exporter.from_notebook_node(nb, resources, **kw) # Look up a script exporter for this notebook's language lang_name = langinfo.get('name') if lang_name: self.log.debug("Using script exporter for language: %s", lang_name) exporter = self._get_language_exporter(lang_name) if exporter is not None: return exporter.from_notebook_node(nb, resources, **kw) # Fall back to plain script export self.file_extension = langinfo.get('file_extension', '.txt') self.output_mimetype = langinfo.get('mimetype', 'text/plain') return super(ScriptExporter, self).from_notebook_node(nb, resources, **kw)
40.634921
82
0.664844
import entrypoints from .templateexporter import TemplateExporter from traitlets import Dict, default from .base import get_exporter class ScriptExporter(TemplateExporter): _exporters = Dict() _lang_exporters = Dict() @default('template_file') def _template_file_default(self): return 'script.tpl' def _get_language_exporter(self, lang_name): if lang_name not in self._lang_exporters: try: Exporter = entrypoints.get_single( 'nbconvert.exporters.script', lang_name).load() except entrypoints.NoSuchEntryPoint: self._lang_exporters[lang_name] = None else: self._lang_exporters[lang_name] = Exporter(parent=self) return self._lang_exporters[lang_name] def from_notebook_node(self, nb, resources=None, **kw): langinfo = nb.metadata.get('language_info', {}) exporter_name = langinfo.get('nbconvert_exporter') if exporter_name and exporter_name != 'script': self.log.debug("Loading script exporter: %s", exporter_name) if exporter_name not in self._exporters: Exporter = get_exporter(exporter_name) self._exporters[exporter_name] = Exporter(parent=self) exporter = self._exporters[exporter_name] return exporter.from_notebook_node(nb, resources, **kw) lang_name = langinfo.get('name') if lang_name: self.log.debug("Using script exporter for language: %s", lang_name) exporter = self._get_language_exporter(lang_name) if exporter is not None: return exporter.from_notebook_node(nb, resources, **kw) # Fall back to plain script export self.file_extension = langinfo.get('file_extension', '.txt') self.output_mimetype = langinfo.get('mimetype', 'text/plain') return super(ScriptExporter, self).from_notebook_node(nb, resources, **kw)
true
true
f716ba644f454c2eb8166dff1191bf0ce61c89b2
598
py
Python
derg/forms.py
mihail4216/myter
4ed1e8abc3f57595858347b21c86a9a10b3ff4a4
[ "MIT" ]
null
null
null
derg/forms.py
mihail4216/myter
4ed1e8abc3f57595858347b21c86a9a10b3ff4a4
[ "MIT" ]
null
null
null
derg/forms.py
mihail4216/myter
4ed1e8abc3f57595858347b21c86a9a10b3ff4a4
[ "MIT" ]
null
null
null
# -*- coding:utf-8 -*- from django import forms # class username(forms.Form): # usernames = forms.CharField(max_length=100) class LoginForm(forms.Form): """ Лучше пользоваться формой и объявлять ее тут, тут можно менять сам тип поля, тест, число, визивик повесить на поле В самом html этого не сможем сделать, но там можно как вначале ты делал так объявлять, для простых форм """ username = forms.CharField(label=u'Имя пользователя') password = forms.CharField(label=u'Пароль', widget=forms.PasswordInput()) class LogoutForm(forms.Form): logout = forms.BooleanField
35.176471
122
0.727425
from django import forms class LoginForm(forms.Form): username = forms.CharField(label=u'Имя пользователя') password = forms.CharField(label=u'Пароль', widget=forms.PasswordInput()) class LogoutForm(forms.Form): logout = forms.BooleanField
true
true
f716ba93e72c41d843f4c01e2abc5c7f8996c487
148
py
Python
petstagram/common/urls.py
DimAntDim/SoftUni_Petstagram_Workshop
b4d6da5fa0d19de4b434046d0b7c73a40c8343b5
[ "MIT" ]
1
2021-06-14T19:50:52.000Z
2021-06-14T19:50:52.000Z
petstagram/common/urls.py
ArifRasim/Petstagram
dc754ecc2ee7184563b26d2ba3f795c2fc767b93
[ "MIT" ]
1
2021-08-09T16:31:13.000Z
2021-08-09T16:31:13.000Z
petstagram/common/urls.py
ArifRasim/Petstagram
dc754ecc2ee7184563b26d2ba3f795c2fc767b93
[ "MIT" ]
1
2022-03-15T13:50:30.000Z
2022-03-15T13:50:30.000Z
from django.urls import path from petstagram.common.views import LandingPage urlpatterns = [ path('', LandingPage.as_view(), name='index'), ]
18.5
50
0.72973
from django.urls import path from petstagram.common.views import LandingPage urlpatterns = [ path('', LandingPage.as_view(), name='index'), ]
true
true
f716bbce2341f6be93b2694916cecbdef85fba95
1,261
py
Python
demo/filepicker_demo/migrations/0002_auto_20150323_1549.py
aaronang/filepicker-django
9de61e9184ae93db9b260764cc2f45a38cb48400
[ "MIT" ]
15
2015-03-25T14:00:16.000Z
2021-04-15T17:47:02.000Z
demo/filepicker_demo/migrations/0002_auto_20150323_1549.py
aaronang/filepicker-django
9de61e9184ae93db9b260764cc2f45a38cb48400
[ "MIT" ]
3
2015-07-14T08:33:37.000Z
2018-12-15T12:58:52.000Z
demo/filepicker_demo/migrations/0002_auto_20150323_1549.py
Ink/django-filepicker
9de61e9184ae93db9b260764cc2f45a38cb48400
[ "MIT" ]
5
2015-07-14T13:30:38.000Z
2018-09-30T19:56:29.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django_filepicker.models class Migration(migrations.Migration): dependencies = [ ('filepicker_demo', '0001_initial'), ] operations = [ migrations.CreateModel( name='BasicFilesModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('text', models.CharField(max_length=64)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='FileModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('fpfile', django_filepicker.models.FPFileField(upload_to=b'uploads')), ('fpurl', models.URLField(max_length=255, null=True, blank=True)), ('mid', models.ForeignKey(to='filepicker_demo.BasicFilesModel')), ], options={ }, bases=(models.Model,), ), migrations.DeleteModel( name='TestModel', ), ]
30.756098
114
0.552736
from __future__ import unicode_literals from django.db import models, migrations import django_filepicker.models class Migration(migrations.Migration): dependencies = [ ('filepicker_demo', '0001_initial'), ] operations = [ migrations.CreateModel( name='BasicFilesModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('text', models.CharField(max_length=64)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='FileModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('fpfile', django_filepicker.models.FPFileField(upload_to=b'uploads')), ('fpurl', models.URLField(max_length=255, null=True, blank=True)), ('mid', models.ForeignKey(to='filepicker_demo.BasicFilesModel')), ], options={ }, bases=(models.Model,), ), migrations.DeleteModel( name='TestModel', ), ]
true
true
f716bc49f322c1fc8a1504767c31a6b027dcd198
583
py
Python
utils/pbtxt.py
Sarmyt/masters_python_code
800d22624e9a9c4ae023f1c5ef40bd0efee5366b
[ "MIT" ]
null
null
null
utils/pbtxt.py
Sarmyt/masters_python_code
800d22624e9a9c4ae023f1c5ef40bd0efee5366b
[ "MIT" ]
null
null
null
utils/pbtxt.py
Sarmyt/masters_python_code
800d22624e9a9c4ae023f1c5ef40bd0efee5366b
[ "MIT" ]
1
2021-06-08T18:02:53.000Z
2021-06-08T18:02:53.000Z
from object_detection.protos.string_int_label_map_pb2 import StringIntLabelMap, StringIntLabelMapItem from google.protobuf import text_format def convert_classes(classes, start=1): msg = StringIntLabelMap() for id, name in enumerate(classes, start=start): msg.item.append(StringIntLabelMapItem(id=id, name=name)) text = str(text_format.MessageToBytes(msg, as_utf8=True), 'utf-8') return text if __name__ == '__main__': txt = convert_classes(['Agent']) print(txt) with open('label_map.pbtxt', 'w') as f: f.write(txt)
30.684211
102
0.698113
from object_detection.protos.string_int_label_map_pb2 import StringIntLabelMap, StringIntLabelMapItem from google.protobuf import text_format def convert_classes(classes, start=1): msg = StringIntLabelMap() for id, name in enumerate(classes, start=start): msg.item.append(StringIntLabelMapItem(id=id, name=name)) text = str(text_format.MessageToBytes(msg, as_utf8=True), 'utf-8') return text if __name__ == '__main__': txt = convert_classes(['Agent']) print(txt) with open('label_map.pbtxt', 'w') as f: f.write(txt)
true
true
f716bc57ce244e895a0fbf1e2a341ecb30e07e9c
199
py
Python
profiles/apps.py
javokhirbek1999/pet-finder-rest-api
67e926ad7b9aa4cb03a35f69e5a52b48dc776c62
[ "PostgreSQL", "Unlicense" ]
1
2021-08-22T22:44:41.000Z
2021-08-22T22:44:41.000Z
profiles/apps.py
javokhirbek1999/pet-finder-rest-api
67e926ad7b9aa4cb03a35f69e5a52b48dc776c62
[ "PostgreSQL", "Unlicense" ]
null
null
null
profiles/apps.py
javokhirbek1999/pet-finder-rest-api
67e926ad7b9aa4cb03a35f69e5a52b48dc776c62
[ "PostgreSQL", "Unlicense" ]
null
null
null
from django.apps import AppConfig class ProfilesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'profiles' def ready(self): from . import signals
22.111111
56
0.713568
from django.apps import AppConfig class ProfilesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'profiles' def ready(self): from . import signals
true
true
f716bc7d927d8f7d83db1221db13eba13a2be4a7
958
py
Python
assets/Point3D.py
sanils2002/PYTHON-CODES
607fadc2cba4b185a5529bd101faefa08f4c3469
[ "MIT" ]
null
null
null
assets/Point3D.py
sanils2002/PYTHON-CODES
607fadc2cba4b185a5529bd101faefa08f4c3469
[ "MIT" ]
null
null
null
assets/Point3D.py
sanils2002/PYTHON-CODES
607fadc2cba4b185a5529bd101faefa08f4c3469
[ "MIT" ]
null
null
null
#Define a Point3D class that inherits from object #Inside the Point3D class, define an __init__() function that accepts self, x, y, and z, and assigns these numbers to the member variables self.x, self.y, self.z #Define a __repr__() method that returns "(%d, %d, %d)" % (self.x, self.y, self.z). This tells Python to represent this object in the following format: (x, y, z). #Outside the class definition, create a variable named my_point containing a new instance of Point3D with x=1, y=2, and z=3. #Finally, print my_point. import os from time import sleep def screen_clear(): if os.name == 'posix': _ = os.system('clear') else: _ = os.system('cls') sleep(1) screen_clear() class Point3D(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self): return "(%d, %d, %d)" % (self.x, self.y, self.z) my_point = Point3D(1,2,3) print(my_point)
34.214286
166
0.64405
import os from time import sleep def screen_clear(): if os.name == 'posix': _ = os.system('clear') else: _ = os.system('cls') sleep(1) screen_clear() class Point3D(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self): return "(%d, %d, %d)" % (self.x, self.y, self.z) my_point = Point3D(1,2,3) print(my_point)
true
true
f716bd1d23d98952f326deff4604828c2677d9b6
2,934
py
Python
src/crawl_data/crawl_data/spiders/XinjiangSpider.py
SmartDataLab/Policy_crawler
fb9fcb7ab701dfb98606afe9f7260f2f2e857506
[ "MIT" ]
3
2020-05-06T06:11:46.000Z
2020-05-24T15:07:22.000Z
src/crawl_data/crawl_data/spiders/XinjiangSpider.py
SmartDataLab/Policy_crawler
fb9fcb7ab701dfb98606afe9f7260f2f2e857506
[ "MIT" ]
2
2020-04-02T14:14:28.000Z
2020-04-27T12:45:48.000Z
src/crawl_data/crawl_data/spiders/XinjiangSpider.py
SmartDataLab/Policy_crawler
fb9fcb7ab701dfb98606afe9f7260f2f2e857506
[ "MIT" ]
2
2020-04-04T09:32:07.000Z
2020-07-07T09:54:23.000Z
import scrapy import pickle import os import ast from urllib import parse from scrapy.selector import Selector class XinjiangSpider(scrapy.Spider): name = "Xinjiang" if not os.path.exists('../../data/HTML_pk/%s' % name): os.makedirs('../../data/HTML_pk/%s' % name) if not os.path.exists('../../data/text/%s' % name): os.makedirs('../../data/text/%s' % name) def start_requests(self): total_page = 34 # total_page = 3 url_base = 'http://www.xinjiang.gov.cn/xinjiang/gfxwj/zfxxgk_gknrz{0}.shtml' for i in range(total_page): page = '_'+ str(i+1) if i > 0 else '' yield scrapy.Request(url=url_base.format(page), callback=self.parse) def parse(self,response): detail_page_links = [] for dd in response.css('div.gknr_list dd'): url = response.urljoin(dd.css('a::attr(href)').get()) UID = url.split('/')[-1][:-6] if '?' not in UID: detail_page_links.append(url) yield { 'UID': UID, 'title': dd.css('a::attr(title)').get(), 'date': dd.css('span::text').get(), 'FileNumber':None, 'text length':0, 'url': url, 'crawl state':'half' } yield from response.follow_all(detail_page_links, callback = self.parse_content) def parse_content(self, response): UID = response.url.split('/')[-1][:-6] doc_info_dict = {} for li in response.css('ul.clearfix li'): tmp_l = li.css('*::text').getall() if len(tmp_l) == 2: doc_info_dict[tmp_l[0]] = tmp_l[1] else: tmp_l = tmp_l[0].split(':') if len(tmp_l) == 2: doc_info_dict[tmp_l[0]] = tmp_l[1] File_num = None if '发文字号' in doc_info_dict.keys(): File_num = doc_info_dict['发文字号'] paragraph_list = response.css('div.gknbxq_detail p *::text').getall() attachment_link = response.css('div.ewebeditor_doc img::attr(src)').getall() if len(paragraph_list) == 0: paragraph_list = response.css('p *::text').getall() length = len(''.join(paragraph_list)) if length > 0: state = 'full' with open('../../data/HTML_pk/%s/%s.pkl' % (self.name,UID), 'wb') as f: pickle.dump(response.text,f) with open('../../data/text/%s/%s.txt' % (self.name,UID), 'w') as f: f.write('\n'.join(paragraph_list)) else: state = 'empty' return { 'UID': UID, 'FileNumber':File_num, 'mainText': paragraph_list, 'attachment_link': attachment_link, 'doc_info_dict':doc_info_dict, 'crawl state':state, 'text length':length, }
38.605263
92
0.519087
import scrapy import pickle import os import ast from urllib import parse from scrapy.selector import Selector class XinjiangSpider(scrapy.Spider): name = "Xinjiang" if not os.path.exists('../../data/HTML_pk/%s' % name): os.makedirs('../../data/HTML_pk/%s' % name) if not os.path.exists('../../data/text/%s' % name): os.makedirs('../../data/text/%s' % name) def start_requests(self): total_page = 34 url_base = 'http://www.xinjiang.gov.cn/xinjiang/gfxwj/zfxxgk_gknrz{0}.shtml' for i in range(total_page): page = '_'+ str(i+1) if i > 0 else '' yield scrapy.Request(url=url_base.format(page), callback=self.parse) def parse(self,response): detail_page_links = [] for dd in response.css('div.gknr_list dd'): url = response.urljoin(dd.css('a::attr(href)').get()) UID = url.split('/')[-1][:-6] if '?' not in UID: detail_page_links.append(url) yield { 'UID': UID, 'title': dd.css('a::attr(title)').get(), 'date': dd.css('span::text').get(), 'FileNumber':None, 'text length':0, 'url': url, 'crawl state':'half' } yield from response.follow_all(detail_page_links, callback = self.parse_content) def parse_content(self, response): UID = response.url.split('/')[-1][:-6] doc_info_dict = {} for li in response.css('ul.clearfix li'): tmp_l = li.css('*::text').getall() if len(tmp_l) == 2: doc_info_dict[tmp_l[0]] = tmp_l[1] else: tmp_l = tmp_l[0].split(':') if len(tmp_l) == 2: doc_info_dict[tmp_l[0]] = tmp_l[1] File_num = None if '发文字号' in doc_info_dict.keys(): File_num = doc_info_dict['发文字号'] paragraph_list = response.css('div.gknbxq_detail p *::text').getall() attachment_link = response.css('div.ewebeditor_doc img::attr(src)').getall() if len(paragraph_list) == 0: paragraph_list = response.css('p *::text').getall() length = len(''.join(paragraph_list)) if length > 0: state = 'full' with open('../../data/HTML_pk/%s/%s.pkl' % (self.name,UID), 'wb') as f: pickle.dump(response.text,f) with open('../../data/text/%s/%s.txt' % (self.name,UID), 'w') as f: f.write('\n'.join(paragraph_list)) else: state = 'empty' return { 'UID': UID, 'FileNumber':File_num, 'mainText': paragraph_list, 'attachment_link': attachment_link, 'doc_info_dict':doc_info_dict, 'crawl state':state, 'text length':length, }
true
true
f716bf95e7d6fbcfe61fecbdb7066fd00f5a91e2
62,475
py
Python
gamdist/gamdist.py
rwilson4/gamdist_new
b5d41f7c55fd96399edd1a14e6e259b525495dfd
[ "Apache-2.0" ]
null
null
null
gamdist/gamdist.py
rwilson4/gamdist_new
b5d41f7c55fd96399edd1a14e6e259b525495dfd
[ "Apache-2.0" ]
null
null
null
gamdist/gamdist.py
rwilson4/gamdist_new
b5d41f7c55fd96399edd1a14e6e259b525495dfd
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Match Group, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You may # obtain a copy of the License at # # 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. # # Passing untrusted user input may have unintended consequences. Not # designed to consume input from unknown sources (i.e., the public # internet). # # This file has been modified from the original release by Match Group # LLC. A description of changes may be found in the change log # accompanying this source code. import sys import pickle import multiprocessing as mp import numpy as np import scipy.special as special import scipy.stats as stats import scipy.linalg as linalg from matplotlib import pyplot as plt from .feature import _Feature from .categorical_feature import _CategoricalFeature from .linear_feature import _LinearFeature from .spline_feature import _SplineFeature import proximal_operators as po # To do: # - Hierarchical models # - Piecewise constant fits, total variation regularization # - Monotone constraint # - Implement overdispersion for Poisson family # - Implement Multinomial, Proportional Hazards # - Implement outlier detection # - AICc, BIC, R-squared estimate # - Confidence intervals on mu, predictions (probably need to use Bootstrap but can # do so intelligently) # - Confidence intervals on model parameters, p-values # - Group lasso penalty (l2 norm -- not squared -- or l_\infty norm on f_j(x_j; p_j)) # - Interactions # - Runtime optimization (Cython) # - Fit in parallel # - Residuals # - Compute different types of residuals (Sec 3.1.7 of [GAMr]) # - Plot residuals against mean response, variance, predictor, unused predictor # - QQ plot of residuals # # Done: # - Implement Gaussian, Binomial, Poisson, Gamma, Inv Gaussian, # - Plot splines # - Deviance (on training set and test set), AIC, Dispersion, GCV, UBRE # - Write documentation # - Check implementation of Gamma dispersion # - Implement probit, complementary log-log links. # - Implement Binomial models for covariate classes # - Constrain spline to have mean prediction 0 over the data # - Save and load properly # - Implement overdispersion for Binomial family FAMILIES = ['normal', 'binomial', 'poisson', 'gamma', 'exponential', 'inverse_gaussian' ] LINKS = ['identity', 'logistic', 'probit', 'complementary_log_log', 'log', 'reciprocal', 'reciprocal_squared' ] FAMILIES_WITH_KNOWN_DISPERSIONS = {'binomial': 1, 'poisson': 1 } CANONICAL_LINKS = {'normal': 'identity', 'binomial': 'logistic', 'poisson': 'log', 'gamma': 'reciprocal', 'inverse_gaussian': 'reciprocal_squared' } # Non-canonical but common link/family combinations include: # Binomial: probit and complementary log-log # Gamma: identity and log def _plot_convergence(prim_res, prim_tol, dual_res, dual_tol, dev): """Plot convergence progress. We deem the algorithm to have converged when the prime and dual residuals are smaller than tolerances which are themselves computed based on the data as in [ADMM]. Some analysts prefer to claim convergence when changes to the deviance (a measure of goodness of fit). Thus we plot that as well. Specifically, we plot, on a log scale, dev - dev_final, where dev_final is the deviance of the final model. We add 1e-10 just to avoid taking the logarithm of zero, which is completely arbitrary but makes the plot look acceptable. Parameters ---------- prim_res : array Array of prime residuals after each iteration. prim_tol : array Array of prime tolerances after each iteration. dual_res : array Array of dual residuals after each iteration. dual_tol : array Array of dual tolerances after each iteration. dev : array Array of deviances after each iteration Returns ------- (nothing) """ fig = plt.figure(figsize=(12., 10.)) ax = fig.add_subplot(211) ax.plot(range(len(prim_res)), prim_res, 'b-', label='Primal Residual') ax.plot(range(len(prim_tol)), prim_tol, 'b--', label='Primal Tolerance') ax.plot(range(len(dual_res)), dual_res, 'r-', label='Dual Residual') ax.plot(range(len(dual_tol)), dual_tol, 'r--', label='Dual Tolerance') ax.set_yscale('log') plt.xlabel('Iteration', fontsize=24) plt.ylabel('Residual', fontsize=24) plt.legend(fontsize=24, loc=3) ax = fig.add_subplot(212) ax.plot(range(len(dev)), (dev - dev[-1]) + 1e-10, 'b-', label='Deviance') ax.set_yscale('log') plt.xlabel('Iteration', fontsize=24) plt.ylabel('Deviance Suboptimality', fontsize=24) plt.gcf().subplots_adjust(bottom=0.1) plt.gcf().subplots_adjust(left=0.1) plt.show() def _feature_wrapper(f): """Wrapper for feature optimization. This is a wrapper for use with multi-threaded versions. Unfortunately Python threads are *terrible*, so this doesn't actually get used. Parameters ------ f : list Array of inputs. f[0] is the name of the feature. f[1] is the feature object itself. f[2] is N * fpumz (the vector input to the feature during optimization). f[3] is the ADMM parameter, rho. Returns ------- name : str The name of the feature. (The same as the input.) f_j : array The array of fitted values returned by the feature. """ return f[0], f[1].optimize(f[2], f[3]) def _gamma_dispersion(dof, dev, num_obs): """Gamma dispersion. This function estimates the dispersion of a Gamma family with p degrees of freedom and deviance D, and n observations. The dispersion nu is that number satisfying 2*n * (log nu - psi(nu)) - p / nu = D We use Newton's method with a learning rate to solve this nonlinear equation. Parameters ---------- dof : float Degrees of freedom dev : float Deviance num_obs : int Number of observations Returns ------- nu : float Estimated dispersion """ beta = 0.1 tol = 1e-6 max_its = 100 nu = 1. for i in range(max_its): num = 2. * num_obs * (np.log(nu) - special.psi(nu)) - dof / nu - dev denom = 2. * num_obs * (1. / nu - special.polygamma(1, nu)) + dof / (nu * nu) dnu = num / denom nu -= dnu * beta if abs(dnu) < tol: return nu else: raise ValueError('Could not estimate gamma dispersion.') class GAM: def __init__(self, family=None, link=None, dispersion=None, estimate_overdispersion=False, name=None, load_from_file=None): """Generalized Additive Model This is the constructor for a Generalized Additive Model. References ---------- [glmnet] glmnet (R package): https://cran.r-project.org/web/packages/glmnet/index.html This is the standard package for GAMs in R and was written by people much smarter than I am! [pygam] pygam (Python package): https://github.com/dswah/pyGAM This is a library in Python that does basically the same thing as this script, but in a different way (not using ADMM). [GLM] Generalized Linear Models by McCullagh and Nelder The standard text on GLMs. [GAM] Generalized Additive Models; by Hastie and Tibshirani The book by the folks who invented GAMs. [ESL] The Elements of Statistical Learning; by Hastie, Tibshirani, and Friedman. Covers a lot more than just GAMs. [GAMr] Generalized Additive Models: an Introduction with R; by Wood. Covers more implementation details than [GAM]. [ADMM] Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers; by Boyd, Parikh, Chu, Peleato, and Eckstein. A mouthful, a work of genius. [GAMADMM] A Distributed Algorithm for Fitting Generalized Additive Models; by Chu, Keshavarz, and Boyd Forms the basis of our approach, the inspiration for this package! Parameters ---------- family : str or None (default None) Family of the model. Currently supported families include: 'normal' (for continuous responses), 'binomial' (for binary responses), 'poisson' (for counts), 'gamma' (still in progress), 'inverse_gaussian' (still in progress). Not currently supported families that could be supported include Multinomial models (ordinal and nominal) and proportional hazards models. Required unless loading an existing model from file (see load_from_file). link : str or None (optional) Link function associated with the model. Supported link functions include: Link Canonical For Family 'identity' 'normal' 'logistic' 'binomial' 'log' 'poisson' 'reciprocal' 'gamma' 'reciprocal_squared' 'inverse_gaussian' Other links worth supporting include probit, log-log and complementary log-log link functions. If not specified, the canonical link will be used, but non- canonical links are still permitted. Certain link/family combinations result in a non-convex problem and convergence is not guaranteed. dispersion : float or None (optional) Dispersion parameter associated with the model. Certain families (binomial, poisson) have dispersion independent of the data. Specifying the dispersion for these families does nothing. In other instances, the dispersion is typically unknown and must be estimated from the data. If the dispersion is known, it can be specified here which will reduce the uncertainty of the model. estimate_overdispersion : boolean (optional) Flag specifying whether to estimate over-dispersion for Binomial and Poisson (not yet implemented) families. Is only possible when covariate classes are present and have at least modest size. See [GLM, S4.5] for details. Defaults to False. name : str or None (optional) Name for model, to be used in plots and in saving files. load_from_file : str or None (optional) This module uses an iterative approach to fitting models. For complicated models with lots of data, each iteration can take a long time (though the number of iterations is typically less than 100). If the user wishes to pause after the end of an iteration, they can pick up where the left off by saving results (see the save_flag in .fit) and loading them to start the next iterations. Specifying this option supercedes all other parameters. Returns ------- mdl : Generalized Additive Model object """ if load_from_file is not None: self._load(load_from_file) return if family is None: raise ValueError('Family not specified.') elif family not in FAMILIES: raise ValueError('{} family not supported'.format(family)) elif family == 'exponential': # Exponential is a special case of Gamma with a dispersion of 1. self._family = 'gamma' dispersion = 1. else: self._family = family if link is None: self._link = CANONICAL_LINKS[family] elif link in LINKS: self._link = link else: raise ValueError('{} link not supported'.format(link)) if dispersion is not None: self._known_dispersion = True self._dispersion = dispersion elif (self._family in FAMILIES_WITH_KNOWN_DISPERSIONS.keys() and not estimate_overdispersion): self._known_dispersion = True self._dispersion = FAMILIES_WITH_KNOWN_DISPERSIONS[self._family] else: self._known_dispersion = False if self._link == 'identity': self._eval_link = lambda x: x self._eval_inv_link = lambda x: x elif self._link == 'logistic': self._eval_link = lambda x: np.log( x / (1. - x) ) self._eval_inv_link = lambda x: np.exp(x) / (1 + np.exp(x)) elif self._link == 'probit': # Inverse CDF of the Gaussian distribution self._eval_link = lambda x: stats.norm.ppf(x) self._eval_inv_link = lambda x: stats.norm.cdf(x) elif self._link == 'complementary_log_log': self._eval_link = lambda x: np.log(-np.log(1. - x)) self._eval_inv_link = lambda x: 1. - np.exp(-np.exp(x)) elif self._link == 'log': self._eval_link = lambda x: np.log(x) self._eval_inv_link = lambda x: np.exp(x) elif self._link == 'reciprocal': self._eval_link = lambda x: 1. / x self._eval_inv_link = lambda x: 1. / x elif self._link == 'reciprocal_squared': self._eval_link = lambda x: 1. / (x * x) self._eval_inv_link = lambda x: 1. / np.sqrt(x) self._estimate_overdispersion = estimate_overdispersion self._features = {} self._offset = 0.0 self._num_features = 0 self._fitted = False self._name = name def _save(self): """Save state. Save the model to file to make predictions later, or continue a fitting session. """ mv = {} mv['family'] = self._family mv['link'] = self._link mv['known_dispersion'] = self._known_dispersion if self._known_dispersion: mv['dispersion'] = self._dispersion mv['estimate_overdispersion'] = self._estimate_overdispersion mv['offset'] = self._offset mv['num_features'] = self._num_features mv['fitted'] = self._fitted mv['name'] = self._name features = {} for name, feature in self._features.iteritems(): features[name] = {'type': feature.__type__, 'filename': feature._filename } mv['features'] = features # mv['rho'] = self._rho mv['num_obs'] = self._num_obs mv['y'] = self._y mv['weights'] = self._weights mv['has_covariate_classes'] = self._has_covariate_classes if self._has_covariate_classes: mv['covariate_class_sizes'] = self._covariate_class_sizes mv['f_bar'] = self.f_bar mv['z_bar'] = self.z_bar mv['u'] = self.u mv['prim_res'] = self.prim_res mv['dual_res'] = self.dual_res mv['prim_tol'] = self.prim_tol mv['dual_tol'] = self.dual_tol mv['dev'] = self.dev filename = '{0:s}_model.pckl'.format(self._name) f = open(filename, 'w') pickle.dump(mv, f) f.close() def _load(self, filename): """Load state. Load a model from file to make predictions. """ f = open(filename) mv = pickle.load(f) f.close() self._filename = filename self._family = mv['family'] self._link = mv['link'] self._known_dispersion = mv['known_dispersion'] if self._known_dispersion: self._dispersion = mv['dispersion'] self._estimate_overdispersion = mv['estimate_overdispersion'] self._offset = mv['offset'] self._num_features = mv['num_features'] self._fitted = mv['fitted'] self._name = mv['name'] self._features = {} features = mv['features'] for (name, feature) in features.iteritems(): if feature['type'] == 'categorical': self._features[name] = _CategoricalFeature(load_from_file=feature['filename']) elif feature['type'] == 'linear': self._features[name] = _LinearFeature(load_from_file=feature['filename']) elif feature['type'] == 'spline': self._features[name] = _SplineFeature(load_from_file=feature['filename']) else: raise ValueError('Invalid feature type') # self._rho = mv['rho'] self._num_obs = mv['num_obs'] self._y = mv['y'] self._weights = mv['weights'] self._has_covariate_classes = mv['has_covariate_classes'] if self._has_covariate_classes: self._covariate_class_sizes = mv['covariate_class_sizes'] self.f_bar = mv['f_bar'] self.z_bar = mv['z_bar'] self.u = mv['u'] self.prim_res = mv['prim_res'] self.dual_res = mv['dual_res'] self.prim_tol = mv['prim_tol'] self.dual_tol = mv['dual_tol'] self.dev = mv['dev'] if self._link == 'identity': self._eval_link = lambda x: x self._eval_inv_link = lambda x: x elif self._link == 'logistic': self._eval_link = lambda x: np.log( x / (1. - x) ) self._eval_inv_link = lambda x: np.exp(x) / (1 + np.exp(x)) elif self._link == 'probit': # Inverse CDF of the Gaussian distribution self._eval_link = lambda x: stats.norm.ppf(x) self._eval_inv_link = lambda x: stats.norm.cdf(x) elif self._link == 'complementary_log_log': self._eval_link = lambda x: np.log(-np.log(1. - x)) self._eval_inv_link = lambda x: 1. - np.exp(-np.exp(x)) elif self._link == 'log': self._eval_link = lambda x: np.log(x) self._eval_inv_link = lambda x: np.exp(x) elif self._link == 'reciprocal': self._eval_link = lambda x: 1. / x self._eval_inv_link = lambda x: 1. / x elif self._link == 'reciprocal_squared': self._eval_link = lambda x: 1. / (x * x) self._eval_inv_link = lambda x: 1. / np.sqrt(x) def add_feature(self, name, type, transform=None, rel_dof=None, regularization=None): """Add a feature Add a feature to a Generalized Additive Model. (An implicit constant feature is always included, representing the overall average response.) Parameters ---------- name : str Name for feature. Used internally to keep track of features and is also used when saving files and in plots. type : str Type of feature. Currently supported options include: 'categorical' (for categorical variables) 'linear' (for variables with a linear contribution to the response) 'spline' (for variables with a potentially nonlinear contribution to the response). Other types of features worth supporting include piecewise constant functions and monotonic functions. Those might end up being regularization terms. transform : function or None Optional transform applied to feature data, saving the user from repetitive boilerplate code. Any function may be used; it is applied to data provided during fitting and prediction. Common options might include np.log, np.log1p, or np.sqrt. The user may wish to start with a base feature like 'age' and use derived features 'age_linear', 'age_quadratic' to permit quadratic models for that feature, with potentially different regularization applied to each. rel_dof : float or None Relative degrees of freedom. Applicable only to spline features. The degrees of freedom associated with a spline represent how "wiggly" it is allowed to be. A spline with two degrees of freedom is just a line. (Actually, since these features are constrained to have zero mean response over the data, linear features only have one degree of freedom.) The relative degrees of freedom are used to specify the baseline smoothing parameter (lambda) associated with a feature. When the model is fit to data, the user can specify an overall smoothing parameter applied to all features to alter the amount of regularization in the entire model. Thus the actual degrees of freedom will vary based on the amount of smoothing. The idea is that the analyst may wish to permit some features to be more wiggly than others. By default, all splines have 4 relative degrees of freedom. Regularization of any feature effectively reduces the degrees of freedom, and so this term is potentially applicable, but that is not yet supported. regularization : dictionary or None Dictionary specifying the regularization applied to this feature. Different types of features support different types of regularization. Splines implicitly only support regularization of the wiggliness via a C2 smoothness penalty. That is controlled via the rel_dof. Other features have more diverse options described in their own documentation. Returns ------- (nothing) """ if type == 'categorical': f = _CategoricalFeature(name, regularization=regularization) elif type == 'linear': f = _LinearFeature(name, transform, regularization=regularization) elif type == 'spline': f = _SplineFeature(name, transform, rel_dof) else: raise ValueError('Features of type {} not supported.'.format(type)) self._features[name] = f self._num_features += 1 def fit(self, X, y, covariate_class_sizes=None, weights=None, optimizer='admm', smoothing=1., save_flag=False, verbose=False, plot_convergence=False, max_its=100): """Fit a Generalized Additive Model to data. Note regarding binomial families: many data sets include multiple observations having identical features. For example, imagine a data set with features 'gender', and 'country' and binary response indicating whether the person died (morbid but common in biostatistics). The data might look like this: gender country patients survivors M USA 50 48 F USA 70 65 M CAN 40 38 F CAN 45 43 This still describes a binomial family, but in a more compact format than specifying each individual user. We eventually want to support this more compact format, but we do not currently! In this context, it is important to check for over-dispersion (see [GLM]), and I need to learn more first. In the current implementation, we assume that there is no over-dispersion, and that the number of users having the same set of features is small. Parameters ---------- X : pandas dataframe Dataframe of features. The column names must correspond to the names of features added to the model. X may have extra columns corresponding to features not included in the model; these are simply ignored. Where applicable, the data should be "pre-transformation", since this code will apply any transformations specified in .add_feature. y : array Response. Depending on the model family, the response may need to be in a particular form (for example, for a binomial family, the y's should be either 0 or 1), but this is not checked anywhere! covariate_class_sizes : array or None. If observations are grouped into covariance classes, the size of those classes should be listed in this input. w : array Weights applied to each observation. This is effectively specifying the dispersion of each observation. optimizer : string We use the Alternating Direction Method of Multipliers ('admm') to fit the model. We may eventually support more methods, but right now this option does nothing. smoothing : float Smoothing to apply to entire model, used in conjunction with other regularization parameters. That is, whatever regularization is used for the various features, is scaled by this term, allowing the user to set the overall smoothing by Cross Validation or whatever they like. This allows the user to specify different regularization for each feature, while still permitting a one-dimensional family of models corresponding to different amounts of regularization. Defaults to 1., leaving the regularization as specified in .add_feature(). save_flag : boolean Specifies whether to save intermediate results after each iteration. Useful for complicated models with massive data sets that take a while to fit. If the system crashes during the fit, the analyst can pick up where they left off instead of starting from scratch. Defaults to False. verbose : boolean Specifies whether to print mildly useful information to the screen during the fit. Defaults to False. plot_convergence : boolean Specifies whether to plot the convergence graph at the end. (I suspect only Convex Optimization nerds like me want to see this.) Defaults to False. max_its : integer Maximum number of iterations. Defaults to 100. Returns ------- (nothing) """ if save_flag and self._name is None: msg = 'Cannot save a GAM with no name.' msg += ' Specify name when instantiating model.' raise ValueError(msg) if len(X) != len(y): raise ValueError('Inconsistent number of observations in X and y.') num_threads = 1 self._rho = 0.1 eps_abs = 1e-3 eps_rel = 1e-3 # Note that X may include columns that do not correspond to features in our model # (for example, if the user is experimenting with leaving out features to assess # importance). Thus, the real number of features is self._num_features, not # num_features as in the next line. self._num_obs, num_features = X.shape self._y = y.flatten() self._weights = weights if covariate_class_sizes is not None: self._has_covariate_classes = True self._covariate_class_sizes = covariate_class_sizes mean_response = float(np.sum(self._y)) / np.sum(self._covariate_class_sizes) self._offset = self._eval_link(mean_response) else: self._has_covariate_classes = False self._covariate_class_sizes = None self._offset = self._eval_link(np.mean(self._y)) fj = {} for name, feature in self._features.iteritems(): feature.initialize(X[name].values, smoothing=smoothing, covariate_class_sizes=self._covariate_class_sizes, save_flag=save_flag, save_prefix=self._name) fj[name] = np.zeros(self._num_obs) self.f_bar = np.full((self._num_obs,), self._offset / self._num_features) self.z_bar = np.zeros(self._num_obs) self.u = np.zeros(self._num_obs) self.prim_res = [] self.dual_res = [] self.prim_tol = [] self.dual_tol = [] self.dev = [] z_new = np.zeros(self._num_obs) if num_threads > 1: p = mp.Pool(num_threads) else: p = None for i in range(max_its): if verbose: print 'Iteration {0:d}'.format(i) print 'Optimizing primal variables' fpumz = self._num_features * (self.f_bar + self.u - self.z_bar) fj_new = {} f_new = np.full((self._num_obs,), self._offset) if False: #num_threads > 1: # Getting python to run a for loop in parallel # might as well be impossible :-( args = [(i, self._features[i], fpumz, self._rho) for i in self._features.keys()] results = p.map(_feature_wrapper, args) for i in results: fj_new[i[0]] = i[1] f_new += i[1] else: for name, feature in self._features.iteritems(): if verbose: print 'Optimizing {0:s}'.format(name) fj_new[name] = feature.optimize(fpumz, self._rho) f_new += fj_new[name] f_new /= self._num_features if verbose: print 'Optimizing dual variables' z_new = self._optimize(self.u + f_new, self._num_features, p) self.u += f_new - z_new prim_res = np.sqrt(self._num_features) * linalg.norm(f_new - z_new) dual_res = 0.0 norm_ax = 0.0 norm_bz = 0.0 norm_aty = 0.0 num_params = 0 for name, feature in self._features.iteritems(): dr = ((fj_new[name] - fj[name]) + (z_new - self.z_bar) - (f_new - self.f_bar)) dual_res += dr.dot(dr) norm_ax += fj_new[name].dot(fj_new[name]) zik = fj_new[name] + z_new - f_new norm_bz += zik.dot(zik) norm_aty += feature.compute_dual_tol(self.u) num_params += feature.num_params() dual_res = self._rho * np.sqrt(dual_res) norm_ax = np.sqrt(norm_ax) norm_bz = np.sqrt(norm_bz) norm_aty = np.sqrt(norm_aty) self.f_bar = f_new fj = fj_new self.z_bar = z_new if self._has_covariate_classes: sccs = np.sum(self._covariate_class_sizes) prim_tol = (np.sqrt(sccs * self._num_features) * eps_abs + eps_rel * np.max([norm_ax, norm_bz])) else: prim_tol = (np.sqrt(self._num_obs * self._num_features) * eps_abs + eps_rel * np.max([norm_ax, norm_bz])) dual_tol = np.sqrt(num_params) * eps_abs + eps_rel * norm_aty self.prim_res.append(prim_res) self.dual_res.append(dual_res) self.prim_tol.append(prim_tol) self.dual_tol.append(dual_tol) self.dev.append(self.deviance()) if prim_res < prim_tol and dual_res < dual_tol: if verbose: print 'Fit converged' break else: if verbose: print 'Fit did not converge' if num_threads > 1: p.close() p.join() self._fitted = True if save_flag: self._save() if plot_convergence: _plot_convergence(self.prim_res, self.prim_tol, self.dual_res, self.dual_tol, self.dev) def _optimize(self, upf, N, p=None): """Optimize \bar{z}. Solves the optimization problem: minimize L(N*z) + \rho/2 * \| N*z - N*u - N*\bar{f} \|_2^2 where z is the variable, N is the number of features, u is the scaled dual variable, \bar{f} is the average feature response, and L is the likelihood function which is different depending on the family and link function. This is accomplished via a proximal operator, as discussed in [GAMADMM]: prox_\mu(v) := argmin_x L(x) + \mu/2 * \| x - v \|_2^2 I strongly believe that paper contains a typo in this equation, so we return (1. / N) * prox_\mu (N * (u + \bar{f}) with \mu = \rho instead of \mu = \rho / N as in [GAMADMM]. When implemented as in the paper, convergence was much slower, but it did still converge. Certain combinations of family and link function result in proximal operators with closed form solutions, making this step *very* fast (e.g. 3 flops per observation). Parameters ---------- upf : array Vector representing u + \bar{f} N : integer Number of features. p : Multiprocessing Pool (optional) If multiple threads are available, massive data sets may benefit from solving this optimization problem in parallel. It is up to the individual functions to decide whether to actually do this. Returns ------- z : array Result of the above optimization problem. """ prox = None if self._family == 'normal': if self._link == 'identity': prox = po._prox_normal_identity else: prox = po._prox_normal elif self._family == 'binomial': if self._link == 'logistic': prox = po._prox_binomial_logit else: prox = po._prox_binomial if self._has_covariate_classes: return (1. / N) * prox(N*upf, self._rho, self._y, self._covariate_class_sizes, self._weights, self._eval_inv_link, p=p) elif self._family == 'poisson': if self._link == 'log': prox = po._prox_poisson_log else: prox = po._prox_poisson elif self._family == 'gamma': if self._link == 'reciprocal': prox = po._prox_gamma_reciprocal else: prox = po._prox_gamma elif self._family == 'inverse_gaussian': if self._link == 'reciprocal_squared': prox = po._prox_inv_gaussian_reciprocal_squared else: prox = po._prox_inv_gaussian else: msg = 'Family {0:s} and Link Function {1:s} not (yet) supported.' raise ValueError(msg.format(self._family, self._link)) return (1. / N) * prox(N*upf, self._rho, self._y, w=self._weights, inv_link=self._eval_inv_link, p=p) def predict(self, X): """Apply fitted model to features. Parameters ---------- X : pandas dataframe Data for which we wish to predict the response. The column names must correspond to the names of the features used to fit the model. X may have extra columns corresponding to features not in the model; these are simply ignored. Where applicable, the data should be "pre-transformation", since this code will apply any transformations specified while defining the model. Returns ------- mu : array Predicted mean response for each data point. """ if not self._fitted: raise AttributeError('Model not yet fit.') num_points, m = X.shape eta = np.full((num_points,), self._offset) for name, feature in self._features.iteritems(): eta += feature.predict(X[name].values) return self._eval_inv_link(eta) def confidence_intervals(self, X, prediction=False, width=0.95): """Confidence intervals on predictions. NOT YET IMPLEMENTED There are two notions of confidence intervals that are appropriate. The first is a confidence interval on mu, the mean response. This follows from the uncertainty associated with the fit model. The second is a confidence interval on observations of this model. The distinction is best understood by example. For a Gaussian family, the model might be a perfect fit to the data, and we may have billions of observations, so we know mu perfectly. Confidence intervals on the mean response would be very small. But the response is Gaussian with a non-zero variance, so observations will in general still be spread around the mean response. A confidence interval on the prediction would be larger. Now consider a binomial family. The estimated mean response will be some number between 0 and 1, and we can estimate a confidence interval for that mean. But the observed response is always either 0 or 1, so it doesn't make sense to talk about a confidence interval on the prediction (except in some pedantic sense perhaps). Note that if we are making multiple predictions, it makes sense to talk about a "global" set of confidence intervals. Such a set has the property that *all* predictions fall within their intervals with specified probability. This function does not compute global confidence intervals! Instead each confidence interval is computed "in vacuo". Parameters ---------- X : pandas dataframe Data for which we wish to predict the response. The column names must correspond to the names of the features used to fit the model. X may have extra columns corresponding to features not in the model; these are simply ignored. Where applicable, the data should be "pre-transformation", since this code will apply any transformations specified while defining the model. prediction : boolean Specifies whether to return a confidence interval on the mean response or on the predicted response. (See above.) Defaults to False, leading to a confidence interval on the mean response. width : float between 0 and 1 Desired confidence width. Defaults to 0.95. Returns ------- mu : (n x 2) array Lower and upper bounds on the confidence interval associated with each prediction. """ pass def plot(self, name, true_fn=None): """Plot the component of the modelf for a particular feature. Parameters ---------- name : str Name of feature (must be a feature in the model). true_fn : function or None (optional) Function representing the "true" relationship between the feature and the response. Returns ------- (nothing) """ self._features[name]._plot(true_fn=true_fn) def deviance(self, X=None, y=None, covariate_class_sizes=None, w=None): """Deviance This function works in one of two ways: Firstly, it computes the deviance of the model, defined as 2 * \phi * (\ell(y; y) - \ell(\mu; y)) where \phi is the dispersion (which is only in this equation to cancel out the denominator of the log-likelihood), \ell(y; y) is the log-likelihood of the model that fits the data perfectly, and \ell(\mu; y) is the log-likelihood of the fitted model on the data used to fit the model. This is the quantity we minimize when fitting the model. Secondly, it computes the deviance of the model on arbitrary data sets. This can be used in conjunction with Cross Validation to choose the smoothing parameter by minimizing the deviance on the hold-out set. Parameters ---------- X : pandas dataframe (optional) Dataframe of features. The column names must correspond to the names of features added to the model. (See .predict()). Only applicable for the second use case described above. y : array (optional) Response. Only applicable for the second use case. covariate_class_sizes : array (optional) Array of covariate class sizes. w : array (optional) Weights for observations. Only applicable for the second use case, but optional even then. Returns ------- D : float The deviance of the model. """ if X is None or y is None: y = self._y mu = self._eval_inv_link(self._num_features * self.f_bar) w = self._weights if self._has_covariate_classes: m = self._covariate_class_sizes else: m = 1. else: mu = self.predict(X) if covariate_class_sizes is None: m = covariate_class_sizes else: m = 1. if self._family == 'normal': y_minus_mu = y - mu if w is None: return y_minus_mu.dot(y_minus_mu) else: return w.dot(y_minus_mu * y_minus_mu) elif self._family == 'binomial': if w is None: return -2. * np.sum( y * np.log(mu) + (m - y) * np.log1p(-mu) ) else: return -2. * w.dot( y * np.log(mu) + (m - y) * np.log1p(-mu) ) elif self._family == 'poisson': if w is None: return 2. * np.sum(y * np.log(y / mu) - (y - mu)) else: return 2. * w.dot(y * np.log(y / mu) - (y - mu)) elif self._family == 'gamma': if w is None: return 2. * np.sum(-1. * np.log(y / mu) + (y - mu) / mu) else: return 2. * w.dot(-1. * np.log(y / mu) + (y - mu) / mu) elif self._family == 'inverse_gaussian': if w is None: return np.sum( (y - mu) * (y - mu) / (mu * mu * y) ) else: return w.dot( (y - mu) * (y - mu) / (mu * mu * y) ) def dispersion(self, formula='deviance'): """Dispersion Returns the dispersion associated with the model. Depending on the model family and whether the dispersion was specified by the user, the dispersion may or may not be known a priori. This function will estimate this parameter when appropriate. There are different ways of estimating this parameter that may be appropriate for different kinds of families. The current implementation is based on the deviance, as in Eqn 3.10 on p. 110 of GAMr. As discussed in that section, this tends not to work well for Poisson data (with overdispersion) when the mean response is small. Alternatives are offered in that section, but I have not yet implemented them. This is not terribly relevant for the current implementation since overdispersion is not supported! (When overdispersion is not present, the dispersion of the Poisson is exactly 1.) My eventual hope is to understand the appropriate methods for all the different circumstances and have intelligent defaults that can be overridden by opinionated users. Parameters ---------- formula : str Formula for the dispersion. Options include: 'deviance' (default) 'pearson' 'fletcher' """ if self._family == 'normal': if self._known_dispersion: return self._dispersion else: sigma2 = self.deviance() / (self._num_obs - self.dof()) return sigma2 elif self._family == 'binomial': if self._known_dispersion: return self._dispersion elif self._estimate_overdispersion: return self._binomial_overdispersion() else: return 1. elif self._family == 'poisson': return 1. elif self._family == 'gamma': if self._known_dispersion: return self._dispersion else: return _gamma_dispersion(self.dof(), self.deviance(), self._num_obs) # This equation is a first-order approximation valid when nu is # large (see Section 8.3.6 of [GLM]) #Dbar = self.deviance() / self._num_obs #return Dbar * (6. + Dbar) / (6. + 2. * Dbar) elif self._family == 'inverse_gaussian': if self._known_dispersion: return self._dispersion else: sigma2 = self.deviance() / (self._num_obs - self.dof()) return sigma2 def _binomial_overdispersion(self, formula=None): """Over-Dispersion Parameters ---------- formula : str Which formula to use, either 'replication' or 'pearson'. See Notes. Returns ------- sigma2 : float Estimate of over-dispersion. This is also saved as the self._dispersion parameter so we only calculate this once regardless of how many times this function is called. Notes ----- When using covariate classes, the observed variance may exceed the baseline for the family due to clustering in the population. See GLM for motivation. That text gives two methodologies for estimating over-dispersion. When there are no covariate classes (multiple observations with identical features), estimating over-dispersion is not possible. The most reliable assessment of over-dispersion is only possible when there is replication amongst the covariate classes. This is best illustrated through example. Suppose we have data on patients from two hospitals as shown in the table below. Note that there are 3 rows corresponding to Men in hospital 1. These entries could of course be pooled to give the total patients and survivors for this covariate class, but because they have not, it permits us to estimate over-dispersion more reliably. Gender Hospital Patients Survivors M 1 30 15 M 1 40 19 M 1 35 15 F 1 10 8 M 2 10 3 M 2 18 6 F 2 40 30 Because we are building a model based on gender and hospital alone, we are assuming that all three entries are drawn from the same binomial distribution. We could actually test that hypothesis using, for example, Welch's t-Test. If the result indicates a significant departure from the null hypothesis, there must be some (unobserved) explanation for different survival rates. Perhaps the repeated entries correspond to different doctors, with some doctors being more effective than others. Or perhaps the multiple entries refer to different time periods, like before and after a new treatment was instituted. Regardless, we can quantify the additional variance and use it to make (hopefully) more accurate confidence intervals. When replication is present, we take the following approach, per GLM. Suppose a particular covariate class (e.g. Gender=M, Hospital=1) has r replicates. Across all r replicates, determine the observed success rate, pi. In our example, we have 105 patients and 49 survivors, for a total survival rate of pi = 0.47. Next we compute the variance on r-1 DOF: 1 r (y_j - m_j * pi)^2 s^2 = --- \sum ------------------ r-1 j=1 m_j pi * (1 - pi) where y_j is the number of successes in the jth replicate, m_j is the number of trials in the jth replicate, and s^2 is estimated variance. Per GLM, this is an unbiased estimate of the dispersion parameter. Filling in our specific numbers, we get s^2 = 0.17, indicating under-dispersion. (Important note: these are made up numbers, so there is actually more consistency in the data than would be exhibited from a true binomial model. Over-dispersion is more common than under-dispersion.) Each covariate class with replication can be used to derive an estimate of the dispersion parameter. If we expect the dispersion to be independent of the covariate classes (which may or may not be true), we can pool these estimates, weighted by the degree of replication. If the kth covariate class has r_k replicates and dispersion estimate s_k^2, the overall estimate of dispersion is: \sum_k (r_k - 1) * s_k^2 s^2 = ------------------------- \sum_k (r_k - 1) Another important note: the above formula is *not* present in GLM. That text just says to pool the estimates, but does not specify how. This approach makes sense to me, but that doesn't make it correct! When replication is not present, or even if the degree of replication is small, the above methodology breaks down. Instead, GLM advocates the use of a Pearson-residual based approach. If pi_j is the model prediction for the jth covariate class, then we estimate dispersion as: 1 (y_j - m_j * pi_j)^2 s^2 = ----- \sum ----------------------- n - p j m_j * pi_j * (1 - pi_j) This is similar to the replicate-based formula, but we are using the model prediction for pi_j instead of the pooled observations, and we are using the n-p as the error DOF instead of the number of replicates. This methodology still breaks down when the sizes of the covariate classes, m_j, are small. In order to use the replicate-based formula, there must be at least one covariate class exhibiting replication, and the degree of replication must be at least two. If these conditions are not met, and the user dictates that we use the replicate-based formula, we simply ignore that directive and use the Pearson-based approach. (It might be best to issue a warning in this case, but we do not do that.) If this function is called without specifying which methodology to use, we use the following criteria in assessing whether there is enough replication to use the first approach. First, there must be at least two covariate classes exhibiting replication. Second, the degree of replication of the most-replicated covariate class must be at least 3. Finally, the total replication degrees of freedom must be at least 10. For example, in the example data set above, there are two covariate classes exhibiting replication: Males in Hospital 1, and Males in Hospital 2, with 3 and 2 degrees of replication, respectively. The degree of replication of the most-replicate covariate class is therefore equal to 3. The degrees of freedom are (2-1) + (3-1) = 3, which is below the threshold of 10. We would therefore use the Pearson-based formula in this case. These criteria are completely arbitrary! I need to do more research to determine the appropriate criteria. """ if not self._has_covariate_classes: return 1. min_cc_replicates = 1 min_replication = 2 des_cc_replicates = 2 des_replication = 3 des_replication_dof = 10 # Determine degree of replication # # To use the replication formula, we need at least one # covariate class with replication, and that covariate class # needs replication of at least 2. It might make sense to use # a more stringent set of criteria, but this is enough for # now. # # The way we decide whether two observations have the same # covariate class is by encoding the covariate class by an # index. Each categorical feature has already indexed each # category by an internal integer between 0 and n_k - 1, where # n_k is the number of categories of the kth feature. (None of # this is applicable unless all the features are categorical. # # We use these internal indices along with the numbers of # categories in conjunction with the numpy ravel_multi_index # function to map a tuple of category indices into a single # integer between 0 and the the product of all category sizes # (minus 1). # # We need to take care to loop over the features in a # consistent order, so we create the fnames array just to give # an arbitrary but consistent ordering. r = {} covariate_class = np.zeros((self._num_obs,)) fnames = self._features.keys() for i in range(self._num_obs): multi_index = [] dims = [] for fname in fnames: cindex, csize = self._features[fname].category_index(i) multi_index.append(cindex) dims.append(csize) cci = np.ravel_multi_index(multi_index, dims) covariate_class[i] = cci r[cci] = r.get(cci, 0) + 1 num_cc_with_replicates = 0 max_replication = 0 replication_dof = 0 for j in r.values(): if j > 1: num_cc_with_replicates += 1 replication_dof += j - 1 if j > max_replication: max_replication = j if ((num_cc_with_replicates >= min_cc_replicates and max_replication >= min_replication)): has_replication = True else: has_replication = False if ((num_cc_with_replicates >= des_cc_replicates and max_replication >= des_replication and replication_dof >= des_replication_dof)): has_desired_replication = True else: has_desired_replication = False if formula is None: if has_desired_replication: formula = 'replication' else: formula = 'pearson' if has_replication and formula == 'replication': trials = {} successes = {} # Initial loop to pool trials/successes. for i in range(self._num_obs): cci = covariate_class[i] trials[cci] = trials.get(cci, 0) + self._covariate_class_sizes[i] successes[cci] = successes.get(cci, 0) + self._y[i] # Final loop to compute dispersion s2 = 0. for i in range(self._num_obs): cci = covariate_class[i] pi = float(successes[cci]) / trials[cci] num = self._y[i] - self._covariate_class_sizes[i] * pi denom = self._covariate_class_sizes[i] * pi * (1 - pi) s2 += num * num / denom # Divide by the error DOF s2 /= replication_dof self._known_dispersion = True self._dispersion = s2 return s2 else: mu = self._eval_inv_link(self._num_features * self.f_bar) m = self._covariate_class_sizes bl_var = np.multiply(mu, 1. - mu) res = self._y - np.multiply(m, mu) num = np.multiply(res, res) denom = np.multiply(m, bl_var) n_minus_p = self._num_obs - self.dof() s2 = np.sum(np.divide(num, denom)) / n_minus_p self._known_dispersion = True self._dispersion = s2 return s2 def dof(self): """Degrees of Freedom Returns the degrees of freedom associated with this model. Simply adds up the degrees of freedom associated with each feature. """ dof = 1. # Affine factor for name, feature in self._features.iteritems(): dof += feature.dof() return dof def aic(self): """Akaike Information Criterion Returns the AIC for the fitted model, useful for choosing smoothing parameters. The AIC we compute is actually off by a constant factor, making it easier to compute without detracting from its role in model selection. Different authors seem to throw in multiplicative or additive factors willy-nilly since it doesn't affect model selection. """ p = self.dof() if not self._known_dispersion: # If we are estimating the dispersion, we need to # add one to the DOF. p += 1 # Note that the deviance is twice the dispersion times the # log-likelihood, so no factor of two required there. return self.deviance() / self.dispersion() + 2. * p # return (self.deviance() / self._num_obs # + 2. * p * self.dispersion() / self._num_obs) def aicc(self): # Eqn 6.32 on p. 304 of [GAMr] pass def ubre(self, gamma=1.0): """Un-Biased Risk Estimator Returns the Un-Biased Risk Estimator as discussed in Sections 6.2.1 and 6.2.5 of [GAMr]. This can be used for choosing the smoothing parameter when the dispersion is known. As discussed in Section 6.2.5 of [GAMr], sometimes it is helpful to force smoother fits by exaggerating the effective degrees of freedom. In that case, a value of gamma > 1. may be desirable. """ return self.deviance() + 2. * gamma * self.dispersion() * self.dof() def gcv(self, gamma=1.0): """Generalized Cross Validation This function returns the Generalized Cross Validation (GCV) score, which can be used for choosing the smoothing parameter when the dispersion is unknown. As discussed in Section 6.2.5 of [GAMr], sometimes it is helpful to force smoother fits by exaggerating the effective degrees of freedom. In that case, a value of gamma > 1. may be desirable. """ denom = self._num_obs - gamma * self.dof() return self._num_obs * self.deviance() / (denom * denom) def summary(self): """Print summary statistics associated with fitted model. Prints statistics for the overall model, as well as for each individual feature (see the __str__() function in each feature type for details about what is printed there). For the overall model, the following are printed: phi: Estimated dispersion parameter. Omitted if specified or if it is known for the Family (e.g. Poisson). edof: Estimated degrees of freedom. Deviance: The difference between the log-likelihood of the model that fits the data perfectly and that of the fitted model, times twice the dispersion. AIC: Akaike Information Criterion. AICc: AIC with correction for finite data sets. UBRE: Unbiased Risk Estimator (if dispersion is known). GCV: Generalized Cross Validation (if dispersion is estimated). For more details on these parameters, see the documentation in the corresponding functions. It may also be helpful to include an R^2 value where appropriate, and perhaps a p-value for the model against the null model having just the affine term. It would also be nice to have confidence intervals at least on the estimated dispersion parameter. """ print 'Model Statistics' print '----------------' if not self._known_dispersion: print 'phi: {0:0.06g}'.format(self.dispersion()) print 'edof: {0:0.0f}'.format(self.dof()) print 'Deviance: {0:0.06g}'.format(self.deviance()) print 'AIC: {0:0.06g}'.format(self.aic()) #print 'AICc: {0:0.06g}'.format(aicc) if self._known_dispersion: print 'UBRE: {0:0.06g}'.format(self.ubre()) else: print 'GCV: {0:0.06g}'.format(self.gcv()) print '' print 'Features' print '--------' for name, feature in self._features.iteritems(): print feature.__str__()
41.429045
96
0.595534
import sys import pickle import multiprocessing as mp import numpy as np import scipy.special as special import scipy.stats as stats import scipy.linalg as linalg from matplotlib import pyplot as plt from .feature import _Feature from .categorical_feature import _CategoricalFeature from .linear_feature import _LinearFeature from .spline_feature import _SplineFeature import proximal_operators as po FAMILIES = ['normal', 'binomial', 'poisson', 'gamma', 'exponential', 'inverse_gaussian' ] LINKS = ['identity', 'logistic', 'probit', 'complementary_log_log', 'log', 'reciprocal', 'reciprocal_squared' ] FAMILIES_WITH_KNOWN_DISPERSIONS = {'binomial': 1, 'poisson': 1 } CANONICAL_LINKS = {'normal': 'identity', 'binomial': 'logistic', 'poisson': 'log', 'gamma': 'reciprocal', 'inverse_gaussian': 'reciprocal_squared' } def _plot_convergence(prim_res, prim_tol, dual_res, dual_tol, dev): """Plot convergence progress. We deem the algorithm to have converged when the prime and dual residuals are smaller than tolerances which are themselves computed based on the data as in [ADMM]. Some analysts prefer to claim convergence when changes to the deviance (a measure of goodness of fit). Thus we plot that as well. Specifically, we plot, on a log scale, dev - dev_final, where dev_final is the deviance of the final model. We add 1e-10 just to avoid taking the logarithm of zero, which is completely arbitrary but makes the plot look acceptable. Parameters ---------- prim_res : array Array of prime residuals after each iteration. prim_tol : array Array of prime tolerances after each iteration. dual_res : array Array of dual residuals after each iteration. dual_tol : array Array of dual tolerances after each iteration. dev : array Array of deviances after each iteration Returns ------- (nothing) """ fig = plt.figure(figsize=(12., 10.)) ax = fig.add_subplot(211) ax.plot(range(len(prim_res)), prim_res, 'b-', label='Primal Residual') ax.plot(range(len(prim_tol)), prim_tol, 'b--', label='Primal Tolerance') ax.plot(range(len(dual_res)), dual_res, 'r-', label='Dual Residual') ax.plot(range(len(dual_tol)), dual_tol, 'r--', label='Dual Tolerance') ax.set_yscale('log') plt.xlabel('Iteration', fontsize=24) plt.ylabel('Residual', fontsize=24) plt.legend(fontsize=24, loc=3) ax = fig.add_subplot(212) ax.plot(range(len(dev)), (dev - dev[-1]) + 1e-10, 'b-', label='Deviance') ax.set_yscale('log') plt.xlabel('Iteration', fontsize=24) plt.ylabel('Deviance Suboptimality', fontsize=24) plt.gcf().subplots_adjust(bottom=0.1) plt.gcf().subplots_adjust(left=0.1) plt.show() def _feature_wrapper(f): """Wrapper for feature optimization. This is a wrapper for use with multi-threaded versions. Unfortunately Python threads are *terrible*, so this doesn't actually get used. Parameters ------ f : list Array of inputs. f[0] is the name of the feature. f[1] is the feature object itself. f[2] is N * fpumz (the vector input to the feature during optimization). f[3] is the ADMM parameter, rho. Returns ------- name : str The name of the feature. (The same as the input.) f_j : array The array of fitted values returned by the feature. """ return f[0], f[1].optimize(f[2], f[3]) def _gamma_dispersion(dof, dev, num_obs): """Gamma dispersion. This function estimates the dispersion of a Gamma family with p degrees of freedom and deviance D, and n observations. The dispersion nu is that number satisfying 2*n * (log nu - psi(nu)) - p / nu = D We use Newton's method with a learning rate to solve this nonlinear equation. Parameters ---------- dof : float Degrees of freedom dev : float Deviance num_obs : int Number of observations Returns ------- nu : float Estimated dispersion """ beta = 0.1 tol = 1e-6 max_its = 100 nu = 1. for i in range(max_its): num = 2. * num_obs * (np.log(nu) - special.psi(nu)) - dof / nu - dev denom = 2. * num_obs * (1. / nu - special.polygamma(1, nu)) + dof / (nu * nu) dnu = num / denom nu -= dnu * beta if abs(dnu) < tol: return nu else: raise ValueError('Could not estimate gamma dispersion.') class GAM: def __init__(self, family=None, link=None, dispersion=None, estimate_overdispersion=False, name=None, load_from_file=None): """Generalized Additive Model This is the constructor for a Generalized Additive Model. References ---------- [glmnet] glmnet (R package): https://cran.r-project.org/web/packages/glmnet/index.html This is the standard package for GAMs in R and was written by people much smarter than I am! [pygam] pygam (Python package): https://github.com/dswah/pyGAM This is a library in Python that does basically the same thing as this script, but in a different way (not using ADMM). [GLM] Generalized Linear Models by McCullagh and Nelder The standard text on GLMs. [GAM] Generalized Additive Models; by Hastie and Tibshirani The book by the folks who invented GAMs. [ESL] The Elements of Statistical Learning; by Hastie, Tibshirani, and Friedman. Covers a lot more than just GAMs. [GAMr] Generalized Additive Models: an Introduction with R; by Wood. Covers more implementation details than [GAM]. [ADMM] Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers; by Boyd, Parikh, Chu, Peleato, and Eckstein. A mouthful, a work of genius. [GAMADMM] A Distributed Algorithm for Fitting Generalized Additive Models; by Chu, Keshavarz, and Boyd Forms the basis of our approach, the inspiration for this package! Parameters ---------- family : str or None (default None) Family of the model. Currently supported families include: 'normal' (for continuous responses), 'binomial' (for binary responses), 'poisson' (for counts), 'gamma' (still in progress), 'inverse_gaussian' (still in progress). Not currently supported families that could be supported include Multinomial models (ordinal and nominal) and proportional hazards models. Required unless loading an existing model from file (see load_from_file). link : str or None (optional) Link function associated with the model. Supported link functions include: Link Canonical For Family 'identity' 'normal' 'logistic' 'binomial' 'log' 'poisson' 'reciprocal' 'gamma' 'reciprocal_squared' 'inverse_gaussian' Other links worth supporting include probit, log-log and complementary log-log link functions. If not specified, the canonical link will be used, but non- canonical links are still permitted. Certain link/family combinations result in a non-convex problem and convergence is not guaranteed. dispersion : float or None (optional) Dispersion parameter associated with the model. Certain families (binomial, poisson) have dispersion independent of the data. Specifying the dispersion for these families does nothing. In other instances, the dispersion is typically unknown and must be estimated from the data. If the dispersion is known, it can be specified here which will reduce the uncertainty of the model. estimate_overdispersion : boolean (optional) Flag specifying whether to estimate over-dispersion for Binomial and Poisson (not yet implemented) families. Is only possible when covariate classes are present and have at least modest size. See [GLM, S4.5] for details. Defaults to False. name : str or None (optional) Name for model, to be used in plots and in saving files. load_from_file : str or None (optional) This module uses an iterative approach to fitting models. For complicated models with lots of data, each iteration can take a long time (though the number of iterations is typically less than 100). If the user wishes to pause after the end of an iteration, they can pick up where the left off by saving results (see the save_flag in .fit) and loading them to start the next iterations. Specifying this option supercedes all other parameters. Returns ------- mdl : Generalized Additive Model object """ if load_from_file is not None: self._load(load_from_file) return if family is None: raise ValueError('Family not specified.') elif family not in FAMILIES: raise ValueError('{} family not supported'.format(family)) elif family == 'exponential': self._family = 'gamma' dispersion = 1. else: self._family = family if link is None: self._link = CANONICAL_LINKS[family] elif link in LINKS: self._link = link else: raise ValueError('{} link not supported'.format(link)) if dispersion is not None: self._known_dispersion = True self._dispersion = dispersion elif (self._family in FAMILIES_WITH_KNOWN_DISPERSIONS.keys() and not estimate_overdispersion): self._known_dispersion = True self._dispersion = FAMILIES_WITH_KNOWN_DISPERSIONS[self._family] else: self._known_dispersion = False if self._link == 'identity': self._eval_link = lambda x: x self._eval_inv_link = lambda x: x elif self._link == 'logistic': self._eval_link = lambda x: np.log( x / (1. - x) ) self._eval_inv_link = lambda x: np.exp(x) / (1 + np.exp(x)) elif self._link == 'probit': self._eval_link = lambda x: stats.norm.ppf(x) self._eval_inv_link = lambda x: stats.norm.cdf(x) elif self._link == 'complementary_log_log': self._eval_link = lambda x: np.log(-np.log(1. - x)) self._eval_inv_link = lambda x: 1. - np.exp(-np.exp(x)) elif self._link == 'log': self._eval_link = lambda x: np.log(x) self._eval_inv_link = lambda x: np.exp(x) elif self._link == 'reciprocal': self._eval_link = lambda x: 1. / x self._eval_inv_link = lambda x: 1. / x elif self._link == 'reciprocal_squared': self._eval_link = lambda x: 1. / (x * x) self._eval_inv_link = lambda x: 1. / np.sqrt(x) self._estimate_overdispersion = estimate_overdispersion self._features = {} self._offset = 0.0 self._num_features = 0 self._fitted = False self._name = name def _save(self): """Save state. Save the model to file to make predictions later, or continue a fitting session. """ mv = {} mv['family'] = self._family mv['link'] = self._link mv['known_dispersion'] = self._known_dispersion if self._known_dispersion: mv['dispersion'] = self._dispersion mv['estimate_overdispersion'] = self._estimate_overdispersion mv['offset'] = self._offset mv['num_features'] = self._num_features mv['fitted'] = self._fitted mv['name'] = self._name features = {} for name, feature in self._features.iteritems(): features[name] = {'type': feature.__type__, 'filename': feature._filename } mv['features'] = features mv['num_obs'] = self._num_obs mv['y'] = self._y mv['weights'] = self._weights mv['has_covariate_classes'] = self._has_covariate_classes if self._has_covariate_classes: mv['covariate_class_sizes'] = self._covariate_class_sizes mv['f_bar'] = self.f_bar mv['z_bar'] = self.z_bar mv['u'] = self.u mv['prim_res'] = self.prim_res mv['dual_res'] = self.dual_res mv['prim_tol'] = self.prim_tol mv['dual_tol'] = self.dual_tol mv['dev'] = self.dev filename = '{0:s}_model.pckl'.format(self._name) f = open(filename, 'w') pickle.dump(mv, f) f.close() def _load(self, filename): """Load state. Load a model from file to make predictions. """ f = open(filename) mv = pickle.load(f) f.close() self._filename = filename self._family = mv['family'] self._link = mv['link'] self._known_dispersion = mv['known_dispersion'] if self._known_dispersion: self._dispersion = mv['dispersion'] self._estimate_overdispersion = mv['estimate_overdispersion'] self._offset = mv['offset'] self._num_features = mv['num_features'] self._fitted = mv['fitted'] self._name = mv['name'] self._features = {} features = mv['features'] for (name, feature) in features.iteritems(): if feature['type'] == 'categorical': self._features[name] = _CategoricalFeature(load_from_file=feature['filename']) elif feature['type'] == 'linear': self._features[name] = _LinearFeature(load_from_file=feature['filename']) elif feature['type'] == 'spline': self._features[name] = _SplineFeature(load_from_file=feature['filename']) else: raise ValueError('Invalid feature type') self._num_obs = mv['num_obs'] self._y = mv['y'] self._weights = mv['weights'] self._has_covariate_classes = mv['has_covariate_classes'] if self._has_covariate_classes: self._covariate_class_sizes = mv['covariate_class_sizes'] self.f_bar = mv['f_bar'] self.z_bar = mv['z_bar'] self.u = mv['u'] self.prim_res = mv['prim_res'] self.dual_res = mv['dual_res'] self.prim_tol = mv['prim_tol'] self.dual_tol = mv['dual_tol'] self.dev = mv['dev'] if self._link == 'identity': self._eval_link = lambda x: x self._eval_inv_link = lambda x: x elif self._link == 'logistic': self._eval_link = lambda x: np.log( x / (1. - x) ) self._eval_inv_link = lambda x: np.exp(x) / (1 + np.exp(x)) elif self._link == 'probit': self._eval_link = lambda x: stats.norm.ppf(x) self._eval_inv_link = lambda x: stats.norm.cdf(x) elif self._link == 'complementary_log_log': self._eval_link = lambda x: np.log(-np.log(1. - x)) self._eval_inv_link = lambda x: 1. - np.exp(-np.exp(x)) elif self._link == 'log': self._eval_link = lambda x: np.log(x) self._eval_inv_link = lambda x: np.exp(x) elif self._link == 'reciprocal': self._eval_link = lambda x: 1. / x self._eval_inv_link = lambda x: 1. / x elif self._link == 'reciprocal_squared': self._eval_link = lambda x: 1. / (x * x) self._eval_inv_link = lambda x: 1. / np.sqrt(x) def add_feature(self, name, type, transform=None, rel_dof=None, regularization=None): """Add a feature Add a feature to a Generalized Additive Model. (An implicit constant feature is always included, representing the overall average response.) Parameters ---------- name : str Name for feature. Used internally to keep track of features and is also used when saving files and in plots. type : str Type of feature. Currently supported options include: 'categorical' (for categorical variables) 'linear' (for variables with a linear contribution to the response) 'spline' (for variables with a potentially nonlinear contribution to the response). Other types of features worth supporting include piecewise constant functions and monotonic functions. Those might end up being regularization terms. transform : function or None Optional transform applied to feature data, saving the user from repetitive boilerplate code. Any function may be used; it is applied to data provided during fitting and prediction. Common options might include np.log, np.log1p, or np.sqrt. The user may wish to start with a base feature like 'age' and use derived features 'age_linear', 'age_quadratic' to permit quadratic models for that feature, with potentially different regularization applied to each. rel_dof : float or None Relative degrees of freedom. Applicable only to spline features. The degrees of freedom associated with a spline represent how "wiggly" it is allowed to be. A spline with two degrees of freedom is just a line. (Actually, since these features are constrained to have zero mean response over the data, linear features only have one degree of freedom.) The relative degrees of freedom are used to specify the baseline smoothing parameter (lambda) associated with a feature. When the model is fit to data, the user can specify an overall smoothing parameter applied to all features to alter the amount of regularization in the entire model. Thus the actual degrees of freedom will vary based on the amount of smoothing. The idea is that the analyst may wish to permit some features to be more wiggly than others. By default, all splines have 4 relative degrees of freedom. Regularization of any feature effectively reduces the degrees of freedom, and so this term is potentially applicable, but that is not yet supported. regularization : dictionary or None Dictionary specifying the regularization applied to this feature. Different types of features support different types of regularization. Splines implicitly only support regularization of the wiggliness via a C2 smoothness penalty. That is controlled via the rel_dof. Other features have more diverse options described in their own documentation. Returns ------- (nothing) """ if type == 'categorical': f = _CategoricalFeature(name, regularization=regularization) elif type == 'linear': f = _LinearFeature(name, transform, regularization=regularization) elif type == 'spline': f = _SplineFeature(name, transform, rel_dof) else: raise ValueError('Features of type {} not supported.'.format(type)) self._features[name] = f self._num_features += 1 def fit(self, X, y, covariate_class_sizes=None, weights=None, optimizer='admm', smoothing=1., save_flag=False, verbose=False, plot_convergence=False, max_its=100): """Fit a Generalized Additive Model to data. Note regarding binomial families: many data sets include multiple observations having identical features. For example, imagine a data set with features 'gender', and 'country' and binary response indicating whether the person died (morbid but common in biostatistics). The data might look like this: gender country patients survivors M USA 50 48 F USA 70 65 M CAN 40 38 F CAN 45 43 This still describes a binomial family, but in a more compact format than specifying each individual user. We eventually want to support this more compact format, but we do not currently! In this context, it is important to check for over-dispersion (see [GLM]), and I need to learn more first. In the current implementation, we assume that there is no over-dispersion, and that the number of users having the same set of features is small. Parameters ---------- X : pandas dataframe Dataframe of features. The column names must correspond to the names of features added to the model. X may have extra columns corresponding to features not included in the model; these are simply ignored. Where applicable, the data should be "pre-transformation", since this code will apply any transformations specified in .add_feature. y : array Response. Depending on the model family, the response may need to be in a particular form (for example, for a binomial family, the y's should be either 0 or 1), but this is not checked anywhere! covariate_class_sizes : array or None. If observations are grouped into covariance classes, the size of those classes should be listed in this input. w : array Weights applied to each observation. This is effectively specifying the dispersion of each observation. optimizer : string We use the Alternating Direction Method of Multipliers ('admm') to fit the model. We may eventually support more methods, but right now this option does nothing. smoothing : float Smoothing to apply to entire model, used in conjunction with other regularization parameters. That is, whatever regularization is used for the various features, is scaled by this term, allowing the user to set the overall smoothing by Cross Validation or whatever they like. This allows the user to specify different regularization for each feature, while still permitting a one-dimensional family of models corresponding to different amounts of regularization. Defaults to 1., leaving the regularization as specified in .add_feature(). save_flag : boolean Specifies whether to save intermediate results after each iteration. Useful for complicated models with massive data sets that take a while to fit. If the system crashes during the fit, the analyst can pick up where they left off instead of starting from scratch. Defaults to False. verbose : boolean Specifies whether to print mildly useful information to the screen during the fit. Defaults to False. plot_convergence : boolean Specifies whether to plot the convergence graph at the end. (I suspect only Convex Optimization nerds like me want to see this.) Defaults to False. max_its : integer Maximum number of iterations. Defaults to 100. Returns ------- (nothing) """ if save_flag and self._name is None: msg = 'Cannot save a GAM with no name.' msg += ' Specify name when instantiating model.' raise ValueError(msg) if len(X) != len(y): raise ValueError('Inconsistent number of observations in X and y.') num_threads = 1 self._rho = 0.1 eps_abs = 1e-3 eps_rel = 1e-3 # Note that X may include columns that do not correspond to features in our model # (for example, if the user is experimenting with leaving out features to assess # importance). Thus, the real number of features is self._num_features, not # num_features as in the next line. self._num_obs, num_features = X.shape self._y = y.flatten() self._weights = weights if covariate_class_sizes is not None: self._has_covariate_classes = True self._covariate_class_sizes = covariate_class_sizes mean_response = float(np.sum(self._y)) / np.sum(self._covariate_class_sizes) self._offset = self._eval_link(mean_response) else: self._has_covariate_classes = False self._covariate_class_sizes = None self._offset = self._eval_link(np.mean(self._y)) fj = {} for name, feature in self._features.iteritems(): feature.initialize(X[name].values, smoothing=smoothing, covariate_class_sizes=self._covariate_class_sizes, save_flag=save_flag, save_prefix=self._name) fj[name] = np.zeros(self._num_obs) self.f_bar = np.full((self._num_obs,), self._offset / self._num_features) self.z_bar = np.zeros(self._num_obs) self.u = np.zeros(self._num_obs) self.prim_res = [] self.dual_res = [] self.prim_tol = [] self.dual_tol = [] self.dev = [] z_new = np.zeros(self._num_obs) if num_threads > 1: p = mp.Pool(num_threads) else: p = None for i in range(max_its): if verbose: print 'Iteration {0:d}'.format(i) print 'Optimizing primal variables' fpumz = self._num_features * (self.f_bar + self.u - self.z_bar) fj_new = {} f_new = np.full((self._num_obs,), self._offset) if False: #num_threads > 1: # Getting python to run a for loop in parallel # might as well be impossible :-( args = [(i, self._features[i], fpumz, self._rho) for i in self._features.keys()] results = p.map(_feature_wrapper, args) for i in results: fj_new[i[0]] = i[1] f_new += i[1] else: for name, feature in self._features.iteritems(): if verbose: print 'Optimizing {0:s}'.format(name) fj_new[name] = feature.optimize(fpumz, self._rho) f_new += fj_new[name] f_new /= self._num_features if verbose: print 'Optimizing dual variables' z_new = self._optimize(self.u + f_new, self._num_features, p) self.u += f_new - z_new prim_res = np.sqrt(self._num_features) * linalg.norm(f_new - z_new) dual_res = 0.0 norm_ax = 0.0 norm_bz = 0.0 norm_aty = 0.0 num_params = 0 for name, feature in self._features.iteritems(): dr = ((fj_new[name] - fj[name]) + (z_new - self.z_bar) - (f_new - self.f_bar)) dual_res += dr.dot(dr) norm_ax += fj_new[name].dot(fj_new[name]) zik = fj_new[name] + z_new - f_new norm_bz += zik.dot(zik) norm_aty += feature.compute_dual_tol(self.u) num_params += feature.num_params() dual_res = self._rho * np.sqrt(dual_res) norm_ax = np.sqrt(norm_ax) norm_bz = np.sqrt(norm_bz) norm_aty = np.sqrt(norm_aty) self.f_bar = f_new fj = fj_new self.z_bar = z_new if self._has_covariate_classes: sccs = np.sum(self._covariate_class_sizes) prim_tol = (np.sqrt(sccs * self._num_features) * eps_abs + eps_rel * np.max([norm_ax, norm_bz])) else: prim_tol = (np.sqrt(self._num_obs * self._num_features) * eps_abs + eps_rel * np.max([norm_ax, norm_bz])) dual_tol = np.sqrt(num_params) * eps_abs + eps_rel * norm_aty self.prim_res.append(prim_res) self.dual_res.append(dual_res) self.prim_tol.append(prim_tol) self.dual_tol.append(dual_tol) self.dev.append(self.deviance()) if prim_res < prim_tol and dual_res < dual_tol: if verbose: print 'Fit converged' break else: if verbose: print 'Fit did not converge' if num_threads > 1: p.close() p.join() self._fitted = True if save_flag: self._save() if plot_convergence: _plot_convergence(self.prim_res, self.prim_tol, self.dual_res, self.dual_tol, self.dev) def _optimize(self, upf, N, p=None): """Optimize \bar{z}. Solves the optimization problem: minimize L(N*z) + \rho/2 * \| N*z - N*u - N*\bar{f} \|_2^2 where z is the variable, N is the number of features, u is the scaled dual variable, \bar{f} is the average feature response, and L is the likelihood function which is different depending on the family and link function. This is accomplished via a proximal operator, as discussed in [GAMADMM]: prox_\mu(v) := argmin_x L(x) + \mu/2 * \| x - v \|_2^2 I strongly believe that paper contains a typo in this equation, so we return (1. / N) * prox_\mu (N * (u + \bar{f}) with \mu = \rho instead of \mu = \rho / N as in [GAMADMM]. When implemented as in the paper, convergence was much slower, but it did still converge. Certain combinations of family and link function result in proximal operators with closed form solutions, making this step *very* fast (e.g. 3 flops per observation). Parameters ---------- upf : array Vector representing u + \bar{f} N : integer Number of features. p : Multiprocessing Pool (optional) If multiple threads are available, massive data sets may benefit from solving this optimization problem in parallel. It is up to the individual functions to decide whether to actually do this. Returns ------- z : array Result of the above optimization problem. """ prox = None if self._family == 'normal': if self._link == 'identity': prox = po._prox_normal_identity else: prox = po._prox_normal elif self._family == 'binomial': if self._link == 'logistic': prox = po._prox_binomial_logit else: prox = po._prox_binomial if self._has_covariate_classes: return (1. / N) * prox(N*upf, self._rho, self._y, self._covariate_class_sizes, self._weights, self._eval_inv_link, p=p) elif self._family == 'poisson': if self._link == 'log': prox = po._prox_poisson_log else: prox = po._prox_poisson elif self._family == 'gamma': if self._link == 'reciprocal': prox = po._prox_gamma_reciprocal else: prox = po._prox_gamma elif self._family == 'inverse_gaussian': if self._link == 'reciprocal_squared': prox = po._prox_inv_gaussian_reciprocal_squared else: prox = po._prox_inv_gaussian else: msg = 'Family {0:s} and Link Function {1:s} not (yet) supported.' raise ValueError(msg.format(self._family, self._link)) return (1. / N) * prox(N*upf, self._rho, self._y, w=self._weights, inv_link=self._eval_inv_link, p=p) def predict(self, X): """Apply fitted model to features. Parameters ---------- X : pandas dataframe Data for which we wish to predict the response. The column names must correspond to the names of the features used to fit the model. X may have extra columns corresponding to features not in the model; these are simply ignored. Where applicable, the data should be "pre-transformation", since this code will apply any transformations specified while defining the model. Returns ------- mu : array Predicted mean response for each data point. """ if not self._fitted: raise AttributeError('Model not yet fit.') num_points, m = X.shape eta = np.full((num_points,), self._offset) for name, feature in self._features.iteritems(): eta += feature.predict(X[name].values) return self._eval_inv_link(eta) def confidence_intervals(self, X, prediction=False, width=0.95): """Confidence intervals on predictions. NOT YET IMPLEMENTED There are two notions of confidence intervals that are appropriate. The first is a confidence interval on mu, the mean response. This follows from the uncertainty associated with the fit model. The second is a confidence interval on observations of this model. The distinction is best understood by example. For a Gaussian family, the model might be a perfect fit to the data, and we may have billions of observations, so we know mu perfectly. Confidence intervals on the mean response would be very small. But the response is Gaussian with a non-zero variance, so observations will in general still be spread around the mean response. A confidence interval on the prediction would be larger. Now consider a binomial family. The estimated mean response will be some number between 0 and 1, and we can estimate a confidence interval for that mean. But the observed response is always either 0 or 1, so it doesn't make sense to talk about a confidence interval on the prediction (except in some pedantic sense perhaps). Note that if we are making multiple predictions, it makes sense to talk about a "global" set of confidence intervals. Such a set has the property that *all* predictions fall within their intervals with specified probability. This function does not compute global confidence intervals! Instead each confidence interval is computed "in vacuo". Parameters ---------- X : pandas dataframe Data for which we wish to predict the response. The column names must correspond to the names of the features used to fit the model. X may have extra columns corresponding to features not in the model; these are simply ignored. Where applicable, the data should be "pre-transformation", since this code will apply any transformations specified while defining the model. prediction : boolean Specifies whether to return a confidence interval on the mean response or on the predicted response. (See above.) Defaults to False, leading to a confidence interval on the mean response. width : float between 0 and 1 Desired confidence width. Defaults to 0.95. Returns ------- mu : (n x 2) array Lower and upper bounds on the confidence interval associated with each prediction. """ pass def plot(self, name, true_fn=None): """Plot the component of the modelf for a particular feature. Parameters ---------- name : str Name of feature (must be a feature in the model). true_fn : function or None (optional) Function representing the "true" relationship between the feature and the response. Returns ------- (nothing) """ self._features[name]._plot(true_fn=true_fn) def deviance(self, X=None, y=None, covariate_class_sizes=None, w=None): """Deviance This function works in one of two ways: Firstly, it computes the deviance of the model, defined as 2 * \phi * (\ell(y; y) - \ell(\mu; y)) where \phi is the dispersion (which is only in this equation to cancel out the denominator of the log-likelihood), \ell(y; y) is the log-likelihood of the model that fits the data perfectly, and \ell(\mu; y) is the log-likelihood of the fitted model on the data used to fit the model. This is the quantity we minimize when fitting the model. Secondly, it computes the deviance of the model on arbitrary data sets. This can be used in conjunction with Cross Validation to choose the smoothing parameter by minimizing the deviance on the hold-out set. Parameters ---------- X : pandas dataframe (optional) Dataframe of features. The column names must correspond to the names of features added to the model. (See .predict()). Only applicable for the second use case described above. y : array (optional) Response. Only applicable for the second use case. covariate_class_sizes : array (optional) Array of covariate class sizes. w : array (optional) Weights for observations. Only applicable for the second use case, but optional even then. Returns ------- D : float The deviance of the model. """ if X is None or y is None: y = self._y mu = self._eval_inv_link(self._num_features * self.f_bar) w = self._weights if self._has_covariate_classes: m = self._covariate_class_sizes else: m = 1. else: mu = self.predict(X) if covariate_class_sizes is None: m = covariate_class_sizes else: m = 1. if self._family == 'normal': y_minus_mu = y - mu if w is None: return y_minus_mu.dot(y_minus_mu) else: return w.dot(y_minus_mu * y_minus_mu) elif self._family == 'binomial': if w is None: return -2. * np.sum( y * np.log(mu) + (m - y) * np.log1p(-mu) ) else: return -2. * w.dot( y * np.log(mu) + (m - y) * np.log1p(-mu) ) elif self._family == 'poisson': if w is None: return 2. * np.sum(y * np.log(y / mu) - (y - mu)) else: return 2. * w.dot(y * np.log(y / mu) - (y - mu)) elif self._family == 'gamma': if w is None: return 2. * np.sum(-1. * np.log(y / mu) + (y - mu) / mu) else: return 2. * w.dot(-1. * np.log(y / mu) + (y - mu) / mu) elif self._family == 'inverse_gaussian': if w is None: return np.sum( (y - mu) * (y - mu) / (mu * mu * y) ) else: return w.dot( (y - mu) * (y - mu) / (mu * mu * y) ) def dispersion(self, formula='deviance'): """Dispersion Returns the dispersion associated with the model. Depending on the model family and whether the dispersion was specified by the user, the dispersion may or may not be known a priori. This function will estimate this parameter when appropriate. There are different ways of estimating this parameter that may be appropriate for different kinds of families. The current implementation is based on the deviance, as in Eqn 3.10 on p. 110 of GAMr. As discussed in that section, this tends not to work well for Poisson data (with overdispersion) when the mean response is small. Alternatives are offered in that section, but I have not yet implemented them. This is not terribly relevant for the current implementation since overdispersion is not supported! (When overdispersion is not present, the dispersion of the Poisson is exactly 1.) My eventual hope is to understand the appropriate methods for all the different circumstances and have intelligent defaults that can be overridden by opinionated users. Parameters ---------- formula : str Formula for the dispersion. Options include: 'deviance' (default) 'pearson' 'fletcher' """ if self._family == 'normal': if self._known_dispersion: return self._dispersion else: sigma2 = self.deviance() / (self._num_obs - self.dof()) return sigma2 elif self._family == 'binomial': if self._known_dispersion: return self._dispersion elif self._estimate_overdispersion: return self._binomial_overdispersion() else: return 1. elif self._family == 'poisson': return 1. elif self._family == 'gamma': if self._known_dispersion: return self._dispersion else: return _gamma_dispersion(self.dof(), self.deviance(), self._num_obs) elif self._family == 'inverse_gaussian': if self._known_dispersion: return self._dispersion else: sigma2 = self.deviance() / (self._num_obs - self.dof()) return sigma2 def _binomial_overdispersion(self, formula=None): """Over-Dispersion Parameters ---------- formula : str Which formula to use, either 'replication' or 'pearson'. See Notes. Returns ------- sigma2 : float Estimate of over-dispersion. This is also saved as the self._dispersion parameter so we only calculate this once regardless of how many times this function is called. Notes ----- When using covariate classes, the observed variance may exceed the baseline for the family due to clustering in the population. See GLM for motivation. That text gives two methodologies for estimating over-dispersion. When there are no covariate classes (multiple observations with identical features), estimating over-dispersion is not possible. The most reliable assessment of over-dispersion is only possible when there is replication amongst the covariate classes. This is best illustrated through example. Suppose we have data on patients from two hospitals as shown in the table below. Note that there are 3 rows corresponding to Men in hospital 1. These entries could of course be pooled to give the total patients and survivors for this covariate class, but because they have not, it permits us to estimate over-dispersion more reliably. Gender Hospital Patients Survivors M 1 30 15 M 1 40 19 M 1 35 15 F 1 10 8 M 2 10 3 M 2 18 6 F 2 40 30 Because we are building a model based on gender and hospital alone, we are assuming that all three entries are drawn from the same binomial distribution. We could actually test that hypothesis using, for example, Welch's t-Test. If the result indicates a significant departure from the null hypothesis, there must be some (unobserved) explanation for different survival rates. Perhaps the repeated entries correspond to different doctors, with some doctors being more effective than others. Or perhaps the multiple entries refer to different time periods, like before and after a new treatment was instituted. Regardless, we can quantify the additional variance and use it to make (hopefully) more accurate confidence intervals. When replication is present, we take the following approach, per GLM. Suppose a particular covariate class (e.g. Gender=M, Hospital=1) has r replicates. Across all r replicates, determine the observed success rate, pi. In our example, we have 105 patients and 49 survivors, for a total survival rate of pi = 0.47. Next we compute the variance on r-1 DOF: 1 r (y_j - m_j * pi)^2 s^2 = --- \sum ------------------ r-1 j=1 m_j pi * (1 - pi) where y_j is the number of successes in the jth replicate, m_j is the number of trials in the jth replicate, and s^2 is estimated variance. Per GLM, this is an unbiased estimate of the dispersion parameter. Filling in our specific numbers, we get s^2 = 0.17, indicating under-dispersion. (Important note: these are made up numbers, so there is actually more consistency in the data than would be exhibited from a true binomial model. Over-dispersion is more common than under-dispersion.) Each covariate class with replication can be used to derive an estimate of the dispersion parameter. If we expect the dispersion to be independent of the covariate classes (which may or may not be true), we can pool these estimates, weighted by the degree of replication. If the kth covariate class has r_k replicates and dispersion estimate s_k^2, the overall estimate of dispersion is: \sum_k (r_k - 1) * s_k^2 s^2 = ------------------------- \sum_k (r_k - 1) Another important note: the above formula is *not* present in GLM. That text just says to pool the estimates, but does not specify how. This approach makes sense to me, but that doesn't make it correct! When replication is not present, or even if the degree of replication is small, the above methodology breaks down. Instead, GLM advocates the use of a Pearson-residual based approach. If pi_j is the model prediction for the jth covariate class, then we estimate dispersion as: 1 (y_j - m_j * pi_j)^2 s^2 = ----- \sum ----------------------- n - p j m_j * pi_j * (1 - pi_j) This is similar to the replicate-based formula, but we are using the model prediction for pi_j instead of the pooled observations, and we are using the n-p as the error DOF instead of the number of replicates. This methodology still breaks down when the sizes of the covariate classes, m_j, are small. In order to use the replicate-based formula, there must be at least one covariate class exhibiting replication, and the degree of replication must be at least two. If these conditions are not met, and the user dictates that we use the replicate-based formula, we simply ignore that directive and use the Pearson-based approach. (It might be best to issue a warning in this case, but we do not do that.) If this function is called without specifying which methodology to use, we use the following criteria in assessing whether there is enough replication to use the first approach. First, there must be at least two covariate classes exhibiting replication. Second, the degree of replication of the most-replicated covariate class must be at least 3. Finally, the total replication degrees of freedom must be at least 10. For example, in the example data set above, there are two covariate classes exhibiting replication: Males in Hospital 1, and Males in Hospital 2, with 3 and 2 degrees of replication, respectively. The degree of replication of the most-replicate covariate class is therefore equal to 3. The degrees of freedom are (2-1) + (3-1) = 3, which is below the threshold of 10. We would therefore use the Pearson-based formula in this case. These criteria are completely arbitrary! I need to do more research to determine the appropriate criteria. """ if not self._has_covariate_classes: return 1. min_cc_replicates = 1 min_replication = 2 des_cc_replicates = 2 des_replication = 3 des_replication_dof = 10 r = {} covariate_class = np.zeros((self._num_obs,)) fnames = self._features.keys() for i in range(self._num_obs): multi_index = [] dims = [] for fname in fnames: cindex, csize = self._features[fname].category_index(i) multi_index.append(cindex) dims.append(csize) cci = np.ravel_multi_index(multi_index, dims) covariate_class[i] = cci r[cci] = r.get(cci, 0) + 1 num_cc_with_replicates = 0 max_replication = 0 replication_dof = 0 for j in r.values(): if j > 1: num_cc_with_replicates += 1 replication_dof += j - 1 if j > max_replication: max_replication = j if ((num_cc_with_replicates >= min_cc_replicates and max_replication >= min_replication)): has_replication = True else: has_replication = False if ((num_cc_with_replicates >= des_cc_replicates and max_replication >= des_replication and replication_dof >= des_replication_dof)): has_desired_replication = True else: has_desired_replication = False if formula is None: if has_desired_replication: formula = 'replication' else: formula = 'pearson' if has_replication and formula == 'replication': trials = {} successes = {} for i in range(self._num_obs): cci = covariate_class[i] trials[cci] = trials.get(cci, 0) + self._covariate_class_sizes[i] successes[cci] = successes.get(cci, 0) + self._y[i] s2 = 0. for i in range(self._num_obs): cci = covariate_class[i] pi = float(successes[cci]) / trials[cci] num = self._y[i] - self._covariate_class_sizes[i] * pi denom = self._covariate_class_sizes[i] * pi * (1 - pi) s2 += num * num / denom s2 /= replication_dof self._known_dispersion = True self._dispersion = s2 return s2 else: mu = self._eval_inv_link(self._num_features * self.f_bar) m = self._covariate_class_sizes bl_var = np.multiply(mu, 1. - mu) res = self._y - np.multiply(m, mu) num = np.multiply(res, res) denom = np.multiply(m, bl_var) n_minus_p = self._num_obs - self.dof() s2 = np.sum(np.divide(num, denom)) / n_minus_p self._known_dispersion = True self._dispersion = s2 return s2 def dof(self): """Degrees of Freedom Returns the degrees of freedom associated with this model. Simply adds up the degrees of freedom associated with each feature. """ dof = 1. for name, feature in self._features.iteritems(): dof += feature.dof() return dof def aic(self): """Akaike Information Criterion Returns the AIC for the fitted model, useful for choosing smoothing parameters. The AIC we compute is actually off by a constant factor, making it easier to compute without detracting from its role in model selection. Different authors seem to throw in multiplicative or additive factors willy-nilly since it doesn't affect model selection. """ p = self.dof() if not self._known_dispersion: # If we are estimating the dispersion, we need to # add one to the DOF. p += 1 # Note that the deviance is twice the dispersion times the # log-likelihood, so no factor of two required there. return self.deviance() / self.dispersion() + 2. * p # return (self.deviance() / self._num_obs # + 2. * p * self.dispersion() / self._num_obs) def aicc(self): # Eqn 6.32 on p. 304 of [GAMr] pass def ubre(self, gamma=1.0): """Un-Biased Risk Estimator Returns the Un-Biased Risk Estimator as discussed in Sections 6.2.1 and 6.2.5 of [GAMr]. This can be used for choosing the smoothing parameter when the dispersion is known. As discussed in Section 6.2.5 of [GAMr], sometimes it is helpful to force smoother fits by exaggerating the effective degrees of freedom. In that case, a value of gamma > 1. may be desirable. """ return self.deviance() + 2. * gamma * self.dispersion() * self.dof() def gcv(self, gamma=1.0): """Generalized Cross Validation This function returns the Generalized Cross Validation (GCV) score, which can be used for choosing the smoothing parameter when the dispersion is unknown. As discussed in Section 6.2.5 of [GAMr], sometimes it is helpful to force smoother fits by exaggerating the effective degrees of freedom. In that case, a value of gamma > 1. may be desirable. """ denom = self._num_obs - gamma * self.dof() return self._num_obs * self.deviance() / (denom * denom) def summary(self): """Print summary statistics associated with fitted model. Prints statistics for the overall model, as well as for each individual feature (see the __str__() function in each feature type for details about what is printed there). For the overall model, the following are printed: phi: Estimated dispersion parameter. Omitted if specified or if it is known for the Family (e.g. Poisson). edof: Estimated degrees of freedom. Deviance: The difference between the log-likelihood of the model that fits the data perfectly and that of the fitted model, times twice the dispersion. AIC: Akaike Information Criterion. AICc: AIC with correction for finite data sets. UBRE: Unbiased Risk Estimator (if dispersion is known). GCV: Generalized Cross Validation (if dispersion is estimated). For more details on these parameters, see the documentation in the corresponding functions. It may also be helpful to include an R^2 value where appropriate, and perhaps a p-value for the model against the null model having just the affine term. It would also be nice to have confidence intervals at least on the estimated dispersion parameter. """ print 'Model Statistics' print '----------------' if not self._known_dispersion: print 'phi: {0:0.06g}'.format(self.dispersion()) print 'edof: {0:0.0f}'.format(self.dof()) print 'Deviance: {0:0.06g}'.format(self.deviance()) print 'AIC: {0:0.06g}'.format(self.aic()) #print 'AICc: {0:0.06g}'.format(aicc) if self._known_dispersion: print 'UBRE: {0:0.06g}'.format(self.ubre()) else: print 'GCV: {0:0.06g}'.format(self.gcv()) print '' print 'Features' print '--------' for name, feature in self._features.iteritems(): print feature.__str__()
false
true
f716bfb88f86b0dedbf9b46d2a9ed40caaf4e047
405
py
Python
tests/benchmarkstt/test_modules.py
ioannisNoukakis/benchmarkstt
41074c9b89632e8d9ff8e0ee72187211052bfb04
[ "MIT" ]
1
2019-02-01T10:37:12.000Z
2019-02-01T10:37:12.000Z
tests/benchmarkstt/test_modules.py
ioannisNoukakis/benchmarkstt
41074c9b89632e8d9ff8e0ee72187211052bfb04
[ "MIT" ]
null
null
null
tests/benchmarkstt/test_modules.py
ioannisNoukakis/benchmarkstt
41074c9b89632e8d9ff8e0ee72187211052bfb04
[ "MIT" ]
null
null
null
from benchmarkstt.modules import Modules from benchmarkstt.normalization import cli def test_module(): modules = Modules('cli') assert modules['normalization'] is cli assert modules.normalization is cli for k, v in modules: assert modules[k] is v assert getattr(modules, k) is v keys = modules.keys() assert type(keys) is list assert 'normalization' in keys
25.3125
42
0.696296
from benchmarkstt.modules import Modules from benchmarkstt.normalization import cli def test_module(): modules = Modules('cli') assert modules['normalization'] is cli assert modules.normalization is cli for k, v in modules: assert modules[k] is v assert getattr(modules, k) is v keys = modules.keys() assert type(keys) is list assert 'normalization' in keys
true
true
f716c03e06bd0f761318cae39eb26bd38855049d
3,328
py
Python
src/sst/elements/merlin/interfaces/pymerlin-interface.py
vjleung/sst-elements
b2d4a41f1cd152ac96c9eca54000980a26a757d3
[ "BSD-3-Clause" ]
2
2019-06-10T15:32:03.000Z
2019-06-11T14:17:32.000Z
src/sst/elements/merlin/interfaces/pymerlin-interface.py
plavin/sst-elements
a84c63fa024782383272fb32ca24eb668f25b1c7
[ "BSD-3-Clause" ]
null
null
null
src/sst/elements/merlin/interfaces/pymerlin-interface.py
plavin/sst-elements
a84c63fa024782383272fb32ca24eb668f25b1c7
[ "BSD-3-Clause" ]
1
2019-09-24T13:41:56.000Z
2019-09-24T13:41:56.000Z
#!/usr/bin/env python # # Copyright 2009-2020 NTESS. Under the terms # of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. # # Copyright (c) 2009-2020, NTESS # All rights reserved. # # Portions are copyright of other developers: # See the file CONTRIBUTORS.TXT in the top level directory # the distribution for more information. # # This file is part of the SST software package. For license # information, see the LICENSE file in the top level directory of the # distribution. import sst from sst.merlin.base import * class LinkControl(NetworkInterface): def __init__(self): NetworkInterface.__init__(self) self._declareParams("params",["link_bw","input_buf_size","output_buf_size","vn_remap"]) self._subscribeToPlatformParamSet("network_interface") # returns subcomp, port_name def build(self,comp,slot,slot_num,job_id,job_size,logical_nid,use_nid_remap = False): sub = comp.setSubComponent(slot,"merlin.linkcontrol",slot_num) self._applyStatisticsSettings(sub) sub.addParams(self._getGroupParams("params")) sub.addParam("job_id",job_id) sub.addParam("job_size",job_size) sub.addParam("use_nid_remap",use_nid_remap) sub.addParam("logical_nid",logical_nid) return sub,"rtr_port" class ReorderLinkControl(NetworkInterface): def __init__(self): NetworkInterface.__init__(self) self._declareClassVariables(["network_interface"]) self._setCallbackOnWrite("network_interface",self._network_interface_callback) self.network_interface = PlatformDefinition.getPlatformDefinedClassInstance("reorderlinkcontrol_network_interface") if not self.network_interface: self.network_interface = LinkControl() # This is just a default, can be overwritten self._unlockVariable("network_interface") def _network_interface_callback(self, variable_name, value): if not value: return self._lockVariable("network_interface") self._setPassthroughTarget(value) def setNetworkInterface(self,interface): self.network_interface = interface def build(self,comp,slot,slot_num,job_id,job_size,nid,use_nid_map = False): sub = comp.setSubComponent(slot,"merlin.reorderlinkcontrol",slot_num) #self._applyStatisticsSettings(sub) #sub.addParams(self._params) return self.network_interface.build(sub,"networkIF",0,job_id,job_size,nid,use_nid_map) # Functions to enable statistics def enableAllStatistics(self,stat_params,apply_to_children=False): # no stats of our own, simply pass to network interface if self.network_interface: self.network_interface.enableAllStatistics(stat_params,apply_to_children) def enableStatistics(self,stats,stat_params,apply_to_children=False): # no stats of our own, simply pass to network interface if self.network_interface: self.network_interface.enableStatistics(stats,stat_params,apply_to_children) def setStatisticLoadLevel(self,level,apply_to_children=False): # no stats of our own, simply pass to network interface if self.network_interface: self.network_intrface.setStatisticLoadLevel(level,apply_to_children)
41.08642
123
0.735577
import sst from sst.merlin.base import * class LinkControl(NetworkInterface): def __init__(self): NetworkInterface.__init__(self) self._declareParams("params",["link_bw","input_buf_size","output_buf_size","vn_remap"]) self._subscribeToPlatformParamSet("network_interface") def build(self,comp,slot,slot_num,job_id,job_size,logical_nid,use_nid_remap = False): sub = comp.setSubComponent(slot,"merlin.linkcontrol",slot_num) self._applyStatisticsSettings(sub) sub.addParams(self._getGroupParams("params")) sub.addParam("job_id",job_id) sub.addParam("job_size",job_size) sub.addParam("use_nid_remap",use_nid_remap) sub.addParam("logical_nid",logical_nid) return sub,"rtr_port" class ReorderLinkControl(NetworkInterface): def __init__(self): NetworkInterface.__init__(self) self._declareClassVariables(["network_interface"]) self._setCallbackOnWrite("network_interface",self._network_interface_callback) self.network_interface = PlatformDefinition.getPlatformDefinedClassInstance("reorderlinkcontrol_network_interface") if not self.network_interface: self.network_interface = LinkControl() self._unlockVariable("network_interface") def _network_interface_callback(self, variable_name, value): if not value: return self._lockVariable("network_interface") self._setPassthroughTarget(value) def setNetworkInterface(self,interface): self.network_interface = interface def build(self,comp,slot,slot_num,job_id,job_size,nid,use_nid_map = False): sub = comp.setSubComponent(slot,"merlin.reorderlinkcontrol",slot_num) return self.network_interface.build(sub,"networkIF",0,job_id,job_size,nid,use_nid_map) def enableAllStatistics(self,stat_params,apply_to_children=False): if self.network_interface: self.network_interface.enableAllStatistics(stat_params,apply_to_children) def enableStatistics(self,stats,stat_params,apply_to_children=False): if self.network_interface: self.network_interface.enableStatistics(stats,stat_params,apply_to_children) def setStatisticLoadLevel(self,level,apply_to_children=False): if self.network_interface: self.network_intrface.setStatisticLoadLevel(level,apply_to_children)
true
true
f716c359878a902aee90be96fdffab16acbcdd2b
110,391
py
Python
articles/inversion.py
Solara570/demo-solara
3ce6df1fd68089c427bbd46fb0857e8b76428ca6
[ "MIT" ]
79
2017-09-25T04:42:05.000Z
2022-03-24T06:10:56.000Z
articles/inversion.py
Solara570/demo-solara
3ce6df1fd68089c427bbd46fb0857e8b76428ca6
[ "MIT" ]
1
2018-04-13T14:12:00.000Z
2018-04-13T14:12:00.000Z
articles/inversion.py
Solara570/demo-solara
3ce6df1fd68089c427bbd46fb0857e8b76428ca6
[ "MIT" ]
13
2017-09-29T03:20:20.000Z
2022-03-07T13:18:16.000Z
#coding=utf-8 ################################################################################################ # A 3-part series on circle inversion, Descartes' theorem along with its variants, and more! # # # # Part 1: An Introduction to Circle Inversion - https://zhuanlan.zhihu.com/p/86644341 # # Part 2: Four Circles & Descartes' Theorem (1) - https://zhuanlan.zhihu.com/p/105819963 # # Part 3: Four Circles & Descartes' Theorem (2) - https://zhuanlan.zhihu.com/p/106874090 # ################################################################################################ import numpy as np import itertools as it from manimlib.constants import * from manimlib.utils.color import * from manimlib.utils.space_ops import * from manimlib.utils.simple_functions import * from manimlib.animation.composition import AnimationGroup from manimlib.animation.creation import ShowCreation, Write, DrawBorderThenFill from manimlib.animation.fading import FadeOut, FadeInFromDown from manimlib.animation.transform import Transform, ReplacementTransform, MoveToTarget, ApplyMethod from manimlib.mobject.mobject import Mobject from manimlib.mobject.coordinate_systems import Axes, NumberPlane, ThreeDAxes from manimlib.mobject.geometry import Circle, Line, Dot, SmallDot, Square, Polygon, RegularPolygon, \ Arrow, Sector, Vector from manimlib.mobject.numbers import DecimalNumber from manimlib.mobject.value_tracker import ValueTracker from manimlib.mobject.shape_matchers import BackgroundRectangle, SurroundingRectangle from manimlib.mobject.three_dimensions import Sphere from manimlib.mobject.svg.brace import Brace from manimlib.mobject.svg.tex_mobject import TexMobject, TextMobject from manimlib.mobject.types.vectorized_mobject import VMobject, VGroup, VectorizedPoint, DashedVMobject from manimlib.scene.scene import Scene from manimlib.scene.three_d_scene import ThreeDScene from short.apollonian_gasket import calc_centers_by_radii, calc_new_agc_info, AGCircle, \ ApollonianGasket, ApollonianGasketScene from short.ford_circles import get_coprime_numers_by_denom, get_stroke_width_by_height, \ AssembledFraction, ZoomInOnFordCircles ##### ## Constants MAX_NORM = 1e2 CB_DARK = "#825201" CB_LIGHT = "#B69B4C" ##### ## General Methods def complex_inversion(z, z0, r): return z0 + np.conjugate(r**2 / (z-z0)) def R3_inversion(point, inv_center, radius): z = R3_to_complex(point) z0 = R3_to_complex(inv_center) w = complex_inversion(z, z0, radius) return complex_to_R3(w) def inversion(point, inv_center, radius): # Just a rename return R3_inversion(point, inv_center, radius) def is_close_in_R3(p1, p2, thres = 1e-6): """Check if two points are close in R^3.""" return np.linalg.norm(p1 - p2) < thres def is_close(z1, z2, thres = 1e-6): """Check if two complex numbers are close to each other.""" return np.abs(z1 - z2) < thres def get_tangent_point(c1, c2, thres = 1e-4): """Return the tangency point of circles 'c1' and 'c2'.""" p1 = c1.get_center() p2 = c2.get_center() r1 = c1.get_height() / 2 r2 = c2.get_height() / 2 d = get_norm(p2 - p1) if is_close(d, r1-r2, thres): return p1 + r1*normalize(p2-p1) elif is_close(d, r2-r1, thres): return p2 + r2*normalize(p1-p2) elif is_close(d, r1+r2, thres): return (r1*p2+r2*p1) / (r1+r2) else: raise Exception("These two circles aren't tangent.") def get_para_and_perp_components(point, lp1, lp2): v = lp2 - point v0 = lp2 - lp1 v_para = fdiv(np.dot(v, v0), np.dot(v0, v0)) * v0 v_perp = v - v_para return v_para, v_perp def distance_to_the_line(point, lp1, lp2): """Return the distance from 'point' to the line given by 'lp1' and 'lp2'.""" v_para, v_perp = get_para_and_perp_components(point, lp1, lp2) return np.linalg.norm(v_perp) def is_on_the_line(point, lp1, lp2, thres = 1e-6): """Check if 'point' is on the line given by two points 'lp1' and 'lp2'.""" return is_close(distance_to_the_line(point, lp1, lp2), thres) def get_random_vector(max_step): """Return a random vector with a maximum length of 'max_step'.""" return max_step*np.random.random() * rotate_vector(RIGHT, TAU*np.random.random()) def get_nearest_int(num): return int(np.round(num, 0)) def solve_quadratic_equation(a, b, c): delta = b**2 - 4*a*c x1 = (-b-np.sqrt(delta)) /(2*a) x2 = (-b+np.sqrt(delta)) /(2*a) print(a, b, c, x1, x2) return x1, x2 def get_next_terms(k1, k2, k3): """Return two adjacent terms in the loxodromic sequence.""" b = -2*(k1+k2+k3) c = 2*(k1**2+k2**2+k3**2) - (k1+k2+k3)**2 return list(map(get_nearest_int, solve_quadratic_equation(1, b, c))) def get_sequence_string(arr): arr_copy = list(map(str, arr)) arr_copy.insert(0, "...") arr_copy.append("...") return ", ".join(arr_copy) ##### ## Mobjects class FineCircle(Circle): CONFIG = { # In manim, circles are approximated by multiple cubic Beziers, # so it's necessary to increase the number of components for # high-precision calculations. "num_components": 100, } class ExtendedLine(Line): def __init__(self, sp, ep, n = 10, **kwargs): unit_vec = normalize(ep - sp) new_sp = sp - n * unit_vec new_ep = ep + n * unit_vec Line.__init__(self, new_sp, new_ep, **kwargs) class DotLabel(VMobject): CONFIG = { "position" : UP, "label_buff" : 0.25, } def __init__(self, label_text, dot, **kwargs): VMobject.__init__(self, **kwargs) self.dot = dot label = TexMobject(label_text, **kwargs) if self.position is not None: label.add_updater( lambda l: l.next_to(self.dot.get_center(), self.position, buff = self.label_buff) ) self.add(label) def set_label(self, label): label.next_to(self.dot.get_center()) class TwoDotsSegment(Line): def __init__(self, dot_1, dot_2, **kwargs): self.dot_1 = dot_1 self.dot_2 = dot_2 sp, ep = self.get_dots_centers() Line.__init__(self, start = sp, end = ep, **kwargs) self.add_updater(self.set_start_and_end) def get_dots_centers(self): return self.dot_1.get_center(), self.dot_2.get_center() def set_start_and_end(self, line_mob): sp, ep = self.get_dots_centers() line_mob.put_start_and_end_on(sp, ep) class LengthLabel(DecimalNumber): CONFIG = { "num_decimal_places" : 3, "label_height" : 0.3, "label_buff" : 0.3, "offset" : 0, "is_on_opposite_side" : False, } def __init__(self, line_mob, **kwargs): DecimalNumber.__init__(self, **kwargs) self.line_mob = line_mob self.add_updater(self.set_label) def set_label(self, label): label.set_value(self.line_mob.get_length()) label.set_height(self.label_height) label.rotate(self.line_mob.get_angle()) side_factor = -1 if self.is_on_opposite_side else 1 label.move_to( self.line_mob.get_center() \ + self.line_mob.get_vector() / 2 * self.offset \ + side_factor * rotate_vector(self.line_mob.get_unit_vector(), PI/2) * self.label_buff ) def set_offset(self, offset): self.offset = offset return self def switch_side(self): self.is_on_opposite_side = not self.is_on_opposite_side return self class ManyDotsPolygon(VMobject): def __init__(self, *dots, **kwargs): VMobject.__init__(self, **kwargs) self.dots = dots dots_centers = self.get_dots_centers() polygon = Polygon(*dots_centers, **kwargs) polygon.add_updater(self.set_vertices) self.add(polygon) def get_dots_centers(self): return [dot.get_center() for dot in self.dots] def set_vertices(self, polygon_mob): vertices = self.get_dots_centers() polygon_mob.set_points_as_corners([*vertices, vertices[0]]) class AngleIndicator(VMobject): CONFIG = { "color" : RED, "radius" : 0.2, "fill_opacity" : 0.6, "is_minor_arc" : True, } def __init__(self, dot_A, dot_C, dot_B, **kwargs): VMobject.__init__(self, **kwargs) self.dot_A = dot_A self.dot_C = dot_C self.dot_B = dot_B sector = Sector() sector.add_updater(self.set_sector) self.add(sector) self.sector = sector def get_point_center(self, point_or_mob): if isinstance(point_or_mob, Mobject): return point_or_mob.get_center() else: return point_or_mob def get_point_centers(self): return tuple(map(self.get_point_center, [self.dot_A, self.dot_C, self.dot_B])) def set_sector(self, mob): pt_A, pt_C, pt_B = self.get_point_centers() start_angle, angle = self.get_angles() outer_radius = min([self.radius, get_norm(pt_C - pt_A)/2, get_norm(pt_C - pt_B)/2]) new_sector = Sector( start_angle = start_angle, angle = angle, outer_radius = outer_radius, color = self.color, fill_opacity = self.fill_opacity, stroke_width = 0 ) new_sector.move_arc_center_to(self.get_point_center(self.dot_C)) mob.become(new_sector) def get_angles(self): pt_A, pt_C, pt_B = self.get_point_centers() start_angle = angle_of_vector(pt_A - pt_C) end_angle = angle_of_vector(pt_B - pt_C) angle = (end_angle - start_angle) % TAU if self.is_minor_arc and angle > PI: angle -= TAU return start_angle, angle class RightAngleIndicator(VMobject): CONFIG = { "color" : WHITE, "side_length" : 0.2, "line_width" : 1, "square_opacity" : 0.5, } def __init__(self, dot_A, dot_C, dot_B, **kwargs): VMobject.__init__(self, **kwargs) self.dot_A = dot_A self.dot_C = dot_C self.dot_B = dot_B line = VMobject(stroke_width = self.line_width, fill_opacity = 0) square = VMobject(stroke_width = 0, fill_color = self.color, fill_opacity = self.square_opacity) line.add_updater(self.set_line) square.add_updater(self.set_square) self.add(square, line) self.line = line self.square = square def get_point_center(self, point_or_mob): if isinstance(point_or_mob, Mobject): return point_or_mob.get_center() else: return point_or_mob def get_point_centers(self): return tuple(map(self.get_point_center, [self.dot_A, self.dot_C, self.dot_B])) def get_norm_vectors(self): pt_A, pt_C, pt_B = self.get_point_centers() norm_vec_CA = normalize(pt_A - pt_C) norm_vec_CB = normalize(pt_B - pt_C) return norm_vec_CA, norm_vec_CB def get_corner_points(self): pt_A, pt_C, pt_B = self.get_point_centers() norm_vec_CA, norm_vec_CB = self.get_norm_vectors() side_length = min([self.side_length, get_norm(pt_A - pt_C)/2, get_norm(pt_B - pt_C)/2]) return ( pt_C, pt_C + norm_vec_CA * side_length, pt_C + norm_vec_CA * side_length + norm_vec_CB * side_length, pt_C + norm_vec_CB * side_length ) def set_line(self, line_mob): p, q, r, s = self.get_corner_points() line_mob.set_points_as_corners([q, r, s]) def set_square(self, square_mob): p, q, r, s = self.get_corner_points() square_mob.set_points_as_corners([p, q, r, s, p]) class InversedDot(VMobject): CONFIG = { "color" : PINK, "stroke_width" : 3, "fill_opacity" : 1, "is_hollow" : True, "center_color" : BLACK, } def __init__(self, orig_dot, circle, **kwargs): self.orig_dot = orig_dot self.circle = circle VMobject.__init__(self, **kwargs) def generate_points(self): if self.is_hollow: self.fill_color = self.center_color else: self.fill_color = self.color self.stroke_width = 0 inv_dot = Dot(ORIGIN, color = self.color) self.inv_dot = inv_dot self.add(inv_dot) self.add_updater_to_inversed_dot() def add_updater_to_inversed_dot(self): self.inv_dot.add_updater(self.move_inversed_dot) def move_inversed_dot(self, inv_dot): point = self.orig_dot.get_center() inv_center = self.circle.get_center() radius = self.circle.get_height() / 2. if is_close_in_R3(point, inv_center): pass else: inv_dot.move_to(inversion(point, inv_center, radius)) class InversedVMobject(VMobject): CONFIG = { "is_analytical" : True, "match_original_style" : False, "use_dashed_vmob" : True, "dashed_vmob_config": { "num_dashes" : 50, "positive_space_ratio" : 0.6, }, } def __init__(self, orig_vmob, circle, **kwargs): VMobject.__init__(self, **kwargs) self.orig_vmob = orig_vmob self.circle = circle self.orig_vmob_type = "Others" self.initialize_orig_vmob_type() self.add_updater_to_inversed_vmobject() def add_updater_to_inversed_vmobject(self): self.add_updater(self.set_inversed_vmobject) def initialize_orig_vmob_type(self): if isinstance(self.orig_vmob, Line): self.orig_vmob_type = "Line" elif isinstance(self.orig_vmob, Circle): self.orig_vmob_type = "Circle" else: self.orig_vmob_type = "Others" def set_orig_vmob_type(self, orig_vmob_type): self.orig_vmob_type = orig_vmob_type def set_inversed_vmobject(self, inv_vmob): inv_center = self.circle.get_center() radius = self.circle.get_height() / 2. if self.is_analytical and self.orig_vmob_type == "Line": # If it's a line... lp1, lp2 = self.orig_vmob.get_start_and_end() if is_on_the_line(inv_center, lp1, lp2): # If it's a line passing through the inversion center, # then the inversion is just the line itself. temp_vmob = ExtendedLine(lp1, lp2) else: # If it's a line NOT through the inversion center, # then the inversion is a circle passing through the inversion center. v_para, v_perp = get_para_and_perp_components(inv_center, lp1, lp2) d = distance_to_the_line(inv_center, lp1, lp2) # d = np.linalg.norm(v_perp) inv_vmob_radius = fdiv(radius**2, 2*d) closepoint = inv_center + v_perp inv_vmob_closepoint = inversion(closepoint, inv_center, radius) inv_vmob_center = (inv_center + inv_vmob_closepoint) / 2. temp_vmob = FineCircle(radius = inv_vmob_radius) temp_vmob.move_to(inv_vmob_center) elif self.is_analytical and self.orig_vmob_type == "Circle": # If it's a circle... orig_vmob_center = self.orig_vmob.get_center() orig_vmob_radius = self.orig_vmob.get_height() / 2. center_vec = orig_vmob_center - inv_center d = get_norm(center_vec) if is_close(orig_vmob_radius, d): # If it's a circle passing through the inversion center, # then the inversion is a line perps to the line through the circle centers. foot = inv_center + fdiv(radius**2, 2*d) * normalize(center_vec) lp1 = foot + rotate_vector(center_vec, PI/2) lp2 = foot + rotate_vector(center_vec, -PI/2) temp_vmob = ExtendedLine(lp1, lp2) else: # If it's a circle NOT through the inversion center, # then the inversion is a circle NOT through the inversion center. dp1 = orig_vmob_center - orig_vmob_radius * normalize(center_vec) dp2 = orig_vmob_center + orig_vmob_radius * normalize(center_vec) inv_dp1 = inversion(dp1, inv_center, radius) inv_dp2 = inversion(dp2, inv_center, radius) inv_vmob_radius = get_norm(inv_dp2 - inv_dp1) / 2. inv_vmob_center = (inv_dp2 + inv_dp1) / 2. temp_vmob = FineCircle(radius = inv_vmob_radius) temp_vmob.move_to(inv_vmob_center) else: temp_vmob = self.orig_vmob.copy() temp_vmob.apply_function(lambda p: inversion(p, inv_center, radius)) if self.use_dashed_vmob: temp_vmob = DashedVMobject(temp_vmob, **self.dashed_vmob_config) inv_vmob.become(temp_vmob) if self.match_original_style: inv_vmob.match_style(self.orig_vmob) class FourCirclesNormalForm(VMobject): CONFIG = { "circle_colors" : [MAROON_B, RED, GREEN, BLUE], "r" : 1.2, "l" : 9, "use_dashed_vmob" : True, "dashed_vmob_config" : { "num_dashes" : 30, "positive_space_ratio" : 0.6, } } def __init__(self, **kwargs): VMobject.__init__(self, **kwargs) c1 = Circle(radius = self.r, **kwargs).shift(self.r*LEFT) c2 = Circle(radius = self.r, **kwargs).shift(self.r*RIGHT) c3 = Line(self.l*LEFT, self.l*RIGHT, **kwargs).shift(self.r*DOWN) c4 = Line(self.l*LEFT, self.l*RIGHT, **kwargs).shift(self.r*UP) for mob, color in zip([c1, c2, c3, c4], self.circle_colors): mob.set_color(color) if self.use_dashed_vmob: self.add(DashedVMobject(mob, **self.dashed_vmob_config)) else: self.add(mob) class DescartesFourCircles(VMobject): CONFIG = { "outer_circle_index" : None, "orig_circle_color" : BLUE, "new_circle_color" : YELLOW, "show_new_circles" : True, "show_new_circles_centers" : False, } def __init__(self, ccdot1, ccdot2, ccdot3, **kwargs): self.ccdot1 = ccdot1 self.ccdot2 = ccdot2 self.ccdot3 = ccdot3 VMobject.__init__(self, **kwargs) self.add_orig_circles() self.add_orig_circles_updaters() self.generate_new_circles() if self.show_new_circles: self.add_new_circles() if self.show_new_circles_centers: self.add_new_circles_centers() def add_orig_circles(self): self.c1, self.c2, self.c3 = self.cs = VGroup(*[ Circle(arc_center = cc, radius = r, color = self.orig_circle_color) for cc, r in zip(self.get_orig_circle_centers(), self.calc_radii_by_centers()) ]) self.add(self.cs) def add_orig_circles_updaters(self): def get_center(k): return self.get_orig_circle_centers()[k] def get_abs_radius(k): return np.abs(self.calc_radii_by_centers()[k]) # Since enumerate() won't work here (seriously?), # I have to use a much more direct approach - list them all. self.c1.add_updater(lambda c: c.move_to(get_center(0))) self.c1.add_updater(lambda c: c.set_height(2*get_abs_radius(0))) self.c2.add_updater(lambda c: c.move_to(get_center(1))) self.c2.add_updater(lambda c: c.set_height(2*get_abs_radius(1))) self.c3.add_updater(lambda c: c.move_to(get_center(2))) self.c3.add_updater(lambda c: c.set_height(2*get_abs_radius(2))) def get_orig_circles(self): return self.cs def get_orig_circle_centers(self): return [dot.get_center() for dot in (self.ccdot1, self.ccdot2, self.ccdot3)] def get_orig_circle_radii(self): return self.calc_radii_by_centers() def get_orig_circle_curvatures(self): return [fdiv(1, radius) for radius in self.calc_radii_by_centers()] def calc_radii_by_centers(self): p1, p2, p3 = self.get_orig_circle_centers() d12 = get_norm(p2 - p1) d23 = get_norm(p3 - p2) d13 = get_norm(p3 - p1) sum_r = (d12 + d23 + d13) / 2. if self.outer_circle_index == 1: # If circle 1 contains other two circles... return [-sum_r, sum_r-d12, sum_r-d13] elif self.outer_circle_index == 2: # If circle 2 contains other two circles... return [sum_r-d12, -sum_r, sum_r-d23] elif self.outer_circle_index == 3: # If circle 3 contains other two circles... return [sum_r-d13, sum_r-d23, -sum_r] else: return [sum_r-d23, sum_r-d13, sum_r-d12] def generate_new_circles(self): self.c4_1, self.c4_2 = self.new_circles = VGroup(*[ Circle(arc_center = new_cc, radius = new_r, color = self.new_circle_color) for new_cc, new_r in self.calc_new_circles_centers_and_radii() ]) self.generate_new_circles_centers() self.add_new_circles_updaters() def calc_new_circles_centers_and_radii(self): k1, k2, k3 = self.get_orig_circle_curvatures() z1, z2, z3 = map(R3_to_complex, self.get_orig_circle_centers()) # Calculate the curvatures of new circles sum_k = k1 + k2 + k3 sum_k2 = k1**2 + k2**2 + k3**2 sum_k_cycle_prod = k1*k2 + k2*k3 + k3*k1 b = (-2)*sum_k c = sum_k2 - 2*sum_k_cycle_prod delta = b**2 - 4*c k4_1 = (-b + np.sqrt(delta)) / 2 k4_2 = (-b - np.sqrt(delta)) / 2 # Calculate the centers of new circles # arxiv.org/abs/math/0101066v1 - Eqn 2.3 sum_kz = k1*z1 + k2*z2 + k3*z3 sum_k2z = k1**2 * z1 + k2**2 * z2 + k3**2 * z3 coeff_1 = (sum_k - k4_1) * k4_1 const_1 = 2 * sum_k2z - (sum_k + k4_1) * sum_kz z4_1 = const_1 / coeff_1 coeff_2 = (sum_k - k4_2) * k4_2 const_2 = 2 * sum_k2z - (sum_k + k4_2) * sum_kz z4_2 = const_2 / coeff_2 return [[complex_to_R3(z4_1), fdiv(1, k4_1)], [complex_to_R3(z4_2), fdiv(1, k4_2)]] def generate_new_circles_centers(self): ccdot4_1 = Dot(color = self.new_circle_color) ccdot4_1.add_updater(lambda m: m.move_to(self.c4_1.get_center())) ccdot4_2 = Dot(color = self.new_circle_color) ccdot4_2.add_updater(lambda m: m.move_to(self.c4_2.get_center())) self.ccdot4_1 = ccdot4_1 self.ccdot4_2 = ccdot4_2 def add_new_circles_updaters(self): def get_new_center(k): return self.calc_new_circles_centers_and_radii()[k][0] def get_abs_new_radius(k): return np.abs(self.calc_new_circles_centers_and_radii()[k][1]) # Since enumerate() won't work here (seriously?), # I have to use a much more direct approach - list them all. self.c4_1.add_updater(lambda c: c.move_to(get_new_center(0))) self.c4_1.add_updater(lambda c: c.set_height(2*get_abs_new_radius(0))) self.c4_2.add_updater(lambda c: c.move_to(get_new_center(1))) self.c4_2.add_updater(lambda c: c.set_height(2*get_abs_new_radius(1))) def add_new_circles(self): if not hasattr(self, "new_circles"): self.new_circles = generate_new_circles() self.add(self.new_circles) def get_new_circles(self): if not hasattr(self, "new_circles"): self.new_circles = generate_new_circles() return self.new_circles def add_new_circles_centers(self): self.add(self.ccdot4_1, self.ccdot4_2) def remove_new_circles_center(self): self.remove(self.ccdot4_1, self.ccdot4_2) ##### ## Inversion Introduction Scenes class ConceptsInInversion(Scene): CONFIG = { "color_circle" : YELLOW, "color_radius" : RED, "color_P" : WHITE, } def construct(self): self.add_backgrounds() self.move_around_point_P() def add_backgrounds(self): circle_O = Circle(radius = 3.5, color = self.color_circle) circle_O.shift(3*LEFT) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle_O.get_bottom(), UP) dot_O = Dot(circle_O.get_center(), color = self.color_circle) label_O = DotLabel("O", dot_O, color = self.color_circle, position = DOWN) remark_O = TextMobject("反演中心", color = self.color_circle) remark_O.next_to(label_O, LEFT, buff = 0.15) radius = Line(circle_O.get_center(), circle_O.get_left()) label_radius = TexMobject("R").scale(0.8) remark_radius = TextMobject("反演幂").scale(0.8) brace_radius = Brace(radius, UP) brace_radius.put_at_tip(label_radius) remark_radius.next_to(label_radius, LEFT, buff = 0.15) group_radius = VGroup(radius, label_radius, brace_radius, remark_radius) group_radius.set_color(self.color_radius) group_radius.rotate(-PI/12, about_point = dot_O.get_center()) def_inversion = TextMobject("反演变换:$P \\mapsto P'$") rlt_inversion = TexMobject("|OP| \\times |OP'|=", "R^2") rlt_inversion.next_to(def_inversion, DOWN, aligned_edge = RIGHT) rlt_inversion[-1].set_color(self.color_radius) remarks = VGroup(def_inversion, rlt_inversion) remarks.to_corner(DR) dot_P = Dot(LEFT, color = self.color_P) label_P = DotLabel("P", dot_P, color = self.color_P, position = DL, label_buff = 0.2) dot_Pi = InversedDot(dot_P, circle_O, color = self.color_P) label_Pi = DotLabel("P'", dot_Pi, color = self.color_P, position = DR, label_buff = 0.2) line_OP = TwoDotsSegment(dot_O, dot_P, stroke_width = 2) line_OPi = TwoDotsSegment(dot_O, dot_Pi, stroke_width = 2) self.add(remarks) self.add(group_radius) self.add(circle_O, dot_O, label_O, remark_O, remark_circle) self.add(dot_P, dot_Pi, label_P, label_Pi, line_OP, line_OPi) self.circle_O = circle_O self.dot_P = dot_P def move_around_point_P(self): self.dot_P.save_state() for dx, dy in [(-0.2, 0.3), (0.1, -0.4), (4, 0.3), (1, 1)]: vec = np.array([dx, dy, 0]) self.play(self.dot_P.shift, vec, run_time = 1) self.wait() self.play(self.dot_P.move_to, self.circle_O.get_right()) self.wait() self.play(self.dot_P.restore, run_time = 1) self.wait() class InversionExamples(Scene): CONFIG = { "color_circle" : YELLOW, } def construct(self): circle_O = Circle(radius = 3.5, color = self.color_circle) circle_O.shift(3*LEFT) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle_O.get_bottom(), UP) dot_O = Dot(circle_O.get_center(), color = self.color_circle) label_O = DotLabel("O", dot_O, color = self.color_circle, position = DOWN) init_shape = Square(side_length = 1.2, color = BLUE).rotate(TAU/13) init_shape.next_to(circle_O.get_right(), LEFT, buff = 0.5) init_shape.save_state() inv_shape = InversedVMobject(init_shape, circle_O, use_dashed_vmob = False) new_shapes = [ RegularPolygon(n = 6, start_angle = PI/7, color = PINK).scale(0.8), TexMobject("42", color = RED).scale(2.5).rotate(-PI/9), TexMobject("\\pi", color = MAROON_B).scale(5).rotate(PI/15), ] self.add(circle_O, remark_circle, dot_O, label_O) self.add(init_shape, inv_shape) for new_shape in new_shapes: # new_shape.set_color(BLUE) new_shape.next_to(circle_O.get_right(), LEFT, buff = 0.6) self.play(Transform(init_shape, new_shape), run_time = 1) self.wait() init_shape.generate_target() init_shape.target.become(new_shape) init_shape.target.shift(get_random_vector(0.5)) random_angle = 0.5*np.random.random() init_shape.target.rotate(random_angle) self.play(MoveToTarget(init_shape, path_arc = random_angle, run_time = 1)), self.wait() self.play(ApplyMethod(init_shape.restore)) self.wait() class LineToLineInversion(Scene): CONFIG = { "color_circle" : YELLOW, "color_orig" : BLUE, "color_inv" : RED, } def construct(self): self.add_backgrounds() self.show_line_to_line_inversion() def add_backgrounds(self): circle_O = Circle(radius = 2.5, color = self.color_circle) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle_O.get_bottom(), UP) dot_O = Dot(circle_O.get_center(), color = self.color_circle) label_O = DotLabel("O", dot_O, color = self.color_circle, position = DOWN) conclusion = TextMobject("经过反演中心的直线", "$\\mapsto$", "经过反演中心的直线") conclusion.scale(0.8) conclusion[0].set_color(self.color_orig) conclusion[2].set_color(self.color_inv) conclusion.to_corner(DR) self.add(circle_O, remark_circle, dot_O, label_O) self.add(conclusion) self.circle_O = circle_O def show_line_to_line_inversion(self): angle_tracker = ValueTracker(-PI/11) position_tracker = ValueTracker(1.4) angle_tracker.save_state() position_tracker.save_state() orig_line = ExtendedLine(LEFT, RIGHT, color = self.color_orig, stroke_width = 8) orig_line.add_updater(lambda m: m.rotate(angle_tracker.get_value() - m.get_angle())) inv_line = ExtendedLine(LEFT, RIGHT, color = self.color_inv, stroke_width = 4) inv_line.add_updater(lambda m: m.rotate(angle_tracker.get_value() - m.get_angle())) dot_P = Dot(color = self.color_orig) dot_P.add_updater( lambda m: m.move_to( position_tracker.get_value() * rotate_vector(RIGHT, angle_tracker.get_value()) ) ) dot_Pi = InversedDot(dot_P, self.circle_O, is_hollow = False, color = self.color_inv) label_P = DotLabel("P", dot_P, position = DOWN, color = self.color_orig) label_Pi = DotLabel("P'", dot_Pi, position = DOWN, color = self.color_inv) def get_lb(): return LEFT_SIDE + UP * LEFT_SIDE[0] * np.tan(angle_tracker.get_value()) def get_rb(): return RIGHT_SIDE + UP * RIGHT_SIDE[0] * np.tan(angle_tracker.get_value()) def is_oolb(m): return m.get_right()[0] < LEFT_SIDE[0] def is_oorb(m): return m.get_left()[0] > RIGHT_SIDE[0] oolb_arrow = Arrow(ORIGIN, LEFT, color = self.color_inv).scale(2) oolb_arrow.add_updater(lambda m: m.set_angle(angle_tracker.get_value() + PI)) oolb_arrow.add_updater(lambda m: m.next_to(get_lb(), DOWN, aligned_edge = LEFT, buff = 0.2)) oorb_arrow = Arrow(ORIGIN, RIGHT, color = self.color_inv).scale(2) oorb_arrow.add_updater(lambda m: m.set_angle(angle_tracker.get_value())) oorb_arrow.add_updater(lambda m: m.next_to(get_rb(), DOWN, aligned_edge = RIGHT, buff = 0.2)) oolb_label = TexMobject("P'", color = self.color_inv, background_stroke_width = 0) oolb_label.add_updater(lambda m: m.next_to(oolb_arrow, DOWN, buff = 0.2)) oorb_label = TexMobject("P'", color = self.color_inv, background_stroke_width = 0) oorb_label.add_updater(lambda m: m.next_to(oorb_arrow, DOWN, buff = 0.2)) oolb_group = VGroup(oolb_arrow, oolb_label) oorb_group = VGroup(oorb_arrow, oorb_label) oolb_group.add_updater(lambda m: m.set_fill(opacity = 1 if is_oolb(label_Pi) else 0)) oolb_group.add_updater(lambda m: m.set_stroke(opacity = 1 if is_oolb(label_Pi) else 0)) oorb_group.add_updater(lambda m: m.set_fill(opacity = 1 if is_oorb(label_Pi) else 0)) oorb_group.add_updater(lambda m: m.set_stroke(opacity = 1 if is_oorb(label_Pi) else 0)) self.add(orig_line, inv_line, dot_P, dot_Pi, label_P, label_Pi) self.add(oolb_group, oorb_group) for d_position, d_angle in [(2, 0), (1, PI/10), (-5, 0), (-3, -PI/7), (4, PI/11)]: self.play( ApplyMethod(position_tracker.increment_value, d_position), ApplyMethod(angle_tracker.increment_value, d_angle), run_time = 2, ) self.wait() self.play( ApplyMethod(angle_tracker.restore), ApplyMethod(position_tracker.restore), run_time = 2, ) self.wait() class LineToCircleInversion(Scene): CONFIG = { "color_circle" : YELLOW, "color_orig" : BLUE, "color_inv" : RED, "line_config" : { "stroke_width" : 2, "color" : WHITE, }, } def construct(self): self.add_backgrounds() self.add_shapes() self.show_line_to_circle_inversion() def add_backgrounds(self): circle_O = Circle(radius = 3, color = self.color_circle) circle_O.shift(3*LEFT+0.5*UP) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle_O.get_bottom(), UP) dot_O = Dot(circle_O.get_center(), color = self.color_circle) label_O = DotLabel("O", dot_O, color = self.color_circle, position = DOWN) conclusion1 = TextMobject("不经过反演中心的直线", "$\\mapsto$", "经过反演中心的圆") conclusion1[0].set_color(self.color_orig) conclusion1[-1].set_color(self.color_inv) conclusion2 = TextMobject("经过反演中心的圆", "$\\mapsto$", "不经过反演中心的直线") conclusion2[0].set_color(self.color_inv) conclusion2[-1].set_color(self.color_orig) conclusions = VGroup(conclusion1, conclusion2) for c in conclusions: c.scale(0.8) conclusions.arrange_submobjects(DOWN, index_of_submobject_to_align = 1) conclusions.to_corner(DR) bg_rect = BackgroundRectangle(conclusions) self.add(circle_O, remark_circle) self.add_foreground_mobjects(dot_O, label_O, bg_rect, conclusions) self.dot_O = dot_O self.circle_O = circle_O self.conclusions = conclusions self.bg_rect = bg_rect def add_shapes(self): position_tracker = ValueTracker(2) line_angle_tracker = ValueTracker(PI*9/19) circle_angle_tracker = ValueTracker(PI/5) line = ExtendedLine(LEFT, RIGHT, color = self.color_orig) line.add_updater(lambda m: m.move_to(position_tracker.get_value() * RIGHT)) line.add_updater(lambda m: m.rotate(line_angle_tracker.get_value() - m.get_angle())) inv_line = InversedVMobject(line, self.circle_O, use_dashed_vmob = False, color = self.color_inv) inv_line_center = SmallDot(color = self.color_inv) inv_line_center.add_updater(lambda m: m.move_to(inv_line.get_center())) dot_Ai = Dot(color = self.color_inv) dot_Ai.add_updater( lambda m: m.move_to(inv_line.get_center() * 2 - self.circle_O.get_center()) ) dot_Pi = Dot(color = self.color_inv) dot_Pi.add_updater( lambda m: m.move_to( inv_line.get_center() \ + rotate_vector( inv_line.get_center() - self.circle_O.get_center(), circle_angle_tracker.get_value() ) ) ) dot_P = InversedDot(dot_Pi, self.circle_O, is_hollow = False, color = self.color_orig) dot_A = InversedDot(dot_Ai, self.circle_O, is_hollow = False, color = self.color_orig) line_OA, line_OAi, line_OP, line_OPi, line_AP, line_AiPi = aux_lines = VGroup(*[ TwoDotsSegment(pt_1, pt_2, **self.line_config) for pt_1, pt_2 in [ (self.dot_O, dot_A), (self.dot_O, dot_Ai), (self.dot_O, dot_P), (self.dot_O, dot_Pi), (dot_A, dot_P), (dot_Ai, dot_Pi) ] ]) ai_AiOPi = AngleIndicator(dot_Ai, self.dot_O, dot_Pi, color = MAROON_B, radius = 0.8) rtai_OAP = RightAngleIndicator(self.dot_O, dot_A, dot_P) rtai_OPiAi = RightAngleIndicator(self.dot_O, dot_Pi, dot_Ai) label_P = TexMobject("P", color = self.color_orig) label_Pi = TexMobject("P'", color = self.color_inv) label_A = TexMobject("A", color = self.color_orig) label_Ai = TexMobject("A'", color = self.color_inv) label_A.add_updater( lambda m: m.move_to( dot_A.get_center() + 0.3 * normalize(dot_A.get_center() - self.dot_O.get_center()) ) ) label_P.add_updater( lambda m: m.move_to( dot_P.get_center() + 0.3 * normalize(dot_A.get_center() - self.dot_O.get_center()) ) ) label_Ai.add_updater( lambda m: m.move_to( dot_Ai.get_center() + 0.4 * rotate_vector( normalize(dot_Ai.get_center() - inv_line_center.get_center()), -PI/4 ) ) ) label_Pi.add_updater( lambda m: m.move_to( dot_Pi.get_center() + 0.4 * normalize(dot_Pi.get_center() - inv_line_center.get_center()) ) ) def get_ub(): return line.get_center() + TOP + RIGHT * TOP[1] / np.tan(line_angle_tracker.get_value()) def get_bb(): return line.get_center() + BOTTOM + RIGHT * BOTTOM[1] / np.tan(line_angle_tracker.get_value()) def is_ooub(m): return m.get_bottom()[1] > TOP[1] def is_oobb(m): return m.get_top()[1] < BOTTOM[1] ooub_arrow = Arrow(ORIGIN, LEFT, color = self.color_orig).scale(2) ooub_arrow.add_updater(lambda m: m.set_angle(line_angle_tracker.get_value())) ooub_arrow.add_updater(lambda m: m.next_to(get_ub(), RIGHT, aligned_edge = TOP, buff = 0.2)) oobb_arrow = Arrow(ORIGIN, RIGHT, color = self.color_orig).scale(2) oobb_arrow.add_updater(lambda m: m.set_angle(line_angle_tracker.get_value() + PI)) oobb_arrow.add_updater(lambda m: m.next_to(get_bb(), RIGHT, aligned_edge = BOTTOM, buff = 0.2)) oolb_label = TexMobject("P", color = self.color_orig, background_stroke_width = 0) oolb_label.add_updater(lambda m: m.next_to(ooub_arrow, RIGHT, buff = 0.2)) oorb_label = TexMobject("P", color = self.color_orig, background_stroke_width = 0) oorb_label.add_updater(lambda m: m.next_to(oobb_arrow, RIGHT, buff = 0.2)) ooub_group = VGroup(ooub_arrow, oolb_label) oobb_group = VGroup(oobb_arrow, oorb_label) ooub_group.add_updater(lambda m: m.set_fill(opacity = 1 if is_ooub(label_P) else 0)) ooub_group.add_updater(lambda m: m.set_stroke(opacity = 1 if is_ooub(label_P) else 0)) oobb_group.add_updater(lambda m: m.set_fill(opacity = 1 if is_oobb(label_P) else 0)) oobb_group.add_updater(lambda m: m.set_stroke(opacity = 1 if is_oobb(label_P) else 0)) self.add(line, inv_line) self.add(dot_A, dot_P, dot_Ai, dot_Pi) self.add(label_P, label_Pi, label_A, label_Ai) self.add(aux_lines) self.add(ai_AiOPi, rtai_OAP, rtai_OPiAi) self.add(ooub_group, oobb_group) self.position_tracker = position_tracker self.line_angle_tracker = line_angle_tracker self.circle_angle_tracker = circle_angle_tracker def show_line_to_circle_inversion(self): play_args = [ [0, PI/12, 0, 2], [0, 0, PI*7/5, 4], [-2, PI/8, -PI/5, 3], [0, 0, PI*19/10, 6], [1.5, -PI/7, PI*2/5, 4], ] restore_arg = [ -sum([arg[k] for arg in play_args]) for k in range(len(play_args[0])) ] restore_arg[1] = (restore_arg[1] + PI) % (2*PI) - PI restore_arg[2] = (restore_arg[2] + PI) % (2*PI) - PI restore_arg[-1] = 3 play_args.append(restore_arg) for d_center, d_line_angle, d_circle_angle, run_time in play_args: self.play( ApplyMethod(self.position_tracker.increment_value, d_center), ApplyMethod(self.line_angle_tracker.increment_value, d_line_angle), ApplyMethod(self.circle_angle_tracker.increment_value, d_circle_angle), run_time = run_time, ) self.wait() class InversionCreateSimilarTriangles(Scene): CONFIG = { "random_seed" : 5+7-0, "num_of_nudges" : 5, "max_step" : 1, "color_A" : RED, "color_B" : BLUE, "color_combined" : MAROON_B, "color_circle": YELLOW, } def construct(self): self.add_remark() self.show_figure_animation() def add_remark(self): cond_1 = TexMobject("{|OP|", "\\over", "|OQ|}", "=", "{|OQ'|", "\\over", "|OP'|}") cond_2 = TexMobject("\\angle POQ", "=", "\\angle Q'OP'") conds = VGroup(cond_1, cond_2) conds.arrange_submobjects(DOWN, buff = 0.5) conds_rect = SurroundingRectangle(conds, color = WHITE) arrow = TexMobject("\\Downarrow") arrow.next_to(conds_rect, DOWN) concl = TexMobject("\\triangle OPQ", "\\sim", "\\triangle OQ'P'") concl.next_to(arrow, DOWN) for mob in (cond_1[0], cond_1[2], concl[0]): mob.set_color(self.color_A) for mob in (cond_1[-1], cond_1[-3], concl[-1]): mob.set_color(self.color_B) for mob in (cond_2[0], cond_2[-1]): mob.set_color(self.color_combined) remark = VGroup(conds, conds_rect, arrow, concl) remark.to_corner(DR) self.add(remark) def show_figure_animation(self): circle = Circle(radius = 3, color = self.color_circle) circle.move_to(3.5*LEFT) dot_O = Dot(color = self.color_combined) dot_O.add_updater(lambda m: m.move_to(circle.get_center())) dot_P = Dot(point = 1.2*UP+LEFT, color = self.color_A) dot_Q = Dot(point = 0.5*DOWN+1.9*LEFT, color = self.color_A) dot_Pi = InversedDot(dot_P, circle, is_hollow = False, color = self.color_B) dot_Qi = InversedDot(dot_Q, circle, is_hollow = False, color = self.color_B) triangle_OPQ = ManyDotsPolygon( dot_O, dot_P, dot_Q, color = self.color_A, stroke_width = 5, fill_opacity = 0.4 ) triangle_OPiQi = ManyDotsPolygon( dot_O, dot_Pi, dot_Qi, color = self.color_B, stroke_width = 2, fill_opacity = 0.3 ) label_O, label_P, label_Pi, label_Q, label_Qi = ( DotLabel( text, dot, color = color, position = position, background_stroke_width = 5, ).scale(0.8) for text, dot, color, position in zip( ["O", "P", "P'", "Q", "Q'"], [dot_O, dot_P, dot_Pi, dot_Q, dot_Qi], [self.color_combined, self.color_A, self.color_B, self.color_A, self.color_B], [LEFT, UP, UP, DOWN, DOWN] ) ) self.add(dot_O, dot_P, dot_Q, dot_Pi, dot_Qi) self.add(circle, triangle_OPQ, triangle_OPiQi) self.add(label_O, label_P, label_Pi, label_Q, label_Qi) dot_P.save_state() dot_Q.save_state() for k in range(self.num_of_nudges): nudge_P = get_random_vector(self.max_step) nudge_Q = get_random_vector(self.max_step) self.play( ApplyMethod(dot_P.shift, nudge_P), ApplyMethod(dot_Q.shift, nudge_Q), run_time = 2 ) self.wait() self.play(dot_P.restore, dot_Q.restore, run_time = 2) self.wait() class CircleToCircleInversionProof(Scene): CONFIG = { "color_O" : YELLOW, "color_A" : RED, "color_B" : BLUE, "color_combined" : MAROON_B, "label_buff" : 0.1, "label_scaling_factor" : 0.75, "line_config" : { "stroke_width" : 2, "color" : WHITE, }, } def construct(self): self.add_backgrounds() self.show_left_and_right_points() self.show_random_point() self.show_similar_triangles() self.show_complementary_property() self.show_inversion_result() def add_backgrounds(self): circle_O = Circle(radius = 3.2, color = self.color_O) circle_O.shift(3.5*LEFT) dot_O = Dot(circle_O.get_center(), color = self.color_O) remark_O = TextMobject("反演圆", color = YELLOW) remark_O.next_to(circle_O.get_bottom(), UP, buff = 0.4) circle_C = Circle(radius = 0.8, stroke_width = 2) circle_C.next_to(circle_O.get_right(), LEFT, buff = 0.5) dot_C = Dot(circle_C.get_center()) label_O, label_C = ( DotLabel( text, dot, color = color, position = DOWN, label_buff = self.label_buff ).scale(self.label_scaling_factor) for text, dot, color in zip(["O", "C"], [dot_O, dot_C], [self.color_O, WHITE]) ) for orig_mob in (circle_C, dot_C, label_C): orig_mob.set_sheen_direction(RIGHT) orig_mob.set_color([self.color_A, self.color_B]) inv_circle_template = InversedVMobject(circle_C, circle_O, use_dashed_vmob = False) inv_circle = Circle(radius = inv_circle_template.get_width()/2) inv_circle.move_to(inv_circle_template.get_center()) inv_circle.set_sheen_direction(LEFT) inv_circle.set_color([self.color_A, self.color_B]) self.add(circle_O, dot_O, circle_C, dot_C) self.add(label_O, label_C) self.add(remark_O) self.wait() self.circle_O = circle_O self.dot_O = dot_O self.remark_O = remark_O self.circle_C = circle_C self.dot_C = dot_C self.inv_circle = inv_circle def show_left_and_right_points(self): dot_A = Dot(color = self.color_A) dot_A.move_to(self.circle_C.get_left()) dot_B = Dot(color = self.color_B) dot_B.move_to(self.circle_C.get_right()) dot_Ai = InversedDot(dot_A, self.circle_O, is_hollow = False, color = self.color_A) dot_Bi = InversedDot(dot_B, self.circle_O, is_hollow = False, color = self.color_B) dot_Q = Dot((dot_Ai.get_center() + dot_Bi.get_center()) / 2) line_OB = Line(self.dot_O.get_center(), dot_B.get_center(), **self.line_config) line_OAi = Line(self.dot_O.get_center(), dot_Ai.get_center(), **self.line_config) label_A, label_Ai, label_B, label_Bi = ( DotLabel( text, dot, color = color, position = position, label_buff = self.label_buff ).scale(self.label_scaling_factor) for text, dot, color, position in zip( ["A", "A'", "B", "B'"], [dot_A, dot_Ai, dot_B, dot_Bi], [self.color_A, self.color_A, self.color_B, self.color_B], [DL, DR, DR, DL] ) ) remark_AB = TextMobject("圆心连线 \\\\ 的交点...").scale(0.6) remark_AB.next_to(VGroup(dot_A, dot_B), DOWN, buff = 1) arrows_AB = VGroup(*[ Arrow(remark_AB.get_critical_point(direction), dot, buff = 0.1) for direction, dot in zip([UL, UR], [dot_A, dot_B]) ]) remark_AiBi = TextMobject("...以及它们的反点").scale(0.8) remark_AiBi.next_to(VGroup(dot_Ai, dot_Bi), DOWN, buff = 1) arrows_AiBi = VGroup(*[ Arrow(remark_AiBi.get_critical_point(direction), dot, buff = 0.1) for direction, dot in zip([UR, UL], [dot_Ai, dot_Bi]) ]) self.play(ShowCreation(line_OB)) self.play(Write(dot_A), Write(dot_B), Write(label_A), Write(label_B)) self.wait() self.play(Write(remark_AB), ShowCreation(arrows_AB)) self.wait() self.play( ReplacementTransform(dot_A.deepcopy(), dot_Ai), ReplacementTransform(dot_B.deepcopy(), dot_Bi), ) self.play(Write(label_Ai), Write(label_Bi)) self.wait() self.play( ReplacementTransform(remark_AB, remark_AiBi), ReplacementTransform(arrows_AB, arrows_AiBi) ) self.play(ReplacementTransform(line_OB, line_OAi)) self.play(FadeOut(VGroup(remark_AiBi, arrows_AiBi))) self.wait() self.dot_A = dot_A self.dot_Ai = dot_Ai self.dot_B = dot_B self.dot_Bi = dot_Bi self.dot_Q = dot_Q self.line_OAi = line_OAi self.dots_AB = VGroup(dot_A, dot_Ai, dot_B, dot_Bi) self.labels_AB = VGroup(label_A, label_Ai, label_B, label_Bi) def show_random_point(self): angle_tracker = ValueTracker(PI/3) dot_P = Dot() dot_P.add_updater( lambda m: m.move_to( self.circle_C.point_at_angle(angle_tracker.get_value() % TAU) ) ) dot_P.add_updater( lambda m: m.set_color( interpolate_color( self.color_A, self.color_B, (dot_P.get_center()[0] - self.dot_A.get_center()[0]) / (self.dot_B.get_center()[0] - self.dot_A.get_center()[0]) ) ) ) label_P = DotLabel("P", dot_P, position = None) label_P.scale(0.8) label_P.add_updater(lambda m: m.set_color(dot_P.get_color())) label_P.add_updater( lambda m: m.move_to(dot_P.get_center() * 1.4 - self.dot_C.get_center() * 0.4) ) arrow_P = Vector(DR, buff = 0, color = WHITE).scale(0.5) arrow_P.add_updater(lambda m: m.next_to(dot_P, UL, buff = 0.1)) remark_P = TextMobject("圆上任意一点...").scale(0.75) remark_P.add_updater(lambda m: m.next_to(arrow_P, UL, buff = 0.1)) dot_Pi = InversedDot(dot_P, self.circle_O, is_hollow = False) dot_Pi.add_updater(lambda m: m.set_color(dot_P.get_color())) label_Pi = DotLabel("P'", dot_Pi, position = None) label_Pi.scale(0.8) label_Pi.add_updater(lambda m: m.set_color(dot_Pi.get_color())) label_Pi.add_updater( lambda m: m.move_to(dot_Pi.get_center() * 1.1 - self.inv_circle.get_center() * 0.1) ) arrow_Pi = Vector(DL, buff = 0, color = WHITE).scale(0.5) arrow_Pi.add_updater(lambda m: m.next_to(dot_Pi, UR, buff = 0.1)) remark_Pi = TextMobject("...以及它的反点").scale(0.75) remark_Pi.add_updater(lambda m: m.next_to(arrow_Pi, UR, buff = 0.1)) line_OP, line_OPi, line_AP, line_AiPi, line_BP, line_BiPi = aux_lines = VGroup(*[ TwoDotsSegment(pt_1, pt_2, **self.line_config) for pt_1, pt_2 in [ (self.dot_O, dot_P), (self.dot_O, dot_Pi), (self.dot_A, dot_P), (self.dot_Ai, dot_Pi), (self.dot_B, dot_P), (self.dot_Bi, dot_Pi) ] ]) rtai_APB = RightAngleIndicator(self.dot_A, dot_P, self.dot_B) rtai_BiPiAi = RightAngleIndicator(self.dot_Bi, dot_Pi, self.dot_Ai, side_length = 0.5) self.play(Write(dot_P), Write(label_P)) self.play(ShowCreation(arrow_P), Write(remark_P)) self.play(Write(line_AP), Write(line_BP)) self.play(ShowCreation(rtai_APB)) self.wait() self.play(ReplacementTransform(dot_P.deepcopy(), dot_Pi)) self.play(Write(label_Pi)) self.play( ReplacementTransform(arrow_P.deepcopy(), arrow_Pi), ReplacementTransform(remark_P.deepcopy(), remark_Pi), ) self.play(angle_tracker.increment_value, PI/6, run_time = 2) self.play(FadeOut(VGroup(arrow_P, remark_P, arrow_Pi, remark_Pi))) self.wait() self.play(Write(VGroup(line_OP, line_OPi, line_AiPi, line_BiPi))) self.wait() self.dot_P = dot_P self.dot_Pi = dot_Pi self.rtai_APB = rtai_APB self.rtai_BiPiAi = rtai_BiPiAi self.angle_tracker = angle_tracker self.aux_lines = aux_lines self.dots_P = VGroup(dot_P, dot_Pi) self.labels_P = VGroup(label_P, label_Pi) self.rtais = VGroup(self.rtai_APB, self.rtai_BiPiAi) def show_similar_triangles(self): ai_OAP = AngleIndicator(self.dot_O, self.dot_A, self.dot_P, radius = 0.3, color = self.color_A) ai_OBP = AngleIndicator(self.dot_O, self.dot_B, self.dot_P, radius = 0.4, color = self.color_B) ai_OPiAi = AngleIndicator(self.dot_O, self.dot_Pi, self.dot_Ai, radius = 0.3, color = self.color_A) ai_OPiBi = AngleIndicator(self.dot_O, self.dot_Pi, self.dot_Bi, radius = 0.4, color = self.color_B) triangle_OAP, triangle_OPiAi, triangle_OBP, triangle_OPiBi = [ ManyDotsPolygon( pt_1, pt_2, pt_3, color = self.color_combined, stroke_width = 0, fill_opacity = 0.4 ) for pt_1, pt_2, pt_3 in ( (self.dot_O, self.dot_A, self.dot_P), (self.dot_O, self.dot_Pi, self.dot_Ai), (self.dot_O, self.dot_B, self.dot_P), (self.dot_O, self.dot_Pi, self.dot_Bi), ) ] remark_sim_A = TexMobject("\\triangle OAP", "\\sim", "\\triangle OP'A'") remark_sim_B = TexMobject("\\triangle OBP", "\\sim", "\\triangle OP'B'") remark_arrow = TexMobject("\\Downarrow") remark_angle_A = TexMobject("\\angle OAP", "=", "\\angle OP'A'") remark_angle_B = TexMobject("\\angle OBP", "=", "\\angle OP'B'") remarks_A = VGroup(remark_sim_A, remark_arrow, remark_angle_A) remarks_B = VGroup(remark_sim_B, remark_arrow, remark_angle_B) remarks_A.arrange_submobjects(DOWN) remarks_A.next_to(self.dot_Q, DOWN, buff = 1) remark_sim_B.move_to(remark_sim_A.get_center()) remark_angle_B.move_to(remark_angle_A.get_center()) for remark, color in ([remark_sim_A, self.color_combined], [remark_sim_B, self.color_combined], \ [remark_angle_A, self.color_A], [remark_angle_B, self.color_B]): remark[0].set_color(color) remark[-1].set_color(color) self.play(Write(remark_sim_A)) self.play(FadeInFromDown(VGroup(remark_arrow, remark_angle_A))) self.wait() self.play(ShowCreation(triangle_OAP), ShowCreation(ai_OAP)) self.wait() self.play( ReplacementTransform(triangle_OAP, triangle_OPiAi), ReplacementTransform(ai_OAP.deepcopy(), ai_OPiAi), ) self.play(FadeOut(triangle_OPiAi)) self.wait() self.play(ReplacementTransform(remarks_A, remarks_B)) self.wait() self.play(ShowCreation(triangle_OBP), ShowCreation(ai_OBP)) self.wait() self.play( ReplacementTransform(triangle_OBP, triangle_OPiBi), ReplacementTransform(ai_OBP.deepcopy(), ai_OPiBi), ) self.play(FadeOut(remarks_B), FadeOut(triangle_OPiBi)) self.wait() self.ai_OAP = ai_OAP self.ai_OBP = ai_OBP self.ai_OPiAi = ai_OPiAi self.ai_OPiBi = ai_OPiBi self.ais = VGroup(ai_OAP, ai_OBP, ai_OPiAi, ai_OPiBi) def show_complementary_property(self): ai_OAP_copy = self.ai_OAP.deepcopy() ai_OBP_copy = self.ai_OBP.deepcopy() rtai_APB_copy = self.rtai_APB.deepcopy() for ai_copy in (ai_OAP_copy, ai_OBP_copy, rtai_APB_copy): ai_copy.clear_updaters() comp_prop = VGroup(ai_OAP_copy, TexMobject("="), ai_OBP_copy, TexMobject("+"), rtai_APB_copy) comp_prop.arrange_submobjects(RIGHT) comp_prop.scale(1.2) comp_prop.next_to(self.circle_O.get_top(), DOWN, buff = 1) self.play( ReplacementTransform(self.ai_OAP.deepcopy(), ai_OAP_copy), ReplacementTransform(self.ai_OBP.deepcopy(), ai_OBP_copy), ReplacementTransform(self.rtai_APB.deepcopy(), rtai_APB_copy), ) self.play(Write(comp_prop[1]), Write(comp_prop[3])) self.wait() self.play(ReplacementTransform(rtai_APB_copy.deepcopy(), self.rtai_BiPiAi)) self.wait() for ai in self.ais: ai.clear_updaters() self.play( FadeOut(comp_prop), FadeOut(self.ais), FadeOut(self.labels_AB), FadeOut(self.labels_P), ) self.wait() def show_inversion_result(self): inv_circle_copy = self.inv_circle.deepcopy() self.play(self.angle_tracker.set_value, PI, run_time = 2) self.wait() def update_inv_circle(inv_circle): angle = self.angle_tracker.get_value() if (angle <= -PI) or (angle > PI): alpha = 1 else: QPi = self.dot_Pi.get_center() - self.dot_Q.get_center() QAi = self.dot_Ai.get_center() - self.dot_Q.get_center() theta = angle_between(QPi, QAi) if self.dot_Pi.get_center()[1] < self.dot_Q.get_center()[1]: theta = 2*PI - theta alpha = theta / (2*PI) inv_circle.become(inv_circle_copy.get_subcurve(0, alpha)) self.inv_circle.add_updater(update_inv_circle) self.add(self.inv_circle) self.play( ApplyMethod(self.angle_tracker.increment_value, -2*PI), run_time = 5, ) self.inv_circle.clear_updaters() for line in self.aux_lines: line.clear_updaters() self.play( FadeOut(self.dots_AB), FadeOut(self.dots_P), FadeOut(self.rtais), FadeOut(self.line_OAi), FadeOut(self.aux_lines) ) self.wait() color_template = Square( stroke_width = 0, fill_opacity = 1, fill_color = [self.color_A, self.color_B] ) conclusion = TextMobject("不经过反演中心的圆", "$\\mapsto$", "不经过反演中心的圆") conclusion.scale(0.8) conclusion[0].set_color_by_gradient(self.color_A, self.color_B) conclusion[2].set_color_by_gradient(self.color_B, self.color_A) conclusion.to_corner(DR) self.play(Write(conclusion)) self.wait(3) self.play(FadeOut(conclusion), FadeOut(self.inv_circle)) self.wait() class ConcentricPropertyDoesNotHold(Scene): def setup(self): N = 8 self.circle_radii = [0.9-0.1*k for k in range(N)] self.dot_radii = [0.08-0.005*k for k in range(N)] self.circle_colors = color_gradient([BLUE, GREEN, RED], N) def construct(self): orig_circles = VGroup(*[ Circle(radius = radius, stroke_width = 1.5,color = color) for radius, color in zip(self.circle_radii, self.circle_colors)] ) orig_circles.shift(2*LEFT+0.5*DOWN) orig_circles_centers = VGroup(*[ Dot(circle.get_center(), radius = radius, color = color) for circle, radius, color in zip(orig_circles, self.dot_radii, self.circle_colors) ]) # Dot(orig_circles.get_center()) circle = Circle(radius = 3, color = YELLOW) circle.shift(3.8*LEFT+0.5*DOWN) circle_center = Dot(circle.get_center(), color = YELLOW) inv_circles = VGroup(*[ InversedVMobject(orig_circle, circle).clear_updaters().set_color(color) for orig_circle, color in zip(orig_circles, self.circle_colors) ]) inv_circles_centers = VGroup(*[ Dot(inv_circle.get_center(), color = color) for inv_circle, color in zip(inv_circles, self.circle_colors) ]) circle_text = TextMobject("反演圆", color = YELLOW) circle_text.next_to(circle.get_bottom(), UP, buff = 0.4) orig_circles_text = TextMobject("同心的圆", color = WHITE) orig_circles_text.next_to(orig_circles, UP) orig_circles_text.to_edge(UP, buff = 0.4) inv_circles_text = TextMobject("不同心的像", color = WHITE) inv_circles_text.next_to(inv_circles, UP) inv_circles_text.to_edge(UP, buff = 0.4) arrow = Arrow(orig_circles_text.get_right(), inv_circles_text.get_left()) self.add(circle, circle_center) self.add(orig_circles, orig_circles_centers) self.add(inv_circles, inv_circles_centers) self.add(circle_text, orig_circles_text, inv_circles_text, arrow) self.wait() class DemonstratePtolemyInequality(Scene): CONFIG = { "R" : 2.7, "angle_A" : -PI*2/3, "angle_B" : PI*4/5, "angle_D" : -PI/5, "radius_C" : 3.2, "angle_C" : PI/5, } def construct(self): radius_tracker = ValueTracker(self.radius_C) angle_tracker = ValueTracker(self.angle_C) circle = Circle(radius = self.R, color = WHITE, stroke_width = 1) circle.shift(DOWN) dashed_circle = DashedVMobject(circle, num_dashes = 100, positive_space_ratio = 0.5) dot_A, dot_B, dot_C, dot_D = dots = VGroup(*[ Dot(circle.point_at_angle(angle % TAU), color = WHITE) for angle in (self.angle_A, self.angle_B, self.angle_C, self.angle_D) ]) dot_C.add_updater( lambda m: m.move_to( circle.get_center() + radius_tracker.get_value() * \ rotate_vector(RIGHT, angle_tracker.get_value()) ) ) dot_labels = VGroup(*[ DotLabel(text, dot, position = position, label_buff = 0.1) for text, dot, position in zip( ["A", "B", "C", "D"], dots, [DL, UL, UR, DR] ) ]) lines = VGroup(*[ TwoDotsSegment(dot_1, dot_2) for dot_1, dot_2 in ( [dot_B, dot_A], [dot_A, dot_C], [dot_A, dot_D], [dot_B, dot_C], [dot_B, dot_D], [dot_C, dot_D], ) ]) length_labels = VGroup(*[LengthLabel(line) for line in lines]) length_labels[0].switch_side() length_labels[2].switch_side() length_labels[1].set_offset(-0.4) length_labels[-2].set_offset(-0.4) def get_sums(): AB, AC, AD, BC, BD, CD = [line.get_length() for line in lines] sum_lhs = AB * CD + AD * BC sum_rhs = AC * BD return sum_lhs, sum_rhs relation_eq = TexMobject( "|AB| \\cdot |CD| + |AD| \\cdot |BC|", "=", "|AC| \\cdot |BD|", background_stroke_width = 0, ) relation_neq = TexMobject( "|AB| \\cdot |CD| + |AD| \\cdot |BC|", ">", "|AC| \\cdot |BD|", background_stroke_width = 0, ) relation_eq[1].set_color(GREEN) relation_neq[1].set_color(RED) relation_eq.to_edge(UP, buff = 1.2) for eq_mob, neq_mob in zip(relation_eq, relation_neq): neq_mob.move_to(eq_mob.get_center()) lhs, eq_sign, rhs = relation_eq neq_sign = relation_neq[1] label_lhs = DecimalNumber(num_decimal_places = 4, show_ellipsis = True) label_rhs = DecimalNumber(num_decimal_places = 4, show_ellipsis = True) label_lhs.add_updater(lambda m: m.set_value(get_sums()[0])) label_rhs.add_updater(lambda m: m.set_value(get_sums()[1])) brace_lhs = Brace(lhs, UP, buff = 0.1) brace_rhs = Brace(rhs, UP, buff = 0.1) brace_lhs.put_at_tip(label_lhs) brace_rhs.put_at_tip(label_rhs) def get_indication_color(thres = 1e-2): return GREEN if is_close(radius_tracker.get_value(), self.R, thres = thres) else RED def get_indication_opacity(thres = 1e-2): return 0 if is_close(radius_tracker.get_value(), self.R, thres = thres) else 1 figure_group = VGroup(dashed_circle, dots, lines, length_labels, dot_labels) figure_group.add_updater(lambda m: m.set_color(get_indication_color())) relation_group = VGroup(lhs, eq_sign, rhs, neq_sign, brace_lhs, brace_rhs, label_lhs, label_rhs) label_lhs.add_updater(lambda m: m.set_color(get_indication_color())) label_rhs.add_updater(lambda m: m.set_color(get_indication_color())) eq_sign.add_updater(lambda m: m.set_opacity(1 - get_indication_opacity())) neq_sign.add_updater(lambda m: m.set_opacity(get_indication_opacity())) self.add(figure_group) self.add(relation_group) deltas = [ (0.5, -0.1), (0, -0.4), (-1, 0.3), (0, 0.4), (-1, 0), (0.3, -0.2), (0.7, -0.3), ] radius_tracker.save_state() angle_tracker.save_state() for d_radius, d_angle in deltas: self.play( ApplyMethod(radius_tracker.increment_value, d_radius), ApplyMethod(angle_tracker.increment_value, d_angle), run_time = 2, ) self.wait() self.play( ApplyMethod(radius_tracker.restore), ApplyMethod(angle_tracker.restore), run_time = 2, ) self.wait() class PtolemyInversionFigure(Scene): CONFIG = { "R" : 3.8, "r" : 1.3, "angle_A" : PI, "angle_B" : PI/3, "angle_C" : -PI/9, "angle_D" : -PI*2/7, "color_circle" : YELLOW, "color_ABD" : BLUE, } def construct(self): circle_ABD = Circle(radius = self.r, color = self.color_ABD, stroke_width = 3) circle_ABD.shift(0.2*LEFT) dot_A, dot_B, dot_C, dot_D = dots = VGroup(*[ Dot(circle_ABD.point_at_angle(angle % TAU), color = WHITE) for angle in (self.angle_A, self.angle_B, self.angle_C, self.angle_D) ]) dot_A.set_color(self.color_circle) dot_C.shift(0.4*RIGHT) circle = Circle(radius = self.R, color = self.color_circle, stroke_width = 5) circle.move_to(dot_A.get_center()) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle.get_bottom(), UP) label_A, label_B, label_C, label_D = dot_labels = VGroup(*[ DotLabel(text, dot, position = position, label_buff = 0.2) for text, dot, position in zip( ["A", "B", "C", "D"], dots, [DL, UP, DOWN, DOWN] ) ]) label_A.set_color(self.color_circle) dot_Bi, dot_Ci, dot_Di = inv_dots = VGroup(*[ InversedDot(dot, circle, is_hollow = False, color = WHITE) for dot in (dot_B, dot_C, dot_D) ]) label_Bi, label_Ci, label_Di = inv_dot_labels = VGroup(*[ DotLabel(text, dot, position = RIGHT, label_buff = 0.2) for text, dot in zip(["B'", "C'", "D'"], [dot_Bi, dot_Ci, dot_Di]) ]) lines = VGroup(*[ TwoDotsSegment(dot_1, dot_2, stroke_width = 1) for dot_1, dot_2 in ( [dot_A, dot_B], [dot_A, dot_C], [dot_A, dot_D], [dot_B, dot_C], [dot_B, dot_D], [dot_C, dot_D], [dot_A, dot_Bi], [dot_A, dot_Ci], [dot_A, dot_Di], [dot_Bi, dot_Ci], [dot_Bi, dot_Di], [dot_Ci, dot_Di], ) ]) inv_circle_ABD = InversedVMobject(circle_ABD, circle, use_dashed_vmob = False) inv_circle_ABD.add_updater(lambda m: m.set_color(self.color_ABD)) inv_circle_ABD.add_updater(lambda m: m.set_stroke(width = 2)) self.add(circle, remark_circle, circle_ABD, inv_circle_ABD) self.add(dots, dot_labels, inv_dots, inv_dot_labels, lines) self.add() self.wait() ##### ## Inversion Advanced P1 Scenes class KissingCirclesPuzzle(Scene): def construct(self): self.show_figure() self.show_question() def show_figure(self): type_text_1 = TextMobject("外切-外切-外切") type_text_2 = TextMobject("内切-内切-外切") type_text_1.move_to(LEFT_SIDE/2) type_text_2.move_to(RIGHT_SIDE/2) type_text_1.to_edge(DOWN) type_text_2.to_edge(DOWN) dot_l1, dot_l2, dot_l3 = dots_l = VGroup(*[ VectorizedPoint(np.array([coords[0], coords[1], 0]), color = BLUE) for coords in [(-3.9, 1.5), (-4.9, 0.0), (-2.8, -1.0)] ]) dot_r1, dot_r2, dot_r3 = dots_r = VGroup(*[ VectorizedPoint(np.array([coords[0], coords[1], 0]), color = BLUE) for coords in [(4.6, 0.3), (3.9, 0.6), (3.5, 1.6)] ]) dfc_l = DescartesFourCircles(*dots_l, show_new_circles = False) dfc_r = DescartesFourCircles(*dots_r, show_new_circles = False, outer_circle_index = 2) for dfc in [dfc_l, dfc_r]: for mob in dfc.get_orig_circles(): mob.set_stroke(width = 2, color = BLUE) self.add(type_text_1, type_text_2) self.add(dfc_l, dfc_r) self.dfc_l = dfc_l self.dfc_r = dfc_r self.dots_l = dots_l self.dots_r = dots_r def show_question(self): question = TextMobject("能否添加第四个圆,使之与其他三个圆都相切?") question.to_edge(UP, buff = 0.2) self.add(question) self.wait() class KissingCirclesSimplified(Scene): def construct(self): line1 = ExtendedLine(UL, UR) line2 = ExtendedLine(DL, DR) center_circle = Circle(radius = 1) figure_group = VGroup(line1, line2, center_circle) for mob in figure_group: mob.set_stroke(width = 2, color = BLUE) question = TextMobject("能否添加第四个“圆”,使之与其他三个“圆”都相切?") question.next_to(figure_group, UP, buff = 0.5) group = VGroup(question, figure_group) group.move_to(ORIGIN) self.add(group) self.wait() class KissingCirclesSimplifiedAnswer(Scene): def construct(self): line1 = ExtendedLine(UL, UR, stroke_width = 2, color = BLUE) line2 = ExtendedLine(DL, DR, stroke_width = 2, color = BLUE) center_circle = Circle(radius = 1, stroke_width = 2, color = BLUE) new_circles = VGroup(*[ Circle(radius = 1, color = color, fill_opacity = 0.1, stroke_width = 5) \ .next_to(center_circle, direction, buff = 0) for direction, color in zip([LEFT, RIGHT], [RED, ORANGE]) ]) numbers = VGroup(*[ TexMobject(f"{num}", color = circle.get_color()).move_to(circle.get_center()) for num, circle in zip(["1", "2"], new_circles) ]) group = VGroup(line1, line2, center_circle, new_circles, numbers) group.move_to(ORIGIN) self.add(group) self.wait() class KissingCirclesSimplifiedExplanation(Scene): CONFIG = { "dashed_vmob_config" : { "num_dashes" : 30, "positive_space_ratio" : 0.6, }, "line_colors" : [GREEN, BLUE], "center_color" : MAROON_B, "circle_colors" : [RED, ORANGE], } def construct(self): self.add_backgrounds() self.show_process() def add_backgrounds(self): N = 5 line1 = Line(UP + N*LEFT, UP + N*RIGHT, stroke_width = 2, color = self.line_colors[0]) line2 = Line(DOWN + N*LEFT, DOWN + N*RIGHT, stroke_width = 2, color = self.line_colors[1]) center_circle = FineCircle(radius = 1, stroke_width = 2, color = self.center_color) new_circle1 = FineCircle(radius = 1, stroke_width = 5, color = self.circle_colors[0]) new_circle1.next_to(center_circle, LEFT, buff = 0) new_circle2 = FineCircle(radius = 1, stroke_width = 5, color = self.circle_colors[1]) new_circle2.next_to(center_circle, RIGHT, buff = 0) inv_old_group = VGroup(line1, line2, center_circle) inv_new_group = VGroup(new_circle1, new_circle2) inv_group = VGroup(inv_old_group, inv_new_group) inv_group.rotate(-PI*2/5) inv_group.shift(3*RIGHT) circle = FineCircle(radius = 3.5, color = YELLOW) circle.shift(2*LEFT) circle_center = Dot(circle.get_center(), color = YELLOW) remark_circle = TextMobject("反演圆", color = YELLOW) remark_circle.next_to(circle.get_bottom(), UP) remark_center = VGroup(*[ Arrow(DL, UR, color = YELLOW, buff = 0).scale(0.3), TextMobject("反演中心", color = YELLOW).scale(0.8), ]) remark_center.arrange_submobjects(DL, buff = 0) remark_center.next_to(circle_center, DL, buff = 0.1) orig_old_group = VGroup(*[ InversedVMobject(mob, circle, use_dashed_vmob = False, match_original_style = True) for mob in inv_old_group ]) orig_new_group = VGroup(*[ InversedVMobject(mob, circle, use_dashed_vmob = False, match_original_style = True) for mob in inv_new_group ]) for mob in orig_old_group: mob.clear_updaters() mob.set_stroke(width = 2) for mob in orig_new_group: mob.clear_updaters() mob.set_stroke(width = 5) mob.set_fill(opacity = 0.1) self.add(orig_old_group) self.add(circle, circle_center, remark_circle, remark_center) self.circle = circle self.inv_old_group = inv_old_group self.inv_new_group = inv_new_group self.orig_old_group = orig_old_group self.orig_new_group = orig_new_group def show_process(self): dashed_inv_old_group = VGroup(*[ DashedVMobject(mob, **self.dashed_vmob_config) for mob in self.inv_old_group ]) dashed_inv_new_group = VGroup(*[ DashedVMobject(mob, **self.dashed_vmob_config) for mob in self.inv_new_group ]) self.play(ShowCreation(dashed_inv_old_group, lag_ratio = 0.05), run_time = 3) self.wait() dashed_copys = VGroup(*[dashed_inv_old_group[-1].deepcopy() for k in range(2)]) dashed_copys.generate_target() for mob_copy, mob_template in zip(dashed_copys.target, dashed_inv_new_group): mob_copy.match_style(mob_template) mob_copy.move_to(mob_template.get_center()) self.play(MoveToTarget(dashed_copys), run_time = 3) self.remove(dashed_copys) self.add(dashed_inv_new_group) self.wait() self.play(DrawBorderThenFill(self.orig_new_group), run_time = 3) self.wait(2) self.play( FadeOut(dashed_inv_new_group), FadeOut(dashed_inv_old_group), FadeOut(self.orig_new_group), ) self.wait() class DifferentTangentTypesWithSameConclusion(KissingCirclesPuzzle): CONFIG = { "random_seed" : 570, "num_of_nudges" : 5, "max_step" : 0.5, "color_1" : ORANGE, "color_2" : RED, } def construct(self): super().show_figure() self.dots_l.save_state() self.dots_r.save_state() for dfc in [self.dfc_l, self.dfc_r]: dfc.add_new_circles() dfc.get_orig_circles().set_stroke(width = 2) c4_1, c4_2 = dfc.get_new_circles() c4_1.set_color(self.color_1) c4_2.set_color(self.color_2) self.add(self.dfc_l, self.dfc_r) for k in range(self.num_of_nudges): for dot in it.chain(self.dots_l, self.dots_r): dot.generate_target() dot.target.shift(get_random_vector(self.max_step)) anims = AnimationGroup(*[ MoveToTarget(dot, path_arc = PI/3., run_time = 1.5) for dot in it.chain(self.dots_l, self.dots_r) ], run_time = 2) self.play(anims) self.wait() self.play(self.dots_l.restore, self.dots_r.restore, run_time = 1.5) class LineToCircleInversionRevisited(LineToCircleInversion): def construct(self): super().construct() self.remove_conclusions() self.add_explanation() def remove_conclusions(self): self.remove(self.bg_rect) self.remove(self.conclusions) def add_explanation(self): radius = Line( self.circle_O.get_left(), self.circle_O.get_center(), color = self.color_circle, stroke_width = 1, ) radius_text = TexMobject("R", color = self.color_circle) radius_text.next_to(radius, UP, buff = 0.1) radius_group = VGroup(radius, radius_text) radius_group.rotate(-PI/12, about_point = self.circle_O.get_center()) remark_length = TexMobject("|OA| = d", "\\Downarrow", "|OA'| = \dfrac{R^2}{d}") remark_length.arrange_submobjects(DOWN) remark_length.scale(1.2) remark_length[0].set_color(self.color_orig) remark_length[-1].set_color(self.color_inv) remark_length.to_edge(RIGHT) self.add(radius_group, remark_length) self.wait() class CircleToCircleInversionRevisited(CircleToCircleInversionProof): def construct(self): super().add_backgrounds() super().show_left_and_right_points() super().show_random_point() super().show_similar_triangles() self.arrange_elements() self.add_explanation() def arrange_elements(self): self.angle_tracker.set_value(PI/3) self.remove(self.remark_O) self.remove(self.ai_OAP, self.ai_OBP, self.ai_OPiAi, self.ai_OPiBi) self.add(self.inv_circle) self.add(self.dots_P, self.labels_P) self.add(self.dots_AB, self.labels_AB) self.add(self.aux_lines, self.rtais) dot_I = Dot(self.inv_circle.get_center()) label_I = DotLabel("I", dot_I, position = DOWN, label_buff = 0.15).scale(0.8) for mob in (dot_I, label_I): mob.set_sheen_direction(RIGHT) mob.set_color([self.color_B, self.color_A]) remark_I = TextMobject("反形的圆心(并非$C$的反点!)") remark_I.scale(0.5) remark_I.next_to(label_I, DOWN, buff = 0.1) self.add(dot_I, label_I, remark_I) def add_explanation(self): for circle, color, text, angle in zip( [self.circle_O, self.circle_C], [self.color_O, MAROON_B], ["R", "r"], [-PI/12, PI/3] ): radius = Line( circle.get_left(), circle.get_center(), color = color, stroke_width = 1, ) radius_text = TexMobject(text, color = color) radius_text.next_to(radius, UP, buff = 0.1) radius_group = VGroup(radius, radius_text) radius_group.rotate(angle, about_point = circle.get_center()) self.add(radius_group) remark_length_A = TexMobject("|OA| = d-r", "\\Rightarrow", "|OA'| = \dfrac{R^2}{d-r}") remark_length_B = TexMobject("|OB| = d+r", "\\Rightarrow", "|OB'| = \dfrac{R^2}{d+r}") remark_length_A[0].set_color(self.color_A) remark_length_A[-1].set_color(self.color_A) remark_length_B[0].set_color(self.color_B) remark_length_B[-1].set_color(self.color_B) length_group = VGroup(remark_length_A, remark_length_B) length_group.arrange_submobjects(DOWN, buff = 0.4) brace = Brace(length_group, RIGHT) arrow = TexMobject("\\Rightarrow") remarks = VGroup( TexMobject("|A'B'| = \\dfrac{2 R^2 r}{|d^2-r^2|}"), TexMobject("|OI| = \\dfrac{R^2 d}{|d^2-r^2|}") ) remarks.arrange_submobjects(DOWN, aligned_edge = LEFT) remarks.set_color(MAROON_B) result_group = VGroup(brace, arrow, remarks) result_group.arrange_submobjects(RIGHT) result_group.next_to(length_group, RIGHT) remark_group = VGroup(length_group, result_group) remark_group.center().to_edge(DOWN, buff = 0.2) bg_rect = BackgroundRectangle(remark_group, fill_opacity = 0.9) self.add(bg_rect, remark_group) self.wait() class DescartesTheoremExamples(Scene): CONFIG = { "circle_colors" : [MAROON_B, RED, GREEN, BLUE], "curvs_outer" : [3, 6, 7, 34], "curvs_inner" : [10, 15, 19, -6], } def setup(self): self.text_color_map = dict( zip(["{k_1}", "{k_2}", "{k_3}", "{k_4}"], self.circle_colors) ) def construct(self): self.add_title() self.add_outer_dfc() self.add_inner_dfc() def add_title(self): title = TexMobject( "\\left(", "{k_1}", "+", "{k_2}", "+", "{k_3}", "+", "{k_4}", "\\right) ^2", "= 2 \\left(", "{k_1}","^2 +","{k_2}","^2 +","{k_3}","^2 +","{k_4}","^2", "\\right)" ) title.set_color_by_tex_to_color_map(self.text_color_map) title.scale(1.2) title.to_edge(UP, buff = 0.2) self.add(title) def add_outer_dfc(self): r1, r2, r3, r4 = [1./curv for curv in self.curvs_outer] p1, p2, p3 = [ VectorizedPoint(center) for center in calc_centers_by_radii(r1, r2, r3, init_angle = PI*2/3) ] outer_dfc = DescartesFourCircles(p1, p2, p3, show_new_circles = False) c1, c2, c3 = outer_dfc.get_orig_circles() c4 = outer_dfc.get_new_circles()[0] outer_circles = VGroup(c1, c2, c3, c4) outer_circles.clear_updaters() outer_circles.set_height(5.5) outer_circles.to_corner(DL) texts = VGroup(*[ TexMobject(f"k_{num}", "=", f"{curv}") \ .scale(0.8) \ .move_to(circle.get_center()) for num, curv, circle in zip(range(1, 5), self.curvs_outer, outer_circles) ]) for circle, text, color in zip(outer_circles, texts, self.circle_colors): circle.set_color(color) text.set_color(color) texts[-1].shift(2.5*RIGHT+1.2*UP) arrow = Arrow( texts[-1].get_bottom(), outer_circles[-1].get_right(), path_arc = -PI*2/3, buff = 0.1, ).set_color(self.circle_colors[-1]) outer_group = VGroup(outer_circles, texts, arrow) self.add(outer_group) def add_inner_dfc(self): r1, r2, r3, r4 = [1./curv for curv in self.curvs_inner] p1, p2, p3 = [ VectorizedPoint(center) for center in calc_centers_by_radii(r1, r2, r3, init_angle = -PI/7) ] inner_dfc = DescartesFourCircles(p1, p2, p3, show_new_circles = False) c1, c2, c3 = inner_dfc.get_orig_circles() c4 = inner_dfc.get_new_circles()[1] inner_circles = VGroup(c1, c2, c3, c4) inner_circles.clear_updaters() inner_circles.set_height(5.5) inner_circles.to_corner(DR) inner_texts = VGroup(*[ TexMobject(f"k_{num}", "=", f"{curv}") \ .scale(0.8) \ .move_to(circle.get_center()) for num, curv, circle in zip(range(1, 5), self.curvs_inner, inner_circles) ]) for circle, text, color in zip(inner_circles, inner_texts, self.circle_colors): circle.set_color(color) text.set_color(color) inner_texts[-1].shift(2.8*LEFT+2.7*UP) inner_arrow = Arrow( inner_texts[-1].get_critical_point(DOWN), inner_texts[-1].get_critical_point(DOWN)+0.7*DR, buff = 0.1, ).set_color(self.circle_colors[-1]) inner_group = VGroup(inner_circles, inner_texts, inner_arrow) self.add(inner_group) self.wait() self.inner_circles = inner_circles self.inner_texts = inner_texts self.inner_arrow = inner_arrow class DFCInversionProofP1(DescartesTheoremExamples): CONFIG = { "remark_scale_text" : "示意图,图像并非真实比例", "orig_label_texts" : ["C_1", "C_2", "C_3", "C_4"], "inv_label_texts" : ["C_1'", "C_2'", "C_3'", "C_4'"], } def construct(self): super().add_inner_dfc() self.arrange_elements() self.add_labels() self.add_inversion_center() self.add_mapsto_symbol() self.add_not_to_scale_remark() self.wait() def arrange_elements(self): self.remove(self.inner_texts, self.inner_arrow) self.inner_circles.center().shift(4*UP) normal_form = FourCirclesNormalForm() normal_form.shift(4*DOWN) self.add(normal_form) self.normal_form = normal_form def add_labels(self): orig_labels = VGroup() for n, (circle, text) in enumerate(zip(self.inner_circles, self.orig_label_texts)): label = TexMobject(text).scale(1.2) label.set_color(circle.get_color()) label.move_to(circle.get_center()) orig_labels.add(label) inv_labels = VGroup() for n, (circle, text) in enumerate(zip(self.normal_form, self.inv_label_texts)): label = TexMobject(text).scale(1.2) label.set_color(circle.get_color()) label.move_to(circle.get_center()) inv_labels.add(label) c1, c2, c3, c4 = self.inner_circles l1, l2, l3, l4 = orig_labels c1i, c2i, c3i, c4i = self.normal_form l1i, l2i, l3i, l4i = inv_labels l4.next_to(c4.get_bottom(), UP, buff = 0.3) l3i.next_to(c3i, DOWN).to_edge(RIGHT) l4i.next_to(c4i, UP).to_edge(RIGHT) self.add(orig_labels, inv_labels) self.orig_labels = orig_labels self.inv_labels = inv_labels def add_inversion_center(self): c1, c2, c3, c4 = self.inner_circles inv_center = get_tangent_point(c3, c4) dot_O = Dot(inv_center, color = YELLOW) label_O = TexMobject("O", color = YELLOW).next_to(dot_O, UP) remark_O = TextMobject("反演中心", color = YELLOW) remark_O.next_to(dot_O, RIGHT, buff = 1.5) arrow_O = Arrow(remark_O.get_left(), dot_O.get_right(), color = YELLOW, buff = 0.2) orig_center_group = VGroup(dot_O, label_O, remark_O, arrow_O) inv_dot_O = VectorizedPoint() inv_dot_O.next_to(self.normal_form[-1], UP, buff = 1.4) inv_dot_O.shift(2*RIGHT) inv_center_group = orig_center_group.deepcopy() inv_center_group.shift(inv_dot_O.get_center() - dot_O.get_center()) self.add(orig_center_group, inv_center_group) self.orig_center_group = orig_center_group self.inv_center_group = inv_center_group def add_mapsto_symbol(self): mapsto = TexMobject("\\mapsto") mapsto.rotate(-PI/2) mapsto.scale(2.5) mapsto.next_to(self.inner_circles, DOWN) remark_mapsto = TextMobject("反演变换") remark_mapsto.next_to(mapsto, LEFT) self.add(mapsto, remark_mapsto) def add_not_to_scale_remark(self): remark_scale = TextMobject("(" + self.remark_scale_text + ")") remark_scale.scale(0.75) remark_scale.next_to(6.5*DL, RIGHT, buff = 0) self.add(remark_scale) class DFCInversionProofP2(DFCInversionProofP1): CONFIG = { "remark_scale_text" : "示意图,反演圆未标出,且图像并非真实比例", "inv_label_texts" : ["C_1'", "C_2'", "C_3':y=-1", "C_4':y=1"], "inv_center_coord_text" : "(x_0, y_0) \\, (y_0>1)", "circle_center_coord_texts" : ["(-1,0)", "(1,0)"], } def construct(self): super().construct() self.change_center_remarks() self.add_coord_system() self.change_inv_labels() self.wait() def change_center_remarks(self): for center_group in (self.orig_center_group, self.inv_center_group): dot, label, remark, arrow = center_group self.remove(remark, arrow) if center_group is self.inv_center_group: coord = TexMobject(self.inv_center_coord_text) coord.next_to(dot, RIGHT) coord.set_color(dot.get_color()) self.add(coord) def add_coord_system(self): c1, c2, c3, c4 = self.normal_form center_point = (c1.get_center() + c2.get_center()) / 2 unit_size = c1.get_height()/2 coord_system = Axes( center_point = center_point, number_line_config = {"unit_size" : unit_size}, y_min = -1.8, y_max = 2.8, ) self.add(coord_system) self.coord_system = coord_system def change_inv_labels(self): l1i, l2i, l3i, l4i = self.inv_labels for label, x_coord, coord_text in zip([l1i, l2i], [-1, 1], self.circle_center_coord_texts): center = self.coord_system.c2p(x_coord, 0) label.next_to(center, UP) dot_i = Dot(center, radius = 0.1).set_color(label.get_color()) coord_i = TexMobject(coord_text).set_color(label.get_color()).next_to(center, DOWN) self.add(dot_i, coord_i) ##### ## Inversion Advanced P2 Scenes class ApollonianGasketConstruction(ApollonianGasketScene): CONFIG = { "max_iter" : 8, "curvatures" : [2, 2, 3], "init_angle" : 0, "curv_thres" : 30000, "ag_config": { "agc_config" : { "radius_thres" : 1e-3, "circle_color" : BLUE, "label_color" : WHITE, }, }, "color_curr" : YELLOW, "wait_time" : 2, } def construct(self): r1, r2, r3 = [1./curv for curv in self.curvatures] p1, p2, p3 = calc_centers_by_radii(r1, r2, r3, init_angle = self.init_angle) agc1 = AGCircle(p1, r1, parents = None, **self.ag_config["agc_config"]) agc2 = AGCircle(p2, r2, parents = None, **self.ag_config["agc_config"]) agc3 = AGCircle(p3, r3, parents = None, **self.ag_config["agc_config"]) remark = TextMobject("(圆内数字为该圆的曲率)") remark.scale(0.75).to_corner(DL) self.add(remark) for k in range(self.max_iter): agcs_copy = [agc.deepcopy() for agc in (agc1, agc2, agc3)] ag = ApollonianGasket( *agcs_copy, num_iter = k, curv_thres = self.curv_thres, **self.ag_config ) iter_num = VGroup( TextMobject("迭代次数:"), TexMobject(f"{k}") ).arrange_submobjects(RIGHT).scale(1.5) iter_num.to_edge(LEFT, buff = 1) ag.scale(3.8) ag.shift(np.array([0, 3.8, 0]) - ag.get_top() + 3*RIGHT) VGroup(*ag.agc_list[-1]).set_color(self.color_curr) self.add(ag, iter_num) self.wait(self.wait_time) if k != self.max_iter-1: self.remove(ag, iter_num) class ApollonianGasketExample1(Scene): CONFIG = { "max_iter" : 20, "curvatures" : [3, 6, 7], "curvature_texts" : [-2, 3, 6, 7], "init_angle" : 0, "curv_thres" : 4000, "ag_config": { "agc_config" : { "radius_thres" : 1e-3, "circle_color" : BLUE, "label_color" : WHITE, }, }, "ag_scaling_factor" : 5.2, } def construct(self): r1, r2, r3 = [1./curv for curv in self.curvatures] p1, p2, p3 = calc_centers_by_radii(r1, r2, r3, init_angle = self.init_angle) agc1 = AGCircle(p1, r1, parents = None, **self.ag_config["agc_config"]) agc2 = AGCircle(p2, r2, parents = None, **self.ag_config["agc_config"]) agc3 = AGCircle(p3, r3, parents = None, **self.ag_config["agc_config"]) ag_seed = ApollonianGasket( *[agc.deepcopy() for agc in (agc1, agc2, agc3)], num_iter = 0, curv_thres = self.curv_thres, **self.ag_config ) ag_result = ApollonianGasket( *[agc.deepcopy() for agc in (agc1, agc2, agc3)], num_iter = self.max_iter, curv_thres = self.curv_thres, **self.ag_config ) ag_seed_center = ag_seed[0][0].get_right() ag_result_center = ag_result[0][0].get_right() arrow = Arrow(LEFT, RIGHT) figure_group = VGroup(ag_seed, ag_result, arrow) for ag, center, direction in zip( [ag_seed, ag_result], [ag_seed_center, ag_result_center], [4*LEFT, 4*RIGHT]): ag.scale(self.ag_scaling_factor) ag.shift(direction - center) figure_group.shift(DOWN) k1, k2, k3, k4 = list(map(str, self.curvature_texts)) title = TexMobject( f"({k1}+{k2}+{k3}+{k4})^2 = 2\\left[({k1})^2+{k2}^2+{k3}^2+{k4}^2 \\right]" ) title.set_width(13) title.set_color(YELLOW) title.to_edge(UP) self.add(figure_group, title) self.wait() class ApollonianGasketExample2(ApollonianGasketExample1): CONFIG = { "max_iter" : 20, "curvatures" : [5, 8, 12], "curvature_texts" : [-3, 5, 8, 12], "curv_thres" : 5000, "ag_config": { "agc_config" : { "radius_thres" : 5e-4, "circle_color" : BLUE, "label_color" : WHITE, }, }, "ag_scaling_factor" : 8, } class LoxodromicSpiralInTangentCircles(Scene): CONFIG = { "max_iter" : 20, "agc_config" : { "radius_thres" : 1, "circle_color" : BLUE, "label_color" : WHITE, }, "curve_config" : { "color" : YELLOW, "stroke_width" : 2, }, "alpha" : 0.6, "dashed_line_config" : { "color" : GREY, "stroke_width" : 0.5, "num_dashes" : 200, "positive_space_ratio" : 0.6, } } def construct(self): self.generate_circles() self.generate_curves() self.generate_labels() self.generate_lines() self.add_elements() self.zooming_in() def generate_circles(self): agcm2 = AGCircle(2/3.*UP, 1/3., **self.agc_config) agcm1 = AGCircle(RIGHT/2, 1/2., **self.agc_config) agczr = AGCircle(ORIGIN, -1, **self.agc_config) agcp1 = AGCircle(LEFT/2, 1/2., **self.agc_config) agcp2 = AGCircle(2/3.*DOWN, 1/3., **self.agc_config) agc_list = [agcm2, agcm1, agczr, agcp1, agcp2] for n in range(self.max_iter): A, B, C, known_agc = agc_list[:4] agc_m_k, agc_m_c = calc_new_agc_info(A, B, C, known_agc = known_agc) agc_m = AGCircle(agc_m_c, 1./agc_m_k, parents = (A, B, C), **self.agc_config) known_agc, C, B, A = agc_list[-4:] agc_p_k, agc_p_c = calc_new_agc_info(C, B, A, known_agc = known_agc) agc_p = AGCircle(agc_p_c, 1./agc_p_k, parents = (C, B, A), **self.agc_config) agc_list.insert(0, agc_m) agc_list.append(agc_p) agc_group = VGroup(*agc_list) agc_group.set_height(7.8) self.agc_list = agc_list self.agc_group = agc_group def generate_curves(self): agc_ps = self.agc_list[-self.max_iter-4:] agc_ps_points = [] loxo_curve_p_solid = VMobject(**self.curve_config) for k in range(len(agc_ps)-2): if k != 0: c1, c2, c3 = agc_ps[k], agc_ps[k+1], agc_ps[k+2] pt1 = get_tangent_point(c1, c2) pt2 = get_tangent_point(c2, c3) p = c2.get_center() if k != 1: agc_ps_points.extend( [pt1, p*(1-self.alpha)+pt1*self.alpha, p*(1-self.alpha)+pt2*self.alpha, pt2] ) else: agc_ps_points.extend( [pt1, p*0.7+pt1*0.3, p*0.6+pt2*0.4, pt2] ) else: c1, c2 = agc_ps[1], agc_ps[2] pt = get_tangent_point(c1, c2) agc_ps_points.extend([8*LEFT, 7*LEFT, 6*LEFT, pt]) loxo_curve_p_solid.append_points(agc_ps_points) loxo_curve_m_solid = loxo_curve_p_solid.deepcopy() loxo_curve_m_solid.rotate(PI, about_point = self.agc_group.get_center()) self.loxo_curve_p_solid = loxo_curve_p_solid self.loxo_curve_m_solid = loxo_curve_m_solid def generate_labels(self): labels = VGroup(*[ TexMobject("C_{%d}" % num, background_stroke_width = 0) for num in range(-self.max_iter-2, self.max_iter+3) ]) for label, circle in zip(labels, self.agc_group): label.set_height(circle.get_height()*0.15) label.move_to(circle.get_center()) label_c0 = labels[self.max_iter+2] label_c0.set_height(0.8) label_c0.next_to(self.agc_group.get_critical_point(UL), DR, buff = 0.1) self.labels = labels def generate_lines(self): agc_ps = self.agc_list[-self.max_iter-2:] line_p_solid = VMobject(**self.dashed_line_config) line_p_solid_corners = [8*LEFT] for circle in agc_ps: line_p_solid_corners.append(circle.get_center()) line_p_solid.set_points_as_corners(line_p_solid_corners) line_m_solid = line_p_solid.deepcopy() line_m_solid.rotate(PI, about_point = self.agc_group.get_center()) self.line_p_solid = line_p_solid self.line_m_solid = line_m_solid def add_elements(self): figure = VGroup( self.agc_group, self.loxo_curve_p_solid, self.loxo_curve_m_solid, self.line_p_solid, self.line_m_solid, self.labels, ) self.add(figure) self.figure = figure def zooming_in(self): self.figure.save_state() self.wait(0.5) self.play( ApplyMethod(self.figure.shift, -self.agc_group[-1].get_center()), run_time = 2, ) self.wait() for k in range(10): self.play( ApplyMethod(self.figure.scale, 2.5, {"about_point" : self.agc_group[-1].get_center()}), run_time = 2, ) self.wait() self.play(self.figure.restore, run_time = 15) self.wait(2) class ShowFordCircles(ZoomInOnFordCircles): CONFIG = { "q_max" : 30, } def construct(self): self.setup_axes() self.setup_circles_and_labels() self.add_remarks() self.first_zoom_in() self.wait() def first_zoom_in(self): self.zoom_in_on(1/2., 6) def add_remarks(self): nl_text = TextMobject("数轴") nl_arrow = Arrow(ORIGIN, UP).match_height(nl_text) nl_remark = VGroup(nl_arrow, nl_text) nl_remark.scale(0.8) nl_remark.set_color(LIGHT_GREY) nl_remark.arrange_submobjects(RIGHT, buff = 0.1) nl_remark.next_to(self.axes.coords_to_point(0, 0), DOWN, buff = 0.1) nl_remark.to_edge(LEFT, buff = 0.15) frac_remark = TextMobject("圆内分数为圆心横坐标") frac_remark.scale(0.6) frac_remark.to_corner(DL, buff = 0.15) self.add(nl_remark, frac_remark) class ShowFordCirclesDetails(ShowFordCircles): CONFIG = { "q_max" : 100, } def construct(self): super().construct() self.further_zoom_in() def setup_circles_and_labels(self): circles = VGroup() labels = VGroup() for q in range(1, self.q_max+1): for p in get_coprime_numers_by_denom(q): if (q <= 40) or (0.6 <= p/q <= 0.8): circle = self.generate_circle_by_fraction(p, q) circle.add_updater( lambda m: m.set_stroke(width = get_stroke_width_by_height(m.get_height())) ) label = AssembledFraction(p, q) label.set_height(circle.get_height() * self.label_height_factor) label.move_to(circle.get_center()) circles.add(circle) labels.add(label) self.add(circles, labels) self.circles = circles self.labels = labels def further_zoom_in(self): self.acl = VGroup(self.axes, self.circles, self.labels) self.acl.save_state() self.wait(0.5) self.play_zooming_animation(1/np.sqrt(2), 9, run_time = 5) self.wait() self.play_zooming_animation(0.73, 5, run_time = 4) self.wait() self.play_zooming_animation(0.74, 5, run_time = 4) self.wait() self.play(self.acl.restore, run_time = 5) self.wait(2) class ProveFordCirclesPropertiesP1(Scene): CONFIG = { "c1_frac" : [2, 3], "c2_frac" : [3, 4], "c3_frac" : [5, 7], "circle_config" : {"stroke_color" : BLUE, "stroke_width" : 2,}, "line_config" : {"stroke_color" : GREY, "stroke_width" : 2,}, "aux_line_config" : {"stroke_color" : GREY, "stroke_width" : 0.8,}, "polygon_config" : {"fill_color" : GREY, "fill_opacity" : 0.4, "stroke_width" : 0,}, } def setup(self): a, b = self.c1_frac c, d = self.c2_frac p, q = self.c3_frac r1 = 1/(2*b**2) r2 = 1/(2*d**2) r3 = 1/(2*q**2) c1_center = a/b*RIGHT + r1*UP c2_center = c/d*RIGHT + r2*UP c3_center = p/q*RIGHT + r3*UP c1 = Circle(arc_center = c1_center, radius = r1, **self.circle_config) c2 = Circle(arc_center = c2_center, radius = r2, **self.circle_config) c3 = Circle(arc_center = c3_center, radius = r3, **self.circle_config) c1_dot = SmallDot(color = GREY) c1_dot.add_updater(lambda m: m.move_to(c1.get_center())) c2_dot = SmallDot(color = GREY) c2_dot.add_updater(lambda m: m.move_to(c2.get_center())) c3_dot = SmallDot(color = GREY) c3_dot.add_updater(lambda m: m.move_to(c3.get_center())) line = Line( 2*c1.get_bottom()-c2.get_bottom(), 2*c2.get_bottom()-c1.get_bottom(), **self.line_config ) VGroup(c1, c2, c3, line).set_height(6).center().to_edge(UP) aux_line_1 = Line(c1.get_center(), c1.get_bottom(), **self.aux_line_config) aux_line_2 = Line(c2.get_center(), c2.get_bottom(), **self.aux_line_config) aux_line_3 = Line(c1.get_center(), c2.get_center(), **self.aux_line_config) aux_line_4 = Line(c1.get_bottom(), c2.get_bottom(), **self.aux_line_config) \ .shift(c2.get_height()/2*UP) polygon = Polygon( c1.get_center(), c2.get_center(), aux_line_4.get_start_and_end()[0], **self.polygon_config, ) l1 = TexMobject("\\dfrac{a}{b}").next_to(c1, DOWN) l2 = TexMobject("\\dfrac{c}{d}").next_to(c2, DOWN) l3 = TexMobject("\\dfrac{a+c}{b+d}").next_to(c3, DOWN) self.orig_group = VGroup(c1, c2, line, c1_dot, c2_dot, l1, l2) self.aux_group = VGroup(aux_line_1, aux_line_2, aux_line_3, aux_line_4, polygon) self.new_group = VGroup(c3, c3_dot, l3) def construct(self): self.add(self.orig_group, self.aux_group) self.wait() class ProveFordCirclesPropertiesP2(ProveFordCirclesPropertiesP1): def construct(self): self.add(self.orig_group, self.new_group) self.wait() class ShowFordCirclesFareySum(ZoomInOnFordCircles): pass # A rename, that's it. class DFCInversionProofP3(DFCInversionProofP2): CONFIG = { "remark_scale_text" : "示意图,反演圆未标出,且图像并非真实比例", "inv_label_texts" : ["C_1'", "C_2'", "C_3':\\mathrm{Im}(z)=-1", "C_4':\\mathrm{Im}(z)=1"], "inv_center_coord_text" : "z_0 = x_0+iy_0\\, (y_0>1)", "circle_center_coord_texts" : ["-1", "1"], } def construct(self): super().construct() self.wait() def add_coord_system(self): c1, c2, c3, c4 = self.normal_form center_point = (c1.get_center() + c2.get_center()) / 2 unit_size = c1.get_height()/2 coord_system = NumberPlane( center_point = center_point, number_line_config = {"unit_size" : unit_size}, y_min = -3, y_max = 3, background_line_style = { "stroke_color" : GREY, "stroke_width" : 1.5, "stroke_opacity" : 0.8, }, ) aux_coord_system = Axes( center_point = center_point, number_line_config = {"unit_size" : unit_size}, y_min = -3, y_max = 3, stroke_opacity = 0.8, ) self.add(coord_system, aux_coord_system) self.coord_system = coord_system class NormalFormIn3D(ThreeDScene): CONFIG = { "axis_unit_size" : 1.5, "axis_min" : -1.5, "axis_max" : 2.8, "resolution" : (60, 120), "plane_colors" : [GREEN, BLUE], "sphere_colors" : [MAROON_B, RED, PINK], } def construct(self): self.add_3d_stuff() self.add_2d_stuff() def add_3d_stuff(self): self.set_camera_orientation(theta = 70 * DEGREES, phi = 50 * DEGREES) axes = ThreeDAxes( x_min = self.axis_min, x_max = self.axis_max, y_min = self.axis_min, y_max = self.axis_max, z_min = self.axis_min, z_max = self.axis_max, number_line_config = {"unit_size" : self.axis_unit_size}, ) sphere_centers = [ axis.number_to_point(1) for axis in [axes.x_axis, axes.y_axis, axes.z_axis] ] radius = 1/np.sqrt(2) * self.axis_unit_size sphere_dots = VGroup(*[ Sphere( radius = 0.08, resolution = self.resolution, fill_opacity = 1, stroke_width = 0, ).move_to(sphere_center).set_color(color) for sphere_center, color in zip(sphere_centers, self.sphere_colors) ]) spheres = VGroup(*[ Sphere( radius = radius, resolution = self.resolution, fill_opacity = 0.6, stroke_width = 0.5, ).move_to(sphere_center).set_color(color) for sphere_center, color in zip(sphere_centers, self.sphere_colors) ]) planes = VGroup(*[ VGroup(*[ Square( side_length = 1, fill_opacity = fill_opacity, stroke_color = GREY, stroke_width = 0.3, stroke_opacity = 0.2, ) for k in range(n**2) ]).arrange_in_grid(n, n, buff = 0) \ .apply_matrix(z_to_vector([1, 1, 1])) \ .move_to(np.average(sphere_centers)) \ .shift(radius * normalize(direction)) \ .set_color(color) for n, fill_opacity, direction, color in zip( [7, 8], [0.2, 0.3], [np.ones(3), -np.ones(3)], self.plane_colors, ) ]) figure_group = VGroup(axes, planes, sphere_dots, spheres) figure_group.shift(RIGHT*2+0.5*OUT) self.add(figure_group) self.add(axes) self.add(planes) self.add(sphere_dots, spheres) def add_2d_stuff(self): sphere_remarks = VGroup(*[ TextMobject( "球:圆心为" + f"$({int(x)},{int(y)},{int(z)})$" + \ ",半径为" + "$\\dfrac{1}{\\sqrt{2}}$" ).set_color(color) for (x, y, z), color in zip([RIGHT, UP, OUT], self.sphere_colors) ]).arrange_submobjects(DOWN) plane_remarks = VGroup(*[ TexMobject( "\\text{平面:}" + "x+y+z=1" + sign + "\\dfrac{\\sqrt{3}}{\\sqrt{2}" ).set_color(color) for sign, color in zip(["+", "-"], self.plane_colors) ]).arrange_submobjects(DOWN) remarks = VGroup(sphere_remarks, plane_remarks) remarks.arrange_submobjects(DOWN, aligned_edge = LEFT) remarks.scale(0.8) remarks.to_corner(DR) self.add_fixed_in_frame_mobjects(remarks) self.wait() ##### ## Banner class Banner_Intro(Scene): CONFIG = { "circle_color" : YELLOW, "text_color" : BLUE, "inv_text_color" : BLUE, "circle_center" : 0.8*UP, "circle_radius" : 3, "grid_side_length" : 0.5, "x_range" : 300, "y_range" : 300, "dist_thres" : 300, } def construct(self): circle = Circle(color = self.circle_color, radius = self.circle_radius, stroke_width = 5) circle.move_to(self.circle_center) dot = SmallDot(self.circle_center, color = self.circle_color) text = TextMobject("Inversion", color = self.text_color, background_stroke_width = 3) text.rotate(PI/2.) text.move_to(0.4*RIGHT) text.apply_complex_function(np.exp) text.rotate(-PI/2.) text.scale(1.5) text.move_to(0.9*DOWN) inv_text = InversedVMobject(text, circle, use_dashed_vmob = False) inv_text.suspend_updating() inv_text.set_background_stroke(color = "#303030", width = 3) inv_text.set_stroke(width = 0) inv_text.set_fill(color = self.inv_text_color, opacity = 0.5) grid = VGroup(*[ Square( side_length = self.grid_side_length, stroke_width = 0, fill_opacity = 0.3, fill_color = CB_DARK if (i+j)%2==0 else CB_LIGHT ).move_to(self.circle_center + (i*RIGHT+j*UP)*self.grid_side_length) for i in range(-self.x_range, self.x_range+1, 1) for j in range(-self.y_range, self.y_range+1, 1) if np.sqrt(i**2+j**2) * self.grid_side_length < self.dist_thres ]) for square in grid: if is_close_in_R3(square.get_center(), self.circle_center): grid.remove(square) inv_grid = InversedVMobject(grid, circle, use_dashed_vmob = False) self.add(inv_grid, circle, dot, text, inv_text) self.wait() class Banner_AdvancedP1(ApollonianGasketScene): CONFIG = { "curvatures" : [570, 968, 1112], "init_angle" : PI/7, "num_iter" : 20, "curv_thres" : 1e6, "ag_config" : { "agc_config" : { "radius_thres" : 5e-6, "circle_color" : YELLOW, "label_color" : WHITE, }, }, "part_text" : "上篇", } def construct(self): super().construct() ag = self.ag ag.set_height(7) circle_myst = ag.agc_list[0][0] label_myst = circle_myst.label label_question = TexMobject("???") label_question.match_height(label_myst) label_question.move_to(label_myst) self.remove(label_myst) self.add(label_question) part = TextMobject(self.part_text) part.to_corner(DR) self.add(part) class Banner_AdvancedP2(Banner_AdvancedP1): CONFIG = { "part_text" : "下篇", }
40.915864
132
0.599125
= sp - n * unit_vec new_ep = ep + n * unit_vec Line.__init__(self, new_sp, new_ep, **kwargs) class DotLabel(VMobject): CONFIG = { "position" : UP, "label_buff" : 0.25, } def __init__(self, label_text, dot, **kwargs): VMobject.__init__(self, **kwargs) self.dot = dot label = TexMobject(label_text, **kwargs) if self.position is not None: label.add_updater( lambda l: l.next_to(self.dot.get_center(), self.position, buff = self.label_buff) ) self.add(label) def set_label(self, label): label.next_to(self.dot.get_center()) class TwoDotsSegment(Line): def __init__(self, dot_1, dot_2, **kwargs): self.dot_1 = dot_1 self.dot_2 = dot_2 sp, ep = self.get_dots_centers() Line.__init__(self, start = sp, end = ep, **kwargs) self.add_updater(self.set_start_and_end) def get_dots_centers(self): return self.dot_1.get_center(), self.dot_2.get_center() def set_start_and_end(self, line_mob): sp, ep = self.get_dots_centers() line_mob.put_start_and_end_on(sp, ep) class LengthLabel(DecimalNumber): CONFIG = { "num_decimal_places" : 3, "label_height" : 0.3, "label_buff" : 0.3, "offset" : 0, "is_on_opposite_side" : False, } def __init__(self, line_mob, **kwargs): DecimalNumber.__init__(self, **kwargs) self.line_mob = line_mob self.add_updater(self.set_label) def set_label(self, label): label.set_value(self.line_mob.get_length()) label.set_height(self.label_height) label.rotate(self.line_mob.get_angle()) side_factor = -1 if self.is_on_opposite_side else 1 label.move_to( self.line_mob.get_center() \ + self.line_mob.get_vector() / 2 * self.offset \ + side_factor * rotate_vector(self.line_mob.get_unit_vector(), PI/2) * self.label_buff ) def set_offset(self, offset): self.offset = offset return self def switch_side(self): self.is_on_opposite_side = not self.is_on_opposite_side return self class ManyDotsPolygon(VMobject): def __init__(self, *dots, **kwargs): VMobject.__init__(self, **kwargs) self.dots = dots dots_centers = self.get_dots_centers() polygon = Polygon(*dots_centers, **kwargs) polygon.add_updater(self.set_vertices) self.add(polygon) def get_dots_centers(self): return [dot.get_center() for dot in self.dots] def set_vertices(self, polygon_mob): vertices = self.get_dots_centers() polygon_mob.set_points_as_corners([*vertices, vertices[0]]) class AngleIndicator(VMobject): CONFIG = { "color" : RED, "radius" : 0.2, "fill_opacity" : 0.6, "is_minor_arc" : True, } def __init__(self, dot_A, dot_C, dot_B, **kwargs): VMobject.__init__(self, **kwargs) self.dot_A = dot_A self.dot_C = dot_C self.dot_B = dot_B sector = Sector() sector.add_updater(self.set_sector) self.add(sector) self.sector = sector def get_point_center(self, point_or_mob): if isinstance(point_or_mob, Mobject): return point_or_mob.get_center() else: return point_or_mob def get_point_centers(self): return tuple(map(self.get_point_center, [self.dot_A, self.dot_C, self.dot_B])) def set_sector(self, mob): pt_A, pt_C, pt_B = self.get_point_centers() start_angle, angle = self.get_angles() outer_radius = min([self.radius, get_norm(pt_C - pt_A)/2, get_norm(pt_C - pt_B)/2]) new_sector = Sector( start_angle = start_angle, angle = angle, outer_radius = outer_radius, color = self.color, fill_opacity = self.fill_opacity, stroke_width = 0 ) new_sector.move_arc_center_to(self.get_point_center(self.dot_C)) mob.become(new_sector) def get_angles(self): pt_A, pt_C, pt_B = self.get_point_centers() start_angle = angle_of_vector(pt_A - pt_C) end_angle = angle_of_vector(pt_B - pt_C) angle = (end_angle - start_angle) % TAU if self.is_minor_arc and angle > PI: angle -= TAU return start_angle, angle class RightAngleIndicator(VMobject): CONFIG = { "color" : WHITE, "side_length" : 0.2, "line_width" : 1, "square_opacity" : 0.5, } def __init__(self, dot_A, dot_C, dot_B, **kwargs): VMobject.__init__(self, **kwargs) self.dot_A = dot_A self.dot_C = dot_C self.dot_B = dot_B line = VMobject(stroke_width = self.line_width, fill_opacity = 0) square = VMobject(stroke_width = 0, fill_color = self.color, fill_opacity = self.square_opacity) line.add_updater(self.set_line) square.add_updater(self.set_square) self.add(square, line) self.line = line self.square = square def get_point_center(self, point_or_mob): if isinstance(point_or_mob, Mobject): return point_or_mob.get_center() else: return point_or_mob def get_point_centers(self): return tuple(map(self.get_point_center, [self.dot_A, self.dot_C, self.dot_B])) def get_norm_vectors(self): pt_A, pt_C, pt_B = self.get_point_centers() norm_vec_CA = normalize(pt_A - pt_C) norm_vec_CB = normalize(pt_B - pt_C) return norm_vec_CA, norm_vec_CB def get_corner_points(self): pt_A, pt_C, pt_B = self.get_point_centers() norm_vec_CA, norm_vec_CB = self.get_norm_vectors() side_length = min([self.side_length, get_norm(pt_A - pt_C)/2, get_norm(pt_B - pt_C)/2]) return ( pt_C, pt_C + norm_vec_CA * side_length, pt_C + norm_vec_CA * side_length + norm_vec_CB * side_length, pt_C + norm_vec_CB * side_length ) def set_line(self, line_mob): p, q, r, s = self.get_corner_points() line_mob.set_points_as_corners([q, r, s]) def set_square(self, square_mob): p, q, r, s = self.get_corner_points() square_mob.set_points_as_corners([p, q, r, s, p]) class InversedDot(VMobject): CONFIG = { "color" : PINK, "stroke_width" : 3, "fill_opacity" : 1, "is_hollow" : True, "center_color" : BLACK, } def __init__(self, orig_dot, circle, **kwargs): self.orig_dot = orig_dot self.circle = circle VMobject.__init__(self, **kwargs) def generate_points(self): if self.is_hollow: self.fill_color = self.center_color else: self.fill_color = self.color self.stroke_width = 0 inv_dot = Dot(ORIGIN, color = self.color) self.inv_dot = inv_dot self.add(inv_dot) self.add_updater_to_inversed_dot() def add_updater_to_inversed_dot(self): self.inv_dot.add_updater(self.move_inversed_dot) def move_inversed_dot(self, inv_dot): point = self.orig_dot.get_center() inv_center = self.circle.get_center() radius = self.circle.get_height() / 2. if is_close_in_R3(point, inv_center): pass else: inv_dot.move_to(inversion(point, inv_center, radius)) class InversedVMobject(VMobject): CONFIG = { "is_analytical" : True, "match_original_style" : False, "use_dashed_vmob" : True, "dashed_vmob_config": { "num_dashes" : 50, "positive_space_ratio" : 0.6, }, } def __init__(self, orig_vmob, circle, **kwargs): VMobject.__init__(self, **kwargs) self.orig_vmob = orig_vmob self.circle = circle self.orig_vmob_type = "Others" self.initialize_orig_vmob_type() self.add_updater_to_inversed_vmobject() def add_updater_to_inversed_vmobject(self): self.add_updater(self.set_inversed_vmobject) def initialize_orig_vmob_type(self): if isinstance(self.orig_vmob, Line): self.orig_vmob_type = "Line" elif isinstance(self.orig_vmob, Circle): self.orig_vmob_type = "Circle" else: self.orig_vmob_type = "Others" def set_orig_vmob_type(self, orig_vmob_type): self.orig_vmob_type = orig_vmob_type def set_inversed_vmobject(self, inv_vmob): inv_center = self.circle.get_center() radius = self.circle.get_height() / 2. if self.is_analytical and self.orig_vmob_type == "Line": # If it's a line... lp1, lp2 = self.orig_vmob.get_start_and_end() if is_on_the_line(inv_center, lp1, lp2): # then the inversion is just the line itself. temp_vmob = ExtendedLine(lp1, lp2) else: # If it's a line NOT through the inversion center, v_para, v_perp = get_para_and_perp_components(inv_center, lp1, lp2) d = distance_to_the_line(inv_center, lp1, lp2) inv_vmob_radius = fdiv(radius**2, 2*d) closepoint = inv_center + v_perp inv_vmob_closepoint = inversion(closepoint, inv_center, radius) inv_vmob_center = (inv_center + inv_vmob_closepoint) / 2. temp_vmob = FineCircle(radius = inv_vmob_radius) temp_vmob.move_to(inv_vmob_center) elif self.is_analytical and self.orig_vmob_type == "Circle": orig_vmob_center = self.orig_vmob.get_center() orig_vmob_radius = self.orig_vmob.get_height() / 2. center_vec = orig_vmob_center - inv_center d = get_norm(center_vec) if is_close(orig_vmob_radius, d): # If it's a circle passing through the inversion center, foot = inv_center + fdiv(radius**2, 2*d) * normalize(center_vec) lp1 = foot + rotate_vector(center_vec, PI/2) lp2 = foot + rotate_vector(center_vec, -PI/2) temp_vmob = ExtendedLine(lp1, lp2) else: # then the inversion is a circle NOT through the inversion center. dp1 = orig_vmob_center - orig_vmob_radius * normalize(center_vec) dp2 = orig_vmob_center + orig_vmob_radius * normalize(center_vec) inv_dp1 = inversion(dp1, inv_center, radius) inv_dp2 = inversion(dp2, inv_center, radius) inv_vmob_radius = get_norm(inv_dp2 - inv_dp1) / 2. inv_vmob_center = (inv_dp2 + inv_dp1) / 2. temp_vmob = FineCircle(radius = inv_vmob_radius) temp_vmob.move_to(inv_vmob_center) else: temp_vmob = self.orig_vmob.copy() temp_vmob.apply_function(lambda p: inversion(p, inv_center, radius)) if self.use_dashed_vmob: temp_vmob = DashedVMobject(temp_vmob, **self.dashed_vmob_config) inv_vmob.become(temp_vmob) if self.match_original_style: inv_vmob.match_style(self.orig_vmob) class FourCirclesNormalForm(VMobject): CONFIG = { "circle_colors" : [MAROON_B, RED, GREEN, BLUE], "r" : 1.2, "l" : 9, "use_dashed_vmob" : True, "dashed_vmob_config" : { "num_dashes" : 30, "positive_space_ratio" : 0.6, } } def __init__(self, **kwargs): VMobject.__init__(self, **kwargs) c1 = Circle(radius = self.r, **kwargs).shift(self.r*LEFT) c2 = Circle(radius = self.r, **kwargs).shift(self.r*RIGHT) c3 = Line(self.l*LEFT, self.l*RIGHT, **kwargs).shift(self.r*DOWN) c4 = Line(self.l*LEFT, self.l*RIGHT, **kwargs).shift(self.r*UP) for mob, color in zip([c1, c2, c3, c4], self.circle_colors): mob.set_color(color) if self.use_dashed_vmob: self.add(DashedVMobject(mob, **self.dashed_vmob_config)) else: self.add(mob) class DescartesFourCircles(VMobject): CONFIG = { "outer_circle_index" : None, "orig_circle_color" : BLUE, "new_circle_color" : YELLOW, "show_new_circles" : True, "show_new_circles_centers" : False, } def __init__(self, ccdot1, ccdot2, ccdot3, **kwargs): self.ccdot1 = ccdot1 self.ccdot2 = ccdot2 self.ccdot3 = ccdot3 VMobject.__init__(self, **kwargs) self.add_orig_circles() self.add_orig_circles_updaters() self.generate_new_circles() if self.show_new_circles: self.add_new_circles() if self.show_new_circles_centers: self.add_new_circles_centers() def add_orig_circles(self): self.c1, self.c2, self.c3 = self.cs = VGroup(*[ Circle(arc_center = cc, radius = r, color = self.orig_circle_color) for cc, r in zip(self.get_orig_circle_centers(), self.calc_radii_by_centers()) ]) self.add(self.cs) def add_orig_circles_updaters(self): def get_center(k): return self.get_orig_circle_centers()[k] def get_abs_radius(k): return np.abs(self.calc_radii_by_centers()[k]) # Since enumerate() won't work here (seriously?), self.c1.add_updater(lambda c: c.move_to(get_center(0))) self.c1.add_updater(lambda c: c.set_height(2*get_abs_radius(0))) self.c2.add_updater(lambda c: c.move_to(get_center(1))) self.c2.add_updater(lambda c: c.set_height(2*get_abs_radius(1))) self.c3.add_updater(lambda c: c.move_to(get_center(2))) self.c3.add_updater(lambda c: c.set_height(2*get_abs_radius(2))) def get_orig_circles(self): return self.cs def get_orig_circle_centers(self): return [dot.get_center() for dot in (self.ccdot1, self.ccdot2, self.ccdot3)] def get_orig_circle_radii(self): return self.calc_radii_by_centers() def get_orig_circle_curvatures(self): return [fdiv(1, radius) for radius in self.calc_radii_by_centers()] def calc_radii_by_centers(self): p1, p2, p3 = self.get_orig_circle_centers() d12 = get_norm(p2 - p1) d23 = get_norm(p3 - p2) d13 = get_norm(p3 - p1) sum_r = (d12 + d23 + d13) / 2. if self.outer_circle_index == 1: return [-sum_r, sum_r-d12, sum_r-d13] elif self.outer_circle_index == 2: return [sum_r-d12, -sum_r, sum_r-d23] elif self.outer_circle_index == 3: return [sum_r-d13, sum_r-d23, -sum_r] else: return [sum_r-d23, sum_r-d13, sum_r-d12] def generate_new_circles(self): self.c4_1, self.c4_2 = self.new_circles = VGroup(*[ Circle(arc_center = new_cc, radius = new_r, color = self.new_circle_color) for new_cc, new_r in self.calc_new_circles_centers_and_radii() ]) self.generate_new_circles_centers() self.add_new_circles_updaters() def calc_new_circles_centers_and_radii(self): k1, k2, k3 = self.get_orig_circle_curvatures() z1, z2, z3 = map(R3_to_complex, self.get_orig_circle_centers()) sum_k = k1 + k2 + k3 sum_k2 = k1**2 + k2**2 + k3**2 sum_k_cycle_prod = k1*k2 + k2*k3 + k3*k1 b = (-2)*sum_k c = sum_k2 - 2*sum_k_cycle_prod delta = b**2 - 4*c k4_1 = (-b + np.sqrt(delta)) / 2 k4_2 = (-b - np.sqrt(delta)) / 2 sum_kz = k1*z1 + k2*z2 + k3*z3 sum_k2z = k1**2 * z1 + k2**2 * z2 + k3**2 * z3 coeff_1 = (sum_k - k4_1) * k4_1 const_1 = 2 * sum_k2z - (sum_k + k4_1) * sum_kz z4_1 = const_1 / coeff_1 coeff_2 = (sum_k - k4_2) * k4_2 const_2 = 2 * sum_k2z - (sum_k + k4_2) * sum_kz z4_2 = const_2 / coeff_2 return [[complex_to_R3(z4_1), fdiv(1, k4_1)], [complex_to_R3(z4_2), fdiv(1, k4_2)]] def generate_new_circles_centers(self): ccdot4_1 = Dot(color = self.new_circle_color) ccdot4_1.add_updater(lambda m: m.move_to(self.c4_1.get_center())) ccdot4_2 = Dot(color = self.new_circle_color) ccdot4_2.add_updater(lambda m: m.move_to(self.c4_2.get_center())) self.ccdot4_1 = ccdot4_1 self.ccdot4_2 = ccdot4_2 def add_new_circles_updaters(self): def get_new_center(k): return self.calc_new_circles_centers_and_radii()[k][0] def get_abs_new_radius(k): return np.abs(self.calc_new_circles_centers_and_radii()[k][1]) # I have to use a much more direct approach - list them all. self.c4_1.add_updater(lambda c: c.move_to(get_new_center(0))) self.c4_1.add_updater(lambda c: c.set_height(2*get_abs_new_radius(0))) self.c4_2.add_updater(lambda c: c.move_to(get_new_center(1))) self.c4_2.add_updater(lambda c: c.set_height(2*get_abs_new_radius(1))) def add_new_circles(self): if not hasattr(self, "new_circles"): self.new_circles = generate_new_circles() self.add(self.new_circles) def get_new_circles(self): if not hasattr(self, "new_circles"): self.new_circles = generate_new_circles() return self.new_circles def add_new_circles_centers(self): self.add(self.ccdot4_1, self.ccdot4_2) def remove_new_circles_center(self): self.remove(self.ccdot4_1, self.ccdot4_2) ##### ## Inversion Introduction Scenes class ConceptsInInversion(Scene): CONFIG = { "color_circle" : YELLOW, "color_radius" : RED, "color_P" : WHITE, } def construct(self): self.add_backgrounds() self.move_around_point_P() def add_backgrounds(self): circle_O = Circle(radius = 3.5, color = self.color_circle) circle_O.shift(3*LEFT) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle_O.get_bottom(), UP) dot_O = Dot(circle_O.get_center(), color = self.color_circle) label_O = DotLabel("O", dot_O, color = self.color_circle, position = DOWN) remark_O = TextMobject("反演中心", color = self.color_circle) remark_O.next_to(label_O, LEFT, buff = 0.15) radius = Line(circle_O.get_center(), circle_O.get_left()) label_radius = TexMobject("R").scale(0.8) remark_radius = TextMobject("反演幂").scale(0.8) brace_radius = Brace(radius, UP) brace_radius.put_at_tip(label_radius) remark_radius.next_to(label_radius, LEFT, buff = 0.15) group_radius = VGroup(radius, label_radius, brace_radius, remark_radius) group_radius.set_color(self.color_radius) group_radius.rotate(-PI/12, about_point = dot_O.get_center()) def_inversion = TextMobject("反演变换:$P \\mapsto P'$") rlt_inversion = TexMobject("|OP| \\times |OP'|=", "R^2") rlt_inversion.next_to(def_inversion, DOWN, aligned_edge = RIGHT) rlt_inversion[-1].set_color(self.color_radius) remarks = VGroup(def_inversion, rlt_inversion) remarks.to_corner(DR) dot_P = Dot(LEFT, color = self.color_P) label_P = DotLabel("P", dot_P, color = self.color_P, position = DL, label_buff = 0.2) dot_Pi = InversedDot(dot_P, circle_O, color = self.color_P) label_Pi = DotLabel("P'", dot_Pi, color = self.color_P, position = DR, label_buff = 0.2) line_OP = TwoDotsSegment(dot_O, dot_P, stroke_width = 2) line_OPi = TwoDotsSegment(dot_O, dot_Pi, stroke_width = 2) self.add(remarks) self.add(group_radius) self.add(circle_O, dot_O, label_O, remark_O, remark_circle) self.add(dot_P, dot_Pi, label_P, label_Pi, line_OP, line_OPi) self.circle_O = circle_O self.dot_P = dot_P def move_around_point_P(self): self.dot_P.save_state() for dx, dy in [(-0.2, 0.3), (0.1, -0.4), (4, 0.3), (1, 1)]: vec = np.array([dx, dy, 0]) self.play(self.dot_P.shift, vec, run_time = 1) self.wait() self.play(self.dot_P.move_to, self.circle_O.get_right()) self.wait() self.play(self.dot_P.restore, run_time = 1) self.wait() class InversionExamples(Scene): CONFIG = { "color_circle" : YELLOW, } def construct(self): circle_O = Circle(radius = 3.5, color = self.color_circle) circle_O.shift(3*LEFT) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle_O.get_bottom(), UP) dot_O = Dot(circle_O.get_center(), color = self.color_circle) label_O = DotLabel("O", dot_O, color = self.color_circle, position = DOWN) init_shape = Square(side_length = 1.2, color = BLUE).rotate(TAU/13) init_shape.next_to(circle_O.get_right(), LEFT, buff = 0.5) init_shape.save_state() inv_shape = InversedVMobject(init_shape, circle_O, use_dashed_vmob = False) new_shapes = [ RegularPolygon(n = 6, start_angle = PI/7, color = PINK).scale(0.8), TexMobject("42", color = RED).scale(2.5).rotate(-PI/9), TexMobject("\\pi", color = MAROON_B).scale(5).rotate(PI/15), ] self.add(circle_O, remark_circle, dot_O, label_O) self.add(init_shape, inv_shape) for new_shape in new_shapes: new_shape.next_to(circle_O.get_right(), LEFT, buff = 0.6) self.play(Transform(init_shape, new_shape), run_time = 1) self.wait() init_shape.generate_target() init_shape.target.become(new_shape) init_shape.target.shift(get_random_vector(0.5)) random_angle = 0.5*np.random.random() init_shape.target.rotate(random_angle) self.play(MoveToTarget(init_shape, path_arc = random_angle, run_time = 1)), self.wait() self.play(ApplyMethod(init_shape.restore)) self.wait() class LineToLineInversion(Scene): CONFIG = { "color_circle" : YELLOW, "color_orig" : BLUE, "color_inv" : RED, } def construct(self): self.add_backgrounds() self.show_line_to_line_inversion() def add_backgrounds(self): circle_O = Circle(radius = 2.5, color = self.color_circle) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle_O.get_bottom(), UP) dot_O = Dot(circle_O.get_center(), color = self.color_circle) label_O = DotLabel("O", dot_O, color = self.color_circle, position = DOWN) conclusion = TextMobject("经过反演中心的直线", "$\\mapsto$", "经过反演中心的直线") conclusion.scale(0.8) conclusion[0].set_color(self.color_orig) conclusion[2].set_color(self.color_inv) conclusion.to_corner(DR) self.add(circle_O, remark_circle, dot_O, label_O) self.add(conclusion) self.circle_O = circle_O def show_line_to_line_inversion(self): angle_tracker = ValueTracker(-PI/11) position_tracker = ValueTracker(1.4) angle_tracker.save_state() position_tracker.save_state() orig_line = ExtendedLine(LEFT, RIGHT, color = self.color_orig, stroke_width = 8) orig_line.add_updater(lambda m: m.rotate(angle_tracker.get_value() - m.get_angle())) inv_line = ExtendedLine(LEFT, RIGHT, color = self.color_inv, stroke_width = 4) inv_line.add_updater(lambda m: m.rotate(angle_tracker.get_value() - m.get_angle())) dot_P = Dot(color = self.color_orig) dot_P.add_updater( lambda m: m.move_to( position_tracker.get_value() * rotate_vector(RIGHT, angle_tracker.get_value()) ) ) dot_Pi = InversedDot(dot_P, self.circle_O, is_hollow = False, color = self.color_inv) label_P = DotLabel("P", dot_P, position = DOWN, color = self.color_orig) label_Pi = DotLabel("P'", dot_Pi, position = DOWN, color = self.color_inv) def get_lb(): return LEFT_SIDE + UP * LEFT_SIDE[0] * np.tan(angle_tracker.get_value()) def get_rb(): return RIGHT_SIDE + UP * RIGHT_SIDE[0] * np.tan(angle_tracker.get_value()) def is_oolb(m): return m.get_right()[0] < LEFT_SIDE[0] def is_oorb(m): return m.get_left()[0] > RIGHT_SIDE[0] oolb_arrow = Arrow(ORIGIN, LEFT, color = self.color_inv).scale(2) oolb_arrow.add_updater(lambda m: m.set_angle(angle_tracker.get_value() + PI)) oolb_arrow.add_updater(lambda m: m.next_to(get_lb(), DOWN, aligned_edge = LEFT, buff = 0.2)) oorb_arrow = Arrow(ORIGIN, RIGHT, color = self.color_inv).scale(2) oorb_arrow.add_updater(lambda m: m.set_angle(angle_tracker.get_value())) oorb_arrow.add_updater(lambda m: m.next_to(get_rb(), DOWN, aligned_edge = RIGHT, buff = 0.2)) oolb_label = TexMobject("P'", color = self.color_inv, background_stroke_width = 0) oolb_label.add_updater(lambda m: m.next_to(oolb_arrow, DOWN, buff = 0.2)) oorb_label = TexMobject("P'", color = self.color_inv, background_stroke_width = 0) oorb_label.add_updater(lambda m: m.next_to(oorb_arrow, DOWN, buff = 0.2)) oolb_group = VGroup(oolb_arrow, oolb_label) oorb_group = VGroup(oorb_arrow, oorb_label) oolb_group.add_updater(lambda m: m.set_fill(opacity = 1 if is_oolb(label_Pi) else 0)) oolb_group.add_updater(lambda m: m.set_stroke(opacity = 1 if is_oolb(label_Pi) else 0)) oorb_group.add_updater(lambda m: m.set_fill(opacity = 1 if is_oorb(label_Pi) else 0)) oorb_group.add_updater(lambda m: m.set_stroke(opacity = 1 if is_oorb(label_Pi) else 0)) self.add(orig_line, inv_line, dot_P, dot_Pi, label_P, label_Pi) self.add(oolb_group, oorb_group) for d_position, d_angle in [(2, 0), (1, PI/10), (-5, 0), (-3, -PI/7), (4, PI/11)]: self.play( ApplyMethod(position_tracker.increment_value, d_position), ApplyMethod(angle_tracker.increment_value, d_angle), run_time = 2, ) self.wait() self.play( ApplyMethod(angle_tracker.restore), ApplyMethod(position_tracker.restore), run_time = 2, ) self.wait() class LineToCircleInversion(Scene): CONFIG = { "color_circle" : YELLOW, "color_orig" : BLUE, "color_inv" : RED, "line_config" : { "stroke_width" : 2, "color" : WHITE, }, } def construct(self): self.add_backgrounds() self.add_shapes() self.show_line_to_circle_inversion() def add_backgrounds(self): circle_O = Circle(radius = 3, color = self.color_circle) circle_O.shift(3*LEFT+0.5*UP) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle_O.get_bottom(), UP) dot_O = Dot(circle_O.get_center(), color = self.color_circle) label_O = DotLabel("O", dot_O, color = self.color_circle, position = DOWN) conclusion1 = TextMobject("不经过反演中心的直线", "$\\mapsto$", "经过反演中心的圆") conclusion1[0].set_color(self.color_orig) conclusion1[-1].set_color(self.color_inv) conclusion2 = TextMobject("经过反演中心的圆", "$\\mapsto$", "不经过反演中心的直线") conclusion2[0].set_color(self.color_inv) conclusion2[-1].set_color(self.color_orig) conclusions = VGroup(conclusion1, conclusion2) for c in conclusions: c.scale(0.8) conclusions.arrange_submobjects(DOWN, index_of_submobject_to_align = 1) conclusions.to_corner(DR) bg_rect = BackgroundRectangle(conclusions) self.add(circle_O, remark_circle) self.add_foreground_mobjects(dot_O, label_O, bg_rect, conclusions) self.dot_O = dot_O self.circle_O = circle_O self.conclusions = conclusions self.bg_rect = bg_rect def add_shapes(self): position_tracker = ValueTracker(2) line_angle_tracker = ValueTracker(PI*9/19) circle_angle_tracker = ValueTracker(PI/5) line = ExtendedLine(LEFT, RIGHT, color = self.color_orig) line.add_updater(lambda m: m.move_to(position_tracker.get_value() * RIGHT)) line.add_updater(lambda m: m.rotate(line_angle_tracker.get_value() - m.get_angle())) inv_line = InversedVMobject(line, self.circle_O, use_dashed_vmob = False, color = self.color_inv) inv_line_center = SmallDot(color = self.color_inv) inv_line_center.add_updater(lambda m: m.move_to(inv_line.get_center())) dot_Ai = Dot(color = self.color_inv) dot_Ai.add_updater( lambda m: m.move_to(inv_line.get_center() * 2 - self.circle_O.get_center()) ) dot_Pi = Dot(color = self.color_inv) dot_Pi.add_updater( lambda m: m.move_to( inv_line.get_center() \ + rotate_vector( inv_line.get_center() - self.circle_O.get_center(), circle_angle_tracker.get_value() ) ) ) dot_P = InversedDot(dot_Pi, self.circle_O, is_hollow = False, color = self.color_orig) dot_A = InversedDot(dot_Ai, self.circle_O, is_hollow = False, color = self.color_orig) line_OA, line_OAi, line_OP, line_OPi, line_AP, line_AiPi = aux_lines = VGroup(*[ TwoDotsSegment(pt_1, pt_2, **self.line_config) for pt_1, pt_2 in [ (self.dot_O, dot_A), (self.dot_O, dot_Ai), (self.dot_O, dot_P), (self.dot_O, dot_Pi), (dot_A, dot_P), (dot_Ai, dot_Pi) ] ]) ai_AiOPi = AngleIndicator(dot_Ai, self.dot_O, dot_Pi, color = MAROON_B, radius = 0.8) rtai_OAP = RightAngleIndicator(self.dot_O, dot_A, dot_P) rtai_OPiAi = RightAngleIndicator(self.dot_O, dot_Pi, dot_Ai) label_P = TexMobject("P", color = self.color_orig) label_Pi = TexMobject("P'", color = self.color_inv) label_A = TexMobject("A", color = self.color_orig) label_Ai = TexMobject("A'", color = self.color_inv) label_A.add_updater( lambda m: m.move_to( dot_A.get_center() + 0.3 * normalize(dot_A.get_center() - self.dot_O.get_center()) ) ) label_P.add_updater( lambda m: m.move_to( dot_P.get_center() + 0.3 * normalize(dot_A.get_center() - self.dot_O.get_center()) ) ) label_Ai.add_updater( lambda m: m.move_to( dot_Ai.get_center() + 0.4 * rotate_vector( normalize(dot_Ai.get_center() - inv_line_center.get_center()), -PI/4 ) ) ) label_Pi.add_updater( lambda m: m.move_to( dot_Pi.get_center() + 0.4 * normalize(dot_Pi.get_center() - inv_line_center.get_center()) ) ) def get_ub(): return line.get_center() + TOP + RIGHT * TOP[1] / np.tan(line_angle_tracker.get_value()) def get_bb(): return line.get_center() + BOTTOM + RIGHT * BOTTOM[1] / np.tan(line_angle_tracker.get_value()) def is_ooub(m): return m.get_bottom()[1] > TOP[1] def is_oobb(m): return m.get_top()[1] < BOTTOM[1] ooub_arrow = Arrow(ORIGIN, LEFT, color = self.color_orig).scale(2) ooub_arrow.add_updater(lambda m: m.set_angle(line_angle_tracker.get_value())) ooub_arrow.add_updater(lambda m: m.next_to(get_ub(), RIGHT, aligned_edge = TOP, buff = 0.2)) oobb_arrow = Arrow(ORIGIN, RIGHT, color = self.color_orig).scale(2) oobb_arrow.add_updater(lambda m: m.set_angle(line_angle_tracker.get_value() + PI)) oobb_arrow.add_updater(lambda m: m.next_to(get_bb(), RIGHT, aligned_edge = BOTTOM, buff = 0.2)) oolb_label = TexMobject("P", color = self.color_orig, background_stroke_width = 0) oolb_label.add_updater(lambda m: m.next_to(ooub_arrow, RIGHT, buff = 0.2)) oorb_label = TexMobject("P", color = self.color_orig, background_stroke_width = 0) oorb_label.add_updater(lambda m: m.next_to(oobb_arrow, RIGHT, buff = 0.2)) ooub_group = VGroup(ooub_arrow, oolb_label) oobb_group = VGroup(oobb_arrow, oorb_label) ooub_group.add_updater(lambda m: m.set_fill(opacity = 1 if is_ooub(label_P) else 0)) ooub_group.add_updater(lambda m: m.set_stroke(opacity = 1 if is_ooub(label_P) else 0)) oobb_group.add_updater(lambda m: m.set_fill(opacity = 1 if is_oobb(label_P) else 0)) oobb_group.add_updater(lambda m: m.set_stroke(opacity = 1 if is_oobb(label_P) else 0)) self.add(line, inv_line) self.add(dot_A, dot_P, dot_Ai, dot_Pi) self.add(label_P, label_Pi, label_A, label_Ai) self.add(aux_lines) self.add(ai_AiOPi, rtai_OAP, rtai_OPiAi) self.add(ooub_group, oobb_group) self.position_tracker = position_tracker self.line_angle_tracker = line_angle_tracker self.circle_angle_tracker = circle_angle_tracker def show_line_to_circle_inversion(self): play_args = [ [0, PI/12, 0, 2], [0, 0, PI*7/5, 4], [-2, PI/8, -PI/5, 3], [0, 0, PI*19/10, 6], [1.5, -PI/7, PI*2/5, 4], ] restore_arg = [ -sum([arg[k] for arg in play_args]) for k in range(len(play_args[0])) ] restore_arg[1] = (restore_arg[1] + PI) % (2*PI) - PI restore_arg[2] = (restore_arg[2] + PI) % (2*PI) - PI restore_arg[-1] = 3 play_args.append(restore_arg) for d_center, d_line_angle, d_circle_angle, run_time in play_args: self.play( ApplyMethod(self.position_tracker.increment_value, d_center), ApplyMethod(self.line_angle_tracker.increment_value, d_line_angle), ApplyMethod(self.circle_angle_tracker.increment_value, d_circle_angle), run_time = run_time, ) self.wait() class InversionCreateSimilarTriangles(Scene): CONFIG = { "random_seed" : 5+7-0, "num_of_nudges" : 5, "max_step" : 1, "color_A" : RED, "color_B" : BLUE, "color_combined" : MAROON_B, "color_circle": YELLOW, } def construct(self): self.add_remark() self.show_figure_animation() def add_remark(self): cond_1 = TexMobject("{|OP|", "\\over", "|OQ|}", "=", "{|OQ'|", "\\over", "|OP'|}") cond_2 = TexMobject("\\angle POQ", "=", "\\angle Q'OP'") conds = VGroup(cond_1, cond_2) conds.arrange_submobjects(DOWN, buff = 0.5) conds_rect = SurroundingRectangle(conds, color = WHITE) arrow = TexMobject("\\Downarrow") arrow.next_to(conds_rect, DOWN) concl = TexMobject("\\triangle OPQ", "\\sim", "\\triangle OQ'P'") concl.next_to(arrow, DOWN) for mob in (cond_1[0], cond_1[2], concl[0]): mob.set_color(self.color_A) for mob in (cond_1[-1], cond_1[-3], concl[-1]): mob.set_color(self.color_B) for mob in (cond_2[0], cond_2[-1]): mob.set_color(self.color_combined) remark = VGroup(conds, conds_rect, arrow, concl) remark.to_corner(DR) self.add(remark) def show_figure_animation(self): circle = Circle(radius = 3, color = self.color_circle) circle.move_to(3.5*LEFT) dot_O = Dot(color = self.color_combined) dot_O.add_updater(lambda m: m.move_to(circle.get_center())) dot_P = Dot(point = 1.2*UP+LEFT, color = self.color_A) dot_Q = Dot(point = 0.5*DOWN+1.9*LEFT, color = self.color_A) dot_Pi = InversedDot(dot_P, circle, is_hollow = False, color = self.color_B) dot_Qi = InversedDot(dot_Q, circle, is_hollow = False, color = self.color_B) triangle_OPQ = ManyDotsPolygon( dot_O, dot_P, dot_Q, color = self.color_A, stroke_width = 5, fill_opacity = 0.4 ) triangle_OPiQi = ManyDotsPolygon( dot_O, dot_Pi, dot_Qi, color = self.color_B, stroke_width = 2, fill_opacity = 0.3 ) label_O, label_P, label_Pi, label_Q, label_Qi = ( DotLabel( text, dot, color = color, position = position, background_stroke_width = 5, ).scale(0.8) for text, dot, color, position in zip( ["O", "P", "P'", "Q", "Q'"], [dot_O, dot_P, dot_Pi, dot_Q, dot_Qi], [self.color_combined, self.color_A, self.color_B, self.color_A, self.color_B], [LEFT, UP, UP, DOWN, DOWN] ) ) self.add(dot_O, dot_P, dot_Q, dot_Pi, dot_Qi) self.add(circle, triangle_OPQ, triangle_OPiQi) self.add(label_O, label_P, label_Pi, label_Q, label_Qi) dot_P.save_state() dot_Q.save_state() for k in range(self.num_of_nudges): nudge_P = get_random_vector(self.max_step) nudge_Q = get_random_vector(self.max_step) self.play( ApplyMethod(dot_P.shift, nudge_P), ApplyMethod(dot_Q.shift, nudge_Q), run_time = 2 ) self.wait() self.play(dot_P.restore, dot_Q.restore, run_time = 2) self.wait() class CircleToCircleInversionProof(Scene): CONFIG = { "color_O" : YELLOW, "color_A" : RED, "color_B" : BLUE, "color_combined" : MAROON_B, "label_buff" : 0.1, "label_scaling_factor" : 0.75, "line_config" : { "stroke_width" : 2, "color" : WHITE, }, } def construct(self): self.add_backgrounds() self.show_left_and_right_points() self.show_random_point() self.show_similar_triangles() self.show_complementary_property() self.show_inversion_result() def add_backgrounds(self): circle_O = Circle(radius = 3.2, color = self.color_O) circle_O.shift(3.5*LEFT) dot_O = Dot(circle_O.get_center(), color = self.color_O) remark_O = TextMobject("反演圆", color = YELLOW) remark_O.next_to(circle_O.get_bottom(), UP, buff = 0.4) circle_C = Circle(radius = 0.8, stroke_width = 2) circle_C.next_to(circle_O.get_right(), LEFT, buff = 0.5) dot_C = Dot(circle_C.get_center()) label_O, label_C = ( DotLabel( text, dot, color = color, position = DOWN, label_buff = self.label_buff ).scale(self.label_scaling_factor) for text, dot, color in zip(["O", "C"], [dot_O, dot_C], [self.color_O, WHITE]) ) for orig_mob in (circle_C, dot_C, label_C): orig_mob.set_sheen_direction(RIGHT) orig_mob.set_color([self.color_A, self.color_B]) inv_circle_template = InversedVMobject(circle_C, circle_O, use_dashed_vmob = False) inv_circle = Circle(radius = inv_circle_template.get_width()/2) inv_circle.move_to(inv_circle_template.get_center()) inv_circle.set_sheen_direction(LEFT) inv_circle.set_color([self.color_A, self.color_B]) self.add(circle_O, dot_O, circle_C, dot_C) self.add(label_O, label_C) self.add(remark_O) self.wait() self.circle_O = circle_O self.dot_O = dot_O self.remark_O = remark_O self.circle_C = circle_C self.dot_C = dot_C self.inv_circle = inv_circle def show_left_and_right_points(self): dot_A = Dot(color = self.color_A) dot_A.move_to(self.circle_C.get_left()) dot_B = Dot(color = self.color_B) dot_B.move_to(self.circle_C.get_right()) dot_Ai = InversedDot(dot_A, self.circle_O, is_hollow = False, color = self.color_A) dot_Bi = InversedDot(dot_B, self.circle_O, is_hollow = False, color = self.color_B) dot_Q = Dot((dot_Ai.get_center() + dot_Bi.get_center()) / 2) line_OB = Line(self.dot_O.get_center(), dot_B.get_center(), **self.line_config) line_OAi = Line(self.dot_O.get_center(), dot_Ai.get_center(), **self.line_config) label_A, label_Ai, label_B, label_Bi = ( DotLabel( text, dot, color = color, position = position, label_buff = self.label_buff ).scale(self.label_scaling_factor) for text, dot, color, position in zip( ["A", "A'", "B", "B'"], [dot_A, dot_Ai, dot_B, dot_Bi], [self.color_A, self.color_A, self.color_B, self.color_B], [DL, DR, DR, DL] ) ) remark_AB = TextMobject("圆心连线 \\\\ 的交点...").scale(0.6) remark_AB.next_to(VGroup(dot_A, dot_B), DOWN, buff = 1) arrows_AB = VGroup(*[ Arrow(remark_AB.get_critical_point(direction), dot, buff = 0.1) for direction, dot in zip([UL, UR], [dot_A, dot_B]) ]) remark_AiBi = TextMobject("...以及它们的反点").scale(0.8) remark_AiBi.next_to(VGroup(dot_Ai, dot_Bi), DOWN, buff = 1) arrows_AiBi = VGroup(*[ Arrow(remark_AiBi.get_critical_point(direction), dot, buff = 0.1) for direction, dot in zip([UR, UL], [dot_Ai, dot_Bi]) ]) self.play(ShowCreation(line_OB)) self.play(Write(dot_A), Write(dot_B), Write(label_A), Write(label_B)) self.wait() self.play(Write(remark_AB), ShowCreation(arrows_AB)) self.wait() self.play( ReplacementTransform(dot_A.deepcopy(), dot_Ai), ReplacementTransform(dot_B.deepcopy(), dot_Bi), ) self.play(Write(label_Ai), Write(label_Bi)) self.wait() self.play( ReplacementTransform(remark_AB, remark_AiBi), ReplacementTransform(arrows_AB, arrows_AiBi) ) self.play(ReplacementTransform(line_OB, line_OAi)) self.play(FadeOut(VGroup(remark_AiBi, arrows_AiBi))) self.wait() self.dot_A = dot_A self.dot_Ai = dot_Ai self.dot_B = dot_B self.dot_Bi = dot_Bi self.dot_Q = dot_Q self.line_OAi = line_OAi self.dots_AB = VGroup(dot_A, dot_Ai, dot_B, dot_Bi) self.labels_AB = VGroup(label_A, label_Ai, label_B, label_Bi) def show_random_point(self): angle_tracker = ValueTracker(PI/3) dot_P = Dot() dot_P.add_updater( lambda m: m.move_to( self.circle_C.point_at_angle(angle_tracker.get_value() % TAU) ) ) dot_P.add_updater( lambda m: m.set_color( interpolate_color( self.color_A, self.color_B, (dot_P.get_center()[0] - self.dot_A.get_center()[0]) / (self.dot_B.get_center()[0] - self.dot_A.get_center()[0]) ) ) ) label_P = DotLabel("P", dot_P, position = None) label_P.scale(0.8) label_P.add_updater(lambda m: m.set_color(dot_P.get_color())) label_P.add_updater( lambda m: m.move_to(dot_P.get_center() * 1.4 - self.dot_C.get_center() * 0.4) ) arrow_P = Vector(DR, buff = 0, color = WHITE).scale(0.5) arrow_P.add_updater(lambda m: m.next_to(dot_P, UL, buff = 0.1)) remark_P = TextMobject("圆上任意一点...").scale(0.75) remark_P.add_updater(lambda m: m.next_to(arrow_P, UL, buff = 0.1)) dot_Pi = InversedDot(dot_P, self.circle_O, is_hollow = False) dot_Pi.add_updater(lambda m: m.set_color(dot_P.get_color())) label_Pi = DotLabel("P'", dot_Pi, position = None) label_Pi.scale(0.8) label_Pi.add_updater(lambda m: m.set_color(dot_Pi.get_color())) label_Pi.add_updater( lambda m: m.move_to(dot_Pi.get_center() * 1.1 - self.inv_circle.get_center() * 0.1) ) arrow_Pi = Vector(DL, buff = 0, color = WHITE).scale(0.5) arrow_Pi.add_updater(lambda m: m.next_to(dot_Pi, UR, buff = 0.1)) remark_Pi = TextMobject("...以及它的反点").scale(0.75) remark_Pi.add_updater(lambda m: m.next_to(arrow_Pi, UR, buff = 0.1)) line_OP, line_OPi, line_AP, line_AiPi, line_BP, line_BiPi = aux_lines = VGroup(*[ TwoDotsSegment(pt_1, pt_2, **self.line_config) for pt_1, pt_2 in [ (self.dot_O, dot_P), (self.dot_O, dot_Pi), (self.dot_A, dot_P), (self.dot_Ai, dot_Pi), (self.dot_B, dot_P), (self.dot_Bi, dot_Pi) ] ]) rtai_APB = RightAngleIndicator(self.dot_A, dot_P, self.dot_B) rtai_BiPiAi = RightAngleIndicator(self.dot_Bi, dot_Pi, self.dot_Ai, side_length = 0.5) self.play(Write(dot_P), Write(label_P)) self.play(ShowCreation(arrow_P), Write(remark_P)) self.play(Write(line_AP), Write(line_BP)) self.play(ShowCreation(rtai_APB)) self.wait() self.play(ReplacementTransform(dot_P.deepcopy(), dot_Pi)) self.play(Write(label_Pi)) self.play( ReplacementTransform(arrow_P.deepcopy(), arrow_Pi), ReplacementTransform(remark_P.deepcopy(), remark_Pi), ) self.play(angle_tracker.increment_value, PI/6, run_time = 2) self.play(FadeOut(VGroup(arrow_P, remark_P, arrow_Pi, remark_Pi))) self.wait() self.play(Write(VGroup(line_OP, line_OPi, line_AiPi, line_BiPi))) self.wait() self.dot_P = dot_P self.dot_Pi = dot_Pi self.rtai_APB = rtai_APB self.rtai_BiPiAi = rtai_BiPiAi self.angle_tracker = angle_tracker self.aux_lines = aux_lines self.dots_P = VGroup(dot_P, dot_Pi) self.labels_P = VGroup(label_P, label_Pi) self.rtais = VGroup(self.rtai_APB, self.rtai_BiPiAi) def show_similar_triangles(self): ai_OAP = AngleIndicator(self.dot_O, self.dot_A, self.dot_P, radius = 0.3, color = self.color_A) ai_OBP = AngleIndicator(self.dot_O, self.dot_B, self.dot_P, radius = 0.4, color = self.color_B) ai_OPiAi = AngleIndicator(self.dot_O, self.dot_Pi, self.dot_Ai, radius = 0.3, color = self.color_A) ai_OPiBi = AngleIndicator(self.dot_O, self.dot_Pi, self.dot_Bi, radius = 0.4, color = self.color_B) triangle_OAP, triangle_OPiAi, triangle_OBP, triangle_OPiBi = [ ManyDotsPolygon( pt_1, pt_2, pt_3, color = self.color_combined, stroke_width = 0, fill_opacity = 0.4 ) for pt_1, pt_2, pt_3 in ( (self.dot_O, self.dot_A, self.dot_P), (self.dot_O, self.dot_Pi, self.dot_Ai), (self.dot_O, self.dot_B, self.dot_P), (self.dot_O, self.dot_Pi, self.dot_Bi), ) ] remark_sim_A = TexMobject("\\triangle OAP", "\\sim", "\\triangle OP'A'") remark_sim_B = TexMobject("\\triangle OBP", "\\sim", "\\triangle OP'B'") remark_arrow = TexMobject("\\Downarrow") remark_angle_A = TexMobject("\\angle OAP", "=", "\\angle OP'A'") remark_angle_B = TexMobject("\\angle OBP", "=", "\\angle OP'B'") remarks_A = VGroup(remark_sim_A, remark_arrow, remark_angle_A) remarks_B = VGroup(remark_sim_B, remark_arrow, remark_angle_B) remarks_A.arrange_submobjects(DOWN) remarks_A.next_to(self.dot_Q, DOWN, buff = 1) remark_sim_B.move_to(remark_sim_A.get_center()) remark_angle_B.move_to(remark_angle_A.get_center()) for remark, color in ([remark_sim_A, self.color_combined], [remark_sim_B, self.color_combined], \ [remark_angle_A, self.color_A], [remark_angle_B, self.color_B]): remark[0].set_color(color) remark[-1].set_color(color) self.play(Write(remark_sim_A)) self.play(FadeInFromDown(VGroup(remark_arrow, remark_angle_A))) self.wait() self.play(ShowCreation(triangle_OAP), ShowCreation(ai_OAP)) self.wait() self.play( ReplacementTransform(triangle_OAP, triangle_OPiAi), ReplacementTransform(ai_OAP.deepcopy(), ai_OPiAi), ) self.play(FadeOut(triangle_OPiAi)) self.wait() self.play(ReplacementTransform(remarks_A, remarks_B)) self.wait() self.play(ShowCreation(triangle_OBP), ShowCreation(ai_OBP)) self.wait() self.play( ReplacementTransform(triangle_OBP, triangle_OPiBi), ReplacementTransform(ai_OBP.deepcopy(), ai_OPiBi), ) self.play(FadeOut(remarks_B), FadeOut(triangle_OPiBi)) self.wait() self.ai_OAP = ai_OAP self.ai_OBP = ai_OBP self.ai_OPiAi = ai_OPiAi self.ai_OPiBi = ai_OPiBi self.ais = VGroup(ai_OAP, ai_OBP, ai_OPiAi, ai_OPiBi) def show_complementary_property(self): ai_OAP_copy = self.ai_OAP.deepcopy() ai_OBP_copy = self.ai_OBP.deepcopy() rtai_APB_copy = self.rtai_APB.deepcopy() for ai_copy in (ai_OAP_copy, ai_OBP_copy, rtai_APB_copy): ai_copy.clear_updaters() comp_prop = VGroup(ai_OAP_copy, TexMobject("="), ai_OBP_copy, TexMobject("+"), rtai_APB_copy) comp_prop.arrange_submobjects(RIGHT) comp_prop.scale(1.2) comp_prop.next_to(self.circle_O.get_top(), DOWN, buff = 1) self.play( ReplacementTransform(self.ai_OAP.deepcopy(), ai_OAP_copy), ReplacementTransform(self.ai_OBP.deepcopy(), ai_OBP_copy), ReplacementTransform(self.rtai_APB.deepcopy(), rtai_APB_copy), ) self.play(Write(comp_prop[1]), Write(comp_prop[3])) self.wait() self.play(ReplacementTransform(rtai_APB_copy.deepcopy(), self.rtai_BiPiAi)) self.wait() for ai in self.ais: ai.clear_updaters() self.play( FadeOut(comp_prop), FadeOut(self.ais), FadeOut(self.labels_AB), FadeOut(self.labels_P), ) self.wait() def show_inversion_result(self): inv_circle_copy = self.inv_circle.deepcopy() self.play(self.angle_tracker.set_value, PI, run_time = 2) self.wait() def update_inv_circle(inv_circle): angle = self.angle_tracker.get_value() if (angle <= -PI) or (angle > PI): alpha = 1 else: QPi = self.dot_Pi.get_center() - self.dot_Q.get_center() QAi = self.dot_Ai.get_center() - self.dot_Q.get_center() theta = angle_between(QPi, QAi) if self.dot_Pi.get_center()[1] < self.dot_Q.get_center()[1]: theta = 2*PI - theta alpha = theta / (2*PI) inv_circle.become(inv_circle_copy.get_subcurve(0, alpha)) self.inv_circle.add_updater(update_inv_circle) self.add(self.inv_circle) self.play( ApplyMethod(self.angle_tracker.increment_value, -2*PI), run_time = 5, ) self.inv_circle.clear_updaters() for line in self.aux_lines: line.clear_updaters() self.play( FadeOut(self.dots_AB), FadeOut(self.dots_P), FadeOut(self.rtais), FadeOut(self.line_OAi), FadeOut(self.aux_lines) ) self.wait() color_template = Square( stroke_width = 0, fill_opacity = 1, fill_color = [self.color_A, self.color_B] ) conclusion = TextMobject("不经过反演中心的圆", "$\\mapsto$", "不经过反演中心的圆") conclusion.scale(0.8) conclusion[0].set_color_by_gradient(self.color_A, self.color_B) conclusion[2].set_color_by_gradient(self.color_B, self.color_A) conclusion.to_corner(DR) self.play(Write(conclusion)) self.wait(3) self.play(FadeOut(conclusion), FadeOut(self.inv_circle)) self.wait() class ConcentricPropertyDoesNotHold(Scene): def setup(self): N = 8 self.circle_radii = [0.9-0.1*k for k in range(N)] self.dot_radii = [0.08-0.005*k for k in range(N)] self.circle_colors = color_gradient([BLUE, GREEN, RED], N) def construct(self): orig_circles = VGroup(*[ Circle(radius = radius, stroke_width = 1.5,color = color) for radius, color in zip(self.circle_radii, self.circle_colors)] ) orig_circles.shift(2*LEFT+0.5*DOWN) orig_circles_centers = VGroup(*[ Dot(circle.get_center(), radius = radius, color = color) for circle, radius, color in zip(orig_circles, self.dot_radii, self.circle_colors) ]) circle = Circle(radius = 3, color = YELLOW) circle.shift(3.8*LEFT+0.5*DOWN) circle_center = Dot(circle.get_center(), color = YELLOW) inv_circles = VGroup(*[ InversedVMobject(orig_circle, circle).clear_updaters().set_color(color) for orig_circle, color in zip(orig_circles, self.circle_colors) ]) inv_circles_centers = VGroup(*[ Dot(inv_circle.get_center(), color = color) for inv_circle, color in zip(inv_circles, self.circle_colors) ]) circle_text = TextMobject("反演圆", color = YELLOW) circle_text.next_to(circle.get_bottom(), UP, buff = 0.4) orig_circles_text = TextMobject("同心的圆", color = WHITE) orig_circles_text.next_to(orig_circles, UP) orig_circles_text.to_edge(UP, buff = 0.4) inv_circles_text = TextMobject("不同心的像", color = WHITE) inv_circles_text.next_to(inv_circles, UP) inv_circles_text.to_edge(UP, buff = 0.4) arrow = Arrow(orig_circles_text.get_right(), inv_circles_text.get_left()) self.add(circle, circle_center) self.add(orig_circles, orig_circles_centers) self.add(inv_circles, inv_circles_centers) self.add(circle_text, orig_circles_text, inv_circles_text, arrow) self.wait() class DemonstratePtolemyInequality(Scene): CONFIG = { "R" : 2.7, "angle_A" : -PI*2/3, "angle_B" : PI*4/5, "angle_D" : -PI/5, "radius_C" : 3.2, "angle_C" : PI/5, } def construct(self): radius_tracker = ValueTracker(self.radius_C) angle_tracker = ValueTracker(self.angle_C) circle = Circle(radius = self.R, color = WHITE, stroke_width = 1) circle.shift(DOWN) dashed_circle = DashedVMobject(circle, num_dashes = 100, positive_space_ratio = 0.5) dot_A, dot_B, dot_C, dot_D = dots = VGroup(*[ Dot(circle.point_at_angle(angle % TAU), color = WHITE) for angle in (self.angle_A, self.angle_B, self.angle_C, self.angle_D) ]) dot_C.add_updater( lambda m: m.move_to( circle.get_center() + radius_tracker.get_value() * \ rotate_vector(RIGHT, angle_tracker.get_value()) ) ) dot_labels = VGroup(*[ DotLabel(text, dot, position = position, label_buff = 0.1) for text, dot, position in zip( ["A", "B", "C", "D"], dots, [DL, UL, UR, DR] ) ]) lines = VGroup(*[ TwoDotsSegment(dot_1, dot_2) for dot_1, dot_2 in ( [dot_B, dot_A], [dot_A, dot_C], [dot_A, dot_D], [dot_B, dot_C], [dot_B, dot_D], [dot_C, dot_D], ) ]) length_labels = VGroup(*[LengthLabel(line) for line in lines]) length_labels[0].switch_side() length_labels[2].switch_side() length_labels[1].set_offset(-0.4) length_labels[-2].set_offset(-0.4) def get_sums(): AB, AC, AD, BC, BD, CD = [line.get_length() for line in lines] sum_lhs = AB * CD + AD * BC sum_rhs = AC * BD return sum_lhs, sum_rhs relation_eq = TexMobject( "|AB| \\cdot |CD| + |AD| \\cdot |BC|", "=", "|AC| \\cdot |BD|", background_stroke_width = 0, ) relation_neq = TexMobject( "|AB| \\cdot |CD| + |AD| \\cdot |BC|", ">", "|AC| \\cdot |BD|", background_stroke_width = 0, ) relation_eq[1].set_color(GREEN) relation_neq[1].set_color(RED) relation_eq.to_edge(UP, buff = 1.2) for eq_mob, neq_mob in zip(relation_eq, relation_neq): neq_mob.move_to(eq_mob.get_center()) lhs, eq_sign, rhs = relation_eq neq_sign = relation_neq[1] label_lhs = DecimalNumber(num_decimal_places = 4, show_ellipsis = True) label_rhs = DecimalNumber(num_decimal_places = 4, show_ellipsis = True) label_lhs.add_updater(lambda m: m.set_value(get_sums()[0])) label_rhs.add_updater(lambda m: m.set_value(get_sums()[1])) brace_lhs = Brace(lhs, UP, buff = 0.1) brace_rhs = Brace(rhs, UP, buff = 0.1) brace_lhs.put_at_tip(label_lhs) brace_rhs.put_at_tip(label_rhs) def get_indication_color(thres = 1e-2): return GREEN if is_close(radius_tracker.get_value(), self.R, thres = thres) else RED def get_indication_opacity(thres = 1e-2): return 0 if is_close(radius_tracker.get_value(), self.R, thres = thres) else 1 figure_group = VGroup(dashed_circle, dots, lines, length_labels, dot_labels) figure_group.add_updater(lambda m: m.set_color(get_indication_color())) relation_group = VGroup(lhs, eq_sign, rhs, neq_sign, brace_lhs, brace_rhs, label_lhs, label_rhs) label_lhs.add_updater(lambda m: m.set_color(get_indication_color())) label_rhs.add_updater(lambda m: m.set_color(get_indication_color())) eq_sign.add_updater(lambda m: m.set_opacity(1 - get_indication_opacity())) neq_sign.add_updater(lambda m: m.set_opacity(get_indication_opacity())) self.add(figure_group) self.add(relation_group) deltas = [ (0.5, -0.1), (0, -0.4), (-1, 0.3), (0, 0.4), (-1, 0), (0.3, -0.2), (0.7, -0.3), ] radius_tracker.save_state() angle_tracker.save_state() for d_radius, d_angle in deltas: self.play( ApplyMethod(radius_tracker.increment_value, d_radius), ApplyMethod(angle_tracker.increment_value, d_angle), run_time = 2, ) self.wait() self.play( ApplyMethod(radius_tracker.restore), ApplyMethod(angle_tracker.restore), run_time = 2, ) self.wait() class PtolemyInversionFigure(Scene): CONFIG = { "R" : 3.8, "r" : 1.3, "angle_A" : PI, "angle_B" : PI/3, "angle_C" : -PI/9, "angle_D" : -PI*2/7, "color_circle" : YELLOW, "color_ABD" : BLUE, } def construct(self): circle_ABD = Circle(radius = self.r, color = self.color_ABD, stroke_width = 3) circle_ABD.shift(0.2*LEFT) dot_A, dot_B, dot_C, dot_D = dots = VGroup(*[ Dot(circle_ABD.point_at_angle(angle % TAU), color = WHITE) for angle in (self.angle_A, self.angle_B, self.angle_C, self.angle_D) ]) dot_A.set_color(self.color_circle) dot_C.shift(0.4*RIGHT) circle = Circle(radius = self.R, color = self.color_circle, stroke_width = 5) circle.move_to(dot_A.get_center()) remark_circle = TextMobject("反演圆", color = self.color_circle) remark_circle.next_to(circle.get_bottom(), UP) label_A, label_B, label_C, label_D = dot_labels = VGroup(*[ DotLabel(text, dot, position = position, label_buff = 0.2) for text, dot, position in zip( ["A", "B", "C", "D"], dots, [DL, UP, DOWN, DOWN] ) ]) label_A.set_color(self.color_circle) dot_Bi, dot_Ci, dot_Di = inv_dots = VGroup(*[ InversedDot(dot, circle, is_hollow = False, color = WHITE) for dot in (dot_B, dot_C, dot_D) ]) label_Bi, label_Ci, label_Di = inv_dot_labels = VGroup(*[ DotLabel(text, dot, position = RIGHT, label_buff = 0.2) for text, dot in zip(["B'", "C'", "D'"], [dot_Bi, dot_Ci, dot_Di]) ]) lines = VGroup(*[ TwoDotsSegment(dot_1, dot_2, stroke_width = 1) for dot_1, dot_2 in ( [dot_A, dot_B], [dot_A, dot_C], [dot_A, dot_D], [dot_B, dot_C], [dot_B, dot_D], [dot_C, dot_D], [dot_A, dot_Bi], [dot_A, dot_Ci], [dot_A, dot_Di], [dot_Bi, dot_Ci], [dot_Bi, dot_Di], [dot_Ci, dot_Di], ) ]) inv_circle_ABD = InversedVMobject(circle_ABD, circle, use_dashed_vmob = False) inv_circle_ABD.add_updater(lambda m: m.set_color(self.color_ABD)) inv_circle_ABD.add_updater(lambda m: m.set_stroke(width = 2)) self.add(circle, remark_circle, circle_ABD, inv_circle_ABD) self.add(dots, dot_labels, inv_dots, inv_dot_labels, lines) self.add() self.wait() ##### ## Inversion Advanced P1 Scenes class KissingCirclesPuzzle(Scene): def construct(self): self.show_figure() self.show_question() def show_figure(self): type_text_1 = TextMobject("外切-外切-外切") type_text_2 = TextMobject("内切-内切-外切") type_text_1.move_to(LEFT_SIDE/2) type_text_2.move_to(RIGHT_SIDE/2) type_text_1.to_edge(DOWN) type_text_2.to_edge(DOWN) dot_l1, dot_l2, dot_l3 = dots_l = VGroup(*[ VectorizedPoint(np.array([coords[0], coords[1], 0]), color = BLUE) for coords in [(-3.9, 1.5), (-4.9, 0.0), (-2.8, -1.0)] ]) dot_r1, dot_r2, dot_r3 = dots_r = VGroup(*[ VectorizedPoint(np.array([coords[0], coords[1], 0]), color = BLUE) for coords in [(4.6, 0.3), (3.9, 0.6), (3.5, 1.6)] ]) dfc_l = DescartesFourCircles(*dots_l, show_new_circles = False) dfc_r = DescartesFourCircles(*dots_r, show_new_circles = False, outer_circle_index = 2) for dfc in [dfc_l, dfc_r]: for mob in dfc.get_orig_circles(): mob.set_stroke(width = 2, color = BLUE) self.add(type_text_1, type_text_2) self.add(dfc_l, dfc_r) self.dfc_l = dfc_l self.dfc_r = dfc_r self.dots_l = dots_l self.dots_r = dots_r def show_question(self): question = TextMobject("能否添加第四个圆,使之与其他三个圆都相切?") question.to_edge(UP, buff = 0.2) self.add(question) self.wait() class KissingCirclesSimplified(Scene): def construct(self): line1 = ExtendedLine(UL, UR) line2 = ExtendedLine(DL, DR) center_circle = Circle(radius = 1) figure_group = VGroup(line1, line2, center_circle) for mob in figure_group: mob.set_stroke(width = 2, color = BLUE) question = TextMobject("能否添加第四个“圆”,使之与其他三个“圆”都相切?") question.next_to(figure_group, UP, buff = 0.5) group = VGroup(question, figure_group) group.move_to(ORIGIN) self.add(group) self.wait() class KissingCirclesSimplifiedAnswer(Scene): def construct(self): line1 = ExtendedLine(UL, UR, stroke_width = 2, color = BLUE) line2 = ExtendedLine(DL, DR, stroke_width = 2, color = BLUE) center_circle = Circle(radius = 1, stroke_width = 2, color = BLUE) new_circles = VGroup(*[ Circle(radius = 1, color = color, fill_opacity = 0.1, stroke_width = 5) \ .next_to(center_circle, direction, buff = 0) for direction, color in zip([LEFT, RIGHT], [RED, ORANGE]) ]) numbers = VGroup(*[ TexMobject(f"{num}", color = circle.get_color()).move_to(circle.get_center()) for num, circle in zip(["1", "2"], new_circles) ]) group = VGroup(line1, line2, center_circle, new_circles, numbers) group.move_to(ORIGIN) self.add(group) self.wait() class KissingCirclesSimplifiedExplanation(Scene): CONFIG = { "dashed_vmob_config" : { "num_dashes" : 30, "positive_space_ratio" : 0.6, }, "line_colors" : [GREEN, BLUE], "center_color" : MAROON_B, "circle_colors" : [RED, ORANGE], } def construct(self): self.add_backgrounds() self.show_process() def add_backgrounds(self): N = 5 line1 = Line(UP + N*LEFT, UP + N*RIGHT, stroke_width = 2, color = self.line_colors[0]) line2 = Line(DOWN + N*LEFT, DOWN + N*RIGHT, stroke_width = 2, color = self.line_colors[1]) center_circle = FineCircle(radius = 1, stroke_width = 2, color = self.center_color) new_circle1 = FineCircle(radius = 1, stroke_width = 5, color = self.circle_colors[0]) new_circle1.next_to(center_circle, LEFT, buff = 0) new_circle2 = FineCircle(radius = 1, stroke_width = 5, color = self.circle_colors[1]) new_circle2.next_to(center_circle, RIGHT, buff = 0) inv_old_group = VGroup(line1, line2, center_circle) inv_new_group = VGroup(new_circle1, new_circle2) inv_group = VGroup(inv_old_group, inv_new_group) inv_group.rotate(-PI*2/5) inv_group.shift(3*RIGHT) circle = FineCircle(radius = 3.5, color = YELLOW) circle.shift(2*LEFT) circle_center = Dot(circle.get_center(), color = YELLOW) remark_circle = TextMobject("反演圆", color = YELLOW) remark_circle.next_to(circle.get_bottom(), UP) remark_center = VGroup(*[ Arrow(DL, UR, color = YELLOW, buff = 0).scale(0.3), TextMobject("反演中心", color = YELLOW).scale(0.8), ]) remark_center.arrange_submobjects(DL, buff = 0) remark_center.next_to(circle_center, DL, buff = 0.1) orig_old_group = VGroup(*[ InversedVMobject(mob, circle, use_dashed_vmob = False, match_original_style = True) for mob in inv_old_group ]) orig_new_group = VGroup(*[ InversedVMobject(mob, circle, use_dashed_vmob = False, match_original_style = True) for mob in inv_new_group ]) for mob in orig_old_group: mob.clear_updaters() mob.set_stroke(width = 2) for mob in orig_new_group: mob.clear_updaters() mob.set_stroke(width = 5) mob.set_fill(opacity = 0.1) self.add(orig_old_group) self.add(circle, circle_center, remark_circle, remark_center) self.circle = circle self.inv_old_group = inv_old_group self.inv_new_group = inv_new_group self.orig_old_group = orig_old_group self.orig_new_group = orig_new_group def show_process(self): dashed_inv_old_group = VGroup(*[ DashedVMobject(mob, **self.dashed_vmob_config) for mob in self.inv_old_group ]) dashed_inv_new_group = VGroup(*[ DashedVMobject(mob, **self.dashed_vmob_config) for mob in self.inv_new_group ]) self.play(ShowCreation(dashed_inv_old_group, lag_ratio = 0.05), run_time = 3) self.wait() dashed_copys = VGroup(*[dashed_inv_old_group[-1].deepcopy() for k in range(2)]) dashed_copys.generate_target() for mob_copy, mob_template in zip(dashed_copys.target, dashed_inv_new_group): mob_copy.match_style(mob_template) mob_copy.move_to(mob_template.get_center()) self.play(MoveToTarget(dashed_copys), run_time = 3) self.remove(dashed_copys) self.add(dashed_inv_new_group) self.wait() self.play(DrawBorderThenFill(self.orig_new_group), run_time = 3) self.wait(2) self.play( FadeOut(dashed_inv_new_group), FadeOut(dashed_inv_old_group), FadeOut(self.orig_new_group), ) self.wait() class DifferentTangentTypesWithSameConclusion(KissingCirclesPuzzle): CONFIG = { "random_seed" : 570, "num_of_nudges" : 5, "max_step" : 0.5, "color_1" : ORANGE, "color_2" : RED, } def construct(self): super().show_figure() self.dots_l.save_state() self.dots_r.save_state() for dfc in [self.dfc_l, self.dfc_r]: dfc.add_new_circles() dfc.get_orig_circles().set_stroke(width = 2) c4_1, c4_2 = dfc.get_new_circles() c4_1.set_color(self.color_1) c4_2.set_color(self.color_2) self.add(self.dfc_l, self.dfc_r) for k in range(self.num_of_nudges): for dot in it.chain(self.dots_l, self.dots_r): dot.generate_target() dot.target.shift(get_random_vector(self.max_step)) anims = AnimationGroup(*[ MoveToTarget(dot, path_arc = PI/3., run_time = 1.5) for dot in it.chain(self.dots_l, self.dots_r) ], run_time = 2) self.play(anims) self.wait() self.play(self.dots_l.restore, self.dots_r.restore, run_time = 1.5) class LineToCircleInversionRevisited(LineToCircleInversion): def construct(self): super().construct() self.remove_conclusions() self.add_explanation() def remove_conclusions(self): self.remove(self.bg_rect) self.remove(self.conclusions) def add_explanation(self): radius = Line( self.circle_O.get_left(), self.circle_O.get_center(), color = self.color_circle, stroke_width = 1, ) radius_text = TexMobject("R", color = self.color_circle) radius_text.next_to(radius, UP, buff = 0.1) radius_group = VGroup(radius, radius_text) radius_group.rotate(-PI/12, about_point = self.circle_O.get_center()) remark_length = TexMobject("|OA| = d", "\\Downarrow", "|OA'| = \dfrac{R^2}{d}") remark_length.arrange_submobjects(DOWN) remark_length.scale(1.2) remark_length[0].set_color(self.color_orig) remark_length[-1].set_color(self.color_inv) remark_length.to_edge(RIGHT) self.add(radius_group, remark_length) self.wait() class CircleToCircleInversionRevisited(CircleToCircleInversionProof): def construct(self): super().add_backgrounds() super().show_left_and_right_points() super().show_random_point() super().show_similar_triangles() self.arrange_elements() self.add_explanation() def arrange_elements(self): self.angle_tracker.set_value(PI/3) self.remove(self.remark_O) self.remove(self.ai_OAP, self.ai_OBP, self.ai_OPiAi, self.ai_OPiBi) self.add(self.inv_circle) self.add(self.dots_P, self.labels_P) self.add(self.dots_AB, self.labels_AB) self.add(self.aux_lines, self.rtais) dot_I = Dot(self.inv_circle.get_center()) label_I = DotLabel("I", dot_I, position = DOWN, label_buff = 0.15).scale(0.8) for mob in (dot_I, label_I): mob.set_sheen_direction(RIGHT) mob.set_color([self.color_B, self.color_A]) remark_I = TextMobject("反形的圆心(并非$C$的反点!)") remark_I.scale(0.5) remark_I.next_to(label_I, DOWN, buff = 0.1) self.add(dot_I, label_I, remark_I) def add_explanation(self): for circle, color, text, angle in zip( [self.circle_O, self.circle_C], [self.color_O, MAROON_B], ["R", "r"], [-PI/12, PI/3] ): radius = Line( circle.get_left(), circle.get_center(), color = color, stroke_width = 1, ) radius_text = TexMobject(text, color = color) radius_text.next_to(radius, UP, buff = 0.1) radius_group = VGroup(radius, radius_text) radius_group.rotate(angle, about_point = circle.get_center()) self.add(radius_group) remark_length_A = TexMobject("|OA| = d-r", "\\Rightarrow", "|OA'| = \dfrac{R^2}{d-r}") remark_length_B = TexMobject("|OB| = d+r", "\\Rightarrow", "|OB'| = \dfrac{R^2}{d+r}") remark_length_A[0].set_color(self.color_A) remark_length_A[-1].set_color(self.color_A) remark_length_B[0].set_color(self.color_B) remark_length_B[-1].set_color(self.color_B) length_group = VGroup(remark_length_A, remark_length_B) length_group.arrange_submobjects(DOWN, buff = 0.4) brace = Brace(length_group, RIGHT) arrow = TexMobject("\\Rightarrow") remarks = VGroup( TexMobject("|A'B'| = \\dfrac{2 R^2 r}{|d^2-r^2|}"), TexMobject("|OI| = \\dfrac{R^2 d}{|d^2-r^2|}") ) remarks.arrange_submobjects(DOWN, aligned_edge = LEFT) remarks.set_color(MAROON_B) result_group = VGroup(brace, arrow, remarks) result_group.arrange_submobjects(RIGHT) result_group.next_to(length_group, RIGHT) remark_group = VGroup(length_group, result_group) remark_group.center().to_edge(DOWN, buff = 0.2) bg_rect = BackgroundRectangle(remark_group, fill_opacity = 0.9) self.add(bg_rect, remark_group) self.wait() class DescartesTheoremExamples(Scene): CONFIG = { "circle_colors" : [MAROON_B, RED, GREEN, BLUE], "curvs_outer" : [3, 6, 7, 34], "curvs_inner" : [10, 15, 19, -6], } def setup(self): self.text_color_map = dict( zip(["{k_1}", "{k_2}", "{k_3}", "{k_4}"], self.circle_colors) ) def construct(self): self.add_title() self.add_outer_dfc() self.add_inner_dfc() def add_title(self): title = TexMobject( "\\left(", "{k_1}", "+", "{k_2}", "+", "{k_3}", "+", "{k_4}", "\\right) ^2", "= 2 \\left(", "{k_1}","^2 +","{k_2}","^2 +","{k_3}","^2 +","{k_4}","^2", "\\right)" ) title.set_color_by_tex_to_color_map(self.text_color_map) title.scale(1.2) title.to_edge(UP, buff = 0.2) self.add(title) def add_outer_dfc(self): r1, r2, r3, r4 = [1./curv for curv in self.curvs_outer] p1, p2, p3 = [ VectorizedPoint(center) for center in calc_centers_by_radii(r1, r2, r3, init_angle = PI*2/3) ] outer_dfc = DescartesFourCircles(p1, p2, p3, show_new_circles = False) c1, c2, c3 = outer_dfc.get_orig_circles() c4 = outer_dfc.get_new_circles()[0] outer_circles = VGroup(c1, c2, c3, c4) outer_circles.clear_updaters() outer_circles.set_height(5.5) outer_circles.to_corner(DL) texts = VGroup(*[ TexMobject(f"k_{num}", "=", f"{curv}") \ .scale(0.8) \ .move_to(circle.get_center()) for num, curv, circle in zip(range(1, 5), self.curvs_outer, outer_circles) ]) for circle, text, color in zip(outer_circles, texts, self.circle_colors): circle.set_color(color) text.set_color(color) texts[-1].shift(2.5*RIGHT+1.2*UP) arrow = Arrow( texts[-1].get_bottom(), outer_circles[-1].get_right(), path_arc = -PI*2/3, buff = 0.1, ).set_color(self.circle_colors[-1]) outer_group = VGroup(outer_circles, texts, arrow) self.add(outer_group) def add_inner_dfc(self): r1, r2, r3, r4 = [1./curv for curv in self.curvs_inner] p1, p2, p3 = [ VectorizedPoint(center) for center in calc_centers_by_radii(r1, r2, r3, init_angle = -PI/7) ] inner_dfc = DescartesFourCircles(p1, p2, p3, show_new_circles = False) c1, c2, c3 = inner_dfc.get_orig_circles() c4 = inner_dfc.get_new_circles()[1] inner_circles = VGroup(c1, c2, c3, c4) inner_circles.clear_updaters() inner_circles.set_height(5.5) inner_circles.to_corner(DR) inner_texts = VGroup(*[ TexMobject(f"k_{num}", "=", f"{curv}") \ .scale(0.8) \ .move_to(circle.get_center()) for num, curv, circle in zip(range(1, 5), self.curvs_inner, inner_circles) ]) for circle, text, color in zip(inner_circles, inner_texts, self.circle_colors): circle.set_color(color) text.set_color(color) inner_texts[-1].shift(2.8*LEFT+2.7*UP) inner_arrow = Arrow( inner_texts[-1].get_critical_point(DOWN), inner_texts[-1].get_critical_point(DOWN)+0.7*DR, buff = 0.1, ).set_color(self.circle_colors[-1]) inner_group = VGroup(inner_circles, inner_texts, inner_arrow) self.add(inner_group) self.wait() self.inner_circles = inner_circles self.inner_texts = inner_texts self.inner_arrow = inner_arrow class DFCInversionProofP1(DescartesTheoremExamples): CONFIG = { "remark_scale_text" : "示意图,图像并非真实比例", "orig_label_texts" : ["C_1", "C_2", "C_3", "C_4"], "inv_label_texts" : ["C_1'", "C_2'", "C_3'", "C_4'"], } def construct(self): super().add_inner_dfc() self.arrange_elements() self.add_labels() self.add_inversion_center() self.add_mapsto_symbol() self.add_not_to_scale_remark() self.wait() def arrange_elements(self): self.remove(self.inner_texts, self.inner_arrow) self.inner_circles.center().shift(4*UP) normal_form = FourCirclesNormalForm() normal_form.shift(4*DOWN) self.add(normal_form) self.normal_form = normal_form def add_labels(self): orig_labels = VGroup() for n, (circle, text) in enumerate(zip(self.inner_circles, self.orig_label_texts)): label = TexMobject(text).scale(1.2) label.set_color(circle.get_color()) label.move_to(circle.get_center()) orig_labels.add(label) inv_labels = VGroup() for n, (circle, text) in enumerate(zip(self.normal_form, self.inv_label_texts)): label = TexMobject(text).scale(1.2) label.set_color(circle.get_color()) label.move_to(circle.get_center()) inv_labels.add(label) c1, c2, c3, c4 = self.inner_circles l1, l2, l3, l4 = orig_labels c1i, c2i, c3i, c4i = self.normal_form l1i, l2i, l3i, l4i = inv_labels l4.next_to(c4.get_bottom(), UP, buff = 0.3) l3i.next_to(c3i, DOWN).to_edge(RIGHT) l4i.next_to(c4i, UP).to_edge(RIGHT) self.add(orig_labels, inv_labels) self.orig_labels = orig_labels self.inv_labels = inv_labels def add_inversion_center(self): c1, c2, c3, c4 = self.inner_circles inv_center = get_tangent_point(c3, c4) dot_O = Dot(inv_center, color = YELLOW) label_O = TexMobject("O", color = YELLOW).next_to(dot_O, UP) remark_O = TextMobject("反演中心", color = YELLOW) remark_O.next_to(dot_O, RIGHT, buff = 1.5) arrow_O = Arrow(remark_O.get_left(), dot_O.get_right(), color = YELLOW, buff = 0.2) orig_center_group = VGroup(dot_O, label_O, remark_O, arrow_O) inv_dot_O = VectorizedPoint() inv_dot_O.next_to(self.normal_form[-1], UP, buff = 1.4) inv_dot_O.shift(2*RIGHT) inv_center_group = orig_center_group.deepcopy() inv_center_group.shift(inv_dot_O.get_center() - dot_O.get_center()) self.add(orig_center_group, inv_center_group) self.orig_center_group = orig_center_group self.inv_center_group = inv_center_group def add_mapsto_symbol(self): mapsto = TexMobject("\\mapsto") mapsto.rotate(-PI/2) mapsto.scale(2.5) mapsto.next_to(self.inner_circles, DOWN) remark_mapsto = TextMobject("反演变换") remark_mapsto.next_to(mapsto, LEFT) self.add(mapsto, remark_mapsto) def add_not_to_scale_remark(self): remark_scale = TextMobject("(" + self.remark_scale_text + ")") remark_scale.scale(0.75) remark_scale.next_to(6.5*DL, RIGHT, buff = 0) self.add(remark_scale) class DFCInversionProofP2(DFCInversionProofP1): CONFIG = { "remark_scale_text" : "示意图,反演圆未标出,且图像并非真实比例", "inv_label_texts" : ["C_1'", "C_2'", "C_3':y=-1", "C_4':y=1"], "inv_center_coord_text" : "(x_0, y_0) \\, (y_0>1)", "circle_center_coord_texts" : ["(-1,0)", "(1,0)"], } def construct(self): super().construct() self.change_center_remarks() self.add_coord_system() self.change_inv_labels() self.wait() def change_center_remarks(self): for center_group in (self.orig_center_group, self.inv_center_group): dot, label, remark, arrow = center_group self.remove(remark, arrow) if center_group is self.inv_center_group: coord = TexMobject(self.inv_center_coord_text) coord.next_to(dot, RIGHT) coord.set_color(dot.get_color()) self.add(coord) def add_coord_system(self): c1, c2, c3, c4 = self.normal_form center_point = (c1.get_center() + c2.get_center()) / 2 unit_size = c1.get_height()/2 coord_system = Axes( center_point = center_point, number_line_config = {"unit_size" : unit_size}, y_min = -1.8, y_max = 2.8, ) self.add(coord_system) self.coord_system = coord_system def change_inv_labels(self): l1i, l2i, l3i, l4i = self.inv_labels for label, x_coord, coord_text in zip([l1i, l2i], [-1, 1], self.circle_center_coord_texts): center = self.coord_system.c2p(x_coord, 0) label.next_to(center, UP) dot_i = Dot(center, radius = 0.1).set_color(label.get_color()) coord_i = TexMobject(coord_text).set_color(label.get_color()).next_to(center, DOWN) self.add(dot_i, coord_i) llonianGasketScene): CONFIG = { "max_iter" : 8, "curvatures" : [2, 2, 3], "init_angle" : 0, "curv_thres" : 30000, "ag_config": { "agc_config" : { "radius_thres" : 1e-3, "circle_color" : BLUE, "label_color" : WHITE, }, }, "color_curr" : YELLOW, "wait_time" : 2, } def construct(self): r1, r2, r3 = [1./curv for curv in self.curvatures] p1, p2, p3 = calc_centers_by_radii(r1, r2, r3, init_angle = self.init_angle) agc1 = AGCircle(p1, r1, parents = None, **self.ag_config["agc_config"]) agc2 = AGCircle(p2, r2, parents = None, **self.ag_config["agc_config"]) agc3 = AGCircle(p3, r3, parents = None, **self.ag_config["agc_config"]) remark = TextMobject("(圆内数字为该圆的曲率)") remark.scale(0.75).to_corner(DL) self.add(remark) for k in range(self.max_iter): agcs_copy = [agc.deepcopy() for agc in (agc1, agc2, agc3)] ag = ApollonianGasket( *agcs_copy, num_iter = k, curv_thres = self.curv_thres, **self.ag_config ) iter_num = VGroup( TextMobject("迭代次数:"), TexMobject(f"{k}") ).arrange_submobjects(RIGHT).scale(1.5) iter_num.to_edge(LEFT, buff = 1) ag.scale(3.8) ag.shift(np.array([0, 3.8, 0]) - ag.get_top() + 3*RIGHT) VGroup(*ag.agc_list[-1]).set_color(self.color_curr) self.add(ag, iter_num) self.wait(self.wait_time) if k != self.max_iter-1: self.remove(ag, iter_num) class ApollonianGasketExample1(Scene): CONFIG = { "max_iter" : 20, "curvatures" : [3, 6, 7], "curvature_texts" : [-2, 3, 6, 7], "init_angle" : 0, "curv_thres" : 4000, "ag_config": { "agc_config" : { "radius_thres" : 1e-3, "circle_color" : BLUE, "label_color" : WHITE, }, }, "ag_scaling_factor" : 5.2, } def construct(self): r1, r2, r3 = [1./curv for curv in self.curvatures] p1, p2, p3 = calc_centers_by_radii(r1, r2, r3, init_angle = self.init_angle) agc1 = AGCircle(p1, r1, parents = None, **self.ag_config["agc_config"]) agc2 = AGCircle(p2, r2, parents = None, **self.ag_config["agc_config"]) agc3 = AGCircle(p3, r3, parents = None, **self.ag_config["agc_config"]) ag_seed = ApollonianGasket( *[agc.deepcopy() for agc in (agc1, agc2, agc3)], num_iter = 0, curv_thres = self.curv_thres, **self.ag_config ) ag_result = ApollonianGasket( *[agc.deepcopy() for agc in (agc1, agc2, agc3)], num_iter = self.max_iter, curv_thres = self.curv_thres, **self.ag_config ) ag_seed_center = ag_seed[0][0].get_right() ag_result_center = ag_result[0][0].get_right() arrow = Arrow(LEFT, RIGHT) figure_group = VGroup(ag_seed, ag_result, arrow) for ag, center, direction in zip( [ag_seed, ag_result], [ag_seed_center, ag_result_center], [4*LEFT, 4*RIGHT]): ag.scale(self.ag_scaling_factor) ag.shift(direction - center) figure_group.shift(DOWN) k1, k2, k3, k4 = list(map(str, self.curvature_texts)) title = TexMobject( f"({k1}+{k2}+{k3}+{k4})^2 = 2\\left[({k1})^2+{k2}^2+{k3}^2+{k4}^2 \\right]" ) title.set_width(13) title.set_color(YELLOW) title.to_edge(UP) self.add(figure_group, title) self.wait() class ApollonianGasketExample2(ApollonianGasketExample1): CONFIG = { "max_iter" : 20, "curvatures" : [5, 8, 12], "curvature_texts" : [-3, 5, 8, 12], "curv_thres" : 5000, "ag_config": { "agc_config" : { "radius_thres" : 5e-4, "circle_color" : BLUE, "label_color" : WHITE, }, }, "ag_scaling_factor" : 8, } class LoxodromicSpiralInTangentCircles(Scene): CONFIG = { "max_iter" : 20, "agc_config" : { "radius_thres" : 1, "circle_color" : BLUE, "label_color" : WHITE, }, "curve_config" : { "color" : YELLOW, "stroke_width" : 2, }, "alpha" : 0.6, "dashed_line_config" : { "color" : GREY, "stroke_width" : 0.5, "num_dashes" : 200, "positive_space_ratio" : 0.6, } } def construct(self): self.generate_circles() self.generate_curves() self.generate_labels() self.generate_lines() self.add_elements() self.zooming_in() def generate_circles(self): agcm2 = AGCircle(2/3.*UP, 1/3., **self.agc_config) agcm1 = AGCircle(RIGHT/2, 1/2., **self.agc_config) agczr = AGCircle(ORIGIN, -1, **self.agc_config) agcp1 = AGCircle(LEFT/2, 1/2., **self.agc_config) agcp2 = AGCircle(2/3.*DOWN, 1/3., **self.agc_config) agc_list = [agcm2, agcm1, agczr, agcp1, agcp2] for n in range(self.max_iter): A, B, C, known_agc = agc_list[:4] agc_m_k, agc_m_c = calc_new_agc_info(A, B, C, known_agc = known_agc) agc_m = AGCircle(agc_m_c, 1./agc_m_k, parents = (A, B, C), **self.agc_config) known_agc, C, B, A = agc_list[-4:] agc_p_k, agc_p_c = calc_new_agc_info(C, B, A, known_agc = known_agc) agc_p = AGCircle(agc_p_c, 1./agc_p_k, parents = (C, B, A), **self.agc_config) agc_list.insert(0, agc_m) agc_list.append(agc_p) agc_group = VGroup(*agc_list) agc_group.set_height(7.8) self.agc_list = agc_list self.agc_group = agc_group def generate_curves(self): agc_ps = self.agc_list[-self.max_iter-4:] agc_ps_points = [] loxo_curve_p_solid = VMobject(**self.curve_config) for k in range(len(agc_ps)-2): if k != 0: c1, c2, c3 = agc_ps[k], agc_ps[k+1], agc_ps[k+2] pt1 = get_tangent_point(c1, c2) pt2 = get_tangent_point(c2, c3) p = c2.get_center() if k != 1: agc_ps_points.extend( [pt1, p*(1-self.alpha)+pt1*self.alpha, p*(1-self.alpha)+pt2*self.alpha, pt2] ) else: agc_ps_points.extend( [pt1, p*0.7+pt1*0.3, p*0.6+pt2*0.4, pt2] ) else: c1, c2 = agc_ps[1], agc_ps[2] pt = get_tangent_point(c1, c2) agc_ps_points.extend([8*LEFT, 7*LEFT, 6*LEFT, pt]) loxo_curve_p_solid.append_points(agc_ps_points) loxo_curve_m_solid = loxo_curve_p_solid.deepcopy() loxo_curve_m_solid.rotate(PI, about_point = self.agc_group.get_center()) self.loxo_curve_p_solid = loxo_curve_p_solid self.loxo_curve_m_solid = loxo_curve_m_solid def generate_labels(self): labels = VGroup(*[ TexMobject("C_{%d}" % num, background_stroke_width = 0) for num in range(-self.max_iter-2, self.max_iter+3) ]) for label, circle in zip(labels, self.agc_group): label.set_height(circle.get_height()*0.15) label.move_to(circle.get_center()) label_c0 = labels[self.max_iter+2] label_c0.set_height(0.8) label_c0.next_to(self.agc_group.get_critical_point(UL), DR, buff = 0.1) self.labels = labels def generate_lines(self): agc_ps = self.agc_list[-self.max_iter-2:] line_p_solid = VMobject(**self.dashed_line_config) line_p_solid_corners = [8*LEFT] for circle in agc_ps: line_p_solid_corners.append(circle.get_center()) line_p_solid.set_points_as_corners(line_p_solid_corners) line_m_solid = line_p_solid.deepcopy() line_m_solid.rotate(PI, about_point = self.agc_group.get_center()) self.line_p_solid = line_p_solid self.line_m_solid = line_m_solid def add_elements(self): figure = VGroup( self.agc_group, self.loxo_curve_p_solid, self.loxo_curve_m_solid, self.line_p_solid, self.line_m_solid, self.labels, ) self.add(figure) self.figure = figure def zooming_in(self): self.figure.save_state() self.wait(0.5) self.play( ApplyMethod(self.figure.shift, -self.agc_group[-1].get_center()), run_time = 2, ) self.wait() for k in range(10): self.play( ApplyMethod(self.figure.scale, 2.5, {"about_point" : self.agc_group[-1].get_center()}), run_time = 2, ) self.wait() self.play(self.figure.restore, run_time = 15) self.wait(2) class ShowFordCircles(ZoomInOnFordCircles): CONFIG = { "q_max" : 30, } def construct(self): self.setup_axes() self.setup_circles_and_labels() self.add_remarks() self.first_zoom_in() self.wait() def first_zoom_in(self): self.zoom_in_on(1/2., 6) def add_remarks(self): nl_text = TextMobject("数轴") nl_arrow = Arrow(ORIGIN, UP).match_height(nl_text) nl_remark = VGroup(nl_arrow, nl_text) nl_remark.scale(0.8) nl_remark.set_color(LIGHT_GREY) nl_remark.arrange_submobjects(RIGHT, buff = 0.1) nl_remark.next_to(self.axes.coords_to_point(0, 0), DOWN, buff = 0.1) nl_remark.to_edge(LEFT, buff = 0.15) frac_remark = TextMobject("圆内分数为圆心横坐标") frac_remark.scale(0.6) frac_remark.to_corner(DL, buff = 0.15) self.add(nl_remark, frac_remark) class ShowFordCirclesDetails(ShowFordCircles): CONFIG = { "q_max" : 100, } def construct(self): super().construct() self.further_zoom_in() def setup_circles_and_labels(self): circles = VGroup() labels = VGroup() for q in range(1, self.q_max+1): for p in get_coprime_numers_by_denom(q): if (q <= 40) or (0.6 <= p/q <= 0.8): circle = self.generate_circle_by_fraction(p, q) circle.add_updater( lambda m: m.set_stroke(width = get_stroke_width_by_height(m.get_height())) ) label = AssembledFraction(p, q) label.set_height(circle.get_height() * self.label_height_factor) label.move_to(circle.get_center()) circles.add(circle) labels.add(label) self.add(circles, labels) self.circles = circles self.labels = labels def further_zoom_in(self): self.acl = VGroup(self.axes, self.circles, self.labels) self.acl.save_state() self.wait(0.5) self.play_zooming_animation(1/np.sqrt(2), 9, run_time = 5) self.wait() self.play_zooming_animation(0.73, 5, run_time = 4) self.wait() self.play_zooming_animation(0.74, 5, run_time = 4) self.wait() self.play(self.acl.restore, run_time = 5) self.wait(2) class ProveFordCirclesPropertiesP1(Scene): CONFIG = { "c1_frac" : [2, 3], "c2_frac" : [3, 4], "c3_frac" : [5, 7], "circle_config" : {"stroke_color" : BLUE, "stroke_width" : 2,}, "line_config" : {"stroke_color" : GREY, "stroke_width" : 2,}, "aux_line_config" : {"stroke_color" : GREY, "stroke_width" : 0.8,}, "polygon_config" : {"fill_color" : GREY, "fill_opacity" : 0.4, "stroke_width" : 0,}, } def setup(self): a, b = self.c1_frac c, d = self.c2_frac p, q = self.c3_frac r1 = 1/(2*b**2) r2 = 1/(2*d**2) r3 = 1/(2*q**2) c1_center = a/b*RIGHT + r1*UP c2_center = c/d*RIGHT + r2*UP c3_center = p/q*RIGHT + r3*UP c1 = Circle(arc_center = c1_center, radius = r1, **self.circle_config) c2 = Circle(arc_center = c2_center, radius = r2, **self.circle_config) c3 = Circle(arc_center = c3_center, radius = r3, **self.circle_config) c1_dot = SmallDot(color = GREY) c1_dot.add_updater(lambda m: m.move_to(c1.get_center())) c2_dot = SmallDot(color = GREY) c2_dot.add_updater(lambda m: m.move_to(c2.get_center())) c3_dot = SmallDot(color = GREY) c3_dot.add_updater(lambda m: m.move_to(c3.get_center())) line = Line( 2*c1.get_bottom()-c2.get_bottom(), 2*c2.get_bottom()-c1.get_bottom(), **self.line_config ) VGroup(c1, c2, c3, line).set_height(6).center().to_edge(UP) aux_line_1 = Line(c1.get_center(), c1.get_bottom(), **self.aux_line_config) aux_line_2 = Line(c2.get_center(), c2.get_bottom(), **self.aux_line_config) aux_line_3 = Line(c1.get_center(), c2.get_center(), **self.aux_line_config) aux_line_4 = Line(c1.get_bottom(), c2.get_bottom(), **self.aux_line_config) \ .shift(c2.get_height()/2*UP) polygon = Polygon( c1.get_center(), c2.get_center(), aux_line_4.get_start_and_end()[0], **self.polygon_config, ) l1 = TexMobject("\\dfrac{a}{b}").next_to(c1, DOWN) l2 = TexMobject("\\dfrac{c}{d}").next_to(c2, DOWN) l3 = TexMobject("\\dfrac{a+c}{b+d}").next_to(c3, DOWN) self.orig_group = VGroup(c1, c2, line, c1_dot, c2_dot, l1, l2) self.aux_group = VGroup(aux_line_1, aux_line_2, aux_line_3, aux_line_4, polygon) self.new_group = VGroup(c3, c3_dot, l3) def construct(self): self.add(self.orig_group, self.aux_group) self.wait() class ProveFordCirclesPropertiesP2(ProveFordCirclesPropertiesP1): def construct(self): self.add(self.orig_group, self.new_group) self.wait() class ShowFordCirclesFareySum(ZoomInOnFordCircles): pass class DFCInversionProofP3(DFCInversionProofP2): CONFIG = { "remark_scale_text" : "示意图,反演圆未标出,且图像并非真实比例", "inv_label_texts" : ["C_1'", "C_2'", "C_3':\\mathrm{Im}(z)=-1", "C_4':\\mathrm{Im}(z)=1"], "inv_center_coord_text" : "z_0 = x_0+iy_0\\, (y_0>1)", "circle_center_coord_texts" : ["-1", "1"], } def construct(self): super().construct() self.wait() def add_coord_system(self): c1, c2, c3, c4 = self.normal_form center_point = (c1.get_center() + c2.get_center()) / 2 unit_size = c1.get_height()/2 coord_system = NumberPlane( center_point = center_point, number_line_config = {"unit_size" : unit_size}, y_min = -3, y_max = 3, background_line_style = { "stroke_color" : GREY, "stroke_width" : 1.5, "stroke_opacity" : 0.8, }, ) aux_coord_system = Axes( center_point = center_point, number_line_config = {"unit_size" : unit_size}, y_min = -3, y_max = 3, stroke_opacity = 0.8, ) self.add(coord_system, aux_coord_system) self.coord_system = coord_system class NormalFormIn3D(ThreeDScene): CONFIG = { "axis_unit_size" : 1.5, "axis_min" : -1.5, "axis_max" : 2.8, "resolution" : (60, 120), "plane_colors" : [GREEN, BLUE], "sphere_colors" : [MAROON_B, RED, PINK], } def construct(self): self.add_3d_stuff() self.add_2d_stuff() def add_3d_stuff(self): self.set_camera_orientation(theta = 70 * DEGREES, phi = 50 * DEGREES) axes = ThreeDAxes( x_min = self.axis_min, x_max = self.axis_max, y_min = self.axis_min, y_max = self.axis_max, z_min = self.axis_min, z_max = self.axis_max, number_line_config = {"unit_size" : self.axis_unit_size}, ) sphere_centers = [ axis.number_to_point(1) for axis in [axes.x_axis, axes.y_axis, axes.z_axis] ] radius = 1/np.sqrt(2) * self.axis_unit_size sphere_dots = VGroup(*[ Sphere( radius = 0.08, resolution = self.resolution, fill_opacity = 1, stroke_width = 0, ).move_to(sphere_center).set_color(color) for sphere_center, color in zip(sphere_centers, self.sphere_colors) ]) spheres = VGroup(*[ Sphere( radius = radius, resolution = self.resolution, fill_opacity = 0.6, stroke_width = 0.5, ).move_to(sphere_center).set_color(color) for sphere_center, color in zip(sphere_centers, self.sphere_colors) ]) planes = VGroup(*[ VGroup(*[ Square( side_length = 1, fill_opacity = fill_opacity, stroke_color = GREY, stroke_width = 0.3, stroke_opacity = 0.2, ) for k in range(n**2) ]).arrange_in_grid(n, n, buff = 0) \ .apply_matrix(z_to_vector([1, 1, 1])) \ .move_to(np.average(sphere_centers)) \ .shift(radius * normalize(direction)) \ .set_color(color) for n, fill_opacity, direction, color in zip( [7, 8], [0.2, 0.3], [np.ones(3), -np.ones(3)], self.plane_colors, ) ]) figure_group = VGroup(axes, planes, sphere_dots, spheres) figure_group.shift(RIGHT*2+0.5*OUT) self.add(figure_group) self.add(axes) self.add(planes) self.add(sphere_dots, spheres) def add_2d_stuff(self): sphere_remarks = VGroup(*[ TextMobject( "球:圆心为" + f"$({int(x)},{int(y)},{int(z)})$" + \ ",半径为" + "$\\dfrac{1}{\\sqrt{2}}$" ).set_color(color) for (x, y, z), color in zip([RIGHT, UP, OUT], self.sphere_colors) ]).arrange_submobjects(DOWN) plane_remarks = VGroup(*[ TexMobject( "\\text{平面:}" + "x+y+z=1" + sign + "\\dfrac{\\sqrt{3}}{\\sqrt{2}" ).set_color(color) for sign, color in zip(["+", "-"], self.plane_colors) ]).arrange_submobjects(DOWN) remarks = VGroup(sphere_remarks, plane_remarks) remarks.arrange_submobjects(DOWN, aligned_edge = LEFT) remarks.scale(0.8) remarks.to_corner(DR) self.add_fixed_in_frame_mobjects(remarks) self.wait() ##### ## Banner class Banner_Intro(Scene): CONFIG = { "circle_color" : YELLOW, "text_color" : BLUE, "inv_text_color" : BLUE, "circle_center" : 0.8*UP, "circle_radius" : 3, "grid_side_length" : 0.5, "x_range" : 300, "y_range" : 300, "dist_thres" : 300, } def construct(self): circle = Circle(color = self.circle_color, radius = self.circle_radius, stroke_width = 5) circle.move_to(self.circle_center) dot = SmallDot(self.circle_center, color = self.circle_color) text = TextMobject("Inversion", color = self.text_color, background_stroke_width = 3) text.rotate(PI/2.) text.move_to(0.4*RIGHT) text.apply_complex_function(np.exp) text.rotate(-PI/2.) text.scale(1.5) text.move_to(0.9*DOWN) inv_text = InversedVMobject(text, circle, use_dashed_vmob = False) inv_text.suspend_updating() inv_text.set_background_stroke(color = "#303030", width = 3) inv_text.set_stroke(width = 0) inv_text.set_fill(color = self.inv_text_color, opacity = 0.5) grid = VGroup(*[ Square( side_length = self.grid_side_length, stroke_width = 0, fill_opacity = 0.3, fill_color = CB_DARK if (i+j)%2==0 else CB_LIGHT ).move_to(self.circle_center + (i*RIGHT+j*UP)*self.grid_side_length) for i in range(-self.x_range, self.x_range+1, 1) for j in range(-self.y_range, self.y_range+1, 1) if np.sqrt(i**2+j**2) * self.grid_side_length < self.dist_thres ]) for square in grid: if is_close_in_R3(square.get_center(), self.circle_center): grid.remove(square) inv_grid = InversedVMobject(grid, circle, use_dashed_vmob = False) self.add(inv_grid, circle, dot, text, inv_text) self.wait() class Banner_AdvancedP1(ApollonianGasketScene): CONFIG = { "curvatures" : [570, 968, 1112], "init_angle" : PI/7, "num_iter" : 20, "curv_thres" : 1e6, "ag_config" : { "agc_config" : { "radius_thres" : 5e-6, "circle_color" : YELLOW, "label_color" : WHITE, }, }, "part_text" : "上篇", } def construct(self): super().construct() ag = self.ag ag.set_height(7) circle_myst = ag.agc_list[0][0] label_myst = circle_myst.label label_question = TexMobject("???") label_question.match_height(label_myst) label_question.move_to(label_myst) self.remove(label_myst) self.add(label_question) part = TextMobject(self.part_text) part.to_corner(DR) self.add(part) class Banner_AdvancedP2(Banner_AdvancedP1): CONFIG = { "part_text" : "下篇", }
true
true
f716c43082d102e192f1af6ae1893777487ae14c
11,372
py
Python
smartcab/environment.py
BhanuPrakashNani/physics-simulation
7d7ad4bff654f4ad80dbc6a7ab254489d623658f
[ "MIT" ]
7
2018-12-07T14:25:15.000Z
2021-04-07T22:14:49.000Z
smartcab/environment.py
BhanuPrakashNani/physics-simulation
7d7ad4bff654f4ad80dbc6a7ab254489d623658f
[ "MIT" ]
9
2018-12-07T18:11:29.000Z
2018-12-22T09:39:39.000Z
smartcab/environment.py
BhanuPrakashNani/physics-simulation
7d7ad4bff654f4ad80dbc6a7ab254489d623658f
[ "MIT" ]
22
2018-12-06T16:35:34.000Z
2019-01-26T13:08:14.000Z
import time,random from collections import OrderedDict from simulator import Simulator class TrafficLight(object): """A traffic light that switches periodically.""" valid_states = [True, False] # True = NS open, False = EW open def __init__(self, state=None, period=None): self.state = state if state is not None else random.choice(self.valid_states) self.period = period if period is not None else random.choice([3, 4, 5]) self.last_updated = 0 def reset(self): self.last_updated = 0 def update(self, t): if t - self.last_updated >= self.period: self.state = not self.state # assuming state is boolean self.last_updated = t class Environment(object): """Environment within which all agents operate.""" valid_actions = [None, 'forward', 'left', 'right'] valid_inputs = {'light': TrafficLight.valid_states, 'oncoming': valid_actions, 'left': valid_actions, 'right': valid_actions} valid_headings = [(1, 0), (0, -1), (-1, 0), (0, 1)] # ENWS hard_time_limit = -100 # even if enforce_deadline is False, end trial when deadline reaches this value (to avoid deadlocks) def __init__(self): self.done = False self.t = 0 self.agent_states = OrderedDict() self.status_text = "" # Road network self.grid_size = (8, 6) # (cols, rows) self.bounds = (1, 1, self.grid_size[0], self.grid_size[1]) self.block_size = 100 self.intersections = OrderedDict() self.roads = [] for x in xrange(self.bounds[0], self.bounds[2] + 1): for y in xrange(self.bounds[1], self.bounds[3] + 1): self.intersections[(x, y)] = TrafficLight() # a traffic light at each intersection for a in self.intersections: for b in self.intersections: if a == b: continue if (abs(a[0] - b[0]) + abs(a[1] - b[1])) == 1: # L1 distance = 1 self.roads.append((a, b)) # Dummy agents self.num_dummies = 3 # no. of dummy agents for i in xrange(self.num_dummies): self.create_agent(DummyAgent) # Primary agent self.primary_agent = None # to be set explicitly self.enforce_deadline = False def create_agent(self, agent_class, *args, **kwargs): agent = agent_class(self, *args, **kwargs) self.agent_states[agent] = {'location': random.choice(self.intersections.keys()), 'heading': (0, 1)} return agent def set_primary_agent(self, agent, enforce_deadline=False): self.primary_agent = agent self.enforce_deadline = enforce_deadline def reset(self): self.done = False self.t = 0 # Reset traffic lights for traffic_light in self.intersections.itervalues(): traffic_light.reset() # Pick a start and a destination start = random.choice(self.intersections.keys()) destination = random.choice(self.intersections.keys()) # Ensure starting location and destination are not too close while self.compute_dist(start, destination) < 4: start = random.choice(self.intersections.keys()) destination = random.choice(self.intersections.keys()) start_heading = random.choice(self.valid_headings) deadline = self.compute_dist(start, destination) * 5 print "Environment.reset(): Trial set up with start = {}, destination = {}, deadline = {}".format(start, destination, deadline) # Initialize agent(s) for agent in self.agent_states.iterkeys(): self.agent_states[agent] = { 'location': start if agent is self.primary_agent else random.choice(self.intersections.keys()), 'heading': start_heading if agent is self.primary_agent else random.choice(self.valid_headings), 'destination': destination if agent is self.primary_agent else None, 'deadline': deadline if agent is self.primary_agent else None} agent.reset(destination=(destination if agent is self.primary_agent else None)) def step(self): #print "Environment.step(): t = {}".format(self.t) # [debug] # Update traffic lights for intersection, traffic_light in self.intersections.iteritems(): traffic_light.update(self.t) # Update agents for agent in self.agent_states.iterkeys(): agent.update(self.t) self.t += 1 if self.primary_agent is not None: agent_deadline = self.agent_states[self.primary_agent]['deadline'] if agent_deadline <= self.hard_time_limit: self.done = True print "Environment.step(): Primary agent hit hard time limit ({})! Trial aborted.".format(self.hard_time_limit) elif self.enforce_deadline and agent_deadline <= 0: self.done = True print "Environment.step(): Primary agent ran out of time! Trial aborted." self.agent_states[self.primary_agent]['deadline'] = agent_deadline - 1 def sense(self, agent): assert agent in self.agent_states, "Unknown agent!" state = self.agent_states[agent] location = state['location'] heading = state['heading'] light = 'green' if (self.intersections[location].state and heading[1] != 0) or ((not self.intersections[location].state) and heading[0] != 0) else 'red' # Populate oncoming, left, right oncoming = None left = None right = None for other_agent, other_state in self.agent_states.iteritems(): if agent == other_agent or location != other_state['location'] or (heading[0] == other_state['heading'][0] and heading[1] == other_state['heading'][1]): continue other_heading = other_agent.get_next_waypoint() if (heading[0] * other_state['heading'][0] + heading[1] * other_state['heading'][1]) == -1: if oncoming != 'left': # we don't want to override oncoming == 'left' oncoming = other_heading elif (heading[1] == other_state['heading'][0] and -heading[0] == other_state['heading'][1]): if right != 'forward' and right != 'left': # we don't want to override right == 'forward or 'left' right = other_heading else: if left != 'forward': # we don't want to override left == 'forward' left = other_heading return {'light': light, 'oncoming': oncoming, 'left': left, 'right': right} # TODO: make this a namedtuple def get_deadline(self, agent): return self.agent_states[agent]['deadline'] if agent is self.primary_agent else None def act(self, agent, action): assert agent in self.agent_states, "Unknown agent!" assert action in self.valid_actions, "Invalid action!" state = self.agent_states[agent] location = state['location'] heading = state['heading'] light = 'green' if (self.intersections[location].state and heading[1] != 0) or ((not self.intersections[location].state) and heading[0] != 0) else 'red' sense = self.sense(agent) # Move agent if within bounds and obeys traffic rules reward = 0 # reward/penalty move_okay = True if action == 'forward': if light != 'green': move_okay = False elif action == 'left': if light == 'green' and (sense['oncoming'] == None or sense['oncoming'] == 'left'): heading = (heading[1], -heading[0]) else: move_okay = False elif action == 'right': if light == 'green' or sense['left'] != 'straight': heading = (-heading[1], heading[0]) else: move_okay = False if move_okay: # Valid move (could be null) if action is not None: # Valid non-null move location = ((location[0] + heading[0] - self.bounds[0]) % (self.bounds[2] - self.bounds[0] + 1) + self.bounds[0], (location[1] + heading[1] - self.bounds[1]) % (self.bounds[3] - self.bounds[1] + 1) + self.bounds[1]) # wrap-around #if self.bounds[0] <= location[0] <= self.bounds[2] and self.bounds[1] <= location[1] <= self.bounds[3]: # bounded state['location'] = location state['heading'] = heading reward = 2.0 if action == agent.get_next_waypoint() else -0.5 # valid, but is it correct? (as per waypoint) else: # Valid null move reward = 0.0 else: # Invalid move reward = -1.0 if agent is self.primary_agent: if state['location'] == state['destination']: if state['deadline'] >= 0: reward += 10 # bonus self.done = True print "Environment.act(): Primary agent has reached destination!" # [debug] self.status_text = "state: {}\naction: {}\nreward: {}".format(agent.get_state(), action, reward) #print "Environment.act() [POST]: location: {}, heading: {}, action: {}, reward: {}".format(location, heading, action, reward) # [debug] return reward def compute_dist(self, a, b): """L1 distance between two points.""" return abs(b[0] - a[0]) + abs(b[1] - a[1]) class Agent(object): """Base class for all agents.""" def __init__(self, env): self.env = env self.state = None self.next_waypoint = None self.color = 'cyan' def reset(self, destination=None): pass def update(self, t): pass def get_state(self): return self.state def get_next_waypoint(self): return self.next_waypoint class DummyAgent(Agent): color_choices = ['blue', 'cyan', 'magenta', 'orange'] def __init__(self, env): super(DummyAgent, self).__init__(env) # sets self.env = env, state = None, next_waypoint = None, and a default color self.next_waypoint = random.choice(Environment.valid_actions[1:]) self.color = random.choice(self.color_choices) def update(self, t): inputs = self.env.sense(self) action_okay = True if self.next_waypoint == 'right': if inputs['light'] == 'red' and inputs['left'] == 'forward': action_okay = False elif self.next_waypoint == 'forward': if inputs['light'] == 'red': action_okay = False elif self.next_waypoint == 'left': if inputs['light'] == 'red' or (inputs['oncoming'] == 'forward' or inputs['oncoming'] == 'right'): action_okay = False action = None if action_okay: action = self.next_waypoint self.next_waypoint = random.choice(Environment.valid_actions[1:]) reward = self.env.act(self, action) #print "DummyAgent.update(): t = {}, inputs = {}, action = {}, reward = {}".format(t, inputs, action, reward) # [debug] #print "DummyAgent.update(): next_waypoint = {}".format(self.next_waypoint) # [debug]
42.59176
164
0.587671
import time,random from collections import OrderedDict from simulator import Simulator class TrafficLight(object): """A traffic light that switches periodically.""" valid_states = [True, False] def __init__(self, state=None, period=None): self.state = state if state is not None else random.choice(self.valid_states) self.period = period if period is not None else random.choice([3, 4, 5]) self.last_updated = 0 def reset(self): self.last_updated = 0 def update(self, t): if t - self.last_updated >= self.period: self.state = not self.state self.last_updated = t class Environment(object): """Environment within which all agents operate.""" valid_actions = [None, 'forward', 'left', 'right'] valid_inputs = {'light': TrafficLight.valid_states, 'oncoming': valid_actions, 'left': valid_actions, 'right': valid_actions} valid_headings = [(1, 0), (0, -1), (-1, 0), (0, 1)] hard_time_limit = -100 def __init__(self): self.done = False self.t = 0 self.agent_states = OrderedDict() self.status_text = "" self.grid_size = (8, 6) self.bounds = (1, 1, self.grid_size[0], self.grid_size[1]) self.block_size = 100 self.intersections = OrderedDict() self.roads = [] for x in xrange(self.bounds[0], self.bounds[2] + 1): for y in xrange(self.bounds[1], self.bounds[3] + 1): self.intersections[(x, y)] = TrafficLight() for a in self.intersections: for b in self.intersections: if a == b: continue if (abs(a[0] - b[0]) + abs(a[1] - b[1])) == 1: self.roads.append((a, b)) self.num_dummies = 3 for i in xrange(self.num_dummies): self.create_agent(DummyAgent) self.primary_agent = None self.enforce_deadline = False def create_agent(self, agent_class, *args, **kwargs): agent = agent_class(self, *args, **kwargs) self.agent_states[agent] = {'location': random.choice(self.intersections.keys()), 'heading': (0, 1)} return agent def set_primary_agent(self, agent, enforce_deadline=False): self.primary_agent = agent self.enforce_deadline = enforce_deadline def reset(self): self.done = False self.t = 0 for traffic_light in self.intersections.itervalues(): traffic_light.reset() start = random.choice(self.intersections.keys()) destination = random.choice(self.intersections.keys()) while self.compute_dist(start, destination) < 4: start = random.choice(self.intersections.keys()) destination = random.choice(self.intersections.keys()) start_heading = random.choice(self.valid_headings) deadline = self.compute_dist(start, destination) * 5 print "Environment.reset(): Trial set up with start = {}, destination = {}, deadline = {}".format(start, destination, deadline) for agent in self.agent_states.iterkeys(): self.agent_states[agent] = { 'location': start if agent is self.primary_agent else random.choice(self.intersections.keys()), 'heading': start_heading if agent is self.primary_agent else random.choice(self.valid_headings), 'destination': destination if agent is self.primary_agent else None, 'deadline': deadline if agent is self.primary_agent else None} agent.reset(destination=(destination if agent is self.primary_agent else None)) def step(self): for intersection, traffic_light in self.intersections.iteritems(): traffic_light.update(self.t) for agent in self.agent_states.iterkeys(): agent.update(self.t) self.t += 1 if self.primary_agent is not None: agent_deadline = self.agent_states[self.primary_agent]['deadline'] if agent_deadline <= self.hard_time_limit: self.done = True print "Environment.step(): Primary agent hit hard time limit ({})! Trial aborted.".format(self.hard_time_limit) elif self.enforce_deadline and agent_deadline <= 0: self.done = True print "Environment.step(): Primary agent ran out of time! Trial aborted." self.agent_states[self.primary_agent]['deadline'] = agent_deadline - 1 def sense(self, agent): assert agent in self.agent_states, "Unknown agent!" state = self.agent_states[agent] location = state['location'] heading = state['heading'] light = 'green' if (self.intersections[location].state and heading[1] != 0) or ((not self.intersections[location].state) and heading[0] != 0) else 'red' oncoming = None left = None right = None for other_agent, other_state in self.agent_states.iteritems(): if agent == other_agent or location != other_state['location'] or (heading[0] == other_state['heading'][0] and heading[1] == other_state['heading'][1]): continue other_heading = other_agent.get_next_waypoint() if (heading[0] * other_state['heading'][0] + heading[1] * other_state['heading'][1]) == -1: if oncoming != 'left': oncoming = other_heading elif (heading[1] == other_state['heading'][0] and -heading[0] == other_state['heading'][1]): if right != 'forward' and right != 'left': # we don't want to override right == 'forward or 'left' right = other_heading else: if left != 'forward': # we don't want to override left == 'forward' left = other_heading return {'light': light, 'oncoming': oncoming, 'left': left, 'right': right} def get_deadline(self, agent): return self.agent_states[agent]['deadline'] if agent is self.primary_agent else None def act(self, agent, action): assert agent in self.agent_states, "Unknown agent!" assert action in self.valid_actions, "Invalid action!" state = self.agent_states[agent] location = state['location'] heading = state['heading'] light = 'green' if (self.intersections[location].state and heading[1] != 0) or ((not self.intersections[location].state) and heading[0] != 0) else 'red' sense = self.sense(agent) reward = 0 move_okay = True if action == 'forward': if light != 'green': move_okay = False elif action == 'left': if light == 'green' and (sense['oncoming'] == None or sense['oncoming'] == 'left'): heading = (heading[1], -heading[0]) else: move_okay = False elif action == 'right': if light == 'green' or sense['left'] != 'straight': heading = (-heading[1], heading[0]) else: move_okay = False if move_okay: if action is not None: location = ((location[0] + heading[0] - self.bounds[0]) % (self.bounds[2] - self.bounds[0] + 1) + self.bounds[0], (location[1] + heading[1] - self.bounds[1]) % (self.bounds[3] - self.bounds[1] + 1) + self.bounds[1]) state['location'] = location state['heading'] = heading reward = 2.0 if action == agent.get_next_waypoint() else -0.5 else: reward = 0.0 else: reward = -1.0 if agent is self.primary_agent: if state['location'] == state['destination']: if state['deadline'] >= 0: reward += 10 self.done = True print "Environment.act(): Primary agent has reached destination!" self.status_text = "state: {}\naction: {}\nreward: {}".format(agent.get_state(), action, reward) return reward def compute_dist(self, a, b): """L1 distance between two points.""" return abs(b[0] - a[0]) + abs(b[1] - a[1]) class Agent(object): """Base class for all agents.""" def __init__(self, env): self.env = env self.state = None self.next_waypoint = None self.color = 'cyan' def reset(self, destination=None): pass def update(self, t): pass def get_state(self): return self.state def get_next_waypoint(self): return self.next_waypoint class DummyAgent(Agent): color_choices = ['blue', 'cyan', 'magenta', 'orange'] def __init__(self, env): super(DummyAgent, self).__init__(env) self.next_waypoint = random.choice(Environment.valid_actions[1:]) self.color = random.choice(self.color_choices) def update(self, t): inputs = self.env.sense(self) action_okay = True if self.next_waypoint == 'right': if inputs['light'] == 'red' and inputs['left'] == 'forward': action_okay = False elif self.next_waypoint == 'forward': if inputs['light'] == 'red': action_okay = False elif self.next_waypoint == 'left': if inputs['light'] == 'red' or (inputs['oncoming'] == 'forward' or inputs['oncoming'] == 'right'): action_okay = False action = None if action_okay: action = self.next_waypoint self.next_waypoint = random.choice(Environment.valid_actions[1:]) reward = self.env.act(self, action)
false
true
f716c4d714c5addfce5044ca823eb0d4556612cc
518
py
Python
test/autest/gold_tests/smoke/smoke.test.py
SolidWallOfCode/txn-box
d92269be8bb8989bdaa96048757a01a0d3f6ba6d
[ "Apache-2.0" ]
7
2019-10-11T23:53:01.000Z
2021-09-15T01:56:50.000Z
test/autest/gold_tests/smoke/smoke.test.py
SolidWallOfCode/txn-box
d92269be8bb8989bdaa96048757a01a0d3f6ba6d
[ "Apache-2.0" ]
13
2019-08-07T16:03:51.000Z
2022-03-24T19:01:33.000Z
test/autest/gold_tests/smoke/smoke.test.py
SolidWallOfCode/txn-box
d92269be8bb8989bdaa96048757a01a0d3f6ba6d
[ "Apache-2.0" ]
5
2019-07-24T15:59:02.000Z
2021-06-23T10:02:47.000Z
# @file # # Copyright 2020, Verizon Media # SPDX-License-Identifier: Apache-2.0 # ''' Basic smoke tests. ''' Test.Summary = ''' Test basic functions and directives. ''' Test.TxnBoxTestAndRun("Smoke Test", "smoke.replay.yaml", config_path='Auto', config_key="meta.txn_box.global" ,remap=[('http://example.one/3', 'http://example.one/3', ('--key=meta.txn_box.remap-1', 'smoke.replay.yaml')) ,('http://example.one', 'http://example.one') ] )
28.777778
125
0.57722
Test.Summary = ''' Test basic functions and directives. ''' Test.TxnBoxTestAndRun("Smoke Test", "smoke.replay.yaml", config_path='Auto', config_key="meta.txn_box.global" ,remap=[('http://example.one/3', 'http://example.one/3', ('--key=meta.txn_box.remap-1', 'smoke.replay.yaml')) ,('http://example.one', 'http://example.one') ] )
true
true
f716c4e4e1ba4e92ac11bebaf53ac8c7e09eae5b
209
py
Python
treat/__init__.py
tjlaboss/tasty_treat
5a137b49c6648eda6500025de8bab9c8dcc78d45
[ "MIT" ]
3
2019-03-04T22:52:07.000Z
2022-01-23T12:28:58.000Z
treat/__init__.py
tjlaboss/tasty_treat
5a137b49c6648eda6500025de8bab9c8dcc78d45
[ "MIT" ]
3
2021-07-23T17:30:35.000Z
2021-09-17T16:25:57.000Z
treat/__init__.py
tjlaboss/tasty_treat
5a137b49c6648eda6500025de8bab9c8dcc78d45
[ "MIT" ]
null
null
null
from . import constants from . import argparse from . import elements from . import materials from . import mesh from . import moc from .treat_lattice import TreatLattice from .core_builder import CoreBuilder
23.222222
39
0.808612
from . import constants from . import argparse from . import elements from . import materials from . import mesh from . import moc from .treat_lattice import TreatLattice from .core_builder import CoreBuilder
true
true
f716c526012bd7a8136418de119de0fdce82deb1
2,884
py
Python
mswh/comm/tests/test_sql.py
hannesb0/MSWH
ce214f26369106c124052638e93cc38fbd58cc91
[ "BSD-3-Clause-LBNL" ]
5
2019-05-23T00:54:33.000Z
2021-06-01T18:06:49.000Z
mswh/comm/tests/test_sql.py
hannesb0/MSWH
ce214f26369106c124052638e93cc38fbd58cc91
[ "BSD-3-Clause-LBNL" ]
36
2019-05-22T23:02:35.000Z
2021-04-04T21:24:17.000Z
mswh/comm/tests/test_sql.py
hannesb0/MSWH
ce214f26369106c124052638e93cc38fbd58cc91
[ "BSD-3-Clause-LBNL" ]
14
2019-08-25T01:27:40.000Z
2021-11-17T19:25:02.000Z
import logging import os import unittest from mswh.comm.sql import Sql import pandas as pd logging.basicConfig(level=logging.DEBUG) # has setUpClass method, thus run the test on the entire class class SqlTests(unittest.TestCase): """Tests the db-python read-write capabilities.""" @classmethod def setUpClass(cls): """Initiates the sqlite db engine for the test db file. """ test_db_name = "test.db" test_db_fulpath = os.path.join(os.path.dirname(__file__), test_db_name) cls.test_db_fulpath = test_db_fulpath print(test_db_fulpath) # create test db if it does not exist if not os.path.exists(test_db_fulpath): os.system("touch " + test_db_fulpath) cls.sql_api = Sql(test_db_fulpath) # example dict to write to db cls.df = pd.DataFrame( data=[["a", 1], ["b", 2]], columns=["comp", "cost"] ) # example dict to write to db as table cls.dict = {"k1": [12, 13, 14], "k2": ["a", "b", "c"]} # example csv data cls.path_to_csv = os.path.join(os.path.dirname(__file__), "table.csv") # sql code to execute cls.raw_sql = """CREATE TABLE sys_components ( Component TEXT NOT NULL , Function TEXT NOT NULL , PRIMARY KEY (Component) );""" @classmethod def tearDownClass(cls): """Clean up for any reinitiation of the test, but keep the result. Any new run will overwrite the result. """ store_db_name = "test_done.db" # close the test db cls.sql_api.db.close() store_db_fulpath = os.path.join( os.path.dirname(__file__), store_db_name ) # rename file, overwrite if exists if os.path.exists(store_db_fulpath): os.remove(store_db_fulpath) os.rename(cls.test_db_fulpath, store_db_fulpath) def test_a_pd2table(self): """Tests write pandas dataframe to db as a table. """ self.sql_api.pd2table(self.df, "pd2table") def test_b_csv2table(self): """Tests write csv file to db as a table. """ self.sql_api.csv2table(self.path_to_csv, "csv2table") def test_c_table2pd(self): """Reads a single table from db as a pd.df""" df = self.sql_api.table2pd("pd2table") self.assertTrue((df == self.df).all().all()) def test_d_commit(self): """Use sql to write to db (e.g. create, alter)""" self.assertTrue(self.sql_api.commit(self.raw_sql)) def test_e_tables2dict(self): """Read all tables from db into a dictionary of dataframes. """ data = self.sql_api.tables2dict() self.assertEqual(data["pd2table"].iloc[1, 1], 2)
29.428571
80
0.587379
import logging import os import unittest from mswh.comm.sql import Sql import pandas as pd logging.basicConfig(level=logging.DEBUG) class SqlTests(unittest.TestCase): @classmethod def setUpClass(cls): test_db_name = "test.db" test_db_fulpath = os.path.join(os.path.dirname(__file__), test_db_name) cls.test_db_fulpath = test_db_fulpath print(test_db_fulpath) if not os.path.exists(test_db_fulpath): os.system("touch " + test_db_fulpath) cls.sql_api = Sql(test_db_fulpath) cls.df = pd.DataFrame( data=[["a", 1], ["b", 2]], columns=["comp", "cost"] ) cls.dict = {"k1": [12, 13, 14], "k2": ["a", "b", "c"]} cls.path_to_csv = os.path.join(os.path.dirname(__file__), "table.csv") cls.raw_sql = """CREATE TABLE sys_components ( Component TEXT NOT NULL , Function TEXT NOT NULL , PRIMARY KEY (Component) );""" @classmethod def tearDownClass(cls): store_db_name = "test_done.db" cls.sql_api.db.close() store_db_fulpath = os.path.join( os.path.dirname(__file__), store_db_name ) if os.path.exists(store_db_fulpath): os.remove(store_db_fulpath) os.rename(cls.test_db_fulpath, store_db_fulpath) def test_a_pd2table(self): self.sql_api.pd2table(self.df, "pd2table") def test_b_csv2table(self): self.sql_api.csv2table(self.path_to_csv, "csv2table") def test_c_table2pd(self): df = self.sql_api.table2pd("pd2table") self.assertTrue((df == self.df).all().all()) def test_d_commit(self): self.assertTrue(self.sql_api.commit(self.raw_sql)) def test_e_tables2dict(self): data = self.sql_api.tables2dict() self.assertEqual(data["pd2table"].iloc[1, 1], 2)
true
true
f716c53c15f21f36710f5ff9f2db87e1f34e3965
2,442
py
Python
2022-TR-Crystallography/Simulations-2.py
JMSkelton/Linkage-Isomer-JMAK-Kinetics
6ad7626ea9447855121a9b8ef6eb10efb93db300
[ "MIT" ]
null
null
null
2022-TR-Crystallography/Simulations-2.py
JMSkelton/Linkage-Isomer-JMAK-Kinetics
6ad7626ea9447855121a9b8ef6eb10efb93db300
[ "MIT" ]
null
null
null
2022-TR-Crystallography/Simulations-2.py
JMSkelton/Linkage-Isomer-JMAK-Kinetics
6ad7626ea9447855121a9b8ef6eb10efb93db300
[ "MIT" ]
null
null
null
# Simulations-2.py import glob import math import yaml from KineticAnalysis.NumericalSimulator import NumericalSimulator PPEqThreshold = 1.0e-4 if __name__ == "__main__": # Read fits to time-resolved datasets. tr_data_sets = { } for f in glob.glob(r"TimeResolved-*.yaml"): with open(f, 'rb') as input_file: input_yaml = yaml.load( input_file, Loader = yaml.CLoader ) tr_data_sets[input_yaml['label']] = ( input_yaml['t_cyc'], input_yaml['t_exc'], input_yaml['temp'], (input_yaml['data_t'], input_yaml['data_a']), (input_yaml['alpha_bg'], input_yaml['k_exc'], input_yaml['k_dec']), input_yaml['rms'] ) # For each dataset, determine the maximum excited-state population given the fitted k_exc/k_dec. for label, (t_cyc, t_exc, _, _, (_, k_exc, k_dec), _) in tr_data_sets.items(): simulator = NumericalSimulator( excN = 1.0, excK = k_exc, decN = 1.0, decK = k_dec ) # 1. Determine the excitation level achieved with the set t_cyc/t_exc. a_0, a_max = 0.0, 0.0 while True: simulator.InitialiseTrajectory(a_0) simulator.SetExcitation(True) simulator.RunTrajectory(t_exc) _, a_sim = simulator.GetTrajectory() a_max = a_sim[-1] simulator.SetExcitation(False) simulator.RunTrajectory(t_cyc - t_exc) _, a_sim = simulator.GetTrajectory() if math.fabs(a_sim[-1] - a_0) < PPEqThreshold: break a_0 = a_sim[-1] # 2. Determine the steady-state (maximum) excitation level. simulator.SetExcitation(True) simulator.InitialiseTrajectory(0.0) a_max_sim = 0.0 while True: simulator.RunTrajectory(1.0) _, a_sim = simulator.GetTrajectory() if math.fabs(a_sim[-1] - a_max_sim) < PPEqThreshold: break a_max_sim = a_sim[-1] print("{0}: a_max = {1:.3f}, theoretical = {2:.3f}".format(label, a_max, a_max_sim)) print("")
28.729412
100
0.514742
import glob import math import yaml from KineticAnalysis.NumericalSimulator import NumericalSimulator PPEqThreshold = 1.0e-4 if __name__ == "__main__": tr_data_sets = { } for f in glob.glob(r"TimeResolved-*.yaml"): with open(f, 'rb') as input_file: input_yaml = yaml.load( input_file, Loader = yaml.CLoader ) tr_data_sets[input_yaml['label']] = ( input_yaml['t_cyc'], input_yaml['t_exc'], input_yaml['temp'], (input_yaml['data_t'], input_yaml['data_a']), (input_yaml['alpha_bg'], input_yaml['k_exc'], input_yaml['k_dec']), input_yaml['rms'] ) for label, (t_cyc, t_exc, _, _, (_, k_exc, k_dec), _) in tr_data_sets.items(): simulator = NumericalSimulator( excN = 1.0, excK = k_exc, decN = 1.0, decK = k_dec ) a_0, a_max = 0.0, 0.0 while True: simulator.InitialiseTrajectory(a_0) simulator.SetExcitation(True) simulator.RunTrajectory(t_exc) _, a_sim = simulator.GetTrajectory() a_max = a_sim[-1] simulator.SetExcitation(False) simulator.RunTrajectory(t_cyc - t_exc) _, a_sim = simulator.GetTrajectory() if math.fabs(a_sim[-1] - a_0) < PPEqThreshold: break a_0 = a_sim[-1] simulator.SetExcitation(True) simulator.InitialiseTrajectory(0.0) a_max_sim = 0.0 while True: simulator.RunTrajectory(1.0) _, a_sim = simulator.GetTrajectory() if math.fabs(a_sim[-1] - a_max_sim) < PPEqThreshold: break a_max_sim = a_sim[-1] print("{0}: a_max = {1:.3f}, theoretical = {2:.3f}".format(label, a_max, a_max_sim)) print("")
true
true
f716c5621fcdf0c3aada36d496dec8b1fe35c8cc
9,045
py
Python
GUI-II/web_scrap.py
DulceWRLD/College
9b94868514f461c97121d72ea0855f72ca95e798
[ "MIT" ]
2
2021-08-21T01:25:50.000Z
2021-12-10T06:51:46.000Z
GUI-II/web_scrap.py
DulceWRLD/College
9b94868514f461c97121d72ea0855f72ca95e798
[ "MIT" ]
null
null
null
GUI-II/web_scrap.py
DulceWRLD/College
9b94868514f461c97121d72ea0855f72ca95e798
[ "MIT" ]
6
2021-03-14T22:21:23.000Z
2022-03-29T15:30:58.000Z
########################################################################################### # Created by Jason Downing # # Some code originally found at this Stackoverflow Post: # # https://stackoverflow.com/questions/18966368/python-beautifulsoup-scrape-tables # # Also this page as well: # # http://www.pythonforbeginners.com/python-on-the-web/web-scraping-with-beautifulsoup/ # # # # Copyright 2016 Jason Downing # # # MIT LICENSED - DO WHATEVER YOU WANT WITH THIS FILE. # ########################################################################################### # To setup urllib2 / bs4 (BeautifulSoup) # Follow this URL: http://linuxconfig.org/how-to-install-python3-beautiful-soup-environment-on-debian-linux # and run this command: pip install requests import json import requests from bs4 import BeautifulSoup # 6 URLs to scrap for lift / trail data. # Order is: Waterville Valley, Cannon Mt, Bretton Woods, Loon Mt & Cranmore Mt urls = ["http://www.waterville.com/ski-ride/snow-report.html", "http://cannonmt.com/trail-lift-report.html", "http://brettonwoods.com/alpine_trails/trail_report#top", "http://www.loonmtn.com/explore/snow-conditions/trail-lift-report", "http://www.cranmore.com/winter/snow-grooming-report", "http://www.patspeak.com/snow_report.php"] mountains = ["Waterville Valley", "Cannon Mt", "Bretton Woods", "Loon Mt", "Cranmore Mt", "Pats Peak"] # global JSON object to write only once. JSON_trails = {} # Waterville Valley def waterville(): print ("DONE\n") open_trails = [] closed_trails = [] # Get the page, then grab just the text and use BeautifulSoup to work some magic on it. page = requests.get(urls[0]) data = page.text soup = BeautifulSoup(data, "lxml") # Get an entire div. ski_data = soup.findAll('div', {'class' : 'tabset_content'}) # Let's get all open trails. for each_div in soup.findAll('li', {'class' : 'open'}): open_trails.append(each_div.text) # Also all closed trails. for each_div in soup.findAll('li', {'class' : 'closed'}): closed_trails.append(each_div.text) # Dump to trails object. JSON_trails['waterville_open'] = open_trails JSON_trails['waterville_closed'] = closed_trails # Cannon Mt def cannon(): print ("DONE\n") trail_list = [] trail_status = [] open_trails = [] closed_trails = [] # Get the page, then grab just the text and use BeautifulSoup to work some magic on it. page = requests.get(urls[1]) data = page.text soup = BeautifulSoup(data, "lxml") # Get lift status # From stackoverflow: # https://stackoverflow.com/questions/13074586/extracting-selected-columns-from-a-table-using-beautifulsoup tables = soup.find('table') # change this for consistent code. rows = tables.findAll('tr') for cells in rows: cell = cells.findAll('td') trail_list.append(cell[0].text) trail_status.append(cell[1].text) # Get trail status # THIS TRICK COMES FROM STACKOVERFLOW! # https://stackoverflow.com/questions/14095511/beautifulsoup-in-python-getting-the-n-th-tag-of-a-type tables = soup.findAll('table')[1] rows = tables.findAll('tr') for cells in rows: if (len(cells) == 4): cell = cells.findAll('td') trail_list.append(cell[0].text) trail_status.append(cell[1].text) # # Print for debugging purposes. # print ("Trails: \n") # for trail in trail_list: # print (trail) # print ("Status: \n") # for status in trail_status: # print (status) # Now let's figure out open / closed status for trails! list_length = len(trail_list) for a in range(list_length): if (trail_status[a] == 'Open'): open_trails.append(trail_list[a]) else: closed_trails.append(trail_list[a]) # Dump to trails object. JSON_trails['cannon_open'] = open_trails JSON_trails['cannon_closed'] = closed_trails # Bretton Woods def bretton_woods(): print ("DONE\n") trail_list = [] # List of all the trails, in order on the page. trail_status = [] # List of trail status, in order on the page. open_trails = [] # All the open trails or lifts closed_trails = [] # All the closed trails or lifts open_src = '/images/icons/open-sm.png' # Get the page, then grab just the text and use BeautifulSoup to work some magic on it. page = requests.get(urls[2]) data = page.text soup = BeautifulSoup(data, "lxml") # Get an entire div. ski_data = soup.findAll('div', {'id' : 'trail-content'}) # Using this Stackoverflow post to figure out how to get the text I need. # https://stackoverflow.com/questions/13202087/beautiful-soup-find-children-for-particular-div for tag in ski_data: tab = tag.findAll('div', {'class': 'trails-report'}) for tag2 in tab: trail_list.append(tag2.text) # This gets all the trails by name. # Now to get trail conditions tab = tag.findAll('div', {'class': 'condition'}) for img in tab: img_src = img.findAll('img')[0].get('src') # This gets the trail status (by image source) trail_status.append(img_src) # Now let's figure out open / closed status for trails! list_length = len(trail_list) for a in range(list_length): if (trail_status[a] == open_src): open_trails.append(trail_list[a]) else: closed_trails.append(trail_list[a]) # Dump to trails object. JSON_trails['bretton_woods_open'] = open_trails JSON_trails['bretton_woods_closed'] = closed_trails # Loon Mt def loon(): trail_list = [] # List of all the trails, in order on the page. trail_status = [] # List of trail status, in order on the page. open_trails = [] # All the open trails or lifts closed_trails = [] # All the closed trails or lifts # Get the page, then grab just the text and use BeautifulSoup to work some magic on it. page = requests.get(urls[3]) data = page.text soup = BeautifulSoup(data, "lxml") lifts = soup.findAll("table", {"class": "lift-status"}) titles_html = [] open_src = "/assets/prebuilt/img/template/small-green-checkmark.png" closed_src = "/assets/prebuilt/img/template/small-red-x.png" # Get all the td's on the page so we can go through and find the names / trail status. for td in soup.findAll("td"): titles_html += td # Let's get all the img's so we can find open / closed trails and lifts. for lift in lifts: # Get all the trail names. for td in lift.findAll('td'): #print (td.getText()) trail_list.append(td.getText().strip()) # Get all the trail status' img_src = lift.findAll('img') # Get all img's. # See if we found an image if len(img_src): # We did, so only keep the relevant images. if (img_src[0].get('src') == open_src or img_src[0].get('src') == closed_src): # Append to our trail status list. trail_status.append(img_src) # See what list of trails we got. # for trail in trail_list: # print (trail) # See what list of status we got. for status in trail_status: print (status) print ("length of names: ") print (len(trail_list)) print ("length of status: ") print (len(trail_status)) # Now that we have a list of status and trails, let's put them together. list_length = len(trail_list) for a in range(list_length): if (trail_status[a] == open_src): open_trails.append(trail_list[a]) else: closed_trails.append(trail_list[a]) # Dump to trails object. JSON_trails['loon_open'] = open_trails JSON_trails['loon_closed'] = closed_trails # Cranmore Mt def cranmore(): print ("NOT DONE.\n") open_trails = [] closed_trails = [] # Dump to trails object. JSON_trails['cranmore_open'] = open_trails JSON_trails['cranmore_closed'] = closed_trails def pats_peak(): print ("NOT DONE.\n") open_trails = [] closed_trails = [] # Dump to trails object. JSON_trails['pats_peak_open'] = open_trails JSON_trails['pats_peak_closed'] = closed_trails # Main loop for data gathering for num in range(0, len(urls)): print (mountains[num] + " lift / trail conditions") print ("Current URL to check: " + urls[num] + "\n") if (num == 0): print ("Hello.") #waterville() if (num == 1): print ("Hello.") #cannon() if (num == 2): print ("Hello.") #bretton_woods() if (num == 3): loon() if (num == 4): print ("Hello.") #cranmore() if (num == 5): print ("Hello.") #pats_peak() # Dump to JSON file now. # Stackoverflow post this is from: # https://stackoverflow.com/questions/16267767/python-writing-json-to-file with open("json/ski.json", "w") as outfile: json.dump(JSON_trails, outfile, indent = 4)
31.297578
109
0.629519
true
true
f716c5911528e44ebe67f4a2d8cb1ca1d4e1243b
4,273
py
Python
codalab/rest/chats.py
millerjohnp/codalab-worksheets
d6fc37864e7a8966380fc9d73865b10e434d6678
[ "Apache-2.0" ]
null
null
null
codalab/rest/chats.py
millerjohnp/codalab-worksheets
d6fc37864e7a8966380fc9d73865b10e434d6678
[ "Apache-2.0" ]
null
null
null
codalab/rest/chats.py
millerjohnp/codalab-worksheets
d6fc37864e7a8966380fc9d73865b10e434d6678
[ "Apache-2.0" ]
1
2020-03-13T08:16:17.000Z
2020-03-13T08:16:17.000Z
""" Chatbox API """ import os from bottle import get, local, post, request import yaml from codalab.objects.chat_box_qa import ChatBoxQA from codalab.server.authenticated_plugin import AuthenticatedPlugin @get('/chats', apply=AuthenticatedPlugin()) def get_chat_box(): """ Return a list of chats that the current user has had """ query = {'user_id': request.user.user_id} return { 'chats': local.model.get_chat_log_info(query), 'root_user_id': local.model.root_user_id, 'system_user_id': local.model.system_user_id, } @post('/chats', apply=AuthenticatedPlugin()) def post_chat_box(): """ Add the chat to the log. Return an auto response, if the chat is directed to the system. Otherwise, return an updated chat list of the sender. """ recipient_user_id = request.POST.get('recipientUserId', None) message = request.POST.get('message', None) worksheet_uuid = request.POST.get('worksheetId', -1) bundle_uuid = request.POST.get('bundleId', -1) info = { 'sender_user_id': request.user.user_id, 'recipient_user_id': recipient_user_id, 'message': message, 'worksheet_uuid': worksheet_uuid, 'bundle_uuid': bundle_uuid, } chats = add_chat_log_info(info) return {'chats': chats} # @get('/faqs') def get_faq(): """ Return a list of FAQ items, each of the following format: '0': { 'question': 'how can I upload / add a bundle?' 'answer': { 'response': 'You can do cl upload or click Update Bundle.', 'command': 'cl upload <file_path>' } } Currently disabled. Needs further work. """ file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '../objects/chat_box_qa.yaml' ) with open(file_path, 'r') as stream: content = yaml.safe_load(stream) return {'faq': content} def add_chat_log_info(query_info): """ Add the given chat into the database. |query_info| encapsulates all the information of one chat Example: query_info = { 'sender_user_id': 1, 'recipient_user_id': 2, 'message': 'Hello this is my message', 'worksheet_uuid': 0x508cf51e546742beba97ed9a69329838, // the worksheet the user is browsing when he/she sends this message 'bundle_uuid': 0x8e66b11ecbda42e2a1f544627acf1418, // the bundle the user is browsing when he/she sends this message } Return an auto response, if the chat is directed to the system. Otherwise, return an updated chat list of the sender. """ updated_data = local.model.add_chat_log_info(query_info) if query_info.get('recipient_user_id') != local.model.system_user_id: return updated_data else: message = query_info.get('message') worksheet_uuid = query_info.get('worksheet_uuid') bundle_uuid = query_info.get('bundle_uuid') bot_response = format_message_response( ChatBoxQA.answer(message, worksheet_uuid, bundle_uuid) ) info = { 'sender_user_id': local.model.system_user_id, 'recipient_user_id': request.user.user_id, 'message': bot_response, 'worksheet_uuid': worksheet_uuid, 'bundle_uuid': bundle_uuid, } local.model.add_chat_log_info(info) return bot_response def format_message_response(params): """ Format automatic response |params| is None if the system can't process the user's message or is not confident enough to give a response. Otherwise, |params| is a triple that consists of the question that the system is trying to answer, the response it has for that question, and the recommended command to run. Return the automatic response that will be sent back to the user's chat box. """ if params is None: return 'Thank you for your question. Our staff will get back to you as soon as we can.' else: question, response, command = params result = 'This is the question we are trying to answer: ' + question + '\n' result += response + '\n' result += 'You can try to run the following command: \n' result += command return result
34.739837
132
0.656681
import os from bottle import get, local, post, request import yaml from codalab.objects.chat_box_qa import ChatBoxQA from codalab.server.authenticated_plugin import AuthenticatedPlugin @get('/chats', apply=AuthenticatedPlugin()) def get_chat_box(): query = {'user_id': request.user.user_id} return { 'chats': local.model.get_chat_log_info(query), 'root_user_id': local.model.root_user_id, 'system_user_id': local.model.system_user_id, } @post('/chats', apply=AuthenticatedPlugin()) def post_chat_box(): recipient_user_id = request.POST.get('recipientUserId', None) message = request.POST.get('message', None) worksheet_uuid = request.POST.get('worksheetId', -1) bundle_uuid = request.POST.get('bundleId', -1) info = { 'sender_user_id': request.user.user_id, 'recipient_user_id': recipient_user_id, 'message': message, 'worksheet_uuid': worksheet_uuid, 'bundle_uuid': bundle_uuid, } chats = add_chat_log_info(info) return {'chats': chats} def get_faq(): file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '../objects/chat_box_qa.yaml' ) with open(file_path, 'r') as stream: content = yaml.safe_load(stream) return {'faq': content} def add_chat_log_info(query_info): updated_data = local.model.add_chat_log_info(query_info) if query_info.get('recipient_user_id') != local.model.system_user_id: return updated_data else: message = query_info.get('message') worksheet_uuid = query_info.get('worksheet_uuid') bundle_uuid = query_info.get('bundle_uuid') bot_response = format_message_response( ChatBoxQA.answer(message, worksheet_uuid, bundle_uuid) ) info = { 'sender_user_id': local.model.system_user_id, 'recipient_user_id': request.user.user_id, 'message': bot_response, 'worksheet_uuid': worksheet_uuid, 'bundle_uuid': bundle_uuid, } local.model.add_chat_log_info(info) return bot_response def format_message_response(params): if params is None: return 'Thank you for your question. Our staff will get back to you as soon as we can.' else: question, response, command = params result = 'This is the question we are trying to answer: ' + question + '\n' result += response + '\n' result += 'You can try to run the following command: \n' result += command return result
true
true
f716c5deb4bfae59b106289a4f4dd8d17a07d48e
12,462
py
Python
testing/test_ldclient_evaluation.py
gangeli/python-server-sdk
3095315fd53c3bf723b0f16b0c18acadef4dfb3e
[ "Apache-2.0" ]
null
null
null
testing/test_ldclient_evaluation.py
gangeli/python-server-sdk
3095315fd53c3bf723b0f16b0c18acadef4dfb3e
[ "Apache-2.0" ]
null
null
null
testing/test_ldclient_evaluation.py
gangeli/python-server-sdk
3095315fd53c3bf723b0f16b0c18acadef4dfb3e
[ "Apache-2.0" ]
null
null
null
import pytest import json import time from ldclient.client import LDClient, Config from ldclient.feature_store import InMemoryFeatureStore from ldclient.flag import EvaluationDetail from ldclient.interfaces import FeatureStore from ldclient.versioned_data_kind import FEATURES from testing.stub_util import MockEventProcessor, MockUpdateProcessor from testing.test_ldclient import make_off_flag_with_value user = { 'key': 'userkey' } flag1 = { 'key': 'key1', 'version': 100, 'on': False, 'offVariation': 0, 'variations': [ 'value1' ], 'trackEvents': False } flag2 = { 'key': 'key2', 'version': 200, 'on': False, 'offVariation': 1, 'variations': [ 'x', 'value2' ], 'trackEvents': True, 'debugEventsUntilDate': 1000 } class ErroringFeatureStore(FeatureStore): def get(self, kind, key, callback=lambda x: x): raise NotImplementedError() def all(self, kind, callback=lambda x: x): raise NotImplementedError() def upsert(self, kind, item): pass def delete(self, key, version): pass def init(self, data): pass @property def initialized(self): return True def make_client(store): return LDClient(config=Config(sdk_key='SDK_KEY', base_uri='http://test', event_processor_class=MockEventProcessor, update_processor_class=MockUpdateProcessor, feature_store=store)) def get_log_lines(caplog, level): loglines = caplog.records if callable(loglines): # records() is a function in older versions of the caplog plugin loglines = loglines() return [line.message for line in loglines if line.levelname == level] def test_variation_for_existing_feature(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) assert 'value' == client.variation('feature.key', user, default='default') def test_variation_for_unknown_feature(): store = InMemoryFeatureStore() client = make_client(store) assert 'default' == client.variation('feature.key', user, default='default') def test_variation_when_user_is_none(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) assert 'default' == client.variation('feature.key', None, default='default') def test_variation_when_user_has_no_key(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) assert 'default' == client.variation('feature.key', { }, default='default') def test_variation_for_flag_that_evaluates_to_none(): empty_flag = { 'key': 'feature.key', 'on': False, 'offVariation': None } store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': empty_flag}}) client = make_client(store) assert 'default' == client.variation('feature.key', user, default='default') def test_variation_detail_for_existing_feature(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) expected = EvaluationDetail('value', 0, {'kind': 'OFF'}) assert expected == client.variation_detail('feature.key', user, default='default') def test_variation_detail_for_unknown_feature(): store = InMemoryFeatureStore() client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'ERROR', 'errorKind': 'FLAG_NOT_FOUND'}) assert expected == client.variation_detail('feature.key', user, default='default') def test_variation_detail_when_user_is_none(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'ERROR', 'errorKind': 'USER_NOT_SPECIFIED'}) assert expected == client.variation_detail('feature.key', None, default='default') def test_variation_detail_when_user_has_no_key(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'ERROR', 'errorKind': 'USER_NOT_SPECIFIED'}) assert expected == client.variation_detail('feature.key', { }, default='default') def test_variation_detail_for_flag_that_evaluates_to_none(): empty_flag = { 'key': 'feature.key', 'on': False, 'offVariation': None } store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': empty_flag}}) client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'OFF'}) actual = client.variation_detail('feature.key', user, default='default') assert expected == actual assert actual.is_default_value() == True def test_variation_when_feature_store_throws_error(caplog): store = ErroringFeatureStore() client = make_client(store) assert client.variation('feature.key', { "key": "user" }, default='default') == 'default' errlog = get_log_lines(caplog, 'ERROR') assert errlog == [ 'Unexpected error while retrieving feature flag "feature.key": NotImplementedError()' ] def test_variation_detail_when_feature_store_throws_error(caplog): store = ErroringFeatureStore() client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'ERROR', 'errorKind': 'EXCEPTION'}) actual = client.variation_detail('feature.key', { "key": "user" }, default='default') assert expected == actual assert actual.is_default_value() == True errlog = get_log_lines(caplog, 'ERROR') assert errlog == [ 'Unexpected error while retrieving feature flag "feature.key": NotImplementedError()' ] def test_all_flags_returns_values(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) result = client.all_flags(user) assert result == { 'key1': 'value1', 'key2': 'value2' } def test_all_flags_returns_none_if_user_is_none(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) result = client.all_flags(None) assert result is None def test_all_flags_returns_none_if_user_has_no_key(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) result = client.all_flags({ }) assert result is None def test_all_flags_returns_none_if_feature_store_throws_error(caplog): store = ErroringFeatureStore() client = make_client(store) assert client.all_flags({ "key": "user" }) is None errlog = get_log_lines(caplog, 'ERROR') assert errlog == [ 'Unable to read flags for all_flag_state: NotImplementedError()' ] def test_all_flags_state_returns_state(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) state = client.all_flags_state(user) assert state.valid == True result = state.to_json_dict() assert result == { 'key1': 'value1', 'key2': 'value2', '$flagsState': { 'key1': { 'variation': 0, 'version': 100 }, 'key2': { 'variation': 1, 'version': 200, 'trackEvents': True, 'debugEventsUntilDate': 1000 } }, '$valid': True } def test_all_flags_state_returns_state_with_reasons(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) state = client.all_flags_state(user, with_reasons=True) assert state.valid == True result = state.to_json_dict() assert result == { 'key1': 'value1', 'key2': 'value2', '$flagsState': { 'key1': { 'variation': 0, 'version': 100, 'reason': {'kind': 'OFF'} }, 'key2': { 'variation': 1, 'version': 200, 'trackEvents': True, 'debugEventsUntilDate': 1000, 'reason': {'kind': 'OFF'} } }, '$valid': True } def test_all_flags_state_can_be_filtered_for_client_side_flags(): flag1 = { 'key': 'server-side-1', 'on': False, 'offVariation': 0, 'variations': [ 'a' ], 'clientSide': False } flag2 = { 'key': 'server-side-2', 'on': False, 'offVariation': 0, 'variations': [ 'b' ], 'clientSide': False } flag3 = { 'key': 'client-side-1', 'on': False, 'offVariation': 0, 'variations': [ 'value1' ], 'clientSide': True } flag4 = { 'key': 'client-side-2', 'on': False, 'offVariation': 0, 'variations': [ 'value2' ], 'clientSide': True } store = InMemoryFeatureStore() store.init({ FEATURES: { flag1['key']: flag1, flag2['key']: flag2, flag3['key']: flag3, flag4['key']: flag4 } }) client = make_client(store) state = client.all_flags_state(user, client_side_only=True) assert state.valid == True values = state.to_values_map() assert values == { 'client-side-1': 'value1', 'client-side-2': 'value2' } def test_all_flags_state_can_omit_details_for_untracked_flags(): future_time = (time.time() * 1000) + 100000 flag1 = { 'key': 'key1', 'version': 100, 'on': False, 'offVariation': 0, 'variations': [ 'value1' ], 'trackEvents': False } flag2 = { 'key': 'key2', 'version': 200, 'on': False, 'offVariation': 1, 'variations': [ 'x', 'value2' ], 'trackEvents': True } flag3 = { 'key': 'key3', 'version': 300, 'on': False, 'offVariation': 1, 'variations': [ 'x', 'value3' ], 'debugEventsUntilDate': future_time } store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2, 'key3': flag3 } }) client = make_client(store) state = client.all_flags_state(user, with_reasons=True, details_only_for_tracked_flags=True) assert state.valid == True result = state.to_json_dict() assert result == { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3', '$flagsState': { 'key1': { 'variation': 0 }, 'key2': { 'variation': 1, 'version': 200, 'trackEvents': True, 'reason': {'kind': 'OFF'} }, 'key3': { 'variation': 1, 'version': 300, 'debugEventsUntilDate': future_time, 'reason': {'kind': 'OFF'} } }, '$valid': True } def test_all_flags_state_returns_empty_state_if_user_is_none(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) state = client.all_flags_state(None) assert state.valid == False def test_all_flags_state_returns_empty_state_if_user_has_no_key(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) state = client.all_flags_state({ }) assert state.valid == False def test_all_flags_returns_empty_state_if_feature_store_throws_error(caplog): store = ErroringFeatureStore() client = make_client(store) state = client.all_flags_state({ "key": "user" }) assert state.valid == False errlog = get_log_lines(caplog, 'ERROR') assert errlog == [ 'Unable to read flags for all_flag_state: NotImplementedError()' ]
34.520776
116
0.620847
import pytest import json import time from ldclient.client import LDClient, Config from ldclient.feature_store import InMemoryFeatureStore from ldclient.flag import EvaluationDetail from ldclient.interfaces import FeatureStore from ldclient.versioned_data_kind import FEATURES from testing.stub_util import MockEventProcessor, MockUpdateProcessor from testing.test_ldclient import make_off_flag_with_value user = { 'key': 'userkey' } flag1 = { 'key': 'key1', 'version': 100, 'on': False, 'offVariation': 0, 'variations': [ 'value1' ], 'trackEvents': False } flag2 = { 'key': 'key2', 'version': 200, 'on': False, 'offVariation': 1, 'variations': [ 'x', 'value2' ], 'trackEvents': True, 'debugEventsUntilDate': 1000 } class ErroringFeatureStore(FeatureStore): def get(self, kind, key, callback=lambda x: x): raise NotImplementedError() def all(self, kind, callback=lambda x: x): raise NotImplementedError() def upsert(self, kind, item): pass def delete(self, key, version): pass def init(self, data): pass @property def initialized(self): return True def make_client(store): return LDClient(config=Config(sdk_key='SDK_KEY', base_uri='http://test', event_processor_class=MockEventProcessor, update_processor_class=MockUpdateProcessor, feature_store=store)) def get_log_lines(caplog, level): loglines = caplog.records if callable(loglines): loglines = loglines() return [line.message for line in loglines if line.levelname == level] def test_variation_for_existing_feature(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) assert 'value' == client.variation('feature.key', user, default='default') def test_variation_for_unknown_feature(): store = InMemoryFeatureStore() client = make_client(store) assert 'default' == client.variation('feature.key', user, default='default') def test_variation_when_user_is_none(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) assert 'default' == client.variation('feature.key', None, default='default') def test_variation_when_user_has_no_key(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) assert 'default' == client.variation('feature.key', { }, default='default') def test_variation_for_flag_that_evaluates_to_none(): empty_flag = { 'key': 'feature.key', 'on': False, 'offVariation': None } store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': empty_flag}}) client = make_client(store) assert 'default' == client.variation('feature.key', user, default='default') def test_variation_detail_for_existing_feature(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) expected = EvaluationDetail('value', 0, {'kind': 'OFF'}) assert expected == client.variation_detail('feature.key', user, default='default') def test_variation_detail_for_unknown_feature(): store = InMemoryFeatureStore() client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'ERROR', 'errorKind': 'FLAG_NOT_FOUND'}) assert expected == client.variation_detail('feature.key', user, default='default') def test_variation_detail_when_user_is_none(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'ERROR', 'errorKind': 'USER_NOT_SPECIFIED'}) assert expected == client.variation_detail('feature.key', None, default='default') def test_variation_detail_when_user_has_no_key(): feature = make_off_flag_with_value('feature.key', 'value') store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': feature}}) client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'ERROR', 'errorKind': 'USER_NOT_SPECIFIED'}) assert expected == client.variation_detail('feature.key', { }, default='default') def test_variation_detail_for_flag_that_evaluates_to_none(): empty_flag = { 'key': 'feature.key', 'on': False, 'offVariation': None } store = InMemoryFeatureStore() store.init({FEATURES: {'feature.key': empty_flag}}) client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'OFF'}) actual = client.variation_detail('feature.key', user, default='default') assert expected == actual assert actual.is_default_value() == True def test_variation_when_feature_store_throws_error(caplog): store = ErroringFeatureStore() client = make_client(store) assert client.variation('feature.key', { "key": "user" }, default='default') == 'default' errlog = get_log_lines(caplog, 'ERROR') assert errlog == [ 'Unexpected error while retrieving feature flag "feature.key": NotImplementedError()' ] def test_variation_detail_when_feature_store_throws_error(caplog): store = ErroringFeatureStore() client = make_client(store) expected = EvaluationDetail('default', None, {'kind': 'ERROR', 'errorKind': 'EXCEPTION'}) actual = client.variation_detail('feature.key', { "key": "user" }, default='default') assert expected == actual assert actual.is_default_value() == True errlog = get_log_lines(caplog, 'ERROR') assert errlog == [ 'Unexpected error while retrieving feature flag "feature.key": NotImplementedError()' ] def test_all_flags_returns_values(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) result = client.all_flags(user) assert result == { 'key1': 'value1', 'key2': 'value2' } def test_all_flags_returns_none_if_user_is_none(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) result = client.all_flags(None) assert result is None def test_all_flags_returns_none_if_user_has_no_key(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) result = client.all_flags({ }) assert result is None def test_all_flags_returns_none_if_feature_store_throws_error(caplog): store = ErroringFeatureStore() client = make_client(store) assert client.all_flags({ "key": "user" }) is None errlog = get_log_lines(caplog, 'ERROR') assert errlog == [ 'Unable to read flags for all_flag_state: NotImplementedError()' ] def test_all_flags_state_returns_state(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) state = client.all_flags_state(user) assert state.valid == True result = state.to_json_dict() assert result == { 'key1': 'value1', 'key2': 'value2', '$flagsState': { 'key1': { 'variation': 0, 'version': 100 }, 'key2': { 'variation': 1, 'version': 200, 'trackEvents': True, 'debugEventsUntilDate': 1000 } }, '$valid': True } def test_all_flags_state_returns_state_with_reasons(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) state = client.all_flags_state(user, with_reasons=True) assert state.valid == True result = state.to_json_dict() assert result == { 'key1': 'value1', 'key2': 'value2', '$flagsState': { 'key1': { 'variation': 0, 'version': 100, 'reason': {'kind': 'OFF'} }, 'key2': { 'variation': 1, 'version': 200, 'trackEvents': True, 'debugEventsUntilDate': 1000, 'reason': {'kind': 'OFF'} } }, '$valid': True } def test_all_flags_state_can_be_filtered_for_client_side_flags(): flag1 = { 'key': 'server-side-1', 'on': False, 'offVariation': 0, 'variations': [ 'a' ], 'clientSide': False } flag2 = { 'key': 'server-side-2', 'on': False, 'offVariation': 0, 'variations': [ 'b' ], 'clientSide': False } flag3 = { 'key': 'client-side-1', 'on': False, 'offVariation': 0, 'variations': [ 'value1' ], 'clientSide': True } flag4 = { 'key': 'client-side-2', 'on': False, 'offVariation': 0, 'variations': [ 'value2' ], 'clientSide': True } store = InMemoryFeatureStore() store.init({ FEATURES: { flag1['key']: flag1, flag2['key']: flag2, flag3['key']: flag3, flag4['key']: flag4 } }) client = make_client(store) state = client.all_flags_state(user, client_side_only=True) assert state.valid == True values = state.to_values_map() assert values == { 'client-side-1': 'value1', 'client-side-2': 'value2' } def test_all_flags_state_can_omit_details_for_untracked_flags(): future_time = (time.time() * 1000) + 100000 flag1 = { 'key': 'key1', 'version': 100, 'on': False, 'offVariation': 0, 'variations': [ 'value1' ], 'trackEvents': False } flag2 = { 'key': 'key2', 'version': 200, 'on': False, 'offVariation': 1, 'variations': [ 'x', 'value2' ], 'trackEvents': True } flag3 = { 'key': 'key3', 'version': 300, 'on': False, 'offVariation': 1, 'variations': [ 'x', 'value3' ], 'debugEventsUntilDate': future_time } store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2, 'key3': flag3 } }) client = make_client(store) state = client.all_flags_state(user, with_reasons=True, details_only_for_tracked_flags=True) assert state.valid == True result = state.to_json_dict() assert result == { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3', '$flagsState': { 'key1': { 'variation': 0 }, 'key2': { 'variation': 1, 'version': 200, 'trackEvents': True, 'reason': {'kind': 'OFF'} }, 'key3': { 'variation': 1, 'version': 300, 'debugEventsUntilDate': future_time, 'reason': {'kind': 'OFF'} } }, '$valid': True } def test_all_flags_state_returns_empty_state_if_user_is_none(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) state = client.all_flags_state(None) assert state.valid == False def test_all_flags_state_returns_empty_state_if_user_has_no_key(): store = InMemoryFeatureStore() store.init({ FEATURES: { 'key1': flag1, 'key2': flag2 } }) client = make_client(store) state = client.all_flags_state({ }) assert state.valid == False def test_all_flags_returns_empty_state_if_feature_store_throws_error(caplog): store = ErroringFeatureStore() client = make_client(store) state = client.all_flags_state({ "key": "user" }) assert state.valid == False errlog = get_log_lines(caplog, 'ERROR') assert errlog == [ 'Unable to read flags for all_flag_state: NotImplementedError()' ]
true
true
f716c6d4dbe952ad73298aca3af754a81ad523a5
1,666
py
Python
step6_orchestration/telegram_publisher/publisher.py
osmya/pydatanlp
4162221224d2ad67078949691b0cfc4222731acd
[ "Apache-2.0" ]
19
2019-07-01T13:31:45.000Z
2021-08-02T10:46:59.000Z
step6_orchestration/telegram_publisher/publisher.py
osmya/pydatanlp
4162221224d2ad67078949691b0cfc4222731acd
[ "Apache-2.0" ]
1
2019-07-11T15:15:18.000Z
2019-07-20T16:41:36.000Z
step6_orchestration/telegram_publisher/publisher.py
osmya/pydatanlp
4162221224d2ad67078949691b0cfc4222731acd
[ "Apache-2.0" ]
15
2019-07-11T21:26:06.000Z
2021-08-04T09:04:59.000Z
from aiogram import Bot, Dispatcher, executor, types from aiogram.utils.exceptions import CantParseEntities from dotenv import load_dotenv, find_dotenv from signal import signal, SIGINT from tqdm import tqdm from os import getenv import sys import fire import uvloop import redis load_dotenv(find_dotenv('.telegram')) uvloop.install() REDIS_HOST = getenv('REDIS_URL', 'localhost') channel_id = getenv('MY_TELEGRAM_NUMBER') async def push_update(content, bot): try: return await bot.send_message( channel_id, content, parse_mode='Markdown') except CantParseEntities: return await bot.send_message(channel_id, content) async def listen(source): r_conn = redis.Redis(REDIS_HOST) p = r_conn.pubsub(ignore_subscribe_messages=True) p.subscribe(source) for message in tqdm(p.listen()): yield message['data'] async def subscribe_and_listen(bot, channel_name='processed'): async for message in listen(channel_name): await push_update(message, bot) def main(): fire.Fire(TelegramPublisher) class TelegramPublisher: def publish(self, channel_name='processed'): signal(SIGINT, interrupt_handler) try: loop = uvloop.new_event_loop() bot = Bot(token=getenv('TELEGRAM_KEY'), loop=loop) task = loop.create_task(subscribe_and_listen(bot, channel_name)) loop.run_until_complete(task) finally: task.cancel() loop.run_until_complete(bot.close()) loop.close() def interrupt_handler(signal, frame): print('\nYou pressed Ctrl+C!') sys.exit(0) if __name__ == "__main__": main()
27.311475
76
0.697479
from aiogram import Bot, Dispatcher, executor, types from aiogram.utils.exceptions import CantParseEntities from dotenv import load_dotenv, find_dotenv from signal import signal, SIGINT from tqdm import tqdm from os import getenv import sys import fire import uvloop import redis load_dotenv(find_dotenv('.telegram')) uvloop.install() REDIS_HOST = getenv('REDIS_URL', 'localhost') channel_id = getenv('MY_TELEGRAM_NUMBER') async def push_update(content, bot): try: return await bot.send_message( channel_id, content, parse_mode='Markdown') except CantParseEntities: return await bot.send_message(channel_id, content) async def listen(source): r_conn = redis.Redis(REDIS_HOST) p = r_conn.pubsub(ignore_subscribe_messages=True) p.subscribe(source) for message in tqdm(p.listen()): yield message['data'] async def subscribe_and_listen(bot, channel_name='processed'): async for message in listen(channel_name): await push_update(message, bot) def main(): fire.Fire(TelegramPublisher) class TelegramPublisher: def publish(self, channel_name='processed'): signal(SIGINT, interrupt_handler) try: loop = uvloop.new_event_loop() bot = Bot(token=getenv('TELEGRAM_KEY'), loop=loop) task = loop.create_task(subscribe_and_listen(bot, channel_name)) loop.run_until_complete(task) finally: task.cancel() loop.run_until_complete(bot.close()) loop.close() def interrupt_handler(signal, frame): print('\nYou pressed Ctrl+C!') sys.exit(0) if __name__ == "__main__": main()
true
true