signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def logging_syslog_server_port ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) logging = ET . SubElement ( config , "logging" , xmlns = "urn:brocade.com:mgmt:brocade-ras" ) syslog_server = ET . SubElement ( logging , "syslog-server" ) syslogip_key = ET . SubElement ( syslog_server , "syslogip" ) syslogip_key . text = kwargs . pop ( 'syslogip' ) use_vrf_key = ET ...
def autoscroll ( self , autoscroll ) : """Autoscroll will ' right justify ' text from the cursor if set True , otherwise it will ' left justify ' the text ."""
if autoscroll : self . displaymode |= LCD_ENTRYSHIFTINCREMENT else : self . displaymode &= ~ LCD_ENTRYSHIFTINCREMENT self . write8 ( LCD_ENTRYMODESET | self . displaymode )
def _reads_per_position ( bam_in , loci_file , out_dir ) : """Create input for compute entropy"""
data = Counter ( ) a = pybedtools . BedTool ( bam_in ) b = pybedtools . BedTool ( loci_file ) c = a . intersect ( b , s = True , bed = True , wo = True ) for line in c : end = int ( line [ 1 ] ) + 1 + int ( line [ 2 ] ) if line [ 5 ] == "+" else int ( line [ 1 ] ) + 1 start = int ( line [ 1 ] ) + 1 if line [ 5 ...
def validate ( ref_intervals , ref_pitches , ref_velocities , est_intervals , est_pitches , est_velocities ) : """Checks that the input annotations have valid time intervals , pitches , and velocities , and throws helpful errors if not . Parameters ref _ intervals : np . ndarray , shape = ( n , 2) Array of ...
transcription . validate ( ref_intervals , ref_pitches , est_intervals , est_pitches ) # Check that velocities have the same length as intervals / pitches if not ref_velocities . shape [ 0 ] == ref_pitches . shape [ 0 ] : raise ValueError ( 'Reference velocities must have the same length as ' 'pitches and intervals...
def emoticons ( string ) : '''emot . emoticons is use to detect emoticons from text > > > text = " I love python 👨 : - ) " > > > emot . emoticons ( text ) > > > { ' value ' : [ ' : - ) ' ] , ' location ' : [ [ 16 , 19 ] ] , ' mean ' : [ ' Happy face smiley ' ] , ' flag ' : True }'''
__entities = [ ] flag = True try : pattern = u'(' + u'|' . join ( k for k in emo_unicode . EMOTICONS ) + u')' __entities = [ ] __value = [ ] __location = [ ] matches = re . finditer ( r"%s" % pattern , str ( string ) ) for et in matches : __value . append ( et . group ( ) . strip ( ) ) ...
def learn_q ( self , predicted_q_arr , real_q_arr ) : '''Infernce Q - Value . Args : predicted _ q _ arr : ` np . ndarray ` of predicted Q - Values . real _ q _ arr : ` np . ndarray ` of real Q - Values .'''
self . __predicted_q_arr_list . append ( predicted_q_arr ) while len ( self . __predicted_q_arr_list ) > self . __seq_len : self . __predicted_q_arr_list = self . __predicted_q_arr_list [ 1 : ] while len ( self . __predicted_q_arr_list ) < self . __seq_len : self . __predicted_q_arr_list . append ( self . __pre...
def export ( self , file_path = None , export_format = None ) : """Write the users to a file ."""
with io . open ( file_path , mode = 'w' , encoding = "utf-8" ) as export_file : if export_format == 'yaml' : import yaml yaml . safe_dump ( self . to_dict ( ) , export_file , default_flow_style = False ) elif export_format == 'json' : export_file . write ( text_type ( json . dumps ( self...
def list ( self , bank ) : '''Lists entries stored in the specified bank . : param bank : The name of the location inside the cache which will hold the key and its associated data . : return : An iterable object containing all bank entries . Returns an empty iterator if the bank doesn ' t exists . : r...
fun = '{0}.list' . format ( self . driver ) return self . modules [ fun ] ( bank , ** self . _kwargs )
def createLearningRateScheduler ( self , optimizer ) : """Creates the learning rate scheduler and attach the optimizer"""
if self . lr_scheduler_class is None : return None return self . lr_scheduler_class ( optimizer , ** self . lr_scheduler_params )
def prepare_query ( self , symbol , start_date , end_date ) : """Method returns prepared request query for Yahoo YQL API ."""
query = 'select * from yahoo.finance.historicaldata where symbol = "%s" and startDate = "%s" and endDate = "%s"' % ( symbol , start_date , end_date ) return query
def get_song ( self , netease = False ) : """获取歌曲 , 对外统一接口"""
song = self . _playlist . get ( True ) self . hash_sid [ song [ 'sid' ] ] = True # 去重 self . get_netease_song ( song , netease ) # 判断是否网易320k self . _playingsong = song return song
def stop_proxy ( self ) : """Stop the mitmproxy"""
self . runner . info_log ( "Stopping proxy..." ) if hasattr ( self , 'proxy_pid' ) : try : kill_by_pid ( self . proxy_pid ) except psutil . NoSuchProcess : pass
def _extract_and_handle_mpbgp_withdraws ( self , mp_unreach_attr ) : """Extracts withdraws advertised in the given update message ' s * MpUnReachNlri * attribute . Assumes MPBGP capability is enabled . Parameters : - update _ msg : ( Update ) is assumed to be checked for all bgp message errors . Extract...
msg_rf = mp_unreach_attr . route_family # Check if this route family is among supported route families . if msg_rf not in SUPPORTED_GLOBAL_RF : LOG . info ( 'Received route family %s is not supported. ' 'Ignoring withdraw routes on this UPDATE message.' , msg_rf ) return w_nlris = mp_unreach_attr . withdrawn_ro...
def fragmentate ( self , give_only_index = False , use_lookup = None ) : """Get the indices of non bonded parts in the molecule . Args : give _ only _ index ( bool ) : If ` ` True ` ` a set of indices is returned . Otherwise a new Cartesian instance . use _ lookup ( bool ) : Use a lookup variable for : me...
if use_lookup is None : use_lookup = settings [ 'defaults' ] [ 'use_lookup' ] fragments = [ ] pending = set ( self . index ) self . get_bonds ( use_lookup = use_lookup ) while pending : index = self . get_coordination_sphere ( pending . pop ( ) , use_lookup = True , n_sphere = float ( 'inf' ) , only_surface = F...
def parse_n_jobs ( s ) : """This function parses a " math " - like string as a function of CPU count . It is useful for specifying the number of jobs . For example , on an 8 - core machine : : assert parse _ n _ jobs ( ' 0.5 * n ' ) = = 4 assert parse _ n _ jobs ( ' 2n ' ) = = 16 assert parse _ n _ jobs (...
n_jobs = None N = cpu_count ( ) if isinstance ( s , int ) : n_jobs = s elif isinstance ( s , float ) : n_jobs = int ( s ) elif isinstance ( s , str ) : m = re . match ( r'(\d*(?:\.\d*)?)?(\s*\*?\s*n)?$' , s . strip ( ) ) if m is None : raise ValueError ( 'Unable to parse n_jobs="{}"' . format ( ...
def _run_program ( self , bin , fastafile , params = None ) : """Run HMS and predict motifs from a FASTA file . Parameters bin : str Command used to run the tool . fastafile : str Name of the FASTA input file . params : dict , optional Optional parameters . For some of the tools required parameters ...
params = self . _parse_params ( params ) default_params = { "width" : 10 } if params is not None : default_params . update ( params ) fgfile , summitfile , outfile = self . _prepare_files ( fastafile ) current_path = os . getcwd ( ) os . chdir ( self . tmpdir ) cmd = "{} -i {} -w {} -dna 4 -iteration 50 -chain 20 -...
def get_chunks ( sequence , chunk_size ) : """Split sequence into chunks . : param list sequence : : param int chunk _ size :"""
return [ sequence [ idx : idx + chunk_size ] for idx in range ( 0 , len ( sequence ) , chunk_size ) ]
def _apply_auth ( self , view_func ) : """Apply decorator to authenticate the user who is making the request . : param view _ func : The flask view func ."""
@ functools . wraps ( view_func ) def decorated ( * args , ** kwargs ) : if not self . auth : return view_func ( * args , ** kwargs ) auth_data = self . auth . get_authorization ( ) if auth_data is None : return self . _handle_authentication_error ( ) if not self . _authentication_callba...
def build ( tasks , worker_scheduler_factory = None , detailed_summary = False , ** env_params ) : """Run internally , bypassing the cmdline parsing . Useful if you have some luigi code that you want to run internally . Example : . . code - block : : python luigi . build ( [ MyTask1 ( ) , MyTask2 ( ) ] , lo...
if "no_lock" not in env_params : env_params [ "no_lock" ] = True luigi_run_result = _schedule_and_run ( tasks , worker_scheduler_factory , override_defaults = env_params ) return luigi_run_result if detailed_summary else luigi_run_result . scheduling_succeeded
def extract_index ( index_data , global_index = False ) : '''Instantiates and returns an AllIndex object given a valid index configuration CLI Example : salt myminion boto _ dynamodb . extract _ index index'''
parsed_data = { } keys = [ ] for key , value in six . iteritems ( index_data ) : for item in value : for field , data in six . iteritems ( item ) : if field == 'hash_key' : parsed_data [ 'hash_key' ] = data elif field == 'hash_key_data_type' : parsed_d...
def request ( method = 'GET' ) : """send restful post http request decorator Provide a brief way to manipulate restful api , : param method : : class : ` str ` , : return : : class : ` func `"""
def decorator ( func ) : @ functools . wraps ( func ) def action ( self , * args , ** kwargs ) : f = furl ( self . server ) path , body = func ( self , * args , ** kwargs ) # deal with query string query = dict ( ) if isinstance ( path , tuple ) : path , query...
def _check_configs ( self ) : """Reloads the configuration files ."""
configs = set ( self . _find_configs ( ) ) known_configs = set ( self . configs . keys ( ) ) new_configs = configs - known_configs for cfg in ( known_configs - configs ) : self . log . debug ( "Compass configuration has been removed: " + cfg ) del self . configs [ cfg ] for cfg in new_configs : self . log ....
def user_tickets_assigned ( self , user_id , external_id = None , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / tickets # allowed - for"
api_path = "/api/v2/users/{user_id}/tickets/assigned.json" api_path = api_path . format ( user_id = user_id ) api_query = { } if "query" in kwargs . keys ( ) : api_query . update ( kwargs [ "query" ] ) del kwargs [ "query" ] if external_id : api_query . update ( { "external_id" : external_id , } ) return se...
def detalhe ( self , posicao = 0 ) : """Retorna o detalhe de um CEP da última lista de resultados"""
handle = self . _url_open ( 'detalheCEPAction.do' , { 'Metodo' : 'detalhe' , 'TipoCep' : 2 , 'Posicao' : posicao + 1 , 'CEP' : '' } ) html = handle . read ( ) return self . _parse_detalhe ( html )
def list_distribute_contents_simple ( input_list , function = lambda x : x ) : # type : ( List , Callable [ [ Any ] , Any ] ) - > List """Distribute the contents of a list eg . [ 1 , 1 , 1 , 2 , 2 , 3 ] - > [ 1 , 2 , 3 , 1 , 2 , 1 ] . List can contain complex types like dictionaries in which case the function can...
dictionary = dict ( ) for obj in input_list : dict_of_lists_add ( dictionary , function ( obj ) , obj ) output_list = list ( ) i = 0 done = False while not done : found = False for key in sorted ( dictionary ) : if i < len ( dictionary [ key ] ) : output_list . append ( dictionary [ key ...
def _cnn_filter ( in_file , vrn_files , data ) : """Perform CNN filtering on input VCF using pre - trained models ."""
# tensor _ type = " reference " # 1D , reference sequence tensor_type = "read_tensor" # 2D , reads , flags , mapping quality score_file = _cnn_score_variants ( in_file , tensor_type , data ) return _cnn_tranch_filtering ( score_file , vrn_files , tensor_type , data )
def dissect ( self , data ) : """Dissect the field . : param bytes data : The data to extract the field value from : return : The rest of the data not used to dissect the field value : rtype : bytes"""
size = struct . calcsize ( "B" ) if len ( data ) < size : raise NotEnoughData ( "Not enough data to decode field '%s' value" % self . name ) curve_type = struct . unpack ( "B" , data [ : size ] ) [ 0 ] if curve_type == 0x03 : self . _value = ECParametersNamedCurveField ( "none" ) data = self . _value . diss...
def get_annotation ( self , id_ ) : """Data for a specific annotation ."""
endpoint = "annotations/{id}" . format ( id = id_ ) return self . _make_request ( endpoint )
def compile_string ( string , compiler_class = Compiler , ** kwargs ) : """Compile a single string , and return a string of CSS . Keyword arguments are passed along to the underlying ` Compiler ` ."""
compiler = compiler_class ( ** kwargs ) return compiler . compile_string ( string )
def rpc_v2 ( self , cmd , arg_format , result_format , * args , ** kw ) : """Send an RPC call to this module , interpret the return value according to the result _ type kw argument . Unless raise keyword is passed with value False , raise an RPCException if the command is not successful . v2 enforces the us...
if args : packed_args = pack_rpc_payload ( arg_format , list ( args ) ) elif arg_format == "" : packed_args = b'' else : raise RPCInvalidArgumentsError ( "Arg format expects arguments to be present" , arg_format = arg_format , args = args ) passed_kw = dict ( ) if 'timeout' in kw : passed_kw [ 'timeout'...
def _inspect_and_map ( self , identifier ) : """example response : u ' comment ' : u ' ' , u ' virtual _ size ' : 566087127, u ' container ' : u ' a2ea130e8c7a945823c804253c20f7c877376c69a36311a0cc614d5c455f645f ' , u ' os ' : u ' linux ' , u ' parent ' : u ' 14e75a5684c2fabb7db24d92bdda09d11da1179a7d86ab...
# validate try : response = normalize_keys ( self . client . inspect_image ( identifier ) ) self . comment = response [ 'comment' ] if response [ 'comment' ] else None self . id = response [ "id" ] self . virtual_size = response [ 'virtual_size' ] self . container = response [ 'container' ] self...
def to_primitive ( self , value , context = None ) : """Schematics serializer override If epoch _ date is true then convert the ` datetime . datetime ` object into an epoch ` int ` ."""
if context and context . get ( 'epoch_date' ) : epoch = dt ( 1970 , 1 , 1 ) value = ( value - epoch ) . total_seconds ( ) return int ( value ) elif context and context . get ( 'datetime_date' ) : return value else : return super ( Type , self ) . to_primitive ( value , context )
def slamdunkFilterStatsTable ( self ) : """Take the parsed filter stats from Slamdunk and add it to a separate table"""
headers = OrderedDict ( ) headers [ 'mapped' ] = { 'namespace' : 'Slamdunk' , 'title' : '{} Mapped' . format ( config . read_count_prefix ) , 'description' : '# mapped reads ({})' . format ( config . read_count_desc ) , 'shared_key' : 'read_count' , 'min' : 0 , 'format' : '{:,.2f}' , 'suffix' : config . read_count_pref...
def expand_nested ( self , cats ) : """Populate widget with nested catalogs"""
down = '│' right = '└──' def get_children ( parent ) : return [ e ( ) for e in parent . _entries . values ( ) if e . _container == 'catalog' ] if len ( cats ) == 0 : return cat = cats [ 0 ] old = list ( self . options . items ( ) ) name = next ( k for k , v in old if v == cat ) index = next ( i for i , ( k , v ...
def predict_size_distribution_component_models ( self , model_names , input_columns , output_columns , metadata_cols , data_mode = "forecast" , location = 6 ) : """Make predictions using fitted size distribution models . Args : model _ names : Name of the models for predictions input _ columns : Data columns ...
groups = self . size_distribution_models . keys ( ) predictions = pd . DataFrame ( self . data [ data_mode ] [ "combo" ] [ metadata_cols ] ) for group in groups : group_idxs = self . data [ data_mode ] [ "combo" ] [ self . group_col ] == group group_count = np . count_nonzero ( group_idxs ) print ( self . s...
def numRegisteredByRole ( self ) : '''Return a dictionary listing registrations by all available roles ( including no role )'''
role_list = list ( self . availableRoles ) + [ None , ] return { getattr ( x , 'name' , None ) : self . numRegisteredForRole ( x ) for x in role_list }
def disable_auto_login ( ) : '''. . versionadded : : 2016.3.0 Disables auto login on the machine Returns : bool : ` ` True ` ` if successful , otherwise ` ` False ` ` CLI Example : . . code - block : : bash salt ' * ' user . disable _ auto _ login'''
# Remove the kcpassword file cmd = 'rm -f /etc/kcpassword' __salt__ [ 'cmd.run' ] ( cmd ) # Remove the entry from the defaults file cmd = [ 'defaults' , 'delete' , '/Library/Preferences/com.apple.loginwindow.plist' , 'autoLoginUser' ] __salt__ [ 'cmd.run' ] ( cmd ) return True if not get_auto_login ( ) else False
def _GetRecord ( self , offset , record_size ) : """Retrieve a single record from the file . Args : offset : offset from start of input _ dat where header starts record _ size : length of the header according to file ( untrusted ) Returns : A dict containing a single browser history record ."""
record_header = "<4sLQQL" get4 = lambda x : struct . unpack ( "<L" , self . input_dat [ x : x + 4 ] ) [ 0 ] url_offset = struct . unpack ( "B" , self . input_dat [ offset + 52 : offset + 53 ] ) [ 0 ] if url_offset in [ 0xFF , 0xFE ] : return None data_offset = get4 ( offset + 68 ) data_size = get4 ( offset + 72 ) s...
def flux_components ( self , kwargs_light , n_grid = 400 , delta_grid = 0.01 , deltaPix = 0.05 , type = "lens" ) : """computes the total flux in each component of the model : param kwargs _ light : : param n _ grid : : param delta _ grid : : return :"""
flux_list = [ ] R_h_list = [ ] x_grid , y_grid = util . make_grid ( numPix = n_grid , deltapix = delta_grid ) kwargs_copy = copy . deepcopy ( kwargs_light ) for k , kwargs in enumerate ( kwargs_light ) : if 'center_x' in kwargs_copy [ k ] : kwargs_copy [ k ] [ 'center_x' ] = 0 kwargs_copy [ k ] [ 'c...
def CopyToDateTimeString ( self ) : """Copies the time elements to a date and time string . Returns : str : date and time value formatted as : " YYYY - MM - DD hh : mm : ss " or " YYYY - MM - DD hh : mm : ss . # # # # # " or None if time elements are missing . Raises : ValueError : if the precision value ...
if self . _number_of_seconds is None or self . fraction_of_second is None : return None precision_helper = precisions . PrecisionHelperFactory . CreatePrecisionHelper ( self . _precision ) return precision_helper . CopyToDateTimeString ( self . _time_elements_tuple , self . fraction_of_second )
def tables_with_counts ( self ) : """Return the number of entries in all table ."""
table_to_count = lambda t : self . count_rows ( t ) return zip ( self . tables , map ( table_to_count , self . tables ) )
def write ( self , file ) : r"""Save CAPTCHA image in given filepath . Property calls self . image and saves image contents in a file , returning CAPTCHA text and filepath as a tuple . See : image . : param file : Path to file , where CAPTCHA image will be saved . : returns : ` ` tuple ` ` ( CAPTCHA tex...
text , image = self . image image . save ( file , format = self . format ) return ( text , file )
def get_client_ip ( environ ) : # type : ( Dict [ str , str ] ) - > Optional [ Any ] """Infer the user IP address from various headers . This cannot be used in security sensitive situations since the value may be forged from a client , but it ' s good enough for the event payload ."""
try : return environ [ "HTTP_X_FORWARDED_FOR" ] . split ( "," ) [ 0 ] . strip ( ) except ( KeyError , IndexError ) : pass try : return environ [ "HTTP_X_REAL_IP" ] except KeyError : pass return environ . get ( "REMOTE_ADDR" )
def format_phone_number ( number ) : """Formats a phone number in international notation . : param number : str or phonenumber object : return : str"""
if not isinstance ( number , phonenumbers . PhoneNumber ) : number = phonenumbers . parse ( number ) return phonenumbers . format_number ( number , phonenumbers . PhoneNumberFormat . INTERNATIONAL )
def report ( self , filename = None ) : """Write details of each versioned target to file : param string filename : file to write out the report to Fields in the report : invocation _ id : A sequence number that increases each time a task is invoked task _ name : The name of the task targets _ hash : an i...
# TODO ( zundel ) set report to stream to the file filename = filename or self . _filename if filename : # Usually the directory exists from reporting initialization , but not if clean - all was a goal . with safe_open ( filename , 'w' ) as writer : writer . write ( 'invocation_id,task_name,targets_hash,tar...
def get_sites ( self , entry ) : """Return the sites linked in HTML ."""
try : index_url = reverse ( 'zinnia:entry_archive_index' ) except NoReverseMatch : index_url = '' return format_html_join ( ', ' , '<a href="{}://{}{}" target="blank">{}</a>' , [ ( settings . PROTOCOL , site . domain , index_url , conditional_escape ( site . name ) ) for site in entry . sites . all ( ) ] )
def get_topic_triggers ( rs , topic , thats , depth = 0 , inheritance = 0 , inherited = False ) : """Recursively scan a topic and return a list of all triggers . Arguments : rs ( RiveScript ) : A reference to the parent RiveScript instance . topic ( str ) : The original topic name . thats ( bool ) : Are we ...
# Break if we ' re in too deep . if depth > rs . _depth : rs . _warn ( "Deep recursion while scanning topic inheritance" ) # Keep in mind here that there is a difference between ' includes ' and # ' inherits ' - - topics that inherit other topics are able to OVERRIDE # triggers that appear in the inherited topic . ...
def construct ( path , name = None ) : "Selects an appropriate CGroup subclass for the given CGroup path ."
name = name if name else path . split ( "/" ) [ 4 ] classes = { "memory" : Memory , "cpu" : CPU , "cpuacct" : CPUAcct } constructor = classes . get ( name , CGroup ) log . debug ( "Chose %s for: %s" , constructor . __name__ , path ) return constructor ( path , name )
def adddeploykey ( self , project_id , title , key ) : """Creates a new deploy key for a project . : param project _ id : project id : param title : title of the key : param key : the key itself : return : true if success , false if not"""
data = { 'id' : project_id , 'title' : title , 'key' : key } request = requests . post ( '{0}/{1}/keys' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return reque...
def stc_system_info ( stc_addr ) : """Return dictionary of STC and API information . If a session already exists , then use it to get STC information and avoid taking the time to start a new session . A session is necessary to get STC information ."""
stc = stchttp . StcHttp ( stc_addr ) sessions = stc . sessions ( ) if sessions : # If a session already exists , use it to get STC information . stc . join_session ( sessions [ 0 ] ) sys_info = stc . system_info ( ) else : # Create a new session to get STC information . stc . new_session ( 'anonymous' ) ...
def extend ( base : Dict [ Any , Any ] , extension : Dict [ Any , Any ] ) -> Dict [ Any , Any ] : '''Extend base by updating with the extension . * * Arguments * * : ` ` base ` ` : dictionary to have keys updated or added : ` ` extension ` ` : dictionary to update base with * * Return Value ( s ) * * Resu...
_ = copy . deepcopy ( base ) _ . update ( extension ) return _
def makedict ( self , dictfile , fnamefobject ) : """stuff file data into the blank dictionary"""
# fname = ' . / exapmlefiles / 5ZoneDD . idf ' # fname = ' . / 1ZoneUncontrolled . idf ' if isinstance ( dictfile , Idd ) : localidd = copy . deepcopy ( dictfile ) dt , dtls = localidd . dt , localidd . dtls else : dt , dtls = self . initdict ( dictfile ) # astr = mylib2 . readfile ( fname ) astr = fnamefob...
def _delete_partition ( self , tenant_id , tenant_name ) : """Function to delete a service partition ."""
self . dcnm_obj . delete_partition ( tenant_name , fw_const . SERV_PART_NAME )
def opens ( self , tag = None , fromdate = None , todate = None ) : """Gets total counts of recipients who opened your emails . This is only recorded when open tracking is enabled for that email ."""
return self . call ( "GET" , "/stats/outbound/opens" , tag = tag , fromdate = fromdate , todate = todate )
def get_gradebook_column_ids_by_gradebooks ( self , gradebook_ids ) : """Gets the list of ` ` GradebookColumn Ids ` ` corresponding to a list of ` ` Gradebooks ` ` . arg : gradebook _ ids ( osid . id . IdList ) : list of gradebook ` ` Ids ` ` return : ( osid . id . IdList ) - list of gradebook column ` ` Ids ...
# Implemented from template for # osid . resource . ResourceBinSession . get _ resource _ ids _ by _ bins id_list = [ ] for gradebook_column in self . get_gradebook_columns_by_gradebooks ( gradebook_ids ) : id_list . append ( gradebook_column . get_id ( ) ) return IdList ( id_list )
def ssh ( gandi , resource , login , identity , wipe_key , wait , args ) : """Spawn an SSH session to virtual machine . Resource can be a Hostname or an ID"""
if '@' in resource : ( login , resource ) = resource . split ( '@' , 1 ) if wipe_key : gandi . iaas . ssh_keyscan ( resource ) if wait : gandi . iaas . wait_for_sshd ( resource ) gandi . iaas . ssh ( resource , login , identity , args )
def listFieldsFromWorkitem ( self , copied_from , keep = False ) : """List all the attributes to be rendered directly from some to - be - copied workitems More details , please refer to : class : ` rtcclient . template . Templater . listFieldsFromWorkitem `"""
return self . templater . listFieldsFromWorkitem ( copied_from , keep = keep )
def get_pfam_accession_numbers_from_pdb_id ( self , pdb_id ) : '''Note : an alternative is to use the RCSB API e . g . http : / / www . rcsb . org / pdb / rest / hmmer ? structureId = 1cdg .'''
pdb_id = pdb_id . lower ( ) if self . pdb_chain_to_pfam_mapping . get ( pdb_id ) : return self . pdb_chain_to_pfam_mapping [ pdb_id ] . copy ( )
def get_addon_id ( addonxml ) : '''Parses an addon id from the given addon . xml filename .'''
xml = parse ( addonxml ) addon_node = xml . getElementsByTagName ( 'addon' ) [ 0 ] return addon_node . getAttribute ( 'id' )
def binary_shader ( self , output_jar , main , jar , custom_rules = None , jvm_options = None ) : """Yields an ` Executor . Runner ` that will perform shading of the binary ` jar ` when ` run ( ) ` . The default rules will ensure the ` main ` class name is un - changed along with a minimal set of support classe...
all_rules = self . assemble_binary_rules ( main , jar , custom_rules = custom_rules ) return self . binary_shader_for_rules ( output_jar , jar , all_rules , jvm_options = jvm_options )
def output ( ret , ** kwargs ) : '''Display the output as table . Args : * nested _ indent : integer , specify the left alignment . * has _ header : boolean specifying if header should be displayed . Default : True . * row _ delimiter : character to separate rows . Default : ` ` _ ` ` . * delim : characte...
# to facilitate re - use if 'opts' in kwargs : global __opts__ # pylint : disable = W0601 __opts__ = kwargs . pop ( 'opts' ) # Prefer kwargs before opts base_indent = kwargs . get ( 'nested_indent' , 0 ) or __opts__ . get ( 'out.table.nested_indent' , 0 ) rows_key = kwargs . get ( 'rows_key' ) or __opts__ ....
def chat_post_message ( self , channel , text , ** params ) : """chat . postMessage This method posts a message to a channel . https : / / api . slack . com / methods / chat . postMessage"""
method = 'chat.postMessage' params . update ( { 'channel' : channel , 'text' : text , } ) return self . _make_request ( method , params )
def split_sentences_spacy ( text , language_model = 'en' ) : r"""You must download a spacy language model with python - m download ' en ' The default English language model for spacy tends to be a lot more agressive than NLTK ' s punkt : > > > split _ sentences _ nltk ( " Hi Ms . Lovelace . \ nI ' m a wanna - \...
doc = nlp ( text ) sentences = [ ] if not hasattr ( doc , 'sents' ) : logger . warning ( "Using NLTK sentence tokenizer because SpaCy language model hasn't been loaded" ) return split_sentences_nltk ( text ) for w , span in enumerate ( doc . sents ) : sent = '' . join ( doc [ i ] . string for i in range ( s...
def hasField ( cls , fieldName ) : """returns True / False wether the collection has field K in it ' s schema . Use the dot notation for the nested fields : address . street"""
path = fieldName . split ( "." ) v = cls . _fields for k in path : try : v = v [ k ] except KeyError : return False return True
def is_zero_user ( self ) : """返回当前用户是否为三零用户 , 其实是四零 : 赞同0 , 感谢0 , 提问0 , 回答0. : return : 是否是三零用户 : rtype : bool"""
return self . upvote_num + self . thank_num + self . question_num + self . answer_num == 0
def getBox ( box , pagesize ) : """Parse sizes by corners in the form : < X - Left > < Y - Upper > < Width > < Height > The last to values with negative values are interpreted as offsets form the right and lower border ."""
box = str ( box ) . split ( ) if len ( box ) != 4 : raise Exception ( "box not defined right way" ) x , y , w , h = [ getSize ( pos ) for pos in box ] return getCoords ( x , y , w , h , pagesize )
def createEditor ( self , parent , option , index ) : """Returns the widget used to change data from the model and can be reimplemented to customize editing behavior . Reimplemented from QStyledItemDelegate ."""
logger . debug ( "ConfigItemDelegate.createEditor, parent: {!r}" . format ( parent . objectName ( ) ) ) assert index . isValid ( ) , "sanity check failed: invalid index" cti = index . model ( ) . getItem ( index ) editor = cti . createEditor ( self , parent , option ) return editor
def maximum_size_bytes ( self ) : """Gets the biggest disk drive : returns size in bytes ."""
return utils . max_safe ( [ device . get ( 'CapacityBytes' ) for device in self . devices if device . get ( 'CapacityBytes' ) is not None ] )
def mutagen_call ( action , path , func , * args , ** kwargs ) : """Call a Mutagen function with appropriate error handling . ` action ` is a string describing what the function is trying to do , and ` path ` is the relevant filename . The rest of the arguments describe the callable to invoke . We require a...
try : return func ( * args , ** kwargs ) except mutagen . MutagenError as exc : log . debug ( u'%s failed: %s' , action , six . text_type ( exc ) ) raise UnreadableFileError ( path , six . text_type ( exc ) ) except Exception as exc : # Isolate bugs in Mutagen . log . debug ( u'%s' , traceback . format_...
def resolve ( self , definitions ) : """Resolve named references to other WSDL objects . Can be safely called multiple times . @ param definitions : A definitions object . @ type definitions : L { Definitions }"""
if not self . __resolved : self . do_resolve ( definitions ) self . __resolved = True
def do_cancel ( self , taskid : int ) -> None : """Cancel an indicated task"""
task = task_by_id ( taskid , self . _loop ) if task : fut = asyncio . run_coroutine_threadsafe ( cancel_task ( task ) , loop = self . _loop ) fut . result ( timeout = 3 ) self . _sout . write ( 'Cancel task %d\n' % taskid ) else : self . _sout . write ( 'No task %d\n' % taskid )
def rms ( self , x , params = ( ) ) : """Returns root mean square value of f ( x , params )"""
internal_x , internal_params = self . pre_process ( np . asarray ( x ) , np . asarray ( params ) ) if internal_params . ndim > 1 : raise NotImplementedError ( "Parameters should be constant." ) result = np . empty ( internal_x . size // self . nx ) for idx in range ( internal_x . shape [ 0 ] ) : result [ idx ] ...
def valid_conkey ( self , conkey ) : """Check that the conkey is a valid one . Return True if valid . A condition key is valid if it is one in the _ COND _ PREFIXES list . With the prefix removed , the remaining string must be either a number or the empty string ."""
for prefix in _COND_PREFIXES : trailing = conkey . lstrip ( prefix ) if trailing == '' and conkey : # conkey is not empty return True try : int ( trailing ) return True except ValueError : pass return False
def matches ( self , a , b , ** config ) : """The message must match by package"""
package_a = self . processor . _u2p ( a [ 'msg' ] [ 'update' ] [ 'title' ] ) [ 0 ] package_b = self . processor . _u2p ( b [ 'msg' ] [ 'update' ] [ 'title' ] ) [ 0 ] if package_a != package_b : return False return True
def main ( argv = None ) : """The entry point of the application ."""
if argv is None : argv = sys . argv [ 1 : ] usage = '\n\n\n' . join ( __doc__ . split ( '\n\n\n' ) [ 1 : ] ) version = 'Gitpress ' + __version__ # Parse options args = docopt ( usage , argv = argv , version = version ) # Execute command try : return execute ( args ) except RepositoryNotFoundError as ex : er...
def almost_unitary ( gate : Gate ) -> bool : """Return true if gate tensor is ( almost ) unitary"""
res = ( gate @ gate . H ) . asoperator ( ) N = gate . qubit_nb return np . allclose ( asarray ( res ) , np . eye ( 2 ** N ) , atol = TOLERANCE )
def extract_names ( sender ) : """Tries to extract sender ' s names from ` From : ` header . It could extract not only the actual names but e . g . the name of the company , parts of email , etc . > > > extract _ names ( ' Sergey N . Obukhov < serobnic @ mail . ru > ' ) [ ' Sergey ' , ' Obukhov ' , ' serobn...
sender = to_unicode ( sender , precise = True ) # Remove non - alphabetical characters sender = "" . join ( [ char if char . isalpha ( ) else ' ' for char in sender ] ) # Remove too short words and words from " black " list i . e . # words like ` ru ` , ` gmail ` , ` com ` , ` org ` , etc . sender = [ word for word in ...
def validate_code_path ( valid_paths , code_path , ** kw ) : """Raise an exception if code _ path is not one of our whitelisted valid _ paths ."""
root , name = code_path . split ( ':' , 1 ) if name not in valid_paths [ root ] : raise ValueError ( "%r is not a valid code_path" % code_path )
def Fritzsche ( SG , Tavg , L = None , D = None , P1 = None , P2 = None , Q = None , Ts = 288.7 , Ps = 101325. , Zavg = 1 , E = 1 ) : r'''Calculation function for dealing with flow of a compressible gas in a pipeline with the Fritzsche formula . Can calculate any of the following , given all other inputs : * ...
# Rational ( ' 2.827E - 3 ' ) / ( 3600*24 ) * ( 1000 ) * * Rational ( ' 2.69 ' ) * ( 1000 ) * * Rational ( ' 0.538 ' ) * 1000 / ( 1000 * * 2 ) * * Rational ( ' 0.538 ' ) c5 = 93.50009798751128188757518688244137811221 # 14135*10 * * ( 57/125 ) / 432 c2 = 0.8587 c3 = 0.538 c4 = 2.69 if Q is None and ( None not in [ L , D...
def _getPowerupInterfaces ( self ) : """Collect powerup interfaces this object declares that it can be installed on ."""
powerupInterfaces = getattr ( self . __class__ , "powerupInterfaces" , ( ) ) pifs = [ ] for x in powerupInterfaces : if isinstance ( x , type ( Interface ) ) : # just an interface pifs . append ( ( x , 0 ) ) else : # an interface and a priority pifs . append ( x ) m = getattr ( self , "__getPowe...
def send_ether_over_wpa ( self , pkt , ** kwargs ) : """Send an Ethernet packet using the WPA channel Extra arguments will be ignored , and are just left for compatibility"""
payload = LLC ( ) / SNAP ( ) / pkt [ Ether ] . payload dest = pkt . dst if dest == "ff:ff:ff:ff:ff:ff" : self . send_wpa_to_group ( payload , dest ) else : assert dest == self . client self . send_wpa_to_client ( payload )
def normalized_messages ( self , no_field_name = '_entity' ) : """Return all the error messages as a dictionary"""
if isinstance ( self . messages , dict ) : return self . messages if not self . field_names : return { no_field_name : self . messages } return dict ( ( name , self . messages ) for name in self . field_names )
def as_dict ( self , join = '.' ) : """Returns the error as a path to message dictionary . Paths are joined with the ` ` join ` ` string ."""
if self . path : path = [ str ( node ) for node in self . path ] else : path = '' return { join . join ( path ) : self . message }
def destroy ( self , request , pk = None ) : '''For DELETE actions , actually deactivate the user , don ' t delete .'''
user = self . get_object ( ) user . is_active = False user . save ( ) return Response ( status = status . HTTP_204_NO_CONTENT )
def ytickangle ( self , angle , index = 1 ) : """Set the angle of the y - axis tick labels . Parameters value : int Angle in degrees index : int , optional Y - axis index Returns Chart"""
self . layout [ 'yaxis' + str ( index ) ] [ 'tickangle' ] = angle return self
def make_response ( status , headers , payload , environ ) : """This function generates an appropriate response object for this async mode ."""
return Response ( body = payload , status = int ( status . split ( ) [ 0 ] ) , headers = headers )
def is_transport_reaction_formulae ( rxn ) : """Return boolean if a reaction is a transport reaction ( from formulae ) . Parameters rxn : cobra . Reaction The metabolic reaction under investigation ."""
# Collecting criteria to classify transporters by . rxn_reactants = set ( [ met . formula for met in rxn . reactants ] ) rxn_products = set ( [ met . formula for met in rxn . products ] ) # Looking for formulas that stay the same on both side of the reaction . transported_mets = [ formula for formula in rxn_reactants i...
def get_x ( self , var , coords = None ) : """Get the centers of the triangles in the x - dimension Parameters % ( CFDecoder . get _ y . parameters ) s Returns % ( CFDecoder . get _ y . returns ) s"""
if coords is None : coords = self . ds . coords # first we try the super class ret = super ( UGridDecoder , self ) . get_x ( var , coords ) # but if that doesn ' t work because we get the variable name in the # dimension of ` var ` , we use the means of the triangles if ret is None or ret . name in var . dims : ...
def nodes_to_dict_of_dataframes ( grid , nodes , lv_transformer = True ) : """Creates dictionary of dataframes containing grid Parameters grid : ding0 . Network nodes : list of ding0 grid components objects Nodes of the grid graph lv _ transformer : bool , True Toggle transformer representation in power...
generator_instances = [ MVStationDing0 , GeneratorDing0 ] # TODO : MVStationDing0 has a slack generator cos_phi_load = cfg_ding0 . get ( 'assumptions' , 'cos_phi_load' ) cos_phi_feedin = cfg_ding0 . get ( 'assumptions' , 'cos_phi_gen' ) srid = int ( cfg_ding0 . get ( 'geo' , 'srid' ) ) load_in_generation_case = cfg_din...
def is_domain_class_member_attribute ( ent , attr_name ) : """Checks if the given attribute name is a entity attribute of the given registered resource ."""
attr = get_domain_class_attribute ( ent , attr_name ) return attr . kind == RESOURCE_ATTRIBUTE_KINDS . MEMBER
def coords_on_grid ( self , x , y ) : """Snap coordinates on the grid with integer coordinates"""
if isinstance ( x , float ) : x = int ( self . _round ( x ) ) if isinstance ( y , float ) : y = int ( self . _round ( y ) ) if not self . _y_coord_down : y = self . _extents - y return x , y
def colorize ( text , ansi = True ) : """If the client wants ansi , replace the tokens with ansi sequences - - otherwise , simply strip them out ."""
if ansi : text = text . replace ( '^^' , '\x00' ) for token , code in _ANSI_CODES : text = text . replace ( token , code ) text = text . replace ( '\x00' , '^' ) else : text = strip_caret_codes ( text ) return text
def rename ( dct , mapping ) : """Rename the keys of a dictionary with the given mapping > > > rename ( { " a " : 1 , " BBB " : 2 } , { " a " : " AAA " } ) { ' AAA ' : 1 , ' BBB ' : 2}"""
def _block ( memo , key ) : if key in dct : memo [ mapping [ key ] ] = dct [ key ] return memo else : return memo return reduce ( _block , mapping , omit ( dct , * mapping . keys ( ) ) )
def get_lowest_probable_prepared_certificate_in_view ( self , view_no ) -> Optional [ int ] : """Return lowest pp _ seq _ no of the view for which can be prepared but choose from unprocessed PRE - PREPAREs and PREPAREs ."""
# TODO : Naive implementation , dont need to iterate over the complete # data structures , fix this later seq_no_pp = SortedList ( ) # pp _ seq _ no of PRE - PREPAREs # pp _ seq _ no of PREPAREs with count of PREPAREs for each seq_no_p = set ( ) for ( v , p ) in self . prePreparesPendingPrevPP : if v == view_no : ...
def average_series ( self , * args , ** kwargs ) -> InfoArray : """Average the actual time series of the | Variable | object for all time points . Method | IOSequence . average _ series | works similarly as method | Variable . average _ values | of class | Variable | , from which we borrow some examples . H...
try : if not self . NDIM : array = self . series else : mask = self . get_submask ( * args , ** kwargs ) if numpy . any ( mask ) : weights = self . refweights [ mask ] weights /= numpy . sum ( weights ) series = self . series [ : , mask ] a...
async def terminateInstance ( self , * args , ** kwargs ) : """Terminate an instance Terminate an instance in a specified region This method is ` ` experimental ` `"""
return await self . _makeApiCall ( self . funcinfo [ "terminateInstance" ] , * args , ** kwargs )
def install ( self , package , force = False , upgrade = False , options = None ) : """Installs the given package into this virtual environment , as specified in pip ' s package syntax or a tuple of ( ' name ' , ' ver ' ) , only if it is not already installed . Some valid examples : ' Django ' ' Django = = ...
if self . readonly : raise VirtualenvReadonlyException ( ) if options is None : options = [ ] if isinstance ( package , tuple ) : package = '==' . join ( package ) if package . startswith ( ( '-e' , '-r' ) ) : package_args = package . split ( ) else : package_args = [ package ] if not ( force or upg...
def input_files_to_stage ( self ) : """Return a list of the input files needed by this link . For ` Link ` sub - classes this will return the union of all the input files of each internal ` Link ` . That is to say this will include files produced by one ` Link ` in a ` Chain ` and used as input to another `...
ret_list = [ ] for key , val in self . file_dict . items ( ) : # For input files we only want files that were marked as input if val & FileFlags . in_stage_mask == FileFlags . in_stage_mask : ret_list . append ( key ) return ret_list
def oei ( cn , ns = None , lo = None , di = None , iq = None , ico = None , pl = None , fl = None , fs = None , ot = None , coe = None , moc = None ) : # pylint : disable = too - many - arguments , redefined - outer - name """This function is a wrapper for : meth : ` ~ pywbem . WBEMConnection . OpenEnumerateInsta...
return CONN . OpenEnumerateInstances ( cn , ns , LocalOnly = lo , DeepInheritance = di , IncludeQualifiers = iq , IncludeClassOrigin = ico , PropertyList = pl , FilterQueryLanguage = fl , FilterQuery = fs , OperationTimeout = ot , ContinueOnError = coe , MaxObjectCount = moc )
def WalkChildren ( elem ) : """Walk the XML tree of children below elem , returning each in order ."""
for child in elem . childNodes : yield child for elem in WalkChildren ( child ) : yield elem