signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def commit_check ( ) : '''Perform a commit check on the configuration CLI Example : . . code - block : : bash salt ' device _ name ' junos . commit _ check'''
conn = __proxy__ [ 'junos.conn' ] ( ) ret = { } ret [ 'out' ] = True try : conn . cu . commit_check ( ) ret [ 'message' ] = 'Commit check succeeded.' except Exception as exception : ret [ 'message' ] = 'Commit check failed with {0}' . format ( exception ) ret [ 'out' ] = False return ret
def _delete_objects_not_in_list ( self , cont , object_prefix = "" ) : """Finds all the objects in the specified container that are not present in the self . _ local _ files list , and deletes them ."""
objnames = set ( cont . get_object_names ( prefix = object_prefix , full_listing = True ) ) localnames = set ( self . _local_files ) to_delete = list ( objnames . difference ( localnames ) ) self . _sync_summary [ "deleted" ] += len ( to_delete ) # We don ' t need to wait around for this to complete . Store the thread ...
def run ( self , raw_args = None ) : """Parses the given arguments ( if these are None , then argparse ' s parser defaults to parsing sys . argv ) , inits a Core instance , calls its lint method with the respective arguments , and then exits ."""
args = self . parser . parse_args ( raw_args ) core = Core ( ) try : report = core . lint ( ** vars ( args ) ) except Exception as err : self . parser . error ( str ( err ) ) print ( report ) self . parser . exit ( )
def _to_str ( uri : URIRef ) -> str : """Convert a FHIR style URI into a tag name to be used to retrieve data from a JSON representation Example : http : / / hl7 . org / fhir / Provenance . agent . whoReference - - > whoReference : param uri : URI to convert : return : tag name"""
local_name = str ( uri ) . replace ( str ( FHIR ) , '' ) return local_name . rsplit ( '.' , 1 ) [ 1 ] if '.' in local_name else local_name
def get_authors ( filepath : str ) -> List [ str ] : """Open file and check for author info ."""
str_oneline = r'(^__author__ = )(\[.*?\])' # type " str comp_oneline = re . compile ( str_oneline , re . MULTILINE ) # type : Pattern [ str ] with open ( filepath ) as file_open : file_read = file_open . read ( ) # type : str match = comp_oneline . findall ( file_read ) if match : inner_list_as_str = match ...
def list_present ( name , acl_type , acl_names = None , perms = '' , recurse = False , force = False ) : '''Ensure a Linux ACL list is present Takes a list of acl names and add them to the given path name The acl path acl _ type The type of the acl is used for it can be ' user ' or ' group ' acl _ names...
if acl_names is None : acl_names = [ ] ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : '' } _octal = { 'r' : 4 , 'w' : 2 , 'x' : 1 , '-' : 0 } _octal_perms = sum ( [ _octal . get ( i , i ) for i in perms ] ) if not os . path . exists ( name ) : ret [ 'comment' ] = '{0} does not exist' . ...
def deprecate_module_attribute ( mod , deprecated ) : """Return a wrapped object that warns about deprecated accesses"""
deprecated = set ( deprecated ) class Wrapper ( object ) : def __getattr__ ( self , attr ) : if attr in deprecated : warnings . warn ( "Property %s is deprecated" % attr ) return getattr ( mod , attr ) def __setattr__ ( self , attr , value ) : if attr in deprecated : ...
def dictionary ( element_name , # type : Text children , # type : List [ Processor ] required = True , # type : bool alias = None , # type : Optional [ Text ] hooks = None # type : Optional [ Hooks ] ) : # type : ( . . . ) - > RootProcessor """Create a processor for dictionary values . : param element _ name : Na...
processor = _Dictionary ( element_name , children , required , alias ) return _processor_wrap_if_hooks ( processor , hooks )
def save_data ( self , trigger_id , ** data ) : """let ' s save the data : param trigger _ id : trigger ID from which to save data : param data : the data to check to be used and save : type trigger _ id : int : type data : dict : return : the status of the save statement : rtype : boolean"""
# convert the format to be released in Markdown status = False data [ 'output_format' ] = 'md' title , content = super ( ServiceReddit , self ) . save_data ( trigger_id , ** data ) if self . token : trigger = Reddit . objects . get ( trigger_id = trigger_id ) if trigger . share_link : status = self . re...
def get_bundle_list ( self , href = None , limit = None , embed_items = None , embed_tracks = None , embed_metadata = None , embed_insights = None ) : """Get a list of available bundles . ' href ' the relative href to the bundle list to retriev . If None , the first bundle list will be returned . ' limit ' th...
# Argument error checking . assert limit is None or limit > 0 j = None if href is None : j = self . _get_first_bundle_list ( limit , embed_items , embed_tracks , embed_metadata , embed_insights ) else : j = self . _get_additional_bundle_list ( href , limit , embed_items , embed_tracks , embed_metadata , embed_i...
def _compile ( self , lines ) : '''Set the correct render method ( boolean or function call ) and read variables from the current line .'''
m = self . __class__ . RE_IF . match ( lines . current ) if m is None : raise DefineBlockError ( 'Incorrect block definition at line {}, {}\nShould be ' 'something like: #if @foo:' . format ( lines . pos , lines . current ) ) args = m . group ( 3 ) self . _evaluate = m . group ( 2 ) . replace ( '.' , '-' ) self . _...
def get_profile ( self , name , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Gets the specified profile . Example : > > > from google . cloud import talent _ v4beta1 > > > client = talent _ v4beta1 . ProfileServi...
# Wrap the transport method to add retry and timeout logic . if "get_profile" not in self . _inner_api_calls : self . _inner_api_calls [ "get_profile" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . get_profile , default_retry = self . _method_configs [ "GetProfile" ] . retry , default_...
def proxy_image ( self , s = 0 , c = 0 , z = 0 , t = 0 ) : """Return a : class : ` jicimagelib . image . MicroscopyImage ` instance . : param s : series : param c : channel : param z : zslice : param t : timepoint : returns : : class : ` jicimagelib . image . MicroscopyImage `"""
for proxy_image in self : if proxy_image . is_me ( s = s , c = c , z = z , t = t ) : return proxy_image
def _set_internal_value ( self , new_internal_value ) : """This is supposed to be only used by fitting engines : param new _ internal _ value : new value in internal representation : return : none"""
if new_internal_value != self . _internal_value : self . _internal_value = new_internal_value # Call callbacks if any for callback in self . _callbacks : callback ( self )
def en_last ( self ) : """Report the energies from the last SCF present in the output . Returns a | dict | providing the various energy values from the last SCF cycle performed in the output . Keys are those of : attr : ` ~ opan . output . OrcaOutput . p _ en ` . Any energy value not relevant to the parsed ...
# Initialize the return dict last_ens = dict ( ) # Iterate and store for ( k , l ) in self . en . items ( ) : last_ens . update ( { k : l [ - 1 ] if l != [ ] else None } ) # # next ( k , l ) # Should be ready to return ? return last_ens
def lambda_from_file ( python_file ) : """Reads a python file and returns a awslambda . Code object : param python _ file : : return :"""
lambda_function = [ ] with open ( python_file , 'r' ) as f : lambda_function . extend ( f . read ( ) . splitlines ( ) ) return awslambda . Code ( ZipFile = ( Join ( '\n' , lambda_function ) ) )
def kill ( self ) : """Kill the browser . This is useful when the browser is stuck ."""
if self . process : self . process . kill ( ) self . process . wait ( )
def plot_correlations ( self , iabscissa = 1 ) : """spectrum of correlation matrix and largest correlation"""
if not hasattr ( self , 'corrspec' ) : self . load ( ) if len ( self . corrspec ) < 2 : return self x = self . corrspec [ : , iabscissa ] y = self . corrspec [ : , 6 : ] # principle axes ys = self . corrspec [ : , : 6 ] # " special " values from matplotlib . pyplot import semilogy , hold , text , grid , axis , ...
def handle_arguments ( self , string , root , opening , closing ) : """Handles phrase - arguments . Sets the override and increment flags if found . Also makes sure that the argument sequence is at the start of the phrase and else warns about the unescaped meta characters . If the arguments are indeed at th...
# The actual argument string ( ignore whitespace ) args = string [ opening + 1 : closing ] . replace ( " " , "" ) # The argument sequence must be at the start of the phrase # and must match the allowed argument regular expression if opening > 0 or not self . arguments . match ( args ) : if opening == 0 : ra...
def pwd ( self , ** kwargs ) : """Returns the cwd Optional kwargs : node = < node > If specified , return only the directory name at depth < node > ."""
b_node = False node = 0 for key , val in kwargs . items ( ) : if key == 'node' : b_node = True node = int ( val ) str_path = self . cwd ( ) if b_node : l_path = str_path . split ( '/' ) if len ( l_path ) >= node + 1 : str_path = str_path . split ( '/' ) [ node ] return str_path
def create_file_system ( name , performance_mode = 'generalPurpose' , keyid = None , key = None , profile = None , region = None , creation_token = None , ** kwargs ) : '''Creates a new , empty file system . name ( string ) - The name for the new file system performance _ mode ( string ) - The PerformanceMo...
if creation_token is None : creation_token = name tags = { "Key" : "Name" , "Value" : name } client = _get_conn ( key = key , keyid = keyid , profile = profile , region = region ) response = client . create_file_system ( CreationToken = creation_token , PerformanceMode = performance_mode ) if 'FileSystemId' in resp...
def default_get ( self , fields ) : """To get default values for the object . @ param self : The object pointer . @ param fields : List of fields for which we want default values @ return : A dictionary which of fields with values ."""
if self . _context is None : self . _context = { } res = super ( QuickRoomReservation , self ) . default_get ( fields ) if self . _context : keys = self . _context . keys ( ) if 'date' in keys : res . update ( { 'check_in' : self . _context [ 'date' ] } ) if 'room_id' in keys : roomid = ...
def _detect_sse3 ( self ) : "Does this compiler support SSE3 intrinsics ?"
self . _print_support_start ( 'SSE3' ) result = self . hasfunction ( '__m128 v; _mm_hadd_ps(v,v)' , include = '<pmmintrin.h>' , extra_postargs = [ '-msse3' ] ) self . _print_support_end ( 'SSE3' , result ) return result
def get_schema_type ( cls , schema ) : """Get schema type for the argument : param schema : Schema to analyze : return : COMPILED _ TYPE constant : rtype : str | None"""
schema_type = type ( schema ) # Marker if issubclass ( schema_type , markers . Marker ) : return const . COMPILED_TYPE . MARKER # Marker Type elif issubclass ( schema_type , six . class_types ) and issubclass ( schema , markers . Marker ) : return const . COMPILED_TYPE . MARKER # CompiledSchema elif isinstance ...
def get_cached_image ( self , width , height , zoom , parameters = None , clear = False ) : """Get ImageSurface object , if possible , cached The method checks whether the image was already rendered . This is done by comparing the passed size and parameters with those of the last image . If they are equal , the...
global MAX_ALLOWED_AREA if not parameters : parameters = { } if self . __compare_parameters ( width , height , zoom , parameters ) and not clear : return True , self . __image , self . __zoom # Restrict image surface size to prevent excessive use of memory while True : try : self . __limiting_multip...
def AddPathIfNotExists ( env_dict , key , path , sep = os . pathsep ) : """This function will take ' key ' out of the dictionary ' env _ dict ' , then add the path ' path ' to that key if it is not already there . This treats the value of env _ dict [ key ] as if it has a similar format to the PATH variable ....
try : is_list = 1 paths = env_dict [ key ] if not is_List ( env_dict [ key ] ) : paths = paths . split ( sep ) is_list = 0 if os . path . normcase ( path ) not in list ( map ( os . path . normcase , paths ) ) : paths = [ path ] + paths if is_list : env_dict [ key ] = ...
def meff_SO ( self , ** kwargs ) : '''Returns the split - off hole effective mass calculated from Eg _ Gamma ( T ) , Delta _ SO , Ep and F . Interpolation of Eg _ Gamma ( T ) , Delta _ SO , Ep and luttinger1 , and then calculation of meff _ SO is recommended for alloys .'''
Eg = self . Eg_Gamma ( ** kwargs ) Delta_SO = self . Delta_SO ( ** kwargs ) Ep = self . Ep ( ** kwargs ) luttinger1 = self . luttinger1 ( ** kwargs ) return 1. / ( luttinger1 - ( Ep * Delta_SO ) / ( 3 * Eg * ( Eg + Delta_SO ) ) )
def _retrieve_stack_host_zone_name ( awsclient , default_stack_name = None ) : """Use service discovery to get the host zone name from the default stack : return : Host zone name as string"""
global _host_zone_name if _host_zone_name is not None : return _host_zone_name env = get_env ( ) if env is None : print ( "Please set environment..." ) # TODO : why is there a sys . exit in library code used by cloudformation ! ! ! sys . exit ( ) if default_stack_name is None : # TODO why ' dp - < env >...
def __decompressContent ( coding , pgctnt ) : '''Decompress returned HTTP content depending on the specified encoding . Currently supports identity / none , deflate , and gzip , which should cover 99 % + of the content on the internet .'''
log . trace ( "Decompressing %s byte content with compression type: %s" , len ( pgctnt ) , coding ) if coding == 'deflate' : pgctnt = zlib . decompress ( pgctnt , - zlib . MAX_WBITS ) elif coding == 'gzip' : buf = io . BytesIO ( pgctnt ) f = gzip . GzipFile ( fileobj = buf ) pgctnt = f . read ( ) elif c...
def ValidateChildren ( self , problems ) : """Validate StopTimes and headways of this trip ."""
assert self . _schedule , "Trip must be in a schedule to ValidateChildren" # TODO : validate distance values in stop times ( if applicable ) self . ValidateNoDuplicateStopSequences ( problems ) stoptimes = self . GetStopTimes ( problems ) stoptimes . sort ( key = lambda x : x . stop_sequence ) self . ValidateTripStartA...
def __shapeIndex ( self , i = None ) : """Returns the offset in a . shp file for a shape based on information in the . shx index file ."""
shx = self . shx if not shx : return None if not self . _offsets : # File length ( 16 - bit word * 2 = bytes ) - header length shx . seek ( 24 ) shxRecordLength = ( unpack ( ">i" , shx . read ( 4 ) ) [ 0 ] * 2 ) - 100 numRecords = shxRecordLength // 8 # Jump to the first record . shx . seek ( 10...
def get_maps ( ) : """Get the full dict of maps { map _ name : map _ class } ."""
maps = { } for mp in Map . all_subclasses ( ) : if mp . filename : map_name = mp . __name__ if map_name in maps : raise DuplicateMapException ( "Duplicate map found: " + map_name ) maps [ map_name ] = mp return maps
def apply_order ( self ) : '''Naively apply query orders .'''
self . _ensure_modification_is_safe ( ) if len ( self . query . orders ) > 0 : self . _iterable = Order . sorted ( self . _iterable , self . query . orders )
def validate_serializer ( serializer , _type ) : """Validates the serializer for given type . : param serializer : ( Serializer ) , the serializer to be validated . : param _ type : ( Type ) , type to be used for serializer validation ."""
if not issubclass ( serializer , _type ) : raise ValueError ( "Serializer should be an instance of {}" . format ( _type . __name__ ) )
def check_actually_paused ( services = None , ports = None ) : """Check that services listed in the services object and ports are actually closed ( not listened to ) , to verify that the unit is properly paused . @ param services : See _ extract _ services _ list _ helper @ returns status , : string for sta...
state = None message = None messages = [ ] if services is not None : services = _extract_services_list_helper ( services ) services_running , services_states = _check_running_services ( services ) if any ( services_states ) : # there shouldn ' t be any running so this is a problem messages . append ...
def from_str ( value : str ) -> ulid . ULID : """Create a new : class : ` ~ ulid . ulid . ULID ` instance from the given : class : ` ~ str ` value . : param value : Base32 encoded string : type value : : class : ` ~ str ` : return : ULID from string value : rtype : : class : ` ~ ulid . ulid . ULID ` : rai...
return ulid . ULID ( base32 . decode_ulid ( value ) )
def run_script ( self , script_id , params = None ) : """Runs a stored script . script _ id : = id of stored script . params : = up to 10 parameters required by the script . s = pi . run _ script ( sid , [ par1 , par2 ] ) s = pi . run _ script ( sid ) s = pi . run _ script ( sid , [ 1 , 2 , 3 , 4 , 5 , 6 ...
# I p1 script id # I p2 0 # I p3 params * 4 ( 0-10 params ) # ( optional ) extension # I [ ] params if params is not None : ext = bytearray ( ) for p in params : ext . extend ( struct . pack ( "I" , p ) ) nump = len ( params ) extents = [ ext ] else : nump = 0 extents = [ ] res = yield f...
def update_stack ( self , name , working_bucket , wait = False , update_only = False , disable_progress = False ) : """Update or create the CF stack managed by Zappa ."""
capabilities = [ ] template = name + '-template-' + str ( int ( time . time ( ) ) ) + '.json' with open ( template , 'wb' ) as out : out . write ( bytes ( self . cf_template . to_json ( indent = None , separators = ( ',' , ':' ) ) , "utf-8" ) ) self . upload_to_s3 ( template , working_bucket , disable_progress = di...
def cmake_setup ( ) : """attempt to build using CMake > = 3"""
cmake_exe = shutil . which ( 'cmake' ) if not cmake_exe : raise FileNotFoundError ( 'CMake not available' ) wopts = [ '-G' , 'MinGW Makefiles' , '-DCMAKE_SH="CMAKE_SH-NOTFOUND' ] if os . name == 'nt' else [ ] subprocess . check_call ( [ cmake_exe ] + wopts + [ str ( SRCDIR ) ] , cwd = BINDIR ) ret = subprocess . ru...
def method_file_cd ( f ) : """A decorator to cd back to the original directory where this object was created ( useful for any calls to TObject . Write ) . This function can decorate methods ."""
@ wraps ( f ) def wrapper ( self , * args , ** kwargs ) : with preserve_current_directory ( ) : self . GetDirectory ( ) . cd ( ) return f ( self , * args , ** kwargs ) return wrapper
def walk_processes ( top , topname = 'top' , topdown = True , ignoreFlag = False ) : """Generator for recursive tree of climlab processes Starts walking from climlab process ` ` top ` ` and generates a complete list of all processes and sub - processes that are managed from ` ` top ` ` process . ` ` level ` `...
if not ignoreFlag : flag = topdown else : flag = True proc = top level = 0 if flag : yield topname , proc , level if len ( proc . subprocess ) > 0 : # there are sub - processes level += 1 for name , subproc in proc . subprocess . items ( ) : for name2 , subproc2 , level2 in walk_processes ( ...
def reboot ( self ) : """Requests an autopilot reboot by sending a ` ` MAV _ CMD _ PREFLIGHT _ REBOOT _ SHUTDOWN ` ` command ."""
reboot_msg = self . message_factory . command_long_encode ( 0 , 0 , # target _ system , target _ component mavutil . mavlink . MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN , # command 0 , # confirmation 1 , # param 1 , autopilot ( reboot ) 0 , # param 2 , onboard computer ( do nothing ) 0 , # param 3 , camera ( do nothing ) 0 , #...
def show_support_save_status_output_show_support_save_status_status ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_support_save_status = ET . Element ( "show_support_save_status" ) config = show_support_save_status output = ET . SubElement ( show_support_save_status , "output" ) show_support_save_status = ET . SubElement ( output , "show-support-save-status" ) status = ET . SubElement ( show_...
def send_email_message ( self , recipient , subject , html_message , text_message , sender_email , sender_name ) : """Send email message via Flask - Sendmail . Args : recipient : Email address or tuple of ( Name , Email - address ) . subject : Subject line . html _ message : The message body in HTML . tex...
if not current_app . testing : # pragma : no cover # Prepare email message from flask_sendmail import Message message = Message ( subject , recipients = [ recipient ] , html = html_message , body = text_message ) # Send email message self . mail . send ( message )
def convenience_calc_probs ( self , params ) : """Calculates the probabilities of the chosen alternative , and the long format probabilities for this model and dataset ."""
shapes , intercepts , betas = self . convenience_split_params ( params ) prob_args = [ betas , self . design , self . alt_id_vector , self . rows_to_obs , self . rows_to_alts , self . utility_transform ] prob_kwargs = { "intercept_params" : intercepts , "shape_params" : shapes , "chosen_row_to_obs" : self . chosen_row_...
def parsimonious_acr ( tree , character , prediction_method , states , num_nodes , num_tips ) : """Calculates parsimonious states on the tree and stores them in the corresponding feature . : param states : numpy array of possible states : param prediction _ method : str , ACCTRAN ( accelerated transformation ) ...
initialise_parsimonious_states ( tree , character , states ) uppass ( tree , character ) results = [ ] result = { STATES : states , NUM_NODES : num_nodes , NUM_TIPS : num_tips } logger = logging . getLogger ( 'pastml' ) def process_result ( method , feature ) : out_feature = get_personalized_feature_name ( characte...
def getParameterByType ( self , type ) : """Searchs a parameter by type and returns it ."""
result = None for parameter in self . getParameters ( ) : typeParam = parameter . getType ( ) if typeParam == type : result = parameter break return result
def annotate ( self , text , lang = None , customParams = None ) : """identify the list of entities and nonentities mentioned in the text @ param text : input text to annotate @ param lang : language of the provided document ( can be an ISO2 or ISO3 code ) . If None is provided , the language will be automatica...
params = { "lang" : lang , "text" : text } if customParams : params . update ( customParams ) return self . _er . jsonRequestAnalytics ( "/api/v1/annotate" , params )
def discover_glitter_apps ( self ) : """Find all the Glitter App configurations in the current project ."""
for app_name in settings . INSTALLED_APPS : module_name = '{app_name}.glitter_apps' . format ( app_name = app_name ) try : glitter_apps_module = import_module ( module_name ) if hasattr ( glitter_apps_module , 'apps' ) : self . glitter_apps . update ( glitter_apps_module . apps ) ...
def predict ( self , x_test ) : """Returns the prediction of the model on the given test data . Args : x _ test : array - like , shape = ( n _ samples , sent _ length ) Test samples . Returns : y _ pred : array - like , shape = ( n _ smaples , sent _ length ) Prediction labels for x ."""
if self . model : lengths = map ( len , x_test ) x_test = self . p . transform ( x_test ) y_pred = self . model . predict ( x_test ) y_pred = self . p . inverse_transform ( y_pred , lengths ) return y_pred else : raise OSError ( 'Could not find a model. Call load(dir_path).' )
def debug ( self , message , extra = { } ) : '''Writes an error message to the log @ param message : The message to write @ param extra : The extras object to pass in'''
if self . level_dict [ 'DEBUG' ] >= self . level_dict [ self . log_level ] : extras = self . add_extras ( extra , "DEBUG" ) self . _write_message ( message , extras ) self . fire_callbacks ( 'DEBUG' , message , extra )
def get_obj_doc0 ( obj , alt = "(no doc)" ) : """Returns first line of cls . _ _ doc _ _ , or alternative text"""
ret = obj . __doc__ . strip ( ) . split ( "\n" ) [ 0 ] if obj . __doc__ is not None else alt return ret
def _preprocess_data ( self , data ) : """Converts a data array to the preferred 3D structure . Parameters data : : obj : ` numpy . ndarray ` The data to process . Returns : obj : ` numpy . ndarray ` The data re - formatted ( if needed ) as a 3D matrix Raises ValueError If the data is not 1 , 2 , ...
original_type = data . dtype if len ( data . shape ) == 1 : data = data [ : , np . newaxis , np . newaxis ] elif len ( data . shape ) == 2 : data = data [ : , : , np . newaxis ] elif len ( data . shape ) == 0 or len ( data . shape ) > 3 : raise ValueError ( 'Illegal data array passed to image. Must be 1, 2,...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'system' ) and self . system is not None : _dict [ 'system' ] = self . system . _to_dict ( ) return _dict
def bootstrap_c_source ( scheduler_bindings_path , output_dir , module_name = NATIVE_ENGINE_MODULE ) : """Bootstrap an external CFFI C source file ."""
safe_mkdir ( output_dir ) with temporary_dir ( ) as tempdir : temp_output_prefix = os . path . join ( tempdir , module_name ) real_output_prefix = os . path . join ( output_dir , module_name ) temp_c_file = '{}.c' . format ( temp_output_prefix ) if PY2 : temp_c_file = temp_c_file . encode ( 'utf...
def getClientSSLContext ( self ) : '''Returns an ssl . SSLContext appropriate for initiating a TLS session'''
sslctx = ssl . create_default_context ( ssl . Purpose . SERVER_AUTH ) self . _loadCasIntoSSLContext ( sslctx ) return sslctx
def user_activity_stats_by_date ( self , username , date , grouped = None ) : """Retrieve activity information about a specific user on the specified date . Params : username ( string ) : filters the username of the user whose activity you are interested in . date ( string ) : filters by the date of interest ...
request_url = "{}/api/0/user/{}/activity/{}" . format ( self . instance , username , date ) payload = { } if username is not None : payload [ 'username' ] = username if date is not None : payload [ 'date' ] = date if grouped is not None : payload [ 'grouped' ] = grouped return_value = self . _call_api ( req...
def calcAcceptanceRatio ( self , V , W ) : """Given a order vector V and a proposed order vector W , calculate the acceptance ratio for changing to W when using MCMC . ivar : dict < int , < dict , < int , int > > > wmg : A two - dimensional dictionary that associates integer representations of each pair of ca...
acceptanceRatio = 1.0 for comb in itertools . combinations ( V , 2 ) : # Check if comb [ 0 ] is ranked before comb [ 1 ] in V and W vIOverJ = 1 wIOverJ = 1 if V . index ( comb [ 0 ] ) > V . index ( comb [ 1 ] ) : vIOverJ = 0 if W . index ( comb [ 0 ] ) > W . index ( comb [ 1 ] ) : wIOver...
def as_rest_table ( data , full = False ) : """Originally from ActiveState recipes , copy / pasted from GitHub where it is listed with an MIT license . https : / / github . com / ActiveState / code / tree / master / recipes / Python / 579054 _ Generate _ Sphinx _ table"""
data = data if data else [ [ "No Data" ] ] table = [ ] # max size of each column sizes = list ( map ( max , zip ( * [ [ len ( str ( elt ) ) for elt in member ] for member in data ] ) ) ) num_elts = len ( sizes ) if full : start_of_line = "| " vertical_separator = " | " end_of_line = " |" line_marker = "...
def _get_derivative ( self , C , sa1180 , vs30 ) : """Returns equation 30 page 1047"""
derAmp = np . zeros_like ( vs30 ) n = self . CONSTS [ 'n' ] c = C [ 'c' ] b = C [ 'b' ] idx = vs30 < C [ 'vlin' ] derAmp [ idx ] = ( b * sa1180 [ idx ] * ( - 1. / ( sa1180 [ idx ] + c ) + 1. / ( sa1180 [ idx ] + c * ( vs30 [ idx ] / C [ 'vlin' ] ) ** n ) ) ) return derAmp
def _match_dbname ( self , dbname ) : """Map a database name to the Cluster that holds the database . Args : dbname : A database name . Returns : A dict containing the information about the Cluster that holds the database ."""
for config in self . _clusters : if re . match ( config [ 'pattern' ] , dbname ) : return config raise Exception ( 'No such database %s.' % dbname )
def query_int_attribute ( self , target , display_mask , attr ) : """Return the value of an integer attribute"""
reply = NVCtrlQueryAttributeReplyRequest ( display = self . display , opcode = self . display . get_extension_major ( extname ) , target_id = target . id ( ) , target_type = target . type ( ) , display_mask = display_mask , attr = attr ) if not reply . _data . get ( 'flags' ) : return None return int ( reply . _dat...
def instruction_PAGE ( self , opcode ) : """call op from page 2 or 3"""
op_address , opcode2 = self . read_pc_byte ( ) paged_opcode = opcode * 256 + opcode2 # log . debug ( " $ % x * * * call paged opcode $ % x " % ( # self . program _ counter , paged _ opcode self . call_instruction_func ( op_address - 1 , paged_opcode )
def step ( self ) : """Run the next child task and wait for completion ( no timeout ) ."""
if self . index >= len ( self . tasklist ) : raise TaskError ( "step(): sequential compound task %s finished" % self ) self . check_state ( ) # Select next task from the set and advance the index self . task = self . tasklist [ self . index ] self . index += 1 return self . runTask ( self . task )
def index_humansorted ( seq , key = None , reverse = False , alg = ns . DEFAULT ) : """This is a wrapper around ` ` index _ natsorted ( seq , alg = ns . LOCALE ) ` ` . Parameters seq : iterable The input to sort . key : callable , optional A key used to determine how to sort each element of the sequence ....
return index_natsorted ( seq , key , reverse , alg | ns . LOCALE )
def latencies ( self ) : """List [ Tuple [ : class : ` int ` , : class : ` float ` ] ] : A list of latencies between a HEARTBEAT and a HEARTBEAT _ ACK in seconds . This returns a list of tuples with elements ` ` ( shard _ id , latency ) ` ` ."""
return [ ( shard_id , shard . ws . latency ) for shard_id , shard in self . shards . items ( ) ]
def _begin_stream ( self , command : Command ) : '''Start data stream transfer .'''
begin_reply = yield from self . _commander . begin_stream ( command ) self . _response . reply = begin_reply self . event_dispatcher . notify ( self . Event . begin_transfer , self . _response )
def shut_down ( ) : """Closes connection and restores terminal"""
curses . nocbreak ( ) curses . echo ( ) curses . endwin ( ) gpsd_socket . close ( ) print ( 'Keyboard interrupt received\nTerminated by user\nGood Bye.\n' ) sys . exit ( 1 )
def print_page_cb ( self , print_op , print_context , keep_refs = { } ) : """Called for printing operation by Gtk"""
ORIENTATION_PORTRAIT = 0 ORIENTATION_LANDSCAPE = 1 scaling = 2.0 img = self . img ( width , height ) = img . size # take care of rotating the image if required if print_context . get_width ( ) <= print_context . get_height ( ) : print_orientation = ORIENTATION_PORTRAIT else : print_orientation = ORIENTATION_LAN...
def index_of_nearest ( p , hot_points , distance_f = distance ) : """Given a point and a set of hot points it found the hot point nearest to the given point . An arbitrary distance function can be specified : return the index of the nearest hot points , or None if the list of hot points is empty"""
min_dist = None nearest_hp_i = None for i , hp in enumerate ( hot_points ) : dist = distance_f ( p , hp ) if min_dist is None or dist < min_dist : min_dist = dist nearest_hp_i = i return nearest_hp_i
def displayStatusMessage ( self , msgObj ) : """Display the last status message and partially completed key sequences . | Args | * ` ` msgObj ` ` ( * * QtmacsMessage * * ) : the data supplied by the hook . | Returns | * * * None * * | Raises | * * * None * *"""
# Ensure the message ends with a newline character . msg = msgObj . data if not msg . endswith ( '\n' ) : msg = msg + '\n' # Display the message in the status field . self . qteLabel . setText ( msg )
def clip_datetime ( dt , tz = DEFAULT_TZ , is_dst = None ) : """Limit a datetime to a valid range for datetime , datetime64 , and Timestamp objects > > > from datetime import timedelta > > > clip _ datetime ( MAX _ DATETIME + timedelta ( 100 ) ) = = pd . Timestamp ( MAX _ DATETIME , tz = ' utc ' ) = = MAX _ TIM...
if isinstance ( dt , datetime . datetime ) : # TODO : this gives up a day of datetime range due to assumptions about timezone # make MIN / MAX naive and replace dt . replace ( tz = None ) before comparison # set it back when done dt = make_tz_aware ( dt , tz = tz , is_dst = is_dst ) try : return pd . Ti...
def register_segment_dcnm ( self , cfg , seg_id_min , seg_id_max ) : """Register segmentation id pool with DCNM ."""
orch_id = cfg . dcnm . orchestrator_id try : segid_range = self . dcnm_client . get_segmentid_range ( orch_id ) if segid_range is None : self . dcnm_client . set_segmentid_range ( orch_id , seg_id_min , seg_id_max ) else : conf_min , _ , conf_max = segid_range [ "segmentIdRanges" ] . partiti...
def read_targets ( targets ) : """Reads generic key - value pairs from input files"""
results = { } for target , regexer in regexer_for_targets ( targets ) : with open ( target ) as fh : results . update ( extract_keypairs ( fh . readlines ( ) , regexer ) ) return results
def resolve ( self , key ) : """Resolve a key to a factory . Attempts to resolve explicit bindings and entry points , preferring explicit bindings . : raises NotBoundError : if the key cannot be resolved"""
try : return self . _resolve_from_binding ( key ) except NotBoundError : return self . _resolve_from_entry_point ( key )
def get_server_capabilities ( self ) : """Get hardware properties which can be used for scheduling : return : a dictionary of server capabilities . : raises : IloError , on an error from iLO . : raises : IloCommandNotSupportedError , if the command is not supported on the server ."""
capabilities = self . _call_method ( 'get_server_capabilities' ) # TODO ( nisha ) : Assumption is that Redfish always see the pci _ device # member name field populated similarly to IPMI . # If redfish is not able to get nic _ capacity , we can fall back to # IPMI way of retrieving nic _ capacity in the future . As of ...
def qteImportModule ( self , fileName : str ) : """Import ` ` fileName ` ` at run - time . If ` ` fileName ` ` has no path prefix then it must be in the standard Python module path . Relative path names are possible . | Args | * ` ` fileName ` ` ( * * str * * ) : file name ( with full path ) of module to ...
# Split the absolute file name into the path - and file name . path , name = os . path . split ( fileName ) name , ext = os . path . splitext ( name ) # If the file name has a path prefix then search there , otherwise # search the default paths for Python . if path == '' : path = sys . path else : path = [ path...
def AFF4Path ( self , client_urn ) : """Returns the AFF4 URN this pathspec will be stored under . Args : client _ urn : A ClientURN . Returns : A urn that corresponds to this pathspec . Raises : ValueError : If pathspec is not of the correct type ."""
# If the first level is OS and the second level is TSK its probably a mount # point resolution . We map it into the tsk branch . For example if we get : # path : \ \ \ \ . \ \ Volume { 1234 } \ \ # pathtype : OS # mount _ point : / c : / # nested _ path { # path : / windows / # pathtype : TSK # We map this to aff4 : / ...
def add_menu_items_for_pages ( self , pagequeryset = None , allow_subnav = True ) : """Add menu items to this menu , linking to each page in ` pagequeryset ` ( which should be a PageQuerySet instance )"""
item_manager = self . get_menu_items_manager ( ) item_class = item_manager . model item_list = [ ] i = item_manager . count ( ) for p in pagequeryset . all ( ) : item_list . append ( item_class ( menu = self , link_page = p , sort_order = i , allow_subnav = allow_subnav ) ) i += 1 item_manager . bulk_create ( i...
def extract ( self , file_obj , extractOnly = True , handler = 'update/extract' , ** kwargs ) : """POSTs a file to the Solr ExtractingRequestHandler so rich content can be processed using Apache Tika . See the Solr wiki for details : http : / / wiki . apache . org / solr / ExtractingRequestHandler The Extract...
if not hasattr ( file_obj , "name" ) : raise ValueError ( "extract() requires file-like objects which have a defined name property" ) params = { "extractOnly" : "true" if extractOnly else "false" , "lowernames" : "true" , "wt" : "json" , } params . update ( kwargs ) filename = quote ( file_obj . name . encode ( 'ut...
def add_results ( self , * rvs , ** kwargs ) : """Changes the state to reflect the mutation which yielded the given result . In order to use the result , the ` fetch _ mutation _ tokens ` option must have been specified in the connection string , _ and _ the result must have been successful . : param rvs ...
if not rvs : raise MissingTokenError . pyexc ( message = 'No results passed' ) for rv in rvs : mi = rv . _mutinfo if not mi : if kwargs . get ( 'quiet' ) : return False raise MissingTokenError . pyexc ( message = 'Result does not contain token' ) self . _add_scanvec ( mi ) re...
def get_members_of_group ( self , gname ) : """Get all members of a group which name is given in parameter : param gname : name of the group : type gname : str : return : list of contacts in the group : rtype : list [ alignak . objects . contact . Contact ]"""
contactgroup = self . find_by_name ( gname ) if contactgroup : return contactgroup . get_contacts ( ) return [ ]
def create ( cls , name , md5_password = None , connect_retry = 120 , session_hold_timer = 180 , session_keep_alive = 60 ) : """Create a new BGP Connection Profile . : param str name : name of profile : param str md5 _ password : optional md5 password : param int connect _ retry : The connect retry timer , in...
json = { 'name' : name , 'connect' : connect_retry , 'session_hold_timer' : session_hold_timer , 'session_keep_alive' : session_keep_alive } if md5_password : json . update ( md5_password = md5_password ) return ElementCreator ( cls , json )
def get_report_rst ( self ) : """formats the project into a report in RST format"""
res = '' res += '-----------------------------------\n' res += self . nme + '\n' res += '-----------------------------------\n\n' res += self . desc + '\n' res += self . fldr + '\n\n' res += '.. contents:: \n\n\n' res += 'Overview\n' + '===========================================\n\n' res += 'This document contains det...
def grid ( self , ** kw ) : """Position a widget in the parent widget in a grid . : param column : use cell identified with given column ( starting with 0) : type column : int : param columnspan : this widget will span several columns : type columnspan : int : param in \ _ : widget to use as container :...
ttk . Scrollbar . grid ( self , ** kw ) self . _layout = 'grid'
def compare ( molecules , ensemble_lookup , options ) : """compare stuff : param molecules : : param ensemble _ lookup : : param options : : return :"""
print ( " Analyzing differences ... " ) print ( '' ) sort_order = classification . get_sort_order ( molecules ) ensemble1 = sorted ( ensemble_lookup . keys ( ) ) [ 0 ] ensemble2 = sorted ( ensemble_lookup . keys ( ) ) [ 1 ] stats = { } stats [ 'header' ] = [ ' ' ] name = os . path . basename ( ensemble1 ) . replace ( '...
def _encrypt_assertion ( self , encrypt_cert , sp_entity_id , response , node_xpath = None ) : """Encryption of assertions . : param encrypt _ cert : Certificate to be used for encryption . : param sp _ entity _ id : Entity ID for the calling service provider . : param response : A samlp . Response : param ...
_certs = [ ] if encrypt_cert : _certs . append ( encrypt_cert ) elif sp_entity_id is not None : _certs = self . metadata . certs ( sp_entity_id , "any" , "encryption" ) exception = None for _cert in _certs : try : begin_cert = "-----BEGIN CERTIFICATE-----\n" end_cert = "\n-----END CERTIFICAT...
def _merge_similar ( loci , loci_similarity ) : """Internal function to reduce loci complexity : param loci : class cluster : param locilen _ sorted : list of loci sorted by size : return c : updated class cluster"""
n_cluster = 0 internal_cluster = { } clus_seen = { } loci_sorted = sorted ( loci_similarity . iteritems ( ) , key = operator . itemgetter ( 1 ) , reverse = True ) for pairs , sim in loci_sorted : common = sim > parameters . similar n_cluster += 1 logger . debug ( "_merge_similar:try new cluster %s" % n_clus...
def open_stream ( self , destination , timeout_ms = None ) : """Opens a new stream to a destination service on the device . Not the same as the posix ' open ' or any other Open methods , this corresponds to the OPEN message described in the ADB protocol documentation mentioned above . It creates a stream ( un...
timeout = timeouts . PolledTimeout . from_millis ( timeout_ms ) stream_transport = self . _make_stream_transport ( ) self . transport . write_message ( adb_message . AdbMessage ( command = 'OPEN' , arg0 = stream_transport . local_id , arg1 = 0 , data = destination + '\0' ) , timeout ) if not stream_transport . ensure_o...
def asset_class ( self ) -> str : """Returns the full asset class path for this stock"""
result = self . parent . name if self . parent else "" # Iterate to the top asset class and add names . cursor = self . parent while cursor : result = cursor . name + ":" + result cursor = cursor . parent return result
def set_property ( self , prop , objects ) : """Add a property to the definition and set its ` ` objects ` ` ."""
self . _properties . add ( prop ) objects = set ( objects ) self . _objects |= objects pairs = self . _pairs for o in self . _objects : if o in objects : pairs . add ( ( o , prop ) ) else : pairs . discard ( ( o , prop ) )
def build_homogeneisation_vehicules ( temporary_store = None , year = None ) : assert temporary_store is not None """Compute vehicule numbers by type"""
assert year is not None # Load data bdf_survey_collection = SurveyCollection . load ( collection = 'budget_des_familles' , config_files_directory = config_files_directory ) survey = bdf_survey_collection . get_survey ( 'budget_des_familles_{}' . format ( year ) ) if year == 1995 : vehicule = None # L ' enquête BdF...
def connect ( args ) : """% prog connect assembly . fasta read _ mapping . blast Connect contigs using long reads ."""
p = OptionParser ( connect . __doc__ ) p . add_option ( "--clip" , default = 2000 , type = "int" , help = "Only consider end of contigs [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , blastfile = args clip = opts . clip sizes = Si...
def create_shield_layer ( shield , hashcode ) : """Creates the layer for shields ."""
return pgnreader . parse_pagan_file ( ( '%s%spgn%s' % ( PACKAGE_DIR , os . sep , os . sep ) ) + shield + '.pgn' , hashcode , sym = False , invert = False )
def create_plan ( existing_users = None , proposed_users = None , purge_undefined = None , protected_users = None , allow_non_unique_id = None , manage_home = True , manage_keys = True ) : """Determine what changes are required . args : existing _ users ( Users ) : List of discovered users proposed _ users ( ...
plan = list ( ) proposed_usernames = list ( ) if not purge_undefined : purge_undefined = constants . PURGE_UNDEFINED if not protected_users : protected_users = constants . PROTECTED_USERS if not allow_non_unique_id : allow_non_unique_id = constants . ALLOW_NON_UNIQUE_ID # Create list of modifications to mak...
def _message_callback ( self , msg ) : """Callback function to handle incoming MIDI messages ."""
if msg . type == 'polytouch' : button = button_from_press ( msg . note ) if button : self . on_button ( button , msg . value != 0 ) elif msg . note == 127 : self . on_fader_touch ( msg . value != 0 ) elif msg . type == 'control_change' and msg . control == 0 : self . _msb = msg . value e...
def _prep_bins ( ) : """Support for running straight out of a cloned source directory instead of an installed distribution"""
from os import path from sys import platform , maxsize from shutil import copy bit_suffix = "-x86_64" if maxsize > 2 ** 32 else "-x86" package_root = path . abspath ( path . dirname ( __file__ ) ) prebuilt_path = path . join ( package_root , "prebuilt" , platform + bit_suffix ) config = { "MANIFEST_DIR" : prebuilt_path...
def _ascii2 ( value ) : """A variant of the ` ascii ( ) ` built - in function known from Python 3 that : (1 ) ensures ASCII - only output , and (2 ) produces a nicer formatting for use in exception and warning messages and other human consumption . This function calls ` ascii ( ) ` and post - processes its ...
if isinstance ( value , Mapping ) : # NocaseDict in current impl . is not a Mapping ; it uses # its own repr ( ) implementation ( via ascii ( ) , called further down ) items = [ _ascii2 ( k ) + ": " + _ascii2 ( v ) for k , v in six . iteritems ( value ) ] item_str = "{" + ", " . join ( items ) + "}" if valu...
def makeringlatticeCIJ ( n , k , seed = None ) : '''This function generates a directed lattice network with toroidal boundary counditions ( i . e . with ring - like " wrapping around " ) . Parameters N : int number of vertices K : int number of edges seed : hashable , optional If None ( default ) , ...
rng = get_rng ( seed ) # initialize CIJ = np . zeros ( ( n , n ) ) CIJ1 = np . ones ( ( n , n ) ) kk = 0 count = 0 seq = range ( 1 , n ) seq2 = range ( n - 1 , 0 , - 1 ) # fill in while kk < k : count += 1 dCIJ = np . triu ( CIJ1 , seq [ count ] ) - np . triu ( CIJ1 , seq [ count ] + 1 ) dCIJ2 = np . triu (...
def cybox_RAW_ft_handler ( self , enrichment , fact , attr_info , add_fact_kargs ) : """Handler for facts whose content is to be written to disk rather than stored in the database . We use it for all elements that contain the string ' Raw _ ' ( ' Raw _ Header ' , ' Raw _ Artifact ' , . . . )"""
# get the value raw_value = add_fact_kargs [ 'values' ] [ 0 ] if len ( raw_value ) >= RAW_DATA_TO_DB_FOR_LENGTH_LESS_THAN : # rewrite the argument for the creation of the fact : there are # no values to be added to the database ( value_hash , storage_location ) = write_large_value ( raw_value , dingos . DINGOS_LARG...