signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_tree ( profile , sha , recursive = True ) : """Fetch a tree . Args : profile A profile generated from ` ` simplygithub . authentication . profile ` ` . Such profiles tell this module ( i ) the ` ` repo ` ` to connect to , and ( ii ) the ` ` token ` ` to connect with . sha The SHA of the tree t...
resource = "/trees/" + sha if recursive : resource += "?recursive=1" data = api . get_request ( profile , resource ) return prepare ( data )
def _get_addr ( self , v ) : """Get address of the basic block or CFG node specified by v . : param v : Can be one of the following : a CFGNode , or an address . : return : The address . : rtype : int"""
if isinstance ( v , CFGNode ) : return v . addr elif type ( v ) is int : return v else : raise AngrBladeError ( 'Unsupported SimRun argument type %s' % type ( v ) )
def msgblock ( key , text , side = '|' ) : """puts text inside a visual ascii block"""
blocked_text = '' . join ( [ ' + --- ' , key , ' ---\n' ] + [ ' ' + side + ' ' + line + '\n' for line in text . split ( '\n' ) ] + [ ' L ___ ' , key , ' ___\n' ] ) return blocked_text
def fput_object ( self , bucket_name , object_name , file_path , content_type = 'application/octet-stream' , metadata = None , sse = None , progress = None , part_size = DEFAULT_PART_SIZE ) : """Add a new object to the cloud storage server . Examples : minio . fput _ object ( ' foo ' , ' bar ' , ' filepath ' , ...
# Open file in ' read ' mode . with open ( file_path , 'rb' ) as file_data : file_size = os . stat ( file_path ) . st_size return self . put_object ( bucket_name , object_name , file_data , file_size , content_type , metadata , sse , progress , part_size )
def check_auth ( username , pwd ) : """This function is called to check if a username / password combination is valid ."""
cfg = get_current_config ( ) return username == cfg [ "dashboard_httpauth" ] . split ( ":" ) [ 0 ] and pwd == cfg [ "dashboard_httpauth" ] . split ( ":" ) [ 1 ]
def validate ( mcs , bases , attributes ) : """Check attributes ."""
if bases [ 0 ] is object : return None mcs . check_model_cls ( attributes ) mcs . check_include_exclude ( attributes ) mcs . check_properties ( attributes )
def assert_element_present ( self , selector , by = By . CSS_SELECTOR , timeout = settings . SMALL_TIMEOUT ) : """Similar to wait _ for _ element _ present ( ) , but returns nothing . Waits for an element to appear in the HTML of a page . The element does not need be visible ( it may be hidden ) . Returns Tru...
if self . timeout_multiplier and timeout == settings . SMALL_TIMEOUT : timeout = self . __get_new_timeout ( timeout ) self . wait_for_element_present ( selector , by = by , timeout = timeout ) return True
async def getStickerSet ( self , name ) : """See : https : / / core . telegram . org / bots / api # getstickerset"""
p = _strip ( locals ( ) ) return await self . _api_request ( 'getStickerSet' , _rectify ( p ) )
def _parse_relation ( chunk , type = "O" ) : """Returns a string of the roles and relations parsed from the given < chunk > element . The chunk type ( which is part of the relation string ) can be given as parameter ."""
r1 = chunk . get ( XML_RELATION ) r2 = chunk . get ( XML_ID , chunk . get ( XML_OF ) ) r1 = [ x != "-" and x or None for x in r1 . split ( "|" ) ] or [ None ] r2 = [ x != "-" and x or None for x in r2 . split ( "|" ) ] or [ None ] r2 = [ x is not None and x . split ( _UID_SEPARATOR ) [ - 1 ] or x for x in r2 ] if len (...
def find_credential ( self , url ) : """If the URL indicated appears to be a repository defined in this config , return the credential for that repository ."""
for repository , cred in self . creds_by_repository . items ( ) : if url . startswith ( repository ) : return cred
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : """Ignore usergroup from read and alter auth _ source _ ldap with auth _ source"""
if entity is None : entity = type ( self ) ( self . _server_config , usergroup = self . usergroup , # pylint : disable = no - member ) if ignore is None : ignore = set ( ) ignore . add ( 'usergroup' ) if attrs is None : attrs = self . read_json ( ) attrs [ 'auth_source' ] = attrs . pop ( 'auth_source_ld...
def store ( self , record , value ) : """Store the value in the record ."""
record . _values [ self . name ] [ record . id ] = value
def _compute_distance ( self , rup , dists , C ) : """equation 3 pag 1960: ` ` c31 * logR + c32 * ( R - Rref ) ` `"""
rref = 1.0 c31 = - 1.7 return ( c31 * np . log10 ( dists . rhypo ) + C [ 'c32' ] * ( dists . rhypo - rref ) )
def parse ( item ) : r"""> > > Tag . parse ( ' x ' ) = = { ' key ' : ' x ' , ' value ' : None } True > > > Tag . parse ( ' x = yes ' ) = = { ' key ' : ' x ' , ' value ' : ' yes ' } True > > > Tag . parse ( ' x = 3 ' ) [ ' value ' ] > > > Tag . parse ( ' x = red fox \ \ : green eggs ' ) [ ' value ' ] ' r...
key , sep , value = item . partition ( '=' ) value = value . replace ( '\\:' , ';' ) value = value . replace ( '\\s' , ' ' ) value = value . replace ( '\\n' , '\n' ) value = value . replace ( '\\r' , '\r' ) value = value . replace ( '\\\\' , '\\' ) value = value or None return { 'key' : key , 'value' : value , }
def mainloop ( self ) : """Handles events and calls their handler for infinity ."""
while self . keep_going : with self . lock : if self . on_connect and not self . readable ( 2 ) : self . on_connect ( ) self . on_connect = None if not self . keep_going : break self . process_once ( )
def msg_curse ( self , args = None , max_width = None ) : """Return the dict to display in the curse interface ."""
# Init the return message ret = [ ] # Only process if stats exist and display plugin enable . . . if not self . stats or args . disable_process : return ret # Compute the sort key process_sort_key = glances_processes . sort_key # Header self . __msg_curse_header ( ret , process_sort_key , args ) # Process list # Lo...
def _parameter_constraints ( self , theta_E , gamma , q , phi_G , s_scale ) : """sets bounds to parameters due to numerical stability : param theta _ E : : param gamma : : param q : : param phi _ G : : param s _ scale : : return :"""
if theta_E < 0 : theta_E = 0 if s_scale < 0.00000001 : s_scale = 0.00000001 if gamma < 1.2 : gamma = 1.2 theta_E = 0 if gamma > 2.9 : gamma = 2.9 theta_E = 0 if q < 0.01 : q = 0.01 theta_E = 0 if q > 1 : q = 1. theta_E = 0 return theta_E , gamma , q , phi_G , s_scale
def check_marginal_likelihoods ( tree , feature ) : """Sanity check : combined bottom - up and top - down likelihood of each node of the tree must be the same . : param tree : ete3 . Tree , the tree of interest : param feature : str , character for which the likelihood is calculated : return : void , stores t...
lh_feature = get_personalized_feature_name ( feature , LH ) lh_sf_feature = get_personalized_feature_name ( feature , LH_SF ) for node in tree . traverse ( ) : if not node . is_root ( ) and not ( node . is_leaf ( ) and node . dist == 0 ) : node_loglh = np . log10 ( getattr ( node , lh_feature ) . sum ( ) ) ...
def bounds ( sceneid ) : """Retrieve image bounds . Attributes sceneid : str Sentinel - 2 sceneid . Returns out : dict dictionary with image bounds ."""
scene_params = _sentinel_parse_scene_id ( sceneid ) sentinel_address = "{}/{}" . format ( SENTINEL_BUCKET , scene_params [ "key" ] ) with rasterio . open ( "{}/preview.jp2" . format ( sentinel_address ) ) as src : wgs_bounds = transform_bounds ( * [ src . crs , "epsg:4326" ] + list ( src . bounds ) , densify_pts = ...
def humanize ( t ) : """> > > print humanize ( 0) now > > > print humanize ( 1) in a minute > > > print humanize ( 60) in a minute > > > print humanize ( 61) in 2 minutes > > > print humanize ( 3600) in an hour > > > print humanize ( 3601) in 2 hours"""
m , s = divmod ( t , 60 ) if s : m += 1 # ceil minutes h , m = divmod ( m , 60 ) if m and h : h += 1 # ceil hours # d , h = divmod ( h , 24) if h > 1 : res = 'in %d hours' % h elif h == 1 : res = 'in an hour' else : if m > 1 : res = 'in %d minutes' % m elif m == 1 : res =...
def p_type_def ( self , p ) : '''type _ def : IDENT COLON OBJECT SEMI | IDENT COLON LCURLY enum _ list RCURLY SEMI'''
if len ( p ) == 5 : p [ 0 ] = ( p [ 1 ] , p [ 3 ] ) elif len ( p ) == 7 : p [ 0 ] = ( p [ 1 ] , p [ 4 ] )
def get_remainder_set ( self , j ) : """Return the set of children with indices less than j of all ancestors of j . The set C from ( arXiv : 1701.07072 ) . : param int j : fermionic site index : return : children of j - ancestors , with indices less than j : rtype : list ( FenwickNode )"""
result = [ ] ancestors = self . get_update_set ( j ) # This runs in O ( log ( N ) log ( N ) ) where N is the number of qubits . for a in ancestors : for c in a . children : if c . index < j : result . append ( c ) return result
def get_effective_rlzs ( rlzs ) : """Group together realizations with the same unique identifier ( uid ) and yield the first representative of each group ."""
effective = [ ] for uid , group in groupby ( rlzs , operator . attrgetter ( 'uid' ) ) . items ( ) : rlz = group [ 0 ] if all ( path == '@' for path in rlz . lt_uid ) : # empty realization continue effective . append ( Realization ( rlz . value , sum ( r . weight for r in group ) , rlz . lt_path , rl...
def get_streaming_playlist ( cookie , path , video_type = 'M3U8_AUTO_480' ) : '''获取流媒体 ( 通常是视频 ) 的播放列表 . 默认得到的是m3u8格式的播放列表 , 因为它最通用 . path - 视频的绝对路径 video _ type - 视频格式 , 可以根据网速及片源 , 选择不同的格式 .'''
url = '' . join ( [ const . PCS_URL , 'file?method=streaming' , '&path=' , encoder . encode_uri_component ( path ) , '&type=' , video_type , '&app_id=250528' , ] ) req = net . urlopen ( url , headers = { 'Cookie' : cookie . header_output ( ) } ) if req : return req . data else : return None
def query_log ( self , filter = None , query = None , count = None , offset = None , sort = None , ** kwargs ) : """Search the query and event log . Searches the query and event log to find query sessions that match the specified criteria . Searching the * * logs * * endpoint uses the standard Discovery query s...
headers = { } if 'headers' in kwargs : headers . update ( kwargs . get ( 'headers' ) ) sdk_headers = get_sdk_headers ( 'discovery' , 'V1' , 'query_log' ) headers . update ( sdk_headers ) params = { 'version' : self . version , 'filter' : filter , 'query' : query , 'count' : count , 'offset' : offset , 'sort' : self...
def get_vocab ( docs ) : """Build a DataFrame containing all the words in the docs provided along with their POS tags etc > > > doc = nlp ( " Hey Mr . Tangerine Man ! " ) < BLANKLINE > > > > get _ vocab ( [ doc ] ) word pos tag dep ent _ type ent _ iob sentiment 0 ! PUNCT . punct O 0.0 1 Hey INTJ UH int...
if isinstance ( docs , spacy . tokens . doc . Doc ) : return get_vocab ( [ docs ] ) vocab = set ( ) for doc in tqdm ( docs ) : for tok in doc : vocab . add ( ( tok . text , tok . pos_ , tok . tag_ , tok . dep_ , tok . ent_type_ , tok . ent_iob_ , tok . sentiment ) ) # TODO : add ent type info and other ...
def all_from ( cls , * args , ** kwargs ) : """Query for items passing PyQuery args explicitly ."""
pq_items = cls . _get_items ( * args , ** kwargs ) return [ cls ( item = i ) for i in pq_items . items ( ) ]
def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_date_and_time_info ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) logical_chassis_fwdl_status = ET . Element ( "logical_chassis_fwdl_status" ) config = logical_chassis_fwdl_status output = ET . SubElement ( logical_chassis_fwdl_status , "output" ) cluster_fwdl_entries = ET . SubElement ( output , "cluster-fwdl-entries" ) fwdl_entries = ET . SubEleme...
def Metropolis ( self , compute_target , mh_options ) : """Performs a certain number of Metropolis steps . Parameters compute _ target : function computes the target density for the proposed values mh _ options : dict + ' type _ prop ' : { ' random _ walk ' , ' independent ' } type of proposal : either ...
opts = mh_options . copy ( ) nsteps = opts . pop ( 'nsteps' , 0 ) delta_dist = opts . pop ( 'delta_dist' , 0.1 ) proposal = self . choose_proposal ( ** opts ) xout = self . copy ( ) xp = self . __class__ ( theta = np . empty_like ( self . theta ) ) step_ars = [ ] for _ in self . mcmc_iterate ( nsteps , self . arr , xou...
def send_result ( self , return_code , output , service_description = '' , time_stamp = 0 , specific_servers = None ) : '''Send result to the Skinken WS'''
if time_stamp == 0 : time_stamp = int ( time . time ( ) ) if specific_servers == None : specific_servers = self . servers else : specific_servers = set ( self . servers ) . intersection ( specific_servers ) for server in specific_servers : post_data = { } post_data [ 'time_stamp' ] = time_stamp ...
def get_validation_data ( doc ) : """Validate the docstring . Parameters doc : Docstring A Docstring object with the given function name . Returns tuple errors : list of tuple Errors occurred during validation . warnings : list of tuple Warnings occurred during validation . examples _ errs : str...
errs = [ ] wrns = [ ] if not doc . raw_doc : errs . append ( error ( 'GL08' ) ) return errs , wrns , '' if doc . start_blank_lines != 1 : errs . append ( error ( 'GL01' ) ) if doc . end_blank_lines != 1 : errs . append ( error ( 'GL02' ) ) if doc . double_blank_lines : errs . append ( error ( 'GL03'...
def size ( self , width = None , height = None ) : u'''Set / get window size .'''
info = CONSOLE_SCREEN_BUFFER_INFO ( ) status = self . GetConsoleScreenBufferInfo ( self . hout , byref ( info ) ) if not status : return None if width is not None and height is not None : wmin = info . srWindow . Right - info . srWindow . Left + 1 hmin = info . srWindow . Bottom - info . srWindow . Top + 1 ...
def dump ( self , * args , ** kwargs ) : """Dumps a representation of the Model on standard output ."""
lxml . etree . dump ( self . _obj , * args , ** kwargs )
def send_response_only ( self , code , message = None ) : """Send the response header only ."""
if message is None : if code in self . responses : message = self . responses [ code ] [ 0 ] else : message = '' if self . request_version != 'HTTP/0.9' : if not hasattr ( self , '_headers_buffer' ) : self . _headers_buffer = [ ] self . _headers_buffer . append ( ( "%s %d %s\r\n"...
def _add ( self , replace , section , name , * args ) : """Add records . The first argument is the replace mode . If false , RRs are added to an existing RRset ; if true , the RRset is replaced with the specified contents . The second argument is the section to add to . The third argument is always a name ....
if isinstance ( name , ( str , unicode ) ) : name = dns . name . from_text ( name , None ) if isinstance ( args [ 0 ] , dns . rdataset . Rdataset ) : for rds in args : if replace : self . delete ( name , rds . rdtype ) for rd in rds : self . _add_rr ( name , rds . ttl , r...
def create_route ( self , route_table_id , destination_cidr_block , gateway_id = None , instance_id = None ) : """Creates a new route in the route table within a VPC . The route ' s target can be either a gateway attached to the VPC or a NAT instance in the VPC . : type route _ table _ id : str : param rout...
params = { 'RouteTableId' : route_table_id , 'DestinationCidrBlock' : destination_cidr_block } if gateway_id is not None : params [ 'GatewayId' ] = gateway_id elif instance_id is not None : params [ 'InstanceId' ] = instance_id return self . get_status ( 'CreateRoute' , params )
def transform_single ( self , data , center , i = 0 ) : """Compute entries of ` data ` in hypercube centered at ` center ` Parameters data : array - like Data to find in entries in cube . Warning : first column must be index column . center : array - like Center points for the cube . Cube is found as all ...
lowerbounds , upperbounds = center - self . radius_ , center + self . radius_ # Slice the hypercube entries = ( data [ : , self . di_ ] >= lowerbounds ) & ( data [ : , self . di_ ] <= upperbounds ) hypercube = data [ np . invert ( np . any ( entries == False , axis = 1 ) ) ] if self . verbose > 1 : print ( "There a...
def has_nested_keys ( mapping , k1 , * more ) : """Return ` ` True ` ` if ` mapping [ k1 ] [ k2 ] . . . [ kN ] ` is valid . Example : : . . . ' x ' : 0, . . . ' z ' : 1, . . . ' b ' : 3 > > > has _ nested _ keys ( D , ' a ' , ' x ' ) True > > > has _ nested _ keys ( D , ' a ' , ' y ' , ' z ' ) True ...
if k1 in mapping : if more : return has_nested_keys ( mapping [ k1 ] , * more ) else : return True else : return False
def length ( self ) : """The total discretized length of every entity . Returns length : float , summed length of every entity"""
length = float ( sum ( i . length ( self . vertices ) for i in self . entities ) ) return length
def rst_to_json ( text ) : """I convert Restructured Text with field lists into Dictionaries ! TODO : Convert to text node approach ."""
records = [ ] last_type = None key = None data = { } directive = False lines = text . splitlines ( ) for index , line in enumerate ( lines ) : # check for directives if len ( line ) and line . strip ( ) . startswith ( ".." ) : directive = True continue # set the title if len ( line ) and ( l...
def _CreateImage ( media_service , opener , url ) : """Creates an image and uploads it to the server . Args : media _ service : a SudsServiceProxy instance for AdWords ' s MediaService . opener : an OpenerDirector instance . url : a str URL used to load image data . Returns : The image that was successf...
# Note : The utf - 8 decode is for 2to3 Python 3 compatibility . image_data = opener . open ( url ) . read ( ) . decode ( 'utf-8' ) image = { 'type' : 'IMAGE' , 'data' : image_data , 'xsi_type' : 'Image' } return media_service . upload ( image ) [ 0 ]
def run_subprocess ( command ) : """command is the command to run , as a string . runs a subprocess , returns stdout and stderr from the subprocess as strings ."""
x = subprocess . Popen ( command , shell = True , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) out , err = x . communicate ( ) out = out . decode ( 'utf-8' ) err = err . decode ( 'utf-8' ) if x . returncode != 0 : print ( 'STDERR from called program: {}' . format ( err ) ) print ( 'STDOUT from call...
def initialize_form ( self , instance , model , data = None , extra = None ) : """Takes a " finalized " query and generate it ' s form data"""
model_fields = self . get_fields_from_model ( model , self . _filter_fields ) forms = [ ] if instance : for field_data in instance . list_fields ( ) : forms . append ( AdvancedFilterQueryForm . _parse_query_dict ( field_data , model ) ) formset = AFQFormSetNoExtra if not extra else AFQFormSet self . fields_...
def from_xyz_string ( xyz_string ) : """Args : xyz _ string : string of the form ' x , y , z ' , ' - x , - y , z ' , ' - 2y + 1/2 , 3x + 1/2 , z - y + 1/2 ' , etc . Returns : SymmOp"""
rot_matrix = np . zeros ( ( 3 , 3 ) ) trans = np . zeros ( 3 ) toks = xyz_string . strip ( ) . replace ( " " , "" ) . lower ( ) . split ( "," ) re_rot = re . compile ( r"([+-]?)([\d\.]*)/?([\d\.]*)([x-z])" ) re_trans = re . compile ( r"([+-]?)([\d\.]+)/?([\d\.]*)(?![x-z])" ) for i , tok in enumerate ( toks ) : # build ...
def peek ( self , size = - 1 ) : """Return buffered data without advancing the file position . Always returns at least one byte of data , unless at EOF . The exact number of bytes returned is unspecified ."""
self . _check_can_read ( ) if self . _mode == _MODE_READ_EOF or not self . _fill_buffer ( ) : return b"" return self . _buffer
def get_port_stats ( port ) : """Iterate over connections and count states for specified port : param port : port for which stats are collected : return : Counter with port states"""
cnts = defaultdict ( int ) for c in psutil . net_connections ( ) : c_port = c . laddr [ 1 ] if c_port != port : continue status = c . status . lower ( ) cnts [ status ] += 1 return cnts
def encode ( cls , value ) : """convert a boolean value into something we can persist to redis . An empty string is the representation for False . : param value : bool : return : bytes"""
if value not in [ True , False ] : raise InvalidValue ( 'not a boolean' ) return b'1' if value else b''
def stop ( self ) : """Stop execution of all current and future payloads"""
if not self . running . wait ( 0.2 ) : return self . _logger . debug ( 'runner disabled: %s' , self ) with self . _lock : self . running . clear ( ) self . _stopped . wait ( )
def _worker_fn ( samples , batchify_fn , dataset = None ) : """Function for processing data in worker process ."""
# pylint : disable = unused - argument # it is required that each worker process has to fork a new MXIndexedRecordIO handle # preserving dataset as global variable can save tons of overhead and is safe in new process global _worker_dataset batch = batchify_fn ( [ _worker_dataset [ i ] for i in samples ] ) buf = io . By...
def delete_individual ( self , ind_obj ) : """Delete a case from the database Args : ind _ obj ( puzzle . models . Individual ) : initialized individual model"""
logger . info ( "Deleting individual {0} from database" . format ( ind_obj . ind_id ) ) self . session . delete ( ind_obj ) self . save ( ) return ind_obj
def update_edge_todo ( self , elev_fn , dem_proc ) : """Can figure out how to update the todo based on the elev filename"""
for key in self . edges [ elev_fn ] . keys ( ) : self . edges [ elev_fn ] [ key ] . set_data ( 'todo' , data = dem_proc . edge_todo )
def getVariances ( self ) : """get variances"""
var = [ ] var . append ( self . Cr . K ( ) . diagonal ( ) ) if self . bgRE : var . append ( self . Cg . K ( ) . diagonal ( ) ) var . append ( self . Cn . K ( ) . diagonal ( ) ) var = sp . array ( var ) return var
def path ( self , which = None ) : """Extend ` ` nailgun . entity _ mixins . Entity . path ` ` . The format of the returned path depends on the value of ` ` which ` ` : bulk _ resume / foreman _ tasks / api / tasks / bulk _ resume bulk _ search / foreman _ tasks / api / tasks / bulk _ search summary /...
if which in ( 'bulk_resume' , 'bulk_search' , 'summary' ) : return '{0}/{1}' . format ( super ( ForemanTask , self ) . path ( 'base' ) , which ) return super ( ForemanTask , self ) . path ( which )
def action_setattr ( ) : """Creates a setter that will set the action attribute with context ' s key for name to the current value ."""
def action_setattr ( value , context , ** _params ) : setattr ( context [ "action" ] , context [ "key" ] , value ) return _attr ( ) return action_setattr
def watch ( self , resource , namespace = None , name = None , label_selector = None , field_selector = None , resource_version = None , timeout = None ) : """Stream events for a resource from the Kubernetes API : param resource : The API resource object that will be used to query the API : param namespace : Th...
watcher = watch . Watch ( ) for event in watcher . stream ( resource . get , namespace = namespace , name = name , field_selector = field_selector , label_selector = label_selector , resource_version = resource_version , serialize = False , timeout_seconds = timeout ) : event [ 'object' ] = ResourceInstance ( resou...
def delete_collection_custom_resource_definition ( self , ** kwargs ) : # noqa : E501 """delete _ collection _ custom _ resource _ definition # noqa : E501 delete collection of CustomResourceDefinition # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_collection_custom_resource_definition_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . delete_collection_custom_resource_definition_with_http_info ( ** kwargs ) # noqa : E501 return d...
def rect ( self ) : """A dictionary with the size and location of the element ."""
if self . _w3c : return self . _execute ( Command . GET_ELEMENT_RECT ) [ 'value' ] else : rect = self . size . copy ( ) rect . update ( self . location ) return rect
def get_advanced_search_form ( self , data ) : """Hook to dynamically change the advanced search form"""
if self . get_advanced_search_form_class ( ) : self . _advanced_search_form = self . get_advanced_search_form_class ( ) ( data = data ) return self . _advanced_search_form
def repr_args ( args ) : """formats a list of function arguments prettily but as working code ( kwargs are tuples ( argname , argvalue )"""
res = [ ] for x in args : if isinstance ( x , tuple ) and len ( x ) == 2 : key , value = x # todo : exclude this key if value is its default res += [ "%s=%s" % ( key , repr_arg ( value ) ) ] else : res += [ repr_arg ( x ) ] return ', ' . join ( res )
def check_venv ( self ) : """Ensure we ' re inside a virtualenv ."""
if self . zappa : venv = self . zappa . get_current_venv ( ) else : # Just for ` init ` , when we don ' t have settings yet . venv = Zappa . get_current_venv ( ) if not venv : raise ClickException ( click . style ( "Zappa" , bold = True ) + " requires an " + click . style ( "active virtual environment" , bo...
def create_from_yaml ( self , name , yamlfile ) : """Create new environment using conda - env via a yaml specification file . Unlike other methods , this calls conda - env , and requires a named environment and uses channels as defined in rcfiles . Parameters name : string Environment name yamlfile : st...
logger . debug ( str ( ( name , yamlfile ) ) ) cmd_list = [ 'env' , 'create' , '-n' , name , '-f' , yamlfile , '--json' ] return self . _call_and_parse ( cmd_list )
def safe_dump ( data , abspath , pk_protocol = py23 . pk_protocol , enable_verbose = True ) : """A stable version of : func : ` dump ` , this method will silently overwrite existing file . There ' s a issue with : func : ` dump ` : If your program is interrupted while writing , you got an incomplete file , an...
abspath = lower_ext ( str ( abspath ) ) abspath_temp = "%s.tmp" % abspath dump ( data , abspath_temp , pk_protocol = pk_protocol , enable_verbose = enable_verbose ) shutil . move ( abspath_temp , abspath )
def revert_snapshot ( name , vm_snapshot = None , cleanup = False , ** kwargs ) : '''Revert snapshot to the previous from current ( if available ) or to the specific . : param name : domain name : param vm _ snapshot : name of the snapshot to revert : param cleanup : Remove all newer than reverted snapshots ....
ret = dict ( ) conn = __get_conn ( ** kwargs ) domain = _get_domain ( conn , name ) snapshots = domain . listAllSnapshots ( ) _snapshots = list ( ) for snap_obj in snapshots : _snapshots . append ( { 'idx' : _parse_snapshot_description ( snap_obj , unix_time = True ) [ 'created' ] , 'ptr' : snap_obj } ) snapshots =...
def move_into ( self , destination_folder ) : # type : ( Folder ) - > None """Move the Folder into a different folder . This makes the Folder provided a child folder of the destination _ folder . Raises : AuthError : Raised if Outlook returns a 401 , generally caused by an invalid or expired access token . ...
headers = self . headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self . id + '/move' payload = '{ "DestinationId": "' + destination_folder . id + '"}' r = requests . post ( endpoint , headers = headers , data = payload ) if check_response ( r ) : return_folder = r . json ( ) return se...
def from_bboxes ( bboxes ) : """Compute a BoundingBox enclosing all specified bboxes : param bboxes : a list of BoundingBoxes : return : BoundingBox"""
north = max ( [ b . north for b in bboxes ] ) south = min ( [ b . south for b in bboxes ] ) west = min ( [ b . west for b in bboxes ] ) east = max ( [ b . east for b in bboxes ] ) return BoundingBox ( north = north , west = west , south = south , east = east )
def update_gradients_diag ( self , dL_dKdiag , X ) : """derivative of the diagonal of the covariance matrix with respect to the parameters ."""
self . variance . gradient = np . sum ( dL_dKdiag ) self . period . gradient = 0 self . lengthscale . gradient = 0
def acc_difference ( points ) : """Computes the accelaration difference between each adjacent point Args : points ( : obj : ` Point ` ) Returns : : obj : ` list ` of int : Indexes of changepoints"""
data = [ 0 ] for before , after in pairwise ( points ) : data . append ( before . acc - after . acc ) return data
def cli ( env , identifier , details ) : """Invoices and all that mess"""
manager = AccountManager ( env . client ) top_items = manager . get_billing_items ( identifier ) title = "Invoice %s" % identifier table = formatting . Table ( [ "Item Id" , "Category" , "Description" , "Single" , "Monthly" , "Create Date" , "Location" ] , title = title ) table . align [ 'category' ] = 'l' table . alig...
def geo_name ( self ) : """Return a name of the state or county , or , for other lowever levels , the name of the level type in the county . : return :"""
if self . level == 'county' : return str ( self . county_name ) elif self . level == 'state' : return self . state_name else : if hasattr ( self , 'county' ) : return "{} in {}" . format ( self . level , str ( self . county_name ) ) elif hasattr ( self , 'state' ) : return "{} in {}" . f...
def open_tunnel ( * args , ** kwargs ) : """Open an SSH Tunnel , wrapper for : class : ` SSHTunnelForwarder ` Arguments : destination ( Optional [ tuple ] ) : SSH server ' s IP address and port in the format ( ` ` ssh _ address ` ` , ` ` ssh _ port ` ` ) Keyword Arguments : debug _ level ( Optional [ in...
# Attach a console handler to the logger or create one if not passed kwargs [ 'logger' ] = create_logger ( logger = kwargs . get ( 'logger' , None ) , loglevel = kwargs . pop ( 'debug_level' , None ) ) ssh_address_or_host = kwargs . pop ( 'ssh_address_or_host' , None ) # Check if deprecated arguments ssh _ address or s...
def cut_sequences_relative ( records , slices , record_id ) : """Cuts records to slices , indexed by non - gap positions in record _ id"""
with _record_buffer ( records ) as r : try : record = next ( i for i in r ( ) if i . id == record_id ) except StopIteration : raise ValueError ( "Record with id {0} not found." . format ( record_id ) ) new_slices = _update_slices ( record , slices ) for record in multi_cut_sequences ( r ...
def set_legend ( self , legend ) : """legend needs to be a list , tuple or None"""
assert ( isinstance ( legend , list ) or isinstance ( legend , tuple ) or legend is None ) if legend : self . legend = [ quote ( a ) for a in legend ] else : self . legend = None
def wait_for_port ( self , port , timeout = 10 , ** probe_kwargs ) : """block until specified port starts accepting connections , raises an exc ProbeTimeout if timeout is reached : param port : int , port number : param timeout : int or float ( seconds ) , time to wait for establishing the connection : para...
Probe ( timeout = timeout , fnc = functools . partial ( self . is_port_open , port ) , ** probe_kwargs ) . run ( )
def get_new_T_PI_parameters ( self , event ) : """calcualte statisics when temperatures are selected"""
# remember the last saved interpretation if "saved" in list ( self . pars . keys ( ) ) : if self . pars [ 'saved' ] : self . last_saved_pars = { } for key in list ( self . pars . keys ( ) ) : self . last_saved_pars [ key ] = self . pars [ key ] self . pars [ 'saved' ] = False t1 = self ....
def stripQuotes ( value ) : """Strip single or double quotes off string ; remove embedded quote pairs"""
if value [ : 1 ] == '"' : value = value [ 1 : ] if value [ - 1 : ] == '"' : value = value [ : - 1 ] # replace " " with " value = re . sub ( _re_doubleq2 , '"' , value ) elif value [ : 1 ] == "'" : value = value [ 1 : ] if value [ - 1 : ] == "'" : value = value [ : - 1 ] # rep...
def prompt_for_bilateral_choice ( self , prompt , option1 , option2 ) : """Prompt the user for a response that must be one of the two supplied choices . NOTE : The user input verification is case - insensitive , but will return the original case provided by the given options ."""
if prompt is None : prompt = '' prompt = prompt . rstrip ( ) + ' (' + option1 + '/' + option2 + ')' while True : user_input = self . __screen . input ( prompt ) if str ( user_input ) . lower ( ) == option1 . lower ( ) : return option1 elif str ( user_input ) . lower ( ) == option2 . lower ( ) : ...
def get_forwarders ( resolv = "resolv.conf" ) : """Find the forwarders in / etc / resolv . conf , default to 8.8.8.8 and 8.8.4.4"""
ns = [ ] if os . path . exists ( resolv ) : for l in open ( resolv ) : if l . startswith ( "nameserver" ) : address = l . strip ( ) . split ( " " , 2 ) [ 1 ] # forwarding to ourselves would be bad if not address . startswith ( "127" ) : ns . append ( addre...
def initialize ( self , max_batch_size : int , max_input_length : int , get_max_output_length_function : Callable ) : """Delayed construction of modules to ensure multiple Inference models can agree on computing a common maximum output length . : param max _ batch _ size : Maximum batch size . : param max _ i...
self . max_batch_size = max_batch_size self . max_input_length = max_input_length if self . max_input_length > self . training_max_seq_len_source : logger . warning ( "Model was only trained with sentences up to a length of %d, " "but a max_input_len of %d is used." , self . training_max_seq_len_source , self . max...
def _lim_moment ( self , u , order = 1 ) : """This method calculates the kth order limiting moment of the distribution . It is given by - E ( u ) = Integral ( - inf to u ) [ ( x ^ k ) * pdf ( x ) dx ] + ( u ^ k ) ( 1 - cdf ( u ) ) where , pdf is the probability density function and cdf is the cumulative den...
def fun ( x ) : return np . power ( x , order ) * self . factor . pdf ( x ) return ( integrate . quad ( fun , - np . inf , u ) [ 0 ] + np . power ( u , order ) * ( 1 - self . factor . cdf ( u ) ) )
def set_bounds ( self , start , stop ) : """Sets boundaries for all instruments in constellation"""
for instrument in self . instruments : instrument . bounds = ( start , stop )
def expand_defaults ( self , client = False , getenv = True , getshell = True ) : """Compile env , client _ env , shell and client _ shell commands"""
if not isinstance ( self . _default , six . string_types ) : self . expanded_default = self . _default else : self . expanded_default = coerce ( self . type , expand_defaults ( self . _default , client , getenv , getshell ) )
def Start ( self , seed_list : List [ str ] = None , skip_seeds : bool = False ) -> None : """Start connecting to the seed list . Args : seed _ list : a list of host : port strings if not supplied use list from ` protocol . xxx . json ` skip _ seeds : skip connecting to seed list"""
if not seed_list : seed_list = settings . SEED_LIST logger . debug ( "Starting up nodeleader" ) if not skip_seeds : logger . debug ( "Attempting to connect to seed list..." ) for bootstrap in seed_list : if not is_ip_address ( bootstrap ) : host , port = bootstrap . split ( ':' ) ...
def _update_route ( dcidr , router_ip , old_router_ip , vpc_info , con , route_table_id , update_reason ) : """Update an existing route entry in the route table ."""
instance = eni = None try : instance , eni = find_instance_and_eni_by_ip ( vpc_info , router_ip ) logging . info ( "--- updating existing route in RT '%s' " "%s -> %s (%s, %s) (old IP: %s, reason: %s)" % ( route_table_id , dcidr , router_ip , instance . id , eni . id , old_router_ip , update_reason ) ) try ...
def needs ( self , reglist ) : """Returns if this instruction need any of the registers in reglist ."""
if isinstance ( reglist , str ) : reglist = [ reglist ] reglist = single_registers ( reglist ) return len ( [ x for x in self . requires if x in reglist ] ) > 0
def _send_str ( self , cmd , args ) : """Format : { Command } { args length ( little endian ) } { str } Length : {4 } { 4 } { str length }"""
logger . debug ( "{} {}" . format ( cmd , args ) ) args = args . encode ( 'utf-8' ) le_args_len = self . _little_endian ( len ( args ) ) data = cmd . encode ( ) + le_args_len + args logger . debug ( "Send string: {}" . format ( data ) ) self . connection . write ( data )
def filter_strings_by_length ( strings : list , length : int ) -> list : """Returns string elements from a given list that have a specific length . Args : strings ( list ) : A list of strings . length ( int ) : The desired length of strings . Returns : list : A list of strings from the input list that mat...
filtered_strings = [ s for s in strings if len ( s ) == length ] return filtered_strings
def _expectation ( X , centers , weights , concentrations , posterior_type = "soft" ) : """Compute the log - likelihood of each datapoint being in each cluster . Parameters centers ( mu ) : array , [ n _ centers x n _ features ] weights ( alpha ) : array , [ n _ centers , ] ( alpha ) concentrations ( kappa ...
n_examples , n_features = np . shape ( X ) n_clusters , _ = centers . shape if n_features <= 50 : # works up to about 50 before numrically unstable vmf_f = _vmf_log else : vmf_f = _vmf_log_asymptotic f_log = np . zeros ( ( n_clusters , n_examples ) ) for cc in range ( n_clusters ) : f_log [ cc , : ] = vmf_f...
def __restore_mbi ( self , hProcess , new_mbi , old_mbi , bSkipMappedFiles , bSkipOnError ) : """Used internally by L { restore _ memory _ snapshot } ."""
# # print " Restoring % s - % s " % ( # # HexDump . address ( old _ mbi . BaseAddress , self . get _ bits ( ) ) , # # HexDump . address ( old _ mbi . BaseAddress + old _ mbi . RegionSize , # # self . get _ bits ( ) ) ) try : # Restore the region state . if new_mbi . State != old_mbi . State : if new_mbi . i...
def isense_parse ( self , filepath , modulename ) : """Parses the specified file from either memory , cached disk or full disk depending on whether the fetch is via SSH or not and how long it has been since we last checked the modification time of the file ."""
# We only want to check whether the file has been modified for reload from datetime import datetime if modulename not in self . _last_isense_check : self . _last_isense_check [ modulename ] = datetime . utcnow ( ) self . parse ( filepath , True ) else : elapsed = ( datetime . utcnow ( ) - self . _last_isens...
def max_width ( self ) : """Get maximum width of progress bar : rtype : int : returns : Maximum column width of progress bar"""
value , unit = float ( self . _width_str [ : - 1 ] ) , self . _width_str [ - 1 ] ensure ( unit in [ "c" , "%" ] , ValueError , "Width unit must be either 'c' or '%'" ) if unit == "c" : ensure ( value <= self . columns , ValueError , "Terminal only has {} columns, cannot draw " "bar of size {}." . format ( self . co...
def get_update_sql ( self , rows ) : """Returns SQL UPDATE for rows ` ` rows ` ` . . code - block : : sql UPDATE table _ name SET field1 = new _ values . field1 field2 = new _ values . field2 FROM ( VALUES (1 , ' value1 ' , ' value2 ' ) , (2 , ' value1 ' , ' value2 ' ) ) AS new _ values ( id , f...
field_names = self . get_field_names ( ) pk = field_names [ 0 ] update_field_names = field_names [ 1 : ] num_columns = len ( rows [ 0 ] ) if num_columns < 2 : raise Exception ( 'At least 2 fields must be passed to get_update_sql' ) all_null_indices = [ all ( row [ index ] is None for row in rows ) for index in rang...
def query ( self , tableClass , comparison = None , limit = None , offset = None , sort = None ) : """Return a generator of instances of C { tableClass } , or tuples of instances if C { tableClass } is a tuple of classes . Examples : : fastCars = s . query ( Vehicle , axiom . attributes . AND ( Vehicle ...
if isinstance ( tableClass , tuple ) : queryClass = MultipleItemQuery else : queryClass = ItemQuery return queryClass ( self , tableClass , comparison , limit , offset , sort )
def enr_at_fpr ( fg_vals , bg_vals , fpr = 0.01 ) : """Computes the enrichment at a specific FPR ( default 1 % ) . Parameters fg _ vals : array _ like The list of values for the positive set . bg _ vals : array _ like The list of values for the negative set . fpr : float , optional The FPR ( between 0...
pos = np . array ( fg_vals ) neg = np . array ( bg_vals ) s = scoreatpercentile ( neg , 100 - fpr * 100 ) neg_matches = float ( len ( neg [ neg >= s ] ) ) if neg_matches == 0 : return float ( "inf" ) return len ( pos [ pos >= s ] ) / neg_matches * len ( neg ) / float ( len ( pos ) )
def check_measurements_against_sensitivities ( self , magnitude , phase = 0 , return_plot = False ) : """Check for all configurations if the sensitivities add up to a given homogeneous model Parameters magnitude : float magnitude used for the homogeneous model phase : float , optional , default = 0 phas...
# generate a temporary tdMan instance tdm = tdMan ( grid = self . grid , configs = self . configs , ) tdm . add_homogeneous_model ( magnitude , phase ) measurements = tdm . measurements ( ) Z = measurements [ : , 0 ] * np . exp ( 1j * measurements [ : , 1 ] / 1000 ) results = [ ] for nr in range ( 0 , tdm . configs . n...
def ensure_dir ( directory : str ) -> None : """Create a directory if it doesn ' t exist ."""
if not os . path . isdir ( directory ) : LOG . debug ( f"Directory {directory} does not exist, creating it." ) os . makedirs ( directory )
def _recv_cf ( self , data ) : """Process a received ' Consecutive Frame ' frame"""
if self . rx_state != ISOTP_WAIT_DATA : return 0 self . rx_timer . cancel ( ) # CFs are never longer than the FF if len ( data ) > self . rx_ll_dl : return 1 # CFs have usually the LL _ DL length if len ( data ) < self . rx_ll_dl : # this is only allowed for the last CF if self . rx_len - self . rx_idx > se...
def get_blocked ( self ) : """Return a UserList of Redditors with whom the user has blocked ."""
url = self . reddit_session . config [ 'blocked' ] return self . reddit_session . request_json ( url )
def _to_rest_hide ( model , props ) : """Purge fields not allowed during a REST serialization This is done on fields with ` to _ rest = False ` ."""
hide = model . get_fields_by_prop ( 'to_rest' , False ) for field in hide : try : del props [ field ] except KeyError : continue
def entropy_bits_nrange ( minimum : Union [ int , float ] , maximum : Union [ int , float ] ) -> float : """Calculate the number of entropy bits in a range of numbers ."""
# Shannon : # d = fabs ( maximum - minimum ) # ent = - ( 1 / d ) * log ( 1 / d , 2 ) * d # Aprox form : log10 ( digits ) * log2(10) if not isinstance ( minimum , ( int , float ) ) : raise TypeError ( 'minimum can only be int or float' ) if not isinstance ( maximum , ( int , float ) ) : raise TypeError ( 'maximu...
def iMath ( image , operation , * args ) : """Perform various ( often mathematical ) operations on the input image / s . Additional parameters should be specific for each operation . See the the full iMath in ANTs , on which this function is based . ANTsR function : ` iMath ` Arguments image : ANTsImage ...
if operation not in _iMathOps : raise ValueError ( 'Operation not recognized' ) imagedim = image . dimension outimage = image . clone ( ) args = [ imagedim , outimage , operation , image ] + [ a for a in args ] processed_args = _int_antsProcessArguments ( args ) libfn = utils . get_lib_fn ( 'iMath' ) libfn ( proces...