signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def show ( config_file = False ) : '''Return a list of sysctl parameters for this minion CLI Example : . . code - block : : bash salt ' * ' sysctl . show'''
roots = ( 'kern' , 'vm' , 'vfs' , 'net' , 'hw' , 'machdep' , 'user' , 'ddb' , 'proc' , 'emul' , 'security' , 'init' ) cmd = 'sysctl -ae' ret = { } out = __salt__ [ 'cmd.run' ] ( cmd , output_loglevel = 'trace' ) comps = [ '' ] for line in out . splitlines ( ) : if any ( [ line . startswith ( '{0}.' . format ( root ...
def _hash_task ( task ) : """Returns a unique hash for identify a task and its params"""
params = task . get ( "params" ) if params : params = json . dumps ( sorted ( list ( task [ "params" ] . items ( ) ) , key = lambda x : x [ 0 ] ) ) # pylint : disable = no - member full = [ str ( task . get ( x ) ) for x in [ "path" , "interval" , "dailytime" , "weekday" , "monthday" , "queue" ] ] full . extend ( [...
def display_message ( self , clear , beep , timeout , line1 , line2 ) : """Display a message on all of the keypads in this area ."""
self . _elk . send ( dm_encode ( self . _index , clear , beep , timeout , line1 , line2 ) )
def set_build_image ( self ) : """Overrides build _ image for worker , to be same as in orchestrator build"""
current_platform = platform . processor ( ) orchestrator_platform = current_platform or 'x86_64' current_buildimage = self . get_current_buildimage ( ) for plat , build_image in self . build_image_override . items ( ) : self . log . debug ( 'Overriding build image for %s platform to %s' , plat , build_image ) s...
def parse_coach_ec_df ( infile ) : """Parse the EC . dat output file of COACH and return a dataframe of results EC . dat contains the predicted EC number and active residues . The columns are : PDB _ ID , TM - score , RMSD , Sequence identity , Coverage , Confidence score , EC number , and Active site residue...
ec_df = pd . read_table ( infile , delim_whitespace = True , names = [ 'pdb_template' , 'tm_score' , 'rmsd' , 'seq_ident' , 'seq_coverage' , 'c_score' , 'ec_number' , 'binding_residues' ] ) ec_df [ 'pdb_template_id' ] = ec_df [ 'pdb_template' ] . apply ( lambda x : x [ : 4 ] ) ec_df [ 'pdb_template_chain' ] = ec_df [ '...
def noisy_moment ( self , moment : 'cirq.Moment' , system_qubits : Sequence [ 'cirq.Qid' ] ) -> 'cirq.OP_TREE' : """Adds noise to the operations from a moment . Args : moment : The moment to add noise to . system _ qubits : A list of all qubits in the system . Returns : An OP _ TREE corresponding to the n...
if not hasattr ( self . noisy_moments , '_not_overridden' ) : return self . noisy_moments ( [ moment ] , system_qubits ) if not hasattr ( self . noisy_operation , '_not_overridden' ) : return [ self . noisy_operation ( op ) for op in moment ] assert False , 'Should be unreachable.'
def create_translate_dictionaries ( symbols ) : u"""create translate dictionaries for text , google , docomo , kddi and softbank via ` symbols ` create dictionaries for translate emoji character to carrier from unicode ( forward ) or to unicode from carrier ( reverse ) . method return dictionary instance which ...
unicode_to_text = { } unicode_to_docomo_img = { } unicode_to_kddi_img = { } unicode_to_softbank_img = { } unicode_to_google = { } unicode_to_docomo = { } unicode_to_kddi = { } unicode_to_softbank = { } google_to_unicode = { } docomo_to_unicode = { } kddi_to_unicode = { } softbank_to_unicode = { } for x in symbols : ...
def timeit ( func ) : """Simple decorator to time functions : param func : function to decorate : type func : callable : return : wrapped function : rtype : callable"""
@ wraps ( func ) def _wrapper ( * args , ** kwargs ) : start = time . time ( ) result = func ( * args , ** kwargs ) elapsed = time . time ( ) - start LOGGER . info ( '%s took %s seconds to complete' , func . __name__ , round ( elapsed , 2 ) ) return result return _wrapper
def stop_executing_svc_checks ( self ) : """Disable service check execution ( globally ) Format of the line that triggers function call : : STOP _ EXECUTING _ SVC _ CHECKS : return : None"""
if self . my_conf . execute_service_checks : self . my_conf . modified_attributes |= DICT_MODATTR [ "MODATTR_ACTIVE_CHECKS_ENABLED" ] . value self . my_conf . execute_service_checks = False self . my_conf . explode_global_conf ( ) self . daemon . update_program_status ( )
def use_file ( self , enabled = True , file_name = None , level = logging . WARNING , when = 'd' , interval = 1 , backup_count = 30 , delay = False , utc = False , at_time = None , log_format = None , date_format = None ) : """Handler for logging to a file , rotating the log file at certain timed intervals ."""
if enabled : if not self . __file_handler : assert file_name , 'File name is missing!' # Create new TimedRotatingFileHandler instance kwargs = { 'filename' : file_name , 'when' : when , 'interval' : interval , 'backupCount' : backup_count , 'encoding' : 'UTF-8' , 'delay' : delay , 'utc' : ut...
import re pattern = '^[a-z]$|^([a-z]).*\\1$' def validate_string ( s ) : """Function to validate whether the input string begins and ends with the same character using regular expressions . Example : > > > validate _ string ( ' mom ' ) ' Valid ' > > > validate _ string ( ' z ' ) ' Valid ' > > > validate...
if re . match ( pattern , s ) : return 'Valid' else : return 'Invalid'
def _section_from_spec ( elf_file , spec ) : '''Retrieve a section given a " spec " ( either number or name ) . Return None if no such section exists in the file .'''
if isinstance ( spec , int ) : num = int ( spec ) if num < elf_file . num_sections ( ) : return elf_file . get_section ( num ) # Not a number . Must be a name then if isinstance ( spec , str ) : try : return elf_file . get_section_by_name ( spec ) except AttributeError : return N...
def wait_time ( self , value ) : """Setter for * * self . _ _ wait _ time * * attribute . : param value : Attribute value . : type value : int or float"""
if value is not None : assert type ( value ) in ( int , float ) , "'{0}' attribute: '{1}' type is not 'int' or 'float'!" . format ( "wait_time" , value ) assert value >= 0 , "'{0}' attribute: '{1}' need to be positive!" . format ( "wait_time" , value ) self . __wait_time = value
def compute_radius ( wcs ) : """Compute the radius from the center to the furthest edge of the WCS ."""
ra , dec = wcs . wcs . crval img_center = SkyCoord ( ra = ra * u . degree , dec = dec * u . degree ) wcs_foot = wcs . calc_footprint ( ) img_corners = SkyCoord ( ra = wcs_foot [ : , 0 ] * u . degree , dec = wcs_foot [ : , 1 ] * u . degree ) radius = img_center . separation ( img_corners ) . max ( ) . value return radiu...
def set_pixel ( self , x , y , state ) : """Set pixel at " x , y " to " state " where state can be one of " ON " , " OFF " or " TOGGLE " """
self . send_cmd ( "P" + str ( x + 1 ) + "," + str ( y + 1 ) + "," + state )
def map ( self , func : Callable [ [ Tuple [ Any , Log ] ] , Tuple [ Any , Log ] ] ) -> 'Writer' : """Map a function func over the Writer value . Haskell : fmap f m = Writer $ let ( a , w ) = runWriter m in ( f a , w ) Keyword arguments : func - - Mapper function :"""
a , w = self . run ( ) b , _w = func ( ( a , w ) ) return Writer ( b , _w )
def match_function_pattern ( self , first , rest = None , least = 1 , offset = 0 ) : """Match each char sequentially from current SourceString position until the pattern doesnt match and return all maches . Integer argument least defines and minimum amount of chars that can be matched . This version takes f...
if not self . has_space ( offset = offset ) : return '' firstchar = self . string [ self . pos + offset ] if not first ( firstchar ) : return '' output = [ firstchar ] pattern = first if rest is None else rest for char in self . string [ self . pos + offset + 1 : ] : if pattern ( char ) : output . a...
def _resolve ( self , path , migration_file ) : """Resolve a migration instance from a file . : param migration _ file : The migration file : type migration _ file : str : rtype : eloquent . migrations . migration . Migration"""
variables = { } name = '_' . join ( migration_file . split ( '_' ) [ 4 : ] ) migration_file = os . path . join ( path , '%s.py' % migration_file ) with open ( migration_file ) as fh : exec ( fh . read ( ) , { } , variables ) klass = variables [ inflection . camelize ( name ) ] instance = klass ( ) instance . set_sc...
def validate_get_dbs ( connection ) : """validates the connection object is capable of read access to rethink should be at least one test database by default : param connection : < rethinkdb . net . DefaultConnection > : return : < set > list of databases : raises : ReqlDriverError AssertionError"""
remote_dbs = set ( rethinkdb . db_list ( ) . run ( connection ) ) assert remote_dbs return remote_dbs
def componentSelection ( self , comp ) : """Toggles the selection of * comp * from the currently active parameter"""
# current row which is selected in auto parameters to all component selection to indexes = self . selectedIndexes ( ) index = indexes [ 0 ] self . model ( ) . toggleSelection ( index , comp )
def device_not_active ( self , addr ) : """Handle inactive devices ."""
self . aldb_device_handled ( addr ) for callback in self . _cb_device_not_active : callback ( addr )
def _read_coord_h5 ( files , shapes , header , twod ) : """Read all coord hdf5 files of a snapshot . Args : files ( list of pathlib . Path ) : list of NodeCoordinates files of a snapshot . shapes ( list of ( int , int ) ) : shape of mesh grids . header ( dict ) : geometry info . twod ( str ) : ' XZ ' , ...
meshes = [ ] for h5file , shape in zip ( files , shapes ) : meshes . append ( { } ) with h5py . File ( h5file , 'r' ) as h5f : for coord , mesh in h5f . items ( ) : # for some reason , the array is transposed ! meshes [ - 1 ] [ coord ] = mesh [ ( ) ] . reshape ( shape ) . T meshe...
def remove_align_qc_tools ( data ) : """Remove alignment based QC tools we don ' t need for data replicates . When we do multiple variant calling on a sample file ( somatic / germline ) , avoid re - running QC ."""
align_qc = set ( [ "qsignature" , "coverage" , "picard" , "samtools" , "fastqc" ] ) data [ "config" ] [ "algorithm" ] [ "qc" ] = [ t for t in dd . get_algorithm_qc ( data ) if t not in align_qc ] return data
def _set_current_page ( self , current_page , last_page ) : """Get the current page for the request . : param current _ page : The current page of results : type current _ page : int : param last _ page : The last page of results : type last _ page : int : rtype : int"""
if not current_page : current_page = self . resolve_current_page ( ) if current_page > last_page : if last_page > 0 : return last_page return 1 if not self . _is_valid_page_number ( current_page ) : return 1 return current_page
def run_hook ( self , app : FlaskUnchained , bundles : List [ Bundle ] ) : """Hook entry point . Override to disable standard behavior of iterating over bundles to discover objects and processing them ."""
self . process_objects ( app , self . collect_from_bundles ( bundles ) )
def get_file_size ( path ) : """The the size of a file in bytes . Parameters path : str The path of the file . Returns int The size of the file in bytes . Raises IOError If the file does not exist . OSError If a file system error occurs ."""
assert isinstance ( path , ( str , _oldstr ) ) if not os . path . isfile ( path ) : raise IOError ( 'File "%s" does not exist.' , path ) return os . path . getsize ( path )
def to_positive_multiple_of_10 ( string ) : """Converts a string into its encoded positive integer ( greater zero ) or throws an exception ."""
try : value = int ( string ) except ValueError : msg = '"%r" is not a positive multiple of 10 (greater zero).' % string raise argparse . ArgumentTypeError ( msg ) if value <= 0 or value % 10 != 0 : msg = '"%r" is not a positive multiple of 10 (greater zero).' % string raise argparse . ArgumentTypeEr...
def get_proteins_from_psm ( line ) : """From a line , return list of proteins reported by Mzid2TSV . When unrolled lines are given , this returns the single protein from the line ."""
proteins = line [ mzidtsvdata . HEADER_PROTEIN ] . split ( ';' ) outproteins = [ ] for protein in proteins : prepost_protein = re . sub ( '\(pre=.*post=.*\)' , '' , protein ) . strip ( ) outproteins . append ( prepost_protein ) return outproteins
def dict ( self ) : """Returns dictionary of post fields and attributes"""
post_dict = { 'id' : self . id , 'link' : self . link , 'permalink' : self . permalink , 'content_type' : self . content_type , 'slug' : self . slug , 'updated' : self . updated , # . strftime ( conf . GOSCALE _ ATOM _ DATETIME _ FORMAT ) , 'published' : self . published , # . strftime ( conf . GOSCALE _ ATOM _ DATETIM...
def normalizeX ( value ) : """Normalizes x coordinate . * * * value * * must be an : ref : ` type - int - float ` . * Returned value is the same type as the input value ."""
if not isinstance ( value , ( int , float ) ) : raise TypeError ( "X coordinates must be instances of " ":ref:`type-int-float`, not %s." % type ( value ) . __name__ ) return value
def shutdown ( server , graceful = True ) : """Shut down the application . If a graceful stop is requested , waits for all of the IO loop ' s handlers to finish before shutting down the rest of the process . We impose a 10 second timeout . Based on http : / / tornadogists . org / 3428652/"""
ioloop = IOLoop . instance ( ) logging . info ( "Stopping server..." ) # Stop listening for new connections server . stop ( ) def final_stop ( ) : ioloop . stop ( ) logging . info ( "Stopped." ) sys . exit ( 0 ) def poll_stop ( counts = { 'remaining' : None , 'previous' : None } ) : remaining = len ( io...
def create ( cls , exiter , args , env , target_roots = None , daemon_graph_session = None , options_bootstrapper = None ) : """Creates a new LocalPantsRunner instance by parsing options . : param Exiter exiter : The Exiter instance to use for this run . : param list args : The arguments ( e . g . sys . argv ) ...
build_root = get_buildroot ( ) options , build_config , options_bootstrapper = cls . parse_options ( args , env , setup_logging = True , options_bootstrapper = options_bootstrapper , ) global_options = options . for_global_scope ( ) # Option values are usually computed lazily on demand , # but command line options are ...
def _get_library_search_paths ( ) : """Returns a list of library search paths , considering of the current working directory , default paths and paths from environment variables ."""
search_paths = [ '' , '/usr/lib64' , '/usr/local/lib64' , '/usr/lib' , '/usr/local/lib' , '/run/current-system/sw/lib' , '/usr/lib/x86_64-linux-gnu/' , os . path . abspath ( os . path . dirname ( __file__ ) ) ] if sys . platform == 'darwin' : path_environment_variable = 'DYLD_LIBRARY_PATH' else : path_environme...
def emitResetAxisSignal ( self , axisNumber ) : """Emits the sigResetAxis with the axisNumber as parameter axisNumber should be 0 for X , 1 for Y , and 2 for both axes ."""
assert axisNumber in ( VALID_AXES_NUMBERS ) , "Axis Nr should be one of {}, got {}" . format ( VALID_AXES_NUMBERS , axisNumber ) # Hide ' auto - scale ( A ) ' button logger . debug ( "ArgosPgPlotItem.autoBtnClicked, mode:{}" . format ( self . autoBtn . mode ) ) if self . autoBtn . mode == 'auto' : self . autoBtn . ...
def add ( self , date_range , library_name ) : """Adds the library with the given date range to the underlying collection of libraries used by this store . The underlying libraries should not overlap as the date ranges are assumed to be CLOSED _ CLOSED by this function and the rest of the class . Arguments : ...
# check that the library is valid try : self . _arctic_lib . arctic [ library_name ] except Exception as e : logger . error ( "Could not load library" ) raise e assert date_range . start and date_range . end , "Date range should have start and end properties {}" . format ( date_range ) start = date_range . ...
def _validate_iss ( claims , issuer = None ) : """Validates that the ' iss ' claim is valid . The " iss " ( issuer ) claim identifies the principal that issued the JWT . The processing of this claim is generally application specific . The " iss " value is a case - sensitive string containing a StringOrURI v...
if issuer is not None : if isinstance ( issuer , string_types ) : issuer = ( issuer , ) if claims . get ( 'iss' ) not in issuer : raise JWTClaimsError ( 'Invalid issuer' )
def factory_reset ( self , ids , except_ids = False , except_baudrate_and_ids = False ) : """Reset all motors on the bus to their factory default settings ."""
mode = ( 0x02 if except_baudrate_and_ids else 0x01 if except_ids else 0xFF ) for id in ids : try : self . _send_packet ( self . _protocol . DxlResetPacket ( id , mode ) ) except ( DxlTimeoutError , DxlCommunicationError ) : pass
def get_user_by_auth_token ( token = None ) : """Return the AuthUser associated to the token , otherwise it will return None . If token is not provided , it will pull it from the headers : Authorization Exception : Along with AuthError , it may : param token : : return : AuthUser"""
if not token : token = request . get_auth_token ( ) secret_key = get_jwt_secret ( ) s = utils . unsign_jwt ( token = token , secret_key = secret_key , salt = get_jwt_salt ( ) ) if "id" not in s : raise exceptions . AuthError ( "Invalid Authorization Bearer Token" ) return get_user_by_id ( int ( s [ "id" ] ) )
def dna ( self , dna ) : """Replace this chromosome ' s DNA with new DNA of equal length , assigning the new DNA to the chromosome ' s genes sequentially . For example , if a chromosome contains these genes . . . 1 . 100100 2 . 011011 . . . and the new DNA is 1111100000 , the genes become : 1 . 11111 ...
assert self . length == len ( dna ) i = 0 for gene in self . genes : gene . dna = dna [ i : i + gene . length ] i += gene . length
def _parse_entry ( self , cols ) : """Parses an entry ' s row and adds the result to py : attr : ` entries ` . Parameters cols : : class : ` bs4 . ResultSet ` The list of columns for that entry ."""
rank , name , vocation , * values = [ c . text . replace ( '\xa0' , ' ' ) . strip ( ) for c in cols ] rank = int ( rank ) if self . category == Category . EXPERIENCE or self . category == Category . LOYALTY_POINTS : extra , value = values else : value , * extra = values value = int ( value . replace ( ',' , '' ...
def static2dplot_timeaveraged ( var , time ) : """If the static _ taverage option is set in tplot , and is supplied with a time range , then the spectrogram plot ( s ) for which it is set will have another window pop up , where the displayed y and z values are averaged by the number of seconds between the speci...
# Grab names of data loaded in as tplot variables . names = list ( pytplot . data_quants . keys ( ) ) # Get data we ' ll actually work with here . valid_variables = tplot_utilities . get_data ( names ) # Don ' t plot anything unless we have spectrograms with which to work . if valid_variables : # Get z label labels...
def _close_remaining_channels ( self ) : """Forcefully close all open channels . : return :"""
for channel_id in list ( self . _channels ) : self . _channels [ channel_id ] . set_state ( Channel . CLOSED ) self . _channels [ channel_id ] . close ( ) self . _cleanup_channel ( channel_id )
def _adjust_offset ( self , real_wave_mfcc , algo_parameters ) : """OFFSET"""
self . log ( u"Called _adjust_offset" ) self . _apply_offset ( offset = algo_parameters [ 0 ] )
def autodiscover ( ) : """Taken from ` ` django . contrib . admin . autodiscover ` ` and used to run any calls to the ` ` processor _ for ` ` decorator ."""
global LOADED if LOADED : return LOADED = True for app in get_app_name_list ( ) : try : module = import_module ( app ) except ImportError : pass else : try : import_module ( "%s.page_processors" % app ) except : if module_has_submodule ( module , "...
def get_initializer ( default_init_type : str , default_init_scale : float , default_init_xavier_rand_type : str , default_init_xavier_factor_type : str , embed_init_type : str , embed_init_sigma : float , rnn_init_type : str , extra_initializers : Optional [ List [ Tuple [ str , mx . initializer . Initializer ] ] ] = ...
# default initializer if default_init_type == C . INIT_XAVIER : default_init = [ ( C . DEFAULT_INIT_PATTERN , mx . init . Xavier ( rnd_type = default_init_xavier_rand_type , factor_type = default_init_xavier_factor_type , magnitude = default_init_scale ) ) ] elif default_init_type == C . INIT_UNIFORM : default_...
def propinfo ( cls , value , prop , visitor ) : """Like : py : meth : ` normalize . visitor . VisitorPattern . apply ` , but takes a property and returns a dict with some basic info . The default implementation returns just the name of the property and the type in here ."""
if not prop : return { "name" : value . __name__ } rv = { "name" : prop . name } if prop . valuetype : if isinstance ( prop . valuetype , tuple ) : rv [ 'type' ] = [ typ . __name__ for typ in prop . valuetype ] else : rv [ 'type' ] = prop . valuetype . __name__ return rv
def as_hdu ( self ) : "Return a version of ourself as an astropy . io . fits . PrimaryHDU object"
from astropy . io import fits # transfer header , preserving ordering ahdr = self . get_header ( ) header = fits . Header ( ahdr . items ( ) ) data = self . get_mddata ( ) hdu = fits . PrimaryHDU ( data = data , header = header ) return hdu
def det4D ( m ) : '''det4D ( array ) yields the determinate of the given matrix array , which may have more than 2 dimensions , in which case the later dimensions are multiplied and added point - wise .'''
# I just solved this in Mathematica , copy - pasted , and replaced the string ' ] m ' with ' ] * m ' : # Mathematica code : Det @ Table [ m [ i ] [ j ] , { i , 0 , 3 } , { j , 0 , 3 } ] return ( m [ 0 ] [ 3 ] * m [ 1 ] [ 2 ] * m [ 2 ] [ 1 ] * m [ 3 ] [ 0 ] - m [ 0 ] [ 2 ] * m [ 1 ] [ 3 ] * m [ 2 ] [ 1 ] * m [ 3 ] [ 0 ]...
def contains_rva ( self , rva ) : """Check whether the section contains the address provided ."""
# Check if the SizeOfRawData is realistic . If it ' s bigger than the size of # the whole PE file minus the start address of the section it could be # either truncated or the SizeOfRawData contains a misleading value . # In either of those cases we take the VirtualSize if len ( self . pe . __data__ ) - self . pe . adju...
def add_source ( self , name , src_dict , free = None , save_source_maps = True , use_pylike = True , use_single_psf = False ) : """Add a new source to the model . Source properties ( spectrum , spatial model ) are set with the src _ dict argument . Parameters name : str Source name . src _ dict : dict or...
# if self . roi . has _ source ( name ) : # msg = ' Source % s already exists . ' % name # self . logger . error ( msg ) # raise Exception ( msg ) srcmap_utils . delete_source_map ( self . files [ 'srcmap' ] , name ) src = self . roi [ name ] if self . config [ 'gtlike' ] [ 'expscale' ] is not None and name not in self...
def update_groups_for_state ( self , state : State ) : """Update all the Group memberships for the users who have State : param state : State to update for : return :"""
users = get_users_for_state ( state ) for config in self . filter ( states = state ) : logger . debug ( "in state loop" ) for user in users : logger . debug ( "in user loop for {}" . format ( user ) ) config . update_group_membership_for_user ( user )
def revocation_date ( self , value ) : """A datetime . datetime object of when the certificate was revoked , if the status is not " good " or " unknown " ."""
if value is not None and not isinstance ( value , datetime ) : raise TypeError ( _pretty_message ( ''' revocation_date must be an instance of datetime.datetime, not %s ''' , _type_name ( value ) ) ) self . _revocation_date = value
def getISAStudy ( studyNum , pathToISATABFile , noAssays = True ) : """This function returns a Study object given the study number in an ISA file Typically , you should use the exploreISA function to check the contents of the ISA file and retrieve the study number you are interested in ! : param studyNum : Th...
from isatools import isatab import copy try : isa = isatab . load ( pathToISATABFile , skip_load_tables = True ) st = copy . deepcopy ( isa . studies [ studyNum - 1 ] ) if noAssays : st . assays = [ ] return st except FileNotFoundError as err : raise err
def camel_2_snake ( name ) : "Converts CamelCase to camel _ case"
s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
def get_url_image_prediction ( self , model_id , picture_url , token = None , url = API_GET_PREDICTION_IMAGE_URL ) : """Gets a prediction from a supplied picture url based on a previously trained model . : param model _ id : string , once you train a model you ' ll be given a model id to use . : param picture _...
auth = 'Bearer ' + self . check_for_token ( token ) m = MultipartEncoder ( fields = { 'sampleLocation' : picture_url , 'modelId' : model_id } ) h = { 'Authorization' : auth , 'Cache-Control' : 'no-cache' , 'Content-Type' : m . content_type } the_url = url r = requests . post ( the_url , headers = h , data = m ) return ...
def date_added ( self , date_added ) : """Updates the security labels date _ added Args : date _ added : Converted to % Y - % m - % dT % H : % M : % SZ date format"""
date_added = self . _utils . format_datetime ( date_added , date_format = '%Y-%m-%dT%H:%M:%SZ' ) self . _data [ 'dateAdded' ] = date_added request = self . _base_request request [ 'dateAdded' ] = date_added return self . _tc_requests . update ( request , owner = self . owner )
def add_grant ( self , grant ) : """Adds a Grant that the provider should support . : param grant : An instance of a class that extends : class : ` oauth2 . grant . GrantHandlerFactory ` : type grant : oauth2 . grant . GrantHandlerFactory"""
if hasattr ( grant , "expires_in" ) : self . token_generator . expires_in [ grant . grant_type ] = grant . expires_in if hasattr ( grant , "refresh_expires_in" ) : self . token_generator . refresh_expires_in = grant . refresh_expires_in self . grant_types . append ( grant )
def Muller_Steinhagen_Heck ( m , x , rhol , rhog , mul , mug , D , roughness = 0 , L = 1 ) : r'''Calculates two - phase pressure drop with the Muller - Steinhagen and Heck (1986 ) correlation from [ 1 ] _ , also in [ 2 ] _ and [ 3 ] _ . . . math : : \ Delta P _ { tp } = G _ { MSH } ( 1 - x ) ^ { 1/3 } + \ Del...
# Liquid - only properties , for calculation of dP _ lo v_lo = m / rhol / ( pi / 4 * D ** 2 ) Re_lo = Reynolds ( V = v_lo , rho = rhol , mu = mul , D = D ) fd_lo = friction_factor ( Re = Re_lo , eD = roughness / D ) dP_lo = fd_lo * L / D * ( 0.5 * rhol * v_lo ** 2 ) # Gas - only properties , for calculation of dP _ go ...
def parse ( self ) : """Apply search template ."""
self . verbose = bool ( self . re_verbose ) self . unicode = bool ( self . re_unicode ) self . global_flag_swap = { "unicode" : ( ( self . re_unicode is not None ) if not _util . PY37 else False ) , "verbose" : False } self . temp_global_flag_swap = { "unicode" : False , "verbose" : False } self . ascii = self . re_uni...
def classify_by_name ( names ) : """Classify a ( composite ) ligand by the HETID ( s )"""
if len ( names ) > 3 : # Polymer if len ( set ( config . RNA ) . intersection ( set ( names ) ) ) != 0 : ligtype = 'RNA' elif len ( set ( config . DNA ) . intersection ( set ( names ) ) ) != 0 : ligtype = 'DNA' else : ligtype = "POLYMER" else : ligtype = 'SMALLMOLECULE' for name ...
def strip_accents ( x ) : u"""Strip accents in the input phrase X . Strip accents in the input phrase X ( assumed in UTF - 8 ) by replacing accented characters with their unaccented cousins ( e . g . é by e ) . : param x : the input phrase to strip . : type x : string : return : Return such a stripped X ...
x = re_latex_lowercase_a . sub ( "a" , x ) x = re_latex_lowercase_ae . sub ( "ae" , x ) x = re_latex_lowercase_oe . sub ( "oe" , x ) x = re_latex_lowercase_e . sub ( "e" , x ) x = re_latex_lowercase_i . sub ( "i" , x ) x = re_latex_lowercase_o . sub ( "o" , x ) x = re_latex_lowercase_u . sub ( "u" , x ) x = re_latex_lo...
def get_contained_extras ( marker ) : """Collect " extra = = . . . " operands from a marker . Returns a list of str . Each str is a speficied extra in this marker ."""
if not marker : return set ( ) marker = Marker ( str ( marker ) ) extras = set ( ) _markers_collect_extras ( marker . _markers , extras ) return extras
def show ( self , ax : plt . Axes = None , figsize : tuple = ( 3 , 3 ) , title : Optional [ str ] = None , hide_axis : bool = True , cmap : str = 'tab20' , alpha : float = 0.5 , ** kwargs ) : "Show the ` ImageSegment ` on ` ax ` ."
ax = show_image ( self , ax = ax , hide_axis = hide_axis , cmap = cmap , figsize = figsize , interpolation = 'nearest' , alpha = alpha , vmin = 0 ) if title : ax . set_title ( title )
def parse_block ( self , contents , parent , module , depth ) : """Extracts all executable definitions from the specified string and adds them to the specified parent ."""
for anexec in self . RE_EXEC . finditer ( contents ) : x = self . _process_execs ( anexec , parent , module ) parent . executables [ x . name . lower ( ) ] = x if isinstance ( parent , Module ) and "public" in x . modifiers : parent . publics [ x . name . lower ( ) ] = 1 # To handle the embedded...
def node_setup ( domain , master , ticket ) : '''Setup the icinga2 node . Returns : : icinga2 node setup - - ticket TICKET _ ID - - endpoint master . domain . tld - - zone domain . tld - - master _ host master . domain . tld - - trustedcert / etc / icinga2 / pki / trusted - master . crt CLI Example : . . co...
result = __salt__ [ 'cmd.run_all' ] ( [ "icinga2" , "node" , "setup" , "--ticket" , ticket , "--endpoint" , master , "--zone" , domain , "--master_host" , master , "--trustedcert" , "{0}trusted-master.crt" . format ( get_certs_path ( ) ) ] , python_shell = False ) return result
def fetch ( self , wait = 0 ) : """get the task result objects . : param int wait : how many milliseconds to wait for a result : return : an unsorted list of task objects"""
if self . started : return fetch ( self . id , wait = wait , cached = self . cached )
def masked_local_attention_2d ( q , k , v , query_shape = ( 8 , 16 ) , memory_flange = ( 8 , 16 ) , name = None ) : """Strided block local self - attention . Each position in a query block can attend to all the generated queries in the query block , which are generated in raster scan , and positions that are ...
with tf . variable_scope ( name , default_name = "local_masked_self_attention_2d" , values = [ q , k , v ] ) : v_shape = common_layers . shape_list ( v ) # Pad query to ensure multiple of corresponding lengths . q = pad_to_multiple_2d ( q , query_shape ) # Set up query blocks . q_indices = gather_in...
def request ( self , method , uri , params = None , data = None , headers = None , auth = None , timeout = None , allow_redirects = False ) : """Make an HTTP request ."""
url = self . relative_uri ( uri ) return self . domain . request ( method , url , params = params , data = data , headers = headers , auth = auth , timeout = timeout , allow_redirects = allow_redirects )
def send_output ( self , value , stdout ) : """Write the output or value of the expression back to user . > > > print ( ' cash rules everything around me ' ) cash rules everything around me"""
writer = self . writer if value is not None : writer . write ( '{!r}\n' . format ( value ) . encode ( 'utf8' ) ) if stdout : writer . write ( stdout . encode ( 'utf8' ) ) yield from writer . drain ( )
def _parseParams ( self ) : """Parse parameters from their string HTML representation to dictionary . Result is saved to the : attr : ` params ` property ."""
# check if there are any parameters if " " not in self . _element or "=" not in self . _element : return # remove ' < ' & ' > ' params = self . _element . strip ( ) [ 1 : - 1 ] . strip ( ) # remove tagname offset = params . find ( self . getTagName ( ) ) + len ( self . getTagName ( ) ) params = params [ offset : ] ...
def mark_entities ( tokens , positions , markers = [ ] , style = "insert" ) : """Adds special markers around tokens at specific positions ( e . g . , entities ) Args : tokens : A list of tokens ( the sentence ) positions : 1 ) A list of inclusive ranges ( tuples ) corresponding to the token ranges of the ...
if markers and len ( markers ) != 2 * len ( positions ) : msg = ( f"Expected len(markers) == 2 * len(positions), " f"but {len(markers)} != {2 * len(positions)}." ) raise ValueError ( msg ) toks = list ( tokens ) # markings will be of the form : # [ ( position , entity _ idx ) , ( position , entity _ idx ) , . ....
def generate ( self , secret , type = 'totp' , account = 'alex' , issuer = None , algo = 'sha1' , digits = 6 , init_counter = None ) : """https : / / github . com / google / google - authenticator / wiki / Key - Uri - Format"""
args = { } uri = 'otpauth://{0}/{1}?{2}' try : # converts the secret to a 16 cars string a = binascii . unhexlify ( secret ) args [ SECRET ] = base64 . b32encode ( a ) . decode ( 'ascii' ) except binascii . Error as ex : raise ValueError ( str ( ex ) ) except Exception as ex : print ( ex ) raise Val...
def osd_tree ( conn , cluster ) : """Check the status of an OSD . Make sure all are up and in What good output would look like : : " epoch " : 8, " num _ osds " : 1, " num _ up _ osds " : 1, " num _ in _ osds " : " 1 " , " full " : " false " , " nearfull " : " false " Note how the booleans are actua...
ceph_executable = system . executable_path ( conn , 'ceph' ) command = [ ceph_executable , '--cluster={cluster}' . format ( cluster = cluster ) , 'osd' , 'tree' , '--format=json' , ] out , err , code = remoto . process . check ( conn , command , ) try : loaded_json = json . loads ( b'' . join ( out ) . decode ( 'ut...
def send_email_confirmation ( request , user , signup = False ) : """E - mail verification mails are sent : a ) Explicitly : when a user signs up b ) Implicitly : when a user attempts to log in using an unverified e - mail while EMAIL _ VERIFICATION is mandatory . Especially in case of b ) , we want to limi...
from . models import EmailAddress , EmailConfirmation cooldown_period = timedelta ( seconds = app_settings . EMAIL_CONFIRMATION_COOLDOWN ) email = user_email ( user ) if email : try : email_address = EmailAddress . objects . get_for_user ( user , email ) if not email_address . verified : ...
def find_one ( self , tname , where = None , where_not = None , columns = None , astype = None ) : '''Find a single record in the provided table from the database . If multiple match , return the first one based on the internal order of the records . If no records are found , return empty dictionary , string or...
records = self . find ( tname , where = where , where_not = where_not , columns = columns , astype = 'dataframe' ) return self . _output ( records , single = True , astype = astype )
def pdu_to_function_code_or_raise_error ( resp_pdu ) : """Parse response PDU and return of : class : ` ModbusFunction ` or raise error . : param resp _ pdu : PDU of response . : return : Subclass of : class : ` ModbusFunction ` matching the response . : raises ModbusError : When response contains error code...
function_code = struct . unpack ( '>B' , resp_pdu [ 0 : 1 ] ) [ 0 ] if function_code not in function_code_to_function_map . keys ( ) : error_code = struct . unpack ( '>B' , resp_pdu [ 1 : 2 ] ) [ 0 ] raise error_code_to_exception_map [ error_code ] return function_code
def handler ( event , context ) : """Historical { { cookiecutter . technology _ name } } event poller . This poller is run at a set interval in order to ensure that changes do not go undetected by historical . Historical pollers generate ` polling events ` which simulate changes . These polling events contain c...
log . debug ( 'Running poller. Configuration: {}' . format ( event ) ) for account in get_historical_accounts ( ) : try : # TODO describe all items # Example : : # groups = describe _ security _ groups ( # account _ number = account [ ' id ' ] , # assume _ role = HISTORICAL _ ROLE , # region = C...
def AddInstanceTags ( r , instance , tags , dry_run = False ) : """Adds tags to an instance . @ type instance : str @ param instance : instance to add tags to @ type tags : list of str @ param tags : tags to add to the instance @ type dry _ run : bool @ param dry _ run : whether to perform a dry run @...
query = { "tag" : tags , "dry-run" : dry_run , } return r . request ( "put" , "/2/instances/%s/tags" % instance , query = query )
def get_assessment_taken_admin_session ( self , proxy ) : """Gets the ` ` OsidSession ` ` associated with the assessment taken administration service . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . assessment . AssessmentTakenAdminSession ) - an ` ` AssessmentTakenAdminSession ` ` raise :...
if not self . supports_assessment_taken_admin ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . AssessmentTakenAdminSession ( proxy = proxy , runtime = self . _runtime )
def ptmsiReallocationComplete ( ) : """P - TMSI REALLOCATION COMPLETE Section 9.4.8"""
a = TpPd ( pd = 0x3 ) b = MessageType ( mesType = 0x11 ) # 00010001 packet = a / b return packet
def bm3_big_F ( p , v , v0 ) : """calculate big F for linearlized form not fully tested : param p : : param f : : return :"""
f = bm3_small_f ( v , v0 ) return cal_big_F ( p , f )
def get_sec2gos ( sortobj ) : """Initialize section _ name2goids ."""
sec_gos = [ ] for section_name , nts in sortobj . get_desc2nts_fnc ( hdrgo_prt = True ) [ 'sections' ] : sec_gos . append ( ( section_name , set ( nt . GO for nt in nts ) ) ) return cx . OrderedDict ( sec_gos )
def get_cognitive_process_metadata ( self ) : """Gets the metadata for a cognitive process . return : ( osid . Metadata ) - metadata for the cognitive process * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template metadata = dict ( self . _mdata [ 'cognitive_process' ] ) metadata . update ( { 'existing_id_values' : self . _my_map [ 'cognitiveProcessId' ] } ) return Metadata ( ** metadata )
def create_module ( self , spec ) : """Improve python2 semantics for module creation ."""
mod = super ( NamespaceLoader2 , self ) . create_module ( spec ) # Set a few properties required by PEP 302 # mod . _ _ file _ _ = [ p for p in self . path ] # this will set mod . _ _ repr _ _ to not builtin . . . shouldnt break anything in py2 . . . # CAREFUL : get _ filename present implies the module has ONE locatio...
def get_requirements_information ( self , path : Path ) -> Tuple [ RequirementsOptions , Optional [ str ] ] : """Returns the information needed to install requirements for a repository - what kind is used and the hash of contents of the defining file ."""
if self . pipfile_location is not None : pipfile = path / self . pipfile_location / "Pipfile" pipfile_lock = path / self . pipfile_location / "Pipfile.lock" pipfile_exists = pipfile . exists ( ) pipfile_lock_exists = pipfile_lock . exists ( ) if pipfile_exists and pipfile_lock_exists : optio...
def setGridColor ( self , color ) : """Sets the color for the grid for this instance to the given color . : param color | < QColor >"""
palette = self . palette ( ) palette . setColor ( palette . GridForeground , QColor ( color ) )
async def trigger_act ( self , addr ) : """Trigger agent in : attr : ` addr ` to act . This method is quite inefficient if used repeatedly for a large number of agents . . . seealso : : : py : meth : ` creamas . mp . MultiEnvironment . trigger _ all `"""
r_agent = await self . env . connect ( addr , timeout = TIMEOUT ) return await r_agent . act ( )
def close ( self ) : """Cleanly shutdown the connection to RabbitMQ : raises : sprockets . mixins . amqp . ConnectionStateError"""
if not self . closable : LOGGER . warning ( 'Closed called while %s' , self . state_description ) raise ConnectionStateError ( self . state_description ) self . state = self . STATE_CLOSING LOGGER . info ( 'Closing RabbitMQ connection' ) self . connection . close ( )
def survey_change_name ( request , pk ) : """Works well with : http : / / www . appelsiini . net / projects / jeditable"""
survey = get_object_or_404 ( Survey , pk = pk ) if not request . user . has_perm ( "formly.change_survey_name" , obj = survey ) : raise PermissionDenied ( ) survey . name = request . POST . get ( "name" ) survey . save ( ) return JsonResponse ( { "status" : "OK" , "name" : survey . name } )
def _need_bib_run ( self , old_cite_counter ) : '''Determine if you need to run " bibtex " . 1 . Check if * . bib exists . 2 . Check latex output for hints . 3 . Test if the numbers of citations changed during first latex run . 4 . Examine * . bib for changes .'''
with open ( '%s.aux' % self . project_name ) as fobj : match = BIB_PATTERN . search ( fobj . read ( ) ) if not match : return False else : self . bib_file = match . group ( 1 ) if not os . path . isfile ( '%s.bib' % self . bib_file ) : self . log . warning ( 'Could not find *.bib file.' ...
def transformToNative ( obj ) : """Turn obj . value into a date or datetime ."""
if obj . isNative : return obj obj . isNative = True if obj . value == '' : return obj obj . value = obj . value obj . value = parseDtstart ( obj , allowSignatureMismatch = True ) if getattr ( obj , 'value_param' , 'DATE-TIME' ) . upper ( ) == 'DATE-TIME' : if hasattr ( obj , 'tzid_param' ) : # Keep a copy ...
def post ( self , request , * args , ** kwargs ) : """Method for handling POST requests . Deletes the object . Successful deletes are logged . Returns a ' render redirect ' to the result of the ` get _ done _ url ` method . If a ProtectedError is raised , the ` render ` method is called with message expla...
self . object = self . get_object ( ) msg = None if request . POST . get ( 'delete' ) : try : with transaction . commit_on_success ( ) : self . log_action ( self . object , CMSLog . DELETE ) msg = "%s deleted" % self . object self . object . delete ( ) except Protecte...
def getIdentifierForPoint ( self , point ) : """Create a unique identifier for and assign it to ` ` point ` ` . If the point already has an identifier , the existing identifier will be returned . > > > contour . getIdentifierForPoint ( point ) ' ILHGJlygfds ' ` ` point ` ` must be a : class : ` BasePoint ...
point = normalizers . normalizePoint ( point ) return self . _getIdentifierforPoint ( point )
def to_array ( self ) : """Serializes this ChatActionMessage to a dictionary . : return : dictionary representation of this object . : rtype : dict"""
array = super ( ChatActionMessage , self ) . to_array ( ) array [ 'action' ] = u ( self . action ) # py2 : type unicode , py3 : type str if self . receiver is not None : if isinstance ( self . receiver , None ) : array [ 'chat_id' ] = None ( self . receiver ) # type Noneelif isinstance ( self . rece...
def model ( self ) : """Model of the spectrum with given redshift ."""
if self . z == 0 : m = self . _model else : # wavelength if self . _internal_wave_unit . physical_type == 'length' : rs = self . _redshift_model . inverse # frequency or wavenumber # NOTE : This will never execute as long as internal wavelength # unit remains Angstrom . else : # pragma :...
def main ( ) : """Command - line entry point for running the view server ."""
import getopt from . import __version__ as VERSION try : option_list , argument_list = getopt . gnu_getopt ( sys . argv [ 1 : ] , 'h' , [ 'version' , 'help' , 'json-module=' , 'debug' , 'log-file=' ] ) message = None for option , value in option_list : if option in ( '--version' ) : mess...
def queryAll ( self , * args , ** kwargs ) : """Returns a : class : ` Deferred ` object which will have its callback invoked with a : class : ` BatchedView ` when the results are complete . Parameters follow conventions of : meth : ` ~ couchbase . bucket . Bucket . query ` . Example : : d = cb . queryAll ...
if not self . connected : cb = lambda x : self . queryAll ( * args , ** kwargs ) return self . connect ( ) . addCallback ( cb ) kwargs [ 'itercls' ] = BatchedView o = super ( RawBucket , self ) . query ( * args , ** kwargs ) o . start ( ) return o . _getDeferred ( )
async def set_position ( self , position , wait_for_completion = True ) : """Set window to desired position . Parameters : * position : Position object containing the target position . * wait _ for _ completion : If set , function will return after device has reached target position ."""
command_send = CommandSend ( pyvlx = self . pyvlx , wait_for_completion = wait_for_completion , node_id = self . node_id , parameter = position ) await command_send . do_api_call ( ) if not command_send . success : raise PyVLXException ( "Unable to send command" ) await self . after_update ( )
def _get_handled_methods ( self , actions_map ) : """Get names of HTTP methods that can be used at requested URI . Arguments : : actions _ map : Map of actions . Must have the same structure as self . _ item _ actions and self . _ collection _ actions"""
methods = ( 'OPTIONS' , ) defined_actions = [ ] for action_name in actions_map . keys ( ) : view_method = getattr ( self , action_name , None ) method_exists = view_method is not None method_defined = view_method != self . not_allowed_action if method_exists and method_defined : defined_actions ...
def get_volume_by_id ( self , id ) : """Get ScaleIO Volume object by its ID : param name : ID of volume : return : ScaleIO Volume object : raise KeyError : No Volume with specified ID found : rtype : ScaleIO Volume object"""
for vol in self . conn . volumes : if vol . id == id : return vol raise KeyError ( "Volume with ID " + id + " not found" )