signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def blast ( args ) : """% prog blast < deltafile | coordsfile > Covert delta or coordsfile to BLAST tabular output ."""
p = OptionParser ( blast . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) deltafile , = args blastfile = deltafile . rsplit ( "." , 1 ) [ 0 ] + ".blast" if need_update ( deltafile , blastfile ) : coords = Coords ( deltafile ) fw = open ( blastfil...
def load_facts ( self , facts ) : """Load a set of facts into the CLIPS data base . The C equivalent of the CLIPS load - facts command . Facts can be loaded from a string or from a text file ."""
facts = facts . encode ( ) if os . path . exists ( facts ) : ret = lib . EnvLoadFacts ( self . _env , facts ) if ret == - 1 : raise CLIPSError ( self . _env ) else : ret = lib . EnvLoadFactsFromString ( self . _env , facts , - 1 ) if ret == - 1 : raise CLIPSError ( self . _env ) return r...
def substitution_set ( string , indexes ) : """for a string , return a set of all possible substitutions"""
strlen = len ( string ) return { mutate_string ( string , x ) for x in indexes if valid_substitution ( strlen , x ) }
def find_neighbor_pores ( self , pores , mode = 'union' , flatten = True , include_input = False ) : r"""Returns a list of pores that are direct neighbors to the given pore ( s ) Parameters pores : array _ like Indices of the pores whose neighbors are sought flatten : boolean If ` ` True ` ` ( default ) t...
pores = self . _parse_indices ( pores ) if sp . size ( pores ) == 0 : return sp . array ( [ ] , ndmin = 1 , dtype = int ) if 'lil' not in self . _am . keys ( ) : self . get_adjacency_matrix ( fmt = 'lil' ) neighbors = topotools . find_neighbor_sites ( sites = pores , logic = mode , am = self . _am [ 'lil' ] , f...
def load_plugins ( ) : """Loads all plugins specified in the RAFCON _ PLUGIN _ PATH environment variable"""
plugins = os . environ . get ( 'RAFCON_PLUGIN_PATH' , '' ) plugin_list = set ( plugins . split ( os . pathsep ) ) global plugin_dict for plugin_path in plugin_list : if not plugin_path : continue plugin_path = os . path . expandvars ( os . path . expanduser ( plugin_path ) ) . strip ( ) if not os . ...
def collect_samples_straggler_mitigation ( agents , train_batch_size ) : """Collects at least train _ batch _ size samples . This is the legacy behavior as of 0.6 , and launches extra sample tasks to potentially improve performance but can result in many wasted samples ."""
num_timesteps_so_far = 0 trajectories = [ ] agent_dict = { } for agent in agents : fut_sample = agent . sample . remote ( ) agent_dict [ fut_sample ] = agent while num_timesteps_so_far < train_batch_size : # TODO ( pcm ) : Make wait support arbitrary iterators and remove the # conversion to list here . [ fu...
def relative_filename_within_dir ( filename : str , directory : str ) -> str : """Starting with a ( typically absolute ) ` ` filename ` ` , returns the part of the filename that is relative to the directory ` ` directory ` ` . If the file is * not * within the directory , returns an empty string ."""
filename = os . path . abspath ( filename ) directory = os . path . abspath ( directory ) if os . path . commonpath ( [ directory , filename ] ) != directory : # Filename is not within directory return "" return os . path . relpath ( filename , start = directory )
def process_message ( self , message , * args , ** kwargs ) : """If its level is into persist levels , convert the message to models and save it"""
if not message . level in PERSISTENT_MESSAGE_LEVELS : return message user = kwargs . get ( "user" ) or self . get_user ( ) try : anonymous = user . is_anonymous ( ) except TypeError : anonymous = user . is_anonymous if anonymous : raise NotImplementedError ( 'Persistent message levels cannot be used for...
def _extractEgaNegFromSent ( sentTokens , clausesDict , foundChains ) : '''Meetod , mis tuvastab antud lausest ' ega ' - predikaadiga seotud eituse ( d ) : ega + sobiv verb . * ) Juhtudel kui ' ega ' - le j2rgneb juba tuvastatud , positiivse polaarsusega verbiahel ( nt ahel mille alguses on käskivas kõneviisi...
sonaEga = WordTemplate ( { ROOT : '^ega$' , POSTAG : '[DJ]' } ) verbEiJarel = WordTemplate ( { POSTAG : 'V' , FORM : '(o|nud|tud|nuks|nuvat|vat|ks|ta|taks|tavat)$' } ) verbEiJarel2 = WordTemplate ( { ROOT : '^mine$' , POSTAG : 'V' , FORM : 'neg o$' } ) verbTud = WordTemplate ( { POSTAG : 'V' , FORM : '(tud)$' } ) verb ...
def run ( self ) : """run the plugin"""
parser = df_parser ( self . workflow . builder . df_path , workflow = self . workflow ) dockerfile_labels = parser . labels labels = Labels ( dockerfile_labels ) component_label = labels . get_name ( Labels . LABEL_TYPE_COMPONENT ) try : component = dockerfile_labels [ component_label ] except KeyError : raise ...
def validate_po_files ( configuration , locale_dir , root_dir = None , report_empty = False , check_all = False ) : """Validate all of the po files found in the root directory that are not product of a merge . Returns a boolean indicating whether or not problems were found ."""
found_problems = False # List of . po files that are the product of a merge ( see generate . py ) . merged_files = configuration . generate_merge . keys ( ) for dirpath , __ , filenames in os . walk ( root_dir if root_dir else locale_dir ) : for name in filenames : __ , ext = os . path . splitext ( name ) ...
def find_near_matches_substitutions ( subsequence , sequence , max_substitutions ) : """Find near - matches of the subsequence in the sequence . This chooses a suitable fuzzy search implementation according to the given parameters . Returns a list of fuzzysearch . Match objects describing the matching parts ...
_check_arguments ( subsequence , sequence , max_substitutions ) if max_substitutions == 0 : return [ Match ( start_index , start_index + len ( subsequence ) , 0 ) for start_index in search_exact ( subsequence , sequence ) ] elif len ( subsequence ) // ( max_substitutions + 1 ) >= 3 : return find_near_matches_su...
def convert_to_cluster_template ( self , plugin_name , hadoop_version , template_name , filecontent ) : """Convert to cluster template Create Cluster Template directly , avoiding Cluster Template mechanism ."""
resp = self . api . post ( '/plugins/%s/%s/convert-config/%s' % ( plugin_name , hadoop_version , urlparse . quote ( template_name ) ) , data = filecontent ) if resp . status_code != 202 : raise RuntimeError ( 'Failed to upload template file for plugin "%s"' ' and version "%s"' % ( plugin_name , hadoop_version ) ) e...
def Tran ( m , x , rhol , rhog , mul , mug , sigma , D , roughness = 0 , L = 1 ) : r'''Calculates two - phase pressure drop with the Tran ( 2000 ) correlation , also shown in [ 2 ] _ and [ 3 ] _ . . . math : : \ Delta P = dP _ { lo } \ phi _ { lo } ^ 2 . . math : : \ phi _ { lo } ^ 2 = 1 + ( 4.3 \ Gamma ^...
# Liquid - only properties , for calculation of dP _ lo v_lo = m / rhol / ( pi / 4 * D ** 2 ) Re_lo = Reynolds ( V = v_lo , rho = rhol , mu = mul , D = D ) fd_lo = friction_factor ( Re = Re_lo , eD = roughness / D ) dP_lo = fd_lo * L / D * ( 0.5 * rhol * v_lo ** 2 ) # Gas - only properties , for calculation of dP _ go ...
def saveShp ( self , target ) : """Save an shp file ."""
if not hasattr ( target , "write" ) : target = os . path . splitext ( target ) [ 0 ] + '.shp' if not self . shapeType : self . shapeType = self . _shapes [ 0 ] . shapeType self . shp = self . __getFileObj ( target ) self . __shapefileHeader ( self . shp , headerType = 'shp' ) self . __shpRecords ( )
def _is_import_binding ( node , name , package = None ) : """Will reuturn node if node will import name , or node will import * from package . None is returned otherwise . See test cases for examples ."""
if node . type == syms . import_name and not package : imp = node . children [ 1 ] if imp . type == syms . dotted_as_names : for child in imp . children : if child . type == syms . dotted_as_name : if child . children [ 2 ] . value == name : return node ...
def iter ( self ) : """Iterate over the sequences in self . file _ , yielding each as an instance of the desired read class . @ raise ValueError : If the input file has an odd number of records or if any sequence has a different length than its predicted secondary structure ."""
upperCase = self . _upperCase for _file in self . _files : with asHandle ( _file ) as fp : records = SeqIO . parse ( fp , 'fasta' ) while True : try : record = next ( records ) except StopIteration : break try : stru...
def list_lbaas_l7policies ( self , retrieve_all = True , ** _params ) : """Fetches a list of all L7 policies for a listener ."""
return self . list ( 'l7policies' , self . lbaas_l7policies_path , retrieve_all , ** _params )
def add ( self , synchronous = True , ** kwargs ) : """Add provided Content View Component . : param synchronous : What should happen if the server returns an HTTP 202 ( accepted ) status code ? Wait for the task to complete if ` ` True ` ` . Immediately return the server ' s response otherwise . : param kw...
kwargs = kwargs . copy ( ) # shadow the passed - in kwargs if 'data' not in kwargs : # data is required kwargs [ 'data' ] = dict ( ) if 'component_ids' not in kwargs [ 'data' ] : kwargs [ 'data' ] [ 'components' ] = [ _payload ( self . get_fields ( ) , self . get_values ( ) ) ] kwargs . update ( self . _server_...
def decode ( data ) : """Decode data employing some charset detection and including unicode BOM stripping ."""
if isinstance ( data , unicode ) : return data # Detect standard unicode BOMs . for bom , encoding in UNICODE_BOMS : if data . startswith ( bom ) : return data [ len ( bom ) : ] . decode ( encoding , errors = 'ignore' ) # Try straight UTF - 8. try : return data . decode ( 'utf-8' ) except UnicodeDec...
def get_request ( profile , resource ) : """Do a GET request to Github ' s API . Args : profile A profile generated from ` ` simplygithub . authentication . profile ` ` . Such profiles tell this module ( i ) the ` ` repo ` ` to connect to , and ( ii ) the ` ` token ` ` to connect with . resource The p...
url = get_url ( profile , resource ) headers = get_headers ( profile ) response = requests . get ( url , headers = headers ) return response . json ( )
def get_container_containers ( self , path ) : """: param path : str or Path instance : return : : rtype : dict [ str , ValueTree ] : raises ValueError : A component of path is a field name . : raises KeyError : A component of path doesn ' t exist ."""
container = self . get_container ( path ) containers = { } for name , value in container . _values . items ( ) : if isinstance ( value , ValueTree ) : containers [ name ] = value return containers
async def set_agent ( self , msg , context ) : """Mark a client as the RPC agent for a service ."""
service = msg . get ( 'name' ) client = context . user_data self . service_manager . set_agent ( service , client )
def tree ( self , level = 0 , prefix = '' ) : """A string representation of the tree rooted in this node , useful for debugging purposes ."""
text = '%s%s\n' % ( prefix , self . value . text ) prefix = '%s└── ' % ( ' ' * level ) if self . _lesser : text += self . _lesser . tree ( level + 1 , prefix ) if self . _greater : text += self . _greater . tree ( level + 1 , prefix ) return text
def page_erase ( addr ) : """Erases a single page ."""
if __verbose : print ( "Erasing page: 0x%x..." % ( addr ) ) # Send DNLOAD with first byte = 0x41 and page address buf = struct . pack ( "<BI" , 0x41 , addr ) __dev . ctrl_transfer ( 0x21 , __DFU_DNLOAD , 0 , __DFU_INTERFACE , buf , __TIMEOUT ) # Execute last command if get_status ( ) != __DFU_STATE_DFU_DOWNLOAD_BUS...
def dict2obj ( d ) : """A helper function which convert a dict to an object ."""
if isinstance ( d , ( list , tuple ) ) : d = [ dict2obj ( x ) for x in d ] if not isinstance ( d , dict ) : return d class ObjectFromDict ( object ) : pass o = ObjectFromDict ( ) # an object created from a dict for k in d : o . __dict__ [ k ] = dict2obj ( d [ k ] ) return o
def _view_filter ( self ) : """Overrides OsidSession . _ view _ filter to add sequestering filter ."""
view_filter = OsidSession . _view_filter ( self ) if self . _sequestered_view == SEQUESTERED : view_filter [ 'sequestered' ] = False return view_filter
def _parse_dependencies ( self , pmodules , dependencies , recursive , greedy ) : """Parses the dependencies of the modules in the list pmodules . : arg pmodules : a list of modules that were parsed from a * . f90 file . : arg dependencies : when true , the dependency ' s dependencies will be loaded . : arg r...
# See if we need to also load dependencies for the modules if dependencies : allkeys = [ module . name . lower ( ) for module in pmodules ] for key in allkeys : for depend in self . modules [ key ] . collection ( "dependencies" ) : base = depend . split ( "." ) [ 0 ] if self . ve...
def rargmax ( x , eps = 1e-8 ) : """Argmax with random tie - breaking Args : x : a 1 - dim numpy array Returns : the argmax index"""
idxs = np . where ( abs ( x - np . max ( x , axis = 0 ) ) < eps ) [ 0 ] return np . random . choice ( idxs )
def process_value ( self , value ) : """Process publication value"""
# UID - > SuperModel if api . is_uid ( value ) : return self . to_super_model ( value ) # Content - > SuperModel elif api . is_object ( value ) : return self . to_super_model ( value ) # String - > Unicode elif isinstance ( value , basestring ) : return safe_unicode ( value ) . encode ( "utf-8" ) # DateTime...
def _parseKeyNames ( lib ) : """returns a dictionary mapping of human readable key names to their keycodes this parses constants with the names of K _ * and makes code = name pairs this is for KeyEvent . key variable and that enables things like : if ( event . key = = ' PAGEUP ' ) :"""
_keyNames = { } for attr in dir ( lib ) : # from the modules variables if attr [ : 6 ] == 'TCODK_' : # get the K _ * constants _keyNames [ getattr ( lib , attr ) ] = attr [ 6 : ] # and make CODE = NAME pairs return _keyNames
def get_precinctsreportingpct ( self , obj ) : """Precincts reporting percent if vote is top level result else ` ` None ` ` ."""
if obj . division . level == obj . candidate_election . election . division . level : return obj . candidate_election . election . meta . precincts_reporting_pct return None
def destroy ( self , request , project , pk = None ) : """Delete a note entry"""
try : note = JobNote . objects . get ( id = pk ) note . delete ( ) return Response ( { "message" : "Note deleted" } ) except JobNote . DoesNotExist : return Response ( "No note with id: {0}" . format ( pk ) , status = HTTP_404_NOT_FOUND )
def is_name_zonefile_hash ( self , name , zonefile_hash ) : """Was a zone file sent by a name ?"""
cur = self . db . cursor ( ) return namedb_is_name_zonefile_hash ( cur , name , zonefile_hash )
def get_temperature ( self ) : """Returns the current environment temperature . Attention : Returns None if the value can ' t be queried or is unknown ."""
# raise NotImplementedError ( " This should work according to the AVM docs , but don ' t . . . " ) value = self . box . homeautoswitch ( "gettemperature" , self . actor_id ) if value . isdigit ( ) : self . temperature = float ( value ) / 10 else : self . temperature = None return self . temperature
def parse ( self , xml_file ) : "Get a list of parsed recipes from BeerXML input"
recipes = [ ] with open ( xml_file , "rt" ) as f : tree = ElementTree . parse ( f ) for recipeNode in tree . iter ( ) : if self . to_lower ( recipeNode . tag ) != "recipe" : continue recipe = Recipe ( ) recipes . append ( recipe ) for recipeProperty in list ( recipeNode ) : tag_name ...
def set_text ( self , text = None , ** kwargs ) : """Add textual information passed as dictionary . All pairs in dictionary will be written , but keys should be latin - 1; registered keywords could be used as arguments . When called more than once overwrite exist data ."""
if text is None : text = { } text . update ( popdict ( kwargs , _registered_kw ) ) if 'Creation Time' in text and not isinstance ( text [ 'Creation Time' ] , ( basestring , bytes ) ) : text [ 'Creation Time' ] = datetime . datetime ( * ( check_time ( text [ 'Creation Time' ] ) [ : 6 ] ) ) . isoformat ( ) self ....
def execute_command ( self , * args , ** options ) : """Execute a command and return a parsed response ."""
pool = self . connection_pool command_name = args [ 0 ] connection = pool . get_connection ( command_name , ** options ) try : connection . send_command ( * args ) return self . parse_response ( connection , command_name , ** options ) except ConnectionError : connection . disconnect ( ) connection . se...
def safecall ( func ) : """Wraps a function so that it swallows exceptions ."""
def wrapper ( * args , ** kwargs ) : try : return func ( * args , ** kwargs ) except Exception : pass return wrapper
def attach_profile_to_role ( client , role_name = 'forrest_unicorn_role' , profile_name = 'forrest_unicorn_profile' ) : """Attach an IAM Instance Profile _ profile _ name _ to Role _ role _ name _ . Args : role _ name ( str ) : Name of Role . profile _ name ( str ) : Name of Instance Profile . Returns : T...
current_instance_profiles = resource_action ( client , action = 'list_instance_profiles_for_role' , log_format = 'Found Instance Profiles for %(RoleName)s.' , RoleName = role_name ) [ 'InstanceProfiles' ] for profile in current_instance_profiles : if profile [ 'InstanceProfileName' ] == profile_name : LOG ....
def filenames ( self ) : """A list of all handled auxiliary file names . > > > from hydpy import dummies > > > dummies . v2af . filenames [ ' file1 ' , ' file2 ' ]"""
fns = set ( ) for fn2var in self . _type2filename2variable . values ( ) : fns . update ( fn2var . keys ( ) ) return sorted ( fns )
def on_api_error ( self , error_status = None , message = None , event_origin = None ) : """API error handling"""
if message . meta [ "error" ] . find ( "Widget instance not found on server" ) > - 1 : # widget is missing on the other side , try to re - attach # then try again error_status [ "retry" ] = True self . comm . attach_remote ( self . id , self . remote_name , remote_name = self . name , ** self . init_kwargs )
def compute_process_sigmas ( self , dt , fx = None , ** fx_args ) : """computes the values of sigmas _ f . Normally a user would not call this , but it is useful if you need to call update more than once between calls to predict ( to update for multiple simultaneous measurements ) , so the sigmas correctly re...
if fx is None : fx = self . fx # calculate sigma points for given mean and covariance sigmas = self . points_fn . sigma_points ( self . x , self . P ) for i , s in enumerate ( sigmas ) : self . sigmas_f [ i ] = fx ( s , dt , ** fx_args )
def get_name_levels ( node ) : """Return a list of ` ` ( name , level ) ` ` tuples for assigned names The ` level ` is ` None ` for simple assignments and is a list of numbers for tuple assignments for example in : : a , ( b , c ) = x The levels for for ` a ` is ` ` [ 0 ] ` ` , for ` b ` is ` ` [ 1 , 0 ] ` ...
visitor = _NodeNameCollector ( ) ast . walk ( node , visitor ) return visitor . names
def get_server_session ( self ) : """Start or resume a server session , or raise ConfigurationError ."""
with self . _lock : session_timeout = self . _description . logical_session_timeout_minutes if session_timeout is None : # Maybe we need an initial scan ? Can raise ServerSelectionError . if self . _description . topology_type == TOPOLOGY_TYPE . Single : if not self . _description . has_know...
def load_script ( self , source_name , timeoutMilliseconds = 0 ) : """Return ScriptHook for source _ name Source and with a ready timeout of timeoutMilliseconds"""
script_path = os . path . join ( self . scripts_dir_path , self . _source_to_script_name ( source_name ) ) if os . path . isfile ( script_path ) : return ScriptHook ( script_path , timeoutMilliseconds ) return None
def send ( token_hex , message , ** kwargs ) : """Site : https : / / apple . com API : https : / / developer . apple . com Desc : iOS notifications Installation and usage : pip install hyper"""
priority = kwargs . pop ( 'priority' , 10 ) topic = kwargs . pop ( 'topic' , None ) alert = { "title" : kwargs . pop ( "event" ) , "body" : message , "action" : kwargs . pop ( 'apns_action' , defaults . APNS_PROVIDER_DEFAULT_ACTION ) } data = { "aps" : { 'alert' : alert , 'content-available' : kwargs . pop ( 'content_a...
def department ( self ) : """| Description : The ID of the department to which the chat is directed"""
if self . api and self . department_id : return self . api . _get_department ( self . department_id )
def _set_ext_vni_any ( self , v , load = False ) : """Setter method for ext _ vni _ any , mapped from YANG variable / overlay / access _ list / type / vxlan / extended / ext _ seq / ext _ vni _ any ( empty ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ext _ vni _ an...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGBool , is_leaf = True , yang_name = "ext-vni-any" , rest_name = "vni-any" , parent = self , choice = ( u'choice-ext-vni' , u'case-ext-vni-any' ) , path_helper = self . _path_helper , extmethods = self . _extmethods , regi...
def t_WSIGNORE_comment ( self , token ) : r'[ # ] [ ^ \ n ] * \ n +'
token . lexer . lineno += token . value . count ( '\n' ) newline_token = _create_token ( 'NEWLINE' , '\n' , token . lineno , token . lexpos + len ( token . value ) - 1 ) newline_token . lexer = token . lexer self . _check_for_indent ( newline_token )
def gpg_profile_put_key ( blockchain_id , key_id , key_name = None , immutable = True , txid = None , key_url = None , use_key_server = True , key_server = None , proxy = None , wallet_keys = None , gpghome = None ) : """Put a local GPG key into a blockchain ID ' s global account . If the URL is not given , the k...
if key_name is not None : assert is_valid_keyname ( key_name ) if key_server is None : key_server = DEFAULT_KEY_SERVER if gpghome is None : gpghome = get_default_gpg_home ( ) put_res = { } extra_fields = { } key_data = None if key_name is not None : extra_fields = { 'keyName' : key_name } if key_url is ...
def aln_tree_seqs ( seqs , input_handler = None , tree_type = 'neighborjoining' , params = { } , add_seq_names = True , WorkingDir = tempfile . gettempdir ( ) , SuppressStderr = None , SuppressStdout = None , max_hours = 5.0 , constructor = PhyloNode , clean_up = True ) : """Muscle align sequences and report tree f...
params [ "-maxhours" ] = max_hours if tree_type : params [ "-cluster2" ] = tree_type params [ "-tree2" ] = get_tmp_filename ( WorkingDir ) params [ "-out" ] = get_tmp_filename ( WorkingDir ) muscle_res = muscle_seqs ( seqs , input_handler = input_handler , params = params , add_seq_names = add_seq_names , WorkingDi...
def v_res ( self , nodes = None , level = None ) : """Get resulting voltage level at node . Parameters nodes : : obj : ` list ` List of string representatives of grid topology components , e . g . : class : ` ~ . grid . components . Generator ` . If not provided defaults to all nodes available in grid lev...
# check if voltages are available : if hasattr ( self , 'pfa_v_mag_pu' ) : self . pfa_v_mag_pu . sort_index ( axis = 1 , inplace = True ) else : message = "No voltage results available." raise AttributeError ( message ) if level is None : level = [ 'mv' , 'lv' ] if nodes is None : return self . pfa_...
def _minimize_scalar ( self , desc = "Progress" , rtol = 1.4902e-08 , atol = 1.4902e-08 , verbose = True ) : """Minimize a scalar function using Brent ' s method . Parameters verbose : bool ` ` True ` ` for verbose output ; ` ` False ` ` otherwise ."""
from tqdm import tqdm from numpy import asarray from brent_search import minimize as brent_minimize variables = self . _variables . select ( fixed = False ) if len ( variables ) != 1 : raise ValueError ( "The number of variables must be equal to one." ) var = variables [ variables . names ( ) [ 0 ] ] progress = tqd...
def serve ( host , port , app , request_handler , error_handler , before_start = None , after_start = None , before_stop = None , after_stop = None , debug = False , request_timeout = 60 , response_timeout = 60 , keep_alive_timeout = 5 , ssl = None , sock = None , request_max_size = None , request_buffer_queue_size = 1...
if not run_async : # create new event _ loop after fork loop = asyncio . new_event_loop ( ) asyncio . set_event_loop ( loop ) if debug : loop . set_debug ( debug ) connections = connections if connections is not None else set ( ) server = partial ( protocol , loop = loop , connections = connections , signal...
def get_plane_equation ( p0 , p1 , p2 , reference ) : '''Define the equation of target fault plane passing through 3 given points which includes two points on the fault trace and one point on the fault plane but away from the fault trace . Note : in order to remain the consistency of the fault normal vector d...
p0_xyz = get_xyz_from_ll ( p0 , reference ) p1_xyz = get_xyz_from_ll ( p1 , reference ) p2_xyz = get_xyz_from_ll ( p2 , reference ) p0 = np . array ( p0_xyz ) p1 = np . array ( p1_xyz ) p2 = np . array ( p2_xyz ) u = p1 - p0 v = p2 - p0 # vector normal to plane , ax + by + cy = d , normal = ( a , b , c ) normal = np . ...
def from_spectrogram ( cls , * spectrograms , ** kwargs ) : """Calculate a new ` SpectralVariance ` from a : class : ` ~ gwpy . spectrogram . Spectrogram ` Parameters spectrogram : ` ~ gwpy . spectrogram . Spectrogram ` input ` Spectrogram ` data bins : ` ~ numpy . ndarray ` , optional array of histogra...
# parse args and kwargs if not spectrograms : raise ValueError ( "Must give at least one Spectrogram" ) bins = kwargs . pop ( 'bins' , None ) low = kwargs . pop ( 'low' , None ) high = kwargs . pop ( 'high' , None ) nbins = kwargs . pop ( 'nbins' , 500 ) log = kwargs . pop ( 'log' , False ) norm = kwargs . pop ( 'n...
def avg_send_rate ( self ) : """Average sending rate in MB / s over the entire run . This data may not exist if iperf was interrupted . If the result is not from a success run , this property is None ."""
if not self . _has_data or 'sum_sent' not in self . result [ 'end' ] : return None bps = self . result [ 'end' ] [ 'sum_sent' ] [ 'bits_per_second' ] return bps / 8 / 1024 / 1024
def flash_size_bytes ( size ) : """Given a flash size of the type passed in args . flash _ size ( ie 512KB or 1MB ) then return the size in bytes ."""
if "MB" in size : return int ( size [ : size . index ( "MB" ) ] ) * 1024 * 1024 elif "KB" in size : return int ( size [ : size . index ( "KB" ) ] ) * 1024 else : raise FatalError ( "Unknown size %s" % size )
def _string_from_cmd_list ( cmd_list ) : """Takes a list of command line arguments and returns a pretty representation for printing ."""
cl = [ ] for arg in map ( str , cmd_list ) : if ' ' in arg or '\t' in arg : arg = '"' + arg + '"' cl . append ( arg ) return ' ' . join ( cl )
def _set_local_node ( self , v , load = False ) : """Setter method for local _ node , mapped from YANG variable / local _ node ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ local _ node is considered as a private method . Backends looking to populate t...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = local_node . local_node , is_container = 'container' , presence = False , yang_name = "local-node" , rest_name = "local-node" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_pa...
def set_inlets ( self , pores = None , clusters = None ) : r"""Parameters pores : array _ like The list of inlet pores from which the Phase can enter the Network clusters : list of lists - can be just one list but each list defines a cluster of pores that share a common invasion pressure . Like Basic Inva...
if pores is not None : logger . info ( "Setting inlet pores at shared pressure" ) clusters = [ ] clusters . append ( pores ) elif clusters is not None : logger . info ( "Setting inlet clusters at individual pressures" ) else : logger . error ( "Either 'inlets' or 'clusters' must be passed to" + " se...
def parse ( self ) : """Parse the table data string into records ."""
self . parse_fields ( ) records = [ ] for line in self . t [ 'data' ] . split ( '\n' ) : if EMPTY_ROW . match ( line ) : continue row = [ self . autoconvert ( line [ start_field : end_field + 1 ] ) for start_field , end_field in self . fields ] records . append ( tuple ( row ) ) self . records = rec...
def setWorkingSeatedZeroPoseToRawTrackingPose ( self ) : """Sets the preferred seated position in the working copy ."""
fn = self . function_table . setWorkingSeatedZeroPoseToRawTrackingPose pMatSeatedZeroPoseToRawTrackingPose = HmdMatrix34_t ( ) fn ( byref ( pMatSeatedZeroPoseToRawTrackingPose ) ) return pMatSeatedZeroPoseToRawTrackingPose
def getPrioritySortkey ( self ) : """Returns the key that will be used to sort the current Analysis Request based on both its priority and creation date . On ASC sorting , the oldest item with highest priority will be displayed . : return : string used for sorting"""
priority = self . getPriority ( ) created_date = self . created ( ) . ISO8601 ( ) return '%s.%s' % ( priority , created_date )
def segment_text ( text = os . path . join ( DATA_PATH , 'goodreads-omniscient-books.txt' ) , start = None , stop = r'^Rate\ this' , ignore = r'^[\d]' ) : """Split text into segments ( sections , paragraphs ) using regular expressions to trigger breaks . start"""
start = start if hasattr ( start , 'match' ) else re . compile ( start ) if start else None stop = stop if hasattr ( stop , 'match' ) else re . compile ( stop ) if stop else None ignore = ignore if hasattr ( ignore , 'match' ) else re . compile ( ignore ) if ignore else None segments = [ ] segment = [ ] with open ( tex...
def _check_valid_label ( self , label ) : """Validate label and its shape ."""
if len ( label . shape ) != 2 or label . shape [ 1 ] < 5 : msg = "Label with shape (1+, 5+) required, %s received." % str ( label ) raise RuntimeError ( msg ) valid_label = np . where ( np . logical_and ( label [ : , 0 ] >= 0 , label [ : , 3 ] > label [ : , 1 ] , label [ : , 4 ] > label [ : , 2 ] ) ) [ 0 ] if v...
def do_loop_turn ( self ) : # pylint : disable = too - many - branches """Satellite main loop : : * Check and delete zombies actions / modules * Get returns from queues * Adjust worker number * Get new actions : return : None"""
# Try to see if one of my module is dead , and restart previously dead modules self . check_and_del_zombie_modules ( ) # Also if some zombie workers exist . . . self . check_and_del_zombie_workers ( ) # Call modules that manage a starting tick pass self . hook_point ( 'tick' ) # Print stats for debug for _ , sched in s...
def save ( self , filename ) : """Save model to pickle file . External feature function is not stored"""
import dill tmpmodelparams = self . modelparams . copy ( ) # fv _ extern _ src = None fv_extern_name = None # try : # fv _ extern _ src = dill . source . getsource ( tmpmodelparams [ ' fv _ extern ' ] ) # tmpmodelparams . pop ( ' fv _ extern ' ) # except : # pass # fv _ extern _ name = dill . source . getname ( tmpmode...
def _commit ( self ) : """Commits the batch . This is called by : meth : ` commit ` ."""
if self . _id is None : mode = _datastore_pb2 . CommitRequest . NON_TRANSACTIONAL else : mode = _datastore_pb2 . CommitRequest . TRANSACTIONAL commit_response_pb = self . _client . _datastore_api . commit ( self . project , mode , self . _mutations , transaction = self . _id ) _ , updated_keys = _parse_commit_r...
def refresh ( self ) : """* * refresh * * Refresh this user object with data from the Gett service Input : * None Output : * ` ` True ` ` Example : : if client . user . refresh ( ) : print " User data refreshed ! " print " You have % s bytes of storage remaining . " % ( client . user . storage _ l...
response = GettRequest ( ) . get ( "/users/me?accesstoken=%s" % self . access_token ( ) ) if response . http_status == 200 : self . userid = response . response [ 'userid' ] self . fullname = response . response [ 'fullname' ] self . storage_used = response . response [ 'storage' ] [ 'used' ] self . sto...
def mod_repo ( repo , saltenv = 'base' , ** kwargs ) : '''Modify one or more values for a repo . If the repo does not exist , it will be created , so long as the definition is well formed . For Ubuntu the ` ` ppa : < project > / repo ` ` format is acceptable . ` ` ppa : ` ` format can only be used to create a...
if 'refresh_db' in kwargs : salt . utils . versions . warn_until ( 'Neon' , 'The \'refresh_db\' argument to \'pkg.mod_repo\' has been ' 'renamed to \'refresh\'. Support for using \'refresh_db\' will be ' 'removed in the Neon release of Salt.' ) refresh = kwargs [ 'refresh_db' ] else : refresh = kwargs . get...
def x ( * args , ** kwargs ) : '''same as sys . exit ( 1 ) but prints out where it was called from before exiting I just find this really handy for debugging sometimes since - - 2013-5-9 exit _ code - - int - - if you want it something other than 1'''
with Reflect . context ( args , ** kwargs ) as r : instance = V_CLASS ( r , stream , ** kwargs ) if args : instance ( ) else : instance . writelines ( [ 'exit at line {}\n' . format ( instance . reflect . info [ "line" ] ) , instance . path_value ( ) ] ) exit_code = 1 sys . exit ( exit_code ...
def get_dem ( bounds , out_file = "dem.tif" , src_crs = "EPSG:3005" , dst_crs = "EPSG:3005" , resolution = 25 ) : """Get 25m DEM for provided bounds , write to GeoTIFF"""
bbox = "," . join ( [ str ( b ) for b in bounds ] ) # todo : validate resolution units are equivalent to src _ crs units # build request payload = { "service" : "WCS" , "version" : "1.0.0" , "request" : "GetCoverage" , "coverage" : "pub:bc_elevation_25m_bcalb" , "Format" : "GeoTIFF" , "bbox" : bbox , "CRS" : src_crs , ...
def convenience_calc_hessian ( self , params ) : """Calculates the hessian of the log - likelihood for this model / dataset . Note that this function name is INCORRECT with regard to the actual actions performed . The Mixed Logit model uses the BHHH approximation to the Fisher Information Matrix in place of t...
shapes , intercepts , betas = self . convenience_split_params ( params ) args = [ betas , self . design_3d , self . alt_id_vector , self . rows_to_obs , self . rows_to_alts , self . rows_to_mixers , self . choice_vector , self . utility_transform ] approx_hess = general_bhhh ( * args , ridge = self . ridge , weights = ...
def _print_p ( self ) : """m . _ print _ p ( ) - - Print probability ( frequency ) matrix"""
print "# " , for i in range ( self . width ) : print " %4d " % i , print for L in [ 'A' , 'C' , 'T' , 'G' ] : print "#%s " % L , for i in range ( self . width ) : print "%8.3f " % math . pow ( 2 , self . logP [ i ] [ L ] ) , print
def arg_to_dict ( arg ) : """Convert an argument that can be None , list / tuple or dict to dict Example : : > > > arg _ to _ dict ( None ) > > > arg _ to _ dict ( [ ' a ' , ' b ' ] ) { ' a ' : { } , ' b ' : { } } > > > arg _ to _ dict ( { ' a ' : { ' only ' : ' id ' } , ' b ' : { ' only ' : ' id ' } } ) ...
if arg is None : arg = [ ] try : arg = dict ( arg ) except ValueError : arg = dict . fromkeys ( list ( arg ) , { } ) return arg
def to_practice_counts ( request ) : """Get number of items available to practice . filters : - - use this or body json as in BODY language : language of the items BODY json in following format : " # identifier " : [ ] - - custom identifier ( str ) and filter"""
data = None if request . method == "POST" : data = json . loads ( request . body . decode ( "utf-8" ) ) [ "filters" ] if "filters" in request . GET : data = load_query_json ( request . GET , "filters" ) if data is None or len ( data ) == 0 : return render_json ( request , { } , template = 'models_json.html'...
def _load_data ( self , reset = False ) : '''loads the RDF / turtle application data to the triplestore args : reset ( bool ) : True will delete the definition dataset and reload all of the datafiles .'''
log = logging . getLogger ( "%s.%s" % ( self . log_name , inspect . stack ( ) [ 0 ] [ 3 ] ) ) log . setLevel ( self . log_level ) for attr , obj in self . datafile_obj . items ( ) : if reset or obj [ 'latest_mod' ] > obj [ 'last_json_mod' ] : conn = obj [ 'conn' ] sparql = "DROP ALL;" if os ...
def listen ( self ) : """Listen for incoming control messages . If the ' redis . shard _ hint ' configuration is set , its value will be passed to the pubsub ( ) method when setting up the subscription . The control channel to subscribe to is specified by the ' redis . control _ channel ' configuration ( ...
# Use a specific database handle , with override . This allows # the long - lived listen thread to be configured to use a # different database or different database options . db = self . config . get_database ( 'control' ) # Need a pub - sub object kwargs = { } if 'shard_hint' in self . config [ 'control' ] : kwarg...
def aggregated_relevant_items ( raw_df ) : """Aggragation for calculate mean and std ."""
df = ( raw_df [ [ 'idSegmento' , 'idPlanilhaItens' , 'VlUnitarioAprovado' ] ] . groupby ( by = [ 'idSegmento' , 'idPlanilhaItens' ] ) . agg ( [ np . mean , lambda x : np . std ( x , ddof = 0 ) ] ) ) df . columns = df . columns . droplevel ( 0 ) return ( df . rename ( columns = { '<lambda>' : 'std' } ) )
def login_required ( fn ) : """Decorator that restrict access only for authorized users . User is considered authorized if authorized _ userid returns some value ."""
@ wraps ( fn ) async def wrapped ( * args , ** kwargs ) : request = args [ - 1 ] if not isinstance ( request , web . BaseRequest ) : msg = ( "Incorrect decorator usage. " "Expecting `def handler(request)` " "or `def handler(self, request)`." ) raise RuntimeError ( msg ) await check_authorize...
def find ( name ) : """Locate a filename into the shader library ."""
if op . exists ( name ) : return name path = op . dirname ( __file__ ) or '.' paths = [ path ] + config [ 'include_path' ] for path in paths : filename = op . abspath ( op . join ( path , name ) ) if op . exists ( filename ) : return filename for d in os . listdir ( path ) : fullpath = o...
def remove_lvm_physical_volume ( block_device ) : '''Remove LVM PV signatures from a given block device . : param block _ device : str : Full path of block device to scrub .'''
p = Popen ( [ 'pvremove' , '-ff' , block_device ] , stdin = PIPE ) p . communicate ( input = 'y\n' )
def ParseURIFromKeyValues ( self , data , separator , uri_key ) : """Parse key / value formatted source listing and return potential URLs . The fundamental shape of this format is as follows : key : value # here : = separator key : value URI : [ URL ] # here URI = uri _ key [ URL ] # this is where it beco...
precondition . AssertType ( data , Text ) precondition . AssertType ( separator , Text ) kv_entries = KeyValueParser ( kv_sep = separator ) . ParseEntries ( data ) spaced_entries = FieldParser ( ) . ParseEntries ( data ) uris = [ ] check_uri_on_next_line = False for kv_entry , sp_entry in zip ( kv_entries , spaced_entr...
def head ( self , bytes ) : """Returns the number of given bytes from the head of the buffer . The buffer remains unchanged . : type bytes : int : param bytes : The number of bytes to return ."""
oldpos = self . io . tell ( ) self . io . seek ( 0 ) head = self . io . read ( bytes ) self . io . seek ( oldpos ) return head
def get_usedby_aql ( self , params ) : """Возвращает запрос AQL ( без репозитория ) , из файла конфигурации : param params : : return :"""
if self . _usedby is None : return None _result = { } params = self . merge_valued ( params ) for k , v in self . _usedby [ 'AQL' ] . items ( ) : if isinstance ( v , str ) : k = k . format ( ** params ) v = v . format ( ** params ) _result [ k ] = v return _result
def random ( length , chars = None ) : """Generates a random string . : param length : Length of the string to generate . This can be a numbe or a pair : ` ` ( min _ length , max _ length ) ` ` : param chars : String of characters to choose from"""
if chars is None : chars = string . ascii_letters + string . digits else : ensure_string ( chars ) if not chars : raise ValueError ( "character set must not be empty" ) if is_pair ( length ) : length = randint ( * length ) elif isinstance ( length , Integral ) : if not length > 0 : r...
def mel ( sr , n_dft , n_mels = 128 , fmin = 0.0 , fmax = None , htk = False , norm = 1 ) : """[ np ] create a filterbank matrix to combine stft bins into mel - frequency bins use Slaney ( said Librosa ) n _ mels : numbre of mel bands fmin : lowest frequency [ Hz ] fmax : highest frequency [ Hz ] If ` Non...
return librosa . filters . mel ( sr = sr , n_fft = n_dft , n_mels = n_mels , fmin = fmin , fmax = fmax , htk = htk , norm = norm ) . astype ( K . floatx ( ) )
def upload_and_confirm ( self , incoming , ** kwargs ) : """Upload the file to okcupid and confirm , among other things , its thumbnail position . : param incoming : A filepath string , : class : ` . Info ` object or a file like object to upload to okcupid . com . If an info object is provided , its thumbna...
response_dict = self . upload ( incoming ) if 'error' in response_dict : log . warning ( 'Failed to upload photo' ) return response_dict if isinstance ( incoming , Info ) : kwargs . setdefault ( 'thumb_nail_left' , incoming . thumb_nail_left ) kwargs . setdefault ( 'thumb_nail_top' , incoming . thumb_na...
def service ( self , block , service_name ) : """Return a service , or None . Services are objects implementing arbitrary other interfaces . They are requested by agreed - upon names , see [ XXX TODO ] for a list of possible services . The object returned depends on the service requested . XBlocks must anno...
declaration = block . service_declaration ( service_name ) if declaration is None : raise NoSuchServiceError ( "Service {!r} was not requested." . format ( service_name ) ) service = self . _services . get ( service_name ) if service is None and declaration == "need" : raise NoSuchServiceError ( "Service {!r} i...
def lock ( instance_id , profile = None , ** kwargs ) : '''Lock an instance instance _ id ID of the instance to be locked CLI Example : . . code - block : : bash salt ' * ' nova . lock 1138'''
conn = _auth ( profile , ** kwargs ) return conn . lock ( instance_id )
def get ( self , host , files_count , path = "/" , ssl = False , external = None ) : """Send get request to a url and wrap the results : param host ( str ) : the host name of the url : param path ( str ) : the path of the url ( start with " / " ) : return ( dict ) : the result of the test url"""
theme = "https" if ssl else "http" url = host + path http_url = theme + "://" + url result = { } try : capture_path = os . getcwd ( ) + '/' har_file_path = capture_path + "har/" # fc . load _ page ( self . driver , http _ url ) fc . switch_tab ( self . driver ) self . load_page ( http_url ) prin...
def get ( self , key , default_val = None , require_value = False ) : """Returns a dictionary value"""
val = dict . get ( self , key , default_val ) if val is None and require_value : raise KeyError ( 'key "%s" not found' % key ) if isinstance ( val , dict ) : return AttributeDict ( val ) return val
def create_vmfs_datastore ( datastore_name , disk_id , vmfs_major_version , safety_checks = True , service_instance = None ) : '''Creates a ESXi host disk group with the specified cache and capacity disks . datastore _ name The name of the datastore to be created . disk _ id The disk id ( canonical name ) o...
log . debug ( 'Validating vmfs datastore input' ) schema = VmfsDatastoreSchema . serialize ( ) try : jsonschema . validate ( { 'datastore' : { 'name' : datastore_name , 'backing_disk_id' : disk_id , 'vmfs_version' : vmfs_major_version } } , schema ) except jsonschema . exceptions . ValidationError as exc : rais...
def remove_raw ( self , length_tag , value_tag ) : """Remove the tags for a data type field . : param length _ tag : tag number of the length field . : param value _ tag : tag number of the value field . You can remove either private or standard data field definitions in case a particular application uses t...
self . raw_len_tags . remove ( length_tag ) self . raw_data_tags . remove ( value_tag ) return
def sign ( message , ** config ) : """Insert two new fields into the message dict and return it . Those fields are : - ' signature ' - the computed message digest of the JSON repr . - ' certificate ' - the base64 certificate or gpg key of the signator ."""
if not _implementation : init ( ** config ) return _implementation . sign ( message , ** config )
def _getSyntaxByLanguageName ( self , syntaxName ) : """Get syntax by its name . Name is defined in the xml file"""
xmlFileName = self . _syntaxNameToXmlFileName [ syntaxName ] return self . _getSyntaxByXmlFileName ( xmlFileName )
def _val_pt_xml ( self ) : """The unicode XML snippet containing the ` ` < c : pt > ` ` elements containing the values for this series ."""
xml = '' for idx , value in enumerate ( self . _series . values ) : if value is None : continue xml += ( ' <c:pt idx="{val_idx:d}">\n' ' <c:v>{value}</c:v>\n' ' </c:pt>\n' ) . format ( ** { 'val_idx' : idx , 'value' : value , } ) return xml
def as_dictionary ( self ) : """Return the condition as a dictionary . : return : dict"""
condition_dict = { "name" : self . name , "timelock" : self . timelock , "timeout" : self . timeout , "contractName" : self . contract_name , "functionName" : self . function_name , "events" : [ e . as_dictionary ( ) for e in self . events ] , "parameters" : [ p . as_dictionary ( ) for p in self . parameters ] , } retu...