signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def FDMT ( data , f_min , f_max , maxDT , dataType ) : """This function implements the FDMT algorithm . Input : Input visibility array ( nints , nbl , nchan , npol ) f _ min , f _ max are the base - band begin and end frequencies . The frequencies should be entered in MHz maxDT - the maximal delay ( in time...
nint , nbl , nchan , npol = data . shape niters = int ( np . log2 ( nchan ) ) assert nchan in 2 ** np . arange ( 30 ) and nint in 2 ** np . arange ( 30 ) , "Input dimensions must be a power of 2" logger . info ( 'Input data dimensions: {0}' . format ( data . shape ) ) data = FDMT_initialization ( data , f_min , f_max ,...
def _get_dvs_infrastructure_traffic_resources ( dvs_name , dvs_infra_traffic_ress ) : '''Returns a list of dict representations of the DVS infrastructure traffic resource dvs _ name The name of the DVS dvs _ infra _ traffic _ ress The DVS infrastructure traffic resources'''
log . trace ( 'Building the dicts of the DVS \'%s\' infrastructure ' 'traffic resources' , dvs_name ) res_dicts = [ ] for res in dvs_infra_traffic_ress : res_dict = { 'key' : res . key , 'limit' : res . allocationInfo . limit , 'reservation' : res . allocationInfo . reservation } if res . allocationInfo . share...
def arch_to_personality ( arch ) : """Determine the process personality corresponding to the architecture"""
if isinstance ( arch , bytes ) : arch = unicode ( arch ) return _lxc . arch_to_personality ( arch )
def _parseAtNamespace ( self , src ) : """namespace : @ namespace S * [ IDENT S * ] ? [ STRING | URI ] S * ' ; ' S *"""
src = self . _parseSCDOCDC ( src ) while isAtRuleIdent ( src , 'namespace' ) : ctxsrc = src src = stripAtRuleIdent ( src ) namespace , src = self . _getStringOrURI ( src ) if namespace is None : nsPrefix , src = self . _getIdent ( src ) if nsPrefix is None : raise self . Pars...
def service_desks ( self ) : """Get a list of ServiceDesk Resources from the server visible to the current authenticated user . : rtype : List [ ServiceDesk ]"""
url = self . _options [ 'server' ] + '/rest/servicedeskapi/servicedesk' headers = { 'X-ExperimentalApi' : 'opt-in' } r_json = json_loads ( self . _session . get ( url , headers = headers ) ) projects = [ ServiceDesk ( self . _options , self . _session , raw_project_json ) for raw_project_json in r_json [ 'values' ] ] r...
def _setable_set_ ( name , self , func ) : "Used to set the attribute a single time using the given function ."
setattr ( self . _attr_data_ , name , func ( ) ) if hasattr ( self . _attr_func_ , name ) : delattr ( self . _attr_func_ , name ) setattr ( type ( self ) , name , property ( functools . partial ( self . _simple_get_ , name ) ) )
def generate ( cls ) : """Generates a random : class : ` ~ SigningKey ` object . : rtype : : class : ` ~ SigningKey `"""
return cls ( libnacl . randombytes ( libnacl . crypto_sign_SEEDBYTES ) , encoder = encoding . RawEncoder , )
def rule_metric_names ( self ) : """Returns the rule metric names of the association rules . Only if implements AssociationRulesProducer . : return : the metric names : rtype : list"""
if not self . check_type ( self . jobject , "weka.associations.AssociationRulesProducer" ) : return None return string_array_to_list ( javabridge . call ( self . jobject , "getRuleMetricNames" , "()[Ljava/lang/String;" ) )
def plotF0 ( fromTuple , toTuple , mergeTupleList , fnFullPath ) : '''Plots the original data in a graph above the plot of the dtw ' ed data'''
_matplotlibCheck ( ) plt . hold ( True ) fig , ( ax0 ) = plt . subplots ( nrows = 1 ) # Old data plot1 = ax0 . plot ( fromTuple [ 0 ] , fromTuple [ 1 ] , color = 'red' , linewidth = 2 , label = "From" ) plot2 = ax0 . plot ( toTuple [ 0 ] , toTuple [ 1 ] , color = 'blue' , linewidth = 2 , label = "To" ) ax0 . set_title ...
def next ( self ) : """Returns the next input from this input reader , a record . Returns : The next input from this input reader in the form of a record read from an LevelDB file . Raises : StopIteration : The ordered set records has been exhausted ."""
while True : if not hasattr ( self , "_cur_handle" ) or self . _cur_handle is None : # If there are no more files , StopIteration is raised here self . _cur_handle = super ( _GoogleCloudStorageRecordInputReader , self ) . next ( ) if not hasattr ( self , "_record_reader" ) or self . _record_reader is No...
def change_engine_password ( self , password ) : """Change Engine password for engines on allowed list . : param str password : password for engine level : raises ModificationFailed : failed setting password on engine : return : None"""
self . make_request ( ModificationFailed , method = 'update' , resource = 'change_engine_password' , params = { 'password' : password } )
def resolve ( self , cfg , addr , func_addr , block , jumpkind ) : """Resolves jump tables . : param cfg : A CFG instance . : param int addr : IRSB address . : param int func _ addr : The function address . : param pyvex . IRSB block : The IRSB . : return : A bool indicating whether the indirect jump is r...
project = self . project # short - hand self . _max_targets = cfg . _indirect_jump_target_limit # Perform a backward slicing from the jump target b = Blade ( cfg . graph , addr , - 1 , cfg = cfg , project = project , ignore_sp = False , ignore_bp = False , max_level = 3 , base_state = self . base_state ) stmt_loc = ( a...
def segment_intersection1 ( start0 , end0 , start1 , end1 , s ) : """Image for : func : ` . segment _ intersection ` docstring ."""
if NO_IMAGES : return line0 = bezier . Curve . from_nodes ( stack1d ( start0 , end0 ) ) line1 = bezier . Curve . from_nodes ( stack1d ( start1 , end1 ) ) ax = line0 . plot ( 2 ) line1 . plot ( 256 , ax = ax ) ( x_val , ) , ( y_val , ) = line0 . evaluate ( s ) ax . plot ( [ x_val ] , [ y_val ] , color = "black" , ma...
def normalized ( self ) : """Returns the unit quaternion corresponding to the same rotation as this one ."""
magnitude = self . magnitude ( ) return Quaternion ( self . x / magnitude , self . y / magnitude , self . z / magnitude , self . w / magnitude )
def u2ver ( self ) : """Get the major / minor version of the urllib2 lib . @ return : The urllib2 version . @ rtype : float"""
try : part = u2 . __version__ . split ( '.' , 1 ) n = float ( '.' . join ( part ) ) return n except Exception as e : log . exception ( e ) return 0
def remove_trailing_string ( content , trailing ) : """Strip trailing component ` trailing ` from ` content ` if it exists . Used when generating names from view classes ."""
if content . endswith ( trailing ) and content != trailing : return content [ : - len ( trailing ) ] return content
def load_log ( args ) : """Load a ` logging . Logger ` object . Arguments args : ` argparse . Namespace ` object Namespace containing required settings : { ` args . debug ` , ` args . verbose ` , and ` args . log _ filename ` } . Returns log : ` logging . Logger ` object"""
from astrocats . catalog . utils import logger # Determine verbosity ( ' None ' means use default ) log_stream_level = None if args . debug : log_stream_level = logger . DEBUG elif args . verbose : log_stream_level = logger . INFO # Create log log = logger . get_logger ( stream_level = log_stream_level , tofile...
def _GetDirectory ( self ) : """Retrieves a directory . Returns : TARDirectory : a directory or None if not available ."""
if self . entry_type != definitions . FILE_ENTRY_TYPE_DIRECTORY : return None return TARDirectory ( self . _file_system , self . path_spec )
def get_tc_arguments ( parser ) : """Append test case arguments to parser . : param parser : ArgumentParser : return : ArgumentParser"""
group2 = parser . add_argument_group ( 'Test case arguments' ) group2 . add_argument ( '--log' , default = os . path . abspath ( "./log" ) , help = 'Store logs to specific path. Filename will be ' '<path>/<testcase>_D<dutNumber>.log' ) group2 . add_argument ( '-s' , '--silent' , action = 'store_true' , dest = 'silent' ...
def main ( pos , bobj = None ) : """: param pos : A dictionary with { ' latitude ' : 8.12 , ' longitude ' : 42.6} : param bobj : An object which has a ' get ' method and returns a dictionary ."""
city , distance = get_city ( pos , bobj ) city = get_city_from_file ( city [ 'linenr' ] ) print ( "The city '%s' is about %0.2fkm away from your location %s" % ( city [ 'asciiname' ] , distance / 1000.0 , str ( pos ) ) ) for key , value in sorted ( city . items ( ) ) : print ( "%s: %s" % ( key , value ) )
def get_size ( self ) : """see doc in Term class"""
self . curses . setupterm ( ) return self . curses . tigetnum ( 'cols' ) , self . curses . tigetnum ( 'lines' )
def get_feature_state_for_scope ( self , feature_id , user_scope , scope_name , scope_value ) : """GetFeatureStateForScope . [ Preview API ] Get the state of the specified feature for the given named scope : param str feature _ id : Contribution id of the feature : param str user _ scope : User - Scope at whi...
route_values = { } if feature_id is not None : route_values [ 'featureId' ] = self . _serialize . url ( 'feature_id' , feature_id , 'str' ) if user_scope is not None : route_values [ 'userScope' ] = self . _serialize . url ( 'user_scope' , user_scope , 'str' ) if scope_name is not None : route_values [ 'sco...
def ned ( simulated_array , observed_array , replace_nan = None , replace_inf = None , remove_neg = False , remove_zero = False ) : """Compute the normalized Euclidian distance between the simulated and observed data in vector space . . . image : : / pictures / NED . png * * Range * * 0 ≤ NED < inf , smaller ...
# Checking and cleaning the data simulated_array , observed_array = treat_values ( simulated_array , observed_array , replace_nan = replace_nan , replace_inf = replace_inf , remove_neg = remove_neg , remove_zero = remove_zero ) a = observed_array / np . mean ( observed_array ) b = simulated_array / np . mean ( simulate...
def append_variables ( self , samples_like , sort_labels = True ) : """Create a new sampleset with the given variables with values added . Not defined for empty sample sets . Note that when ` sample _ like ` is a : obj : ` . SampleSet ` , the data vectors and info are ignored . Args : samples _ like : Sam...
samples , labels = as_samples ( samples_like ) num_samples = len ( self ) # we don ' t handle multiple values if samples . shape [ 0 ] == num_samples : # we don ' t need to do anything , it ' s already the correct shape pass elif samples . shape [ 0 ] == 1 and num_samples : samples = np . repeat ( samples , num...
def swd_read32 ( self , offset ) : """Gets a unit of ` ` 32 ` ` bits from the input buffer . Args : self ( JLink ) : the ` ` JLink ` ` instance offset ( int ) : the offset ( in bits ) from which to start reading Returns : The integer read from the input buffer ."""
value = self . _dll . JLINK_SWD_GetU32 ( offset ) return ctypes . c_uint32 ( value ) . value
def _update_project ( self , request , data ) : """Update project info"""
domain_id = identity . get_domain_id_for_operation ( request ) try : project_id = data [ 'project_id' ] # add extra information if keystone . VERSIONS . active >= 3 : EXTRA_INFO = getattr ( settings , 'PROJECT_TABLE_EXTRA_INFO' , { } ) kwargs = dict ( ( key , data . get ( key ) ) for key in ...
def post ( self ) : """API endpoint to push transactions to the Federation . Return : A ` ` dict ` ` containing the data about the transaction ."""
parser = reqparse . RequestParser ( ) parser . add_argument ( 'mode' , type = parameters . valid_mode , default = 'broadcast_tx_async' ) args = parser . parse_args ( ) mode = str ( args [ 'mode' ] ) pool = current_app . config [ 'bigchain_pool' ] # ` force ` will try to format the body of the POST request even if the #...
def is_uniform ( keys , axis = semantics . axis_default ) : """returns true if all keys have equal multiplicity"""
index = as_index ( keys , axis ) return index . uniform
def main ( ) : """Provide the program ' s entry point when directly executed ."""
if len ( sys . argv ) < 2 : print ( "Usage: {} SCOPE..." . format ( sys . argv [ 0 ] ) ) return 1 authenticator = prawcore . TrustedAuthenticator ( prawcore . Requestor ( "prawcore_refresh_token_example" ) , os . environ [ "PRAWCORE_CLIENT_ID" ] , os . environ [ "PRAWCORE_CLIENT_SECRET" ] , os . environ [ "PRAW...
def calc_fwhm_moffat ( self , arr1d , medv = None , moffat_fn = None ) : """FWHM calculation on a 1D array by using least square fitting of a Moffat function on the data . arr1d is a 1D array cut in either X or Y direction on the object ."""
if moffat_fn is None : moffat_fn = self . moffat N = len ( arr1d ) X = np . array ( list ( range ( N ) ) ) Y = arr1d # Fitting works more reliably if we do the following # a . subtract sky background if medv is None : medv = get_median ( Y ) Y = Y - medv maxv = Y . max ( ) # b . clamp to 0 . . max ( of the sky ...
def _close_open_date_ranges ( self , record ) : """If a date range is missing the start or end date , close it by copying the date from the existing value ."""
date_ranges = ( ( 'beginDate' , 'endDate' ) , ) for begin , end in date_ranges : if begin in record and end in record : return elif begin in record : record [ end ] = record [ begin ] elif end in record : record [ begin ] = record [ end ]
def file_md5 ( file_name ) : '''Generate an MD5 hash of the specified file . @ file _ name - The file to hash . Returns an MD5 hex digest string .'''
md5 = hashlib . md5 ( ) with open ( file_name , 'rb' ) as f : for chunk in iter ( lambda : f . read ( 128 * md5 . block_size ) , b'' ) : md5 . update ( chunk ) return md5 . hexdigest ( )
async def AddPendingResources ( self , addcharmwithauthorization , entity , resources ) : '''addcharmwithauthorization : AddCharmWithAuthorization entity : Entity resources : typing . Sequence [ ~ CharmResource ] Returns - > typing . Union [ _ ForwardRef ( ' ErrorResult ' ) , typing . Sequence [ str ] ]'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'Resources' , request = 'AddPendingResources' , version = 1 , params = _params ) _params [ 'AddCharmWithAuthorization' ] = addcharmwithauthorization _params [ 'Entity' ] = entity _params [ 'Resources' ] = resources reply = await self . rpc ( msg ) retu...
def check ( self , item_id ) : """Check if an analysis is complete : type item _ id : int : param item _ id : task _ id to check . : rtype : bool : return : Boolean indicating if a report is done or not ."""
response = self . _request ( "tasks/view/{id}" . format ( id = item_id ) ) if response . status_code == 404 : # probably an unknown task id return False try : content = json . loads ( response . content . decode ( 'utf-8' ) ) status = content [ 'task' ] [ "status" ] if status == 'completed' or status ==...
def find_atoms_within_distance ( atoms , cutoff_distance , point ) : """Returns atoms within the distance from the point . Parameters atoms : [ ampal . atom ] A list of ` ampal . atoms ` . cutoff _ distance : float Maximum distance from point . point : ( float , float , float ) Reference point , 3D co...
return [ x for x in atoms if distance ( x , point ) <= cutoff_distance ]
def pp_event ( seq ) : """Returns pretty representation of an Event or keypress"""
if isinstance ( seq , Event ) : return str ( seq ) # Get the original sequence back if seq is a pretty name already rev_curses = dict ( ( v , k ) for k , v in CURSES_NAMES . items ( ) ) rev_curtsies = dict ( ( v , k ) for k , v in CURTSIES_NAMES . items ( ) ) if seq in rev_curses : seq = rev_curses [ seq ] elif...
def optimize ( population , toolbox , ngen , archive = None , stats = None , verbose = False , history = None ) : """Optimize a population of individuals . : param population : : param toolbox : : param mut _ prob : : param ngen : : param archive : : param stats : : param verbose : : param history :...
start = time . time ( ) if history is not None : history . update ( population ) logbook = tools . Logbook ( ) logbook . header = [ 'gen' , 'nevals' , 'cpu_time' ] + ( stats . fields if stats else [ ] ) render_fitness ( population , toolbox , history ) record_information ( population , stats , start , archive , log...
def get ( self , value ) : """Returns the VRF configuration as a resource dict . Args : value ( string ) : The vrf name to retrieve from the running configuration . Returns : A Python dict object containing the VRF attributes as key / value pairs ."""
config = self . get_block ( 'vrf definition %s' % value ) if not config : return None response = dict ( vrf_name = value ) response . update ( self . _parse_rd ( config ) ) response . update ( self . _parse_description ( config ) ) config = self . get_block ( 'no ip routing vrf %s' % value ) if config : respons...
def modsplit ( s ) : """Split importable"""
if ':' in s : c = s . split ( ':' ) if len ( c ) != 2 : raise ValueError ( "Syntax error: {s}" ) return c [ 0 ] , c [ 1 ] else : c = s . split ( '.' ) if len ( c ) < 2 : raise ValueError ( "Syntax error: {s}" ) return '.' . join ( c [ : - 1 ] ) , c [ - 1 ]
def updateTitle ( self ) : """Updates the Title of this widget according to how many parameters are currently in the model"""
title = 'Auto Parameters ({})' . format ( self . paramList . model ( ) . rowCount ( ) ) self . titleChange . emit ( title ) self . setWindowTitle ( title )
def _plot_methods ( self ) : """A dictionary with mappings from plot method to their summary"""
ret = { } for attr in filter ( lambda s : not s . startswith ( "_" ) , dir ( self ) ) : obj = getattr ( self , attr ) if isinstance ( obj , PlotterInterface ) : ret [ attr ] = obj . _summary return ret
def get_process_by_its_id ( self , process_type_id , expand = None ) : """GetProcessByItsId . [ Preview API ] Get a single process of a specified ID . : param str process _ type _ id : : param str expand : : rtype : : class : ` < ProcessInfo > < azure . devops . v5_0 . work _ item _ tracking _ process . mod...
route_values = { } if process_type_id is not None : route_values [ 'processTypeId' ] = self . _serialize . url ( 'process_type_id' , process_type_id , 'str' ) query_parameters = { } if expand is not None : query_parameters [ '$expand' ] = self . _serialize . query ( 'expand' , expand , 'str' ) response = self ....
def _get_relationship_data ( self ) : """Get useful data for relationship management"""
relationship_field = request . path . split ( '/' ) [ - 1 ] . replace ( '-' , '_' ) if relationship_field not in get_relationships ( self . schema ) : raise RelationNotFound ( "{} has no attribute {}" . format ( self . schema . __name__ , relationship_field ) ) related_type_ = self . schema . _declared_fields [ rel...
def camelCaseToDashName ( camelCase ) : '''camelCaseToDashName - Convert a camel case name to a dash - name ( like paddingTop to padding - top ) @ param camelCase < str > - A camel - case string @ return < str > - A dash - name'''
camelCaseList = list ( camelCase ) ret = [ ] for ch in camelCaseList : if ch . isupper ( ) : ret . append ( '-' ) ret . append ( ch . lower ( ) ) else : ret . append ( ch ) return '' . join ( ret )
def generic_method_not_allowed ( * args ) : """Creates a Lambda Service Generic MethodNotAllowed Response Parameters args list List of arguments Flask passes to the method Returns Flask . Response A response object representing the GenericMethodNotAllowed Error"""
exception_tuple = LambdaErrorResponses . MethodNotAllowedException return BaseLocalService . service_response ( LambdaErrorResponses . _construct_error_response_body ( LambdaErrorResponses . LOCAL_SERVICE_ERROR , "MethodNotAllowedException" ) , LambdaErrorResponses . _construct_headers ( exception_tuple [ 0 ] ) , excep...
def listobs ( vis ) : """Textually describe the contents of a measurement set . vis ( str ) The path to the dataset . Returns A generator of lines of human - readable output Errors can only be detected by looking at the output . Example : : from pwkit . environments . casa import tasks for line in tas...
def inner_list ( sink ) : try : ms = util . tools . ms ( ) ms . open ( vis ) ms . summary ( verbose = True ) ms . close ( ) except Exception as e : sink . post ( b'listobs failed: %s' % e , priority = b'SEVERE' ) for line in util . forkandlog ( inner_list ) : info = l...
def check ( mod ) : """Check the parsed ASDL tree for correctness . Return True if success . For failure , the errors are printed out and False is returned ."""
v = Check ( ) v . visit ( mod ) for t in v . types : if t not in mod . types and not t in builtin_types : v . errors += 1 uses = ", " . join ( v . types [ t ] ) print ( 'Undefined type {}, used in {}' . format ( t , uses ) ) return not v . errors
def _copy ( self , other , copy_func ) : """Copies the contents of another ParsableOctetString object to itself : param object : Another instance of the same class : param copy _ func : An reference of copy . copy ( ) or copy . deepcopy ( ) to use when copying lists , dicts and objects"""
super ( ParsableOctetString , self ) . _copy ( other , copy_func ) self . _bytes = other . _bytes self . _parsed = copy_func ( other . _parsed )
def _CheckIsDevice ( self , file_entry ) : """Checks the is _ device find specification . Args : file _ entry ( FileEntry ) : file entry . Returns : bool : True if the file entry matches the find specification , False if not ."""
if definitions . FILE_ENTRY_TYPE_DEVICE not in self . _file_entry_types : return False return file_entry . IsDevice ( )
def execCommand ( g , command , timeout = 10 ) : """Executes a command by sending it to the rack server Arguments : g : hcam _ drivers . globals . Container the Container object of application globals command : ( string ) the command ( see below ) Possible commands are : start : starts a run stop : ...
if not g . cpars [ 'hcam_server_on' ] : g . clog . warn ( 'execCommand: servers are not active' ) return False try : url = g . cpars [ 'hipercam_server' ] + command g . clog . info ( 'execCommand, command = "' + command + '"' ) response = urllib . request . urlopen ( url , timeout = timeout ) rs...
def raise_api_exceptions ( function , * args , ** kwargs ) : """Raise client side exception ( s ) when present in the API response . Returned data is not modified ."""
try : return_value = function ( * args , ** kwargs ) except errors . HTTPException as exc : if exc . _raw . status_code != 400 : # pylint : disable = W0212 raise # Unhandled HTTPErrors try : # Attempt to convert v1 errors into older format ( for now ) data = exc . _raw . json ( ) ...
def subject_sequence_retriever ( fasta_handle , b6_handle , e_value , * args , ** kwargs ) : """Returns FASTA entries for subject sequences from BLAST hits Stores B6 / M8 entries with E - Values below the e _ value cutoff . Then iterates through the FASTA file and if an entry matches the subject of an B6 / M8 ...
filtered_b6 = defaultdict ( list ) for entry in b6_evalue_filter ( b6_handle , e_value , * args , ** kwargs ) : filtered_b6 [ entry . subject ] . append ( ( entry . subject_start , entry . subject_end , entry . _evalue_str ) ) for fastaEntry in fasta_iter ( fasta_handle ) : if fastaEntry . id in filtered_b6 : ...
def _download ( self , dstFile ) : """Download this resource from its URL to the given file object . : type dstFile : io . BytesIO | io . FileIO"""
for attempt in retry ( predicate = lambda e : isinstance ( e , HTTPError ) and e . code == 400 ) : with attempt : with closing ( urlopen ( self . url ) ) as content : buf = content . read ( ) contentHash = hashlib . md5 ( buf ) assert contentHash . hexdigest ( ) == self . contentHash dstFile . w...
def get_preparation_cmd ( user , permissions , path ) : """Generates the command lines for adjusting a volume ' s ownership and permission flags . Returns an empty list if there is nothing to adjust . : param user : User to set ownership for on the path via ` ` chown ` ` . : type user : unicode | str | int | ...
r_user = resolve_value ( user ) r_permissions = resolve_value ( permissions ) if user : yield chown ( r_user , path ) if permissions : yield chmod ( r_permissions , path )
def validate ( self , model = None , context = None ) : """Validate model and return validation result object : param model : object or dict : param context : object , dict or None : return : shiftschema . result . Result"""
# inject with settings result = Result ( translator = self . translator , locale = self . locale ) # validate state state_result = self . validate_state ( model , context = context ) result . merge ( state_result ) # validate simple properties props_result = self . validate_properties ( model , context = context ) resu...
def _final_frame_length ( header , final_frame_bytes ) : """Calculates the length of a final ciphertext frame , given a complete header and the number of bytes of ciphertext in the final frame . : param header : Complete message header object : type header : aws _ encryption _ sdk . structures . MessageHeader...
final_frame_length = 4 # Sequence Number End final_frame_length += 4 # Sequence Number final_frame_length += header . algorithm . iv_len # IV final_frame_length += 4 # Encrypted Content Length final_frame_length += final_frame_bytes # Encrypted Content final_frame_length += header . algorithm . auth_len # Authenticatio...
def sample ( self , initial_pos , num_samples , stepsize = None , return_type = 'dataframe' ) : """Method to return samples using No U Turn Sampler Parameters initial _ pos : A 1d array like object Vector representing values of parameter position , the starting state in markov chain . num _ samples : int ...
initial_pos = _check_1d_array_object ( initial_pos , 'initial_pos' ) _check_length_equal ( initial_pos , self . model . variables , 'initial_pos' , 'model.variables' ) if stepsize is None : stepsize = self . _find_reasonable_stepsize ( initial_pos ) types = [ ( var_name , 'float' ) for var_name in self . model . va...
def get_sqla_query ( # sqla self , groupby , metrics , granularity , from_dttm , to_dttm , filter = None , # noqa is_timeseries = True , timeseries_limit = 15 , timeseries_limit_metric = None , row_limit = None , inner_from_dttm = None , inner_to_dttm = None , orderby = None , extras = None , columns = None , order_des...
template_kwargs = { 'from_dttm' : from_dttm , 'groupby' : groupby , 'metrics' : metrics , 'row_limit' : row_limit , 'to_dttm' : to_dttm , 'filter' : filter , 'columns' : { col . column_name : col for col in self . columns } , } template_kwargs . update ( self . template_params_dict ) template_processor = self . get_tem...
def __get_function_by_pattern ( self , pattern ) : """Return first function whose name * contains * the string ` pattern ` . : param func : partial function name ( ex . key _ pair ) : return : list function that goes with it ( ex . list _ key _ pairs )"""
function_names = [ name for name in dir ( self . driver ) if pattern in name ] if function_names : name = function_names [ 0 ] if len ( function_names ) > 1 : log . warn ( "Several functions match pattern `%s`: %r -- using first one!" , pattern , function_names ) return getattr ( self . driver , nam...
def do_publish ( broker , cmd , f , when , res , meta , * args , ** kwargs ) : """Implement the publish so it can be called outside the decorator"""
publish_command = functools . partial ( broker . publish , topic = command_types . COMMAND ) call_args = _get_args ( f , args , kwargs ) if when == 'before' : broker . logger . info ( "{}: {}" . format ( f . __qualname__ , { k : v for k , v in call_args . items ( ) if str ( k ) != 'self' } ) ) command_args = dict (...
def decode_union ( self , data_type , obj ) : """The data _ type argument must be a Union . See json _ compat _ obj _ decode ( ) for argument descriptions ."""
val = None if isinstance ( obj , six . string_types ) : # Handles the shorthand format where the union is serialized as only # the string of the tag . tag = obj if data_type . definition . _is_tag_present ( tag , self . caller_permissions ) : val_data_type = data_type . definition . _get_val_data_type (...
def enrich_json_objects_by_object_type ( request , value ) : """Take the given value and start enrichment by object _ type . The va Args : request ( django . http . request . HttpRequest ) : request which is currently processed value ( dict | list | django . db . models . Model ) : in case of django . db . ...
time_start_globally = time ( ) if isinstance ( value , list ) : json = [ x . to_json ( ) if hasattr ( x , "to_json" ) else x for x in value ] else : if isinstance ( value , dict ) : json = value else : json = value . to_json ( ) objects , nested = _collect_json_objects ( json , by = 'object_...
def _set_ciphers ( self ) : """Sets up the allowed ciphers . By default this matches the set in util . ssl _ . DEFAULT _ CIPHERS , at least as supported by macOS . This is done custom and doesn ' t allow changing at this time , mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare ...
ciphers = ( Security . SSLCipherSuite * len ( CIPHER_SUITES ) ) ( * CIPHER_SUITES ) result = Security . SSLSetEnabledCiphers ( self . context , ciphers , len ( CIPHER_SUITES ) ) _assert_no_error ( result )
def generate ( engine , database , models , ** kwargs ) : '''Generate the migrations by introspecting the db'''
validate_args ( engine , database , models ) generator = Generator ( engine , database , models ) generator . run ( )
def binary_search ( a , k ) : """Do a binary search in an array of objects ordered by ' . key ' returns the largest index for which : a [ i ] . key < = k like c + + : a . upperbound ( k ) - -"""
first , last = 0 , len ( a ) while first < last : mid = ( first + last ) >> 1 if k < a [ mid ] . key : last = mid else : first = mid + 1 return first - 1
def apply_upgrade ( self , upgrade ) : """Apply a upgrade and register that it was successful . A upgrade may throw a RuntimeError , if an unrecoverable error happens . : param upgrade : A single upgrade"""
self . _setup_log_prefix ( plugin_id = upgrade . name ) try : # Nested due to Python 2.4 try : upgrade . do_upgrade ( ) self . register_success ( upgrade ) except RuntimeError as e : msg = [ "Upgrade error(s):" ] for m in e . args : msg . append ( " (-) %s" % m ) ...
def is_function_or_method ( obj ) : """Check if an object is a function or method . Args : obj : The Python object in question . Returns : True if the object is an function or method ."""
return inspect . isfunction ( obj ) or inspect . ismethod ( obj ) or is_cython ( obj )
def list_vms ( self , allow_clone = False ) : """Gets VirtualBox VM list ."""
vbox_vms = [ ] result = yield from self . execute ( "list" , [ "vms" ] ) for line in result : if len ( line ) == 0 or line [ 0 ] != '"' or line [ - 1 : ] != "}" : continue # Broken output ( perhaps a carriage return in VM name ) vmname , _ = line . rsplit ( ' ' , 1 ) vmname = vmname . strip ...
def get_data_disk_size ( vm_ , swap , linode_id ) : '''Return the size of of the data disk in MB . . versionadded : : 2016.3.0'''
disk_size = get_linode ( kwargs = { 'linode_id' : linode_id } ) [ 'TOTALHD' ] root_disk_size = config . get_cloud_config_value ( 'disk_size' , vm_ , __opts__ , default = disk_size - swap ) return disk_size - root_disk_size - swap
def create_manifest_from_s3_files ( self ) : """To create a manifest db for the current : return :"""
for k in self . s3 . list_objects ( Bucket = self . sitename ) [ 'Contents' ] : key = k [ "Key" ] files = [ ] if key not in [ self . manifest_file ] : files . append ( key ) self . _set_manifest_data ( files )
def scroll_from_element ( self , on_element , xoffset , yoffset ) : """Touch and scroll starting at on _ element , moving by xoffset and yoffset . : Args : - on _ element : The element where scroll starts . - xoffset : X offset to scroll to . - yoffset : Y offset to scroll to ."""
self . _actions . append ( lambda : self . _driver . execute ( Command . TOUCH_SCROLL , { 'element' : on_element . id , 'xoffset' : int ( xoffset ) , 'yoffset' : int ( yoffset ) } ) ) return self
def distances_indices_sorted ( self , points , sign = False ) : """Computes the distances from the plane to each of the points . Positive distances are on the side of the normal of the plane while negative distances are on the other side . Indices sorting the points from closest to furthest is also computed . ...
distances = [ np . dot ( self . normal_vector , pp ) + self . d for pp in points ] indices = sorted ( range ( len ( distances ) ) , key = lambda k : np . abs ( distances [ k ] ) ) if sign : indices = [ ( ii , int ( np . sign ( distances [ ii ] ) ) ) for ii in indices ] return distances , indices
def set_widget ( self , canvas_w ) : """Call this method with the widget that will be used for the display ."""
self . logger . debug ( "set widget canvas_w=%s" % canvas_w ) self . pgcanvas = canvas_w
def disconnect ( self , receipt = None , headers = None , ** keyword_headers ) : """Disconnect from the server . : param str receipt : the receipt to use ( once the server acknowledges that receipt , we ' re officially disconnected ; optional - if not specified a unique receipt id will be generated ) : para...
if not self . transport . is_connected ( ) : log . debug ( 'Not sending disconnect, already disconnected' ) return headers = utils . merge_headers ( [ headers , keyword_headers ] ) rec = receipt or utils . get_uuid ( ) headers [ HDR_RECEIPT ] = rec self . set_receipt ( rec , CMD_DISCONNECT ) self . send_frame (...
def check ( self , value , major ) : """Check whether the value is between the minimum and maximum . Raise a ValueError if it is not ."""
if self . _min is not None and value < self . _min : raise ValueError ( "Integer %d is lower than minimum %d." % ( value , self . _min ) ) if self . _max is not None and value > self . _max : raise ValueError ( "Integer %d is higher than maximum %d." % ( value , self . _max ) )
def parse_addr ( text ) : "Parse a 1 - to 3 - part address spec ."
if text : parts = text . split ( ':' ) length = len ( parts ) if length == 3 : return parts [ 0 ] , parts [ 1 ] , int ( parts [ 2 ] ) elif length == 2 : return None , parts [ 0 ] , int ( parts [ 1 ] ) elif length == 1 : return None , '' , int ( parts [ 0 ] ) return None , Non...
def flip_ctrlpts_u ( ctrlpts , size_u , size_v ) : """Flips a list of 1 - dimensional control points from u - row order to v - row order . * * u - row order * * : each row corresponds to a list of u values * * v - row order * * : each row corresponds to a list of v values : param ctrlpts : control points in u...
new_ctrlpts = [ ] for i in range ( 0 , size_u ) : for j in range ( 0 , size_v ) : temp = [ float ( c ) for c in ctrlpts [ i + ( j * size_u ) ] ] new_ctrlpts . append ( temp ) return new_ctrlpts
def get_slice ( im , center , size , pad = 0 ) : r"""Given a ` ` center ` ` location and ` ` radius ` ` of a feature , returns the slice object into the ` ` im ` ` that bounds the feature but does not extend beyond the image boundaries . Parameters im : ND - image The image of the porous media center : ...
p = sp . ones ( shape = im . ndim , dtype = int ) * sp . array ( pad ) s = sp . ones ( shape = im . ndim , dtype = int ) * sp . array ( size ) slc = [ ] for dim in range ( im . ndim ) : lower_im = sp . amax ( ( center [ dim ] - s [ dim ] - p [ dim ] , 0 ) ) upper_im = sp . amin ( ( center [ dim ] + s [ dim ] + ...
def nodes_of_class ( self , klass , skip_klass = None ) : """Get the nodes ( including this one or below ) of the given type . : param klass : The type of node to search for . : type klass : builtins . type : param skip _ klass : A type of node to ignore . This is useful to ignore subclasses of : attr : ` k...
if isinstance ( self , klass ) : yield self if skip_klass is None : for child_node in self . get_children ( ) : yield from child_node . nodes_of_class ( klass , skip_klass ) return for child_node in self . get_children ( ) : if isinstance ( child_node , skip_klass ) : continue yield ...
def _encode ( self , sources : mx . nd . NDArray , source_length : int ) -> Tuple [ List [ ModelState ] , mx . nd . NDArray ] : """Returns a ModelState for each model representing the state of the model after encoding the source . : param sources : Source ids . Shape : ( batch _ size , bucket _ key , num _ factor...
model_states = [ ] ratios = [ ] for model in self . models : state , ratio = model . run_encoder ( sources , source_length ) model_states . append ( state ) if ratio is not None : ratios . append ( ratio ) # num _ seq takes batch _ size and beam _ size into account num_seq = model_states [ 0 ] . sta...
def keep_vertices ( self , indices_to_keep , ret_kept_faces = False ) : '''Keep the given vertices and discard the others , and any faces to which they may belong . If ` ret _ kept _ faces ` is ` True ` , return the original indices of the kept faces . Otherwise return ` self ` for chaining .'''
import numpy as np if self . v is None : return indices_to_keep = np . array ( indices_to_keep , dtype = np . uint32 ) initial_num_verts = self . v . shape [ 0 ] if self . f is not None : initial_num_faces = self . f . shape [ 0 ] f_indices_to_keep = self . all_faces_with_verts ( indices_to_keep , as_boolea...
def is_done ( self ) : """True if the last two moves were Pass or if the position is at a move greater than the max depth ."""
return self . position . is_game_over ( ) or self . position . n >= FLAGS . max_game_length
def delete_feature ( self , dataset , fid ) : """Removes a feature from a dataset . Parameters dataset : str The dataset id . fid : str The feature id . Returns HTTP status code ."""
uri = URITemplate ( self . baseuri + '/{owner}/{did}/features/{fid}' ) . expand ( owner = self . username , did = dataset , fid = fid ) return self . session . delete ( uri )
def daterange ( start_date , end_date ) : """Yield one date per day from starting date to ending date . Args : start _ date ( date ) : starting date . end _ date ( date ) : ending date . Yields : date : a date for each day within the range ."""
for n in range ( int ( ( end_date - start_date ) . days ) ) : yield start_date + timedelta ( n )
def get_endpoints ( ) : """get all endpoints known on the Ariane server : return :"""
LOGGER . debug ( "EndpointService.get_endpoints" ) params = SessionService . complete_transactional_req ( None ) if params is None : if MappingService . driver_type != DriverFactory . DRIVER_REST : params = { 'OPERATION' : 'getEndpoints' } args = { 'properties' : params } else : args = {...
def minion_config ( opts , vm_ ) : '''Return a minion ' s configuration for the provided options and VM'''
# Don ' t start with a copy of the default minion opts ; they ' re not always # what we need . Some default options are Null , let ' s set a reasonable default minion = { 'master' : 'salt' , 'log_level' : 'info' , 'hash_type' : 'sha256' , } # Now , let ' s update it to our needs minion [ 'id' ] = vm_ [ 'name' ] master_...
def _split_params ( tag_prefix , tag_suffix ) : "Split comma - separated tag _ suffix [ : - 1 ] and map with _ maybe _ int"
if tag_suffix [ - 1 : ] != ')' : raise ValueError , "unbalanced parenthesis in type %s%s" % ( tag_prefix , tag_suffix ) return map ( _maybe_int , tag_suffix [ : - 1 ] . split ( ',' ) )
def convert ( values , source_measure_or_unit_abbreviation , target_measure_or_unit_abbreviation ) : """Convert a value or a list of values from an unit to another one . The two units must represent the same physical dimension ."""
source_dimension = get_dimension_by_unit_measure_or_abbreviation ( source_measure_or_unit_abbreviation ) target_dimension = get_dimension_by_unit_measure_or_abbreviation ( target_measure_or_unit_abbreviation ) if source_dimension == target_dimension : source = JSONObject ( { } ) target = JSONObject ( { } ) ...
def _hook_variable_gradient_stats ( self , var , name , log_track ) : """Logs a Variable ' s gradient ' s distribution statistics next time backward ( ) is called on it ."""
if not isinstance ( var , torch . autograd . Variable ) : cls = type ( var ) raise TypeError ( 'Expected torch.Variable, not {}.{}' . format ( cls . __module__ , cls . __name__ ) ) handle = self . _hook_handles . get ( name ) if handle is not None and self . _torch_hook_handle_is_valid ( handle ) : raise Va...
def visit_Assign ( self , node ) : """Implement assignment walker . Parse class properties defined via the property ( ) function"""
# [ [ [ cog # cog . out ( " print ( pcolor ( ' Enter assign visitor ' , ' magenta ' ) ) " ) # [ [ [ end ] ] ] # Class - level assignment may also be a class attribute that is not # a managed attribute , record it anyway , no harm in doing so as it # is not attached to a callable if self . _in_class ( node ) : eleme...
def rm ( self , index ) : """Handles the ' r ' command . : index : Index of the item to remove ."""
if self . model . exists ( index ) : self . model . remove ( index )
def spht ( ssphere , nmax = None , mmax = None ) : """Transforms ScalarPatternUniform object * ssphere * into a set of scalar spherical harmonics stored in ScalarCoefs . Example : : > > > p = spherepy . random _ patt _ uniform ( 6 , 8) > > > c = spherepy . spht ( p ) > > > spherepy . pretty _ coefs ( c ) ...
if nmax == None : nmax = ssphere . nrows - 2 mmax = int ( ssphere . ncols / 2 ) - 1 elif mmax == None : mmax = nmax if mmax > nmax : raise ValueError ( err_msg [ 'nmax_g_mmax' ] ) if nmax >= ssphere . nrows - 1 : raise ValueError ( err_msg [ 'nmax_too_lrg' ] ) if mmax >= ssphere . ncols / 2 : ra...
def find_nth_digit ( n ) : """find the nth digit of given number . 1 . find the length of the number where the nth digit is from . 2 . find the actual number where the nth digit is from 3 . find the nth digit and return"""
length = 1 count = 9 start = 1 while n > length * count : n -= length * count length += 1 count *= 10 start *= 10 start += ( n - 1 ) / length s = str ( start ) return int ( s [ ( n - 1 ) % length ] )
def init_prov_graph ( self ) : """Initialize PROV graph with all we know at the start of the recording"""
try : # Use git2prov to get prov on the repo repo_prov = check_output ( [ 'node_modules/git2prov/bin/git2prov' , 'https://github.com/{}/{}/' . format ( self . user , self . repo ) , 'PROV-O' ] ) . decode ( "utf-8" ) repo_prov = repo_prov [ repo_prov . find ( '@' ) : ] # glogger . debug ( ' Git2PROV output :...
def _init_user_stub ( self , ** stub_kwargs ) : """Initializes the user stub using nosegae config magic"""
# do a little dance to keep the same kwargs for multiple tests in the same class # because the user stub will barf if you pass these items into it # stub = user _ service _ stub . UserServiceStub ( * * stub _ kw _ args ) # TypeError : _ _ init _ _ ( ) got an unexpected keyword argument ' USER _ IS _ ADMIN ' task_args =...
def get_memory_usage ( self ) : """Get data about the virtual memory usage of the holder . : returns : Memory usage data : rtype : dict Example : > > > holder . get _ memory _ usage ( ) > > > ' nb _ arrays ' : 12 , # The holder contains the variable values for 12 different periods > > > ' nb _ cells _ b...
usage = dict ( nb_cells_by_array = self . population . count , dtype = self . variable . dtype , ) usage . update ( self . _memory_storage . get_memory_usage ( ) ) if self . simulation . trace : usage_stats = self . simulation . tracer . usage_stats [ self . variable . name ] usage . update ( dict ( nb_requests...
def elements ( self ) : """Return a list of the elements which are not None"""
elements = [ ] for el in ct : if isinstance ( el [ 1 ] , datapoint . Element . Element ) : elements . append ( el [ 1 ] ) return elements
def initialize ( self , init = None , ctx = None , default_init = initializer . Uniform ( ) , force_reinit = False ) : """Initializes parameter and gradient arrays . Only used for : py : class : ` NDArray ` API . Parameters init : Initializer The initializer to use . Overrides : py : meth : ` Parameter . init...
if self . _data is not None and not force_reinit : warnings . warn ( "Parameter '%s' is already initialized, ignoring. " "Set force_reinit=True to re-initialize." % self . name , stacklevel = 2 ) return self . _data = self . _grad = None if ctx is None : ctx = [ context . current_context ( ) ] if isinstance...
def get_node_attributes ( self , node ) : """Given a node , get a dictionary with copies of that node ' s attributes . : param node : reference to the node to retrieve the attributes of . : returns : dict - - copy of each attribute of the specified node . : raises : ValueError - - No such node exists ."""
if not self . has_node ( node ) : raise ValueError ( "No such node exists." ) attributes = { } for attr_name , attr_value in self . _node_attributes [ node ] . items ( ) : attributes [ attr_name ] = copy . copy ( attr_value ) return attributes
def check_version ( self , timeout = 2 , strict = False , topics = [ ] ) : """Attempt to guess the broker version . Note : This is a blocking call . Returns : version tuple , i . e . ( 0 , 10 ) , ( 0 , 9 ) , ( 0 , 8 , 2 ) , . . ."""
timeout_at = time . time ( ) + timeout log . info ( 'Probing node %s broker version' , self . node_id ) # Monkeypatch some connection configurations to avoid timeouts override_config = { 'request_timeout_ms' : timeout * 1000 , 'max_in_flight_requests_per_connection' : 5 } stashed = { } for key in override_config : ...