signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def frompng ( path , ext = 'png' , start = None , stop = None , recursive = False , npartitions = None , labels = None , engine = None , credentials = None ) : """Load images from PNG files . Parameters path : str Path to data files or directory , specified as either a local filesystem path or in a URI - li...
from scipy . misc import imread def getarray ( idx_buffer_filename ) : idx , buf , _ = idx_buffer_filename fbuf = BytesIO ( buf ) yield ( idx , ) , imread ( fbuf ) return frompath ( path , accessor = getarray , ext = ext , start = start , stop = stop , recursive = recursive , npartitions = npartitions , lab...
def is_iterable ( value ) : """must be an iterable ( list , array , tuple )"""
return isinstance ( value , np . ndarray ) or isinstance ( value , list ) or isinstance ( value , tuple ) , value
def tempfile_writer ( target ) : '''write cache data to a temporary location . when writing is complete , rename the file to the actual location . delete the temporary file on any error'''
tmp = target . parent / ( '_%s' % target . name ) try : with tmp . open ( 'wb' ) as fd : yield fd except : tmp . unlink ( ) raise LOG . debug ( 'rename %s -> %s' , tmp , target ) tmp . rename ( target )
def CheckPasswordReuse ( skipUserInput ) : """Check with user for password reuse . Parameters skipUserInput : boolean Set to skip user input . Returns int Integer from - 1 to 2 depending on user response ."""
goodlogging . Log . Info ( "EXTRACT" , "RAR files needs password to extract" ) if skipUserInput is False : prompt = "Enter 't' to reuse the last password for just this file, " "'a' to reuse for all subsequent files, " "'n' to enter a new password for this file " "or 's' to enter a new password for all files: " ...
def generate_sbi ( index : int = None ) : """Generate a SBI config JSON string ."""
date = datetime . datetime . utcnow ( ) . strftime ( '%Y%m%d' ) if index is None : index = randint ( 0 , 999 ) sbi_id = 'SBI-{}-sip-demo-{:03d}' . format ( date , index ) sb_id = 'SBI-{}-sip-demo-{:03d}' . format ( date , index ) pb_id = 'PB-{}-sip-demo-{:03d}' . format ( date , index ) print ( '* Generating SBI: %...
def delete_pointing ( self , event ) : """Delete the currently active pointing"""
if self . current is None : return for item in self . pointings [ self . current ] [ 'items' ] : self . delete ( item ) self . delete ( self . pointings [ self . current ] [ 'label' ] [ 'id' ] ) del ( self . pointings [ self . current ] ) self . current = None
def show_vip ( self , vip , ** _params ) : """Fetches information of a certain load balancer vip ."""
return self . get ( self . vip_path % ( vip ) , params = _params )
def from_response ( cls , header_data , ignore_bad_cookies = False , ignore_bad_attributes = True ) : "Construct a Cookies object from response header data ."
cookies = cls ( ) cookies . parse_response ( header_data , ignore_bad_cookies = ignore_bad_cookies , ignore_bad_attributes = ignore_bad_attributes ) return cookies
def clear ( self ) : """Clear sketch"""
self . ranking = [ ] heapq . heapify ( self . ranking ) self . dq = deque ( maxlen = self . k ) self . num = 0 return self . clear_method ( self )
def is_error_retryable ( request , exc ) : """Return ` ` True ` ` if the exception is recognized as : term : ` retryable error ` . This will return ` ` False ` ` if the request is on its last attempt . This will return ` ` False ` ` if ` ` pyramid _ retry ` ` is inactive for the request ."""
if is_last_attempt ( request ) : return False return ( isinstance ( exc , RetryableException ) or IRetryableError . providedBy ( exc ) )
def map_to_linear ( self , with_stocks : bool = False ) : """Maps the tree to a linear representation suitable for display"""
result = [ ] for ac in self . model . classes : rows = self . __get_ac_tree ( ac , with_stocks ) result += rows return result
def singleton ( cls ) : """See < Singleton > design pattern for detail : http : / / www . oodesign . com / singleton - pattern . html Python < Singleton > reference : http : / / stackoverflow . com / questions / 6760685 / creating - a - singleton - in - python Recommend use Singleton as a metaclass Usage : ...
instances = { } def get_instance ( * args , ** kwargs ) : if cls not in instances : instances [ cls ] = cls ( * args , ** kwargs ) return instances [ cls ] return get_instance
def make_or_augment_meta ( self , role ) : """Create or augment a meta file ."""
if not os . path . exists ( self . paths [ "meta" ] ) : utils . create_meta_main ( self . paths [ "meta" ] , self . config , role , "" ) self . report [ "state" ] [ "ok_role" ] += 1 self . report [ "roles" ] [ role ] [ "state" ] = "ok" # swap values in place to use the config values swaps = [ ( "author" , s...
def transformer_nat_base ( ) : """Set of hyperparameters ."""
hparams = transformer_nat_small ( ) hparams . batch_size = 2048 hparams . hidden_size = 512 hparams . filter_size = 4096 hparams . num_hidden_layers = 6 return hparams
def _makeProcCallMacro ( self , objtype : str , objname : str , data : [ 'SASdata' , str ] = None , args : dict = None ) -> str : """This method generates the SAS code from the python objects and included data and arguments . The list of args in this method is largely alphabetical but there are exceptions in orde...
plot = '' outmeth = '' procopts = args . pop ( 'procopts' , '' ) # Set ODS graphic generation to True by default ODSGraphics = args . get ( 'ODSGraphics' , True ) # The different SAS products vary slightly in plotting and out methods . # this block sets the options correctly for plotting and output statements if self ....
def find ( self , * , name : str = None , args : str = None , returns : str = None , f : Callable = None ) -> Iterator [ Method ] : """Iterates over the methods table , yielding each matching method . Calling without any arguments is equivalent to iterating over the table . For example , to get all methods that...
for method in self . _table : if name is not None and method . name . value != name : continue descriptor = method . descriptor . value end_para = descriptor . find ( ')' ) m_args = descriptor [ 1 : end_para ] if args is not None and args != m_args : continue m_returns = descript...
def unregister ( self , cleanup_mode ) : """Unregisters a machine previously registered with : py : func : ` IVirtualBox . register _ machine ` and optionally do additional cleanup before the machine is unregistered . This method does not delete any files . It only changes the machine configuration and the ...
if not isinstance ( cleanup_mode , CleanupMode ) : raise TypeError ( "cleanup_mode can only be an instance of type CleanupMode" ) media = self . _call ( "unregister" , in_p = [ cleanup_mode ] ) media = [ IMedium ( a ) for a in media ] return media
def stop ( name , file = sys . stderr ) : """Stop a profiling timer . Arguments : name ( str ) : The name of the timer to stop . If no name is given , stop the global anonymous timer . Returns : bool : Whether or not profiling is enabled . Raises : KeyError : If the named timer does not exist ."""
if is_enabled ( ) : elapsed = ( time ( ) - __TIMERS [ name ] ) if elapsed > 60 : elapsed_str = '{:.1f} m' . format ( elapsed / 60 ) elif elapsed > 1 : elapsed_str = '{:.1f} s' . format ( elapsed ) else : elapsed_str = '{:.1f} ms' . format ( elapsed * 1000 ) del __TIMERS [ nam...
def _add_mem_percent ( self , cur_read ) : """Compute memory percent utilisation based on the mem _ rss _ bytes and mem _ limit _ bytes"""
for executor_id , cur_data in cur_read . items ( ) : stats = cur_data [ 'statistics' ] mem_rss_bytes = stats . get ( 'mem_rss_bytes' ) mem_limit_bytes = stats . get ( 'mem_limit_bytes' ) if mem_rss_bytes and mem_limit_bytes != 0 : stats [ 'mem_percent' ] = mem_rss_bytes / float ( mem_limit_bytes...
def _compute_mean ( self , C , mag , rjb ) : """Compute mean value , see table 2."""
m1 = 6.4 r1 = 50. h = 6. R = np . sqrt ( rjb ** 2 + h ** 2 ) R1 = np . sqrt ( r1 ** 2 + h ** 2 ) less_r1 = rjb < r1 ge_r1 = rjb >= r1 mean = ( C [ 'c1' ] + C [ 'c4' ] * ( mag - m1 ) * np . log ( R ) + C [ 'c5' ] * rjb + C [ 'c8' ] * ( 8.5 - mag ) ** 2 ) mean [ less_r1 ] += C [ 'c3' ] * np . log ( R [ less_r1 ] ) mean [...
def _setup_core_modules ( self ) : """Set up core modules ."""
self . ir_emulator = None self . smt_solver = None self . smt_translator = None if self . arch_info : # Set REIL emulator . self . ir_emulator = ReilEmulator ( self . arch_info ) # Set SMT Solver . self . smt_solver = None if SMT_SOLVER not in ( "Z3" , "CVC4" ) : raise Exception ( "{} SMT solver...
def old_parse_uniprot_txt_file ( infile ) : """From : boscoh / uniprot github Parses the text of metadata retrieved from uniprot . org . Only a few fields have been parsed , but this provides a template for the other fields . A single description is generated from joining alternative descriptions . Retu...
with open ( infile , 'r' ) as txt : cache_txt = txt . read ( ) tag = None uniprot_id = None metadata_by_seqid = { } for l in cache_txt . splitlines ( ) : test_tag = l [ : 5 ] . strip ( ) if test_tag and test_tag != tag : tag = test_tag line = l [ 5 : ] . strip ( )...
def create_cluster ( JobType = None , Resources = None , Description = None , AddressId = None , KmsKeyARN = None , RoleARN = None , SnowballType = None , ShippingOption = None , Notification = None , ForwardingAddressId = None ) : """Creates an empty cluster . Each cluster supports five nodes . You use the CreateJ...
pass
def do_forceescape ( value ) : """Enforce HTML escaping . This will probably double escape variables ."""
if hasattr ( value , '__html__' ) : value = value . __html__ ( ) return escape ( text_type ( value ) )
def json_repr ( self , minimal = False ) : """Construct a JSON - friendly representation of the object . : param bool minimal : [ ignored ] : rtype : list"""
if self . value : return [ self . field , self . operator , self . value ] else : return [ self . field , self . operator ]
def _get_session_for_table ( self , base_session ) : """Only present session for modeling when doses were dropped if it ' s succesful ; otherwise show the original modeling session ."""
if base_session . recommended_model is None and base_session . doses_dropped > 0 : return base_session . doses_dropped_sessions [ 0 ] return base_session
def _FormatIPToken ( self , token_data ) : """Formats an IPv4 packet header token as a dictionary of values . Args : token _ data ( bsm _ token _ data _ ip ) : AUT _ IP token data . Returns : dict [ str , str ] : token values ."""
data = '' . join ( [ '{0:02x}' . format ( byte ) for byte in token_data . data ] ) return { 'IPv4_Header' : data }
def to_dict ( self ) : """to _ dict will clean all protected and private properties"""
return dict ( ( k , self . __dict__ [ k ] ) for k in self . __dict__ if k . find ( "_" ) != 0 )
def run_perl_miniscript ( self , segments ) : """Generates and runs a perl miniscript that derives the text that will be emitted from the preprocessor returns the resulting emit list"""
# Check if perl is installed if shutil . which ( "perl" ) is None : self . env . msg . fatal ( "Input contains Perl preprocessor tags, but an installation of Perl could not be found" ) # Generate minimal perl script that captures activities described in the source file lines = [ ] for i , pp_seg in enumerate ( segm...
def tarjan ( self ) : '''API : tarjan ( self ) Description : Implements Tarjan ' s algorithm for determining strongly connected set of nodes . Pre : self . graph _ type should be DIRECTED _ GRAPH . Post : Nodes will have ' component ' attribute that will have component number as value . Changes ' in...
index = 0 component = 0 q = [ ] for n in self . get_node_list ( ) : if self . get_node_attr ( n , 'index' ) is None : index , component = self . strong_connect ( q , n , index , component )
def connect_srv ( self , domain = None , keepalive = 60 , bind_address = "" ) : """Connect to a remote broker . domain is the DNS domain to search for SRV records ; if None , try to determine local domain name . keepalive and bind _ address are as for connect ( )"""
if HAVE_DNS is False : raise ValueError ( 'No DNS resolver library found.' ) if domain is None : domain = socket . getfqdn ( ) domain = domain [ domain . find ( '.' ) + 1 : ] try : rr = '_mqtt._tcp.%s' % domain if self . _ssl is not None : # IANA specifies secure - mqtt ( not mqtts ) for port 8883 ...
async def prover_get_credential ( wallet_handle : int , cred_id : str ) -> str : """Gets human readable credential by the given id . : param wallet _ handle : wallet handler ( created by open _ wallet ) . : param cred _ id : Identifier by which requested credential is stored in the wallet : return : credentia...
logger = logging . getLogger ( __name__ ) logger . debug ( "prover_get_credential: >>> wallet_handle: %r, cred_id: %r" , wallet_handle , cred_id ) if not hasattr ( prover_get_credential , "cb" ) : logger . debug ( "prover_get_credential: Creating callback" ) prover_get_credential . cb = create_cb ( CFUNCTYPE ( ...
def keys ( key , delimiter = DEFAULT_TARGET_DELIM ) : '''. . versionadded : : 2015.8.0 Attempt to retrieve a list of keys from the named value from the pillar . The value can also represent a value in a nested dict using a " : " delimiter for the dict , similar to how pillar . get works . delimiter Specif...
ret = salt . utils . data . traverse_dict_and_list ( __pillar__ , key , KeyError , delimiter ) if ret is KeyError : raise KeyError ( "Pillar key not found: {0}" . format ( key ) ) if not isinstance ( ret , dict ) : raise ValueError ( "Pillar value in key {0} is not a dict" . format ( key ) ) return ret . keys (...
def convert ( self , targetunits ) : """Set new user unit , for wavelength only . This effectively converts the spectrum wavelength to given unit . Note that actual data are always kept in internal unit ( Angstrom ) , and only converted to user unit by : meth : ` GetWaveSet ` during actual computation . U...
nunits = units . Units ( targetunits ) self . waveunits = nunits
def hide_routemap_holder_route_map_content_set_comm_list_match_comm_delete ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hide_routemap_holder = ET . SubElement ( config , "hide-routemap-holder" , xmlns = "urn:brocade.com:mgmt:brocade-ip-policy" ) route_map = ET . SubElement ( hide_routemap_holder , "route-map" ) name_key = ET . SubElement ( route_map , "name" ) name_key . text = kwargs . pop ( 'name' ) ...
def _objective_function ( self , data_align , data_sup , labels , w , s , theta , bias ) : """Compute the objective function of the Semi - Supervised SRM See : eq : ` sssrm - eq ` . Parameters data _ align : list of 2D arrays , element i has shape = [ voxels _ i , n _ align ] Each element in the list contai...
subjects = len ( data_align ) # Compute the SRM loss f_val = 0.0 for subject in range ( subjects ) : samples = data_align [ subject ] . shape [ 1 ] f_val += ( 1 - self . alpha ) * ( 0.5 / samples ) * np . linalg . norm ( data_align [ subject ] - w [ subject ] . dot ( s ) , 'fro' ) ** 2 # Compute the MLR loss f_...
def update ( self , request , pk = None , parent_lookup_organization = None ) : '''Add a user to an organization .'''
user = get_object_or_404 ( User , pk = pk ) org = get_object_or_404 ( SeedOrganization , pk = parent_lookup_organization ) self . check_object_permissions ( request , org ) org . users . add ( user ) return Response ( status = status . HTTP_204_NO_CONTENT )
def remove ( self , symbol ) : """Remove the entry for the unit matching ` symbol ` . Parameters symbol : str The name of the unit symbol to remove from the registry ."""
self . _unit_system_id = None if symbol not in self . lut : raise SymbolNotFoundError ( "Tried to remove the symbol '%s', but it does not exist " "in this registry." % symbol ) del self . lut [ symbol ]
def loadFile ( self , var , close_on_fail = True ) : """A special function to replate a variable name that is a string file path with the loaded file . var is a string on input output is a numpy array or a None - type object ( success vs . failure )"""
out = None try : # First see if it is a full path or directly links from the current # working directory out = np . load ( var ) if self . Verbose : print ( "Loading " + var + " from numpy binary" ) except : try : out = np . loadtxt ( var ) if self . Verbose : print ( "Lo...
def getRejectionReasonsItems ( self ) : """Return the list of predefined rejection reasons"""
reasons = self . getRejectionReasons ( ) if not reasons : return [ ] reasons = reasons [ 0 ] keys = filter ( lambda key : key != "checkbox" , reasons . keys ( ) ) return map ( lambda key : reasons [ key ] , sorted ( keys ) ) or [ ]
def heartbeat ( self ) : """Keep active shards with " trim _ horizon " , " latest " iterators alive by advancing their iterators ."""
for shard in self . active : if shard . sequence_number is None : records = next ( shard ) # Success ! This shard now has an ` ` at _ sequence ` ` iterator if records : self . buffer . push_all ( ( record , shard ) for record in records ) self . migrate_closed_shards ( )
def reverse ( self , matching_name , ** kwargs ) : """Getting a matching name and URL args and return a corresponded URL"""
for record in self . matching_records : if record . name == matching_name : path_template = record . path_template break else : raise NotReversed if path_template . wildcard_name : l = kwargs . get ( path_template . wildcard_name ) if not l : raise NotReversed additional_path...
def extract_from_image ( self , img , scale = 1.0 , margin_width = 5 , margin_height = 5 ) : """Extracts the contents of this box from a given image . For that the image is " unrotated " by the appropriate angle , and the corresponding part is extracted from it . Returns an image with dimensions height * scale ...
rotate_by = ( np . pi / 2 - self . angle ) * 180 / np . pi img_rotated = transform . rotate ( img , angle = rotate_by , center = [ self . center [ 1 ] * scale , self . center [ 0 ] * scale ] , resize = True ) # The resizeable transform will shift the resulting image somewhat wrt original coordinates . # When we cut out...
def parse_file ( self , cu , analysis ) : """Generate data for single file"""
if hasattr ( analysis , 'parser' ) : filename = cu . file_locator . relative_filename ( cu . filename ) source_lines = analysis . parser . lines with cu . source_file ( ) as source_file : source = source_file . read ( ) try : if sys . version_info < ( 3 , 0 ) : encoding = sou...
def create ( zone , brand , zonepath , force = False ) : '''Create an in - memory configuration for the specified zone . zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example : . . code - block : : bash salt ' * ...
ret = { 'status' : True } # write config cfg_file = salt . utils . files . mkstemp ( ) with salt . utils . files . fpopen ( cfg_file , 'w+' , mode = 0o600 ) as fp_ : fp_ . write ( "create -b -F\n" if force else "create -b\n" ) fp_ . write ( "set brand={0}\n" . format ( _sanitize_value ( brand ) ) ) fp_ . wr...
def safe_size ( source ) : """READ THE source UP TO SOME LIMIT , THEN COPY TO A FILE IF TOO BIG RETURN A str ( ) OR A FileString ( )"""
if source is None : return None total_bytes = 0 bytes = [ ] b = source . read ( MIN_READ_SIZE ) while b : total_bytes += len ( b ) bytes . append ( b ) if total_bytes > MAX_STRING_SIZE : try : data = FileString ( TemporaryFile ( ) ) for bb in bytes : data ...
def read ( self , size = - 1 ) : """read a number of bytes from the file and return it as a string . . note : : this method will block if there is no data already available : param size : the maximum number of bytes to read from the file . < 0 means read the file to the end : type size : int : returns :...
chunksize = size < 0 and self . CHUNKSIZE or min ( self . CHUNKSIZE , size ) buf = self . _rbuf buf . seek ( 0 , os . SEEK_END ) collected = buf . tell ( ) while 1 : if size >= 0 and collected >= size : # we have read enough already break output = self . _read_chunk ( chunksize ) if output is None :...
def send_email ( recipient , subject , message , sender = "ploneintranet@netsight.co.uk" ) : """helper function to send an email with the sender preset"""
try : api . portal . send_email ( recipient = recipient , sender = sender , subject = subject , body = message ) except ValueError , e : log . error ( "MailHost error: {0}" . format ( e ) )
def get_sessions ( name , backend , socket = DEFAULT_SOCKET_URL ) : '''. . versionadded : : 2016.11.0 Get number of current sessions on server in backend ( scur ) name Server name backend haproxy backend socket haproxy stats socket , default ` ` / var / run / haproxy . sock ` ` CLI Example : . . c...
class getStats ( haproxy . cmds . Cmd ) : p_args = [ "backend" , "server" ] cmdTxt = "show stat\r\n" helpText = "Fetch all statistics" ha_conn = _get_conn ( socket ) ha_cmd = getStats ( server = name , backend = backend ) result = ha_conn . sendCmd ( ha_cmd ) for line in result . split ( '\n' ) : if lin...
def add_scale ( self , name , W , b , has_bias , input_name , output_name , shape_scale = [ 1 ] , shape_bias = [ 1 ] ) : """Add scale layer to the model . Parameters name : str The name of this layer . W : int | numpy . array Scale of the input . b : int | numpy . array Bias to add to the input . ha...
spec = self . spec nn_spec = self . nn_spec spec_layer = nn_spec . layers . add ( ) spec_layer . name = name spec_layer . input . append ( input_name ) spec_layer . output . append ( output_name ) spec_layer_params = spec_layer . scale spec_layer_params . hasBias = has_bias # add scale and its shape scale = spec_layer_...
def process_request ( self , req , resp ) : """Process the request before routing it . A summary of the rational for the different behavior is shown below . Expect Header Our API does not currently support any implementation of the Expect header . This mostly impacts clients that use the ` 100 - continu...
max_length = goldman . config . MAX_URI_LENGTH if req . expect : abort ( exceptions . ExpectationUnmet ) elif len ( req . uri ) > max_length : abort ( exceptions . URITooLong ( max_length ) ) elif req . content_required : # content _ length could be zero has_content_length = req . content_length is not None...
def parse_compound_list ( path , compounds ) : """Parse a structured list of compounds as obtained from a YAML file Yields CompoundEntries . Path can be given as a string or a context ."""
context = FilePathContext ( path ) for compound_def in compounds : if 'include' in compound_def : file_format = compound_def . get ( 'format' ) include_context = context . resolve ( compound_def [ 'include' ] ) for compound in parse_compound_file ( include_context , file_format ) : ...
def get_options_for_id ( options : Dict [ str , Dict [ str , Any ] ] , identifier : str ) : """Helper method , from the full options dict of dicts , to return either the options related to this parser or an empty dictionary . It also performs all the var type checks : param options : : param identifier : : ...
check_var ( options , var_types = dict , var_name = 'options' ) res = options [ identifier ] if identifier in options . keys ( ) else dict ( ) check_var ( res , var_types = dict , var_name = 'options[' + identifier + ']' ) return res
def sg_summary_loss ( tensor , prefix = 'losses' , name = None ) : r"""Register ` tensor ` to summary report as ` loss ` Args : tensor : A ` Tensor ` to log as loss prefix : A ` string ` . A prefix to display in the tensor board web UI . name : A ` string ` . A name to display in the tensor board web UI . ...
# defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name ( tensor ) if name is None else prefix + name # summary statistics _scalar ( name , tf . reduce_mean ( tensor ) ) _histogram ( name + '-h' , tensor )
def get_assigned_services_uids ( self ) : """Get the current assigned services UIDs of this Worksheet"""
services = self . get_assigned_services ( ) uids = map ( api . get_uid , services ) return list ( set ( uids ) )
def write_resultfiles ( self ) : """Write the output to disk"""
t0 = time . time ( ) writer = ow . output_writer ( output_dictionary = self . result ) if len ( self . options . outpath ) >= 3 and self . options . outpath [ - 3 : ] == ".h5" : writer . write_hdf5 ( filename = self . options . outpath , timestamp = self . options . timestamp ) else : writer . write_txt ( outdi...
def apply_network_settings ( ** settings ) : '''Apply global network configuration . CLI Example : . . code - block : : bash salt ' * ' ip . apply _ network _ settings'''
if 'require_reboot' not in settings : settings [ 'require_reboot' ] = False if 'apply_hostname' not in settings : settings [ 'apply_hostname' ] = False hostname_res = True if settings [ 'apply_hostname' ] in _CONFIG_TRUE : if 'hostname' in settings : hostname_res = __salt__ [ 'network.mod_hostname' ...
def upload ( self , local_path , remote_url ) : """Copy a local file to an S3 location ."""
bucket , key = _parse_url ( remote_url ) with open ( local_path , 'rb' ) as fp : return self . call ( "PutObject" , bucket = bucket , key = key , body = fp )
def setText ( self , text ) : """Sets the text for this item and resizes it to fit the text and the remove button . : param text | < str >"""
super ( XMultiTagItem , self ) . setText ( text ) metrics = QFontMetrics ( self . font ( ) ) hint = QSize ( metrics . width ( text ) + 24 , 18 ) self . setSizeHint ( hint )
def add_index ( collection , name , fields , transformer = None , unique = False , case_insensitive = False ) : """Add a secondary index for a collection ` ` collection ` ` on one or more ` ` fields ` ` . The values at each of the ` ` fields ` ` are loaded from existing objects and their object ids added to t...
assert len ( name ) > 0 assert len ( fields ) > 0 indexes = _db [ collection ] . indexes index = indexes . setdefault ( name , aadict ( ) ) index . transformer = transformer index . value_map = { } # json ( [ value ] ) = > set ( object _ id ) index . unique = unique index . case_insensitive = case_insensitive index . f...
def save_encoder ( self , name : str ) : "Save the encoder to ` name ` inside the model directory ."
encoder = get_model ( self . model ) [ 0 ] if hasattr ( encoder , 'module' ) : encoder = encoder . module torch . save ( encoder . state_dict ( ) , self . path / self . model_dir / f'{name}.pth' )
def update_Dim ( self , name , value ) : '''update a dimension by appending the number of added elements to the dimensions : : < upddated dimension > = < old dimension > + < number of added elements along this dimension >'''
oldVal = self . _dimensions [ name ] self . _dimensions [ name ] += value self . message ( 2 , 'Updating dimension {0} (from {1} to {2})' . format ( name , oldVal , self . _dimensions [ name ] ) ) # Update dimensions within all variables for p in self . par_list : if self . __dict__ [ p ] . __dict__ . has_key ( '_d...
def _ParseCredentialOptions ( self , options ) : """Parses the credential options . Args : options ( argparse . Namespace ) : command line arguments . Raises : BadConfigOption : if the options are invalid ."""
credentials = getattr ( options , 'credentials' , [ ] ) if not isinstance ( credentials , list ) : raise errors . BadConfigOption ( 'Unsupported credentials value.' ) for credential_string in credentials : credential_type , _ , credential_data = credential_string . partition ( ':' ) if not credential_type o...
def update ( self , cardconnection , ccevent ) : '''CardConnectionObserver callback .'''
apduline = "" if 'connect' == ccevent . type : apduline += 'connecting to ' + cardconnection . getReader ( ) elif 'disconnect' == ccevent . type : apduline += 'disconnecting from ' + cardconnection . getReader ( ) elif 'command' == ccevent . type : apduline += '> ' + toHexString ( ccevent . args [ 0 ] ) eli...
def validate_new_email ( email ) : """Validates a " new " email address by checking if it is already used by other users ."""
email = normalize_email ( email ) User = get_user_model ( ) # noqa if User . objects . filter ( email = email ) . exists ( ) : raise ValidationError ( 'The given email address is already registered.' )
def add_user ( self , nick , prefixes = None ) : """Add a user to our internal list of nicks ."""
if nick not in self . _user_nicks : self . _user_nicks . append ( nick ) self . prefixes [ nick ] = prefixes
def dump ( file_name , pattern ) : """Print all keys and values where key matches PATTERN . Default pattern is * ( all keys )"""
db = XonoticDB . load_path ( file_name ) items = sorted ( db . filter ( pattern ) , key = lambda x : natural_sort_key ( x [ 0 ] ) ) for k , v in items : click . echo ( '%s: %s' % ( k , v ) )
def console_logger ( level = "WARNING" ) : """* Setup and return a console logger * * * Key Arguments : * * - ` ` level ` ` - - the level of logging required * * Return : * * - ` ` logger ` ` - - the console logger * * Usage : * * . . code - block : : python from fundamentals import logs log = logs ...
# # # # # # > IMPORTS # # # # # # # STANDARD LIB # # import logging import logging . config # # THIRD PARTY # # import yaml try : yaml . warnings ( { 'YAMLLoadWarning' : False } ) except : pass # # LOCAL APPLICATION # # # SETUP LOGGING loggerConfig = """ version: 1 formatters: console_style: ...
def register_dte_task ( self , * args , ** kwargs ) : """Register a Dte task ."""
kwargs [ "task_class" ] = DteTask return self . register_task ( * args , ** kwargs )
def process_dut ( dut ) : """Signal worker thread that specified Dut needs processing"""
if dut . finished ( ) : return Dut . _signalled_duts . appendleft ( dut ) Dut . _sem . release ( )
def GetAttachmentCollection ( self , _id ) : """Get Attachments for given List Item ID"""
# Build Request soap_request = soap ( 'GetAttachmentCollection' ) soap_request . add_parameter ( 'listName' , self . listName ) soap_request . add_parameter ( 'listItemID' , _id ) self . last_request = str ( soap_request ) # Send Request response = self . _session . post ( url = self . _url ( 'Lists' ) , headers = self...
def _parse_trunk_allowed_vlans ( self , config ) : """Scans the specified config and parse the trunk allowed vlans value Args : config ( str ) : The interface configuration block to scan Returns : dict : A Python dict object with the value of switchport trunk allowed vlans value . The dict returned is int...
match = re . search ( r'switchport trunk allowed vlan (.+)$' , config , re . M ) return dict ( trunk_allowed_vlans = match . group ( 1 ) )
def _overrideMasterSettings ( self ) : """Override so that we can run in a different mode ."""
# config - obj dict of defaults cod = self . _getGuiSettings ( ) # our own GUI setup self . _appName = APP_NAME self . _appHelpString = tealHelpString self . _useSimpleAutoClose = self . _do_usac self . _showExtraHelpButton = False self . _saveAndCloseOnExec = cfgGetBool ( cod , 'saveAndCloseOnExec' , True ) self . _sh...
def label_value ( label_info , multi_line = True ) : """Convert series values to str and maybe concatenate them Parameters label _ info : series Series whose values will be returned multi _ line : bool Whether to place each variable on a separate line Returns out : series Label text strings"""
label_info = label_info . astype ( str ) if not multi_line : label_info = collapse_label_lines ( label_info ) return label_info
def run ( self ) : """Create a list of process definitions ."""
config = self . state . document . settings . env . config # Get all processes : processes = get_processes ( config . autoprocess_process_dir , config . autoprocess_source_base_url ) process_nodes = [ ] for process in sorted ( processes , key = itemgetter ( 'name' ) ) : process_nodes . extend ( self . make_process_...
def prune ( self ) : """On a subtree where the root node ' s s _ center is empty , return a new subtree with no empty s _ centers ."""
if not self [ 0 ] or not self [ 1 ] : # if I have an empty branch direction = not self [ 0 ] # graft the other branch here # if trace : # print ( ' Grafting { } branch ' . format ( # ' right ' if direction else ' left ' ) ) result = self [ direction ] # if result : result . verify ( ) re...
def merge_rest_docs ( prnt_doc = None , child_doc = None ) : """See custom _ inherit . style _ store . reST for details ."""
prnt_sections = parse_rest_doc ( prnt_doc ) child_sections = parse_rest_doc ( child_doc ) header = prnt_sections [ '' ] prnt_sections . update ( child_sections ) if not child_sections [ '' ] . body : prnt_sections [ '' ] = header if not header . body : prnt_sections . popitem ( last = False ) return "\n...
def intersect ( self , other ) : """Return the intersection between this frequency band and another . Args : other ( FrequencyBand ) : the instance to intersect with Examples : : > > > import zounds > > > b1 = zounds . FrequencyBand ( 500 , 1000) > > > b2 = zounds . FrequencyBand ( 900 , 2000) > > > i...
lowest_stop = min ( self . stop_hz , other . stop_hz ) highest_start = max ( self . start_hz , other . start_hz ) return FrequencyBand ( highest_start , lowest_stop )
def transactional_async ( func , args , kwds , ** options ) : """The async version of @ ndb . transaction ."""
options . setdefault ( 'propagation' , datastore_rpc . TransactionOptions . ALLOWED ) if args or kwds : return transaction_async ( lambda : func ( * args , ** kwds ) , ** options ) return transaction_async ( func , ** options )
def load ( self , playerName = None ) : """retrieve the PlayerRecord settings from saved disk file"""
if playerName : # switch the PlayerRecord this object describes self . name = playerName # preset value to load self . filename try : with open ( self . filename , "rb" ) as f : data = f . read ( ) except Exception : raise ValueError ( "invalid profile, '%s'. file does not exist: %s" % ( self . ...
def get_job_results ( self , job_resource_name : str ) -> List [ TrialResult ] : """Returns the actual results ( not metadata ) of a completed job . Params : job _ resource _ name : A string of the form ` projects / project _ id / programs / program _ id / jobs / job _ id ` . Returns : An iterable over th...
response = self . service . projects ( ) . programs ( ) . jobs ( ) . getResult ( parent = job_resource_name ) . execute ( ) trial_results = [ ] for sweep_result in response [ 'result' ] [ 'sweepResults' ] : sweep_repetitions = sweep_result [ 'repetitions' ] key_sizes = [ ( m [ 'key' ] , len ( m [ 'qubits' ] ) )...
def killTask ( self , driver , taskId ) : """Kill parent task process and all its spawned children"""
try : pid = self . runningTasks [ taskId ] pgid = os . getpgid ( pid ) except KeyError : pass else : os . killpg ( pgid , signal . SIGKILL )
def run_lldptool ( self , args ) : """Function for invoking the lldptool utility ."""
full_args = [ 'lldptool' ] + args try : return utils . execute ( full_args , root_helper = self . root_helper ) except Exception as exc : LOG . error ( "Unable to execute %(cmd)s. " "Exception: %(exception)s" , { 'cmd' : full_args , 'exception' : str ( exc ) } )
def parse_complex ( tree_to_parse , xpath_root , xpath_map , complex_key ) : """Creates and returns a Dictionary data structure parsed from the metadata . : param tree _ to _ parse : the XML tree compatible with element _ utils to be parsed : param xpath _ root : the XPATH location of the structure inside the p...
complex_struct = { } for prop in _complex_definitions . get ( complex_key , xpath_map ) : # Normalize complex values : treat values with newlines like values from separate elements parsed = parse_property ( tree_to_parse , xpath_root , xpath_map , prop ) parsed = reduce_value ( flatten_items ( v . split ( _COMP...
def _request_new_chunk ( self ) : """Called to request a new chunk of data to be read from the Crazyflie"""
# Figure out the length of the next request new_len = self . _bytes_left if new_len > _ReadRequest . MAX_DATA_LENGTH : new_len = _ReadRequest . MAX_DATA_LENGTH logger . debug ( 'Requesting new chunk of {}bytes at 0x{:X}' . format ( new_len , self . _current_addr ) ) # Request the data for the next address pk = CRTP...
def setup_logger ( logger_configuration_file , log_dir = None , process_name = '' , log_file = '' ) : # pylint : disable = too - many - branches """Configure the provided logger - get and update the content of the Json configuration file - configure the logger with this file If a log _ dir and process _ name ...
logger_ = logging . getLogger ( ALIGNAK_LOGGER_NAME ) for handler in logger_ . handlers : if not process_name : break # Logger is already configured ? if getattr ( handler , '_name' , None ) == 'daemons' : # Update the declared formats and file names with the process name # This is for unit test...
def most_frequent ( lst ) : """Returns the item that appears most frequently in the given list ."""
lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
def get_kinetic_folding_rate ( self , secstruct , at_temp = None ) : """Run the FOLD - RATE web server to calculate the kinetic folding rate given an amino acid sequence and its structural classficiation ( alpha / beta / mixed ) Stores statistics in the ` ` annotations ` ` attribute , under the key ` kinetic _ ...
import ssbio . protein . sequence . properties . kinetic_folding_rate as kfr rate = kfr . get_foldrate ( seq = self , secstruct = secstruct ) self . annotations [ 'kinetic_folding_rate_37.0_C-foldrate' ] = rate if at_temp : new_rate = kfr . get_foldrate_at_temp ( ref_rate = rate , new_temp = at_temp ) self . an...
def nm_width ( center , width , units = "wn" ) -> float : """Given a center and width , in energy units , get back a width in nm . Parameters center : number Center ( in energy units ) . width : number Width ( in energy units ) . units : string ( optional ) Input units . Default is wn . Returns nu...
red = wt_units . converter ( center - width / 2. , units , "nm" ) blue = wt_units . converter ( center + width / 2. , units , "nm" ) return red - blue
def Set ( self , subject , attribute , value , timestamp = None , replace = True , sync = True ) : """Set the value into the data store ."""
subject = utils . SmartUnicode ( subject ) _ = sync attribute = utils . SmartUnicode ( attribute ) if timestamp is None or timestamp == self . NEWEST_TIMESTAMP : timestamp = time . time ( ) * 1000000 if subject not in self . subjects : self . subjects [ subject ] = { } if replace or attribute not in self . subj...
def save_nk_object ( obj , filename = "file" , path = "" , extension = "nk" , compress = False , compatibility = - 1 ) : """Save whatever python object to a pickled file . Parameters file : object Whatever python thing ( list , dict , . . . ) . filename : str File ' s name . path : str File ' s path ....
if compress is True : with gzip . open ( path + filename + "." + extension , 'wb' ) as name : pickle . dump ( obj , name , protocol = compatibility ) else : with open ( path + filename + "." + extension , 'wb' ) as name : pickle . dump ( obj , name , protocol = compatibility )
def load_geo_adwords ( filename = 'AdWords API Location Criteria 2017-06-26.csv.gz' ) : """WARN : Not a good source of city names . This table has many errors , even after cleaning"""
df = pd . read_csv ( filename , header = 0 , index_col = 0 , low_memory = False ) df . columns = [ c . replace ( ' ' , '_' ) . lower ( ) for c in df . columns ] canonical = pd . DataFrame ( [ list ( row ) for row in df . canonical_name . str . split ( ',' ) . values ] ) def cleaner ( row ) : cleaned = pd . np . arr...
def update_fileserver ( self , interval , backends ) : '''Threading target which handles all updates for a given wait interval'''
def _do_update ( ) : log . debug ( 'Performing fileserver updates for items with an update ' 'interval of %d' , interval ) for backend , update_args in six . iteritems ( backends ) : backend_name , update_func = backend try : if update_args : log . debug ( 'Updating %...
def record_patch ( rec , diff ) : """Return the JSON - compatible structure that results from applying the changes in ` diff ` to the record ` rec ` . The parameters must be structures compatible with json . dumps * or * strings compatible with json . loads . Note that by design , ` old = = record _ patch ( n...
rec , diff = _norm_json_params ( rec , diff ) return json_delta . patch ( rec , diff , in_place = False )
def set_p_features ( self , do_dac = False , expanded = False ) : """Use properties of the physical signal field to set the following features : n _ sig , sig _ len . Parameters do _ dac : bool Whether to use the digital signal field to perform dac conversion to get the physical signal field beforehand . ...
if expanded : if do_dac : self . check_field ( 'e_d_signal' ) self . check_field ( 'fmt' , 'all' ) self . check_field ( 'adc_gain' , 'all' ) self . check_field ( 'baseline' , 'all' ) self . check_field ( 'samps_per_frame' , 'all' ) # All required fields are present an...
def r_oauth_logout ( self ) : """Route to clear the oauth data from the session : return : { " template " }"""
session . pop ( 'oauth_user_uri' , None ) session . pop ( 'oauth_user_name' , None ) next = request . args . get ( 'next' , '' ) if next is not None : return redirect ( session [ 'next' ] ) else : return { "template" : "main::index.html" }
def classify ( self , dataset , missing_value_action = 'auto' ) : """Return a classification , for each example in the ` ` dataset ` ` , using the trained boosted trees model . The output SFrame contains predictions as class labels ( 0 or 1 ) and probabilities associated with the the example . Parameters da...
return super ( BoostedTreesClassifier , self ) . classify ( dataset , missing_value_action = missing_value_action )
def MergePolys ( polys , merge_point_threshold = 10 ) : """Merge multiple polylines , in the order that they were passed in . Merged polyline will have the names of their component parts joined by ' ; ' . Example : merging [ a , b ] , [ c , d ] and [ e , f ] will result in [ a , b , c , d , e , f ] . However ...
name = ";" . join ( ( p . GetName ( ) , '' ) [ p . GetName ( ) is None ] for p in polys ) merged = Poly ( [ ] , name ) if polys : first_poly = polys [ 0 ] for p in first_poly . GetPoints ( ) : merged . AddPoint ( p ) last_point = merged . _GetPointSafe ( - 1 ) for poly in polys [ 1 : ] : ...
def zcr ( data ) : """Computes zero crossing rate of segment"""
data = np . mean ( data , axis = 1 ) count = len ( data ) countZ = np . sum ( np . abs ( np . diff ( np . sign ( data ) ) ) ) / 2 return ( np . float64 ( countZ ) / np . float64 ( count - 1.0 ) )
def regex ( self , * pattern , ** kwargs ) : """Add re pattern : param pattern : : type pattern : : return : self : rtype : Rebulk"""
self . pattern ( self . build_re ( * pattern , ** kwargs ) ) return self