signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def simulated_brick ( face_count , extents , noise , max_iter = 10 ) : """Produce a mesh that is a rectangular solid with noise with a random transform . Parameters face _ count : int Approximate number of faces desired extents : ( n , 3 ) float Dimensions of brick noise : float Magnitude of vertex ...
# create the mesh as a simple box mesh = trimesh . creation . box ( extents = extents ) # add some systematic error pre - tesselation mesh . vertices [ 0 ] += mesh . vertex_normals [ 0 ] + ( noise * 2 ) # subdivide until we have more faces than we want for i in range ( max_iter ) : if len ( mesh . vertices ) > face...
def get_dict ( self , domain = None , path = None ) : """Takes as an argument an optional domain and path and returns a plain old Python dict of name - value pairs of cookies that meet the requirements ."""
dictionary = { } for cookie in iter ( self ) : if ( domain is None or cookie . domain == domain ) and ( path is None or cookie . path == path ) : dictionary [ cookie . name ] = cookie . value return dictionary
def a ( value ) : """Eq ( a ) - > Parser ( a , a ) Returns a parser that parses a token that is equal to the value value ."""
name = getattr ( value , 'name' , value ) return some ( lambda t : t == value ) . named ( u'(a "%s")' % ( name , ) )
def create ( self , ospf_process_id , vrf = None ) : """Creates a OSPF process in the specified VRF or the default VRF . Args : ospf _ process _ id ( str ) : The OSPF process Id value vrf ( str ) : The VRF to apply this OSPF process to Returns : bool : True if the command completed successfully Exceptio...
value = int ( ospf_process_id ) if not 0 < value < 65536 : raise ValueError ( 'ospf as must be between 1 and 65535' ) command = 'router ospf {}' . format ( ospf_process_id ) if vrf : command += ' vrf %s' % vrf return self . configure ( command )
def create ( self , data , ** kwargs ) : """Create a new object . Args : data ( dict ) : parameters to send to the server to create the resource * * kwargs : Extra options to send to the server ( e . g . sudo ) Returns : RESTObject : a new instance of the managed object class built with the data sent ...
self . _check_missing_create_attrs ( data ) new_data = data . copy ( ) file_path = new_data . pop ( 'file_path' ) . replace ( '/' , '%2F' ) path = '%s/%s' % ( self . path , file_path ) server_data = self . gitlab . http_post ( path , post_data = new_data , ** kwargs ) return self . _obj_cls ( self , server_data )
def set_mathjax_style ( style_css , mathfontsize ) : """Write mathjax settings , set math fontsize"""
jax_style = """<script> MathJax.Hub.Config({ "HTML-CSS": { /*preferredFont: "TeX",*/ /*availableFonts: ["TeX", "STIX"],*/ styles: { scale: %d, ".MathJax_Display": { "font-size": %s, } } ...
def recipients ( cls , bigchain ) : """Convert validator dictionary to a recipient list for ` Transaction `"""
recipients = [ ] for public_key , voting_power in cls . get_validators ( bigchain ) . items ( ) : recipients . append ( ( [ public_key ] , voting_power ) ) return recipients
def ReqConnect ( self , front : str ) : """连接交易前置 : param front :"""
self . t . CreateApi ( ) spi = self . t . CreateSpi ( ) self . t . RegisterSpi ( spi ) self . t . OnFrontConnected = self . _OnFrontConnected self . t . OnRspUserLogin = self . _OnRspUserLogin self . t . OnFrontDisconnected = self . _OnFrontDisconnected # self . t . OnRspUserLogout = self . _ OnRspUserLogout self . t ....
def subsample ( self , sample_factor = 2 ) : """Subsample series by an integer factor . Parameters sample _ factor : positive integer , optional , default = 2 Factor for downsampling ."""
if sample_factor < 0 : raise Exception ( 'Factor for subsampling must be postive, got %g' % sample_factor ) s = slice ( 0 , len ( self . index ) , sample_factor ) newindex = self . index [ s ] return self . map ( lambda v : v [ s ] , index = newindex )
def create_table ( group , name , dtype , ** attributes ) : """Create a new array dataset under group with compound datatype and maxshape = ( None , )"""
dset = group . create_dataset ( name , shape = ( 0 , ) , dtype = dtype , maxshape = ( None , ) ) set_attributes ( dset , ** attributes ) return dset
def match ( self , text , noprefix = False ) : """Matches date / datetime string against date patterns and returns pattern and parsed date if matched . It ' s not indeded for common usage , since if successful it returns date as array of numbers and pattern that matched this date : param text : Any human re...
n = len ( text ) if self . cachedpats is not None : pats = self . cachedpats else : pats = self . patterns if n > 5 and not noprefix : basekeys = self . __matchPrefix ( text [ : 6 ] ) else : basekeys = [ ] for p in pats : if n < p [ 'length' ] [ 'min' ] or n > p [ 'length' ] [ 'max' ] : cont...
def on_server_shutdown ( self ) : """Stop the container before shutting down ."""
if not self . _container : return self . _container . stop ( ) self . _container . remove ( v = True , force = True )
def load ( self ) : """Load the climate data as a map Returns : dict : { data : masked 3D numpy array containing climate data per month ( first axis ) , lat _ idx : function converting a latitude to the ( fractional ) row index in the map , lon _ idx : function converting a longitude to the ( fractional ) c...
from scipy . io import netcdf_file from scipy import interpolate import numpy as np # load file f = netcdf_file ( self . input_file ) # extract data , make explicity copies of data out = dict ( ) lats = f . variables [ 'lat' ] [ : ] . copy ( ) lons = f . variables [ 'lon' ] [ : ] . copy ( ) # lons start at 0 , this is ...
def get_smart_task ( self , task_id ) : """Return specified transition . Returns a Command ."""
def process_result ( result ) : return SmartTask ( self , result ) return Command ( 'get' , [ ROOT_SMART_TASKS , task_id ] , process_result = process_result )
def links ( res : requests . models . Response , search : str = None , pattern : str = None ) -> list : """Get the links of the page . Args : res ( requests . models . Response ) : The response of the page . search ( str , optional ) : Defaults to None . Search the links you want . pattern ( str , optional ...
hrefs = [ link . to_text ( ) for link in find_all_links ( res . text ) ] if search : hrefs = [ href for href in hrefs if search in href ] if pattern : hrefs = [ href for href in hrefs if re . findall ( pattern , href ) ] return list ( set ( hrefs ) )
def calcR2 ( predTst , yTest , axis = 0 ) : """calculate coefficient of determination . Assumes that axis = 0 is time Parameters predTst : np . array , predicted reponse for yTest yTest : np . array , acxtually observed response for yTest Returns aryFunc : np . array R2"""
rss = np . sum ( ( yTest - predTst ) ** 2 , axis = axis ) tss = np . sum ( ( yTest - yTest . mean ( ) ) ** 2 , axis = axis ) return 1 - rss / tss
def _download_tlds_list ( self ) : """Function downloads list of TLDs from IANA . LINK : https : / / data . iana . org / TLD / tlds - alpha - by - domain . txt : return : True if list was downloaded , False in case of an error : rtype : bool"""
url_list = 'https://data.iana.org/TLD/tlds-alpha-by-domain.txt' # Default cache file exist ( set by _ default _ cache _ file ) # and we want to write permission if self . _default_cache_file and not os . access ( self . _tld_list_path , os . W_OK ) : self . _logger . info ( "Default cache file is not writable." ) ...
def graph_loads ( graph_json ) : '''Load graph'''
layers = [ ] for layer in graph_json [ 'layers' ] : layer_info = Layer ( layer [ 'type' ] , layer [ 'input' ] , layer [ 'output' ] , layer [ 'size' ] ) layer_info . is_delete = layer [ 'is_delete' ] layers . append ( layer_info ) graph = Graph ( graph_json [ 'max_layer_num' ] , [ ] , [ ] , [ ] ) graph . lay...
def get ( self ) : '''Get the wrapped object .'''
if ( self . obj is None ) or ( time . time ( ) >= self . expires ) : with self . lock : self . expires , self . obj = self . factory ( ) if isinstance ( self . obj , BaseException ) : self . exception = self . obj else : self . exception = None if self . exception : ...
def to_build_module ( build_file_path : str , conf : Config ) -> str : """Return a normalized build module name for ` build _ file _ path ` ."""
build_file = Path ( build_file_path ) root = Path ( conf . project_root ) return build_file . resolve ( ) . relative_to ( root ) . parent . as_posix ( ) . strip ( '.' )
def _get_factors ( self , element ) : """Get factors for categorical axes ."""
if not element . kdims : xfactors , yfactors = [ element . label ] , [ ] else : factors = [ key for key in element . groupby ( element . kdims ) . data . keys ( ) ] if element . ndims > 1 : factors = sorted ( factors ) factors = [ tuple ( d . pprint_value ( k ) for d , k in zip ( element . kdims...
def _iiOfAny ( instance , classes ) : """Returns true , if ` instance ` is instance of any ( _ iiOfAny ) of the ` classes ` . This function doesn ' t use : func : ` isinstance ` check , it just compares the class names . This can be generally dangerous , but it is really useful when you are comparing class ...
if type ( classes ) not in [ list , tuple ] : classes = [ classes ] return any ( map ( lambda x : type ( instance ) . __name__ == x . __name__ , classes ) )
def ducrss ( s1 , s2 ) : """Compute the unit vector parallel to the cross product of two 3 - dimensional vectors and the derivative of this unit vector . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ducrss _ c . html : param s1 : Left hand state for cross product and derivat...
assert len ( s1 ) is 6 and len ( s2 ) is 6 s1 = stypes . toDoubleVector ( s1 ) s2 = stypes . toDoubleVector ( s2 ) sout = stypes . emptyDoubleVector ( 6 ) libspice . ducrss_c ( s1 , s2 , sout ) return stypes . cVectorToPython ( sout )
def apply ( self , snapshot ) : """Set the current context from a given snapshot dictionary"""
for name in snapshot : setattr ( self , name , snapshot [ name ] )
def _process_stock_genotype ( self , limit ) : """The genotypes of the stocks . : param limit : : return :"""
if self . test_mode : graph = self . testgraph else : graph = self . graph raw = '/' . join ( ( self . rawdir , 'stock_genotype' ) ) LOG . info ( "processing stock genotype" ) line_counter = 0 with open ( raw , 'r' ) as f : filereader = csv . reader ( f , delimiter = '\t' , quotechar = '\"' ) f . readli...
def send_headers ( self ) : """Assert , process , and send the HTTP response message - headers . You must set self . status , and self . outheaders before calling this ."""
hkeys = [ key . lower ( ) for key , value in self . outheaders ] status = int ( self . status [ : 3 ] ) if status == 413 : # Request Entity Too Large . Close conn to avoid garbage . self . close_connection = True elif b'content-length' not in hkeys : # " All 1xx ( informational ) , 204 ( no content ) , # and 304 ( ...
def is_canfulfill_intent_name ( name ) : # type : ( str ) - > Callable [ [ HandlerInput ] , bool ] """A predicate function returning a boolean , when name matches the intent name in a CanFulfill Intent Request . The function can be applied on a : py : class : ` ask _ sdk _ core . handler _ input . HandlerInpu...
def can_handle_wrapper ( handler_input ) : # type : ( HandlerInput ) - > bool return ( isinstance ( handler_input . request_envelope . request , CanFulfillIntentRequest ) and handler_input . request_envelope . request . intent . name == name ) return can_handle_wrapper
def sample_without_replacement ( n , k , num_trials = None , random_state = None ) : """Randomly choose k integers without replacement from 0 , . . . , n - 1. Parameters n : scalar ( int ) Number of integers , 0 , . . . , n - 1 , to sample from . k : scalar ( int ) Number of integers to sample . num _ t...
if n <= 0 : raise ValueError ( 'n must be greater than 0' ) if k > n : raise ValueError ( 'k must be smaller than or equal to n' ) size = k if num_trials is None else ( num_trials , k ) random_state = check_random_state ( random_state ) r = random_state . random_sample ( size = size ) result = _sample_without_r...
def backend_notification ( self , event = None , parameters = None ) : """The Alignak backend raises an event to the Alignak arbiter Possible events are : - creation , for a realm or an host creation - deletion , for a realm or an host deletion Calls the reload configuration function if event is creation or...
# request _ parameters = cherrypy . request . json # event = request _ parameters . get ( ' event ' , event ) # parameters = request _ parameters . get ( ' parameters ' , parameters ) if event is None : data = cherrypy . request . json event = data . get ( 'event' , None ) if parameters is None : data = che...
def get_countries_in_region ( cls , region , use_live = True , exception = None ) : # type : ( Union [ int , str ] , bool , Optional [ ExceptionUpperBound ] ) - > List [ str ] """Get countries ( ISO3 codes ) in region Args : region ( Union [ int , str ] ) : Three digit UNStats M49 region code or region name u...
countriesdata = cls . countriesdata ( use_live = use_live ) if isinstance ( region , int ) : regioncode = region else : regionupper = region . upper ( ) regioncode = countriesdata [ 'regionnames2codes' ] . get ( regionupper ) if regioncode is not None : return countriesdata [ 'regioncodes2countries' ] [...
def clear_strategies ( self , client_conn , remove_client = False ) : """Clear the sensor strategies of a client connection . Parameters client _ connection : ClientConnection instance The connection that should have its sampling strategies cleared remove _ client : bool , optional Remove the client conne...
assert get_thread_ident ( ) == self . _server . ioloop_thread_id getter = ( self . _strategies . pop if remove_client else self . _strategies . get ) strategies = getter ( client_conn , None ) if strategies is not None : for sensor , strategy in list ( strategies . items ( ) ) : strategy . cancel ( ) ...
def request_homescreen ( blink ) : """Request homescreen info ."""
url = "{}/api/v3/accounts/{}/homescreen" . format ( blink . urls . base_url , blink . account_id ) return http_get ( blink , url )
def is_consistent ( database , solver , exchange = set ( ) , zeromass = set ( ) ) : """Try to assign a positive mass to each compound Return True if successful . The masses are simply constrained by m _ i > 1 and finding a solution under these conditions proves that the database is mass consistent ."""
prob = solver . create_problem ( ) compound_set = _non_localized_compounds ( database ) mass_compounds = compound_set . difference ( zeromass ) # Define mass variables m = prob . namespace ( mass_compounds , lower = 1 ) prob . set_objective ( m . sum ( mass_compounds ) ) # Define constraints massbalance_lhs = { reactio...
def transformer_librispeech_v1 ( ) : """HParams for training ASR model on LibriSpeech V1."""
hparams = transformer_base ( ) hparams . num_heads = 4 hparams . filter_size = 1024 hparams . hidden_size = 256 hparams . num_encoder_layers = 5 hparams . num_decoder_layers = 3 hparams . learning_rate = 0.15 hparams . batch_size = 6000000 librispeech . set_librispeech_length_hparams ( hparams ) return hparams
def parse_date ( dateString ) : '''Parses a variety of date formats into a 9 - tuple in GMT'''
if not dateString : return None for handler in _date_handlers : try : date9tuple = handler ( dateString ) except ( KeyError , OverflowError , ValueError ) : continue if not date9tuple : continue if len ( date9tuple ) != 9 : continue return date9tuple return None
def _ParseAttributesGroup ( self , file_object ) : """Parses a CUPS IPP attributes group from a file - like object . Args : file _ object ( dfvfs . FileIO ) : file - like object . Yields : tuple [ str , object ] : attribute name and value . Raises : ParseError : if the attributes group cannot be parsed ...
tag_value_map = self . _GetDataTypeMap ( 'int8' ) tag_value = 0 while tag_value != self . _DELIMITER_TAG_END_OF_ATTRIBUTES : file_offset = file_object . tell ( ) tag_value , _ = self . _ReadStructureFromFileObject ( file_object , file_offset , tag_value_map ) if tag_value >= 0x10 : file_object . see...
def compile ( conf ) : """Compiles classic uWSGI configuration file using the default or given ` uwsgiconf ` configuration module ."""
with errorprint ( ) : config = ConfModule ( conf ) for conf in config . configurations : conf . format ( do_print = True )
def findvalue ( array , value , compare = lambda x , y : x == y ) : "A function that uses the compare function to return a value from the list ."
try : return next ( x for x in array if compare ( x , value ) ) except StopIteration : raise ValueError ( '%r not in array' % value )
def get_item_ids_metadata ( self ) : """get the metadata for item"""
metadata = dict ( self . _item_ids_metadata ) metadata . update ( { 'existing_id_values' : self . my_osid_object_form . _my_map [ 'itemIds' ] } ) return Metadata ( ** metadata )
async def create ( self , model_ , ** data ) : """Create a new object saved to database ."""
inst = model_ ( ** data ) query = model_ . insert ( ** dict ( inst . __data__ ) ) pk = await self . execute ( query ) if inst . _pk is None : inst . _pk = pk return inst
def douglas_rachford_pd ( x , f , g , L , niter , tau = None , sigma = None , callback = None , ** kwargs ) : r"""Douglas - Rachford primal - dual splitting algorithm . Minimizes the sum of several convex functions composed with linear operators : : min _ x f ( x ) + sum _ i g _ i ( L _ i x ) where ` ` f ` ...
# Validate input m = len ( L ) if not all ( isinstance ( op , Operator ) for op in L ) : raise ValueError ( '`L` not a sequence of operators' ) if not all ( op . is_linear for op in L ) : raise ValueError ( 'not all operators in `L` are linear' ) if not all ( x in op . domain for op in L ) : raise ValueErro...
def parse ( self , message , schema ) : """Parse message according to schema . ` message ` should already be validated against the given schema . See : ref : ` schemadef ` for more information . Args : message ( dict ) : message data to parse . schema ( str ) : valid message schema . Returns : ( dict ...
func = { 'audit-log' : self . _parse_audit_log_msg , 'event' : self . _parse_event_msg , } [ schema ] return func ( message )
def getmany ( cls , route , args , kwargs , _keys ) : """1 . build name space 2 . look locally for copies 3 . build group for batch 4 . fetch the new ones 5 . return found + new list"""
# copy the list of keys keys = [ ] + _keys # build a list of returning objects returning = [ ] # dictionary of references namespaces = { } # key : ns namespace_keys = { } # ns : key # shorthand returning_append = returning . append memory_get = debris . services . memory . get memory_set = debris . services . memory . ...
def apply ( self , mentions ) : """Apply the Matcher to a * * generator * * of mentions . Optionally only takes the longest match ( NOTE : assumes this is the * first * match )"""
seen_spans = set ( ) for m in mentions : if self . f ( m ) and ( not self . longest_match_only or not any ( [ self . _is_subspan ( m , s ) for s in seen_spans ] ) ) : if self . longest_match_only : seen_spans . add ( self . _get_span ( m ) ) yield m
def make_reverse_dict ( in_dict , warn = True ) : """Build a reverse dictionary from a cluster dictionary Parameters in _ dict : dict ( int : [ int , ] ) A dictionary of clusters . Each cluster is a source index and the list of other source in the cluster . Returns out _ dict : dict ( int : int ) A si...
out_dict = { } for k , v in in_dict . items ( ) : for vv in v : if vv in out_dict : if warn : print ( "Dictionary collision %i" % vv ) out_dict [ vv ] = k return out_dict
def transform ( self , fseries , norm = True , epoch = None ) : """Calculate the energy ` TimeSeries ` for the given fseries Parameters fseries : ` ~ gwpy . frequencyseries . FrequencySeries ` the complex FFT of a time - series data set norm : ` bool ` , ` str ` , optional normalize the energy of the outp...
from . . timeseries import TimeSeries windowed = fseries [ self . get_data_indices ( ) ] * self . get_window ( ) # pad data , move negative frequencies to the end , and IFFT padded = numpy . pad ( windowed , self . padding , mode = 'constant' ) wenergy = npfft . ifftshift ( padded ) # return a ` TimeSeries ` if epoch i...
def get_keypair ( vm_ ) : '''Return the keypair to use'''
keypair = config . get_cloud_config_value ( 'keypair' , vm_ , __opts__ ) if keypair : return keypair else : return False
def add ( self , header , data ) : """appends a new entry to the file"""
if header [ 0 ] != '>' : self . data . append ( ( '>' + header , data ) ) else : self . data . append ( ( header , data ) )
def clone ( giturl , gitpath ) : """clone 一个 git 库 。 : param str giturl : git 仓库的 url 地址 。 : param str gitpath : git 仓库保存路径 。"""
gitArgs = [ 'git' , 'clone' , giturl , gitpath ] slog . info ( ' ' . join ( gitArgs ) ) return subprocess . call ( gitArgs )
def get_calcs ( db , request_get_dict , allowed_users , user_acl_on = False , id = None ) : """: param db : a : class : ` openquake . server . dbapi . Db ` instance : param request _ get _ dict : a dictionary : param allowed _ users : a list of users : param user _ acl _ on : if True , returns only th...
# helper to get job + calculation data from the oq - engine database filterdict = { } if id is not None : filterdict [ 'id' ] = id if 'calculation_mode' in request_get_dict : filterdict [ 'calculation_mode' ] = request_get_dict . get ( 'calculation_mode' ) if 'is_running' in request_get_dict : is_running = ...
def out_format ( data , out = 'nested' , opts = None , ** kwargs ) : '''Return the formatted outputter string for the Python object . data The JSON serializable object . out : ` ` nested ` ` The name of the output to use to transform the data . Default : ` ` nested ` ` . opts Dictionary of configuration...
if not opts : opts = __opts__ return salt . output . out_format ( data , out , opts = opts , ** kwargs )
def Print ( self , output_writer ) : """Prints a human readable version of the filter . Args : output _ writer ( CLIOutputWriter ) : output writer ."""
if self . _names : output_writer . Write ( '\tnames: {0:s}\n' . format ( ', ' . join ( self . _names ) ) )
def prepare_data ( self ) : '''Method returning data passed to template . Subclasses can override it .'''
value = self . get_raw_value ( ) return dict ( widget = self , field = self . field , value = value , readonly = not self . field . writable )
def unsubscribe ( self , callback_id ) : """Ask the hub to cancel the subscription for callback _ id , then delete it from the local database if successful ."""
request = self . get_active_subscription ( callback_id ) request [ 'mode' ] = 'unsubscribe' self . subscribe_impl ( callback_id , ** request )
def load ( self , list_file ) : """Loads the list of annotations from the given file and * * appends * * it to the current list . ` ` list _ file ` ` : str The name of a list file to load and append"""
with open ( list_file ) as f : for line in f : if line and line [ 0 ] != '#' : splits = line . split ( ) bounding_boxes = [ ] for i in range ( 1 , len ( splits ) , 4 ) : assert splits [ i ] [ 0 ] == '[' and splits [ i + 3 ] [ - 1 ] == ']' b...
def get ( cls , user_id , client_id ) : """Get RemoteAccount object for user . : param user _ id : User id : param client _ id : Client id . : returns : A : class : ` invenio _ oauthclient . models . RemoteAccount ` instance ."""
return cls . query . filter_by ( user_id = user_id , client_id = client_id , ) . first ( )
def back_bfs ( self , start , end = None ) : """Returns a list of nodes in some backward BFS order . Starting from the start node the breadth first search proceeds along incoming edges ."""
return [ node for node , step in self . _iterbfs ( start , end , forward = False ) ]
def add_jar_entries ( self , jar_file , digest_name = "SHA-256" ) : """Add manifest sections for all but signature - related entries of : param jar _ file . : param digest _ name The digest algorithm to use : return None TODO : join code with cli _ create"""
key_digest = digest_name + "-Digest" digest = _get_digest ( digest_name ) with ZipFile ( jar_file , 'r' ) as jar : for entry in jar . namelist ( ) : if file_skips_verification ( entry ) : continue section = self . create_section ( entry ) section [ key_digest ] = b64_encoded_dige...
def _generate_examples ( self , archive_paths , objects_getter , bboxes_getter , prefixes = None ) : """Yields examples ."""
trainable_classes = set ( self . info . features [ 'objects_trainable' ] [ 'label' ] . names ) for i , archive_path in enumerate ( archive_paths ) : prefix = prefixes [ i ] if prefixes else None objects = objects_getter ( prefix ) bboxes = bboxes_getter ( prefix ) logging . info ( 'Opening archive %s .....
def chooseForm_slot ( self , element , element_old ) : """Calling this slot chooses the form to be shown : param element : an object that has * _ id * and * classname * attributes : param element _ old : an object that has * _ id * and * classname * attributes This slot is typically connected to List classes ...
self . current_slot = None if ( verbose ) : # enable this if you ' re unsure what ' s coming here . . print ( self . pre , "chooseForm_slot :" , element ) if ( isinstance ( element , type ( None ) ) ) : self . current_row = None self . element = None else : # print ( self . pre , " chooseForm _ slot : " , e...
def _onMessage ( self , ws , message ) : """Called when websocket message is recieved ."""
try : data = json . loads ( message ) [ 'NotificationContainer' ] log . debug ( 'Alert: %s %s %s' , * data ) if self . _callback : self . _callback ( data ) except Exception as err : # pragma : no cover log . error ( 'AlertListener Msg Error: %s' , err )
def percentile_nearest ( self , percentile ) : """Get nearest percentile from regression model evaluation results . Args : percentile : a 0 ~ 100 float number . Returns : the percentile float number . Raises : Exception if the CSV headers do not include ' target ' or ' predicted ' , or BigQuery does n...
if self . _input_csv_files : df = self . _get_data_from_csv_files ( ) if 'target' not in df or 'predicted' not in df : raise ValueError ( 'Cannot find "target" or "predicted" column' ) df = df [ [ 'target' , 'predicted' ] ] . apply ( pd . to_numeric ) abs_errors = np . array ( ( df [ 'target' ] ...
def _sample_oat ( problem , N , num_levels = 4 ) : """Generate trajectories without groups Arguments problem : dict The problem definition N : int The number of samples to generate num _ levels : int , default = 4 The number of grid levels"""
group_membership = np . asmatrix ( np . identity ( problem [ 'num_vars' ] , dtype = int ) ) num_params = group_membership . shape [ 0 ] sample = np . zeros ( ( N * ( num_params + 1 ) , num_params ) ) sample = np . array ( [ generate_trajectory ( group_membership , num_levels ) for n in range ( N ) ] ) return sample . r...
def fromtab ( args ) : """% prog fromtab tabfile fastafile Convert 2 - column sequence file to FASTA format . One usage for this is to generatea ` adapters . fasta ` for TRIMMOMATIC ."""
p = OptionParser ( fromtab . __doc__ ) p . set_sep ( sep = None ) p . add_option ( "--noheader" , default = False , action = "store_true" , help = "Ignore first line" ) p . add_option ( "--replace" , help = "Replace spaces in name to char [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2...
def resize_pane ( pymux , variables ) : """Resize / zoom the active pane ."""
try : left = int ( variables [ '<left>' ] or 0 ) right = int ( variables [ '<right>' ] or 0 ) up = int ( variables [ '<up>' ] or 0 ) down = int ( variables [ '<down>' ] or 0 ) except ValueError : raise CommandException ( 'Expecting an integer.' ) w = pymux . arrangement . get_active_window ( ) if w ...
def get_abbr_impl ( env ) : """Return abbreviated implementation name ."""
impl = env . python_implementation if impl == "PyPy" : return "pp" elif impl == "Jython" : return "jy" elif impl == "IronPython" : return "ip" elif impl == "CPython" : return "cp" raise LookupError ( "Unknown Python implementation: " + impl )
def search_prod_type_tags ( self , tipo , ins , tags , pipeline ) : """Returns the first coincidence . . ."""
drp = self . drps . query_by_name ( ins ) label = drp . product_label ( tipo ) # Strip ( ) is present if label . endswith ( "()" ) : label_alt = label [ : - 2 ] else : label_alt = label # search results of these OBs for prod in self . prod_table [ ins ] : pk = prod [ 'type' ] pt = prod [ 'tags' ] if...
def _GetTimeElementsTuple ( self , key , structure ) : """Retrieves a time elements tuple from the structure . Args : key ( str ) : name of the parsed structure . structure ( pyparsing . ParseResults ) : structure of tokens derived from a line of a text file . Returns : tuple : containing : year ( int...
if key == 'turned_over_header' : month , day , hours , minutes , seconds = structure . date_time milliseconds = 0 else : _ , month , day , hours , minutes , seconds , milliseconds = structure . date_time # Note that dfdatetime _ time _ elements . TimeElements will raise ValueError # for an invalid month . m...
def get_contributors ( self , subreddit , * args , ** kwargs ) : """Return a get _ content generator of contributors for the given subreddit . If it ' s a public subreddit , then authentication as a moderator of the subreddit is required . For protected / private subreddits only access is required . See issue...
# pylint : disable = W0613 def get_contributors_helper ( self , subreddit ) : # It is necessary to have the ' self ' argument as it ' s needed in # restrict _ access to determine what class the decorator is # operating on . url = self . config [ 'contributors' ] . format ( subreddit = six . text_type ( subreddit ) ...
def select_model ( self , name ) : """choose an existing model"""
if name not in self . _parent : raise KeyError ( 'model "{}" not present' . format ( name ) ) self . _current_model_group = name
def validate_ip ( self ) : """Check ip if that is needed . Raise web . HTTPUnauthorized for not allowed hosts ."""
if self . request . app . get ( '_check_ip' , False ) : ip_address , accept = self . check_ip ( ) if not accept : raise web . HTTPUnauthorized ( )
def CBO_Gamma ( self , ** kwargs ) : '''Returns the strain - shifted Gamma - valley conduction band offset ( CBO ) , assuming the strain affects all conduction band valleys equally .'''
return ( self . unstrained . CBO_Gamma ( ** kwargs ) + self . CBO_strain_shift ( ** kwargs ) )
def get_type_description ( self , _type , suffix = '' , * args , ** kwargs ) : """Get description of type : param suffix : : param str _ type : : rtype : str"""
if not SchemaObjects . contains ( _type ) : return _type schema = SchemaObjects . get ( _type ) if schema . all_of : models = ',' . join ( ( self . get_type_description ( _type , * args , ** kwargs ) for _type in schema . all_of ) ) result = '{}' . format ( models . split ( ',' ) [ 0 ] ) for r in models...
def execute_from_file ( self , url , file_var ) : '''Identical to WebPypeClient . execute ( ) , except this function accepts a file path or file type instead of a dictionary .'''
if isinstance ( file_var , file ) : f = file_var elif isinstance ( file_var , str ) : try : f = open ( file_var ) except IOError , e : raise e else : raise TypeError ( "This function only accepts a 'file' type or file path" ) inputs = json . loads ( f . read ( ) ) resp = self . execute ...
def describe_version ( self , ) : """get the thrift api version"""
self . _seqid += 1 d = self . _reqs [ self . _seqid ] = defer . Deferred ( ) self . send_describe_version ( ) return d
def plot_confusion_matrix ( cm , classes , normalize = False , title = 'Confusion matrix' , cmap = plt . cm . Blues ) : """This function prints and plots the confusion matrix . Normalization can be applied by setting ` normalize = True ` ."""
if normalize : cm = cm . astype ( 'float' ) / cm . sum ( axis = 1 ) [ : , np . newaxis ] print ( "Normalized confusion matrix" ) else : print ( 'Confusion matrix, without normalization' ) print ( cm ) plt . imshow ( cm , interpolation = 'nearest' , cmap = cmap ) plt . title ( title ) plt . colorbar ( ) tick...
def find_package ( name : str ) -> Tuple [ Optional [ Path ] , Path ] : """Finds packages install prefix ( or None ) and it ' s containing Folder"""
module = name . split ( "." ) [ 0 ] loader = pkgutil . get_loader ( module ) if name == "__main__" or loader is None : package_path = Path . cwd ( ) else : if hasattr ( loader , 'get_filename' ) : filename = loader . get_filename ( module ) # type : ignore else : __import__ ( name ) ...
def autoparse ( func = None , * , description = None , epilog = None , add_nos = False , parser = None ) : '''This decorator converts a function that takes normal arguments into a function which takes a single optional argument , argv , parses it using an argparse . ArgumentParser , and calls the underlying fun...
# If @ autoparse ( . . . ) is used instead of @ autoparse if func is None : return lambda f : autoparse ( f , description = description , epilog = epilog , add_nos = add_nos , parser = parser ) func_sig = signature ( func ) docstr_description , docstr_epilog = parse_docstring ( getdoc ( func ) ) if parser is None :...
def select_many ( self , collection_selector = identity , result_selector = identity ) : '''Projects each element of a sequence to an intermediate new sequence , flattens the resulting sequences into one sequence and optionally transforms the flattened sequence using a selector function . Note : This method u...
if self . closed ( ) : raise ValueError ( "Attempt to call select_many() on a closed " "Queryable." ) if not is_callable ( collection_selector ) : raise TypeError ( "select_many() parameter projector={0} is not " "callable" . format ( repr ( collection_selector ) ) ) if not is_callable ( result_selector ) : ...
def DjangoStaticResource ( path , rel_url = 'static' ) : """takes an app level file dir to find the site root and servers static files from static Usage : [ . . . in app . resource . . . ] from hendrix . resources import DjangoStaticResource StaticResource = DjangoStaticResource ( ' / abspath / to / stati...
rel_url = rel_url . strip ( '/' ) StaticFilesResource = MediaResource ( path ) StaticFilesResource . namespace = rel_url chalk . green ( "Adding media resource for URL '%s' at path '%s'" % ( rel_url , path ) ) return StaticFilesResource
def add_moc_from_URL ( self , moc_URL , moc_options = { } ) : """load a MOC from a URL and display it in Aladin Lite widget Arguments : moc _ URL : string url moc _ options : dictionary object"""
self . moc_URL = moc_URL self . moc_options = moc_options self . moc_from_URL_flag = not self . moc_from_URL_flag
def read_cumulative_iss_index ( ) : "Read in the whole cumulative index and return dataframe ."
indexdir = get_index_dir ( ) path = indexdir / "COISS_2999_index.hdf" try : df = pd . read_hdf ( path , "df" ) except FileNotFoundError : path = indexdir / "cumindex.hdf" df = pd . read_hdf ( path , "df" ) # replace PDS Nan values ( - 1e32 ) with real NaNs df = df . replace ( - 1.000000e32 , np . nan ) retu...
def authenticated ( self , environ , username = None , password = None , ** params ) : '''Called by the server to check if client is authenticated .'''
if username != self . username : return False o = self . options qop = o . get ( 'qop' ) method = environ [ 'REQUEST_METHOD' ] uri = environ . get ( 'PATH_INFO' , '' ) ha1 = self . ha1 ( o [ 'realm' ] , password ) ha2 = self . ha2 ( qop , method , uri ) if qop is None : response = hexmd5 ( ":" . join ( ( ha1 , ...
def ecdsa_signature_normalize ( self , raw_sig , check_only = False ) : """Check and optionally convert a signature to a normalized lower - S form . If check _ only is True then the normalized signature is not returned . This function always return a tuple containing a boolean ( True if not previously normali...
if check_only : sigout = ffi . NULL else : sigout = ffi . new ( 'secp256k1_ecdsa_signature *' ) result = lib . secp256k1_ecdsa_signature_normalize ( self . ctx , sigout , raw_sig ) return ( bool ( result ) , sigout if sigout != ffi . NULL else None )
def nacm_rule_list_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 = ET . SubElement ( rule_list , "name" ) name . text = kwargs . pop ( 'name' ) callback = kwargs . pop ( 'callback' , self . _cal...
def generate_sibling_distance ( self ) : """Generate a dict containing the distance computed as difference in in number of partitions of each topic from under _ loaded _ brokers to over _ loaded _ brokers . Negative distance means that the destination broker has got less partitions of a certain topic than t...
sibling_distance = defaultdict ( lambda : defaultdict ( dict ) ) topics = { p . topic for p in self . partitions } for source in self . brokers : for dest in self . brokers : if source != dest : for topic in topics : sibling_distance [ dest ] [ source ] [ topic ] = dest . count_p...
def reverse_lookup ( mnemonic : str ) : """Find instruction that matches the mnemonic . : param mnemonic : Mnemonic to match : return : : class : ` Instruction ` that matches or None"""
for i in get_insns ( ) : if "_mnemonic" in i . __dict__ and i . _mnemonic == mnemonic : return i return None
def _get_mainchain ( df , invert ) : """Return only main chain atom entries from a DataFrame"""
if invert : mc = df [ ( df [ 'atom_name' ] != 'C' ) & ( df [ 'atom_name' ] != 'O' ) & ( df [ 'atom_name' ] != 'N' ) & ( df [ 'atom_name' ] != 'CA' ) ] else : mc = df [ ( df [ 'atom_name' ] == 'C' ) | ( df [ 'atom_name' ] == 'O' ) | ( df [ 'atom_name' ] == 'N' ) | ( df [ 'atom_name' ] == 'CA' ) ] return mc
def item_acl ( self , item ) : """Objectify ACL if ES is used or call item . get _ acl ( ) if db is used ."""
if self . es_based : from nefertari_guards . elasticsearch import get_es_item_acl return get_es_item_acl ( item ) return super ( DatabaseACLMixin , self ) . item_acl ( item )
def unpack_fixed8 ( src ) : """Get a FIXED8 value ."""
dec_part = unpack_ui8 ( src ) int_part = unpack_ui8 ( src ) return int_part + dec_part / 256
def set ( self , value ) : '''Atomically sets the value to ` value ` . : param value : The value to set .'''
with self . _reference . get_lock ( ) : self . _reference . value = value return value
def head_request ( self , container , resource = None ) : """Send a HEAD request ."""
url = self . make_url ( container , resource ) headers = self . _make_headers ( None ) try : rsp = requests . head ( url , headers = self . _base_headers , verify = self . _verify , timeout = self . _timeout ) except requests . exceptions . ConnectionError as e : RestHttp . _raise_conn_error ( e ) if self . _db...
def forward ( self , # pylint : disable = arguments - differ text_field_input : Dict [ str , torch . Tensor ] , num_wrapping_dims : int = 0 ) -> torch . Tensor : """Parameters text _ field _ input : ` ` Dict [ str , torch . Tensor ] ` ` A dictionary that was the output of a call to ` ` TextField . as _ tensor `...
raise NotImplementedError
def upgrade ( refresh = False , ** kwargs ) : '''Upgrade all packages to the latest possible version . When run in global zone , it updates also all non - global zones . In non - global zones upgrade is limited by dependency constrains linked to the version of pkg : / / solaris / entire . Returns a dictiona...
if salt . utils . data . is_true ( refresh ) : refresh_db ( ) # Get a list of the packages before install so we can diff after to see # what got installed . old = list_pkgs ( ) # Install or upgrade the package # If package is already installed cmd = [ 'pkg' , 'update' , '-v' , '--accept' ] result = __salt__ [ 'cmd....
def query ( method = 'GET' , profile_dict = None , url = None , path = 'api/v1' , action = None , api_key = None , service = None , params = None , data = None , subdomain = None , client_url = None , description = None , opts = None , verify_ssl = True ) : '''Query the PagerDuty API'''
user_agent = 'SaltStack {0}' . format ( __version__ ) if opts is None : opts = { } if isinstance ( profile_dict , dict ) : creds = profile_dict else : creds = { } if api_key is not None : creds [ 'pagerduty.api_key' ] = api_key if service is not None : creds [ 'pagerduty.service' ] = service if subd...
def rmvsuffix ( subject ) : """Remove the suffix from * subject * ."""
index = subject . rfind ( '.' ) if index > subject . replace ( '\\' , '/' ) . rfind ( '/' ) : subject = subject [ : index ] return subject
def strip_mentions_links ( self , text ) : """Strips Mentions and Links : param text : Text to be stripped from ."""
# print ' Before : ' , text new_text = [ word for word in text . split ( ) if not self . is_mention_line ( word ) ] # print ' After : ' , u ' ' . join ( new _ text ) return u' ' . join ( new_text )
def save_batches ( server_context , assay_id , batches ) : # type : ( ServerContext , int , List [ Batch ] ) - > Union [ List [ Batch ] , None ] """Saves a modified batches . : param server _ context : A LabKey server context . See utils . create _ server _ context . : param assay _ id : The assay protocol id ....
save_batch_url = server_context . build_url ( 'assay' , 'saveAssayBatch.api' ) json_batches = [ ] if batches is None : return None # Nothing to save for batch in batches : if isinstance ( batch , Batch ) : json_batches . append ( batch . to_json ( ) ) else : raise Exception ( 'save_batch() "...
def version_cmp ( ver1 , ver2 , ignore_epoch = False , ** kwargs ) : '''. . versionadded : : 2015.5.4 Do a cmp - style comparison on two packages . Return - 1 if ver1 < ver2 , 0 if ver1 = = ver2 , and 1 if ver1 > ver2 . Return None if there was a problem making the comparison . ignore _ epoch : False Set ...
return __salt__ [ 'lowpkg.version_cmp' ] ( ver1 , ver2 , ignore_epoch = ignore_epoch )
def remove ( name : str ) -> bool : """Remove corpus : param string name : corpus name : return : True or False"""
db = TinyDB ( corpus_db_path ( ) ) temp = Query ( ) data = db . search ( temp . name == name ) if len ( data ) > 0 : path = get_corpus_path ( name ) os . remove ( path ) db . remove ( temp . name == name ) return True return False