signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def corrcoef ( time , crossf , integration_window = 0. ) : """Calculate the correlation coefficient for given auto - and crosscorrelation functions . Standard settings yield the zero lag correlation coefficient . Setting integration _ window > 0 yields the correlation coefficient of integrated auto - and cros...
N = len ( crossf ) cc = np . zeros ( np . shape ( crossf ) [ : - 1 ] ) tbin = abs ( time [ 1 ] - time [ 0 ] ) lim = int ( integration_window / tbin ) if len ( time ) % 2 == 0 : mid = len ( time ) / 2 - 1 else : mid = np . floor ( len ( time ) / 2. ) for i in range ( N ) : ai = np . sum ( crossf [ i , i ] [ ...
def parse_path ( path ) : """Parse a rfc 6901 path ."""
if not path : raise ValueError ( "Invalid path" ) if isinstance ( path , str ) : if path == "/" : raise ValueError ( "Invalid path" ) if path [ 0 ] != "/" : raise ValueError ( "Invalid path" ) return path . split ( _PATH_SEP ) [ 1 : ] elif isinstance ( path , ( tuple , list ) ) : ret...
def ReadStoredProcedures ( self , collection_link , options = None ) : """Reads all store procedures in a collection . : param str collection _ link : The link to the document collection . : param dict options : The request options for the request . : return : Query Iterable of Stored Procedures . : r...
if options is None : options = { } return self . QueryStoredProcedures ( collection_link , None , options )
def get_field_def ( schema , # type : GraphQLSchema parent_type , # type : Union [ GraphQLInterfaceType , GraphQLObjectType ] field_ast , # type : Field ) : # type : ( . . . ) - > Optional [ GraphQLField ] """Not exactly the same as the executor ' s definition of get _ field _ def , in this statically evaluated e...
name = field_ast . name . value if name == "__schema" and schema . get_query_type ( ) == parent_type : return SchemaMetaFieldDef elif name == "__type" and schema . get_query_type ( ) == parent_type : return TypeMetaFieldDef elif name == "__typename" and isinstance ( parent_type , ( GraphQLObjectType , GraphQLIn...
def calculateSignature ( privateSigningKey , message ) : """: type privateSigningKey : ECPrivateKey : type message : bytearray"""
if privateSigningKey . getType ( ) == Curve . DJB_TYPE : rand = os . urandom ( 64 ) res = _curve . calculateSignature ( rand , privateSigningKey . getPrivateKey ( ) , message ) return res else : raise InvalidKeyException ( "Unknown type: %s" % privateSigningKey . getType ( ) )
def cut ( self ) : """Cut text"""
self . truncate_selection ( self . header_end_pos ) if self . has_selected_text ( ) : CodeEditor . cut ( self )
def nbody_separation ( expr , qs ) : """Convert n - body problem to 2 - body problem . Args : expr : sympy expressions to be separated . qs : sympy ' s symbols to be used as supplementary variable . Return : new _ expr ( sympy expr ) , constraints ( sympy expr ) , mapping ( dict ( str , str - > Symbol ) )...
try : import sympy except ImportError : raise ImportError ( "This function requires sympy. Please install it." ) logging . debug ( expr ) free_symbols = expr . free_symbols logging . debug ( free_symbols ) assert type ( expr ) == sympy . Add logging . debug ( expr . args ) mapping = { } new_expr = sympy . expan...
def parse_args ( argv = None ) : """Parse command line options ."""
parser = ArgumentParser ( ) parser . add_argument ( '--replay-file' , dest = "replay_file" , type = str , required = True ) options = parser . parse_args ( argv ) return options
def get ( self , build_record_id , ** kwargs ) : """Get Build Record Push Result by Id . . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please define a ` callback ` function to be invoked when receiving the response . > > > def callback _ function ( respon...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . get_with_http_info ( build_record_id , ** kwargs ) else : ( data ) = self . get_with_http_info ( build_record_id , ** kwargs ) return data
def set_default_moe_hparams ( hparams ) : """Add necessary hyperparameters for mixture - of - experts ."""
hparams . moe_num_experts = 16 hparams . moe_loss_coef = 1e-2 hparams . add_hparam ( "moe_gating" , "top_2" ) # Experts have fixed capacity per batch . We need some extra capacity # in case gating is not perfectly balanced . # moe _ capacity _ factor _ * should be set to a value > = 1. hparams . add_hparam ( "moe_capac...
def height_to_geopotential ( height ) : r"""Compute geopotential for a given height . Parameters height : ` pint . Quantity ` Height above sea level ( array _ like ) Returns ` pint . Quantity ` The corresponding geopotential value ( s ) Examples > > > from metpy . constants import g , G , me , Re ...
# Calculate geopotential geopot = mpconsts . G * mpconsts . me * ( ( 1 / mpconsts . Re ) - ( 1 / ( mpconsts . Re + height ) ) ) return geopot
def filter_leader_files ( cluster_config , broker_files ) : """Given a list of broker files , filters out all the files that are in the replicas . : param cluster _ config : the cluster : type cluster _ config : kafka _ utils . utils . config . ClusterConfig : param broker _ files : the broker files : typ...
print ( "Filtering leaders" ) leader_of = get_partition_leaders ( cluster_config ) result = [ ] for broker , host , files in broker_files : filtered = [ ] for file_path in files : tp = get_tp_from_file ( file_path ) if tp not in leader_of or leader_of [ tp ] == broker : filtered . ap...
def connect ( self , server , port = 6667 ) : """Connects to a given IRC server . After the connection is established , it calls the on _ connect event handler ."""
self . socket . connect ( ( server , port ) ) self . lines = self . _read_lines ( ) for event_handler in list ( self . on_connect ) : event_handler ( self )
def _handle_duplicate_sources ( self , vt , sources ) : """Handles duplicate sources generated by the given gen target by either failure or deletion . This method should be called after all dependencies have been injected into the graph , but before injecting the synthetic version of this target . Returns a b...
target = vt . target target_workdir = vt . results_dir # Walk dependency gentargets and record any sources owned by those targets that are also # owned by this target . duplicates_by_target = OrderedDict ( ) def record_duplicates ( dep ) : if dep == target or not self . is_gentarget ( dep . concrete_derived_from ) ...
def GET ( self , * args , ** kwargs ) : """GET request"""
return self . _handle_api ( self . API_GET , args , kwargs )
def report_stats ( self ) : """Create the dict of stats data for the MCP stats queue"""
if not self . previous : self . previous = dict ( ) for key in self . counters : self . previous [ key ] = 0 values = { 'name' : self . name , 'consumer_name' : self . consumer_name , 'counts' : dict ( self . counters ) , 'previous' : dict ( self . previous ) } self . previous = dict ( self . counters )...
def get_role ( role_id , ** kwargs ) : """Get a role by its ID ."""
try : role = db . DBSession . query ( Role ) . filter ( Role . id == role_id ) . one ( ) return role except NoResultFound : raise HydraError ( "Role not found (role_id={})" . format ( role_id ) )
def _setup_source_and_destination ( self ) : """use the base class to setup the source and destinations but add to that setup the instantiation of the " new _ crash _ source " """
super ( FetchTransformSaveWithSeparateNewCrashSourceApp , self ) . _setup_source_and_destination ( ) if self . config . new_crash_source . new_crash_source_class : self . new_crash_source = self . config . new_crash_source . new_crash_source_class ( self . config . new_crash_source , name = self . app_instance_name...
def to_vobject ( self , filename = None , uid = None ) : """Return iCal object of Remind lines If filename and UID are specified , the vObject only contains that event . If only a filename is specified , the vObject contains all events in the file . Otherwise the vObject contains all all objects of all files ...
self . _update ( ) cal = iCalendar ( ) if uid : self . _gen_vevent ( self . _reminders [ filename ] [ uid ] , cal . add ( 'vevent' ) ) elif filename : for event in self . _reminders [ filename ] . values ( ) : self . _gen_vevent ( event , cal . add ( 'vevent' ) ) else : for filename in self . _remin...
def parse_definitions ( definitions ) : """Parses a list of macro definitions and returns a " symbol table " as a dictionary . : params definitions : A list of command line macro definitions . Each item in the list should be in one of these two formats : * < variable > = < value > * < variable > : ret...
defines = { } if definitions : for definition in definitions : define , value = parse_definition_expr ( definition , default_value = None ) defines [ define ] = value return defines
def from_config ( cls , name , config ) : """Behaves like the base Configurable class ' s ` from _ config ( ) ` except this makes sure that the ` Pluggable ` subclass with the given name is actually a properly installed plugin first ."""
installed_classes = cls . get_installed_classes ( ) if name not in installed_classes : raise ValueError ( "Unknown/unavailable %s" % cls . __name__ . lower ( ) ) pluggable_class = installed_classes [ name ] pluggable_class . validate_config ( config ) instance = pluggable_class ( ) if not instance . name : inst...
def get ( self , location_name ) : """Get a contact address by location name : param str location _ name : name of location : return : return contact address element or None : rtype : ContactAddress"""
location_ref = location_helper ( location_name , search_only = True ) if location_ref : for location in self : if location . location_ref == location_ref : return location
def wait_stopped ( self , timeout = None , force = False ) : """Wait for the thread to stop . You must have previously called signal _ stop or this function will hang . Args : timeout ( float ) : The maximum time to wait for the thread to stop before raising a TimeoutExpiredError . If force is True , Ti...
self . join ( timeout ) if self . is_alive ( ) and force is False : raise TimeoutExpiredError ( "Error waiting for background thread to exit" , timeout = timeout )
def sync_ldap_groups ( self , ldap_groups ) : """Synchronize LDAP groups with local group model ."""
groupname_field = 'name' self . stats_group_total = len ( ldap_groups ) for cname , ldap_attributes in ldap_groups : defaults = { } try : for name , attribute in ldap_attributes . items ( ) : defaults [ self . conf_LDAP_SYNC_GROUP_ATTRIBUTES [ name ] ] = attribute [ 0 ] . decode ( 'utf-8' ) ...
def position_target_global_int_encode ( self , time_boot_ms , coordinate_frame , type_mask , lat_int , lon_int , alt , vx , vy , vz , afx , afy , afz , yaw , yaw_rate ) : '''Reports the current commanded vehicle position , velocity , and acceleration as specified by the autopilot . This should match the command...
return MAVLink_position_target_global_int_message ( time_boot_ms , coordinate_frame , type_mask , lat_int , lon_int , alt , vx , vy , vz , afx , afy , afz , yaw , yaw_rate )
def set_guid ( self ) : """Parses guid and set value"""
try : self . guid = self . soup . find ( 'guid' ) . string except AttributeError : self . guid = None
def QA_util_date_gap ( date , gap , methods ) : ''': param date : 字符串起始日 类型 str eg : 2018-11-11 : param gap : 整数 间隔多数个交易日 : param methods : gt大于 , gte 大于等于 , 小于lt , 小于等于lte , 等于 = = = : return : 字符串 eg : 2000-01-01'''
try : if methods in [ '>' , 'gt' ] : return trade_date_sse [ trade_date_sse . index ( date ) + gap ] elif methods in [ '>=' , 'gte' ] : return trade_date_sse [ trade_date_sse . index ( date ) + gap - 1 ] elif methods in [ '<' , 'lt' ] : return trade_date_sse [ trade_date_sse . index ...
def s_to_ev ( offset_us , source_to_detector_m , array ) : """convert time ( s ) to energy ( eV ) Parameters : numpy array of time in s offset _ us : float . Delay of detector in us source _ to _ detector _ m : float . Distance source to detector in m Returns : numpy array of energy in eV"""
lambda_a = 3956. * ( array + offset_us * 1e-6 ) / source_to_detector_m return ( 81.787 / pow ( lambda_a , 2 ) ) / 1000.
def _init_groups ( self , string ) : """Extracts weather groups ( FM , PROB etc . ) and populates group list Args : TAF report string Raises : MalformedTAF : Group decoding error"""
taf_group_pattern = """ (?:FM|(?:PROB(?:\d{1,2})\s*(?:TEMPO)?)|TEMPO|BECMG|[\S\s])[A-Z0-9\+\-/\s$]+?(?=FM|PROB|TEMPO|BECMG|$) """ group_list = [ ] groups = re . findall ( taf_group_pattern , string , re . VERBOSE ) if not groups : raise MalformedTAF ( "No valid groups found" ) for group in group...
def sample_lists ( items_list , num = 1 , seed = None ) : r"""Args : items _ list ( list ) : num ( int ) : ( default = 1) seed ( None ) : ( default = None ) Returns : list : samples _ list CommandLine : python - m utool . util _ list - - exec - sample _ lists Example : > > > # DISABLE _ DOCTEST ...
if seed is not None : rng = np . random . RandomState ( seed ) else : rng = np . random def random_choice ( items , num ) : size = min ( len ( items ) , num ) return rng . choice ( items , size , replace = False ) . tolist ( ) samples_list = [ random_choice ( items , num ) if len ( items ) > 0 else [ ] ...
def reset ( self ) -> None : """Clear all data in file storage ."""
self . close ( ) for f in os . listdir ( self . dataDir ) : os . remove ( os . path . join ( self . dataDir , f ) ) self . _useLatestChunk ( )
def _get_style_of_faulting_term ( self , C , rake ) : """Returns the style of faulting factor"""
f_n , f_r = self . _get_fault_type_dummy_variables ( rake ) return C [ 'C6' ] * f_n + C [ 'C7' ] * f_r
def return_search_summary ( start_time = 0 , end_time = 0 , nevents = 0 , ifos = None , ** kwargs ) : """Function to create a SearchSummary object where all columns are populated but all are set to values that test False ( ie . strings to ' ' , floats / ints to 0 , . . . ) . This avoids errors when you try to c...
if ifos is None : ifos = [ ] # create an empty search summary search_summary = lsctables . SearchSummary ( ) cols = lsctables . SearchSummaryTable . validcolumns for entry in cols . keys ( ) : if cols [ entry ] in [ 'real_4' , 'real_8' ] : setattr ( search_summary , entry , 0. ) elif cols [ entry ] ...
def get_sentence ( self , offset : int ) -> BioCSentence or None : """Gets sentence with specified offset Args : offset : sentence offset Return : the sentence with specified offset"""
for sentence in self . sentences : if sentence . offset == offset : return sentence return None
def _process_elem_text ( elem , dic , subdic , text = "@text" , ** options ) : """: param elem : ET Element object which has elem . text : param dic : < container > ( dict [ - like ] ) object converted from elem : param subdic : Sub < container > object converted from elem : param options : Keyword options ...
elem . text = elem . text . strip ( ) if elem . text : etext = _parse_text ( elem . text , ** options ) if len ( elem ) or elem . attrib : subdic [ text ] = etext else : dic [ elem . tag ] = etext
def wait_for_jobs ( self , job_ids , timeout , delay ) : """Waits until the jobs appears in the completed job queue ."""
if self . skip : return logger . debug ( "Waiting up to %d sec for completion of the job IDs %s" , timeout , job_ids ) remaining_job_ids = set ( job_ids ) found_jobs = [ ] countdown = timeout while countdown > 0 : matched_jobs = self . find_jobs ( remaining_job_ids ) if matched_jobs : remaining_job_...
def recognize_byte ( self , image , timeout = 10 ) : """Process a byte image buffer ."""
result = [ ] alpr = subprocess . Popen ( self . _cmd , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . DEVNULL ) # send image try : # pylint : disable = unused - variable stdout , stderr = alpr . communicate ( input = image , timeout = 10 ) stdout = io . StringIO ( str ( stdout , ...
def listDatasetChildren ( self , dataset ) : """takes required dataset parameter returns only children dataset name"""
if ( dataset == "" ) : dbsExceptionHandler ( "dbsException-invalid-input" , "DBSDataset/listDatasetChildren. Parent Dataset name is required." ) conn = self . dbi . connection ( ) try : result = self . datasetchildlist . execute ( conn , dataset ) return result finally : if conn : conn . close (...
def _minion_event ( self , load ) : '''Receive an event from the minion and fire it on the master event interface : param dict load : The minion payload'''
load = self . __verify_load ( load , ( 'id' , 'tok' ) ) if load is False : return { } # Route to master event bus self . masterapi . _minion_event ( load ) # Process locally self . _handle_minion_event ( load )
def retrieve ( self ) : """Retrieves all data for this document and saves it ."""
data = self . resource ( self . id ) . get ( ) self . data = data return data
def make_asset_zip ( asset_dir_path , destination_directory = None ) : """Given an asset directory path , creates an asset zip file in the provided destination directory : param asset _ dir _ path : ( str ) path to the directory containing the asset : param destination _ directory : ( str ) path to the destin...
log = logging . getLogger ( mod_logger + '.make_asset_zip' ) log . info ( 'Attempting to create an asset zip from directory: {d}' . format ( d = asset_dir_path ) ) # Ensure the path is a directory if not os . path . isdir ( asset_dir_path ) : raise AssetZipCreationError ( 'Provided asset_dir_path is not a directory...
def is_equal ( self , other ) : """Equality checker with message : param other : Other Impact Function to be compared . : type other : ImpactFunction : returns : True if both are the same IF , other wise False and the message . : rtype : bool , str"""
properties = [ 'debug_mode' , 'use_rounding' , 'requested_extent' , 'crs' , 'analysis_extent' , 'datastore' , 'name' , 'title' , 'start_datetime' , 'end_datetime' , 'duration' , 'earthquake_function' , # ' performance _ log ' , # I don ' t think need we need this one 'hazard' , 'exposure' , 'aggregation' , # Output lay...
def _duplicate_example ( self , request ) : """Duplicates the specified example . Args : request : A request that should contain ' index ' . Returns : An empty response ."""
index = int ( request . args . get ( 'index' ) ) if index >= len ( self . examples ) : return http_util . Respond ( request , { 'error' : 'invalid index provided' } , 'application/json' , code = 400 ) new_example = self . example_class ( ) new_example . CopyFrom ( self . examples [ index ] ) self . examples . appen...
def closing ( input_rasterfilename , times ) : """Do closing . Closing : Dilate firstly , then Erode . Args : input _ rasterfilename : input original raster image filename . times : Erode and Dilate times . Returns : closing _ raster : raster image after close ."""
input_raster = RasterUtilClass . read_raster ( input_rasterfilename ) closing_raster = input_raster for i in range ( times ) : closing_raster = RasterUtilClass . raster_dilation ( closing_raster ) for i in range ( times ) : closing_raster = RasterUtilClass . raster_erosion ( closing_raster ) return closing_rast...
def random_tickers ( length , n_tickers , endswith = None , letters = None , slicer = itertools . islice ) : """Generate a length - n _ tickers list of unique random ticker symbols . Parameters length : int The length of each ticker string . n _ tickers : int Number of tickers to generate . endswith : s...
# The trick here is that we need uniqueness . That defeats the # purpose of using NumPy because we need to generate 1x1. # ( Although the alternative is just to generate a " large # enough " duplicated sequence and prune from it . ) if letters is None : letters = string . ascii_uppercase if endswith : # Only genera...
def _safe_match_list ( inner_type , argument_value ) : """Represent the list of " inner _ type " objects in MATCH form ."""
stripped_type = strip_non_null_from_type ( inner_type ) if isinstance ( stripped_type , GraphQLList ) : raise GraphQLInvalidArgumentError ( u'MATCH does not currently support nested lists, ' u'but inner type was {}: ' u'{}' . format ( inner_type , argument_value ) ) if not isinstance ( argument_value , list ) : ...
def release ( self ) : """Release the lock ."""
# This decrements the appropriate lock counters , and if the lock # becomes free , it looks for a queued thread to hand it off to . # By doing the handoff here we ensure fairness . me = currentThread ( ) with self . _lock : if self . is_exclusive : if self . _exclusive_owner is not me : raise Ru...
def radius_server_host_key ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) radius_server = ET . SubElement ( config , "radius-server" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" ) host = ET . SubElement ( radius_server , "host" ) hostname_key = ET . SubElement ( host , "hostname" ) hostname_key . text = kwargs . pop ( 'hostname' ) key = ET . SubElement ( ho...
def parse_int ( value , base_unit = None ) : """> > > parse _ int ( ' 1 ' ) = = 1 True > > > parse _ int ( ' 0x400 MB ' , ' 16384kB ' ) = = 64 True > > > parse _ int ( ' 1MB ' , ' kB ' ) = = 1024 True > > > parse _ int ( ' 1000 ms ' , ' s ' ) = = 1 True > > > parse _ int ( ' 1GB ' , ' MB ' ) is None...
convert = { 'kB' : { 'kB' : 1 , 'MB' : 1024 , 'GB' : 1024 * 1024 , 'TB' : 1024 * 1024 * 1024 } , 'ms' : { 'ms' : 1 , 's' : 1000 , 'min' : 1000 * 60 , 'h' : 1000 * 60 * 60 , 'd' : 1000 * 60 * 60 * 24 } , 's' : { 'ms' : - 1000 , 's' : 1 , 'min' : 60 , 'h' : 60 * 60 , 'd' : 60 * 60 * 24 } , 'min' : { 'ms' : - 1000 * 60 , ...
def role_list ( auth = None , ** kwargs ) : '''List roles CLI Example : . . code - block : : bash salt ' * ' keystoneng . role _ list salt ' * ' keystoneng . role _ list domain _ id = b62e76fbeeff4e8fb77073f591cf211e'''
cloud = get_operator_cloud ( auth ) kwargs = _clean_kwargs ( ** kwargs ) return cloud . list_roles ( ** kwargs )
def inj_mass_pdf ( key , mass1 , mass2 , lomass , himass , lomass_2 = 0 , himass_2 = 0 ) : '''Estimate the probability density based on the injection strategy Parameters key : string Injection strategy mass1 : array First mass of the injections mass2 : array Second mass of the injections lomass : fl...
mass1 , mass2 = np . array ( mass1 ) , np . array ( mass2 ) if key == 'totalMass' : # Returns the PDF of mass when total mass is uniformly distributed . # Both the component masses have the same distribution for this case . # Parameters # lomass : lower component mass # himass : higher component mass bound = np . s...
def create_replication_instance ( ReplicationInstanceIdentifier = None , AllocatedStorage = None , ReplicationInstanceClass = None , VpcSecurityGroupIds = None , AvailabilityZone = None , ReplicationSubnetGroupIdentifier = None , PreferredMaintenanceWindow = None , MultiAZ = None , EngineVersion = None , AutoMinorVersi...
pass
def is_done ( self , submissionid_or_submission , user_check = True ) : """Tells if a submission is done and its result is available"""
# TODO : not a very nice way to avoid too many database call . Should be refactored . if isinstance ( submissionid_or_submission , dict ) : submission = submissionid_or_submission else : submission = self . get_submission ( submissionid_or_submission , False ) if user_check and not self . user_is_submission_own...
def rollback ( self , dt ) : """Roll provided date backward to next offset only if not on offset ."""
dt = as_timestamp ( dt ) if not self . onOffset ( dt ) : dt = dt - self . __class__ ( 1 , normalize = self . normalize , ** self . kwds ) return dt
async def execute ( self , keys = [ ] , args = [ ] , client = None ) : "Execute the script , passing any required ` ` args ` `"
if client is None : client = self . registered_client args = tuple ( keys ) + tuple ( args ) # make sure the Redis server knows about the script if isinstance ( client , BasePipeline ) : # make sure this script is good to go on pipeline client . scripts . add ( self ) try : return await client . evalsha ( s...
def handle ( self , * args , ** options ) : """Reset the database for this project . Note : Transaction wrappers are in reverse as a work around for autocommit , anybody know how to do this the right way ?"""
router = options [ 'router' ] dbinfo = settings . DATABASES . get ( router ) if dbinfo is None : raise CommandError ( "Unknown database router %s" % router ) engine = dbinfo . get ( 'ENGINE' ) user = password = database_name = database_host = database_port = '' if engine == 'mysql' : ( user , password , databas...
def __filename_to_modname ( self , pathname ) : """@ type pathname : str @ param pathname : Pathname to a module . @ rtype : str @ return : Module name ."""
filename = PathOperations . pathname_to_filename ( pathname ) if filename : filename = filename . lower ( ) filepart , extpart = PathOperations . split_extension ( filename ) if filepart and extpart : modName = filepart else : modName = filename else : modName = pathname return modNa...
def range ( self ) : """A tuple containing the numeric range for this Slot . The Python equivalent of the CLIPS slot - range function ."""
data = clips . data . DataObject ( self . _env ) lib . EnvSlotRange ( self . _env , self . _cls , self . _name , data . byref ) return tuple ( data . value ) if isinstance ( data . value , list ) else ( )
def buildmod ( * modules ) : '''Build module using znc - buildmod CLI Example : . . code - block : : bash salt ' * ' znc . buildmod module . cpp [ . . . ]'''
# Check if module files are missing missing = [ module for module in modules if not os . path . exists ( module ) ] if missing : return 'Error: The file ({0}) does not exist.' . format ( ', ' . join ( missing ) ) cmd = [ 'znc-buildmod' ] cmd . extend ( modules ) out = __salt__ [ 'cmd.run' ] ( cmd , python_shell = F...
def advect ( f , vx , vy ) : """Move field f according to x and y velocities ( u and v ) using an implicit Euler integrator ."""
rows , cols = f . shape cell_xs , cell_ys = np . meshgrid ( np . arange ( cols ) , np . arange ( rows ) ) center_xs = ( cell_xs - vx ) . ravel ( ) center_ys = ( cell_ys - vy ) . ravel ( ) # Compute indices of source cells . left_ix = np . floor ( center_ys ) . astype ( int ) top_ix = np . floor ( center_xs ) . astype (...
def run ( self , node , expr = None , lineno = None , with_raise = True ) : """Execute parsed Ast representation for an expression ."""
# Note : keep the ' node is None ' test : internal code here may run # run ( None ) and expect a None in return . if time . time ( ) - self . start_time > self . max_time : raise RuntimeError ( ERR_MAX_TIME . format ( self . max_time ) ) out = None if len ( self . error ) > 0 : return out if node is None : ...
def load_from_directory ( list_name ) : """To resolve the symbol in the LEVERAGED _ ETF list , the date on which the symbol was in effect is needed . Furthermore , to maintain a point in time record of our own maintenance of the restricted list , we need a knowledge date . Thus , restricted lists are dictio...
data = { } dir_path = os . path . join ( SECURITY_LISTS_DIR , list_name ) for kd_name in listdir ( dir_path ) : kd = datetime . strptime ( kd_name , DATE_FORMAT ) . replace ( tzinfo = pytz . utc ) data [ kd ] = { } kd_path = os . path . join ( dir_path , kd_name ) for ld_name in listdir ( kd_path ) : ...
def cli ( env ) : """List firewalls ."""
mgr = SoftLayer . FirewallManager ( env . client ) table = formatting . Table ( [ 'firewall id' , 'type' , 'features' , 'server/vlan id' ] ) fwvlans = mgr . get_firewalls ( ) dedicated_firewalls = [ firewall for firewall in fwvlans if firewall [ 'dedicatedFirewallFlag' ] ] for vlan in dedicated_firewalls : features...
def generate_colours ( n ) : """Return a list of ` n ` distinct colours , each represented as an RGB string suitable for use in CSS . Based on the code at http : / / martin . ankerl . com / 2009/12/09 / how - to - create - random - colors - programmatically / : param n : number of colours to generate : ty...
colours = [ ] golden_ratio_conjugate = 0.618033988749895 h = 0.8 # Initial hue s = 0.7 # Fixed saturation v = 0.95 # Fixed value for i in range ( n ) : h += golden_ratio_conjugate h %= 1 colours . append ( hsv_to_rgb ( h , s , v ) ) return colours
def rectangle ( self , x0 , y0 , x1 , y1 ) : """Draw a rectangle"""
x0 , y0 , x1 , y1 = self . rect_helper ( x0 , y0 , x1 , y1 ) self . polyline ( [ [ x0 , y0 ] , [ x1 , y0 ] , [ x1 , y1 ] , [ x0 , y1 ] , [ x0 , y0 ] ] )
def add_transcript ( self , tx ) : """Add a transcript to the locus : param tx : transcript to add : type tx : Transcript"""
for y in [ x . payload for x in self . g . get_nodes ( ) ] : if tx . id in [ z . id for z in y ] : sys . stderr . write ( "WARNING tx is already in graph\n" ) return True # transcript isn ' t part of graph yet n = seqtools . graph . Node ( [ tx ] ) other_nodes = self . g . get_nodes ( ) self . g . a...
def is_reference_target ( resource , rtype , label ) : """Return true if the resource has this rtype with this label"""
prop = resource . props . references . get ( rtype , False ) if prop : return label in prop
def _matches_patterns ( self , matches , context ) : """Search for all matches with current paterns agains input _ string : param matches : matches list : type matches : Matches : param context : context to use : type context : dict : return : : rtype :"""
if not self . disabled ( context ) : patterns = self . effective_patterns ( context ) for pattern in patterns : if not pattern . disabled ( context ) : pattern_matches = pattern . matches ( matches . input_string , context ) if pattern_matches : log ( pattern . lo...
def add_xmlid ( ctx , record , xmlid , noupdate = False ) : """Add a XMLID on an existing record"""
try : ref_id , __ , __ = ctx . env [ 'ir.model.data' ] . xmlid_lookup ( xmlid ) except ValueError : pass # does not exist , we ' ll create a new one else : return ctx . env [ 'ir.model.data' ] . browse ( ref_id ) if '.' in xmlid : module , name = xmlid . split ( '.' ) else : module = '' name...
def list_supported_types ( category_name ) : """Prints a list of supported external account type names for the given category _ name . For example , " AWS _ ACCESS _ KEY _ AUTH " is a supported external account type name for external account category " AWS " ."""
types = get_supported_types ( api , category_name ) type_names = [ type . name for type in types ] print ( "Supported account types by name for '{0}': [{1}]" . format ( category_name , COMMA_WITH_SPACE . join ( map ( str , type_names ) ) ) )
def hazard_notes ( self ) : """Get the hazard specific notes defined in definitions . This method will do a lookup in definitions and return the hazard definition specific notes dictionary . This is a helper function to make it easy to get hazard specific notes from the definitions metadata . . . versiona...
notes = [ ] hazard = definition ( self . hazard . keywords . get ( 'hazard' ) ) if 'notes' in hazard : notes += hazard [ 'notes' ] if self . hazard . keywords [ 'layer_mode' ] == 'classified' : if 'classified_notes' in hazard : notes += hazard [ 'classified_notes' ] if self . hazard . keywords [ 'layer_...
def generate_k ( order , secexp , hash_func , data ) : '''order - order of the DSA generator used in the signature secexp - secure exponent ( private key ) in numeric form hash _ func - reference to the same hash function used for generating hash data - hash in binary form of the signing data'''
qlen = bit_length ( order ) holen = hash_func ( ) . digest_size rolen = ( qlen + 7 ) / 8 bx = number_to_string ( secexp , order ) + bits2octets ( data , order ) # Step B v = b ( '\x01' ) * holen # Step C k = b ( '\x00' ) * holen # Step D k = hmac . new ( k , v + b ( '\x00' ) + bx , hash_func ) . digest ( ) # Step E v =...
def levenshtein_distance ( str_a , str_b ) : """Calculate the Levenshtein distance between string a and b . : param str _ a : String - input string a : param str _ b : String - input string b : return : Number - Levenshtein Distance between string a and b"""
len_a , len_b = len ( str_a ) , len ( str_b ) if len_a > len_b : str_a , str_b = str_b , str_a len_a , len_b = len_b , len_a current = range ( len_a + 1 ) for i in range ( 1 , len_b + 1 ) : previous , current = current , [ i ] + [ 0 ] * len_a for j in range ( 1 , len_a + 1 ) : add , delete = pre...
def run ( args , ff = '' ) : """Run setup . py with monkey patches applied ."""
import setuptools . command . egg_info if ff == 'none' : setuptools . command . egg_info . walk_revctrl = no_walk_revctrl else : setuptools . command . egg_info . walk_revctrl = partial ( walk_revctrl , ff = ff ) sys . argv = [ 'setup.py' ] + args import setup cleanup_pycache ( )
def lookupListener ( self , listenID ) : """( internal ) Retrieve a waiting connection by its connection identifier , passing in the transport to be used to connect the waiting protocol factory to ."""
if listenID in self . inboundConnections : # Make the connection ? cwait , call = self . inboundConnections . pop ( listenID ) # _ ConnectionWaiter instance call . cancel ( ) return cwait
def write_generator_data ( self , file ) : """Writes generator data in MATPOWER format ."""
for generator in self . case . generators : vals = [ ] vals . append ( generator . bus . _i ) vals . append ( "1 " ) # ID vals . append ( generator . p ) vals . append ( generator . q ) vals . append ( generator . q_max ) vals . append ( generator . q_min ) vals . append ( generator ...
def getPlatformInfo ( ) : """Identify platform ."""
if "linux" in sys . platform : platform = "linux" elif "darwin" in sys . platform : platform = "darwin" # win32 elif sys . platform . startswith ( "win" ) : platform = "windows" else : raise Exception ( "Platform '%s' is unsupported!" % sys . platform ) return platform
def newRegion ( self , loc , width , height ) : """Creates a new region on the current screen at the specified offset with the specified width and height ."""
return Region . create ( self . getTopLeft ( ) . offset ( loc ) , width , height )
def get_inline_func ( inline_str , modules = None , ** stream_kwargs ) : """returns a function decorated by ` cbox . stream ` decorator . : param str inline _ str : the inline function to execute , can use ` s ` - local variable as the input line / char / raw ( according to ` input _ type ` param ) . : para...
if not _is_compilable ( inline_str ) : raise ValueError ( 'cannot compile the inline expression - "%s"' % inline_str ) inline_globals = _import_inline_modules ( modules ) func = _inline2func ( inline_str , inline_globals , ** stream_kwargs ) return func
def rolling_update ( config = None , name = None , image = None , container_name = None , rc_new = None ) : """Performs a simple rolling update of a ReplicationController . See https : / / github . com / kubernetes / kubernetes / blob / master / docs / design / simple - rolling - update . md for algorithm detai...
if name is None : raise SyntaxError ( 'K8sReplicationController: name: [ {0} ] cannot be None.' . format ( name ) ) if image is None and rc_new is None : raise SyntaxError ( "K8sReplicationController: please specify either 'image' or 'rc_new'" ) if container_name is not None and image is not None and rc_new is ...
def refresh_if_needed ( self ) : """Refresh the status of the task from server if required ."""
if self . state in ( self . PENDING , self . STARTED ) : try : response , = self . _fetch_result ( ) [ 'tasks' ] except ( KeyError , ValueError ) : raise Exception ( "Unable to find results for task." ) if 'error' in response : self . state == self . FAILURE raise ServerError...
def remove_style ( self ) : """Remove all XSL run rStyle elements"""
for n in self . root . xpath ( './/w:rStyle[@w:val="%s"]' % self . style , namespaces = self . namespaces ) : n . getparent ( ) . remove ( n )
def INIT_LIST_EXPR ( self , cursor ) : """Returns a list of literal values ."""
values = [ self . parse_cursor ( child ) for child in list ( cursor . get_children ( ) ) ] return values
def snakescan ( xi , yi , xf , yf ) : """Scan pixels in a snake pattern along the x - coordinate then y - coordinate : param xi : Initial x - coordinate : type xi : int : param yi : Initial y - coordinate : type yi : int : param xf : Final x - coordinate : type xf : int : param yf : Final y - coordina...
# Determine direction to move dx = 1 if xf >= xi else - 1 dy = 1 if yf >= yi else - 1 # Scan pixels first along x - coordinate then y - coordinate and flip # x - direction when the end of the line is reached x , xa , xb = xi , xi , xf for y in range ( yi , yf + dy , dy ) : for x in range ( xa , xb + dx , dx ) : ...
def _read ( self , n ) : """It seems that SSL Objects read ( ) method may not supply as much as you ' re asking for , at least with extremely large messages . somewhere > 16K - found this in the test _ channel . py test _ large unittest ."""
result = self . sslobj . read ( n ) while len ( result ) < n : s = self . sslobj . read ( n - len ( result ) ) if not s : raise IOError ( 'Socket closed' ) result += s return result
def parse_files ( self , req , name , field ) : """Pull a file from the request ."""
files = ( ( k , v ) for k , v in req . POST . items ( ) if hasattr ( v , "file" ) ) return core . get_value ( MultiDict ( files ) , name , field )
def _sync_from_disk ( self ) : """Read any changes made on disk to this Refpkg . This is necessary if other programs are making changes to the Refpkg on disk and your program must be synchronized to them ."""
try : fobj = self . open_manifest ( 'r' ) except IOError as e : if e . errno == errno . ENOENT : raise ValueError ( "couldn't find manifest file in %s" % ( self . path , ) ) elif e . errno == errno . ENOTDIR : raise ValueError ( "%s is not a directory" % ( self . path , ) ) else : ...
def aspectMalefics ( self ) : """Returns a list with the bad aspects the object makes to the malefics ."""
malefics = [ const . MARS , const . SATURN ] return self . __aspectLists ( malefics , aspList = [ 0 , 90 , 180 ] )
def cache_status ( db , aid , force = False ) : """Calculate and cache status for given anime . Don ' t do anything if status already exists and force is False ."""
with db : cur = db . cursor ( ) if not force : # We don ' t do anything if we already have this aid in our # cache . cur . execute ( 'SELECT 1 FROM cache_anime WHERE aid=?' , ( aid , ) ) if cur . fetchone ( ) is not None : return # Retrieve information for determining complet...
def _get_parent_remote_paths ( self ) : """Get list of remote folders based on the list of all file urls : return : set ( [ str ] ) : set of remote folders ( that contain files )"""
parent_paths = set ( [ item . get_remote_parent_path ( ) for item in self . file_urls ] ) if '' in parent_paths : parent_paths . remove ( '' ) return parent_paths
def usermacro_create ( macro , value , hostid , ** kwargs ) : '''Create new host usermacro . : param macro : name of the host usermacro : param value : value of the host usermacro : param hostid : hostid or templateid : param _ connection _ user : Optional - zabbix user ( can also be set in opts or pillar ,...
conn_args = _login ( ** kwargs ) ret = { } try : if conn_args : params = { } method = 'usermacro.create' if macro : # Python mistakenly interprets macro names starting and ending with ' { ' and ' } ' as a dict if isinstance ( macro , dict ) : macro = "{" + six . t...
def dropDuplicates ( self , subset = None ) : """Return a new : class : ` DataFrame ` with duplicate rows removed , optionally only considering certain columns . For a static batch : class : ` DataFrame ` , it just drops duplicate rows . For a streaming : class : ` DataFrame ` , it will keep all data across t...
if subset is None : jdf = self . _jdf . dropDuplicates ( ) else : jdf = self . _jdf . dropDuplicates ( self . _jseq ( subset ) ) return DataFrame ( jdf , self . sql_ctx )
def p_type_ref ( self , p ) : 'type _ ref : ID args nullable'
p [ 0 ] = AstTypeRef ( path = self . path , lineno = p . lineno ( 1 ) , lexpos = p . lexpos ( 1 ) , name = p [ 1 ] , args = p [ 2 ] , nullable = p [ 3 ] , ns = None , )
def _fill_function ( func , globals , defaults , dict , module , closure_values ) : """Fills in the rest of function data into the skeleton function object that were created via _ make _ skel _ func ( ) ."""
func . __globals__ . update ( globals ) func . __defaults__ = defaults func . __dict__ = dict func . __module__ = module cells = func . __closure__ if cells is not None : for cell , value in zip ( cells , closure_values ) : if value is not _empty_cell_value : cell_set ( cell , value ) return fun...
def _pc_decode ( self , msg ) : """PC : PLC ( lighting ) change ."""
housecode = msg [ 4 : 7 ] return { 'housecode' : housecode , 'index' : housecode_to_index ( housecode ) , 'light_level' : int ( msg [ 7 : 9 ] ) }
def _GetTimeElementsTuple ( self , timestamp ) : """Retrieves a time elements tuple from the timestamp . A Symantec log timestamp consist of six hexadecimal octets , that represent : First octet : Number of years since 1970 Second octet : Month , where January is represented by 0 Third octet : Day of the mo...
year , month , day_of_month , hours , minutes , seconds = ( int ( hexdigit [ 0 ] + hexdigit [ 1 ] , 16 ) for hexdigit in zip ( timestamp [ : : 2 ] , timestamp [ 1 : : 2 ] ) ) return ( year + 1970 , month + 1 , day_of_month , hours , minutes , seconds )
def update ( self , vts ) : """Mark a changed or invalidated VersionedTargetSet as successfully processed ."""
for vt in vts . versioned_targets : vt . ensure_legal ( ) if not vt . valid : self . _invalidator . update ( vt . cache_key ) vt . valid = True self . _artifact_write_callback ( vt ) if not vts . valid : vts . ensure_legal ( ) self . _invalidator . update ( vts . cache_key ) ...
def ok ( self , event = None ) : """This method is identical to tkinter . simpledialog . Dialog . ok ( ) , but with ' self . withdraw ( ) ' commented out ."""
if not self . validate ( ) : self . initial_focus . focus_set ( ) # put focus back return # NOTE ( amin ) : Using self . withdraw ( ) here causes the # ui to hang until the window loses and regains # focus . There must be some blocking operation going # on , but after some digging , I haven ' t been able to...
def to_bitarray ( data , width = 8 ) : '''Convert data ( list of integers , bytearray or integer ) to bitarray'''
if isinstance ( data , list ) or isinstance ( data , bytearray ) : data = combine_hex ( data ) return [ True if digit == '1' else False for digit in bin ( data ) [ 2 : ] . zfill ( width ) ]
def _times ( t0 , hours ) : """Return a ( list of ) datetime ( s ) given an initial time and an ( list of ) hourly offset ( s ) . Arguments : t0 - - initial time hours - - hourly offsets from t0"""
if not isinstance ( hours , Iterable ) : return Tide . _times ( t0 , [ hours ] ) [ 0 ] elif not isinstance ( hours [ 0 ] , datetime ) : return np . array ( [ t0 + timedelta ( hours = h ) for h in hours ] ) else : return np . array ( hours )