signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def make_blastdb ( self ) : """Create a BLAST database of the primer file"""
# remove the path and the file extension for easier future globbing db = os . path . splitext ( self . formattedprimers ) [ 0 ] nhr = '{db}.nhr' . format ( db = db ) # add nhr for searching if not os . path . isfile ( str ( nhr ) ) : # Create the databases command = 'makeblastdb -in {primerfile} -parse_seqids -max_...
def AddModem ( self , name , properties ) : '''Convenience method to add a modem You have to specify a device name which must be a valid part of an object path , e . g . " mock _ ac " . For future extensions you can specify a " properties " array , but no extra properties are supported for now . Returns the...
path = '/' + name self . AddObject ( path , 'org.ofono.Modem' , { 'Online' : dbus . Boolean ( True , variant_level = 1 ) , 'Powered' : dbus . Boolean ( True , variant_level = 1 ) , 'Lockdown' : dbus . Boolean ( False , variant_level = 1 ) , 'Emergency' : dbus . Boolean ( False , variant_level = 1 ) , 'Manufacturer' : d...
def _start_selecting ( self , event ) : """Comienza con el proceso de seleccion ."""
self . _selecting = True canvas = self . _canvas x = canvas . canvasx ( event . x ) y = canvas . canvasy ( event . y ) self . _sstart = ( x , y ) if not self . _sobject : self . _sobject = canvas . create_rectangle ( self . _sstart [ 0 ] , self . _sstart [ 1 ] , x , y , dash = ( 3 , 5 ) , outline = '#0000ff' ) canv...
def analyzeWeightPruning ( args ) : """Multiprocess function used to analyze the impact of nonzeros and accuracy after pruning low weights and units with low dutycycle of a pre - trained model . : param args : tuple with the following arguments : - experiment path : The experiment results path - configurati...
path , params , minWeight , minDutycycle , position = args device = torch . device ( "cuda" if torch . cuda . is_available ( ) else "cpu" ) datadir = os . path . join ( params [ "datadir" ] , "speech_commands" ) testDataDir = os . path . join ( datadir , "test" ) # Initialize speech test dataset for this experiment n_m...
def histogram ( self , data , bins = 10 , color = 'w' , orientation = 'h' ) : """Calculate and show a histogram of data Parameters data : array - like Data to histogram . Currently only 1D data is supported . bins : int | array - like Number of bins , or bin edges . color : instance of Color Color of ...
self . _configure_2d ( ) hist = scene . Histogram ( data , bins , color , orientation ) self . view . add ( hist ) self . view . camera . set_range ( ) return hist
def _reduce_file_size_if_necessary ( fileName , maxSize ) : """This function shrinks a file . We remove only the middle part of a file , the file - start and the file - end remain unchanged ."""
fileSize = os . path . getsize ( fileName ) if maxSize is None : logging . debug ( "Size of logfile '%s' is %s bytes, size limit disabled." , fileName , fileSize ) return # disabled , nothing to do if fileSize < ( maxSize + 500 ) : logging . debug ( "Size of logfile '%s' is %s bytes, nothing to do." , fileN...
def connection_from_promised_list ( data_promise , args = None , ** kwargs ) : '''A version of ` connectionFromArray ` that takes a promised array , and returns a promised connection .'''
return data_promise . then ( lambda data : connection_from_list ( data , args , ** kwargs ) )
def search ( self , start = 0 , amount = 15 , order = 'asc' , concise = False , user = True , dependencies = True , comments = True , votes = True , filters = None ) : """Search the LEX : param start : Start at this result number : param amount : Number of results to return : param order : Ordering of the res...
if not filters or len ( filters . keys ( ) ) < 1 : raise Exception ( 'Need at least one filter in the "filters" dict' ) main = { 'start' : start , 'amount' : amount , 'order' : order , } if user : main [ 'user' ] = 'true' if dependencies : main [ 'dependencies' ] = 'true' if comments : main [ 'comments'...
def unsigned_request ( self , path , payload = None ) : """generic bitpay usigned wrapper passing a payload will do a POST , otherwise a GET"""
headers = { "content-type" : "application/json" , "accept" : "application/json" , "X-accept-version" : "2.0.0" } try : if payload : response = requests . post ( self . uri + path , verify = self . verify , data = json . dumps ( payload ) , headers = headers ) else : response = requests . get ( s...
def insert_or_append_blocks ( self , blocks ) : """Insert multiple blocks . If a block already exists , the data is appended . blocks must be a list of tuples where each tuple consists of ( namespace , offset , key , data )"""
start = 0 bulk_insert = self . bulk_insert blocks_len = len ( blocks ) select = 'SELECT ?,?,?,"",0' query = 'INSERT OR IGNORE INTO gauged_data (namespace, offset, ' '`key`, data, flags) ' execute = self . cursor . execute while start < blocks_len : rows = blocks [ start : start + bulk_insert ] params = [ ] ...
def _get_cookie ( self , name , domain ) : '''Return the cookie " name " for " domain " if found If there are mote than one , only the first is returned'''
for c in self . session . cookies : if c . name == name and c . domain == domain : return c return None
def _parse_kexgss_complete ( self , m ) : """Parse the SSH2 _ MSG _ KEXGSS _ COMPLETE message ( client mode ) . : param ` Message ` m : The content of the SSH2 _ MSG _ KEXGSS _ COMPLETE message"""
if self . transport . host_key is None : self . transport . host_key = NullHostKey ( ) self . f = m . get_mpint ( ) mic_token = m . get_string ( ) # This must be TRUE , if there is a GSS - API token in this message . bool = m . get_boolean ( ) srv_token = None if bool : srv_token = m . get_string ( ) if ( self ...
def export ( self , file_obj = None , file_type = None , ** kwargs ) : """Export the path to a file object or return data . Parameters file _ obj : None , str , or file object File object or string to export to file _ type : None or str Type of file : dxf , dict , svg Returns exported : bytes or str ...
return export_path ( self , file_type = file_type , file_obj = file_obj , ** kwargs )
def getLastModified ( self ) : "returns the GMT last - modified datetime or None"
last_modified = self . headers . get ( 'last-modified' ) if last_modified : last_modified = self . convertTimeString ( last_modified ) return last_modified
def decode ( input , fallback_encoding , errors = 'replace' ) : """Decode a single string . : param input : A byte string : param fallback _ encoding : An : class : ` Encoding ` object or a label string . The encoding to use if : obj : ` input ` does note have a BOM . : param errors : Type of error handli...
# Fail early if ` encoding ` is an invalid label . fallback_encoding = _get_encoding ( fallback_encoding ) bom_encoding , input = _detect_bom ( input ) encoding = bom_encoding or fallback_encoding return encoding . codec_info . decode ( input , errors ) [ 0 ] , encoding
def setup_table ( self ) : """Setup table"""
self . horizontalHeader ( ) . setStretchLastSection ( True ) self . adjust_columns ( ) self . columnAt ( 0 ) # Sorting columns self . setSortingEnabled ( False ) self . sortByColumn ( 0 , Qt . DescendingOrder )
def catch ( cls , catch_exception , config = 'default' ) : """Decorator class method catching exceptions raised by the wrapped member function . When exception is caught , the decorator waits for an amount of time specified in the ` ha _ config ` . : param catch _ exception : Exception class or tuple of excep...
def wrap ( method ) : @ functools . wraps ( method ) def wrapped_method ( self , * args , ** kwargs ) : assert isinstance ( self , HA ) delay_policy = self . ha_get_delay_policy ( config ) max_retries = self . ha_get_config ( config ) . max_retries for retries in itertools . coun...
def execute_concurrent ( session , statements_and_parameters , concurrency = 100 , raise_on_first_error = True , results_generator = False ) : """Executes a sequence of ( statement , parameters ) tuples concurrently . Each ` ` parameters ` ` item must be a sequence or : const : ` None ` . The ` concurrency ` pa...
if concurrency <= 0 : raise ValueError ( "concurrency must be greater than 0" ) if not statements_and_parameters : return [ ] executor = ConcurrentExecutorGenResults ( session , statements_and_parameters ) if results_generator else ConcurrentExecutorListResults ( session , statements_and_parameters ) return exe...
def parse_error ( self , response ) : "Parse an error response"
error_code = response . split ( ' ' ) [ 0 ] if error_code in self . EXCEPTION_CLASSES : response = response [ len ( error_code ) + 1 : ] exception_class = self . EXCEPTION_CLASSES [ error_code ] if isinstance ( exception_class , dict ) : exception_class = exception_class . get ( response , ResponseE...
def get_fqhostname ( ) : '''Returns the fully qualified hostname'''
# try getaddrinfo ( ) fqdn = None try : addrinfo = socket . getaddrinfo ( socket . gethostname ( ) , 0 , socket . AF_UNSPEC , socket . SOCK_STREAM , socket . SOL_TCP , socket . AI_CANONNAME ) for info in addrinfo : # info struct [ family , socktype , proto , canonname , sockaddr ] # On Windows ` canonname `...
def chart ( line , cell = None ) : """Generate charts with Google Charts . Use % chart - - help for more details ."""
parser = _commands . CommandParser ( prog = '%chart' , description = """ Generate an inline chart using Google Charts using the data in a Table, Query, dataframe, or list. Numerous types of charts are supported. Options for the charts can be specified in the cell body using YAML or JSON. """ ) for chart_type in [ 'anno...
def is_valid_mpls_label ( label ) : """Validates ` label ` according to MPLS label rules RFC says : This 20 - bit field . A value of 0 represents the " IPv4 Explicit NULL Label " . A value of 1 represents the " Router Alert Label " . A value of 2 represents the " IPv6 Explicit NULL Label " . A value of ...
if ( not isinstance ( label , numbers . Integral ) or ( 4 <= label <= 15 ) or ( label < 0 or label > 2 ** 20 ) ) : return False return True
def hide ( self ) : """Overrides Qt Method"""
for widget in self . replace_widgets : widget . hide ( ) QWidget . hide ( self ) self . visibility_changed . emit ( False ) if self . editor is not None : self . editor . setFocus ( ) self . clear_matches ( )
def setup_aiohttp_apispec ( app : web . Application , * , title : str = "API documentation" , version : str = "0.0.1" , url : str = "/api/docs/swagger.json" , request_data_name : str = "data" , swagger_path : str = None , static_path : str = '/static/swagger' , ** kwargs ) -> None : """aiohttp - apispec extension ....
AiohttpApiSpec ( url , app , request_data_name , title = title , version = version , swagger_path = swagger_path , static_path = static_path , ** kwargs )
def get_shared_volume_path ( container_map , vol , instance = None ) : """Resolves a volume alias of a container configuration or a tuple of two paths to the host and container paths . : param container _ map : Container map . : type container _ map : dockermap . map . config . main . ContainerMap : param vol...
if isinstance ( vol , HostVolume ) : c_path = resolve_value ( vol . path ) if is_path ( c_path ) : return c_path , get_host_path ( container_map . host . root , vol . host_path , instance ) raise ValueError ( "Host-container-binding must be described by two paths or one alias name." , vol ) alias = ...
def mkdir ( dir_path , user = None , group = None , mode = None ) : '''Ensure that a directory is available . CLI Example : . . code - block : : bash salt ' * ' file . mkdir / opt / jetty / context'''
dir_path = os . path . expanduser ( dir_path ) directory = os . path . normpath ( dir_path ) if not os . path . isdir ( directory ) : # If a caller such as managed ( ) is invoked with makedirs = True , make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise...
def _transform_to_2d ( t ) : """Convert vectors to column matrices , to always have a 2d shape ."""
t = np . asarray ( t ) dim = len ( t . shape ) assert dim <= 2 if dim < 2 : t = np . atleast_2d ( t ) . T return t
def create_load_balancer_listeners ( self , name , listeners ) : """Creates a Listener ( or group of listeners ) for an existing Load Balancer : type name : string : param name : The name of the load balancer to create the listeners for : type listeners : List of tuples : param listeners : Each tuple contai...
params = { 'LoadBalancerName' : name } for index , listener in enumerate ( listeners ) : i = index + 1 params [ 'Listeners.member.%d.LoadBalancerPort' % i ] = listener [ 0 ] params [ 'Listeners.member.%d.InstancePort' % i ] = listener [ 1 ] params [ 'Listeners.member.%d.Protocol' % i ] = listener [ 2 ] ...
def order_by_header ( table , headers ) : '''Convert a list of dicts to a list or OrderedDicts ordered by headers'''
ordered_table = [ ] for row in table : # Tricky list comprehension got tricky when needing special handling # Lets do this the simplest way we can : row = { k : v for k , v in row . items ( ) if k in headers } for h in headers : if h not in row : row [ h ] = '' ordered_row = OrderedDict ...
def _write_remaining_pages ( self ) : """Write outstanding IFDs and tags to file ."""
if not self . _tags or self . _truncate : return pageno = self . _shape [ 0 ] * self . _datashape [ 0 ] - 1 if pageno < 1 : self . _tags = None self . _datadtype = None self . _dataoffset = None self . _databytecounts = None return fh = self . _fh fhpos = fh . tell ( ) if fhpos % 2 : fh . wr...
def groups ( self ) -> typing . Iterator [ 'Group' ] : """Returns : generator of all groups in this country"""
for group_category in Mission . valid_group_categories : if group_category in self . _section_this_country . keys ( ) : for group_index in self . _section_this_country [ group_category ] [ 'group' ] : if group_index not in self . __groups [ group_category ] : self . __groups [ gr...
def calculate_Y ( sub_network , skip_pre = False ) : """Calculate bus admittance matrices for AC sub - networks ."""
if not skip_pre : calculate_dependent_values ( sub_network . network ) if sub_network . network . sub_networks . at [ sub_network . name , "carrier" ] != "AC" : logger . warning ( "Non-AC networks not supported for Y!" ) return branches = sub_network . branches ( ) buses_o = sub_network . buses_o network = ...
def get_active_sessions ( self ) : """Retrieves the active , unexpired sessions . : Returns : A generator of : class : ` ~ mwsessions . Session `"""
for last_timestamp , i , events in self . recently_active : yield Session ( events [ - 1 ] . user , unpack_events ( events ) )
def _calc_var_theta ( self ) : """Calculate an estimate of the var ( theta )"""
if self . decaying_prior : n_sampled = np . clip ( self . alpha_ + self . beta_ , 1 , np . inf ) prior_weight = 1 / n_sampled alpha = self . alpha_ + prior_weight * self . alpha_0 beta = self . beta_ + prior_weight * self . beta_0 else : alpha = self . alpha_ + self . alpha_0 beta = self . beta_...
def source ( self , source ) : """When the source gets updated , update the pane object"""
BaseView . source . fset ( self , source ) if self . main_pane : self . main_pane . object = self . contents self . label_pane . object = self . label
def echo ( text , silent = False , newline = True ) : """Print to the console Arguments : text ( str ) : Text to print to the console silen ( bool , optional ) : Whether or not to produce any output newline ( bool , optional ) : Whether or not to append a newline ."""
if silent : return print ( text ) if newline else sys . stdout . write ( text )
def add_comment ( self , case_obj , text , variant_id = None , username = None ) : """Add a comment to a variant or a case"""
comment = Comment ( text = text , username = username or 'Anonymous' , case = case_obj , # md5 sum of chrom , pos , ref , alt variant_id = variant_id ) self . session . add ( comment ) self . save ( ) return comment
def delete_model ( self ) : """Deletes the Amazon SageMaker models backing this predictor ."""
request_failed = False failed_models = [ ] for model_name in self . _model_names : try : self . sagemaker_session . delete_model ( model_name ) except Exception : # pylint : disable = broad - except request_failed = True failed_models . append ( model_name ) if request_failed : raise...
def _get_default_wrapper ( ) : """Return an available default VISA wrapper as a string ( ' ni ' or ' py ' ) . Use NI if the binary is found , else try to use pyvisa - py . If neither can be found , raise a ValueError ."""
from . ctwrapper import NIVisaLibrary ni_binary_found = bool ( NIVisaLibrary . get_library_paths ( ) ) if ni_binary_found : logger . debug ( 'The NI implementation available' ) return 'ni' else : logger . debug ( 'Did not find NI binary' ) try : get_wrapper_class ( 'py' ) # check for pyvisa - py ava...
def get_data ( self , query ) : """Fetch parsed data from a THREDDS server using NCSS . Requests data from the NCSS endpoint given the parameters in ` query ` and handles parsing of the returned content based on the mimetype . Parameters query : NCSSQuery The parameters to send to the NCSS endpoint Retu...
resp = self . get_query ( query ) return response_handlers ( resp , self . unit_handler )
def anchor ( self , anchor_enum_idx ) : """Set value of anchor attribute on ` ` < a : tcPr > ` ` child element"""
if anchor_enum_idx is None and self . tcPr is None : return tcPr = self . get_or_add_tcPr ( ) tcPr . anchor = anchor_enum_idx
def find ( entity , ** kwargs ) : """Return all TypedFields found on the input ` Entity ` that were initialized with the input * * kwargs . Example : > > > find ( myentity , multiple = True , type _ = Foo ) Note : TypedFields . _ _ init _ _ ( ) can accept a string or a class as a type _ argument , but t...
try : typedfields = entity . typed_fields ( ) except AttributeError : typedfields = iterfields ( entity . __class__ ) matching = [ x for x in typedfields if _matches ( x , kwargs ) ] return matching
def execute_with_client ( quiet = False , bootstrap_server = False , create_client = True ) : """Decorator that gets a client and performs an operation on it ."""
def wrapper ( f ) : def wrapper2 ( self , * args , ** kwargs ) : client = self . current_client ( quiet = quiet , bootstrap_server = bootstrap_server , create_client = create_client ) if client and client . running : return f ( self , client , * args , ** kwargs ) return wrapper2 ret...
def create_system ( self ) : """Get an instance of Api System Variables services facade ."""
return System ( self . networkapi_url , self . user , self . password , self . user_ldap )
def AuxPlane ( s1 , d1 , r1 ) : """Get Strike and dip of second plane . Adapted from MATLAB script ` bb . m < http : / / www . ceri . memphis . edu / people / olboyd / Software / Software . html > ` _ written by Andy Michael and Oliver Boyd ."""
r2d = 180 / np . pi z = ( s1 + 90 ) / r2d z2 = d1 / r2d z3 = r1 / r2d # slick vector in plane 1 sl1 = - np . cos ( z3 ) * np . cos ( z ) - np . sin ( z3 ) * np . sin ( z ) * np . cos ( z2 ) sl2 = np . cos ( z3 ) * np . sin ( z ) - np . sin ( z3 ) * np . cos ( z ) * np . cos ( z2 ) sl3 = np . sin ( z3 ) * np . sin ( z2 ...
def format_license ( template , lang ) : """Format the StringIO template object for specified lang string : return StringIO object formatted"""
if not lang : lang = 'txt' out = StringIO ( ) template . seek ( 0 ) # from the start of the buffer out . write ( LANG_CMT [ LANGS [ lang ] ] [ 0 ] + u'\n' ) for line in template . readlines ( ) : out . write ( LANG_CMT [ LANGS [ lang ] ] [ 1 ] + u' ' ) out . write ( line ) out . write ( LANG_CMT [ LANGS [ l...
def check_config ( config , data ) : '''Check config file inputs : param dict config : Configuration settings for the function'''
essential_keys = [ 'input_mmin' , 'b-value' , 'sigma-b' ] for key in essential_keys : if not key in config . keys ( ) : raise ValueError ( 'For KijkoSellevolBayes the key %s needs to ' 'be set in the configuation' % key ) if 'tolerance' not in config . keys ( ) or not config [ 'tolerance' ] : config [ '...
def create_widget ( self ) : """Create the underlying widget ."""
d = self . declaration self . widget = CheckBox ( self . get_context ( ) , None , d . style or "@attr/checkboxStyle" )
def set_smearing_function ( self , function_name ) : """function _ name = = ' Normal ' : smearing is done by normal distribution . ' Cauchy ' : smearing is done by Cauchy distribution ."""
if function_name == 'Cauchy' : self . _smearing_function = CauchyDistribution ( self . _sigma ) else : self . _smearing_function = NormalDistribution ( self . _sigma )
def populate_user ( self ) : """Populates the Django user object using the default bind credentials ."""
user = None try : # self . attrs will only be non - None if we were able to load this user # from the LDAP directory , so this filters out nonexistent users . if self . attrs is not None : self . _get_or_create_user ( force_populate = True ) user = self . _user except ldap . LDAPError as e : results...
def _do_request ( request ) : """Executes download request : param request : A request : type request : DownloadRequest : return : Response of the request : rtype : requests . Response"""
if request . request_type is RequestType . GET : return requests . get ( request . url , headers = request . headers ) if request . request_type is RequestType . POST : return requests . post ( request . url , data = json . dumps ( request . post_values ) , headers = request . headers ) raise ValueError ( 'Inva...
def _antisymm_12 ( C ) : """To get rid of NaNs produced by _ scalar2array , antisymmetrize the first two indices of operators where C _ ijkl = - C _ jikl"""
nans = np . isnan ( C ) C [ nans ] = - np . einsum ( 'jikl' , C ) [ nans ] return C
def _cache_key_select_analyst ( method , self , allow_blank = False , style = None ) : """This function returns the key used to decide if method select _ analyst has to be recomputed"""
key = update_timer ( ) , allow_blank , style return key
def check_response ( self , resp ) : """raise a descriptive exception on a " bad request " response"""
if resp . status_code == 400 : raise ApiException ( json . loads ( resp . content ) . get ( 'message' ) ) return resp
def get_hurricane_florence_abi ( base_dir = '.' , method = None , force = False , channels = range ( 1 , 17 ) , num_frames = 10 ) : """Get GOES - 16 ABI ( Meso sector ) data from 2018-09-11 13:00Z to 17:00Z . Args : base _ dir ( str ) : Base directory for downloaded files . method ( str ) : Force download met...
if method is None : method = 'gcsfs' if method not in [ 'gcsfs' ] : raise NotImplementedError ( "Demo data download method '{}' not " "implemented yet." . format ( method ) ) if isinstance ( num_frames , ( int , float ) ) : frame_slice = slice ( 0 , num_frames ) else : frame_slice = num_frames from . _g...
def _preprocess_typecheck ( argSig , argspecs , slf_or_clsm = False ) : """From a PEP 484 style type - tuple with types for * varargs and / or * * kw this returns a type - tuple containing Tuple [ tp , . . . ] and Dict [ str , kw - tp ] instead ."""
# todo : Maybe move also slf - logic here vargs = argspecs . varargs try : kw = argspecs . keywords except AttributeError : kw = argspecs . varkw try : kwonly = argspecs . kwonlyargs except AttributeError : kwonly = None if not vargs is None or not kw is None : arg_type_lst = list ( get_Tuple_params...
def _init_steps ( self , ) : """Given the flow config and everything else , create a list of steps to run , sorted by step number . : return : List [ StepSpec ]"""
self . _check_old_yaml_format ( ) config_steps = self . flow_config . steps self . _check_infinite_flows ( config_steps ) steps = [ ] for number , step_config in config_steps . items ( ) : specs = self . _visit_step ( number , step_config ) steps . extend ( specs ) return sorted ( steps , key = attrgetter ( "st...
def _validate_color ( self , color ) : """Validates color , raising error if invalid ."""
three_digit_pattern = compile ( "^[a-f0-9]{3}$" ) six_digit_pattern = compile ( "^[a-f0-9]{6}$" ) if not match ( three_digit_pattern , color ) and not match ( six_digit_pattern , color ) : raise InvalidColorError ( "{} is not a valid color" . format ( color ) ) return color
def get_minions ( ) : '''Return a list of minions'''
conn , mdb = _get_conn ( ret = None ) ret = [ ] name = mdb . saltReturns . distinct ( 'minion' ) ret . append ( name ) return ret
def write_newick ( rootnode , features = None , format = 1 , format_root_node = True , is_leaf_fn = None , dist_formatter = None , support_formatter = None , name_formatter = None ) : """Iteratively export a tree structure and returns its NHX representation ."""
newick = [ ] leaf = is_leaf_fn if is_leaf_fn else lambda n : not bool ( n . children ) for postorder , node in rootnode . iter_prepostorder ( is_leaf_fn = is_leaf_fn ) : if postorder : newick . append ( ")" ) if node . up is not None or format_root_node : newick . append ( format_node ( ...
def get_metadata ( self , params = None ) : """Metadata provides certain information about a Filehandle , and you can specify which pieces of information you will receive back by passing in optional parameters . ` ` ` python from filestack import Client client = Client ( ' API _ KEY ' ) filelink = client ...
metadata_url = "{CDN_URL}/{handle}/metadata" . format ( CDN_URL = CDN_URL , handle = self . handle ) response = utils . make_call ( metadata_url , 'get' , params = params , security = self . security ) return response . json ( )
def forward_message ( self , * args , ** kwargs ) : """See : func : ` forward _ message `"""
return forward_message ( * args , ** self . _merge_overrides ( ** kwargs ) ) . run ( )
def classpath_contents ( cls , targets , classpath_products , confs = ( 'default' , ) ) : """Provide a generator over the contents ( classes / resources ) of a classpath . : param targets : Targets to iterate the contents classpath for . : param ClasspathProducts classpath _ products : Product containing classp...
classpath_iter = cls . _classpath_iter ( classpath_products . get_for_targets ( targets ) , confs = confs , ) for f in cls . classpath_entries_contents ( classpath_iter ) : yield f
def child ( self , path ) : """Override the base implementation to inject the share ID our constructor was passed ."""
if self . _shareID is not None : self = url . URL . child ( self , self . _shareID ) self . _shareID = None return url . URL . child ( self , path )
def force_encoding ( value , encoding = 'utf-8' ) : """Return a string encoded in the provided encoding"""
if not isinstance ( value , ( str , unicode ) ) : value = str ( value ) if isinstance ( value , unicode ) : value = value . encode ( encoding ) elif encoding != 'utf-8' : value = value . decode ( 'utf-8' ) . encode ( encoding ) return value
def from_edge_pairs ( pairs , num_vertices = None , symmetric = False , weights = None ) : '''Constructor for Graph objects based on edges given as pairs of vertices . pairs : integer array - like with shape ( num _ edges , 2)'''
if not symmetric : if weights is None : return EdgePairGraph ( pairs , num_vertices = num_vertices ) row , col = np . asarray ( pairs ) . T row , weights = np . broadcast_arrays ( row , weights ) shape = None if num_vertices is None else ( num_vertices , num_vertices ) adj = ss . coo_matrix ...
def _resample_grid ( stations , nodes , lags , mindepth , maxdepth , corners ) : """Resample the lagtime grid to a given volume . For use if the grid from Grid2Time is too large or you want to run a faster , downsampled scan . : type stations : list : param stations : List of station names from in the for...
resamp_nodes = [ ] resamp_lags = [ ] # Cut the volume for i , node in enumerate ( nodes ) : # If the node is within the volume range , keep it if mindepth < float ( node [ 2 ] ) < maxdepth and corners . contains_point ( node [ 0 : 2 ] ) : resamp_nodes . append ( node ) resamp_lags . append ( [ lags ...
def shift ( self , h = 0 , m = 0 , s = 0 , ms = 0 , frames = None , fps = None ) : """Shift start and end times . See : meth : ` SSAFile . shift ( ) ` for full description ."""
delta = make_time ( h = h , m = m , s = s , ms = ms , frames = frames , fps = fps ) self . start += delta self . end += delta
def _build_graph ( self , tags ) : """Builds a graph from the entities included in the tags . Note this is used internally . Args : tags ( list ) : A list of the tags to include in graph Returns : graph : this is the resulting graph of the tagged entities ."""
graph = SimpleGraph ( ) for tag_index in xrange ( len ( tags ) ) : for entity_index in xrange ( len ( tags [ tag_index ] . get ( 'entities' ) ) ) : a_entity_name = graph_key_from_tag ( tags [ tag_index ] , entity_index ) tokens = self . tokenizer . tokenize ( tags [ tag_index ] . get ( 'entities' , ...
def hide ( self ) : """Call ` hide _ all ( ) ` on all known top widgets ."""
top = self . get_top_widget ( ) if isinstance ( top , ( list , tuple ) ) : for t in top : if t is not None : t . hide_all ( ) elif top is not None : top . hide_all ( )
def convert ( self , * args , ** kwargs ) : """Yes it is , thanks captain ."""
self . strings ( ) self . metadata ( ) # save file self . result . save ( self . output ( ) )
def add_option ( self , option ) : """Add an option to the message . : type option : Option : param option : the option : raise TypeError : if the option is not repeatable and such option is already present in the message"""
assert isinstance ( option , Option ) repeatable = defines . OptionRegistry . LIST [ option . number ] . repeatable if not repeatable : ret = self . _already_in ( option ) if ret : raise TypeError ( "Option : %s is not repeatable" , option . name ) else : self . _options . append ( option ) ...
def _update_structure_lines ( self ) : '''ATOM and HETATM lines may be altered by function calls . When this happens , this function should be called to keep self . structure _ lines up to date .'''
structure_lines = [ ] atom_chain_order = [ ] chain_atoms = { } for line in self . lines : linetype = line [ 0 : 6 ] if linetype == 'ATOM ' or linetype == 'HETATM' or linetype == 'TER ' : chain_id = line [ 21 ] self . residue_types . add ( line [ 17 : 20 ] . strip ( ) ) if missing_chai...
def encode ( self , value ) : ''': param value : value to encode'''
kassert . is_of_types ( value , Bits ) remainder = len ( value ) % 8 if remainder : value += Bits ( bin = '0' * ( 8 - remainder ) ) return value
def _read ( self , filename ) : """Internal routine that reads all data from the punch file ."""
data = { } parsers = [ FirstDataParser ( ) , CoordinateParser ( ) , EnergyGradParser ( ) , SkipApproxHessian ( ) , HessianParser ( ) , MassParser ( ) , ] with open ( filename ) as f : while True : line = f . readline ( ) if line == "" : break # at each line , a parsers checks if ...
def update ( self ) : """Update the user ' s details on Todoist . This method must be called to register any local attribute changes with Todoist . > > > from pytodoist import todoist > > > user = todoist . login ( ' john . doe @ gmail . com ' , ' password ' ) > > > user . full _ name = ' John Smith ' >...
args = { attr : getattr ( self , attr ) for attr in self . to_update } _perform_command ( self , 'user_update' , args )
def order_by ( self , * field_names ) : """Change translatable field names in an ` ` order _ by ` ` argument to translation fields for the current language ."""
if not self . _rewrite : return super ( MultilingualQuerySet , self ) . order_by ( * field_names ) new_args = [ ] for key in field_names : new_args . append ( rewrite_order_lookup_key ( self . model , key ) ) return super ( MultilingualQuerySet , self ) . order_by ( * new_args )
def __parse_relation ( ) : '''Gets and parses file'''
relation_filename = get_file ( 'relation.tsv' ) vertice_filename = get_file ( 'vertice.tsv' ) relation_textfile = open ( relation_filename , 'r' ) vertice_textfile = open ( vertice_filename , 'r' ) # Parse vertice : vertices = { } next ( vertice_textfile ) for line in vertice_textfile : tokens = line . strip ( ) . ...
def _make_wcsgeom_from_config ( config ) : """Build a ` WCS . Geom ` object from a fermipy coniguration file"""
binning = config [ 'binning' ] binsz = binning [ 'binsz' ] coordsys = binning . get ( 'coordsys' , 'GAL' ) roiwidth = binning [ 'roiwidth' ] proj = binning . get ( 'proj' , 'AIT' ) ra = config [ 'selection' ] [ 'ra' ] dec = config [ 'selection' ] [ 'dec' ] npix = int ( np . round ( roiwidth / binsz ) ) skydir = SkyCoor...
def bb ( self , * args , ** kwargs ) : """NAME : bb PURPOSE : return Galactic latitude INPUT : t - ( optional ) time at which to get bb obs = [ X , Y , Z ] - ( optional ) position of observer ( in kpc ) ( default = Object - wide default ) OR Orbit object that corresponds to the orbit of the observ...
_check_roSet ( self , kwargs , 'bb' ) lbd = self . _lbd ( * args , ** kwargs ) return lbd [ : , 1 ]
def set ( * dataset , ** kwargs ) : '''Sets the property or list of properties to the given value ( s ) for each dataset . dataset : string name of snapshot ( s ) , filesystem ( s ) , or volume ( s ) properties : string additional zfs properties pairs . . note : : properties are passed as key - value pa...
# # Configure command # NOTE : push filesystem properties filesystem_properties = salt . utils . args . clean_kwargs ( ** kwargs ) # # Set property res = __salt__ [ 'cmd.run_all' ] ( __utils__ [ 'zfs.zfs_command' ] ( command = 'set' , property_name = filesystem_properties . keys ( ) , property_value = filesystem_proper...
def _getPaddingDataToSectionOffset ( self ) : """Returns the data between the last section header and the begenning of data from the first section . @ rtype : str @ return : Data between last section header and the begenning of the first section ."""
start = self . _getPaddingToSectionOffset ( ) end = self . sectionHeaders [ 0 ] . pointerToRawData . value - start return self . _data [ start : start + end ]
def _find_channel ( connection , name , ctype , dtype , sample_rate , unique = False ) : """Internal method to find a single channel Parameters connection : ` nds2 . connection ` , optional open NDS2 connection to use for query name : ` str ` the name of the channel to find ctype : ` int ` the NDS2 ch...
# parse channel type from name , # e . g . ' L1 : GDS - CALIB _ STRAIN , reduced ' - > ' L1 : GDS - CALIB _ STRAIN ' , ' reduced ' name , ctype = _strip_ctype ( name , ctype , connection . get_protocol ( ) ) # query NDS2 found = connection . find_channels ( name , ctype , dtype , * sample_rate ) # if don ' t care about...
def _parseOatHeader ( self , data ) : """Returns the OatHeader"""
header = OatHeader . from_buffer ( data ) if header . magic != b'oat\n' : raise BinaryError ( 'No valid OAT file' ) key_value_store_bytes = ( c_ubyte * header . keyValueStoreSize ) . from_buffer ( data , sizeof ( OatHeader ) ) key_value_store = self . __parseKeyValueStore ( key_value_store_bytes ) return OatHeaderD...
def _get_included_file_path ( self , user_specified_path : str , current_processed_file_path : Path ) -> Path : '''Resolve user specified path to the local included file . : param user _ specified _ path : User specified string that represents the path to a local file : param current _ processed _ file _ path...
self . logger . debug ( f'Currently processed Markdown file: {current_processed_file_path}' ) included_file_path = ( current_processed_file_path . parent / user_specified_path ) . resolve ( ) self . logger . debug ( f'User-specified included file path: {included_file_path}' ) if ( self . working_dir . resolve ( ) in cu...
def build_delta_t_table ( delta_t_recent ) : """Build a table for interpolating Delta T . Given a 2xN array of recent Delta T values , whose element 0 is a sorted array of TT Julian dates and element 1 is Delta T values , this routine returns a more complete table by prepending two built - in data sources t...
ancient = load_bundled_npy ( 'morrison_stephenson_deltat.npy' ) historic = load_bundled_npy ( 'historic_deltat.npy' ) # Prefer USNO over Morrison and Stephenson where they overlap . historic_start_time = historic [ 0 , 0 ] i = searchsorted ( ancient [ 0 ] , historic_start_time ) bundled = concatenate ( [ ancient [ : , ...
def soft_bounce ( self , unique_id , configs = None ) : """Performs a soft bounce ( stop and start ) for the specified process : Parameter unique _ id : the name of the process"""
self . stop ( unique_id , configs ) self . start ( unique_id , configs )
def transformer_decoder ( decoder_input , encoder_output , decoder_self_attention_bias , encoder_decoder_attention_bias , hparams , cache = None , decode_loop_step = None , name = "decoder" , nonpadding = None , save_weights_to = None , make_image_summary = True , losses = None , layer_collection = None , recurrent_mem...
x = decoder_input attention_dropout_broadcast_dims = ( common_layers . comma_separated_string_to_integer_list ( getattr ( hparams , "attention_dropout_broadcast_dims" , "" ) ) ) mlperf_log . transformer_print ( key = mlperf_log . MODEL_HP_NUM_HIDDEN_LAYERS , value = hparams . num_decoder_layers or hparams . num_hidden_...
def showPopup ( self ) : """Displays the popup associated with this navigator ."""
nav = self . navigator ( ) nav . move ( self . mapToGlobal ( QPoint ( 0 , self . height ( ) ) ) ) nav . resize ( 400 , 250 ) nav . show ( )
def _maybe_cache ( arg , format , cache , convert_listlike ) : """Create a cache of unique dates from an array of dates Parameters arg : integer , float , string , datetime , list , tuple , 1 - d array , Series format : string Strftime format to parse time cache : boolean True attempts to create a cache...
from pandas import Series cache_array = Series ( ) if cache : # Perform a quicker unique check from pandas import Index unique_dates = Index ( arg ) . unique ( ) if len ( unique_dates ) < len ( arg ) : cache_dates = convert_listlike ( unique_dates . to_numpy ( ) , True , format ) cache_array...
def config_acl ( args ) : '''Retrieve access control list for a method configuration'''
r = fapi . get_repository_config_acl ( args . namespace , args . config , args . snapshot_id ) fapi . _check_response_code ( r , 200 ) acls = sorted ( r . json ( ) , key = lambda k : k [ 'user' ] ) return map ( lambda acl : '{0}\t{1}' . format ( acl [ 'user' ] , acl [ 'role' ] ) , acls )
def remove_root_family ( self , family_id ) : """Removes a root family . arg : family _ id ( osid . id . Id ) : the ` ` Id ` ` of a family raise : NotFound - ` ` family _ id ` ` not a root raise : NullArgument - ` ` family _ id ` ` is ` ` null ` ` raise : OperationFailed - unable to complete request raise...
# Implemented from template for # osid . resource . BinHierarchyDesignSession . remove _ root _ bin _ template if self . _catalog_session is not None : return self . _catalog_session . remove_root_catalog ( catalog_id = family_id ) return self . _hierarchy_session . remove_root ( id_ = family_id )
def _ic_decode ( self , msg ) : """IC : Send Valid Or Invalid User Code Format ."""
code = msg [ 4 : 16 ] if re . match ( r'(0\d){6}' , code ) : code = re . sub ( r'0(\d)' , r'\1' , code ) return { 'code' : code , 'user' : int ( msg [ 16 : 19 ] ) - 1 , 'keypad' : int ( msg [ 19 : 21 ] ) - 1 }
def get ( self , obj , key ) : """Retrieve ' key ' from an instance of a class which previously exposed it . @ param key : a hashable object , previously passed to L { Exposer . expose } . @ return : the object which was exposed with the given name on obj ' s key . @ raise MethodNotExposed : when the key in q...
if key not in self . _exposed : raise MethodNotExposed ( ) rightFuncs = self . _exposed [ key ] T = obj . __class__ seen = { } for subT in inspect . getmro ( T ) : for name , value in subT . __dict__ . items ( ) : for rightFunc in rightFuncs : if value is rightFunc : if name ...
def _build_block_element_list ( self ) : """Return a list of block elements , ordered from highest priority to lowest ."""
return sorted ( [ e for e in self . block_elements . values ( ) if not e . virtual ] , key = lambda e : e . priority , reverse = True )
def build_documentation_lines ( self ) : """Build a parameter documentation string that can appended to the docstring of a function that uses this : class : ` ~ . Filters ` instance to build filters ."""
return [ line_string for key in sorted ( self . keys ) for line_string in self . build_paramter_string ( key ) ]
def listFields ( self , template ) : """List all the attributes to be rendered from the template file : param template : The template to render . The template is actually a file , which is usually generated by : class : ` rtcclient . template . Templater . getTemplate ` and can also be modified by user acco...
try : temp_source = self . environment . loader . get_source ( self . environment , template ) return self . listFieldsFromSource ( temp_source ) except AttributeError : err_msg = "Invalid value for 'template'" self . log . error ( err_msg ) raise exception . BadValue ( err_msg )
async def write ( self , data ) : """This is an asyncio adapted version of pyserial write . It provides a non - blocking write and returns the number of bytes written upon completion : param data : Data to be written : return : Number of bytes written"""
# the secret sauce - it is in your future future = asyncio . Future ( ) result = None try : result = self . my_serial . write ( bytes ( [ ord ( data ) ] ) ) except serial . SerialException : # self . my _ serial . close ( ) # noinspection PyBroadException try : await self . close ( ) future . ca...
async def state ( gc : GroupControl ) : """Current group state ."""
state = await gc . state ( ) click . echo ( state ) click . echo ( "Full state info: %s" % repr ( state ) )
def add_element ( self , priority , element , count = None ) : """Adds an element with a specific priority . : param priority : priority of the element . : param element : element to add ."""
if count is None : count = next ( self . counter ) entry = [ priority , count , element ] self . element_finder [ element ] = entry heapq . heappush ( self . pq , entry )