signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_port_profile_for_intf_input_rbridge_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_port_profile_for_intf = ET . Element ( "get_port_profile_for_intf" ) config = get_port_profile_for_intf input = ET . SubElement ( get_port_profile_for_intf , "input" ) rbridge_id = ET . SubElement ( input , "rbridge-id" ) rbridge_id . text = kwargs . pop ( 'rbridge_id' ) callback ...
def table_spec_path ( cls , project , location , dataset , table_spec ) : """Return a fully - qualified table _ spec string ."""
return google . api_core . path_template . expand ( "projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}" , project = project , location = location , dataset = dataset , table_spec = table_spec , )
def cli ( ctx , email , first_name , last_name , password , role = "user" , metadata = { } ) : """Create a new user Output : an empty dictionary"""
return ctx . gi . users . create_user ( email , first_name , last_name , password , role = role , metadata = metadata )
def nearest_vertices ( self , lon , lat , k = 1 , max_distance = 2.0 ) : """Query the cKDtree for the nearest neighbours and Euclidean distance from x , y points . Returns 0 , 0 if a cKDtree has not been constructed ( switch tree = True if you need this routine ) Parameters lon : 1D array of longitudinal ...
if self . tree == False or self . tree == None : return 0 , 0 lons = np . array ( lon ) . reshape ( - 1 , 1 ) lats = np . array ( lat ) . reshape ( - 1 , 1 ) xyz = np . empty ( ( lons . shape [ 0 ] , 3 ) ) x , y , z = lonlat2xyz ( lons , lats ) xyz [ : , 0 ] = x [ : ] . reshape ( - 1 ) xyz [ : , 1 ] = y [ : ] . res...
async def reset ( self , von_wallet : Wallet , seed : str = None ) -> Wallet : """Close and delete ( open ) VON anchor wallet and then create , open , and return replacement on current link secret . Note that this operation effectively destroys private keys for keyed data structures such as credential offers ...
LOGGER . debug ( 'WalletManager.reset >>> von_wallet %s' , von_wallet ) if not von_wallet . handle : LOGGER . debug ( 'WalletManager.reset <!< Wallet %s is closed' , von_wallet . name ) raise WalletState ( 'Wallet {} is closed' . format ( von_wallet . name ) ) w_config = von_wallet . config # wallet under reset...
def insert_slash ( string , every = 2 ) : """insert _ slash insert / every 2 char"""
return os . path . join ( string [ i : i + every ] for i in xrange ( 0 , len ( string ) , every ) )
def _set_access_log ( self , config , level ) : """Configure access logs"""
access_handler = self . _get_param ( 'global' , 'log.access_handler' , config , 'syslog' , ) # log format for syslog syslog_formatter = logging . Formatter ( "ldapcherry[%(process)d]: %(message)s" ) # replace access log handler by a syslog handler if access_handler == 'syslog' : cherrypy . log . access_log . handle...
def prepare_migration_target ( self , uuid , nics = None , port = None , tags = None ) : """: param name : Name of the kvm domain that will be migrated : param port : A dict of host _ port : container _ port pairs Example : ` port = { 8080 : 80 , 7000:7000 } ` Only supported if default network is used : p...
if nics is None : nics = [ ] args = { 'nics' : nics , 'port' : port , 'uuid' : uuid } self . _migrate_network_chk . check ( args ) self . _client . sync ( 'kvm.prepare_migration_target' , args , tags = tags )
def compute_Pi_JinsDJ_given_D ( self , CDR3_seq , Pi_J_given_D , max_J_align ) : """Compute Pi _ JinsDJ conditioned on D . This function returns the Pi array from the model factors of the J genomic contributions , P ( D , J ) * P ( delJ | J ) , and the DJ ( N2 ) insertions , first _ nt _ bias _ insDJ ( n _ 1 ...
# max _ insertions = 30 # len ( PinsVD ) - 1 should zeropad the last few spots max_insertions = len ( self . PinsDJ ) - 1 Pi_JinsDJ_given_D = [ np . zeros ( ( 4 , len ( CDR3_seq ) * 3 ) ) for i in range ( len ( Pi_J_given_D ) ) ] for D_in in range ( len ( Pi_J_given_D ) ) : # start position is first nt in a codon f...
def get_filter_solvers ( self , filter_ ) : """Returns the filter solvers that can solve the given filter . Arguments filter : dataql . resources . BaseFilter An instance of the a subclass of ` ` BaseFilter ` ` for which we want to get the solver classes that can solve it . Returns list The list of fi...
solvers_classes = [ s for s in self . filter_solver_classes if s . can_solve ( filter_ ) ] if solvers_classes : solvers = [ ] for solver_class in solvers_classes : # Put the solver instance in the cache if not cached yet . if solver_class not in self . _filter_solvers_cache : self . _filter_...
def resource_to_url ( resource , request = None , quote = False ) : """Converts the given resource to a URL . : param request : Request object ( required for the host name part of the URL ) . If this is not given , the current request is used . : param bool quote : If set , the URL returned will be quoted .""...
if request is None : request = get_current_request ( ) # cnv = request . registry . getAdapter ( request , IResourceUrlConverter ) reg = get_current_registry ( ) cnv = reg . getAdapter ( request , IResourceUrlConverter ) return cnv . resource_to_url ( resource , quote = quote )
def page_templates_loading_check ( app_configs , ** kwargs ) : """Check if any page template can ' t be loaded ."""
errors = [ ] for page_template in settings . get_page_templates ( ) : try : loader . get_template ( page_template [ 0 ] ) except template . TemplateDoesNotExist : errors . append ( checks . Warning ( 'Django cannot find template %s' % page_template [ 0 ] , obj = page_template , id = 'pages.W001'...
def _set_Cpu ( self , v , load = False ) : """Setter method for Cpu , mapped from YANG variable / rbridge _ id / threshold _ monitor / Cpu ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ Cpu is considered as a private method . Backends looking to populat...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = Cpu . Cpu , is_container = 'container' , presence = False , yang_name = "Cpu" , rest_name = "Cpu" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { ...
def aldb_device_handled ( self , addr ) : """Remove device from ALDB device list ."""
if isinstance ( addr , Address ) : remove_addr = addr . id else : remove_addr = addr try : self . _aldb_devices . pop ( remove_addr ) _LOGGER . debug ( 'Removed ALDB device %s' , remove_addr ) except KeyError : _LOGGER . debug ( 'Device %s not in ALDB device list' , remove_addr ) _LOGGER . debug ( '...
def parse ( celf , s ) : "generates an Introspection tree from the given XML string description ."
def from_string_elts ( celf , attrs , tree ) : elts = dict ( ( k , attrs [ k ] ) for k in attrs ) child_tags = dict ( ( childclass . tag_name , childclass ) for childclass in tuple ( celf . tag_elts . values ( ) ) + ( Introspection . Annotation , ) ) children = [ ] for child in tree : if child ....
def get_gradebook_column_summary ( self , gradebook_column_id ) : """Gets the ` ` GradebookColumnSummary ` ` for summary results . arg : gradebook _ column _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` GradebookColumn ` ` return : ( osid . grading . GradebookColumnSummary ) - the gradebook column summary ...
gradebook_column = self . get_gradebook_column ( gradebook_column_id ) summary_map = gradebook_column . _my_map summary_map [ 'gradebookColumnId' ] = str ( gradebook_column . ident ) return GradebookColumnSummary ( osid_object_map = summary_map , runtime = self . _runtime , proxy = self . _proxy )
def build ( dburl , sitedir , mode ) : """Build a site ."""
if mode == 'force' : amode = [ '-a' ] else : amode = [ ] oldcwd = os . getcwd ( ) os . chdir ( sitedir ) db = StrictRedis . from_url ( dburl ) job = get_current_job ( db ) job . meta . update ( { 'out' : '' , 'milestone' : 0 , 'total' : 1 , 'return' : None , 'status' : None } ) job . save ( ) p = subprocess . P...
def check_abundance ( number ) : """Determine if a given number is abundant . A number is considered abundant if the sum of its divisors is greater than the number itself . Examples : check _ abundance ( 12 ) - > True check _ abundance ( 13 ) - > False check _ abundance ( 9 ) - > False : param number : ...
sum_of_divisors = sum ( divisor for divisor in range ( 1 , number ) if number % divisor == 0 ) return sum_of_divisors > number
def from_array ( array ) : """Deserialize a new CallbackQuery from a given dictionary . : return : new CallbackQuery instance . : rtype : CallbackQuery"""
if array is None or not array : return None # end if assert_type_or_raise ( array , dict , parameter_name = "array" ) from . . receivable . peer import User data = { } data [ 'id' ] = u ( array . get ( 'id' ) ) data [ 'from_peer' ] = User . from_array ( array . get ( 'from' ) ) data [ 'chat_instance' ] = u ( array ...
def paste ( ** kwargs ) : """Returns system clipboard contents ."""
window = Tk ( ) window . withdraw ( ) d = window . selection_get ( selection = 'CLIPBOARD' ) return d
def _get_importer ( path_name ) : """Python version of PyImport _ GetImporter C API function"""
cache = sys . path_importer_cache try : importer = cache [ path_name ] except KeyError : # Not yet cached . Flag as using the # standard machinery until we finish # checking the hooks cache [ path_name ] = None for hook in sys . path_hooks : try : importer = hook ( path_name ) ...
def is_obsoletes_pid ( pid ) : """Return True if ` ` pid ` ` is referenced in the obsoletes field of any object . This will return True even if the PID is in the obsoletes field of an object that does not exist on the local MN , such as replica that is in an incomplete chain ."""
return d1_gmn . app . models . ScienceObject . objects . filter ( obsoletes__did = pid ) . exists ( )
def root_namespace ( self , value ) : """Setter for * * self . _ _ root _ namespace * * attribute . : param value : Attribute value . : type value : unicode"""
if value is not None : assert type ( value ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "root_namespace" , value ) self . __root_namespace = value
def updateIncomeProcess ( self ) : '''An alternative method for constructing the income process in the infinite horizon model . Parameters none Returns none'''
if self . cycles == 0 : tax_rate = ( self . IncUnemp * self . UnempPrb ) / ( ( 1.0 - self . UnempPrb ) * self . IndL ) TranShkDstn = deepcopy ( approxMeanOneLognormal ( self . TranShkCount , sigma = self . TranShkStd [ 0 ] , tail_N = 0 ) ) TranShkDstn [ 0 ] = np . insert ( TranShkDstn [ 0 ] * ( 1.0 - self ....
def subtract ( lhs , rhs ) : """Returns element - wise difference of the input arrays with broadcasting . Equivalent to ` ` lhs - rhs ` ` , ` ` mx . nd . broadcast _ sub ( lhs , rhs ) ` ` and ` ` mx . nd . broadcast _ minus ( lhs , rhs ) ` ` when shapes of lhs and rhs do not match . If lhs . shape = = rhs . s...
# pylint : disable = no - member , protected - access if isinstance ( lhs , NDArray ) and isinstance ( rhs , NDArray ) and lhs . shape == rhs . shape : return _ufunc_helper ( lhs , rhs , op . elemwise_sub , operator . sub , _internal . _minus_scalar , None ) return _ufunc_helper ( lhs , rhs , op . broadcast_sub , o...
def __get_update_uri ( self , account_id , ** kwargs ) : """Call documentation : ` / account / get _ update _ uri < https : / / www . wepay . com / developer / reference / account # update _ uri > ` _ , plus extra keyword parameters : : keyword str access _ token : will be used instead of instance ' s ` ` a...
params = { 'account_id' : account_id } return self . make_call ( self . __get_update_uri , params , kwargs )
def get_files ( * bases ) : """List all files in a data directory ."""
for base in bases : basedir , _ = base . split ( "." , 1 ) base = os . path . join ( os . path . dirname ( __file__ ) , * base . split ( "." ) ) rem = len ( os . path . dirname ( base ) ) + len ( basedir ) + 2 for root , dirs , files in os . walk ( base ) : for name in files : yield ...
def sign_execute_deposit ( deposit_params , private_key , infura_url ) : """Function to execute the deposit request by signing the transaction generated from the create deposit function . Execution of this function is as follows : : sign _ execute _ deposit ( deposit _ params = create _ deposit , private _ key ...
create_deposit_upper = deposit_params . copy ( ) create_deposit_upper [ 'transaction' ] [ 'from' ] = to_checksum_address ( create_deposit_upper [ 'transaction' ] [ 'from' ] ) create_deposit_upper [ 'transaction' ] [ 'to' ] = to_checksum_address ( create_deposit_upper [ 'transaction' ] [ 'to' ] ) create_deposit_upper [ ...
def appendData ( self , content ) : """Add characters to the element ' s pcdata ."""
if self . pcdata is not None : self . pcdata += content else : self . pcdata = content
def __prepare_body ( self , search_value , search_type = 'url' ) : """Prepares the http body for querying safebrowsing api . Maybe the list need to get adjusted . : param search _ value : value to search for : type search _ value : str : param search _ type : ' url ' or ' ip ' : type search _ type : str :...
body = { 'client' : { 'clientId' : self . client_id , 'clientVersion' : self . client_version } } if search_type == 'url' : data = { 'threatTypes' : [ 'MALWARE' , 'SOCIAL_ENGINEERING' , 'UNWANTED_SOFTWARE' , 'POTENTIALLY_HARMFUL_APPLICATION' ] , 'platformTypes' : [ 'ANY_PLATFORM' , 'ALL_PLATFORMS' , 'WINDOWS' , 'LI...
def shift_fn ( self , i , pre_dl = None , post_dl = None ) : """Press Shift + Fn1 ~ 12 once . * * 中文文档 * * 按下 Shift + Fn1 ~ 12 组合键 。"""
self . delay ( pre_dl ) self . k . press_key ( self . k . shift_key ) self . k . tap_key ( self . k . function_keys [ i ] ) self . k . release_key ( self . k . shift_key ) self . delay ( post_dl )
def rewrite_elife_title_prefix_json ( json_content , doi ) : """this does the work of rewriting elife title prefix json values"""
if not json_content : return json_content # title prefix rewrites by article DOI title_prefix_values = { } title_prefix_values [ "10.7554/eLife.00452" ] = "Point of View" title_prefix_values [ "10.7554/eLife.00615" ] = "Point of View" title_prefix_values [ "10.7554/eLife.00639" ] = "Point of View" title_prefix_valu...
def _raise_error_if_disconnected ( self ) -> None : """See if we ' re still connected , and if not , raise ` ` SMTPServerDisconnected ` ` ."""
if ( self . transport is None or self . protocol is None or self . transport . is_closing ( ) ) : self . close ( ) raise SMTPServerDisconnected ( "Disconnected from SMTP server" )
def msetnx ( self , * args , ** kwargs ) : """Sets key / values based on a mapping if none of the keys are already set . Mapping can be supplied as a single dictionary argument or as kwargs . Returns a boolean indicating if the operation was successful ."""
if args : if len ( args ) != 1 or not isinstance ( args [ 0 ] , dict ) : raise RedisError ( 'MSETNX requires **kwargs or a single dict arg' ) mapping = args [ 0 ] else : mapping = kwargs if len ( mapping ) == 0 : raise ResponseError ( "wrong number of arguments for 'msetnx' command" ) for key in...
def recoverTransaction ( self , serialized_transaction ) : '''Get the address of the account that signed this transaction . : param serialized _ transaction : the complete signed transaction : type serialized _ transaction : hex str , bytes or int : returns : address of signer , hex - encoded & checksummed ...
txn_bytes = HexBytes ( serialized_transaction ) txn = Transaction . from_bytes ( txn_bytes ) msg_hash = hash_of_signed_transaction ( txn ) return self . recoverHash ( msg_hash , vrs = vrs_from ( txn ) )
def get_family ( self ) : """Gets the ` ` Family ` ` associated with this session . return : ( osid . relationship . Family ) - the family raise : OperationFailed - unable to complete request raise : PermissionDenied - authorization failure * compliance : mandatory - - This method must be implemented . *"""
return FamilyLookupSession ( proxy = self . _proxy , runtime = self . _runtime ) . get_family ( self . _family_id )
def recode ( inlist , listmap , cols = None ) : """Changes the values in a list to a new set of values ( useful when you need to recode data from ( e . g . ) strings to numbers . cols defaults to None ( meaning all columns are recoded ) . Usage : recode ( inlist , listmap , cols = None ) cols = recode cols , ...
lst = copy . deepcopy ( inlist ) if cols != None : if type ( cols ) not in [ ListType , TupleType ] : cols = [ cols ] for col in cols : for row in range ( len ( lst ) ) : try : idx = colex ( listmap , 0 ) . index ( lst [ row ] [ col ] ) lst [ row ] [ c...
def flush ( self ) : """Flush message queue if there ' s an active connection running"""
self . _pending_flush = False if self . handler is None : return if self . send_queue . is_empty ( ) : return self . handler . send_pack ( 'a[%s]' % self . send_queue . get ( ) ) self . send_queue . clear ( )
def unmapped ( sam , mates ) : """get unmapped reads"""
for read in sam : if read . startswith ( '@' ) is True : continue read = read . strip ( ) . split ( ) if read [ 2 ] == '*' and read [ 6 ] == '*' : yield read elif mates is True : if read [ 2 ] == '*' or read [ 6 ] == '*' : yield read for i in read : ...
def cross_product_matrix ( vec ) : """Returns a 3x3 cross - product matrix from a 3 - element vector ."""
return np . array ( [ [ 0 , - vec [ 2 ] , vec [ 1 ] ] , [ vec [ 2 ] , 0 , - vec [ 0 ] ] , [ - vec [ 1 ] , vec [ 0 ] , 0 ] ] )
def _tree_line ( self , no_type : bool = False ) -> str : """Return the receiver ' s contribution to tree diagram ."""
return super ( ) . _tree_line ( ) + ( "!" if self . presence else "" )
def update ( self , unique_name = values . unset , callback_method = values . unset , callback_url = values . unset , friendly_name = values . unset , rate_plan = values . unset , status = values . unset , commands_callback_method = values . unset , commands_callback_url = values . unset , sms_fallback_method = values ...
data = values . of ( { 'UniqueName' : unique_name , 'CallbackMethod' : callback_method , 'CallbackUrl' : callback_url , 'FriendlyName' : friendly_name , 'RatePlan' : rate_plan , 'Status' : status , 'CommandsCallbackMethod' : commands_callback_method , 'CommandsCallbackUrl' : commands_callback_url , 'SmsFallbackMethod' ...
def generate_PJdelJ_nt_pos_vecs ( self , generative_model , genomic_data ) : """Process P ( J ) * P ( delJ | J ) into Pi arrays . Sets the attributes PJdelJ _ nt _ pos _ vec and PJdelJ _ 2nd _ nt _ pos _ per _ aa _ vec . Parameters generative _ model : GenerativeModelVDJ VDJ generative model class containin...
cutJ_genomic_CDR3_segs = genomic_data . cutJ_genomic_CDR3_segs nt2num = { 'A' : 0 , 'C' : 1 , 'G' : 2 , 'T' : 3 } num_del_pos = generative_model . PdelJ_given_J . shape [ 0 ] num_D_genes , num_J_genes = generative_model . PDJ . shape PJ = np . sum ( generative_model . PDJ , axis = 0 ) PJdelJ_nt_pos_vec = [ [ ] ] * num_...
def run_selection ( self ) : """Run selected text or current line in console . If some text is selected , then execute that text in console . If no text is selected , then execute current line , unless current line is empty . Then , advance cursor to next line . If cursor is on last line and that line is no...
text = self . get_current_editor ( ) . get_selection_as_executable_code ( ) if text : self . exec_in_extconsole . emit ( text . rstrip ( ) , self . focus_to_editor ) return editor = self . get_current_editor ( ) line = editor . get_current_line ( ) text = line . lstrip ( ) if text : self . exec_in_extconsol...
async def grant ( self , acl = 'login' ) : """Set access level of this user on the controller . : param str acl : Access control ( ' login ' , ' add - model ' , or ' superuser ' )"""
if await self . controller . grant ( self . username , acl ) : self . _user_info . access = acl
def update_notes ( self , ** kwargs ) : """Updates the notes on the subscription without generating a change This endpoint also allows you to update custom fields : sub . custom _ fields [ 0 ] . value = ' A new value ' sub . update _ notes ( )"""
for key , val in iteritems ( kwargs ) : setattr ( self , key , val ) url = urljoin ( self . _url , '/notes' ) self . put ( url )
def MakePmf ( self , xs , name = '' ) : """Makes a discrete version of this Pdf , evaluated at xs . xs : equally - spaced sequence of values Returns : new Pmf"""
pmf = Pmf ( name = name ) for x in xs : pmf . Set ( x , self . Density ( x ) ) pmf . Normalize ( ) return pmf
def _threaded ( self , * args , ** kwargs ) : """Call the target and put the result in the Queue ."""
for target in self . targets : result = target ( * args , ** kwargs ) self . queue . put ( result )
def _optimize_A ( self , A ) : """Find optimal transformation matrix A by minimization . Parameters A : ndarray The transformation matrix A . Returns A : ndarray The transformation matrix ."""
right_eigenvectors = self . right_eigenvectors_ [ : , : self . n_macrostates ] flat_map , square_map = get_maps ( A ) alpha = to_flat ( 1.0 * A , flat_map ) def obj ( x ) : return - 1 * self . _objective_function ( x , self . transmat_ , right_eigenvectors , square_map , self . populations_ ) alpha = scipy . optimi...
def filter ( self , table , vg_snapshots , filter_string ) : """Naive case - insensitive search ."""
query = filter_string . lower ( ) return [ vg_snapshot for vg_snapshot in vg_snapshots if query in vg_snapshot . name . lower ( ) ]
def _approxaAInv ( self , Or , Op , Oz , ar , ap , az , interp = True ) : """NAME : _ approxaAInv PURPOSE : return R , vR , . . . coordinates for a point based on the linear approximation around the stream track INPUT : Or , Op , Oz , ar , ap , az - phase space coordinates in frequency - angle space ...
if isinstance ( Or , ( int , float , numpy . float32 , numpy . float64 ) ) : # Scalar input Or = numpy . array ( [ Or ] ) Op = numpy . array ( [ Op ] ) Oz = numpy . array ( [ Oz ] ) ar = numpy . array ( [ ar ] ) ap = numpy . array ( [ ap ] ) az = numpy . array ( [ az ] ) # Calculate apar , angle...
def delete_object_in_seconds ( self , obj , seconds , extra_info = None ) : """Sets the object in this container to be deleted after the specified number of seconds . The ' extra _ info ' parameter is included for backwards compatibility . It is no longer used at all , and will not be modified with swiftclien...
return self . manager . delete_object_in_seconds ( self , obj , seconds )
def _ite ( lexer ) : """Return an ITE expression ."""
s = _impl ( lexer ) tok = next ( lexer ) # IMPL ' ? ' ITE ' : ' ITE if isinstance ( tok , OP_question ) : d1 = _ite ( lexer ) _expect_token ( lexer , { OP_colon } ) d0 = _ite ( lexer ) return ( 'ite' , s , d1 , d0 ) # IMPL else : lexer . unpop_token ( tok ) return s
def expandScopesGet ( self , * args , ** kwargs ) : """Expand Scopes Return an expanded copy of the given scopeset , with scopes implied by any roles included . This call uses the GET method with an HTTP body . It remains only for backward compatibility . This method takes input : ` ` v1 / scopeset . json...
return self . _makeApiCall ( self . funcinfo [ "expandScopesGet" ] , * args , ** kwargs )
def prepare_jochem ( ctx , jochem , output , csoutput ) : """Process and filter jochem file to produce list of names for dictionary ."""
click . echo ( 'chemdataextractor.dict.prepare_jochem' ) for i , line in enumerate ( jochem ) : print ( 'JC%s' % i ) if line . startswith ( 'TM ' ) : if line . endswith ( ' @match=ci\n' ) : for tokens in _make_tokens ( line [ 3 : - 11 ] ) : output . write ( ' ' . join ( token...
def create_from_name_and_dictionary ( self , name , datas ) : """Return a populated object Parameter from dictionary datas"""
parameter = ObjectParameter ( ) self . set_common_datas ( parameter , name , datas ) if "optional" in datas : parameter . optional = to_boolean ( datas [ "optional" ] ) if "type" in datas : parameter . type = str ( datas [ "type" ] ) if "generic" in datas : parameter . generic = to_boolean ( datas [ "generi...
def update_annotations_on_build ( self , build_id , annotations ) : """set annotations on build object : param build _ id : str , id of build : param annotations : dict , annotations to set : return :"""
return self . adjust_attributes_on_object ( 'builds' , build_id , 'annotations' , annotations , self . _update_metadata_things )
def qos_rcv_queue_multicast_threshold_traffic_class0 ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) qos = ET . SubElement ( config , "qos" , xmlns = "urn:brocade.com:mgmt:brocade-qos" ) rcv_queue = ET . SubElement ( qos , "rcv-queue" ) multicast = ET . SubElement ( rcv_queue , "multicast" ) threshold = ET . SubElement ( multicast , "threshold" ) traffic_class0 = ET . SubElement ( th...
def _fit_position_tsmap ( self , name , ** kwargs ) : """Localize a source from its TS map ."""
prefix = kwargs . get ( 'prefix' , '' ) dtheta_max = kwargs . get ( 'dtheta_max' , 0.5 ) zmin = kwargs . get ( 'zmin' , - 3.0 ) kw = { 'map_size' : 2.0 * dtheta_max , 'write_fits' : kwargs . get ( 'write_fits' , False ) , 'write_npy' : kwargs . get ( 'write_npy' , False ) , 'use_pylike' : kwargs . get ( 'use_pylike' , ...
def import_oauth2_credentials ( filename = STORAGE_FILENAME ) : """Import OAuth 2.0 session credentials from storage file . Parameters filename ( str ) Name of storage file . Returns credentials ( dict ) All your app credentials and information imported from the configuration file ."""
with open ( filename , 'r' ) as storage_file : storage = safe_load ( storage_file ) # depending on OAuth 2.0 grant _ type , these values may not exist client_secret = storage . get ( 'client_secret' ) refresh_token = storage . get ( 'refresh_token' ) credentials = { 'access_token' : storage [ 'access_token' ] , 'cl...
def transfer_syntax ( UID = None , description = None ) : """Transfer Syntax UID < - > Description lookup . : param UID : Transfer Syntax UID , returns description : param description : Take the description of a transfer syntax and return its UID"""
transfer_syntax = { "1.2.840.10008.1.2" : "Implicit VR Endian: Default Transfer Syntax for DICOM" , "1.2.840.10008.1.2.1" : "Explicit VR Little Endian" , "1.2.840.10008.1.2.1.99" : "Deflated Explicit VR Big Endian" , "1.2.840.10008.1.2.2" : "Explicit VR Big Endian" , "1.2.840.10008.1.2.4.50" : "JPEG Baseline (Process 1...
def PrintResponse ( batch_job_helper , response_xml ) : """Prints the BatchJobService response . Args : batch _ job _ helper : a BatchJobHelper instance . response _ xml : a string containing a response from the BatchJobService ."""
response = batch_job_helper . ParseResponse ( response_xml ) if 'rval' in response [ 'mutateResponse' ] : for data in response [ 'mutateResponse' ] [ 'rval' ] : if 'errorList' in data : print 'Operation %s - FAILURE:' % data [ 'index' ] print '\terrorType=%s' % data [ 'errorList' ] [...
def _html_output ( self , normal_row , error_row , row_ender , help_text_html , errors_on_separate_row ) : """Extend BaseForm ' s helper function for outputting HTML . Used by as _ table ( ) , as _ ul ( ) , as _ p ( ) . Combines the HTML version of the main form ' s fields with the HTML content for any subforms...
parts = [ ] parts . append ( super ( XmlObjectForm , self ) . _html_output ( normal_row , error_row , row_ender , help_text_html , errors_on_separate_row ) ) def _subform_output ( subform ) : return subform . _html_output ( normal_row , error_row , row_ender , help_text_html , errors_on_separate_row ) for name , su...
def chimera_node_placer_2d ( m , n , t , scale = 1. , center = None , dim = 2 ) : """Generates a function that converts Chimera indices to x , y coordinates for a plot . Parameters m : int Number of rows in the Chimera lattice . n : int Number of columns in the Chimera lattice . t : int Size of the ...
import numpy as np tile_center = t // 2 tile_length = t + 3 # 1 for middle of cross , 2 for spacing between tiles # want the enter plot to fill in [ 0 , 1 ] when scale = 1 scale /= max ( m , n ) * tile_length - 3 grid_offsets = { } if center is None : center = np . zeros ( dim ) else : center = np . asarray ( c...
def _new_from_rft ( self , base_template , rft_file ) : """Append a new file from . rft entry to the journal . This instructs Revit to create a new model based on the provided . rft template . Args : base _ template ( str ) : new file journal template from rmj . templates rft _ file ( str ) : full path to...
self . _add_entry ( base_template ) self . _add_entry ( templates . NEW_FROM_RFT . format ( rft_file_path = rft_file , rft_file_name = op . basename ( rft_file ) ) )
def set_multi ( self , mappings , time = 100 , compress_level = - 1 ) : """Set multiple keys with its values on server . If a key is a ( key , cas ) tuple , insert as if cas ( key , value , cas ) had been called . : param mappings : A dict with keys / values : type mappings : dict : param time : Time in s...
mappings = mappings . items ( ) msg = [ ] for key , value in mappings : if isinstance ( key , tuple ) : key , cas = key else : cas = None if cas == 0 : # Like cas ( ) , if the cas value is 0 , treat it as compare - and - set against not # existing . command = 'addq' else : ...
def encode_batch ( self , inputBatch ) : """Encodes a whole batch of input arrays , without learning ."""
X = inputBatch encode = self . encode Y = np . array ( [ encode ( x ) for x in X ] ) return Y
def block ( seed ) : """Return block of normal random numbers Parameters seed : { None , int } The seed to generate the noise . sd Returns noise : numpy . ndarray Array of random numbers"""
num = SAMPLE_RATE * BLOCK_SIZE rng = RandomState ( seed % 2 ** 32 ) variance = SAMPLE_RATE / 2 return rng . normal ( size = num , scale = variance ** 0.5 )
def make_worlist_trie ( wordlist ) : """Creates a nested dictionary representing the trie created by the given word list . : param wordlist : str list : : return : nested dictionary > > > make _ worlist _ trie ( [ ' einander ' , ' einen ' , ' neben ' ] ) { ' e ' : { ' i ' : { ' n ' : { ' a ' : { ' n ' : {...
dicts = dict ( ) for w in wordlist : curr = dicts for l in w : curr = curr . setdefault ( l , { } ) curr [ '__end__' ] = '__end__' return dicts
def on_complete ( cls , req ) : """Callback called when the request to REST is done . Handles the errors and if there is none , : class : ` . OutputPicker ` is shown ."""
# handle http errors if not ( req . status == 200 or req . status == 0 ) : ViewController . log_view . add ( req . text ) alert ( req . text ) # TODO : better handling return try : resp = json . loads ( req . text ) except ValueError : resp = None if not resp : alert ( "Chyba při konverzi!" ...
def install ( self ) : # pragma : no cover """Install / download ssh keys from LDAP for consumption by SSH ."""
keys = self . get_keys_from_ldap ( ) for user , ssh_keys in keys . items ( ) : user_dir = API . __authorized_keys_path ( user ) if not os . path . isdir ( user_dir ) : os . makedirs ( user_dir ) authorized_keys_file = os . path . join ( user_dir , 'authorized_keys' ) with open ( authorized_keys_...
def getDwordAtRva ( self , rva ) : """Returns a C { DWORD } from a given RVA . @ type rva : int @ param rva : The RVA to get the C { DWORD } from . @ rtype : L { DWORD } @ return : The L { DWORD } obtained at the given RVA ."""
return datatypes . DWORD . parse ( utils . ReadData ( self . getDataAtRva ( rva , 4 ) ) )
def setVarcompExact ( self , ldeltamin = - 5 , ldeltamax = 5 , num_intervals = 100 ) : """setVarcompExact ( ALMM self , limix : : mfloat _ t ldeltamin = - 5 , limix : : mfloat _ t ldeltamax = 5 , limix : : muint _ t num _ intervals = 100) Parameters ldeltamin : limix : : mfloat _ t ldeltamax : limix : : mfloa...
return _core . ALMM_setVarcompExact ( self , ldeltamin , ldeltamax , num_intervals )
def eglGetDisplay ( display = EGL_DEFAULT_DISPLAY ) : """Connect to the EGL display server ."""
res = _lib . eglGetDisplay ( display ) if not res or res == EGL_NO_DISPLAY : raise RuntimeError ( 'Could not create display' ) return res
def addSkip ( self , test : unittest . case . TestCase , reason : str ) : """Transforms the test in a serializable version of it and sends it to a queue for further analysis : param test : the test to save : param reason : the reason why the test was skipped"""
test . time_taken = time . time ( ) - self . start_time test . _outcome = None self . result_queue . put ( ( TestState . skipped , test , reason ) )
def largest_tuple_diff ( tuple_list : list ) -> int : """This function computes the highest difference among pairs within a provided list of tuples . Args : tuple _ list : A list of tuples Returns : An integer denoting the highest absolute difference between pair elements in the list . Examples : > > > ...
differences = [ abs ( a - b ) for a , b in tuple_list ] max_difference = max ( differences ) return max_difference
def _fetch_system_by_machine_id ( self ) : '''Get a system by machine ID Returns dict system exists in inventory False system does not exist in inventory None error connection or parsing response'''
machine_id = generate_machine_id ( ) try : url = self . api_url + '/inventory/v1/hosts?insights_id=' + machine_id net_logger . info ( "GET %s" , url ) res = self . session . get ( url , timeout = self . config . http_timeout ) except ( requests . ConnectionError , requests . Timeout ) as e : logger . er...
def set_plugins_params ( self , plugins = None , search_dirs = None , autoload = None , required = False ) : """Sets plugin - related parameters . : param list | str | unicode | OptionsGroup | list [ OptionsGroup ] plugins : uWSGI plugins to load : param list | str | unicode search _ dirs : Directories to searc...
plugins = plugins or [ ] command = 'need-plugin' if required else 'plugin' for plugin in listify ( plugins ) : if plugin not in self . _plugins : self . _set ( command , plugin , multi = True ) self . _plugins . append ( plugin ) self . _set ( 'plugins-dir' , search_dirs , multi = True , priority = ...
def get_date ( ) : '''Displays the current date : return : the system date : rtype : str CLI Example : . . code - block : : bash salt ' * ' timezone . get _ date'''
ret = salt . utils . mac_utils . execute_return_result ( 'systemsetup -getdate' ) return salt . utils . mac_utils . parse_return ( ret )
def write_branch_data ( self , file ) : """Writes branch data to file ."""
# I , J , CKT , R , X , B , RATEA , RATEB , RATEC , GI , BI , GJ , BJ , ST , LEN , O1 , F1 , . . . , O4 , F4 branch_attr = [ "r" , "x" , "b" , "rate_a" , "rate_b" , "rate_c" ] for branch in self . case . branches : if feq ( branch . ratio , 0.0 ) : vals = [ getattr ( branch , a ) for a in branch_attr ] ...
def read_moc_json ( moc , filename = None , file = None ) : """Read JSON encoded data into a MOC . Either a filename , or an open file object can be specified ."""
if file is not None : obj = _read_json ( file ) else : with open ( filename , 'rb' ) as f : obj = _read_json ( f ) for ( order , cells ) in obj . items ( ) : moc . add ( order , cells )
def mac_address_table_aging_time_conversational_time_out ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) mac_address_table = ET . SubElement ( config , "mac-address-table" , xmlns = "urn:brocade.com:mgmt:brocade-mac-address-table" ) aging_time = ET . SubElement ( mac_address_table , "aging-time" ) conversational_time_out = ET . SubElement ( aging_time , "conversational-time-out" ) conver...
def interleave ( args ) : r"""zip followed by flatten Args : args ( tuple ) : tuple of lists to interleave SeeAlso : You may actually be better off doing something like this : a , b , = args ut . flatten ( ut . bzip ( a , b ) ) ut . flatten ( ut . bzip ( [ 1 , 2 , 3 ] , [ ' - ' ] ) ) [1 , ' - ' , 2 ...
arg_iters = list ( map ( iter , args ) ) cycle_iter = it . cycle ( arg_iters ) for iter_ in cycle_iter : yield six . next ( iter_ )
def get_parameter_value ( self , parameter , from_cache = True , timeout = 10 ) : """Retrieve the current value of the specified parameter . : param str parameter : Either a fully - qualified XTCE name or an alias in the format ` ` NAMESPACE / NAME ` ` . : param bool from _ cache : If ` ` False ` ` this call ...
params = { 'fromCache' : from_cache , 'timeout' : int ( timeout * 1000 ) , } parameter = adapt_name_for_rest ( parameter ) url = '/processors/{}/{}/parameters{}' . format ( self . _instance , self . _processor , parameter ) response = self . _client . get_proto ( url , params = params ) proto = pvalue_pb2 . ParameterVa...
def _combine ( self , x , y ) : """Combines two constraints , raising an error if they are not compatible ."""
if x is None or y is None : return x or y if x != y : raise ValueError ( 'Incompatible set of constraints provided.' ) return x
def simxGetObjectVelocity ( clientID , objectHandle , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
linearVel = ( ct . c_float * 3 ) ( ) angularVel = ( ct . c_float * 3 ) ( ) ret = c_GetObjectVelocity ( clientID , objectHandle , linearVel , angularVel , operationMode ) arr1 = [ ] for i in range ( 3 ) : arr1 . append ( linearVel [ i ] ) arr2 = [ ] for i in range ( 3 ) : arr2 . append ( angularVel [ i ] ) retur...
def confd_state_epoll ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" ) epoll = ET . SubElement ( confd_state , "epoll" ) epoll . text = kwargs . pop ( 'epoll' ) callback = kwargs . pop ( 'callback' , self . _callback ) return callback ( config )
def is_mainthread ( thread = None ) : '''Check if thread is the main thread . If ` ` thread ` ` is not supplied check the current thread'''
thread = thread if thread is not None else current_thread ( ) return isinstance ( thread , threading . _MainThread )
def validar ( self , id_vlan ) : """Validates ACL - IPv4 of VLAN from its identifier . Assigns 1 to ' acl _ valida ' . : param id _ vlan : Identifier of the Vlan . Integer value and greater than zero . : return : None : raise InvalidParameterError : Vlan identifier is null and invalid . : raise VlanNaoExi...
if not is_valid_int_param ( id_vlan ) : raise InvalidParameterError ( u'The identifier of Vlan is invalid or was not informed.' ) url = 'vlan/' + str ( id_vlan ) + '/validate/' + IP_VERSION . IPv4 [ 0 ] + '/' code , xml = self . submit ( None , 'PUT' , url ) return self . response ( code , xml )
def getDataMap ( self , intype , pos , name , offset = 0 ) : """Hook defined to lookup a name , and get it from a vector . Can be overloaded to get it from somewhere else ."""
if intype == "input" : vector = self . inputs elif intype == "target" : vector = self . targets else : raise AttributeError ( "invalid map type '%s'" % intype ) return vector [ pos ] [ offset : offset + self [ name ] . size ]
def rotate_texture ( texture , rotation , x_offset = 0.5 , y_offset = 0.5 ) : """Rotates the given texture by a given angle . Args : texture ( texture ) : the texture to rotate rotation ( float ) : the angle of rotation in degrees x _ offset ( float ) : the x component of the center of rotation ( optional )...
x , y = texture x = x . copy ( ) - x_offset y = y . copy ( ) - y_offset angle = np . radians ( rotation ) x_rot = x * np . cos ( angle ) + y * np . sin ( angle ) y_rot = x * - np . sin ( angle ) + y * np . cos ( angle ) return x_rot + x_offset , y_rot + y_offset
def bucket_lister ( manager , bucket_name , prefix = None , marker = None , limit = None ) : """A generator function for listing keys in a bucket ."""
eof = False while not eof : ret , eof , info = manager . list ( bucket_name , prefix = prefix , limit = limit , marker = marker ) if ret is None : raise QiniuError ( info ) if not eof : marker = ret [ 'marker' ] for item in ret [ 'items' ] : yield item
def find_all ( cls , vid = None , pid = None ) : """Returns all FTDI devices matching our vendor and product IDs . : returns : list of devices : raises : : py : class : ` ~ alarmdecoder . util . CommError `"""
if not have_pyftdi : raise ImportError ( 'The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.' ) cls . __devices = [ ] query = cls . PRODUCT_IDS if vid and pid : query = [ ( vid , pid ) ] try : cls . __devices = Ftdi . find_all ( query , nocache = True ) except ( usb . core . ...
def send_keyevents ( self , keyevent : int ) -> None : '''Simulates typing keyevents .'''
self . _execute ( '-s' , self . device_sn , 'shell' , 'input' , 'keyevent' , str ( keyevent ) )
def get_csig ( self , calc = None ) : """Because we ' re a Python value node and don ' t have a real timestamp , we get to ignore the calculator and just use the value contents ."""
try : return self . ninfo . csig except AttributeError : pass contents = self . get_contents ( ) self . get_ninfo ( ) . csig = contents return contents
def unregister ( self , observers ) : u"""Concrete method of Subject . unregister ( ) . Unregister observers as an argument to self . observers ."""
if isinstance ( observers , list ) or isinstance ( observers , tuple ) : for observer in observers : try : index = self . _observers . index ( observer ) self . _observers . remove ( self . _observers [ index ] ) except ValueError : # logging print ( '{observer} n...
def _generate_author_query ( self , author_name ) : """Generates a query handling specifically authors . Notes : The match query is generic enough to return many results . Then , using the filter clause we truncate these so that we imitate legacy ' s behaviour on returning more " exact " results . E . g . Sea...
name_variations = [ name_variation . lower ( ) for name_variation in generate_minimal_name_variations ( author_name ) ] # When the query contains sufficient data , i . e . full names , e . g . ` ` Mele , Salvatore ` ` ( and not ` ` Mele , S ` ` or # ` ` Mele ` ` ) we can improve our filtering in order to filter out res...
def _setup_source_conn ( self , source_conn_id , source_bucket_name = None ) : """Retrieve connection based on source _ conn _ id . In case of s3 it also configures the bucket . Validates that connection id belongs to supported connection type . : param source _ conn _ id : : param source _ bucket _ name :"""
self . source_conn = BaseHook . get_hook ( source_conn_id ) self . source_conn_id = source_conn_id # Workaround for getting hook in case of s3 connection # This is needed because get _ hook silently returns None for s3 connections # See https : / / issues . apache . org / jira / browse / AIRFLOW - 2316 for more info co...
def delete ( self , event ) : """Abort running task if it exists ."""
super ( CeleryReceiver , self ) . delete ( event ) AsyncResult ( event . id ) . revoke ( terminate = True )
def get_view_name ( self ) : """Return the view name , as used in OPTIONS responses and in the browsable API ."""
func = self . settings . VIEW_NAME_FUNCTION return func ( self . __class__ , getattr ( self , 'suffix' , None ) )