signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def VerifyRow ( self , parser_mediator , row ) : """Verifies if a line of the file is in the expected format . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . row ( dict [ str , str ] ) : fields of a single row , as speci...
if len ( row ) < self . MIN_COLUMNS : return False # Check the date format ! # If it doesn ' t parse , then this isn ' t a Trend Micro AV log . try : timestamp = self . _ConvertToTimestamp ( row [ 'date' ] , row [ 'time' ] ) except ValueError : return False if timestamp is None : return False try : ...
def apply_rows ( applicators , rows ) : """Yield rows after applying the applicator functions to them . Applicators are simple unary functions that return a value , and that value is stored in the yielded row . E . g . ` row [ col ] = applicator ( row [ col ] ) ` . These are useful to , e . g . , cast strin...
for row in rows : for ( cols , function ) in applicators : for col in ( cols or [ ] ) : value = row . get ( col , '' ) row [ col ] = function ( row , value ) yield row
def R_value_to_k ( R_value , SI = True ) : r'''Returns the thermal conductivity of a substance given its R - value , which can be in either SI units of m ^ 2 K / ( W * inch ) or the Imperial units of ft ^ 2 deg F * h / ( BTU * inch ) . Parameters R _ value : float R - value of a substance [ m ^ 2 K / ( W ...
if SI : r = R_value / inch else : r = R_value * foot ** 2 * degree_Fahrenheit * hour / Btu / inch return thermal_resistivity_to_k ( r )
def GetFileEntryByPathSpec ( self , path_spec ) : """Retrieves a file entry for a path specification . Args : path _ spec ( PathSpec ) : path specification . Returns : VShadowFileEntry : file entry or None if not available ."""
store_index = vshadow . VShadowPathSpecGetStoreIndex ( path_spec ) # The virtual root file has not corresponding store index but # should have a location . if store_index is None : location = getattr ( path_spec , 'location' , None ) if location is None or location != self . LOCATION_ROOT : return None ...
def two_point_effective_mass ( cartesian_k_points , eigenvalues ) : """Calculate the effective mass given eigenvalues at two k - points . Reimplemented from Aron Walsh ' s original effective mass Fortran code . Args : cartesian _ k _ points ( np . array ) : 2D numpy array containing the k - points in ( recipr...
assert ( cartesian_k_points . shape [ 0 ] == 2 ) assert ( eigenvalues . size == 2 ) dk = cartesian_k_points [ 1 ] - cartesian_k_points [ 0 ] mod_dk = np . sqrt ( np . dot ( dk , dk ) ) delta_e = ( eigenvalues [ 1 ] - eigenvalues [ 0 ] ) * ev_to_hartree * 2.0 effective_mass = mod_dk * mod_dk / delta_e return effective_m...
def _combine_season_stats ( self , table_rows , career_stats , all_stats_dict ) : """Combine all stats for each season . Since all of the stats are spread across multiple tables , they should be combined into a single field which can be used to easily query stats at once . Parameters table _ rows : genera...
most_recent_season = self . _most_recent_season if not table_rows : table_rows = [ ] for row in table_rows : season = self . _parse_season ( row ) try : all_stats_dict [ season ] [ 'data' ] += str ( row ) except KeyError : all_stats_dict [ season ] = { 'data' : str ( row ) } most_rec...
def _select_other_window ( history ) : "Toggle focus between left / right window ."
current_buffer = history . app . current_buffer layout = history . history_layout . layout if current_buffer == history . history_buffer : layout . current_control = history . history_layout . default_buffer_control elif current_buffer == history . default_buffer : layout . current_control = history . history_l...
def binary_stream ( stream ) : """Ensure a stream is binary on Windows . : return : the stream"""
try : import os if os . name == 'nt' : fileno = getattr ( stream , 'fileno' , None ) if fileno : no = fileno ( ) if no >= 0 : # -1 means we ' re working as subprocess import msvcrt msvcrt . setmode ( no , os . O_BINARY ) except ImportError ...
def get_edef_props ( object_class , exported_cfgs , ep_namespace , ep_id , ecf_ep_id , ep_rsvc_id , ep_ts , remote_intents = None , fw_id = None , pkg_ver = None , service_intents = None , ) : """Prepares the EDEF properties of an endpoint , merge of RSA and ECF properties"""
osgi_props = get_rsa_props ( object_class , exported_cfgs , remote_intents , ep_rsvc_id , fw_id , pkg_ver , service_intents , ) ecf_props = get_ecf_props ( ecf_ep_id , ep_namespace , ep_rsvc_id , ep_ts ) return merge_dicts ( osgi_props , ecf_props )
def smart_decode ( binary , errors = "strict" ) : """Automatically find the right codec to decode binary data to string . : param binary : binary data : param errors : one of ' strict ' , ' ignore ' and ' replace ' : return : string"""
d = chardet . detect ( binary ) encoding = d [ "encoding" ] confidence = d [ "confidence" ] text = binary . decode ( encoding , errors = errors ) return text , encoding , confidence
def get ( self , name , typ ) : """Gets a counter specified by its name . It counter does not exist or its type doesn ' t match the specified type it creates a new one . : param name : a counter name to retrieve . : param typ : a counter type . : return : an existing or newly created counter of the specif...
if name == None or len ( name ) == 0 : raise Exception ( "Counter name was not set" ) self . _lock . acquire ( ) try : counter = self . _cache [ name ] if name in self . _cache else None if counter == None or counter . type != typ : counter = Counter ( name , typ ) self . _cache [ name ] = c...
def get_volume_list ( self ) -> list : """Get a list of docker volumes . Only the manager nodes can retrieve all the volumes Returns : list , all the names of the volumes in swarm"""
# Initialising empty list volumes = [ ] # Raise an exception if we are not a manager if not self . _manager : raise RuntimeError ( 'Only the Swarm manager node can retrieve' ' all the services.' ) volume_list = self . _client . volumes . list ( ) for v_list in volume_list : volumes . append ( v_list . name ) re...
def extract_format_spec ( cls , format ) : """Pull apart the format : [ [ fill ] align ] [ 0 ] [ width ] [ . precision ] [ type ]"""
# - - BASED - ON : parse . extract _ format ( ) # pylint : disable = redefined - builtin , unsubscriptable - object if not format : raise ValueError ( "INVALID-FORMAT: %s (empty-string)" % format ) orig_format = format fill = align = None if format [ 0 ] in cls . ALIGN_CHARS : align = format [ 0 ] format = ...
def user_auth_token ( self ) : """GPGAuth Stage1"""
# stage0 is a prequisite if not self . server_identity_is_verified : return False server_login_response = post_log_in ( self , keyid = self . user_fingerprint ) if not check_server_login_stage1_response ( server_login_response ) : raise GPGAuthStage1Exception ( "Login endpoint wrongly formatted" ) # Get the enc...
def _get_config_float ( self , section : str , key : str , fallback : float = object ( ) ) -> float : """Gets a float config value : param section : Section : param key : Key : param fallback : Optional fallback value"""
return self . _config . getfloat ( section , key , fallback = fallback )
def clear ( self , only_read = False ) : """> > > cache = Cache ( log _ level = logging . WARNING ) > > > cache . put ( ' a ' , 0) > > > cache . put ( ' b ' , 1) > > > cache . size ( ) > > > cache . clear ( ) > > > cache . size ( )"""
self . cache_items . clear ( ) self . total_access_count = 0 self . logger . debug ( 'Cache clear operation is completed' )
def with_source_port_tag ( self , tags , connected_value ) : """Add a Source Port tag to the tags list , removing any other Source Ports"""
new_tags = [ t for t in tags if not t . startswith ( "sourcePort:" ) ] new_tags . append ( self . source_port_tag ( connected_value ) ) return new_tags
def validate_page_size ( ctx , param , value ) : """Ensure that a valid value for page size is chosen ."""
# pylint : disable = unused - argument if value == 0 : raise click . BadParameter ( "Page size must be non-zero or unset." , param = param ) return value
def _run_tool ( cmd , use_container = True , work_dir = None , log_file = None ) : """Run with injection of bcbio path . Place at end for runs without containers to avoid overriding other bcbio installations ."""
if isinstance ( cmd , ( list , tuple ) ) : cmd = " " . join ( [ str ( x ) for x in cmd ] ) cmd = utils . local_path_export ( at_start = use_container ) + cmd if log_file : cmd += " 2>&1 | tee -a %s" % log_file try : print ( "Running: %s" % cmd ) subprocess . check_call ( cmd , shell = True ) finally : ...
def load_xml ( self , filepath ) : """Loads the values of the configuration variables from an XML path ."""
from os import path import xml . etree . ElementTree as ET # Make sure the file exists and then import it as XML and read the values out . uxpath = path . expanduser ( filepath ) if path . isfile ( uxpath ) : tree = ET . parse ( uxpath ) vms ( "Parsing global settings from {}." . format ( uxpath ) ) root = ...
def style ( self ) : """Add summaries and convert to Pandas Styler"""
row_titles = [ a . title for a in self . _cleaned_summary_rows ] col_titles = [ a . title for a in self . _cleaned_summary_cols ] row_ix = pd . IndexSlice [ row_titles , : ] col_ix = pd . IndexSlice [ : , col_titles ] def handle_na ( df ) : df . loc [ col_ix ] = df . loc [ col_ix ] . fillna ( '' ) df . loc [ ro...
def on_consume_ready ( self , connection , channel , consumers , ** kwargs ) : """Kombu callback when consumers are ready to accept messages . Called after any ( re ) connection to the broker ."""
if not self . _consumers_ready . ready ( ) : _log . debug ( 'consumer started %s' , self ) self . _consumers_ready . send ( None )
def decrypt ( ciphertext , keyPath ) : """Decrypts a given message that was encrypted with the encrypt ( ) method . : param ciphertext : The encrypted message ( as a string ) . : param keyPath : A path to a file containing a 256 - bit key ( and nothing else ) . : type ciphertext : bytes : type keyPath : str...
with open ( keyPath , 'rb' ) as f : key = f . read ( ) if len ( key ) != SecretBox . KEY_SIZE : raise ValueError ( "Key is %d bytes, but must be exactly %d bytes" % ( len ( key ) , SecretBox . KEY_SIZE ) ) sb = SecretBox ( key ) # The nonce is kept with the message . return sb . decrypt ( ciphertext )
async def load ( self , node_id = None ) : """Load nodes from KLF 200 , if no node _ id is specified all nodes are loaded ."""
if node_id is not None : await self . _load_node ( node_id = node_id ) else : await self . _load_all_nodes ( )
def user_update ( object_id , input_params = { } , always_retry = False , ** kwargs ) : """Invokes the / user - xxxx / update API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Users # API - method % 3A - % 2Fuser - xxxx % 2Fupdate"""
return DXHTTPRequest ( '/%s/update' % object_id , input_params , always_retry = always_retry , ** kwargs )
def rewrite_reserved_words ( func ) : """Given a function whos kwargs need to contain a reserved word such as ` in ` , allow calling that function with the keyword as ` in _ ` , such that function kwargs are rewritten to use the reserved word ."""
@ partial_safe_wraps ( func ) def inner ( * args , ** kwargs ) : for word in RESERVED_WORDS : key = "{0}_" . format ( word ) if key in kwargs : kwargs [ word ] = kwargs . pop ( key ) return func ( * args , ** kwargs ) return inner
def nacm_rule_list_rule_module_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) nacm = ET . SubElement ( config , "nacm" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-acm" ) rule_list = ET . SubElement ( nacm , "rule-list" ) name_key = ET . SubElement ( rule_list , "name" ) name_key . text = kwargs . pop ( 'name' ) rule = ET . SubElement ( rule_list , "rule...
def add_line_segments ( self , vertices , close = True ) : """Add a straight line segment to each point in * vertices * . * vertices * must be an iterable of ( x , y ) pairs ( 2 - tuples ) . Each x and y value is rounded to the nearest integer before use . The optional * close * parameter determines whether t...
for x , y in vertices : self . _add_line_segment ( x , y ) if close : self . _add_close ( ) return self
def lovasz_grad ( gt_sorted ) : """Computes gradient of the Lovasz extension w . r . t sorted errors See Alg . 1 in paper"""
p = len ( gt_sorted ) gts = gt_sorted . sum ( ) intersection = gts - gt_sorted . float ( ) . cumsum ( 0 ) union = gts + ( 1 - gt_sorted ) . float ( ) . cumsum ( 0 ) jaccard = 1. - intersection / union if p > 1 : # cover 1 - pixel case jaccard [ 1 : p ] = jaccard [ 1 : p ] - jaccard [ 0 : - 1 ] return jaccard
def get_float ( self , key , default = UndefinedKey ) : """Return float representation of value found at key : param key : key to use ( dot separated ) . E . g . , a . b . c : type key : basestring : param default : default value if key not found : type default : float : return : float value : type retu...
value = self . get ( key , default ) try : return float ( value ) if value is not None else None except ( TypeError , ValueError ) : raise ConfigException ( u"{key} has type '{type}' rather than 'float'" . format ( key = key , type = type ( value ) . __name__ ) )
def from_design_day_properties ( cls , name , day_type , location , analysis_period , dry_bulb_max , dry_bulb_range , humidity_type , humidity_value , barometric_p , wind_speed , wind_dir , sky_model , sky_properties ) : """Create a design day object from various key properties . Args : name : A text string to ...
dry_bulb_condition = DryBulbCondition ( dry_bulb_max , dry_bulb_range ) humidity_condition = HumidityCondition ( humidity_type , humidity_value , barometric_p ) wind_condition = WindCondition ( wind_speed , wind_dir ) if sky_model == 'ASHRAEClearSky' : sky_condition = OriginalClearSkyCondition . from_analysis_perio...
def canmultiplyby ( self , other ) : '''Multiplication is not well - defined for all pairs of multipliers because the resulting possibilities do not necessarily form a continuous range . For example : {0 , x } * { 0 , y } = { 0 , x * y } {2 } * { 3 } = { 6} {2 } * { 1,2 } = ERROR The proof isn ' t simpl...
return other . optional == bound ( 0 ) or self . optional * other . mandatory + bound ( 1 ) >= self . mandatory
def set_mac_address ( self , mac_address = None , default = False , disable = False ) : """Sets the virtual - router mac address This method will set the switch virtual - router mac address . If a virtual - router mac address already exists it will be overwritten . Args : mac _ address ( string ) : The mac ...
base_command = 'ip virtual-router mac-address' if not default and not disable : if mac_address is not None : # Check to see if mac _ address matches expected format if not re . match ( r'(?:[a-f0-9]{2}:){5}[a-f0-9]{2}' , mac_address ) : raise ValueError ( 'mac_address must be formatted like:' 'a...
def p_partselect_pointer ( self , p ) : 'partselect : pointer LBRACKET expression COLON expression RBRACKET'
p [ 0 ] = Partselect ( p [ 1 ] , p [ 3 ] , p [ 5 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def _build_data_block ( self , lexer ) : """Build the data block of : class : ` ~ ctfile . ctfile . SDfile ` instance . : return : Data block . : rtype : : py : class : ` collections . OrderedDict ` ."""
data_block = OrderedDict ( ) header = '' while True : token = next ( lexer ) key = token . __class__ . __name__ if key == 'DataHeader' : header = token . header [ 1 : - 1 ] data_block . setdefault ( header , [ ] ) elif key == 'DataItem' : data_block [ header ] . append ( token . ...
def time_to_first_byte ( self ) : """Time to first byte of the page request in ms"""
# The unknown page is just a placeholder for entries with no page ID . # As such , it would not have a TTFB if self . page_id == 'unknown' : return None ttfb = 0 for entry in self . entries : if entry [ 'response' ] [ 'status' ] == 200 : for k , v in iteritems ( entry [ 'timings' ] ) : if k ...
def stoch2array ( self ) : """Return the stochastic objects as an array ."""
a = np . empty ( self . dim ) for stochastic in self . stochastics : a [ self . _slices [ stochastic ] ] = stochastic . value return a
def before_request ( self , request , method , url , headers ) : """Performs credential - specific before request logic . Args : request ( Any ) : Unused . JWT credentials do not need to make an HTTP request to refresh . method ( str ) : The request ' s HTTP method . url ( str ) : The request ' s URI . Th...
# pylint : disable = unused - argument # ( pylint doesn ' t correctly recognize overridden methods . ) parts = urllib . parse . urlsplit ( url ) # Strip query string and fragment audience = urllib . parse . urlunsplit ( ( parts . scheme , parts . netloc , parts . path , "" , "" ) ) token = self . _get_jwt_for_audience ...
def nlevenshtein ( seq1 , seq2 , method = 1 ) : """Compute the normalized Levenshtein distance between ` seq1 ` and ` seq2 ` . Two normalization methods are provided . For both of them , the normalized distance will be a float between 0 and 1 , where 0 means equal and 1 completely different . The computation ...
if seq1 == seq2 : return 0.0 len1 , len2 = len ( seq1 ) , len ( seq2 ) if len1 == 0 or len2 == 0 : return 1.0 if len1 < len2 : # minimize the arrays size len1 , len2 = len2 , len1 seq1 , seq2 = seq2 , seq1 if method == 1 : return levenshtein ( seq1 , seq2 ) / float ( len1 ) if method != 2 : rais...
def get_summary_string ( self ) : """Get a formatted string summarising the plugins that were loaded ."""
rows = [ [ "PLUGIN TYPE" , "NAME" , "DESCRIPTION" , "STATUS" ] , [ "-----------" , "----" , "-----------" , "------" ] ] for plugin_type in sorted ( self . get_plugin_types ( ) ) : type_name = plugin_type . replace ( '_' , ' ' ) for name in sorted ( self . get_plugins ( plugin_type ) ) : module = self ....
def default_value ( self ) : """Property to return the default value . If the default value is callable and call _ default is True , return the result of default ( ) . Else return default . Returns : object : the default value ."""
if callable ( self . default ) and self . call_default : return self . default ( ) return self . default
def get_cli_static_event_returns ( self , jid , minions , timeout = None , tgt = '*' , tgt_type = 'glob' , verbose = False , show_timeout = False , show_jid = False ) : '''Get the returns for the command line interface via the event system'''
log . trace ( 'entered - function get_cli_static_event_returns()' ) minions = set ( minions ) if verbose : msg = 'Executing job with jid {0}' . format ( jid ) print ( msg ) print ( '-' * len ( msg ) + '\n' ) elif show_jid : print ( 'jid: {0}' . format ( jid ) ) if timeout is None : timeout = self . ...
def get_permissions ( parser , token ) : """Retrieves all permissions associated with the given obj and user and assigns the result to a context variable . Syntax : : { % get _ permissions obj % } { % for perm in permissions % } { { perm } } { % endfor % } { % get _ permissions obj as " my _ permissio...
return PermissionsForObjectNode . handle_token ( parser , token , approved = True , name = '"permissions"' )
def if_modified_since ( self ) -> Optional [ datetime . datetime ] : """The value of If - Modified - Since HTTP header , or None . This header is represented as a ` datetime ` object ."""
return self . _http_date ( self . headers . get ( hdrs . IF_MODIFIED_SINCE ) )
def get_contents_dir ( node ) : """Return content signatures and names of all our children separated by new - lines . Ensure that the nodes are sorted ."""
contents = [ ] for n in sorted ( node . children ( ) , key = lambda t : t . name ) : contents . append ( '%s %s\n' % ( n . get_csig ( ) , n . name ) ) return '' . join ( contents )
def to_tuple ( self , iterable , surround = "()" , joiner = ", " ) : """Returns the iterable as a SQL tuple ."""
return "{0}{1}{2}" . format ( surround [ 0 ] , joiner . join ( iterable ) , surround [ 1 ] )
def is_acquired ( self ) : """Check if the lock is acquired"""
values = self . client . get ( self . key ) return six . b ( self . _uuid ) in values
def multiply ( self , p , e ) : """Multiply a point by an integer ."""
e %= self . order ( ) if p == self . _infinity or e == 0 : return self . _infinity pubkey = create_string_buffer ( 64 ) public_pair_bytes = b'\4' + to_bytes_32 ( p [ 0 ] ) + to_bytes_32 ( p [ 1 ] ) r = libsecp256k1 . secp256k1_ec_pubkey_parse ( libsecp256k1 . ctx , pubkey , public_pair_bytes , len ( public_pair_byt...
def coerce ( cls , key , value ) : """Ensure that loaded values are PasswordHashes ."""
if isinstance ( value , PasswordHash ) : return value return super ( PasswordHash , cls ) . coerce ( key , value )
def _handler ( func ) : "Decorate a command handler"
def _wrapped ( * a , ** k ) : r = func ( * a , ** k ) if r is None : r = 0 return r return staticmethod ( _wrapped )
def target ( self ) : """Returns the code element that is the actual executable that this type executable points to ."""
if self . pointsto is not None : # It is in the format of module . executable . xinst = self . module . parent . get_executable ( self . pointsto . lower ( ) ) return xinst else : # The executable it points to is the same as its name . fullname = "{}.{}" . format ( self . module . name , self . name ) r...
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_vlan_disc_req ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fcoe_get_interface = ET . Element ( "fcoe_get_interface" ) config = fcoe_get_interface output = ET . SubElement ( fcoe_get_interface , "output" ) fcoe_intf_list = ET . SubElement ( output , "fcoe-intf-list" ) fcoe_intf_fcoe_port_id_key = ET . SubElement ( fcoe_intf_list , "fcoe-intf-f...
def valid_options ( kwargs , allowed_options ) : """Checks that kwargs are valid API options"""
diff = set ( kwargs ) - set ( allowed_options ) if diff : print ( "Invalid option(s): " , ', ' . join ( diff ) ) return False return True
def _infer_dtype ( array , name = None ) : """Given an object array with no missing values , infer its dtype from its first element"""
if array . dtype . kind != 'O' : raise TypeError ( 'infer_type must be called on a dtype=object array' ) if array . size == 0 : return np . dtype ( float ) element = array [ ( 0 , ) * array . ndim ] if isinstance ( element , ( bytes , str ) ) : return strings . create_vlen_dtype ( type ( element ) ) dtype =...
def guess_cortex_cmap ( pname ) : '''guess _ cortex _ cmap ( proptery _ name ) yields a tuple ( cmap , ( vmin , vmax ) ) of a cortical color map appropriate to the given property name and the suggested value scaling for the cmap . If the given property is not a string or is not recognized then the log _ eccentr...
if not pimms . is_str ( pname ) : return ( log_eccentricity , None , None ) if pname in colormaps : return colormaps [ pname ] # check each manually for ( k , v ) in six . iteritems ( colormaps ) : if pname . endswith ( k ) : return v for ( k , v ) in six . iteritems ( colormaps ) : if pname . s...
def sync_accounts_from_stormpath ( self , sync_groups = True ) : """: arg sync _ groups : WARNING ! ! ! Groups will be deleted from stormpath if not present locally when user logs in ! Sync accounts from stormpath - > local database . This may take a long time , depending on how many users you have in your ...
if sync_groups : sp_groups = [ g . name for g in APPLICATION . groups ] db_groups = set ( Group . objects . all ( ) . values_list ( 'name' , flat = True ) ) missing_from_db = set ( sp_groups ) . difference ( db_groups ) if missing_from_db : groups_to_create = [ ] for g_name in missing_fr...
def _get_dpi_from ( cmd , pattern , func ) : """Match pattern against the output of func , passing the results as floats to func . If anything fails , return None ."""
try : out , _ = run_subprocess ( [ cmd ] ) except ( OSError , CalledProcessError ) : pass else : match = re . search ( pattern , out ) if match : return func ( * map ( float , match . groups ( ) ) )
def _ir_calibrate ( self , data ) : """IR calibration ."""
# No radiance - > no temperature data = da . where ( data == 0 , np . float32 ( np . nan ) , data ) cwl = self . _header [ 'block5' ] [ "central_wave_length" ] [ 0 ] * 1e-6 c__ = self . _header [ 'calibration' ] [ "speed_of_light" ] [ 0 ] h__ = self . _header [ 'calibration' ] [ "planck_constant" ] [ 0 ] k__ = self . _...
def change_password ( ) : """View function which handles a change password request ."""
form_class = _security . change_password_form if request . is_json : form = form_class ( MultiDict ( request . get_json ( ) ) ) else : form = form_class ( ) if form . validate_on_submit ( ) : after_this_request ( _commit ) change_user_password ( current_user . _get_current_object ( ) , form . new_passwo...
def _sanitize_config ( config ) : '''check that the config has the correct keys , add missing keys if necessary'''
if 'checks' in config : checks = config [ 'checks' ] if 'structural_checks' not in checks : checks [ 'structural_checks' ] = [ ] if 'neuron_checks' not in checks : checks [ 'neuron_checks' ] = [ ] else : raise ConfigError ( 'Need to have "checks" in the config' ) if 'options' not in conf...
def sanitizer ( name , replacements = [ ( ':' , '_' ) , ( '/' , '_' ) , ( '\\' , '_' ) ] ) : """String sanitizer to avoid problematic characters in filenames ."""
for old , new in replacements : name = name . replace ( old , new ) return name
def set_bn_eval ( m : nn . Module ) -> None : "Set bn layers in eval mode for all recursive children of ` m ` ."
for l in m . children ( ) : if isinstance ( l , bn_types ) and not next ( l . parameters ( ) ) . requires_grad : l . eval ( ) set_bn_eval ( l )
def is_in ( self , search_list , pair ) : """If pair is in search _ list , return the index . Otherwise return - 1"""
index = - 1 for nr , i in enumerate ( search_list ) : if ( np . all ( i == pair ) ) : return nr return index
def jump ( self , selected_number : int ) -> None : """Jump to a specific trace frame in a trace . Parameters : selected _ number : int the trace frame number from trace output"""
self . _verify_entrypoint_selected ( ) if selected_number < 1 or selected_number > len ( self . trace_tuples ) : raise UserError ( "Trace frame number out of bounds " f"(expected 1-{len(self.trace_tuples)} but got {selected_number})." ) self . current_trace_frame_index = selected_number - 1 self . trace ( )
def _get_el_to_normative ( parent_elem , normative_parent_elem ) : """Return ordered dict ` ` el _ to _ normative ` ` , which maps children of ` ` parent _ elem ` ` to their normative counterparts in the children of ` ` normative _ parent _ elem ` ` or to ` ` None ` ` if there is no normative parent . If ther...
el_to_normative = OrderedDict ( ) if normative_parent_elem is None : for el in parent_elem : el_to_normative [ el ] = None else : for norm_el in normative_parent_elem : matches = [ el for el in parent_elem if el . get ( "TYPE" ) == norm_el . get ( "TYPE" ) and el . get ( "LABEL" ) == norm_el . g...
def load ( self ) : """Load the minimum needs . If the minimum needs defined in QSettings use it , if not , get the most relevant available minimum needs ( based on QGIS locale ) . The last thing to do is to just use the default minimum needs ."""
self . minimum_needs = self . settings . value ( 'MinimumNeeds' ) if not self . minimum_needs or self . minimum_needs == '' : # Load the most relevant minimum needs # If more than one profile exists , just use defaults so # the user doesn ' t get confused . profiles = self . get_profiles ( ) if len ( profiles )...
def gather ( self , iterable ) : """Calls the lookup with gather True Passing iterable and yields the result ."""
for result in self . lookup ( iterable , gather = True ) : yield result
def callback ( self , position ) : """Allows the execution of custom code between creation of the zip file and deployment to AWS . : return : None"""
callbacks = self . stage_config . get ( 'callbacks' , { } ) callback = callbacks . get ( position ) if callback : ( mod_path , cb_func_name ) = callback . rsplit ( '.' , 1 ) try : # Prefer callback in working directory if mod_path . count ( '.' ) >= 1 : # Callback function is nested in a folder ...
def portfolio_lp ( weights , latest_prices , min_allocation = 0.01 , total_portfolio_value = 10000 ) : """For a long only portfolio , convert the continuous weights to a discrete allocation using Mixed Integer Linear Programming . This can be thought of as a clever way to round the continuous weights to an inte...
import pulp if not isinstance ( weights , dict ) : raise TypeError ( "weights should be a dictionary of {ticker: weight}" ) if not isinstance ( latest_prices , ( pd . Series , dict ) ) : raise TypeError ( "latest_prices should be a pd.Series" ) if min_allocation > 0.3 : raise ValueError ( "min_allocation sh...
def remove_edges ( self , from_idx , to_idx , symmetric = False , copy = False ) : '''Removes all from - > to and to - > from edges . Note : the symmetric kwarg is unused .'''
flat_inds = self . _pairs . dot ( ( self . _num_vertices , 1 ) ) # convert to sorted order and flatten to_remove = ( np . minimum ( from_idx , to_idx ) * self . _num_vertices + np . maximum ( from_idx , to_idx ) ) mask = np . in1d ( flat_inds , to_remove , invert = True ) res = self . copy ( ) if copy else self res . _...
def relate_obs_ids_to_chosen_alts ( obs_id_array , alt_id_array , choice_array ) : """Creates a dictionary that relates each unique alternative id to the set of observations ids that chose the given alternative . Parameters obs _ id _ array : 1D ndarray of ints . Should be a long - format array of observati...
# Figure out which units of observation chose each alternative . chosen_alts_to_obs_ids = { } for alt_id in np . sort ( np . unique ( alt_id_array ) ) : # Determine which observations chose the current alternative . selection_condition = np . where ( ( alt_id_array == alt_id ) & ( choice_array == 1 ) ) # Store ...
def get_user_role_model ( ) : """Returns the UserRole model that is active in this project ."""
app_model = getattr ( settings , "ARCTIC_USER_ROLE_MODEL" , "arctic.UserRole" ) try : return django_apps . get_model ( app_model ) except ValueError : raise ImproperlyConfigured ( "ARCTIC_USER_ROLE_MODEL must be of the " "form 'app_label.model_name'" ) except LookupError : raise ImproperlyConfigured ( "ARCT...
def filter ( self , func ) : """Returns a SndRcv list filtered by a truth function"""
return self . __class__ ( [ i for i in self . res if func ( * i ) ] , name = 'filtered %s' % self . listname )
def comp_centroid ( data , bounding_box , debug_plot = False , plot_reference = None , logger = None ) : """Detect objects in a region and return the centroid of the brightest one"""
from matplotlib . patches import Ellipse if logger is None : logger = logging . getLogger ( __name__ ) region = bounding_box . slice ref_x = region [ 1 ] . start ref_y = region [ 0 ] . start logger . debug ( 'region ofset is %s, %s' , ref_x , ref_y ) subimage = data [ region ] . copy ( ) bkg = sep . Background ( su...
def update ( self ) : """Update the cloud stats . Return the stats ( dict )"""
# Init new stats stats = self . get_init_value ( ) # Requests lib is needed to get stats from the Cloud API if import_error_tag : return stats # Update the stats if self . input_method == 'local' : stats = self . OPENSTACK . stats # Example : # Uncomment to test on physical computer # stats = { ' am...
def run ( self , tokens ) : """Runs the current list of functions that make up the pipeline against the passed tokens ."""
for fn in self . _stack : results = [ ] for i , token in enumerate ( tokens ) : # JS ignores additional arguments to the functions but we # force pipeline functions to declare ( token , i , tokens ) # or * args result = fn ( token , i , tokens ) if not result : continue ...
def _jstype ( self , stype , sval ) : """Get JavaScript name for given data type , called by ` _ build _ schema ` ."""
if stype == self . IS_LIST : return "array" if stype == self . IS_DICT : return "object" if isinstance ( sval , Scalar ) : return sval . jstype # it is a Schema , so return type of contents v = sval . _schema return self . _jstype ( self . _whatis ( v ) , v )
def _object_name_html ( self ) : """Return an html admin link with the object ' s name as text . If the object doesn ' t exist , return " ( deleted ) " ."""
if self . presently . exists : url = self . url ( ) return "<a href=\"%s\">%s</a>" % ( url , unicode ( self . get_object ( ) ) , ) else : return "(deleted)"
def parse_operations ( self ) : """Flatten routes into a path - > method - > route structure"""
resource_defs = { getmeta ( resources . Error ) . resource_name : resource_definition ( resources . Error ) , getmeta ( resources . Listing ) . resource_name : resource_definition ( resources . Listing ) , } paths = collections . OrderedDict ( ) for path , operation in self . parent . op_paths ( ) : # Cut of first item...
def random_connection ( self ) : '''Pick a random living connection'''
# While at the moment there ' s no need for this to be a context manager # per se , I would like to use that interface since I anticipate # adding some wrapping around it at some point . yield random . choice ( [ conn for conn in self . connections ( ) if conn . alive ( ) ] )
def change_quantity ( self , pk , quantity ) : """Change the quantity of an item . Parameters pk : str or int The primary key of the item . quantity : int - convertible A new quantity . Raises ItemNotInCart NegativeItemQuantity NonConvertibleItemQuantity TooLargeItemQuantity ZeroItemQuantity""...
pk = str ( pk ) try : item = self . items [ pk ] except KeyError : raise ItemNotInCart ( pk = pk ) item . quantity = quantity self . update ( )
def default_loader ( obj , defaults = None ) : """Loads default settings and check if there are overridings exported as environment variables"""
defaults = defaults or { } default_settings_values = { key : value for key , value in default_settings . __dict__ . items ( ) # noqa if key . isupper ( ) } all_keys = deduplicate ( list ( defaults . keys ( ) ) + list ( default_settings_values . keys ( ) ) ) for key in all_keys : if not obj . exists ( key ) : ...
def find_regions ( self , word ) : """Find regions R1 and R2."""
length = len ( word ) for index , match in enumerate ( re . finditer ( "[aeiouy][^aeiouy]" , word ) ) : if index == 0 : if match . end ( ) < length : self . r1 = match . end ( ) if index == 1 : if match . end ( ) < length : self . r2 = match . end ( ) break
def detection ( reference_intervals , estimated_intervals , window = 0.5 , beta = 1.0 , trim = False ) : """Boundary detection hit - rate . A hit is counted whenever an reference boundary is within ` ` window ` ` of a estimated boundary . Note that each boundary is matched at most once : this is achieved by c...
validate_boundary ( reference_intervals , estimated_intervals , trim ) # Convert intervals to boundaries reference_boundaries = util . intervals_to_boundaries ( reference_intervals ) estimated_boundaries = util . intervals_to_boundaries ( estimated_intervals ) # Suppress the first and last intervals if trim : refer...
def parse_setup ( filepath ) : '''Get the kwargs from the setup function in setup . py'''
# TODO : Need to parse setup . cfg and merge with the data from below # Monkey patch setuptools . setup to capture keyword arguments setup_kwargs = { } def setup_interceptor ( ** kwargs ) : setup_kwargs . update ( kwargs ) import setuptools setuptools_setup = setuptools . setup setuptools . setup = setup_intercepto...
def p_multiplicative_expr ( self , p ) : """multiplicative _ expr : unary _ expr | multiplicative _ expr MULT unary _ expr | multiplicative _ expr DIV unary _ expr | multiplicative _ expr MOD unary _ expr"""
if len ( p ) == 2 : p [ 0 ] = p [ 1 ] else : p [ 0 ] = ast . BinOp ( op = p [ 2 ] , left = p [ 1 ] , right = p [ 3 ] )
def printcolour ( text , sameline = False , colour = get_colour ( "ENDC" ) ) : """Print color text using escape codes"""
if sameline : sep = '' else : sep = '\n' sys . stdout . write ( get_colour ( colour ) + text + bcolours [ "ENDC" ] + sep )
def apply ( self , func , ids = None , applyto = 'measurement' , output_format = 'DataFrame' , noneval = nan , setdata = False , dropna = False , ID = None ) : """Apply func to each of the specified measurements . Parameters func : callable Accepts a Measurement object or a DataFrame . ids : hashable | iter...
_output = 'collection' if output_format == 'collection' else 'dict' result = super ( OrderedCollection , self ) . apply ( func , ids , applyto , noneval , setdata , output_format = _output ) # Note : result should be of type dict or collection for the code # below to work if output_format is 'dict' : return result ...
def update_source ( self , ** kwargs ) : """Set BGP update source property for a neighbor . This method currently only supports loopback interfaces . Args : vrf ( str ) : The VRF for this BGP process . rbridge _ id ( str ) : The rbridge ID of the device on which BGP will be configured in a VCS fabric . ...
callback = kwargs . pop ( 'callback' , self . _callback ) ip_addr = ip_interface ( unicode ( kwargs . pop ( 'neighbor' ) ) ) config = self . _update_source_xml ( neighbor = ip_addr , int_type = kwargs . pop ( 'int_type' ) , int_name = kwargs . pop ( 'int_name' ) , rbridge_id = kwargs . pop ( 'rbridge_id' , '1' ) , vrf ...
def _write_frame ( self , frame_out ) : """Write a pamqp frame from Channel0. : param frame _ out : Amqp frame . : return :"""
self . _connection . write_frame ( 0 , frame_out ) LOGGER . debug ( 'Frame Sent: %s' , frame_out . name )
def sky_within ( self , ra , dec , degin = False ) : """Test whether a sky position is within this region Parameters ra , dec : float Sky position . degin : bool If True the ra / dec is interpreted as degrees , otherwise as radians . Default = False . Returns within : bool True if the given positi...
sky = self . radec2sky ( ra , dec ) if degin : sky = np . radians ( sky ) theta_phi = self . sky2ang ( sky ) # Set values that are nan to be zero and record a mask mask = np . bitwise_not ( np . logical_and . reduce ( np . isfinite ( theta_phi ) , axis = 1 ) ) theta_phi [ mask , : ] = 0 theta , phi = theta_phi . tr...
def upload_file ( self , filename , file_type = FILE_TYPE_FREESURFER_DIRECTORY ) : """Create an anatomy object on local disk from the given file . Currently , only Freesurfer anatomy directories are supported . Expects a tar file . Parameters filename : string Name of the ( uploaded ) file file _ type :...
# We currently only support one file type ( i . e . , FREESURFER _ DIRECTORY ) . if file_type != FILE_TYPE_FREESURFER_DIRECTORY : raise ValueError ( 'Unsupported file type: ' + file_type ) return self . upload_freesurfer_archive ( filename )
def open_link ( self , * args ) : """Open the link in the web browser ."""
if "disabled" not in self . state ( ) : webbrowser . open ( self . _link ) self . __clicked = True self . _on_leave ( )
def watch ( self , pipeline = None , full_document = 'default' , resume_after = None , max_await_time_ms = None , batch_size = None , collation = None , start_at_operation_time = None , session = None ) : """Watch changes on this cluster . Returns a : class : ` ~ MotorChangeStream ` cursor which iterates over cha...
cursor_class = create_class_with_framework ( AgnosticChangeStream , self . _framework , self . __module__ ) # Latent cursor that will send initial command on first " async for " . return cursor_class ( self , pipeline , full_document , resume_after , max_await_time_ms , batch_size , collation , start_at_operation_time ...
def openconfig_interfaces ( device_name = None ) : '''. . versionadded : : 2019.2.0 Return a dictionary structured as standardised in the ` openconfig - interfaces < http : / / ops . openconfig . net / branches / master / openconfig - interfaces . html > ` _ YANG model , containing physical and configuration ...
oc_if = { } interfaces = get_interfaces ( device_name = device_name ) ipaddresses = get_ipaddresses ( device_name = device_name ) for interface in interfaces : if_name , if_unit = _if_name_unit ( interface [ 'name' ] ) if if_name not in oc_if : oc_if [ if_name ] = { 'config' : { 'name' : if_name } , 'su...
def get_or_deploy_token ( runner ) -> Tuple [ ContractProxy , int ] : """Deploy or reuse"""
token_contract = runner . contract_manager . get_contract ( CONTRACT_CUSTOM_TOKEN ) token_config = runner . scenario . get ( 'token' , { } ) if not token_config : token_config = { } address = token_config . get ( 'address' ) block = token_config . get ( 'block' , 0 ) reuse = token_config . get ( 'reuse' , False ) t...
def save_or_update ( self , cluster ) : """Save or update the cluster to persistent state . : param cluster : cluster to save or update : type cluster : : py : class : ` elasticluster . cluster . Cluster `"""
if not os . path . exists ( self . storage_path ) : os . makedirs ( self . storage_path ) path = self . _get_cluster_storage_path ( cluster . name ) cluster . storage_file = path with open ( path , 'wb' ) as storage : self . dump ( cluster , storage )
def events_for_unlock_lock ( initiator_state : InitiatorTransferState , channel_state : NettingChannelState , secret : Secret , secrethash : SecretHash , pseudo_random_generator : random . Random , ) -> List [ Event ] : """Unlocks the lock offchain , and emits the events for the successful payment ."""
# next hop learned the secret , unlock the token locally and send the # lock claim message to next hop transfer_description = initiator_state . transfer_description message_identifier = message_identifier_from_prng ( pseudo_random_generator ) unlock_lock = channel . send_unlock ( channel_state = channel_state , message...
def get_principals ( self , role , anonymous = True , users = True , groups = True , object = None , as_list = True ) : """Return all users which are assigned given role ."""
if not isinstance ( role , Role ) : role = Role ( role ) assert role assert users or groups query = RoleAssignment . query . filter_by ( role = role ) if not anonymous : query = query . filter ( RoleAssignment . anonymous == False ) if not users : query = query . filter ( RoleAssignment . user == None ) eli...
def quote_html ( content ) : """Quote HTML symbols All < , > , & and " symbols that are not a part of a tag or an HTML entity must be replaced with the corresponding HTML entities ( < with & lt ; > with & gt ; & with & amp and " with & quot ) . : param content : str : return : str"""
new_content = '' for symbol in content : new_content += HTML_QUOTES_MAP [ symbol ] if symbol in _HQS else symbol return new_content