signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _zforce ( self , R , z , phi = 0. , t = 0. ) : """NAME : zforce PURPOSE : evaluate vertical force K _ z ( R , z ) INPUT : R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT : K _ z ( R , z ) HISTORY : 2012-12-27 - Written - Bovy ( IAS )"""
if self . _new : # if R > 6 . : return self . _ kp ( R , z ) if nu . fabs ( z ) < 10. ** - 6. : return 0. kalphamax1 = R ks1 = kalphamax1 * 0.5 * ( self . _glx + 1. ) weights1 = kalphamax1 * self . _glw sqrtp = nu . sqrt ( z ** 2. + ( ks1 + R ) ** 2. ) sqrtm = nu . sqrt ( z ** 2. + ( ks1...
def list ( self , * args , ** kwargs ) : """List networks . Similar to the ` ` docker networks ls ` ` command . Args : names ( : py : class : ` list ` ) : List of names to filter by . ids ( : py : class : ` list ` ) : List of ids to filter by . filters ( dict ) : Filters to be processed on the network list ...
greedy = kwargs . pop ( 'greedy' , False ) resp = self . client . api . networks ( * args , ** kwargs ) networks = [ self . prepare_model ( item ) for item in resp ] if greedy and version_gte ( self . client . api . _version , '1.28' ) : for net in networks : net . reload ( ) return networks
def generate_host_passthrough ( self , vcpu_num ) : """Generate host - passthrough XML cpu node Args : vcpu _ num ( str ) : number of virtual CPUs Returns : lxml . etree . Element : CPU XML node"""
cpu = ET . Element ( 'cpu' , mode = 'host-passthrough' ) cpu . append ( self . generate_topology ( vcpu_num ) ) if vcpu_num > 1 : cpu . append ( self . generate_numa ( vcpu_num ) ) return cpu
def ExamineEvent ( self , mediator , event ) : """Analyzes an event and creates Windows Services as required . At present , this method only handles events extracted from the Registry . Args : mediator ( AnalysisMediator ) : mediates interactions between analysis plugins and other components , such as stora...
# TODO : Handle event log entries here also ( ie , event id 4697 ) . event_data_type = getattr ( event , 'data_type' , '' ) if event_data_type == 'windows:registry:service' : # Create and store the service . service = WindowsService . FromEvent ( event ) self . _service_collection . AddService ( service )
def pipe_numberinput ( context = None , _INPUT = None , conf = None , ** kwargs ) : """An input that prompts the user for a number and yields it forever . Not loopable . Parameters context : pipe2py . Context object _ INPUT : not used conf : { ' name ' : { ' value ' : ' parameter name ' } , ' prompt '...
value = utils . get_input ( context , conf ) try : value = int ( value ) except : value = 0 while True : yield value
def superscript ( self ) : """| True | if ` w : vertAlign / @ w : val ` is ' superscript ' . | False | if ` w : vertAlign / @ w : val ` contains any other value . | None | if ` w : vertAlign ` is not present ."""
vertAlign = self . vertAlign if vertAlign is None : return None if vertAlign . val == ST_VerticalAlignRun . SUPERSCRIPT : return True return False
def from_array ( array ) : """Deserialize a new EncryptedPassportElement from a given dictionary . : return : new EncryptedPassportElement instance . : rtype : EncryptedPassportElement"""
if array is None or not array : return None # end if assert_type_or_raise ( array , dict , parameter_name = "array" ) from pytgbot . api_types . receivable . passport import PassportFile data = { } data [ 'type' ] = u ( array . get ( 'type' ) ) data [ 'hash' ] = u ( array . get ( 'hash' ) ) data [ 'data' ] = u ( ar...
def wrapped_request ( self , request , * args , ** kwargs ) : """Create and send a request to the server . This method implements a very small subset of the options possible to send an request . It is provided as a shortcut to sending a simple wrapped request . Parameters request : str The request to ca...
f = tornado_Future ( ) try : use_mid = kwargs . get ( 'use_mid' ) timeout = kwargs . get ( 'timeout' ) mid = kwargs . get ( 'mid' ) msg = Message . request ( request , * args , mid = mid ) except Exception : f . set_exc_info ( sys . exc_info ( ) ) return f return transform_future ( self . reply_...
def to_dict ( self ) : '''Save this wait _ time condition into a dictionary .'''
d = super ( WaitTime , self ) . to_dict ( ) d [ 'condition' ] = { 'waitTime' : { 'waitTime' : self . wait_time } } return d
def remove_out_of_bounds_bins ( df , chromosome_size ) : # type : ( pd . DataFrame , int ) - > pd . DataFrame """Remove all reads that were shifted outside of the genome endpoints ."""
# The dataframe is empty and contains no bins out of bounds if "Bin" not in df : return df df = df . drop ( df [ df . Bin > chromosome_size ] . index ) return df . drop ( df [ df . Bin < 0 ] . index )
def reverse_query ( self ) : '''Changes the coordinates as if the query sequence has been reverse complemented'''
self . qry_start = self . qry_length - self . qry_start - 1 self . qry_end = self . qry_length - self . qry_end - 1
def to_si ( self , values , from_unit ) : """Return values in SI and the units to which the values have been converted ."""
if from_unit in self . si_units : return values , from_unit elif from_unit == 'ton' : return self . to_unit ( values , 'tonne' , from_unit ) , 'tonne' else : return self . to_unit ( values , 'kg' , from_unit ) , 'kg'
def create_selection ( ) : """Create a selection expression"""
operation = Forward ( ) nested = Group ( Suppress ( "(" ) + operation + Suppress ( ")" ) ) . setResultsName ( "nested" ) select_expr = Forward ( ) functions = select_functions ( select_expr ) maybe_nested = functions | nested | Group ( var_val ) operation <<= maybe_nested + OneOrMore ( oneOf ( "+ - * /" ) + maybe_neste...
def sp_rand ( m , n , a ) : """Generates an mxn sparse ' d ' matrix with round ( a * m * n ) nonzeros ."""
if m == 0 or n == 0 : return spmatrix ( [ ] , [ ] , [ ] , ( m , n ) ) nnz = min ( max ( 0 , int ( round ( a * m * n ) ) ) , m * n ) nz = matrix ( random . sample ( range ( m * n ) , nnz ) , tc = 'i' ) return spmatrix ( normal ( nnz , 1 ) , nz % m , matrix ( [ int ( ii ) for ii in nz / m ] ) , ( m , n ) )
def init_UI ( self ) : """Set display variables ( font , resolution of GUI , sizer proportions ) then builds the Side bar panel , Top bar panel , and Plots scrolleing panel which are then placed placed together in a sizer and fit to the GUI wx . Frame"""
# Setup ScrolledPanel Ctrls - - - - - # set ctrl size and style variables dw , dh = wx . DisplaySize ( ) r1 = dw / 1210. r2 = dw / 640. self . GUI_RESOLUTION = min ( r1 , r2 , 1 ) top_bar_2v_space = 5 top_bar_h_space = 10 spec_button_space = 10 side_bar_v_space = 10 # set font size and style FONT_WEIGHT = 1 if sys . pl...
def league_scores ( self , total_data , time , show_upcoming , use_12_hour_format ) : """Store output of fixtures based on league and time to a CSV file"""
headers = [ 'League' , 'Home Team Name' , 'Home Team Goals' , 'Away Team Goals' , 'Away Team Name' ] result = [ headers ] league = total_data [ 'competition' ] [ 'name' ] result . extend ( [ league , score [ 'homeTeam' ] [ 'name' ] , score [ 'score' ] [ 'fullTime' ] [ 'homeTeam' ] , score [ 'score' ] [ 'fullTime' ] [ '...
def load_hdf ( cls , filename , path = '' ) : """Loads OrbitPopulation from HDF file . : param filename : HDF file : param path : Path within HDF file store where : class : ` OrbitPopulation ` is saved ."""
df = pd . read_hdf ( filename , '{}/df' . format ( path ) ) return cls . from_df ( df )
def is_univariate_ca ( self ) : """True if cube only contains a CA dimension - pair , in either order ."""
return self . ndim == 2 and set ( self . dim_types ) == { DT . CA_SUBVAR , DT . CA_CAT }
def on_assign ( self , node ) : # ( ' targets ' , ' value ' ) """Simple assignment ."""
val = self . run ( node . value ) for tnode in node . targets : self . node_assign ( tnode , val ) return
def discover_satellite ( cli , deploy = True , timeout = 5 ) : """Looks to make sure a satellite exists , returns endpoint First makes sure we have dotcloud account credentials . Then it looks up the environment for the satellite app . This will contain host and port to construct an endpoint . However , if ap...
if not cli . global_config . loaded : cli . die ( "Please setup skypipe by running `skypipe --setup`" ) try : endpoint = lookup_endpoint ( cli ) ok = client . check_skypipe_endpoint ( endpoint , timeout ) if ok : return endpoint else : return launch_satellite ( cli ) if deploy else N...
def __perform_unsolicited_callbacks ( self , msg ) : """Callbacks for which a client reference is either optional or does not apply at all"""
type_ = msg [ M_TYPE ] payload = msg [ M_PAYLOAD ] # callbacks for responses which might be unsolicited ( e . g . created or deleted ) if type_ in _RSP_PAYLOAD_CB_MAPPING : self . __fire_callback ( _RSP_PAYLOAD_CB_MAPPING [ type_ ] , msg ) # Perform callbacks for feed data elif type_ == E_FEEDDATA : self . __si...
def restore ( self ) : """Restore the main dataframe"""
if self . backup_df is None : self . warning ( "No dataframe is backed up: nothing restore" ) return self . df = self . backup_df self . ok ( "Dataframe is restored" )
def _set_pyqtgraph_title ( layout ) : """Private function to add a title to the first row of the window . Returns True if a Title is set . Else , returns False ."""
if 'title_size' in pytplot . tplot_opt_glob : size = pytplot . tplot_opt_glob [ 'title_size' ] if 'title_text' in pytplot . tplot_opt_glob : if pytplot . tplot_opt_glob [ 'title_text' ] != '' : layout . addItem ( LabelItem ( pytplot . tplot_opt_glob [ 'title_text' ] , size = size , color = 'k' ) , row =...
def _example_order_book ( quote_ctx ) : """获取摆盘数据 , 输出 买价 , 买量 , 买盘经纪个数 , 卖价 , 卖量 , 卖盘经纪个数"""
stock_code_list = [ "US.AAPL" , "HK.00700" ] # subscribe " ORDER _ BOOK " ret_status , ret_data = quote_ctx . subscribe ( stock_code_list , ft . SubType . ORDER_BOOK ) if ret_status != ft . RET_OK : print ( ret_data ) exit ( ) for stk_code in stock_code_list : ret_status , ret_data = quote_ctx . get_order_b...
def _outfp_write_with_check ( self , outfp , data , enable_overwrite_check = True ) : # type : ( BinaryIO , bytes , bool ) - > None '''Internal method to write data out to the output file descriptor , ensuring that it doesn ' t go beyond the bounds of the ISO . Parameters : outfp - The file object to write to...
start = outfp . tell ( ) outfp . write ( data ) if self . _track_writes : # After the write , double check that we didn ' t write beyond the # boundary of the PVD , and raise a PyCdlibException if we do . end = outfp . tell ( ) if end > self . pvd . space_size * self . pvd . logical_block_size ( ) : rai...
def Box ( pos = ( 0 , 0 , 0 ) , length = 1 , width = 2 , height = 3 , normal = ( 0 , 0 , 1 ) , c = "g" , alpha = 1 , texture = None ) : """Build a box of dimensions ` x = length , y = width and z = height ` oriented along vector ` normal ` . . . hint : : | aspring | | aspring . py | _"""
src = vtk . vtkCubeSource ( ) src . SetXLength ( length ) src . SetYLength ( width ) src . SetZLength ( height ) src . Update ( ) poly = src . GetOutput ( ) axis = np . array ( normal ) / np . linalg . norm ( normal ) theta = np . arccos ( axis [ 2 ] ) phi = np . arctan2 ( axis [ 1 ] , axis [ 0 ] ) t = vtk . vtkTransfo...
def get ( key , service = None , profile = None ) : # pylint : disable = W0613 '''Get a decrypted secret from the tISMd API'''
if not profile . get ( 'url' ) or not profile . get ( 'token' ) : raise SaltConfigurationError ( "url and/or token missing from the tism sdb profile" ) request = { "token" : profile [ 'token' ] , "encsecret" : key } result = http . query ( profile [ 'url' ] , method = 'POST' , data = salt . utils . json . dumps ( r...
def make_heap ( n_points , size ) : """Constructor for the numba enabled heap objects . The heaps are used for approximate nearest neighbor search , maintaining a list of potential neighbors sorted by their distance . We also flag if potential neighbors are newly added to the list or not . Internally this is ...
result = np . zeros ( ( 3 , int ( n_points ) , int ( size ) ) , dtype = np . float64 ) result [ 0 ] = - 1 result [ 1 ] = np . infty result [ 2 ] = 0 return result
def peek_step ( self , val : ArrayValue , sn : "DataNode" ) -> Tuple [ ObjectValue , "DataNode" ] : """Return the entry addressed by the receiver + its schema node . Args : val : Current value ( array ) . sn : Current schema node ."""
keys = self . parse_keys ( sn ) for en in val : flag = True try : for k in keys : if en [ k ] != keys [ k ] : flag = False break except KeyError : continue if flag : return ( en , sn ) return ( None , sn )
def _less_or_close ( a , value , ** kwargs ) : r"""Compare values for less or close to boolean masks . Returns a boolean mask for values less than or equal to a target within a specified absolute or relative tolerance ( as in : func : ` numpy . isclose ` ) . Parameters a : array - like Array of values to ...
return ( a < value ) | np . isclose ( a , value , ** kwargs )
def _get_s3_key ( ) : '''Get AWS keys from pillar or config'''
key = __opts__ [ 's3.key' ] if 's3.key' in __opts__ else None keyid = __opts__ [ 's3.keyid' ] if 's3.keyid' in __opts__ else None service_url = __opts__ [ 's3.service_url' ] if 's3.service_url' in __opts__ else None verify_ssl = __opts__ [ 's3.verify_ssl' ] if 's3.verify_ssl' in __opts__ else None kms_keyid = __opts__ ...
def get_stored_files ( self ) : """Check which files are in your temporary storage ."""
method = 'GET' endpoint = '/rest/v1/storage/{}' . format ( self . client . sauce_username ) return self . client . request ( method , endpoint )
def _get ( self , action , show , proxy , timeout ) : """make HTTP request and cache response"""
silent = self . flags [ 'silent' ] if action in self . cache : if action != 'imageinfo' and action != 'labels' : utils . stderr ( "+ %s results in cache" % action , silent ) return else : self . cache [ action ] = { } if self . flags . get ( 'skip' ) and action in self . flags [ 'skip' ] : i...
def make_time_series ( x , t = pd . Timestamp ( datetime . datetime ( 1970 , 1 , 1 ) ) , freq = None ) : """Convert a 2 - D array of time / value pairs ( or pair of time / value vectors ) into a pd . Series time - series > > > make _ time _ series ( range ( 3 ) , freq = ' 15min ' ) # doctest : + NORMALIZE _ WHITE...
if isinstance ( x , pd . DataFrame ) : x = pd . Series ( x [ x . columns [ 0 ] ] ) elif not isinstance ( x , pd . Series ) and ( not isinstance ( t , ( pd . Series , pd . Index , list , tuple ) ) or not len ( t ) ) : # warnings . warn ( " Coercing a non - Series " ) if len ( x ) == 2 : t , x = listify (...
def ReadFlowProcessingRequests ( self , cursor = None ) : """Reads all flow processing requests from the database ."""
query = ( "SELECT request, UNIX_TIMESTAMP(timestamp) " "FROM flow_processing_requests" ) cursor . execute ( query ) res = [ ] for serialized_request , ts in cursor . fetchall ( ) : req = rdf_flows . FlowProcessingRequest . FromSerializedString ( serialized_request ) req . timestamp = mysql_utils . TimestampToRD...
def create_long ( self , value : int ) -> Long : """Creates a new : class : ` ConstantLong ` , adding it to the pool and returning it . : param value : The value of the new long ."""
self . append ( ( 5 , value ) ) self . append ( None ) return self . get ( self . raw_count - 2 )
def keyPressEvent ( self , evt ) : """This handles Ctrl + PageUp , Ctrl + PageDown , Ctrl + Tab , Ctrl + Shift + Tab"""
incr = 0 if evt . modifiers ( ) == Qt . ControlModifier : n = self . tabWidget . count ( ) if evt . key ( ) in [ Qt . Key_PageUp , Qt . Key_Backtab ] : incr = - 1 elif evt . key ( ) in [ Qt . Key_PageDown , Qt . Key_Tab ] : incr = 1 if incr != 0 : new_index = self . _get_tab_inde...
def create_model ( self , parent , name , multiplicity = Multiplicity . ZERO_MANY ) : """Create a single part model in this scope . See : class : ` pykechain . Client . create _ model ` for available parameters ."""
return self . _client . create_model ( parent , name , multiplicity = multiplicity )
def check_status ( self , job_id ) : """Check status of a job ."""
response , http_response = self . _client . jobs . get_job ( job_id = job_id ) . result ( ) if http_response . status_code == 404 : raise HTTPNotFound ( 'The given job ID was not found. Error: {}' . format ( http_response . data ) ) return response
def get_course_video_image_url ( course_id , edx_video_id ) : """Returns course video image url or None if no image found"""
try : video_image = CourseVideo . objects . select_related ( 'video_image' ) . get ( course_id = course_id , video__edx_video_id = edx_video_id ) . video_image return video_image . image_url ( ) except ObjectDoesNotExist : return None
def main ( args = None ) : """Main entry point"""
# parse args if args is None : args = parse_args ( sys . argv [ 1 : ] ) # set logging level if args . verbose > 1 : set_log_debug ( ) elif args . verbose == 1 : set_log_info ( ) outpath = os . path . abspath ( os . path . expanduser ( args . out_dir ) ) cachepath = os . path . abspath ( os . path . expandus...
def _Dielectric ( rho , T ) : """Equation for the Dielectric constant Parameters rho : float Density , [ kg / m3] T : float Temperature , [ K ] Returns epsilon : float Dielectric constant , [ - ] Notes Raise : class : ` NotImplementedError ` if input isn ' t in limit : * 238 ≤ T ≤ 1200 Examp...
# Check input parameters if T < 238 or T > 1200 : raise NotImplementedError ( "Incoming out of bound" ) k = 1.380658e-23 Na = 6.0221367e23 alfa = 1.636e-40 epsilon0 = 8.854187817e-12 mu = 6.138e-30 d = rho / rhoc Tr = Tc / T I = [ 1 , 1 , 1 , 2 , 3 , 3 , 4 , 5 , 6 , 7 , 10 , None ] J = [ 0.25 , 1 , 2.5 , 1.5 , 1.5 ...
def _to_torch ( Z , dtype = None ) : """Converts a None , list , np . ndarray , or torch . Tensor to torch . Tensor ; also handles converting sparse input to dense ."""
if Z is None : return None elif issparse ( Z ) : Z = torch . from_numpy ( Z . toarray ( ) ) elif isinstance ( Z , torch . Tensor ) : pass elif isinstance ( Z , list ) : Z = torch . from_numpy ( np . array ( Z ) ) elif isinstance ( Z , np . ndarray ) : Z = torch . from_numpy ( Z ) else : msg = ( ...
def as_slice ( slice_ ) : """Convert an object to a slice , if possible"""
if isinstance ( slice_ , ( Integral , numpy . integer , type ( None ) ) ) : return slice ( 0 , None , 1 ) if isinstance ( slice_ , ( slice , numpy . ndarray ) ) : return slice_ if isinstance ( slice_ , ( list , tuple ) ) : return tuple ( map ( as_slice , slice_ ) ) raise TypeError ( "Cannot format {!r} as s...
def _compute_mean ( self , C , mag , rhypo , hypo_depth , mean , idx ) : """Compute mean value according to equations 10 and 11 page 226."""
mean [ idx ] = ( C [ 'C1' ] + C [ 'C2' ] * mag + C [ 'C3' ] * np . log ( rhypo [ idx ] + C [ 'C4' ] * np . exp ( C [ 'C5' ] * mag ) ) + C [ 'C6' ] * hypo_depth )
def create ( cls , service = Service ( ) , private = False ) : """create a bin instance on the server"""
response = service . send ( SRequest ( 'POST' , cls . path , data = { 'private' : private } ) ) return cls . from_response ( response , service = service )
def plunge_bearing2pole ( plunge , bearing ) : """Converts the given ` plunge ` and ` bearing ` in degrees to a strike and dip of the plane whose pole would be parallel to the line specified . ( i . e . The pole to the plane returned would plot at the same point as the specified plunge and bearing . ) Param...
plunge , bearing = np . atleast_1d ( plunge , bearing ) strike = bearing + 90 dip = 90 - plunge strike [ strike >= 360 ] -= 360 return strike , dip
def delete ( self ) : """Destructor ."""
if self . maplesat : pysolvers . maplechrono_del ( self . maplesat ) self . maplesat = None if self . prfile : self . prfile . close ( )
def accept ( self ) : """Send a response disposition to the service to indicate that a received message has been accepted . If the client is running in PeekLock mode , the service will wait on this disposition . Otherwise it will be ignored . Returns ` True ` is message was accepted , or ` False ` if the mess...
if self . _can_settle_message ( ) : self . _response = errors . MessageAccepted ( ) self . _settler ( self . _response ) self . state = constants . MessageState . ReceivedSettled return True return False
def deprecated ( replacement_description ) : """States that method is deprecated . : param replacement _ description : Describes what must be used instead . : return : the original method with modified docstring ."""
def decorate ( fn_or_class ) : if isinstance ( fn_or_class , type ) : pass # Can ' t change _ _ doc _ _ of type objects else : try : fn_or_class . __doc__ = "This API point is obsolete. %s\n\n%s" % ( replacement_description , fn_or_class . __doc__ , ) except Attribute...
def _get_foundation_pos ( self , i ) : """Private . Get the absolute coordinates to use for a deck ' s foundation , based on the ` ` starting _ pos _ hint ` ` , the ` ` deck _ hint _ step ` ` , ` ` deck _ x _ hint _ offsets ` ` , and ` ` deck _ y _ hint _ offsets ` ` ."""
( phx , phy ) = get_pos_hint ( self . starting_pos_hint , * self . card_size_hint ) phx += self . deck_x_hint_step * i + self . deck_x_hint_offsets [ i ] phy += self . deck_y_hint_step * i + self . deck_y_hint_offsets [ i ] x = phx * self . width + self . x y = phy * self . height + self . y return ( x , y )
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : """Provide a default value for ` ` entity ` ` . By default , ` ` nailgun . entity _ mixins . EntityReadMixin . read ` ` provides a default value for ` ` entity ` ` like so : : entity = type ( self ) ( ) However , : class : ` ...
# read ( ) should not change the state of the object it ' s called on , but # super ( ) alters the attributes of any entity passed in . Creating a new # object and passing it to super ( ) lets this one avoid changing state . if entity is None : entity = type ( self ) ( self . _server_config , repository = self . re...
def set_row ( x , row ) : """We use db 1 , use offset 4 , we replace row x . To find the correct start _ index we mulitpy by row _ size by x and we put the byte array representation of row in the PLC"""
row_size = 126 set_db_row ( 1 , 4 + x * row_size , row_size , row . _bytearray )
def data_properties ( data , mask = None , background = None ) : """Calculate the morphological properties ( and centroid ) of a 2D array ( e . g . an image cutout of an object ) using image moments . Parameters data : array _ like or ` ~ astropy . units . Quantity ` The 2D array of the image . mask : arr...
from . . segmentation import SourceProperties # prevent circular imports segment_image = np . ones ( data . shape , dtype = np . int ) return SourceProperties ( data , segment_image , label = 1 , mask = mask , background = background )
def bootstrap_salt ( name , config = None , approve_key = True , install = True , pub_key = None , priv_key = None , bootstrap_url = None , force_install = False , unconditional_install = False , bootstrap_delay = None , bootstrap_args = None , bootstrap_shell = None ) : '''Bootstrap a container from package server...
if bootstrap_delay is not None : try : time . sleep ( bootstrap_delay ) except TypeError : # Bad input , but assume since a value was passed that # a delay was desired , and sleep for 5 seconds time . sleep ( 5 ) c_info = info ( name ) if not c_info : return None # default set here as we...
def run ( self ) : """Run charge balance command"""
# Load compound information def compound_name ( id ) : if id not in self . _model . compounds : return id return self . _model . compounds [ id ] . properties . get ( 'name' , id ) # Create a set of excluded reactions exclude = set ( self . _args . exclude ) count = 0 unbalanced = 0 unchecked = 0 for re...
def get_group_instance ( self , parent ) : """Create an instance object"""
o = copy . copy ( self ) o . init_instance ( parent ) return o
def validate_key ( key , sign = False , encrypt = False ) : """Assert that a key is valide and optionally that it can be used for signing or encrypting . Raise GPGProblem otherwise . : param key : the GPG key to check : type key : gpg . gpgme . _ gpgme _ key : param sign : whether the key should be able to ...
if key . revoked : raise GPGProblem ( 'The key "{}" is revoked.' . format ( key . uids [ 0 ] . uid ) , code = GPGCode . KEY_REVOKED ) elif key . expired : raise GPGProblem ( 'The key "{}" is expired.' . format ( key . uids [ 0 ] . uid ) , code = GPGCode . KEY_EXPIRED ) elif key . invalid : raise GPGProblem ...
def flag_time_err ( phase_err , time_thresh = 0.02 ) : """Find large time errors in list . Scan through a list of tuples of time stamps and phase errors and return a list of time stamps with timing errors above a threshold . . . note : : This becomes important for networks cross - correlations , where if ...
time_err = [ ] for stamp in phase_err : if abs ( stamp [ 1 ] ) > time_thresh : time_err . append ( stamp [ 0 ] ) return time_err
def get_builds ( galaxy_base ) : """Retrieve configured genome builds and reference files , using Galaxy configuration files . Allows multiple dbkey specifications in the same file , using the most recently added ."""
name = "samtools" galaxy_config = _get_galaxy_tool_info ( galaxy_base ) galaxy_dt = _get_galaxy_data_table ( name , galaxy_config [ "tool_data_table_config_path" ] ) loc_file , need_remap = _get_galaxy_loc_file ( name , galaxy_dt , galaxy_config [ "tool_data_path" ] , galaxy_base ) assert not need_remap , "Should not n...
def main ( ) : '''Main function .'''
usage = ( '\n\n %prog [options] XML_PATH\n\nArguments:\n\n ' 'XML_PATH the directory containing the ' 'GermaNet .xml files' ) parser = optparse . OptionParser ( usage = usage ) parser . add_option ( '--host' , default = None , help = 'hostname or IP address of the MongoDB instance ' 'where the GermaNet d...
def ls ( params = "" , directory = "." , printed = True ) : """Know the best python implantation of ls ? It ' s just to subprocess ls . . . ( uses dir on windows ) . : param params : options to pass to ls or dir : param directory : if not this directory : param printed : If you ' re using this , you probabl...
command = "{0} {1} {2}" . format ( "ls" if not win_based else "dir" , params , directory ) response = run ( command , shell = True ) # Shell required for windows response . check_returncode ( ) if printed : print ( response . stdout . decode ( "utf-8" ) ) else : return response . stdout
def request_ligodotorg ( url , debug = False ) : """Request the given URL using LIGO . ORG SAML authentication . This requires an active Kerberos ticket for the user , to get one : $ kinit albert . einstein @ LIGO . ORG Parameters url : ` str ` URL path for request debug : ` bool ` , optional Query in...
# set debug to 1 to see all HTTP ( s ) traffic debug = int ( debug ) # need an instance of HTTPS handler to do HTTPS httpsHandler = urllib2 . HTTPSHandler ( debuglevel = debug ) # use a cookie jar to store session cookies jar = cookielib . LWPCookieJar ( ) # if a cookier jar exists open it and read the cookies # and ma...
def _iterate_marginal_coef_slices ( self , i ) : """iterator of indices into tensor ' s coef vector for marginal term i ' s coefs takes a tensor _ term and returns an iterator of indices that chop up the tensor ' s coef vector into slices belonging to term i Parameters i : int , index of marginal term Y...
dims = [ term_ . n_coefs for term_ in self ] # make all linear indices idxs = np . arange ( np . prod ( dims ) ) # reshape indices to a Nd matrix idxs = idxs . reshape ( dims ) # reshape to a 2d matrix , where we can loop over rows idxs = np . moveaxis ( idxs , i , 0 ) . reshape ( idxs . shape [ i ] , int ( idxs . size...
def init_service_processes ( self ) : """Prepare processes defined in the * * settings . SERVICE _ PROCESSES * * . Return : class : ` list ` of the : class : ` ProcessWrapper ` instances ."""
processes = [ ] for process_struct in getattr ( self . context . config . settings , 'SERVICE_PROCESSES' , ( ) ) : process_cls = import_object ( process_struct [ 0 ] ) wait_unless_ready , timeout = process_struct [ 1 ] , process_struct [ 2 ] self . logger . info ( "Init service process '%s'" , process_cls ....
def parse ( name , content , releases , get_head_fn ) : """Parses the given content for a valid changelog : param name : str , package name : param content : str , content : param releases : list , releases : param get _ head _ fn : function : return : dict , changelog"""
changelog = { } releases = frozenset ( releases ) head = False for line in content . splitlines ( ) : new_head = get_head_fn ( name = name , line = line , releases = releases ) if new_head : head = new_head changelog [ head ] = "" continue if not head : continue line = li...
def iter_processes ( self , proc_filter = None ) : """Yields processes from psutil . process _ iter with an optional filter and swallows psutil errors . If a psutil exception is raised during execution of the filter , that process will not be yielded but subsequent processes will . On the other hand , if psutil...
with swallow_psutil_exceptions ( ) : # process _ iter may raise for proc in psutil . process_iter ( ) : with swallow_psutil_exceptions ( ) : # proc _ filter may raise if ( proc_filter is None ) or proc_filter ( proc ) : yield proc
def create_tab ( self , location = None ) : """Create a new tab page ."""
eb = self . _get_or_create_editor_buffer ( location ) self . tab_pages . insert ( self . active_tab_index + 1 , TabPage ( Window ( eb ) ) ) self . active_tab_index += 1
def extend ( self , api , route = "" , base_url = "" , http = True , cli = True , ** kwargs ) : """Adds handlers from a different Hug API to this one - to create a single API"""
api = API ( api ) if http and hasattr ( api , '_http' ) : self . http . extend ( api . http , route , base_url , ** kwargs ) if cli and hasattr ( api , '_cli' ) : self . cli . extend ( api . cli , ** kwargs ) for directive in getattr ( api , '_directives' , { } ) . values ( ) : self . add_directive ( direct...
def _absent ( name , dataset_type , force = False , recursive = False , recursive_all = False ) : '''internal shared function for * _ absent name : string name of dataset dataset _ type : string [ filesystem , volume , snapshot , or bookmark ] type of dataset to remove force : boolean try harder to dest...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } # # log configuration dataset_type = dataset_type . lower ( ) log . debug ( 'zfs.%s_absent::%s::config::force = %s' , dataset_type , name , force ) log . debug ( 'zfs.%s_absent::%s::config::recursive = %s' , dataset_type , name , recursive ) #...
def _parse_xml ( self , xml ) : """Extracts the attributes from the XMLElement instance ."""
from re import split vms ( "Parsing <cron> XML child tag." , 2 ) self . frequency = get_attrib ( xml , "frequency" , default = 5 , cast = int ) self . emails = split ( ",\s*" , get_attrib ( xml , "emails" , default = "" ) ) self . notify = split ( ",\s*" , get_attrib ( xml , "notify" , default = "" ) )
def _handle_value ( self , value ) : """Given a value string , unquote , remove comment , handle lists . ( including empty and single member lists )"""
if self . _inspec : # Parsing a configspec so don ' t handle comments return ( value , '' ) # do we look for lists in values ? if not self . list_values : mat = self . _nolistvalue . match ( value ) if mat is None : raise SyntaxError ( ) # NOTE : we don ' t unquote here return mat . groups (...
def _enforceDataType ( self , data ) : """Converts to float so that this CTI always stores that type . Replaces infinite with the maximum respresentable float . Raises a ValueError if data is a NaN ."""
value = float ( data ) if math . isnan ( value ) : raise ValueError ( "FloatCti can't store NaNs" ) if math . isinf ( value ) : if value > 0 : logger . warn ( "Replacing inf by the largest representable float" ) value = sys . float_info . max else : logger . warn ( "Replacing -inf by...
def build_response ( self , req , resp ) : """Builds a : class : ` Response < requests . Response > ` object from a urllib3 response . This should not be called from user code , and is only exposed for use when subclassing the : class : ` HTTPAdapter < requests . adapters . HTTPAdapter > ` : param req : The...
response = Response ( ) # Fallback to None if there ' s no status _ code , for whatever reason . response . status_code = getattr ( resp , 'status' , None ) # Make headers case - insensitive . response . headers = CaseInsensitiveDict ( getattr ( resp , 'headers' , { } ) ) # Set encoding . response . encoding = get_enco...
def get_tree ( cls , parent = None ) : """: returns : A * queryset * of nodes ordered as DFS , including the parent . If no parent is given , all trees are returned ."""
cls = get_result_class ( cls ) if parent is None : # return the entire tree return cls . objects . all ( ) if parent . is_leaf ( ) : return cls . objects . filter ( pk = parent . pk ) return cls . objects . filter ( tree_id = parent . tree_id , lft__range = ( parent . lft , parent . rgt - 1 ) )
def iter_links ( operations , page ) : """Generate links for an iterable of operations on a starting page ."""
for operation , ns , rule , func in operations : yield Link . for_ ( operation = operation , ns = ns , type = ns . subject_name , qs = page . to_items ( ) , )
def get_platforms ( self , automation_api = 'all' ) : """Get a list of objects describing all the OS and browser platforms currently supported on Sauce Labs ."""
method = 'GET' endpoint = '/rest/v1/info/platforms/{}' . format ( automation_api ) return self . client . request ( method , endpoint )
def _renumber ( a : np . ndarray , keys : np . ndarray , values : np . ndarray ) -> np . ndarray : """Renumber ' a ' by replacing any occurrence of ' keys ' by the corresponding ' values '"""
ordering = np . argsort ( keys ) keys = keys [ ordering ] values = keys [ ordering ] index = np . digitize ( a . ravel ( ) , keys , right = True ) return ( values [ index ] . reshape ( a . shape ) )
async def disconnect_message ( self , message , context ) : """Handle a disconnect message . See : meth : ` AbstractDeviceAdapter . disconnect ` ."""
conn_string = message . get ( 'connection_string' ) client_id = context . user_data await self . disconnect ( client_id , conn_string )
def login_user ( user , remember = False , duration = None , force = False , fresh = True ) : '''Logs a user in . You should pass the actual user object to this . If the user ' s ` is _ active ` property is ` ` False ` ` , they will not be logged in unless ` force ` is ` ` True ` ` . This will return ` ` True...
if not force and not user . is_active : return False user_id = getattr ( user , current_app . login_manager . id_attribute ) ( ) session [ 'user_id' ] = user_id session [ '_fresh' ] = fresh session [ '_id' ] = current_app . login_manager . _session_identifier_generator ( ) if remember : session [ 'remember' ] =...
def get_pmids ( self ) : """Get list of all PMIDs associated with edges in the network ."""
pmids = [ ] for ea in self . _edge_attributes . values ( ) : edge_pmids = ea . get ( 'pmids' ) if edge_pmids : pmids += edge_pmids return list ( set ( pmids ) )
def wrap_list ( item ) : """Returns an object as a list . If the object is a list , it is returned directly . If it is a tuple or set , it is returned as a list . If it is another object , it is wrapped in a list and returned ."""
if item is None : return [ ] elif isinstance ( item , list ) : return item elif isinstance ( item , ( tuple , set ) ) : return list ( item ) else : return [ item ]
def alterar ( self , id_script_type , type , description ) : """Change Script Type from by the identifier . : param id _ script _ type : Identifier of the Script Type . Integer value and greater than zero . : param type : Script Type type . String with a minimum 3 and maximum of 40 characters : param descript...
if not is_valid_int_param ( id_script_type ) : raise InvalidParameterError ( u'The identifier of Script Type is invalid or was not informed.' ) script_type_map = dict ( ) script_type_map [ 'type' ] = type script_type_map [ 'description' ] = description url = 'scripttype/' + str ( id_script_type ) + '/' code , xml =...
def punchFile ( rh ) : """Punch a file to a virtual reader of the specified virtual machine . Input : Request Handle with the following properties : function - ' CHANGEVM ' subfunction - ' PUNCHFILE ' userid - userid of the virtual machine parms [ ' class ' ] - Spool class ( optional ) parms [ ' file ...
rh . printSysLog ( "Enter changeVM.punchFile" ) # Default spool class in " A " , if specified change to specified class spoolClass = "A" if 'class' in rh . parms : spoolClass = str ( rh . parms [ 'class' ] ) punch2reader ( rh , rh . userid , rh . parms [ 'file' ] , spoolClass ) rh . printSysLog ( "Exit changeVM.pun...
def _create_default_config_file ( self ) : """If config file does not exists create and set default values ."""
logger . info ( 'Initialize Maya launcher, creating config file...\n' ) self . add_section ( self . DEFAULTS ) self . add_section ( self . PATTERNS ) self . add_section ( self . ENVIRONMENTS ) self . add_section ( self . EXECUTABLES ) self . set ( self . DEFAULTS , 'executable' , None ) self . set ( self . DEFAULTS , '...
def set_flag_bit ( self , x ) : """Function internally used in set _ flags . No multi - line lambdas in python : / : param x : : return :"""
x = bytes_to_byte ( x ) if KeyTypes . COMM_ENC in self . keys : x &= ~ 0x8 if KeyTypes . APP_KEY in self . keys : x &= ~ 0x10 return byte_to_bytes ( x )
def calculate_crop_list ( full_page_box_list , bounding_box_list , angle_list , page_nums_to_crop ) : """Given a list of full - page boxes ( media boxes ) and a list of tight bounding boxes for each page , calculate and return another list giving the list of bounding boxes to crop down to . The parameter ` angl...
# Definition : the deltas are the four differences , one for each margin , # between the original full page box and the final , cropped full - page box . # In the usual case where margin sizes decrease these are the same as the # four margin - reduction values ( in absolute points ) . The deltas are # usually positive ...
def _quote ( str , LegalChars = _LegalChars ) : r"""Quote a string for use in a cookie header . If the string does not need to be double - quoted , then just return the string . Otherwise , surround the string in doublequotes and quote ( with a \ ) special characters ."""
if all ( c in LegalChars for c in str ) : return str else : return '"' + _nulljoin ( _Translator . get ( s , s ) for s in str ) + '"'
def add_params ( self , ** kw ) : """Add [ possibly many ] parameters to the track . Parameters will be checked against known UCSC parameters and their supported formats . E . g . : : add _ params ( color = ' 128,0,0 ' , visibility = ' dense ' )"""
for k , v in kw . items ( ) : if ( k not in self . params ) and ( k not in self . specific_params ) : raise ParameterError ( '"%s" is not a valid parameter for %s' % ( k , self . __class__ . __name__ ) ) try : self . params [ k ] . validate ( v ) except KeyError : self . specific_par...
def createLabels2D ( self ) : """2D labeling at zmax"""
logger . debug ( " Creating 2D labels..." ) self . zmax = np . argmax ( self . values , axis = 1 ) self . vmax = self . values [ np . arange ( len ( self . pixels ) , dtype = int ) , self . zmax ] kwargs = dict ( pixels = self . pixels , values = self . vmax , nside = self . nside , threshold = self . threshold , xsiz...
def roles ( self ) : """Access the roles : returns : twilio . rest . chat . v2 . service . role . RoleList : rtype : twilio . rest . chat . v2 . service . role . RoleList"""
if self . _roles is None : self . _roles = RoleList ( self . _version , service_sid = self . _solution [ 'sid' ] , ) return self . _roles
def apply ( self , cls , originalMemberNameList , classNamingConvention ) : """: type cls : type : type originalMemberNameList : list ( str ) : type classNamingConvention : INamingConvention"""
self . _memberDelegate . apply ( cls = cls , originalMemberNameList = originalMemberNameList , memberName = self . _memberName , classNamingConvention = classNamingConvention , getter = self . _makeGetter ( ) , setter = self . _makeSetter ( ) )
def get_ecdh_key ( self , other ) : '''other - - > Key25519 instance'''
if self . __secretkey is None : raise KeyTypeError ( 'Wrong key type for operation' ) # Copy because curve25519 _ dh _ CreateSharedKey changes secretkey tmp_secretkey = ffi . new ( C_SECRETKEY , self . secretkey ) ecdh_key = ffi . new ( C_SHAREDKEY ) lib . curve25519_dh_CreateSharedKey ( ecdh_key , other . pubkey ,...
def K ( self , X , X2 = None , presliced = False ) : """Calculates the kernel matrix K ( X , X2 ) ( or K ( X , X ) if X2 is None ) . Handles the slicing as well as scaling and computes k ( x , x ' ) = k ( r ) , where r2 = ( ( x - x ' ) / lengthscales ) 2. Internally , this calls self . K _ r2 ( r2 ) , which i...
if not presliced : X , X2 = self . _slice ( X , X2 ) return self . K_r2 ( self . scaled_square_dist ( X , X2 ) )
def setTargets ( self , targets ) : """Sets the targets ."""
if not self . verifyArguments ( targets ) and not self . patterned : raise NetworkError ( 'setTargets() requires [[...],[...],...] or [{"layerName": [...]}, ...].' , targets ) self . targets = targets
def open ( self , number = 0 ) : """Open the FaderPort and register a callback so we can send and receive MIDI messages . : param number : 0 unless you ' ve got more than one FaderPort attached . In which case 0 is the first , 1 is the second etc I only have access to a single device so I can ' t actually...
self . inport = mido . open_input ( find_faderport_input_name ( number ) ) self . outport = mido . open_output ( find_faderport_output_name ( number ) ) self . outport . send ( mido . Message . from_bytes ( [ 0x91 , 0 , 0x64 ] ) ) # A reset message ? ? ? time . sleep ( 0.01 ) self . inport . callback = self . _message_...
def list_agents ( self ) : '''List agents hosted by the agency .'''
t = text_helper . Table ( fields = ( "Agent ID" , "Agent class" , "State" ) , lengths = ( 40 , 25 , 15 ) ) return t . render ( ( a . _descriptor . doc_id , a . log_category , a . _get_machine_state ( ) . name ) for a in self . _agents )
def save_to_file ( self , path ) : """Dump all cookies to file . Cookies are dumped as JSON - serialized dict of keys and values ."""
with open ( path , 'w' ) as out : out . write ( json . dumps ( self . get_dict ( ) ) )
def add_device_items ( self , item , device ) : """Add the various items from the device to the node : param str item : item key : param dict device : dictionary containing items"""
if item in ( 'aux' , 'console' ) : self . node [ 'properties' ] [ item ] = device [ item ] elif item . startswith ( 'slot' ) : # if self . device _ info [ ' model ' ] = = ' c7200 ' : # if item ! = ' slot0 ' : # self . node [ ' properties ' ] [ item ] = device [ item ] # else : self . node [ 'properties' ] [ ite...
def get_dataset_feature_statistics ( builder , split ) : """Calculate statistics for the specified split ."""
statistics = statistics_pb2 . DatasetFeatureStatistics ( ) # Make this to the best of our abilities . schema = schema_pb2 . Schema ( ) dataset = builder . as_dataset ( split = split ) # Just computing the number of examples for now . statistics . num_examples = 0 # Feature dictionaries . feature_to_num_examples = colle...