signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def isignored ( self , relpath , directory = False ) : """Returns True if path matches pants ignore pattern ."""
relpath = self . _relpath_no_dot ( relpath ) if directory : relpath = self . _append_trailing_slash ( relpath ) return self . ignore . match_file ( relpath )
def linear_least_squares ( a , b , residuals = False ) : """Return the least - squares solution to a linear matrix equation . Solves the equation ` a x = b ` by computing a vector ` x ` that minimizes the Euclidean 2 - norm ` | | b - a x | | ^ 2 ` . The equation may be under - , well - , or over - determined ...
# Copyright ( c ) 2013 Alexandre Drouin . All rights reserved . # From https : / / gist . github . com / aldro61/5889795 from warnings import warn # from scipy . linalg . fblas import dgemm from scipy . linalg . blas import dgemm # if type ( a ) ! = np . ndarray or not a . flags [ ' C _ CONTIGUOUS ' ] : # warn ( ' Matr...
def is_excluded ( root , excludes ) : """Check if the directory is in the exclude list . Note : by having trailing slashes , we avoid common prefix issues , like e . g . an exlude " foo " also accidentally excluding " foobar " ."""
root = os . path . normpath ( root ) for exclude in excludes : if root == exclude : return True return False
def c_M_z ( self , M , z ) : """fitting function of http : / / moriond . in2p3 . fr / J08 / proceedings / duffy . pdf for the mass and redshift dependence of the concentration parameter : param M : halo mass in M _ sun / h : type M : float or numpy array : param z : redshift : type z : float > 0 : return ...
# fitted parameter values A = 5.22 B = - 0.072 C = - 0.42 M_pivot = 2. * 10 ** 12 return A * ( M / M_pivot ) ** B * ( 1 + z ) ** C
def is_inside ( directory , fname ) : """True if fname is inside directory . The parameters should typically be passed to osutils . normpath first , so that . and . . and repeated slashes are eliminated , and the separators are canonical for the platform . The empty string as a dir name is taken as top - of...
# XXX : Most callers of this can actually do something smarter by # looking at the inventory if directory == fname : return True if directory == b'' : return True if not directory . endswith ( b'/' ) : directory += b'/' return fname . startswith ( directory )
def normalize ( self , inplace = True ) : """Normalizes the pdf of the distribution so that it integrates to 1 over all the variables . Parameters inplace : boolean If inplace = True it will modify the distribution itself , else would return a new distribution . Returns CustomDistribution or None : ...
phi = self if inplace else self . copy ( ) pdf = self . pdf pdf_mod = integrate . nquad ( pdf , [ [ - np . inf , np . inf ] for var in self . variables ] ) [ 0 ] phi . _pdf = lambda * args : pdf ( * args ) / pdf_mod if not inplace : return phi
def save_license ( license_code ) : """Grab license , save to LICENSE / LICENSE . txt file"""
desc = _get_license_description ( license_code ) fname = "LICENSE" if sys . platform == "win32" : fname += ".txt" # Windows and file exts with open ( os . path . join ( os . getcwd ( ) , fname ) , "w" ) as afile : afile . write ( desc )
def remove_consecutive_duplicates ( elements ) : """This function eliminates consecutive duplicates from a list . Args : elements : A list of integers or characters . Returns : A list which includes the distinct consecutive elements in the original list . Examples : > > > remove _ consecutive _ duplicat...
from itertools import groupby return [ item for item , _ in groupby ( elements ) ]
def to_chunks ( stream_or_generator ) : """This generator function receives file - like or generator as input and returns generator . : param file | _ _ generator [ bytes ] stream _ or _ generator : readable stream or generator . : rtype : _ _ generator [ bytes ] : raise : TypeError"""
if isinstance ( stream_or_generator , types . GeneratorType ) : yield from stream_or_generator elif hasattr ( stream_or_generator , 'read' ) : while True : chunk = stream_or_generator . read ( CHUNK_SIZE ) if not chunk : break # no more data yield chunk else : rai...
def update ( self , path , verbose = False ) : """if the path isn ' t being watched , start watching it if it is , stop watching it"""
if path in self . _by_path : self . remove ( path ) else : self . add ( path , verbose )
def _get_entity_ids ( field_name , attrs ) : """Find the IDs for a one to many relationship . The server may return JSON data in the following forms for a : class : ` nailgun . entity _ fields . OneToManyField ` : : ' user ' : [ { ' id ' : 1 , . . . } , { ' id ' : 42 , . . . } ] ' users ' : [ { ' id ' : 1 ,...
field_name_ids = field_name + '_ids' plural_field_name = pluralize ( field_name ) if field_name_ids in attrs : return attrs [ field_name_ids ] elif field_name in attrs : return [ entity [ 'id' ] for entity in attrs [ field_name ] ] elif plural_field_name in attrs : return [ entity [ 'id' ] for entity in att...
def _json_safe_float ( number ) : """JSON serialization for infinity can be problematic . See https : / / docs . python . org / 2 / library / json . html # basic - usage This function returns None if ` number ` is infinity or negative infinity . If the ` number ` cannot be converted to float , this will raise...
if number is None : return None if isinstance ( number , float ) : return None if np . isinf ( number ) or np . isnan ( number ) else number # errors if number is not float compatible return float ( number )
def register_object ( self , obj , name , tango_class_name = None , member_filter = None ) : """: param member _ filter : callable ( obj , tango _ class _ name , member _ name , member ) - > bool"""
slash_count = name . count ( "/" ) if slash_count == 0 : alias = name full_name = "{0}/{1}" . format ( self . server_instance , name ) elif slash_count == 2 : alias = None full_name = name else : raise ValueError ( "Invalid name" ) class_name = tango_class_name or obj . __class__ . __name__ tango_cl...
def dec2bin ( s ) : """dec2bin 十进制 to 二进制 : bin ( ) : param s : : return :"""
if not isinstance ( s , int ) : num = int ( s ) else : num = s mid = [ ] while True : if num == 0 : break num , rem = divmod ( num , 2 ) mid . append ( base [ rem ] ) return '' . join ( [ str ( x ) for x in mid [ : : - 1 ] ] )
def send_cons3rt_agent_logs ( self ) : """Send the cons3rt agent log file : return :"""
log = logging . getLogger ( self . cls_logger + '.send_cons3rt_agent_logs' ) if self . cons3rt_agent_log_dir is None : log . warn ( 'There is not CONS3RT agent log directory on this system' ) return log . debug ( 'Searching for log files in directory: {d}' . format ( d = self . cons3rt_agent_log_dir ) ) for ite...
def rectangle_geo_array ( rectangle , map_canvas ) : """Obtain the rectangle in EPSG : 4326. : param rectangle : A rectangle instance . : type rectangle : QgsRectangle : param map _ canvas : A map canvas instance . : type map _ canvas : QgsMapCanvas : returns : A list in the form [ xmin , ymin , xmax , ym...
destination_crs = QgsCoordinateReferenceSystem ( ) destination_crs . createFromSrid ( 4326 ) source_crs = map_canvas . mapSettings ( ) . destinationCrs ( ) return extent_to_array ( rectangle , source_crs , destination_crs )
def add_or_filter ( self , * values ) : """Add a filter using " OR " logic . This filter is useful when matching on one or more criteria . For example , searching for IP 1.1.1.1 and service TCP / 443 , or IP 1.1.1.10 and TCP / 80 . Either pair would produce a positive match . . . seealso : : : class : ` smc...
filt = OrFilter ( * values ) self . update_filter ( filt ) return filt
def reverse_search_history ( event ) : """Search backward starting at the current line and moving ` up ` through the history as necessary . This is an incremental search ."""
event . cli . current_search_state . direction = IncrementalSearchDirection . BACKWARD event . cli . push_focus ( SEARCH_BUFFER )
def is_simple ( tx : Transaction ) -> bool : """Filter a transaction and checks if it is a basic one A simple transaction is a tx which has only one issuer and two outputs maximum . The unlocks must be done with simple " SIG " functions , and the outputs must be simple SIG conditions . : param tx : the tr...
simple = True if len ( tx . issuers ) != 1 : simple = False for unlock in tx . unlocks : if len ( unlock . parameters ) != 1 : simple = False elif type ( unlock . parameters [ 0 ] ) is not SIGParameter : simple = False for o in tx . outputs : # if right condition is not None . . . if get...
def list_role_for_all_namespaces ( self , ** kwargs ) : # noqa : E501 """list _ role _ for _ all _ namespaces # noqa : E501 list or watch objects of kind Role # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > t...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . list_role_for_all_namespaces_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . list_role_for_all_namespaces_with_http_info ( ** kwargs ) # noqa : E501 return data
def send_signals ( self ) : """Shout for the world to hear whether a txn was successful ."""
if self . flag : invalid_ipn_received . send ( sender = self ) return else : valid_ipn_received . send ( sender = self )
def long_banner ( self ) : """Banner for IPython widgets with pylab message"""
# Default banner try : from IPython . core . usage import quick_guide except Exception : quick_guide = '' banner_parts = [ 'Python %s\n' % self . interpreter_versions [ 'python_version' ] , 'Type "copyright", "credits" or "license" for more information.\n\n' , 'IPython %s -- An enhanced Interactive Python.\n' %...
def _delete_file ( fileName , n = 10 ) : """Cleanly deletes a file in ` n ` attempts ( if necessary )"""
status = False count = 0 while not status and count < n : try : _os . remove ( fileName ) except OSError : count += 1 _time . sleep ( 0.2 ) else : status = True return status
def get_output_margin ( self , status = None ) : """Get the output margin ( number of rows for the prompt , footer and timing message ."""
margin = self . get_reserved_space ( ) + self . get_prompt ( self . prompt ) . count ( '\n' ) + 1 if special . is_timing_enabled ( ) : margin += 1 if status : margin += 1 + status . count ( '\n' ) return margin
def cursor ( belstr : str , ast : AST , cursor_loc : int , result : Mapping [ str , Any ] = None ) -> Mapping [ str , Any ] : """Find BEL function or argument at cursor location Args : belstr : BEL String used to create the completion _ text ast ( Mapping [ str , Any ] ) : AST ( dict ) of BEL String cursor ...
log . debug ( f"SubAST: {json.dumps(ast, indent=4)}" ) # Recurse down through subject , object , nested to functions log . debug ( f"Cursor keys {ast.keys()}, BELStr: {belstr}" ) if len ( belstr ) == 0 : return { "type" : "Function" , "replace_span" : ( 0 , 0 ) , "completion_text" : "" } if "relation" in ast and in...
def _parse_table ( self ) : """Parse a wikicode table by starting with the first line ."""
reset = self . _head self . _head += 2 try : self . _push ( contexts . TABLE_OPEN ) padding = self . _handle_table_style ( "\n" ) except BadRoute : self . _head = reset self . _emit_text ( "{" ) return style = self . _pop ( ) self . _head += 1 restore_point = self . _stack_ident try : table = se...
def write_function_dockercall ( self , job ) : '''Writes a string containing the apiDockerCall ( ) that will run the job . : param job _ task _ reference : The name of the job calling docker . : param docker _ image : The corresponding name of the docker image . e . g . " ubuntu : latest " : return : A stri...
docker_dict = { "docker_image" : self . tasks_dictionary [ job ] [ 'runtime' ] [ 'docker' ] , "job_task_reference" : job , "docker_user" : str ( self . docker_user ) } docker_template = heredoc_wdl ( ''' stdout = apiDockerCall(self, image={docker_image}, ...
def t_BIN ( self , t ) : r'( % [ 01 ] + ) | ( [ 01 ] + [ bB ] )'
# A Binary integer # Note 00B is a 0 binary , but # 00Bh is a 12 in hex . So this pattern must come # after HEXA if t . value [ 0 ] == '%' : t . value = t . value [ 1 : ] # Remove initial % else : t . value = t . value [ : - 1 ] # Remove last ' b ' t . value = int ( t . value , 2 ) # Convert to decimal t . ...
def get_child_at ( self , x , y , bAllowTransparency = True ) : """Get the child window located at the given coordinates . If no such window exists an exception is raised . @ see : L { get _ children } @ type x : int @ param x : Horizontal coordinate . @ type y : int @ param y : Vertical coordinate . ...
try : if bAllowTransparency : hWnd = win32 . RealChildWindowFromPoint ( self . get_handle ( ) , ( x , y ) ) else : hWnd = win32 . ChildWindowFromPoint ( self . get_handle ( ) , ( x , y ) ) if hWnd : return self . __get_window ( hWnd ) except WindowsError : pass return None
def _prep_acl_for_compare ( ACL ) : '''Prepares the ACL returned from the AWS API for comparison with a given one .'''
ret = copy . deepcopy ( ACL ) ret [ 'Owner' ] = _normalize_user ( ret [ 'Owner' ] ) for item in ret . get ( 'Grants' , ( ) ) : item [ 'Grantee' ] = _normalize_user ( item . get ( 'Grantee' ) ) return ret
def interact ( self , msg = 'SHUTIT PAUSE POINT' , shutit_pexpect_child = None , print_input = True , level = 1 , resize = True , color = '32' , default_msg = None , wait = - 1 ) : """Same as pause _ point , but sets up the terminal ready for unmediated interaction ."""
shutit_global . shutit_global_object . yield_to_draw ( ) self . pause_point ( msg = msg , shutit_pexpect_child = shutit_pexpect_child , print_input = print_input , level = level , resize = resize , color = color , default_msg = default_msg , interact = True , wait = wait )
def read_ipv6_frag ( self , length , extension ) : """Read Fragment Header for IPv6. Structure of IPv6 - Frag header [ RFC 8200 ] : | Next Header | Reserved | Fragment Offset | Res | M | | Identification | Octets Bits Name Description 0 0 frag . next Next Header 1 8 - Reserved 2 16 frag . offset Fragm...
if length is None : length = len ( self ) _next = self . _read_protos ( 1 ) _temp = self . _read_fileng ( 1 ) _offm = self . _read_binary ( 2 ) _ipid = self . _read_unpack ( 4 ) ipv6_frag = dict ( next = _next , length = 8 , offset = int ( _offm [ : 13 ] , base = 2 ) , mf = True if int ( _offm [ 15 ] , base = 2 ) e...
def retrieve ( self , id ) : """Retrieve a single source Returns a single source available to the user by the provided id If a source with the supplied unique identifier does not exist it returns an error : calls : ` ` get / deal _ sources / { id } ` ` : param int id : Unique identifier of a DealSource . ...
_ , _ , deal_source = self . http_client . get ( "/deal_sources/{id}" . format ( id = id ) ) return deal_source
def _reformat_low ( self , low ) : '''Format the low data for RunnerClient ( ) ' s master _ call ( ) function This also normalizes the following low data formats to a single , common low data structure . Old - style low : ` ` { ' fun ' : ' jobs . lookup _ jid ' , ' jid ' : ' 1234 ' } ` ` New - style : ` ` {...
fun = low . pop ( 'fun' ) verify_fun ( self . functions , fun ) eauth_creds = dict ( [ ( i , low . pop ( i ) ) for i in [ 'username' , 'password' , 'eauth' , 'token' , 'client' , 'user' , 'key' , ] if i in low ] ) # Run name = value args through parse _ input . We don ' t need to run kwargs # through because there is n...
def device_statistics ( fritz , args ) : """Command that prints the device statistics ."""
stats = fritz . get_device_statistics ( args . ain ) print ( stats )
def element_css_attribute_should_be ( self , locator , prop , expected ) : """Verifies the element identified by ` locator ` has the expected value for the targeted ` prop ` . | * Argument * | * Description * | * Example * | | locator | Selenium 2 element locator | id = my _ id | | prop | targeted css attri...
self . _info ( "Verifying element '%s' has css attribute '%s' with a value of '%s'" % ( locator , prop , expected ) ) self . _check_element_css_value ( locator , prop , expected )
def defvalkey ( js , key , default = None , take_none = True ) : """Returns js [ key ] if set , otherwise default . Note js [ key ] can be None . : param js : : param key : : param default : : param take _ none : : return :"""
if js is None : return default if key not in js : return default if js [ key ] is None and not take_none : return default return js [ key ]
def rsi ( arg , n ) : """compute RSI for the given arg arg : Series or DataFrame"""
if isinstance ( arg , pd . DataFrame ) : cols = [ ( name , rsi ( arg [ name ] , n ) ) for name in arg . columns ] return pd . DataFrame . from_items ( cols ) else : assert isinstance ( arg , pd . Series ) n = int ( n ) converted = arg . dropna ( ) change = converted . diff ( ) gain = change ...
def get_loss_func ( self , C = 1.0 , k = 1 ) : """Get loss function of VAE . The loss value is equal to ELBO ( Evidence Lower Bound ) multiplied by - 1. Args : C ( int ) : Usually this is 1.0 . Can be changed to control the second term of ELBO bound , which works as regularization . k ( int ) : Number o...
def lf ( x ) : mu , ln_var = self . encode ( x ) batchsize = len ( mu . data ) # reconstruction loss rec_loss = 0 for l in six . moves . range ( k ) : z = F . gaussian ( mu , ln_var ) rec_loss += F . bernoulli_nll ( x , self . decode ( z , sigmoid = False ) ) / ( k * batchsize ) ...
def get_mime_representation ( self ) : """returns mime part that constitutes this attachment"""
part = deepcopy ( self . part ) part . set_param ( 'maxlinelen' , '78' , header = 'Content-Disposition' ) return part
def from_vizier_table ( cls , table_id , nside = 256 ) : """Creates a ` ~ mocpy . moc . MOC ` object from a VizieR table . * * Info * * : This method is already implemented in ` astroquery . cds < https : / / astroquery . readthedocs . io / en / latest / cds / cds . html > ` _ _ . You can ask to get a ` mocpy . m...
nside_possible_values = ( 8 , 16 , 32 , 64 , 128 , 256 , 512 ) if nside not in nside_possible_values : raise ValueError ( 'Bad value for nside. Must be in {0}' . format ( nside_possible_values ) ) result = cls . from_ivorn ( 'ivo://CDS/' + table_id , nside ) return result
def _is_dir ( self , f ) : '''Check if the given in - dap file is a directory'''
return self . _tar . getmember ( f ) . type == tarfile . DIRTYPE
def get_related ( self , instance , number ) : """Implement high level cache system for get _ related ."""
cache = self . cache cache_key = '%s:%s' % ( instance . pk , number ) if cache_key not in cache : related_objects = super ( CachedModelVectorBuilder , self ) . get_related ( instance , number ) cache [ cache_key ] = related_objects self . cache = cache return cache [ cache_key ]
def documents ( self , key , value ) : """Populate the ` ` documents ` ` key . Also populates the ` ` figures ` ` key through side effects ."""
def _is_hidden ( value ) : return 'HIDDEN' in [ val . upper ( ) for val in value ] or None def _is_figure ( value ) : figures_extensions = [ '.png' ] return value . get ( 'f' ) in figures_extensions def _is_fulltext ( value ) : return value . get ( 'd' , '' ) . lower ( ) == 'fulltext' or None def _get_i...
def join_cluster ( host , user = 'rabbit' , ram_node = None , runas = None ) : '''Join a rabbit cluster CLI Example : . . code - block : : bash salt ' * ' rabbitmq . join _ cluster rabbit . example . com rabbit'''
cmd = [ RABBITMQCTL , 'join_cluster' ] if ram_node : cmd . append ( '--ram' ) cmd . append ( '{0}@{1}' . format ( user , host ) ) if runas is None and not salt . utils . platform . is_windows ( ) : runas = salt . utils . user . get_user ( ) stop_app ( runas ) res = __salt__ [ 'cmd.run_all' ] ( cmd , reset_syste...
def deep_force_unicode ( value ) : """Recursively call force _ text on value ."""
if isinstance ( value , ( list , tuple , set ) ) : value = type ( value ) ( map ( deep_force_unicode , value ) ) elif isinstance ( value , dict ) : value = type ( value ) ( map ( deep_force_unicode , value . items ( ) ) ) elif isinstance ( value , Promise ) : value = force_text ( value ) return value
def _query ( self , method , path , data = None , page = False , retry = 0 ) : """Fetch an object from the Graph API and parse the output , returning a tuple where the first item is the object yielded by the Graph API and the second is the URL for the next page of results , or ` ` None ` ` if results have been ...
if ( data ) : data = dict ( ( k . replace ( '_sqbro_' , '[' ) , v ) for k , v in data . items ( ) ) data = dict ( ( k . replace ( '_sqbrc_' , ']' ) , v ) for k , v in data . items ( ) ) data = dict ( ( k . replace ( '__' , ':' ) , v ) for k , v in data . items ( ) ) data = data or { } def load ( method , ur...
def jsonxs ( data , expr , action = ACTION_GET , value = None , default = None ) : """Get , set , delete values in a JSON structure . ` expr ` is a JSONpath - like expression pointing to the desired value . ` action ` determines the action to perform . See the module - level ` ACTION _ * ` constants . ` value `...
tokens = tokenize ( expr ) # Walk through the list of tokens to reach the correct path in the data # structure . try : prev_path = None cur_path = data for token in tokens : prev_path = cur_path if not token in cur_path and action in [ ACTION_SET , ACTION_MKDICT , ACTION_MKLIST ] : # When se...
def inspect_secret ( self , id ) : """Retrieve secret metadata Args : id ( string ) : Full ID of the secret to remove Returns ( dict ) : A dictionary of metadata Raises : : py : class : ` docker . errors . NotFound ` if no secret with that ID exists"""
url = self . _url ( '/secrets/{0}' , id ) return self . _result ( self . _get ( url ) , True )
def insert_order ( self , order ) : ''': param order : QA _ Order类型 : return :'''
# print ( " * > > QAOrder ! insert _ order { } " . format ( order ) ) # QUEUED = 300 # queued 用于表示在order _ queue中 实际表达的意思是订单存活 待成交 # order . status = ORDER _ STATUS . QUEUED # 🛠 todo 是为了速度快把order对象转换成 df 对象的吗 ? # self . queue _ df = self . queue _ df . append ( order . to _ df ( ) , ignore _ index = True ) # self . qu...
def make_file_path ( project_dir , project_name , root , name ) : """Generates the target path for a file"""
return path . join ( make_dir_path ( project_dir , root , project_name ) , name )
def run ( self ) : '''Run loop'''
logger . info ( "fetcher starting..." ) def queue_loop ( ) : if not self . outqueue or not self . inqueue : return while not self . _quit : try : if self . outqueue . full ( ) : break if self . http_client . free_size ( ) <= 0 : break ...
def merge_range_pairs ( prs ) : '''Takes in a list of pairs specifying ranges and returns a sorted list of merged , sorted ranges .'''
new_prs = [ ] sprs = [ sorted ( p ) for p in prs ] sprs = sorted ( sprs ) merged = False x = 0 while x < len ( sprs ) : newx = x + 1 new_pair = list ( sprs [ x ] ) for y in range ( x + 1 , len ( sprs ) ) : if new_pair [ 0 ] <= sprs [ y ] [ 0 ] - 1 <= new_pair [ 1 ] : new_pair [ 0 ] = min...
def read ( file , frames = - 1 , start = 0 , stop = None , dtype = 'float64' , always_2d = False , fill_value = None , out = None , samplerate = None , channels = None , format = None , subtype = None , endian = None , closefd = True ) : """Provide audio data from a sound file as NumPy array . By default , the wh...
with SoundFile ( file , 'r' , samplerate , channels , subtype , endian , format , closefd ) as f : frames = f . _prepare_read ( start , stop , frames ) data = f . read ( frames , dtype , always_2d , fill_value , out ) return data , f . samplerate
def rename ( self , new_name ) : """Rename the container . On success , returns the new Container object . On failure , returns False ."""
if _lxc . Container . rename ( self , new_name ) : return Container ( new_name ) return False
def add_leaf ( self , value , do_hash = False ) : """Add a leaf to the tree . : param value : hash value ( as a Buffer ) or hex string : param do _ hash : whether to hash value"""
self . tree [ 'is_ready' ] = False self . _add_leaf ( value , do_hash )
def as_artist ( self , origin = ( 0 , 0 ) , ** kwargs ) : """Matplotlib patch object for this region ( ` matplotlib . patches . Ellipse ` ) . Parameters : origin : array _ like , optional The ` ` ( x , y ) ` ` pixel position of the origin of the displayed image . Default is ( 0 , 0 ) . kwargs : ` dict ` ...
from matplotlib . patches import Ellipse xy = self . center . x - origin [ 0 ] , self . center . y - origin [ 1 ] width = self . width height = self . height # From the docstring : MPL expects " rotation in degrees ( anti - clockwise ) " angle = self . angle . to ( 'deg' ) . value mpl_params = self . mpl_properties_def...
def get_pca_ks_stats ( self , maxrange = 5 ) : """Get a dictionary of PC # : K - S test stat for each"""
pc_to_phenotype_pairs = { } num_components = self . principal_observations_df . shape [ 1 ] if num_components < maxrange : maxrange = num_components phenotypes = self . principal_observations_df . phenotype . unique ( ) . tolist ( ) for i in range ( 0 , maxrange ) : phenotype_pair_to_ks = { } for p1 , p2 in...
def findpk2 ( self , r1 , s1 , r2 , s2 , flag1 , flag2 ) : """find pubkey Y from 2 different signature on the same message sigs : ( r1 , s1 ) and ( r2 , s2) returns ( R1 * s1 - R2 * s2 ) / ( r1 - r2)"""
R1 = self . ec . decompress ( r1 , flag1 ) R2 = self . ec . decompress ( r2 , flag2 ) rdiff = self . GFn . value ( r1 - r2 ) return ( R1 * s1 - R2 * s2 ) * ( 1 / rdiff )
def start ( self ) : """Start a thread that consumes the messages and invokes the callback"""
t = threading . Thread ( target = self . _consume ) t . start ( )
def terrain_request_encode ( self , lat , lon , grid_spacing , mask ) : '''Request for terrain data and terrain status lat : Latitude of SW corner of first grid ( degrees * 10 ^ 7 ) ( int32 _ t ) lon : Longitude of SW corner of first grid ( in degrees * 10 ^ 7 ) ( int32 _ t ) grid _ spacing : Grid spacing in ...
return MAVLink_terrain_request_message ( lat , lon , grid_spacing , mask )
def filter ( n : Node , query : str ) -> CompatNodeIterator : """This function has the same signature as the pre - v3 filter ( ) returning a compatibility CompatNodeIterator ."""
ctx = uast ( ) return CompatNodeIterator ( NodeIterator ( ctx . filter ( query , n . internal_node ) , ctx ) )
def status ( logfile , time_format ) : "show current status"
try : r = read ( logfile , time_format ) [ - 1 ] if r [ 1 ] [ 1 ] : return summary ( logfile , time_format ) else : print "working on %s" % colored ( r [ 0 ] , attrs = [ 'bold' ] ) print " since %s" % colored ( server . date_to_txt ( r [ 1 ] [ 0 ] , time_format ) , 'green' ) ...
def params ( self ) : """Parameters used in the url of the API call and for authentication . : return : parameters used in the url . : rtype : dict"""
params = { } params [ "access_token" ] = self . access_token params [ "account_id" ] = self . account_id return params
def encompass ( self ) : """Called when parallelize is False . This function will generate the file names in a directory tree by walking the tree either top - down or bottom - up . For each directory in the tree rooted at directory top ( including top itself ) , it yields a 3 - tuple ( dirpath , dirnames , fi...
self . _printer ( 'Standard Walk' ) count = Counter ( length = 3 ) for directory in self . directory : for root , directories , files in os . walk ( directory , topdown = self . topdown ) : root = root [ len ( str ( directory ) ) + 1 : ] self . _printer ( str ( count . up ) + ": Explored path - " + ...
def pid_tuning_send ( self , axis , desired , achieved , FF , P , I , D , force_mavlink1 = False ) : '''PID tuning information axis : axis ( uint8 _ t ) desired : desired rate ( degrees / s ) ( float ) achieved : achieved rate ( degrees / s ) ( float ) FF : FF component ( float ) P : P component ( float )...
return self . send ( self . pid_tuning_encode ( axis , desired , achieved , FF , P , I , D ) , force_mavlink1 = force_mavlink1 )
def _jseq ( self , cols , converter = None ) : """Return a JVM Seq of Columns from a list of Column or names"""
return _to_seq ( self . sql_ctx . _sc , cols , converter )
def plot_dom_parameters ( data , detector , filename , label , title , vmin = 0.0 , vmax = 10.0 , cmap = 'RdYlGn_r' , under = 'deepskyblue' , over = 'deeppink' , underfactor = 1.0 , overfactor = 1.0 , missing = 'lightgray' , hide_limits = False ) : """Creates a plot in the classical monitoring . km3net . de style ....
x , y , _ = zip ( * detector . doms . values ( ) ) fig , ax = plt . subplots ( figsize = ( 10 , 6 ) ) cmap = plt . get_cmap ( cmap ) cmap . set_over ( over , 1.0 ) cmap . set_under ( under , 1.0 ) m_size = 100 scatter_args = { 'edgecolors' : 'None' , 'vmin' : vmin , 'vmax' : vmax , } sc_inactive = ax . scatter ( x , y ...
def resolve ( self , requirement_set ) : # type : ( RequirementSet ) - > None """Resolve what operations need to be done As a side - effect of this method , the packages ( and their dependencies ) are downloaded , unpacked and prepared for installation . This preparation is done by ` ` pip . operations . prep...
# make the wheelhouse if self . preparer . wheel_download_dir : ensure_dir ( self . preparer . wheel_download_dir ) # If any top - level requirement has a hash specified , enter # hash - checking mode , which requires hashes from all . root_reqs = ( requirement_set . unnamed_requirements + list ( requirement_set . ...
def expect_element ( __funcname = _qualified_name , ** named ) : """Preprocessing decorator that verifies inputs are elements of some expected collection . Examples > > > @ expect _ element ( x = ( ' a ' , ' b ' ) ) . . . def foo ( x ) : . . . return x . upper ( ) > > > foo ( ' a ' ) > > > foo ( ' b '...
def _expect_element ( collection ) : if isinstance ( collection , ( set , frozenset ) ) : # Special case the error message for set and frozen set to make it # less verbose . collection_for_error_message = tuple ( sorted ( collection ) ) else : collection_for_error_message = collection te...
def git_ls_files ( filename ) : """Return a boolean value for whether the given file is tracked by git ."""
with chdir ( get_root ( ) ) : # https : / / stackoverflow . com / a / 2406813 result = run_command ( 'git ls-files --error-unmatch {}' . format ( filename ) , capture = True ) return result . code == 0
def get_all_suppliers ( self , params = None ) : """Get all suppliers This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing : param params : search params : return : list"""
if not params : params = { } return self . _iterate_through_pages ( get_function = self . get_suppliers_per_page , resource = SUPPLIERS , ** { 'params' : params } )
def thread_started ( self ) : """Start polling for a stop event or ready event and do small work via : meth : ` . WPollingThreadTask . _ polling _ iteration ` method call : return : None"""
while self . check_events ( ) is False : self . _polling_iteration ( ) self . stop_event ( ) . wait ( self . polling_timeout ( ) )
def post_install_package ( ) : """Run any functions post install a matching package . Hook functions are in the form post _ install _ [ package name ] and are defined in a deploy . py file Will be executed post install _ packages and upload _ etc"""
module_name = '.' . join ( [ env . project_package_name , 'deploy' ] ) funcs_run = [ ] try : imported = import_module ( module_name ) funcs = vars ( imported ) for f in env . installed_packages [ env . host ] : func = funcs . get ( '' . join ( [ 'post_install_' , f . replace ( '.' , '_' ) . replace ...
def add_raw_code ( self , string_or_list ) : """Add raw Gmsh code ."""
if _is_string ( string_or_list ) : self . _GMSH_CODE . append ( string_or_list ) else : assert isinstance ( string_or_list , list ) for string in string_or_list : self . _GMSH_CODE . append ( string ) return
def all ( self ) : """Return the results represented by this Query as a list . . . versionchanged : : 0.10.0 Returns an iterator that lazily loads records instead of fetching thousands of records at once ."""
return self . rpc_model . search_read_all ( self . domain , self . _order_by , self . fields , context = self . context , offset = self . _offset or 0 , limit = self . _limit , )
def SLICE ( array , n , position = None ) : """Returns a subset of an array . See https : / / docs . mongodb . com / manual / reference / operator / aggregation / slice / for more details : param array : Any valid expression as long as it resolves to an array . : param n : Any valid expression as long as it...
return { '$slice' : [ array , position , n ] } if position is not None else { '$slice' : [ array , n ] }
def deci2sexa ( deci , pre = 3 , trunc = False , lower = None , upper = None , b = False , upper_trim = False ) : """Returns the sexagesimal representation of a decimal number . Parameters deci : float Decimal number to be converted into sexagesimal . If ` lower ` and ` upper ` are given then the number is ...
if lower is not None and upper is not None : deci = normalize ( deci , lower = lower , upper = upper , b = b ) sign = 1 if deci < 0 : deci = abs ( deci ) sign = - 1 hd , f1 = divmod ( deci , 1 ) mm , f2 = divmod ( f1 * 60.0 , 1 ) sf = f2 * 60.0 # Find the seconds part to required precision . fp = 10 ** pre ...
def describe_addresses ( self , xml_bytes ) : """Parse the XML returned by the C { DescribeAddresses } function . @ param xml _ bytes : XML bytes with a C { DescribeAddressesResponse } root element . @ return : a C { list } of L { tuple } of ( publicIp , instancId ) ."""
results = [ ] root = XML ( xml_bytes ) for address_data in root . find ( "addressesSet" ) : address = address_data . findtext ( "publicIp" ) instance_id = address_data . findtext ( "instanceId" ) results . append ( ( address , instance_id ) ) return results
def sys_get_current_resolution ( ) -> Tuple [ int , int ] : """Return the current resolution as ( width , height ) Returns : Tuple [ int , int ] : The current resolution ."""
w = ffi . new ( "int *" ) h = ffi . new ( "int *" ) lib . TCOD_sys_get_current_resolution ( w , h ) return w [ 0 ] , h [ 0 ]
def get_smart_contract ( self , hex_contract_address : str , is_full : bool = False ) -> dict : """This interface is used to get the information of smart contract based on the specified hexadecimal hash value . : param hex _ contract _ address : str , a hexadecimal hash value . : param is _ full : : return : ...
if not isinstance ( hex_contract_address , str ) : raise SDKException ( ErrorCode . param_err ( 'a hexadecimal contract address is required.' ) ) if len ( hex_contract_address ) != 40 : raise SDKException ( ErrorCode . param_err ( 'the length of the contract address should be 40 bytes.' ) ) payload = self . gen...
def getTempDirectory ( rootDir = None ) : """returns a temporary directory that must be manually deleted . rootDir will be created if it does not exist ."""
if rootDir is None : return tempfile . mkdtemp ( ) else : if not os . path . exists ( rootDir ) : try : os . makedirs ( rootDir ) except OSError : # Maybe it got created between the test and the makedirs call ? pass while True : # Keep trying names until we find one t...
def _thumbnail_div ( target_dir , src_dir , fname , snippet , is_backref = False , check = True ) : """Generates RST to place a thumbnail in a gallery"""
thumb , _ = _find_image_ext ( os . path . join ( target_dir , 'images' , 'thumb' , 'sphx_glr_%s_thumb.png' % fname [ : - 3 ] ) ) if check and not os . path . isfile ( thumb ) : # This means we have done something wrong in creating our thumbnail ! raise RuntimeError ( 'Could not find internal sphinx-gallery thumbnai...
def updateReplicationMetadata ( self , pid , replicaMetadata , serialVersion , vendorSpecific = None ) : """See Also : updateReplicationMetadataResponse ( ) Args : pid : replicaMetadata : serialVersion : vendorSpecific : Returns :"""
response = self . updateReplicationMetadataResponse ( pid , replicaMetadata , serialVersion , vendorSpecific ) return self . _read_boolean_response ( response )
def get_one ( self , section , key ) : """Retrieve the first value for a section / key . Raises : KeyError : If no line match the given section / key ."""
lines = iter ( self . get ( section , key ) ) try : return next ( lines ) except StopIteration : raise KeyError ( "Key %s not found in %s" % ( key , section ) )
def lookup ( self , key , name ) : """Look for values in registry in Microsoft software registry . Parameters key : str Registry key path where look . name : str Value name to find . Return str : value"""
KEY_READ = winreg . KEY_READ openkey = winreg . OpenKey ms = self . microsoft for hkey in self . HKEYS : try : bkey = openkey ( hkey , ms ( key ) , 0 , KEY_READ ) except ( OSError , IOError ) : if not self . pi . current_is_x86 ( ) : try : bkey = openkey ( hkey , ms (...
def max ( self ) : """Return the maximum element or ( element - based computation ) ."""
if ( self . _clean . isDict ( ) ) : return self . _wrap ( list ( ) ) return self . _wrap ( max ( self . obj ) )
def cas ( self , key , value , * , flags = None , index ) : """Sets the Key to the given Value with check - and - set semantics Parameters : key ( str ) : Key to set value ( Payload ) : Value to set , It will be encoded by flags index ( ObjectIndex ) : Index ID flags ( int ) : Flags to set with value Th...
self . append ( { "Verb" : "cas" , "Key" : key , "Value" : encode_value ( value , flags , base64 = True ) . decode ( "utf-8" ) , "Flags" : flags , "Index" : extract_attr ( index , keys = [ "ModifyIndex" , "Index" ] ) } ) return self
def _error_msg_iface ( iface , option , expected ) : '''Build an appropriate error message from a given option and a list of expected values .'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]' return msg . format ( iface , option , '|' . join ( str ( e ) for e in expected ) )
def install_theme ( theme = None , monofont = None , monosize = 11 , nbfont = None , nbfontsize = 13 , tcfont = None , tcfontsize = 13 , dffontsize = 93 , outfontsize = 85 , mathfontsize = 100 , margins = 'auto' , cellwidth = '980' , lineheight = 170 , cursorwidth = 2 , cursorcolor = 'default' , altprompt = False , alt...
# get working directory wkdir = os . path . abspath ( './' ) stylefx . reset_default ( False ) stylefx . check_directories ( ) doc = '\nConcatenated font imports, .less styles, & custom variables\n' s = '*' * 65 style_less = '\n' . join ( [ '/*' , s , s , doc , s , s , '*/' ] ) style_less += '\n\n\n' style_less += '/* ...
def get_or_add_tx_rich ( self ) : """Return the ` c : tx [ c : rich ] ` subtree , newly created if not present ."""
tx = self . get_or_add_tx ( ) tx . _remove_strRef ( ) tx . get_or_add_rich ( ) return tx
def get_magic_info ( self , child_type , parent_type = None , attr = 'er' , filename = None , sort_by_file_type = False ) : """Read er _ * . txt or pmag _ * . txt file . If no filename is provided , use er _ * or pmag _ * file in WD . If sort _ by _ file _ type , use file header to determine child , parent type...
parent = '' grandparent_type = None magic_name = 'er_' + child_type + '_name' expected_item_type = child_type if not filename : short_filename = attr + '_' + child_type + 's.txt' magic_file = os . path . join ( self . WD , short_filename ) else : short_filename = os . path . split ( filename ) [ 1 ] mag...
def get_object ( table , id = None , condition = None , cache = False , fields = None , use_local = False , engine_name = None , session = None ) : """Get obj in Local . object _ caches first and also use get ( cache = True ) function if not found in object _ caches"""
from uliweb import functions , settings model = get_model ( table , engine_name ) # if id is an object of Model , so get the real id value if isinstance ( id , Model ) : return id if cache : if use_local : s = get_session ( session ) key = get_object_id ( s . engine_name , model . tablename , id...
def enabled ( name ) : '''Ensure an Apache conf is enabled . name Name of the Apache conf'''
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } is_enabled = __salt__ [ 'apache.check_conf_enabled' ] ( name ) if not is_enabled : if __opts__ [ 'test' ] : msg = 'Apache conf {0} is set to be enabled.' . format ( name ) ret [ 'comment' ] = msg ret [ 'changes' ] [...
def _dpi ( self , density ) : """Return dots per inch corresponding to * density * value ."""
if self . _density_units == 1 : dpi = density elif self . _density_units == 2 : dpi = int ( round ( density * 2.54 ) ) else : dpi = 72 return dpi
def seek ( self , pos ) : """Move to new input file position . If position is negative or out of file , raise Exception ."""
if ( pos > self . file_size ) or ( pos < 0 ) : raise Exception ( "Unable to seek - position out of file!" ) self . file . seek ( pos )
def get_all ( self , start = 0 , count = - 1 , filter = '' , fields = '' , query = '' , sort = '' , view = '' ) : """Gets a list of Deployment Servers based on optional sorting and filtering , and constrained by start and count parameters . Args : start : The first item to return , using 0 - based indexing ...
return self . _client . get_all ( start , count , filter = filter , sort = sort , query = query , fields = fields , view = view )
def store ( self , key , value ) : """Add new record to cache key : entry key value : data of entry"""
self . client . set ( key , value , time = self . timeout )
def add_dynamics_2 ( self , component , runnable , regime , dynamics ) : """Adds dynamics to a runnable component based on the dynamics specifications in the component model . This method builds dynamics dependent on child components . @ param component : Component model containing dynamics specifications . ...
if isinstance ( regime , Dynamics ) or regime . name == '' : suffix = '' else : suffix = '_regime_' + regime . name # Process kinetic schemes ks_code = [ ] for ks in regime . kinetic_schemes : raise NotImplementedError ( "KineticScheme element is not stable in PyLEMS yet, see https://github.com/LEMS/pylems/...
def run ( self ) : """主函数"""
# try : self . fenum . write ( '\n' ) self . fcpp = open ( os . path . join ( os . path . abspath ( self . ctp_dir ) , 'ThostFtdcUserApiDataType.h' ) , 'r' ) for idx , line in enumerate ( self . fcpp ) : l = self . process_line ( idx , line ) self . f_data_type . write ( l ) self . fcpp . close ( ) self . f_dat...