signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _set_system_qos ( self , v , load = False ) : """Setter method for system _ qos , mapped from YANG variable / system _ qos ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ system _ qos is considered as a private method . Backends looking to populate t...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = system_qos . system_qos , is_container = 'container' , presence = False , yang_name = "system-qos" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True...
def _set_token_expiration_time ( self , expires_in ) : """Saves the token expiration time by adding the ' expires in ' parameter to the current datetime ( in utc ) . Parameters expires _ in : int number of seconds from the time of the request until expiration Returns nothing saves expiration time in s...
self . token_expiration_time = dt . datetime . utcnow ( ) + dt . timedelta ( 0 , expires_in )
def _create_controller_info_record ( self , controller_module_name ) : """Creates controller info record for a particular controller type . Info is retrieved from all the controller objects spawned from the specified module , using the controller module ' s ` get _ info ` function . Args : controller _ modu...
module = self . _controller_modules [ controller_module_name ] controller_info = None try : controller_info = module . get_info ( copy . copy ( self . _controller_objects [ controller_module_name ] ) ) except AttributeError : logging . warning ( 'No optional debug info found for controller ' '%s. To provide it,...
def _meco_frequency ( m1 , m2 , chi1 , chi2 ) : """Returns the frequency of the minimum energy cutoff for 3.5pN ( 2.5pN spin )"""
return velocity_to_frequency ( meco_velocity ( m1 , m2 , chi1 , chi2 ) , m1 + m2 )
def run_job_async ( self , tgt , fun , arg = ( ) , tgt_type = 'glob' , ret = '' , timeout = None , jid = '' , kwarg = None , listen = True , io_loop = None , ** kwargs ) : '''Asynchronously send a command to connected minions Prep the job directory and publish a command to any targeted minions . : return : A di...
arg = salt . utils . args . parse_input ( arg , kwargs = kwarg ) try : pub_data = yield self . pub_async ( tgt , fun , arg , tgt_type , ret , jid = jid , timeout = self . _get_timeout ( timeout ) , io_loop = io_loop , listen = listen , ** kwargs ) except SaltClientError : # Re - raise error with specific message ...
def _build ( self , inputs , is_training = True , dropout_keep_prob = 0.5 ) : """Assembles the ` MLP ` and connects it to the graph . Args : inputs : A 2D Tensor of size ` [ batch _ size , input _ size ] ` . is _ training : A bool or tf . Bool Tensor . Indicates whether we are currently training . Defaults ...
self . _input_shape = tuple ( inputs . get_shape ( ) . as_list ( ) ) net = inputs final_index = self . _num_layers - 1 for layer_id in xrange ( self . _num_layers ) : net = self . _layers [ layer_id ] ( net ) if final_index != layer_id or self . _activate_final : # Only perform dropout whenever we are activatin...
def attr ( self , key ) : """Get attribute string from the Booster . Parameters key : str The key to get attribute from . Returns value : str The attribute value of the key , returns None if attribute do not exist ."""
ret = ctypes . c_char_p ( ) success = ctypes . c_int ( ) _check_call ( _LIB . XGBoosterGetAttr ( self . handle , c_str ( key ) , ctypes . byref ( ret ) , ctypes . byref ( success ) ) ) if success . value != 0 : return py_str ( ret . value ) return None
def save_loop ( filename , framerate = 30 , time = 3.0 , axis = np . array ( [ 0. , 0. , 1. ] ) , clf = True , ** kwargs ) : """Off - screen save a GIF of one rotation about the scene . Parameters filename : str The filename in which to save the output image ( should have extension . gif ) framerate : int ...
n_frames = framerate * time az = 2.0 * np . pi / n_frames Visualizer3D . save ( filename , n_frames = n_frames , axis = axis , clf = clf , animate_rate = framerate , animate_az = az ) if clf : Visualizer3D . clf ( )
def euclidean_dissim ( a , b , ** _ ) : """Euclidean distance dissimilarity function"""
if np . isnan ( a ) . any ( ) or np . isnan ( b ) . any ( ) : raise ValueError ( "Missing values detected in numerical columns." ) return np . sum ( ( a - b ) ** 2 , axis = 1 )
def _strip_object ( key ) : """Strips branch and version info if the given key supports those attributes ."""
if hasattr ( key , 'version_agnostic' ) and hasattr ( key , 'for_branch' ) : return key . for_branch ( None ) . version_agnostic ( ) else : return key
def get_related_indicators ( self , indicators = None , enclave_ids = None ) : """Uses the | get _ related _ indicators _ page | method to create a generator that returns each successive report . : param list ( string ) indicators : list of indicator values to search for : param list ( string ) enclave _ ids : ...
return Page . get_generator ( page_generator = self . _get_related_indicators_page_generator ( indicators , enclave_ids ) )
def get_epoch_iterator ( self , ** kwargs ) : """Get an epoch iterator for the data stream ."""
if not self . _fresh_state : self . next_epoch ( ) else : self . _fresh_state = False return super ( DataStream , self ) . get_epoch_iterator ( ** kwargs )
def restart ( self , restart_data , run_async = False ) : """conditional and unconditional restart"""
assert isinstance ( restart_data , dict ) if ( not self . restart_matches ( restart_data . get ( 'role' ) , restart_data . get ( 'postgres_version' ) , ( 'restart_pending' in restart_data ) ) ) : return ( False , "restart conditions are not satisfied" ) with self . _async_executor : prev = self . _async_executo...
def random_filtered_sources ( sources , srcfilter , seed ) : """: param sources : a list of sources : param srcfilte : a SourceFilter instance : param seed : a random seed : returns : an empty list or a list with a single filtered source"""
random . seed ( seed ) while sources : src = random . choice ( sources ) if srcfilter . get_close_sites ( src ) is not None : return [ src ] sources . remove ( src ) return [ ]
def _match_getters ( self , query , getters = None ) : """Tries to match in getters : param query : message tuple : type query : Tuple [ bytes ] : return : response if found or None : rtype : Tuple [ bytes ] | None"""
if getters is None : getters = self . _getters if query in getters : name , response = getters [ query ] logger . debug ( 'Found response in getter of %s' % name ) response = response . format ( self . _properties [ name ] . get_value ( ) ) return response . encode ( 'utf-8' )
def diffuser_curved ( Di1 , Di2 , l ) : r'''Returns loss coefficient for any curved wall pipe expansion as shown in [ 1 ] _ . . . math : : K _ 1 = \ phi ( 1.43-1.3 \ beta ^ 2 ) ( 1 - \ beta ^ 2 ) ^ 2 . . math : : \ phi = 1.01 - 0.624 \ frac { l } { d _ 1 } + 0.30 \ left ( \ frac { l } { d _ 1 } \ right ) ...
beta = Di1 / Di2 phi = 1.01 - 0.624 * l / Di1 + 0.30 * ( l / Di1 ) ** 2 - 0.074 * ( l / Di1 ) ** 3 + 0.0070 * ( l / Di1 ) ** 4 return phi * ( 1.43 - 1.3 * beta ** 2 ) * ( 1 - beta ** 2 ) ** 2
def is_expanded ( request , key ) : """Examines request object to return boolean of whether passed field is expanded ."""
expand = request . query_params . get ( "expand" , "" ) expand_fields = [ ] for e in expand . split ( "," ) : expand_fields . extend ( [ e for e in e . split ( "." ) ] ) return "~all" in expand_fields or key in expand_fields
def baart_criteria ( self , X , y ) : """Returns the optimal Fourier series degree as determined by ` Baart ' s Criteria < http : / / articles . adsabs . harvard . edu / cgi - bin / nph - iarticle _ query ? 1986A % 26A . . . 170 . . . 59P & amp ; data _ type = PDF _ HIGH & amp ; whole _ paper = YES & amp ; type =...
try : min_degree , max_degree = self . degree_range except ValueError : raise ValueError ( "Degree range must be a length two sequence" ) cutoff = self . baart_tolerance ( X ) pipeline = Pipeline ( [ ( 'Fourier' , Fourier ( ) ) , ( 'Regressor' , self . regressor ) ] ) sorted_X = numpy . sort ( X , axis = 0 ) X_...
def process ( self , filename , encoding , ** kwargs ) : """Process ` ` filename ` ` and encode byte - string with ` ` encoding ` ` . This method is called by : func : ` textract . parsers . process ` and wraps the : meth : ` . BaseParser . extract ` method in ` a delicious unicode sandwich < http : / / nedba...
# make a " unicode sandwich " to handle dealing with unknown # input byte strings and converting them to a predictable # output encoding # http : / / nedbatchelder . com / text / unipain / unipain . html # 35 byte_string = self . extract ( filename , ** kwargs ) unicode_string = self . decode ( byte_string ) return sel...
def plot_mag_map_basemap ( fignum , element , lons , lats , element_type , cmap = 'RdYlBu' , lon_0 = 0 , date = "" ) : """makes a color contour map of geomagnetic field element Parameters _ _ _ _ _ fignum : matplotlib figure number element : field element array from pmag . do _ mag _ map for plotting lons...
if not has_basemap : print ( '-W- Basemap must be installed to run plot_mag_map_basemap' ) return from matplotlib import cm # matplotlib ' s color map module lincr = 1 if type ( date ) != str : date = str ( date ) fig = plt . figure ( fignum ) m = Basemap ( projection = 'hammer' , lon_0 = lon_0 ) x , y = m ...
def _emit_select ( self , cluster_ids , ** kwargs ) : """Choose spikes from the specified clusters and emit the ` select ` event on the GUI ."""
# Remove non - existing clusters from the selection . cluster_ids = self . _keep_existing_clusters ( cluster_ids ) logger . debug ( "Select cluster(s): %s." , ', ' . join ( map ( str , cluster_ids ) ) ) self . emit ( 'select' , cluster_ids , ** kwargs )
def hash ( self ) : ''': rtype : int : return : hash of the field'''
hashed = super ( Dynamic , self ) . hash ( ) return khash ( hashed , self . _key , self . _length )
def loads ( cls , data , store_password , try_decrypt_keys = True ) : """Loads the given keystore file using the supplied password for verifying its integrity , and returns a : class : ` KeyStore ` instance . Note that entries in the store that represent some form of cryptographic key material are stored in e...
store_type = "" magic_number = data [ : 4 ] if magic_number == MAGIC_NUMBER_JKS : store_type = "jks" elif magic_number == MAGIC_NUMBER_JCEKS : store_type = "jceks" else : raise BadKeystoreFormatException ( 'Not a JKS or JCEKS keystore' ' (magic number wrong; expected' ' FEEDFEED or CECECECE)' ) try : ve...
def on_completions_request ( self , py_db , request ) : ''': param CompletionsRequest request :'''
arguments = request . arguments # : : type arguments : CompletionsArguments seq = request . seq text = arguments . text frame_id = arguments . frameId thread_id = py_db . suspended_frames_manager . get_thread_id_for_variable_reference ( frame_id ) if thread_id is None : body = CompletionsResponseBody ( [ ] ) va...
def get_driver_platform ( self ) : """Get driver platform where tests are running : return : platform name"""
platform = '' if 'platform' in self . driver . desired_capabilities : platform = self . driver . desired_capabilities [ 'platform' ] elif 'platformName' in self . driver . desired_capabilities : platform = self . driver . desired_capabilities [ 'platformName' ] return platform
def delete ( self , key , time = 0 ) : '''Deletes a key from the memcache . @ return : Nonzero on success . @ param time : number of seconds any subsequent set / update commands should fail . Defaults to None for no delay . @ rtype : int'''
if self . do_check_key : self . check_key ( key ) server , key = self . _get_server ( key ) if not server : return 0 self . _statlog ( 'delete' ) if time != None and time != 0 : cmd = "delete %s %d" % ( key , time ) else : cmd = "delete %s" % key try : server . send_cmd ( cmd ) line = server . r...
def get_handler ( ) : """Return the handler as a named tuple . The named tuple attributes are ' host ' , ' port ' , ' signum ' . Return None when no handler has been registered ."""
host , port , signum = _pdbhandler . _registered ( ) if signum : return Handler ( host if host else DFLT_ADDRESS [ 0 ] . encode ( ) , port if port else DFLT_ADDRESS [ 1 ] , signum )
def count_between ( self , min_score = None , max_score = None ) : """Returns the number of members whose score is between * min _ score * and * max _ score * ( inclusive ) ."""
min_score = float ( '-inf' ) if min_score is None else float ( min_score ) max_score = float ( 'inf' ) if max_score is None else float ( max_score ) return self . redis . zcount ( self . key , min_score , max_score )
def _make_class ( cls , ** kwargs ) : """Return a custom Visual class with given parameters ."""
kwargs = { k : ( v if v is not None else getattr ( cls , k , None ) ) for k , v in kwargs . items ( ) } # The class name contains a hash of the custom parameters . name = cls . __name__ + '_' + _hash ( kwargs ) if name not in _CLASSES : logger . log ( 5 , "Create class %s %s." , name , kwargs ) cls = type ( nam...
def output_sshkey ( gandi , sshkey , output_keys , justify = 12 ) : """Helper to output an ssh key information ."""
output_generic ( gandi , sshkey , output_keys , justify )
def reload ( * command , ignore_patterns = [ ] ) : """Reload given command"""
path = "." sig = signal . SIGTERM delay = 0.25 ignorefile = ".reloadignore" ignore_patterns = ignore_patterns or load_ignore_patterns ( ignorefile ) event_handler = ReloadEventHandler ( ignore_patterns ) reloader = Reloader ( command , signal ) observer = Observer ( ) observer . schedule ( event_handler , path , recurs...
def init_defaults ( self ) : """Sets a model instance variable to the table value and sets the name to the table name as determined from the model class"""
super ( ModelTable , self ) . init_defaults ( ) self . model = self . table self . name = self . model . _meta . db_table
def descendants ( self , typename ) : """Return the descendant types of * typename * ."""
xs = [ ] for child in self . _hier [ typename ] [ 1 ] : xs . append ( child ) xs . extend ( self . descendants ( child ) ) return xs
def get_referenced_object ( referring_object , fieldname ) : """Get an object referred to by a field in another object . For example an object of type Construction has fields for each layer , each of which refers to a Material . This functions allows the object representing a Material to be fetched using the ...
idf = referring_object . theidf object_list = referring_object . getfieldidd_item ( fieldname , u'object-list' ) for obj_type in idf . idfobjects : for obj in idf . idfobjects [ obj_type ] : valid_object_lists = obj . getfieldidd_item ( "Name" , u'reference' ) if set ( object_list ) . intersection (...
def dump ( self ) : """Serialize the state of this subsystem into a dict . Returns : dict : The serialized state"""
walker = self . dump_walker if walker is not None : walker = walker . dump ( ) state = { 'storage' : self . storage . dump ( ) , 'dump_walker' : walker , 'next_id' : self . next_id } return state
def _parse_auth_message ( self , auth_message ) : """Parse a message to see if we have ip addresses or users that we care about : param auth _ message : The auth message to parse : return : Result"""
result = { } has_matched = False for regex in REGEXES_INVALID_USER : # Check for the invalid user / ip messages m = re . search ( regex , auth_message ) if m and not has_matched : has_matched = True # Save the username and IP result [ 'username' ] = m . group ( 'user' ) result [ ...
def saltmem ( human_readable = False ) : '''. . versionadded : : 2015.8.0 Returns the amount of memory that salt is using human _ readable : False return the value in a nicely formatted number CLI Example : . . code - block : : bash salt ' * ' status . saltmem salt ' * ' status . saltmem human _ reada...
# psutil . Process defaults to current process ( ` os . getpid ( ) ` ) p = psutil . Process ( ) # Use oneshot to get a snapshot with p . oneshot ( ) : mem = p . memory_info ( ) . rss if human_readable : return _byte_calc ( mem ) return mem
def sendChatMessage ( self , text , id = None , user = None , group = None , channel = None , parse = 'none' , link_names = True , unfurl_links = True , unfurl_media = False , send_with_api = False , icon_emoji = None , icon_url = None , username = None , attachments = None , thread_ts = None , reply_broadcast = False ...
if id is not None : assert user is None , 'id and user cannot both be set.' assert group is None , 'id and group cannot both be set.' assert channel is None , 'id and channel cannot both be set.' elif user is not None : assert group is None , 'user and group cannot both be set.' assert channel is No...
def resolve_doc ( cls , manifest , target_doc_name , target_doc_package , current_project , node_package ) : """Resolve the given documentation . This follows the same algorithm as resolve _ ref except the is _ enabled checks are unnecessary as docs are always enabled ."""
if target_doc_package is not None : return manifest . find_docs_by_name ( target_doc_name , target_doc_package ) candidate_targets = [ current_project , node_package , None ] target_doc = None for candidate in candidate_targets : target_doc = manifest . find_docs_by_name ( target_doc_name , candidate ) if t...
def convert_result ( converter ) : """Decorator that can convert the result of a function call ."""
def decorate ( fn ) : @ inspection . wraps ( fn ) def new_fn ( * args , ** kwargs ) : return converter ( fn ( * args , ** kwargs ) ) return new_fn return decorate
def describe ( self ) : """Describes the method . : return : Description : rtype : dict [ str , object ]"""
return { "name" : self . name , "params" : self . params , "returns" : self . returns , "description" : self . description , }
def combine_mean_curves ( calc_big , calc_small ) : """Combine the hazard curves coming from two different calculations . The result will be the hazard curves of calc _ big , updated on the sites in common with calc _ small with the PoEs of calc _ small . For instance : calc _ big = USA , calc _ small = Calif...
dstore_big = datastore . read ( calc_big ) dstore_small = datastore . read ( calc_small ) sitecol_big = dstore_big [ 'sitecol' ] sitecol_small = dstore_small [ 'sitecol' ] site_id_big = { ( lon , lat ) : sid for sid , lon , lat in zip ( sitecol_big . sids , sitecol_big . lons , sitecol_big . lats ) } site_id_small = { ...
def get_phrases ( text = None , tokens = None , postags = None , tagger = 'nltk' , grammar = 'SimpleNP' , regex = None , minlen = 2 , maxlen = 8 , output = 'counts' ) : """Give a text ( or POS tag sequence ) , return the phrases matching the given grammar . Works on documents or sentences . Returns a dict with ...
global SimpleNP # # try to get values for both ' postags ' and ' tokens ' , parallel lists of strings if postags is None : try : tagger = TAGGER_NAMES [ tagger ] ( ) except : raise Exception ( "We don't support tagger %s" % tagger ) # otherwise , assume it ' s one of our wrapper * Tagger obj...
def _adjust_bin_edges ( datetime_bins , offset , closed , index , labels ) : """This is required for determining the bin edges resampling with daily frequencies greater than one day , month end , and year end frequencies . Consider the following example . Let ' s say you want to downsample the time series w...
is_super_daily = ( isinstance ( offset , ( MonthEnd , QuarterEnd , YearEnd ) ) or ( isinstance ( offset , Day ) and offset . n > 1 ) ) if is_super_daily : if closed == 'right' : datetime_bins = datetime_bins + datetime . timedelta ( days = 1 , microseconds = - 1 ) if datetime_bins [ - 2 ] > index . max ...
def normalizeGlyphTopMargin ( value ) : """Normalizes glyph top margin . * * * value * * must be a : ref : ` type - int - float ` or ` None ` . * Returned value is the same type as the input value ."""
if not isinstance ( value , ( int , float ) ) and value is not None : raise TypeError ( "Glyph top margin must be an :ref:`type-int-float`, " "not %s." % type ( value ) . __name__ ) return value
def write_file ( self , filename , ** kwargs ) : """Writes POSCAR to a file . The supported kwargs are the same as those for the Poscar . get _ string method and are passed through directly ."""
with zopen ( filename , "wt" ) as f : f . write ( self . get_string ( ** kwargs ) )
def get_callable_documentation ( the_callable ) : """Return a string with the callable signature and its docstring . : param the _ callable : the callable to be analyzed . : type the _ callable : function / callable . : return : the signature ."""
return wrap_text_in_a_box ( title = get_callable_signature_as_string ( the_callable ) , body = ( getattr ( the_callable , '__doc__' ) or 'No documentation' ) . replace ( '\n' , '\n\n' ) , style = 'ascii_double' )
def _read_para_relay_hmac ( self , code , cbit , clen , * , desc , length , version ) : """Read HIP RELAY _ HMAC parameter . Structure of HIP RELAY _ HMAC parameter [ RFC 5770 ] : 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | HMAC | | | Padding | Octets Bits Name Description ...
_hmac = self . _read_fileng ( clen ) relay_hmac = dict ( type = desc , critical = cbit , length = clen , hmac = _hmac , ) _plen = length - clen if _plen : self . _read_fileng ( _plen ) return relay_hmac
def conforms ( element , etype , namespace : Dict [ str , Any ] ) -> bool : """Determine whether element conforms to etype : param element : Element to test for conformance : param etype : Type to test against : param namespace : Namespace to use to resolve forward references : return :"""
etype = proc_forward ( etype , namespace ) if is_union ( etype ) : return union_conforms ( element , etype , namespace , conforms ) else : return element_conforms ( element , etype )
def setLinkQuality ( self , EUIadr , LinkQuality ) : """set custom LinkQualityIn for all receiving messages from the specified EUIadr Args : EUIadr : a given extended address LinkQuality : a given custom link quality link quality / link margin mapping table 3 : 21 - 255 ( dB ) 2 : 11 - 20 ( dB ) 1 : 3...
print '%s call setLinkQuality' % self . port print EUIadr print LinkQuality try : # process EUIadr euiHex = hex ( EUIadr ) euiStr = str ( euiHex ) euiStr = euiStr . rstrip ( 'L' ) address64 = '' if '0x' in euiStr : address64 = euiStr . lstrip ( '0x' ) # prepend 0 at the beginning ...
def norm_join ( prefix , suffix ) : """Join ` ` prefix ` ` and ` ` suffix ` ` paths and return the resulting path , normalized . : param string prefix : the prefix path : param string suffix : the suffix path : rtype : string"""
if ( prefix is None ) and ( suffix is None ) : return "." if prefix is None : return os . path . normpath ( suffix ) if suffix is None : return os . path . normpath ( prefix ) return os . path . normpath ( os . path . join ( prefix , suffix ) )
def optimizer_array ( self , p ) : """Make sure the optimizer copy does not get touched , thus , we only want to set the values * inside * not the array itself . Also we want to update param _ array in here ."""
f = None if self . has_parent ( ) and self . constraints [ __fixed__ ] . size != 0 : f = np . ones ( self . size ) . astype ( bool ) f [ self . constraints [ __fixed__ ] ] = FIXED elif self . _has_fixes ( ) : f = self . _fixes_ if f is None : self . param_array . flat = p [ np . put ( self . param_a...
def _get_docargs ( self , args_user , prt ) : """Pare down docopt . Return a minimal dictionary and a set containing runtime arg values ."""
if prt is not None : print ( "DocOptParse BEFORE docopt: {}" . format ( args_user ) ) docargs = docopt ( self . doc , args_user ) if prt is not None : print ( "DocOptParse AFTER docopt: {}" . format ( docargs ) ) kwargs_doc = { re . sub ( r'^-{1,2}' , '' , k ) : v for k , v in docargs . items ( ) } self . _chk...
def from_pillow ( pil_image ) : """Convert from pillow image to opencv"""
# convert PIL to OpenCV pil_image = pil_image . convert ( 'RGB' ) cv2_image = np . array ( pil_image ) # Convert RGB to BGR cv2_image = cv2_image [ : , : , : : - 1 ] . copy ( ) return cv2_image
def CreateTaskStorage ( self , task ) : """Creates a task storage . The task storage is used to store attributes created by the task . Args : task ( Task ) : task . Returns : StorageWriter : storage writer . Raises : IOError : if the storage type is not supported . OSError : if the storage type is n...
if self . _storage_type != definitions . STORAGE_TYPE_SESSION : raise IOError ( 'Unsupported storage type.' ) storage_file_path = self . _GetTaskStorageFilePath ( task ) return self . _CreateTaskStorageWriter ( storage_file_path , task )
def static_proxy ( request ) : """Serves TinyMCE plugins inside the inline popups and the uploadify SWF , as these are normally static files , and will break with cross - domain JavaScript errors if ` ` STATIC _ URL ` ` is an external host . URL for the file is passed in via querystring in the inline popup ...
normalize = lambda u : ( "//" + u . split ( "://" ) [ - 1 ] ) if "://" in u else u url = normalize ( request . GET [ "u" ] ) host = "//" + request . get_host ( ) static_url = normalize ( settings . STATIC_URL ) for prefix in ( host , static_url , "/" ) : if url . startswith ( prefix ) : url = url . replace ...
def statistical_inefficiencies ( dtrajs , lag , C = None , truncate_acf = True , mact = 2.0 , n_jobs = 1 , callback = None ) : r"""Computes statistical inefficiencies of sliding - window transition counts at given lag Consider a discrete trajectory : math ` { x _ t } ` with : math : ` x _ t \ in { 1 , . . . , n }...
# count matrix if C is None : C = count_matrix_coo2_mult ( dtrajs , lag , sliding = True , sparse = True ) if callback is not None : if not callable ( callback ) : raise ValueError ( 'Provided callback is not callable' ) # split sequences splitseq = _split_sequences_multitraj ( dtrajs , lag ) # compute ...
async def list_blocks ( self , request ) : """Fetches list of blocks from validator , optionally filtered by id . Request : query : - head : The id of the block to use as the head of the chain - id : Comma separated list of block ids to include in results Response : data : JSON array of fully expanded B...
paging_controls = self . _get_paging_controls ( request ) validator_query = client_block_pb2 . ClientBlockListRequest ( head_id = self . _get_head_id ( request ) , block_ids = self . _get_filter_ids ( request ) , sorting = self . _get_sorting_message ( request , "block_num" ) , paging = self . _make_paging_message ( pa...
def fields_from_names ( fields , names = None ) : """Given a dictionary of fields and a list of names , will return a dictionary consisting of the fields specified by names . Names can be either the names of fields , or their aliases ."""
if names is None : return fields if isinstance ( names , string_types ) : names = [ names ] aliases_to_names = aliases_from_fields ( fields ) names_to_aliases = dict ( zip ( aliases_to_names . values ( ) , aliases_to_names . keys ( ) ) ) outfields = { } for name in names : try : outfields [ name ] =...
def summarize_crud_mutation ( method , model , isAsync = False ) : """This function provides the standard form for crud mutations ."""
# create the approrpriate action type action_type = get_crud_action ( method = method , model = model ) # the name of the mutation name = crud_mutation_name ( model = model , action = method ) # a mapping of methods to input factories input_map = { 'create' : create_mutation_inputs , 'update' : update_mutation_inputs ,...
def sparse_arrays ( self , value ) : """Validate and enable spare arrays ."""
if not isinstance ( value , bool ) : raise TypeError ( 'sparse_arrays attribute must be a logical type.' ) self . _sparse_arrays = value
def _findSwiplMacOSHome ( ) : """This function is guesing where SWI - Prolog is installed in MacOS via . app . : parameters : - ` swi _ ver ` ( str ) - Version of SWI - Prolog in ' [ 0-9 ] . [ 0-9 ] . [ 0-9 ] ' format : returns : A tuple of ( path to the swipl so , path to the resource file ) : returns ...
# Need more help with MacOS # That way works , but need more work names = [ 'libswipl.dylib' , 'libpl.dylib' ] path = os . environ . get ( 'SWI_HOME_DIR' ) if path is None : path = os . environ . get ( 'SWI_LIB_DIR' ) if path is None : path = os . environ . get ( 'PLBASE' ) if path is None : ...
def printrec ( recst ) : """Pretty - printing rtsp strings"""
try : recst = recst . decode ( 'UTF-8' ) except AttributeError : pass recs = [ x for x in recst . split ( '\r\n' ) if x ] for rec in recs : print ( rec ) print ( "\n" )
def get_compiled_serving ( self , kitchen , recipe_name , variation_name ) : """get the compiled version of arecipe with variables applied for a specific variation in a kitchen returns a dictionary ' / v2 / servings / compiled / get / < string : kitchenname > / < string : recipename > / < string : variationname...
rc = DKReturnCode ( ) if kitchen is None or isinstance ( kitchen , basestring ) is False : rc . set ( rc . DK_FAIL , 'issue with kitchen' ) return rc if recipe_name is None or isinstance ( recipe_name , basestring ) is False : rc . set ( rc . DK_FAIL , 'issue with recipe_name' ) return rc if variation_n...
def encode_max_segments_accepted ( arg ) : """Encode the maximum number of segments the device will accept , Section 20.1.2.4 , and if the device says it can only accept one segment it shouldn ' t say that it supports segmentation !"""
# unspecified if not arg : return 0 if arg > 64 : return 7 # the largest number not greater than the arg for i in range ( 6 , 0 , - 1 ) : if _max_segments_accepted_encoding [ i ] <= arg : return i raise ValueError ( "invalid max max segments accepted: %r" % ( arg , ) )
def run_validator ( pattern ) : """Validates a pattern against the STIX Pattern grammar . Error messages are returned in a list . The test passed if the returned list is empty ."""
start = '' if isinstance ( pattern , six . string_types ) : start = pattern [ : 2 ] pattern = InputStream ( pattern ) if not start : start = pattern . readline ( ) [ : 2 ] pattern . seek ( 0 ) parseErrListener = STIXPatternErrorListener ( ) lexer = STIXPatternLexer ( pattern ) # it always adds a console...
def generate_image_beacon ( event_collection , body , timestamp = None ) : """Generates an image beacon URL . : param event _ collection : the name of the collection to insert the event to : param body : dict , the body of the event to insert the event to : param timestamp : datetime , optional , the timest...
_initialize_client_from_environment ( ) return _client . generate_image_beacon ( event_collection , body , timestamp = timestamp )
def on_stepin_request ( self , py_db , request ) : ''': param StepInRequest request :'''
arguments = request . arguments # : : type arguments : StepInArguments thread_id = arguments . threadId if py_db . get_use_libraries_filter ( ) : step_cmd_id = CMD_STEP_INTO_MY_CODE else : step_cmd_id = CMD_STEP_INTO self . api . request_step ( py_db , thread_id , step_cmd_id ) response = pydevd_base_schema . b...
def portable_hash ( x ) : """This function returns consistent hash code for builtin types , especially for None and tuple with None . The algorithm is similar to that one used by CPython 2.7 > > > portable _ hash ( None ) > > > portable _ hash ( ( None , 1 ) ) & 0xfffff 219750521"""
if sys . version_info >= ( 3 , 2 , 3 ) and 'PYTHONHASHSEED' not in os . environ : raise Exception ( "Randomness of hash of string should be disabled via PYTHONHASHSEED" ) if x is None : return 0 if isinstance ( x , tuple ) : h = 0x345678 for i in x : h ^= portable_hash ( i ) h *= 1000003...
def _inject_lua_code ( self , lua_code ) : """Sends raw lua code and evaluate it wihtout any checking !"""
msg = ( ctypes . c_ubyte * len ( lua_code ) ) . from_buffer_copy ( lua_code . encode ( ) ) self . call_remote_api ( 'simxWriteStringStream' , 'my_lua_code' , msg )
def truncateGraph ( graph , root_nodes ) : """Create a set of all nodes containg the root _ nodes and all nodes reacheable from them"""
subgraph = Graph ( ) for node in root_nodes : subgraph = GraphUtils . joinGraphs ( subgraph , GraphUtils . getReacheableSubgraph ( graph , node ) ) return subgraph
def read_namespaced_replica_set_status ( self , name , namespace , ** kwargs ) : # noqa : E501 """read _ namespaced _ replica _ set _ status # noqa : E501 read status of the specified ReplicaSet # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , plea...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . read_namespaced_replica_set_status_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 else : ( data ) = self . read_namespaced_replica_set_status_with_http_info ( name , namespace , ** kwargs ) # noqa :...
def row_structural_typicality ( self , X_L_list , X_D_list , row_id ) : """Returns the typicality ( opposite of anomalousness ) of given row . : param row _ id : id of the target row : type row _ id : int : returns : float , the typicality , from 0 to 1"""
return su . row_structural_typicality ( X_L_list , X_D_list , row_id )
def _init_topics ( self ) : """Set up initial subscription of mysensors topics ."""
_LOGGER . info ( 'Setting up initial MQTT topic subscription' ) init_topics = [ '{}/+/+/0/+/+' . format ( self . _in_prefix ) , '{}/+/+/3/+/+' . format ( self . _in_prefix ) , ] self . _handle_subscription ( init_topics ) if not self . persistence : return topics = [ '{}/{}/{}/{}/+/+' . format ( self . _in_prefix ,...
def var ( inlist ) : """Returns the variance of the values in the passed list using N - 1 for the denominator ( i . e . , for estimating population variance ) . Usage : lvar ( inlist )"""
n = len ( inlist ) mn = mean ( inlist ) deviations = [ 0 ] * len ( inlist ) for i in range ( len ( inlist ) ) : deviations [ i ] = inlist [ i ] - mn return ss ( deviations ) / float ( n - 1 )
def load_into_repo ( self , repository : ParameterRepository = None , sheet_name : str = None ) : """Create a Repo from an excel file . : param repository : the repository to load into : param sheet _ name : : return :"""
repository . add_all ( self . load_parameters ( sheet_name ) )
def _random_color ( h_range = ( 0. , 1. ) , s_range = ( .5 , 1. ) , v_range = ( .5 , 1. ) , ) : """Generate a random RGB color ."""
h , s , v = uniform ( * h_range ) , uniform ( * s_range ) , uniform ( * v_range ) r , g , b = hsv_to_rgb ( np . array ( [ [ [ h , s , v ] ] ] ) ) . flat return r , g , b
def delete ( self ) : """Delete the NTP source entry from the node . Returns : True if the operation succeeds , otherwise False ."""
cmd = self . command_builder ( 'ntp source' , disable = True ) return self . configure ( cmd )
def cancelar_ultima_venda ( self , chave_cfe , dados_cancelamento ) : """Sobrepõe : meth : ` ~ satcfe . base . FuncoesSAT . cancelar _ ultima _ venda ` . : return : Uma resposta SAT especializada em ` ` CancelarUltimaVenda ` ` . : rtype : satcfe . resposta . cancelarultimavenda . RespostaCancelarUltimaVenda"""
retorno = super ( ClienteSATLocal , self ) . cancelar_ultima_venda ( chave_cfe , dados_cancelamento ) return RespostaCancelarUltimaVenda . analisar ( retorno )
def as_xml_index ( self , basename = "/tmp/sitemap.xml" ) : """Return a string of the index for a large list that is split . All we need to do is determine the number of component sitemaps will be is and generate their URIs based on a pattern . Q - should there be a flag to select generation of each component...
num_parts = self . requires_multifile ( ) if ( not num_parts ) : raise ListBaseIndexError ( "Request for sitemapindex for list with only %d entries when max_sitemap_entries is set to %s" % ( len ( self ) , str ( self . max_sitemap_entries ) ) ) index = ListBase ( ) index . sitemapindex = True index . capability_nam...
def load_outputs ( self ) : """Load output module ( s )"""
for output in sorted ( logdissect . output . __formats__ ) : self . output_modules [ output ] = __import__ ( 'logdissect.output.' + output , globals ( ) , locals ( ) , [ logdissect ] ) . OutputModule ( args = self . output_args )
def urlmap ( patterns ) : """Recursively build a map of ( group , name ) = > url patterns . Group is either the resolver namespace or app name for the url config . The urls are joined with any prefixes , and cleaned up of extraneous regex specific syntax ."""
for pattern in patterns : group = getattr ( pattern , 'namespace' , None ) if group is None : group = getattr ( pattern , 'app_name' , None ) path = '/' + get_pattern ( pattern ) . lstrip ( '^' ) . rstrip ( '$' ) if isinstance ( pattern , PATTERNS ) : yield ( group , pattern . name ) , p...
def animate_ellipsis ( self ) : """Animate dots at the end of the splash screen message ."""
ellipsis = self . ellipsis . pop ( 0 ) text = ' ' * len ( ellipsis ) + self . splash_text + ellipsis self . ellipsis . append ( ellipsis ) self . _show_message ( text )
def set_remote_config ( experiment_config , port , config_file_name ) : '''Call setClusterMetadata to pass trial'''
# set machine _ list request_data = dict ( ) request_data [ 'machine_list' ] = experiment_config [ 'machineList' ] if request_data [ 'machine_list' ] : for i in range ( len ( request_data [ 'machine_list' ] ) ) : if isinstance ( request_data [ 'machine_list' ] [ i ] . get ( 'gpuIndices' ) , int ) : ...
def zero_to_one ( table , option ) : """normalize from zero to one for row or table"""
if option == 'table' : m = min ( min ( table ) ) ma = max ( max ( table ) ) t = [ ] for row in table : t_row = [ ] if option != 'table' : m , ma = min ( row ) , max ( row ) for i in row : if ma == m : t_row . append ( 0 ) else : t_row . append ( ( i - ...
def find_minimum ( numbers ) : """This Python function finds and returns the smallest number in a given list . Examples : > > > find _ minimum ( [ 10 , 20 , 1 , 45 , 99 ] ) > > > find _ minimum ( [ 1 , 2 , 3 ] ) > > > find _ minimum ( [ 45 , 46 , 50 , 60 ] ) 45 Parameters : numbers ( list ) : a list o...
return min ( numbers )
def decode_aes256 ( key , iv_plus_encrypted ) : """Utility method to decode a payload consisting of the hexed IV + the hexed ciphertext using the given key . See above for more details . : param key : string , 64 hex characters long : param iv _ plus _ encrypted : string , a hexed IV + hexed ciphertext"""
# grab first AES . block _ size bytes ( aka 2 * AES . block _ size characters of hex ) - that ' s the IV iv_size = 2 * AES . block_size hexed_iv = iv_plus_encrypted [ : iv_size ] # grab everything else - that ' s the ciphertext ( aka encrypted message ) hexed_ciphertext = iv_plus_encrypted [ iv_size : ] # unhex the iv ...
def peak_load ( self ) : """Cumulative peak load capacity of generators of this grid Returns float Ad - hoc calculated or cached peak load capacity"""
if self . _peak_load is None : self . _peak_load = sum ( [ _ . peak_load . sum ( ) for _ in self . graph . nodes_by_attribute ( 'load' ) ] ) return self . _peak_load
def currentAbove ( requestContext , seriesList , n ) : """Takes one metric or a wildcard seriesList followed by an integer N . Out of all metrics passed , draws only the metrics whose value is above N at the end of the time period specified . Example : : & target = currentAbove ( server * . instance * . thr...
results = [ ] for series in seriesList : val = safeLast ( series ) if val is not None and val >= n : results . append ( series ) return results
def f_cash ( x , counts , bkg , model ) : """Wrapper for cash statistics , that defines the model function . Parameters x : float Model amplitude . counts : ` ~ numpy . ndarray ` Count map slice , where model is defined . bkg : ` ~ numpy . ndarray ` Background map slice , where model is defined . mo...
return 2.0 * poisson_log_like ( counts , bkg + x * model )
def _prepare_data_dir ( self , data ) : """Prepare destination directory where the data will live . : param data : The : class : ` ~ resolwe . flow . models . Data ` object for which to prepare the private execution directory . : return : The prepared data directory path . : rtype : str"""
logger . debug ( __ ( "Preparing data directory for Data with id {}." , data . id ) ) with transaction . atomic ( ) : # Create a temporary random location and then override it with data # location id since object has to be created first . # TODO Find a better solution , e . g . defer the database constraint . tempo...
def key_release_event ( self , widget , event ) : """Called when a key is released after being pressed . Adjust method signature as appropriate for callback ."""
# get keyname or keycode and translate to ginga standard # keyname = # keycode = keyname = '' # self . transkey ( keyname , keycode ) self . logger . debug ( "key release event, key=%s" % ( keyname ) ) return self . make_ui_callback ( 'key-release' , keyname )
def _hyphenate ( input , add_prefix = False ) : """Change underscores to hyphens so that object attributes can be easily tranlated to GPG option names . : param str input : The attribute to hyphenate . : param bool add _ prefix : If True , add leading hyphens to the input . : rtype : str : return : The ` ...
ret = '--' if add_prefix else '' ret += input . replace ( '_' , '-' ) return ret
def portgroups_configured ( name , dvs , portgroups ) : '''Configures portgroups on a DVS . Creates / updates / removes portgroups in a provided DVS dvs Name of the DVS portgroups Portgroup dict representations ( see module sysdocs )'''
datacenter = _get_datacenter_name ( ) log . info ( 'Running state %s on DVS \'%s\', datacenter \'%s\'' , name , dvs , datacenter ) changes_required = False ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : None } comments = [ ] changes = { } changes_required = False try : # TODO portroups validati...
def compute_regex_CDR3_template_pgen ( self , regex_seq , V_usage_mask_in = None , J_usage_mask_in = None , print_warnings = True , raise_overload_warning = True ) : """Compute Pgen for all seqs consistent with regular expression regex _ seq . Computes Pgen for a ( limited vocabulary ) regular expression of CDR3 ...
V_usage_mask , J_usage_mask = self . format_usage_masks ( V_usage_mask_in , J_usage_mask_in , print_warnings ) CDR3_seqs = self . list_seqs_from_regex ( regex_seq , print_warnings , raise_overload_warning ) pgen = 0 for CDR3_seq in CDR3_seqs : if len ( CDR3_seq ) == 0 : continue pgen += self . compute_C...
def _exec_template ( callable_ , context , args = None , kwargs = None ) : """execute a rendering callable given the callable , a Context , and optional explicit arguments the contextual Template will be located if it exists , and the error handling options specified on that Template will be interpreted her...
template = context . _with_template if template is not None and ( template . format_exceptions or template . error_handler ) : try : callable_ ( context , * args , ** kwargs ) except Exception : _render_error ( template , context , compat . exception_as ( ) ) except : e = sys . exc_i...
def rename_mapobject_type ( self , name , new_name ) : '''Renames a mapobject type . Parameters name : str name of the mapobject type that should be renamed new _ name : str name that should be given to the mapobject type See also : func : ` tmserver . api . mapobject . update _ mapobject _ type ` :...
logger . info ( 'rename mapobject type "%s" of experiment "%s"' , name , self . experiment_name ) content = { 'name' : new_name } mapobject_type_id = self . _get_mapobject_type_id ( name ) url = self . _build_api_url ( '/experiments/{experiment_id}/mapobject_types/{mapobject_type_id}' . format ( experiment_id = self . ...
def next ( self ) : """Get next data batch from iterator . Returns DataBatch The data of next batch . Raises StopIteration If the end of the data is reached ."""
if self . iter_next ( ) : return DataBatch ( data = self . getdata ( ) , label = self . getlabel ( ) , pad = self . getpad ( ) , index = self . getindex ( ) ) else : raise StopIteration
def super_glob ( pattern ) : 'glob that understands * * / for all sub - directories recursively .'
pieces = pattern . split ( '/' ) if '**' in pieces : prefix = '/' . join ( pieces [ : pieces . index ( '**' ) ] ) postfix = '/' . join ( pieces [ pieces . index ( '**' ) + 1 : ] ) roots = [ dirname for dirname , dirnames , filenames in os . walk ( prefix ) ] patterns = [ root + '/' + postfix for root in...
def bind ( self , name , filterset ) : """attach filter to filterset gives a name to use to extract arguments from querydict"""
if self . name is not None : name = self . name self . field . bind ( name , self )