signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def fn_with_diet_vars ( params ) : """Decorator for graph - building function to use diet variables ."""
params = copy . copy ( params ) def dec ( fn ) : def wrapped ( * args ) : return _fn_with_diet_vars ( fn , args , params ) return wrapped return dec
def aa_db_search ( self , files , base , unpack , search_method , maximum_range , threads , evalue , min_orf_length , restrict_read_length , diamond_database ) : '''Amino acid database search pipeline - pipeline where reads are searched as amino acids , and hits are identified using hmmsearch or diamond searche...
# Define outputs if search_method == 'hmmsearch' : output_search_file = files . hmmsearch_output_path ( base ) elif search_method == 'diamond' : output_search_file = files . diamond_search_output_basename ( base ) hit_reads_fasta = files . fa_output_path ( base ) hit_reads_orfs_fasta = files . orf_fasta_output_...
def deleteSession ( self , verbose = None ) : """This deletes the current session and initializes a new one . A message is returned to indicate the success of the deletion . : param verbose : print more : returns : 200 : successful operation"""
response = api ( url = self . ___url + 'session' , method = "DELETE" , verbose = verbose ) return response
def full_size ( self ) : '''show image at full size'''
self . dragpos = wx . Point ( 0 , 0 ) self . zoom = 1.0 self . need_redraw = True
def get ( self , name , default = _MISSING ) : """Get a metadata field ."""
name = self . _convert_name ( name ) if name not in self . _fields : if default is _MISSING : default = self . _default_value ( name ) return default if name in _UNICODEFIELDS : value = self . _fields [ name ] return value elif name in _LISTFIELDS : value = self . _fields [ name ] if val...
def writeString ( self , str ) : """Write the content of the string in the output I / O buffer This routine handle the I18N transcoding from internal UTF - 8 The buffer is lossless , i . e . will store in case of partial or delayed writes ."""
ret = libxml2mod . xmlOutputBufferWriteString ( self . _o , str ) return ret
def _set_arp_entry ( self , v , load = False ) : """Setter method for arp _ entry , mapped from YANG variable / rbridge _ id / arp _ entry ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ arp _ entry is considered as a private method . Backends looking to popu...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "arp_ip_address" , arp_entry . arp_entry , yang_name = "arp-entry" , rest_name = "arp" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'arp-ip-ad...
def log_error ( self , msg , * args ) : """Log an error or print in stdout if no logger ."""
if self . _logger is not None : self . _logger . error ( msg , * args ) else : print ( msg % args )
def participants ( self ) : """Access the participants : returns : twilio . rest . messaging . v1 . session . participant . ParticipantList : rtype : twilio . rest . messaging . v1 . session . participant . ParticipantList"""
if self . _participants is None : self . _participants = ParticipantList ( self . _version , session_sid = self . _solution [ 'sid' ] , ) return self . _participants
def run ( self ) : """Todo"""
self . logger . debug ( "heartbeat started" ) while True : time . sleep ( self . interval ) self . send_heartbeat ( )
def p_expr_exit ( p ) : '''expr : EXIT | EXIT LPAREN RPAREN | EXIT LPAREN expr RPAREN'''
if len ( p ) == 5 : p [ 0 ] = ast . Exit ( p [ 3 ] , lineno = p . lineno ( 1 ) ) else : p [ 0 ] = ast . Exit ( None , lineno = p . lineno ( 1 ) )
def execute_withdrawal ( self , withdrawal_params , private_key ) : """This function is to sign the message generated from the create withdrawal function and submit it to the blockchain for transfer from the smart contract to the owners address . Execution of this function is as follows : : execute _ withdraw...
withdrawal_id = withdrawal_params [ 'id' ] api_params = self . sign_execute_withdrawal_function [ self . blockchain ] ( withdrawal_params , private_key ) return self . request . post ( path = '/withdrawals/{}/broadcast' . format ( withdrawal_id ) , json_data = api_params )
def recreate_grams ( self ) : """Re - create grams for database . In normal situations , you never need to call this method . But after migrate DB , this method is useful . : param session : DB session : type session : : class : ` sqlalchemt . orm . Session `"""
session = self . Session ( ) for document in session . query ( Document ) . all ( ) : logger . info ( document . text ) grams = self . _get_grams ( session , document . text , make = True ) document . grams = list ( grams ) broken_links = session . query ( Gram ) . filter ( ~ Gram . documents . any ( ) ) . ...
def render ( self ) : '''Proxy method to form ' s environment render method'''
return self . env . template . render ( self . template , form = self )
def search_v1 ( self , q , resolve = False ) : """Identical to ` search _ v2 ( ) ` , except in that it does not return tags as ` hashtag dicts ` _ . Returns a ` search result dict ` _ ."""
params = self . __generate_params ( locals ( ) ) if resolve == False : del params [ 'resolve' ] return self . __api_request ( 'GET' , '/api/v1/search' , params )
def delete_app ( self , app_uri ) : """删除应用 删除指定标识的应用 , 当前请求方对该应用应有删除权限 。 Args : - app _ uri : 应用的完整标识 Returns : - result 成功返回空dict { } , 若失败则返回None - ResponseInfo 请求的Response信息"""
url = '{0}/v3/apps/{1}' . format ( self . host , app_uri ) return http . _delete_with_qiniu_mac ( url , None , self . auth )
def has_too_many_calls ( self ) : """Test if there have been too many calls : rtype boolean"""
if self . has_exact and self . _call_count > self . _exact : return True if self . has_maximum and self . _call_count > self . _maximum : return True return False
def reset ( self , state_size_changed = False ) : """Reset parser state . Parameters state _ size _ changed : ` bool ` , optional ` True ` if maximum state size changed ( default : ` False ` ) ."""
if state_size_changed : self . state = deque ( repeat ( '' , self . state_size ) , maxlen = self . state_size ) else : self . state . extend ( repeat ( '' , self . state_size ) ) self . end = True
def average_build_duration ( connection , package ) : """Return the average build duration for a package ( or container ) . : param connection : txkoji . Connection : param package : package name : returns : deferred that when fired returns a datetime . timedelta object"""
if isinstance ( package , str ) and package . endswith ( '-container' ) : return average_last_builds ( connection , package ) return connection . getAverageBuildDuration ( package )
def exit_config_mode ( self , exit_config = "return" , pattern = r">" ) : """Exit configuration mode ."""
return super ( HuaweiBase , self ) . exit_config_mode ( exit_config = exit_config , pattern = pattern )
def _requestDetails ( self , ip_address = None ) : """Get IP address data by sending request to IPinfo API ."""
if ip_address not in self . cache : url = self . API_URL if ip_address : url += '/' + ip_address response = requests . get ( url , headers = self . _get_headers ( ) , ** self . request_options ) if response . status_code == 429 : raise RequestQuotaExceededError ( ) response . raise_f...
def setlocation ( self , url , names = None ) : """Override the invocation location ( url ) for service method . @ param url : A url location . @ type url : A url . @ param names : A list of method names . None = ALL @ type names : [ str , . . ]"""
for p in self . ports : for m in p . methods . values ( ) : if names is None or m . name in names : m . location = url
def optimizer_step ( self , batch_info , device , model , rollout ) : """Single optimization step for a model"""
rollout = rollout . to_transitions ( ) # This algorithm makes quote strong assumptions about how does the model look # so it does not make that much sense to switch to the evaluator interface # As it would be more of a problem than actual benefit observations = rollout . batch_tensor ( 'observations' ) returns = rollou...
def _parse_trunk_native_vlan ( self , config ) : """Scans the specified config and parse the trunk native vlan value Args : config ( str ) : The interface configuration block to scan Returns : dict : A Python dict object with the value of switchport trunk native vlan value . The dict returned is intended ...
match = re . search ( r'switchport trunk native vlan (\d+)' , config ) return dict ( trunk_native_vlan = match . group ( 1 ) )
def led_control_encode ( self , target_system , target_component , instance , pattern , custom_len , custom_bytes ) : '''Control vehicle LEDs target _ system : System ID ( uint8 _ t ) target _ component : Component ID ( uint8 _ t ) instance : Instance ( LED instance to control or 255 for all LEDs ) ( uint8 _ ...
return MAVLink_led_control_message ( target_system , target_component , instance , pattern , custom_len , custom_bytes )
def extract_literal ( templatevar ) : """See if a template FilterExpression holds a literal value . : type templatevar : django . template . FilterExpression : rtype : bool | None"""
# FilterExpression contains another ' var ' that either contains a Variable or SafeData object . if hasattr ( templatevar , 'var' ) : templatevar = templatevar . var if isinstance ( templatevar , SafeData ) : # Literal in FilterExpression , can return . return templatevar else : # Variable in Filter...
def load ( self , ** kwargs ) : """Loads a given resource Loads a given resource provided a ' name ' and an optional ' slot ' parameter . The ' slot ' parameter is not a required load parameter because it is provided as an optional way of constructing the correct ' name ' of the vCMP resource . : param kw...
kwargs [ 'transform_name' ] = True kwargs = self . _mutate_name ( kwargs ) return self . _load ( ** kwargs )
def logout ( ) : """When the user accesses this route they are logged out ."""
cas_username_session_key = current_app . config [ 'CAS_USERNAME_SESSION_KEY' ] cas_attributes_session_key = current_app . config [ 'CAS_ATTRIBUTES_SESSION_KEY' ] if cas_username_session_key in flask . session : del flask . session [ cas_username_session_key ] if cas_attributes_session_key in flask . session : d...
def note_user_data ( note , role ) : """Return the data for user : param note : the note that holds the data : type note : : class : ` jukeboxcore . djadapter . models . Note ` : param role : item data role : type role : QtCore . Qt . ItemDataRole : returns : data for the created date : rtype : dependin...
if role == QtCore . Qt . DisplayRole or role == QtCore . Qt . EditRole : return note . user . username
def set_state ( self , state ) : """used in unittests"""
self . index_x . set ( state [ REG_X ] ) self . index_y . set ( state [ REG_Y ] ) self . user_stack_pointer . set ( state [ REG_U ] ) self . system_stack_pointer . set ( state [ REG_S ] ) self . program_counter . set ( state [ REG_PC ] ) self . accu_a . set ( state [ REG_A ] ) self . accu_b . set ( state [ REG_B ] ) se...
def load_pointings ( self , filename = None ) : """Load some pointings"""
filename = ( filename is None and tkFileDialog . askopenfilename ( ) or filename ) if filename is None : return f = storage . open_vos_or_local ( filename ) lines = f . readlines ( ) f . close ( ) points = [ ] if lines [ 0 ] [ 0 : 5 ] == "<?xml" : # # # assume astrores format # # # with < DATA at start of ' data ' ...
def reverse_geocode ( self , lat , lng , ** params ) : """| Params may be any valid parameter accepted by Google ' s API . | http : / / code . google . com / apis / maps / documentation / geocoding / # GeocodingRequests"""
return self . _get_geocoder_result ( latlng = "%s,%s" % ( lat , lng ) , ** params )
def read_pandas ( fname , * args , ** kwargs ) : """Read a file and return a pd . DataFrame"""
if not os . path . exists ( fname ) : raise ValueError ( 'no data file `{}` found!' . format ( fname ) ) if fname . endswith ( 'csv' ) : df = pd . read_csv ( fname , * args , ** kwargs ) else : xl = pd . ExcelFile ( fname ) if len ( xl . sheet_names ) > 1 and 'sheet_name' not in kwargs : kwargs ...
def _fix_list_dyn_func ( list ) : """This searches a list for dynamic function fragments , which may have been cut by generic searches for " , | ; " . Example : ` link _ a , [ [ copy ( ' links ' , need _ id ) ] ] ` this will be splitted in list of 3 parts : # . link _ a # . [ [ copy ( ' links ' # . need _...
open_func_string = False new_list = [ ] for element in list : if '[[' in element : open_func_string = True new_link = [ element ] elif ']]' in element : new_link . append ( element ) open_func_string = False element = "," . join ( new_link ) new_list . append ( el...
def http_list ( self , path , query_data = { } , as_list = None , ** kwargs ) : """Make a GET request to the Gitlab server for list - oriented queries . Args : path ( str ) : Path or full URL to query ( ' / projects ' or ' http : / / whatever / v4 / api / projecs ' ) query _ data ( dict ) : Data to send as ...
# In case we want to change the default behavior at some point as_list = True if as_list is None else as_list get_all = kwargs . pop ( 'all' , False ) url = self . _build_url ( path ) if get_all is True : return list ( GitlabList ( self , url , query_data , ** kwargs ) ) if 'page' in kwargs or as_list is True : # p...
def ideal_bin_count ( data , method : str = "default" ) -> int : """A theoretically ideal bin count . Parameters data : array _ likes Data to work on . Most methods don ' t use this . method : str Name of the method to apply , available values : - default ( ~ sturges ) - sqrt - sturges - doane -...
n = data . size if n < 1 : return 1 if method == "default" : if n <= 32 : return 7 else : return ideal_bin_count ( data , "sturges" ) elif method == "sqrt" : return int ( np . ceil ( np . sqrt ( n ) ) ) elif method == "sturges" : return int ( np . ceil ( np . log2 ( n ) ) + 1 ) elif ...
def _get_pkg_install_time ( pkg , arch = None ) : '''Return package install time , based on the / var / lib / dpkg / info / < package > . list : return :'''
iso_time = iso_time_t = None loc_root = '/var/lib/dpkg/info' if pkg is not None : locations = [ ] if arch is not None and arch != 'all' : locations . append ( os . path . join ( loc_root , '{0}:{1}.list' . format ( pkg , arch ) ) ) locations . append ( os . path . join ( loc_root , '{0}.list' . form...
def xpathNextPrecedingSibling ( self , ctxt ) : """Traversal function for the " preceding - sibling " direction The preceding - sibling axis contains the preceding siblings of the context node in reverse document order ; the first preceding sibling is first on the axis ; the sibling preceding that node is t...
if ctxt is None : ctxt__o = None else : ctxt__o = ctxt . _o ret = libxml2mod . xmlXPathNextPrecedingSibling ( ctxt__o , self . _o ) if ret is None : raise xpathError ( 'xmlXPathNextPrecedingSibling() failed' ) __tmp = xmlNode ( _obj = ret ) return __tmp
def fire_lasers ( self , modules : Optional [ List [ str ] ] = None , verbose_report : bool = False , transaction_count : Optional [ int ] = None , ) -> Report : """: param modules : The analysis modules which should be executed : param verbose _ report : Gives out the transaction sequence of the vulnerability ...
all_issues = [ ] # type : List [ Issue ] SolverStatistics ( ) . enabled = True exceptions = [ ] for contract in self . contracts : StartTime ( ) # Reinitialize start time for new contracts try : sym = SymExecWrapper ( contract , self . address , self . strategy , dynloader = DynLoader ( self . eth ,...
def ds_extent ( ds , t_srs = None ) : """Return min / max extent of dataset based on corner coordinates xmin , ymin , xmax , ymax If t _ srs is specified , output will be converted to specified srs"""
ul , ll , ur , lr = gt_corners ( ds . GetGeoTransform ( ) , ds . RasterXSize , ds . RasterYSize ) ds_srs = get_ds_srs ( ds ) if t_srs is not None and not ds_srs . IsSame ( t_srs ) : ct = osr . CoordinateTransformation ( ds_srs , t_srs ) # Check to see if ct creation failed # if ct = = NULL : # Check to ...
def sendtoaddress ( self , recv_addr , amount , comment = "" ) : """send ammount to address , with optional comment . Returns txid . sendtoaddress ( ADDRESS , AMMOUNT , COMMENT )"""
return self . req ( "sendtoaddress" , [ recv_addr , amount , comment ] )
def getSystemVariable ( self , remote , name ) : """Get single system variable from CCU / Homegear"""
var = None if self . remotes [ remote ] [ 'username' ] and self . remotes [ remote ] [ 'password' ] : LOG . debug ( "ServerThread.getSystemVariable: Getting System variable via JSON-RPC" ) session = self . jsonRpcLogin ( remote ) if not session : return try : params = { "_session_id_" : ...
def copy ( self ) : """Make deep copy of this key jar . : return : A : py : class : ` oidcmsg . key _ jar . KeyJar ` instance"""
kj = KeyJar ( ) for issuer in self . owners ( ) : kj [ issuer ] = [ kb . copy ( ) for kb in self [ issuer ] ] kj . verify_ssl = self . verify_ssl return kj
def append_json ( self , obj : Any , headers : Optional [ 'MultiMapping[str]' ] = None ) -> Payload : """Helper to append JSON part ."""
if headers is None : headers = CIMultiDict ( ) return self . append_payload ( JsonPayload ( obj , headers = headers ) )
def setVerCrossPlotAutoRangeOn ( self , axisNumber ) : """Sets the vertical cross - hair plot ' s auto - range on for the axis with number axisNumber . : param axisNumber : 0 ( X - axis ) , 1 ( Y - axis ) , 2 , ( Both X and Y axes ) ."""
setXYAxesAutoRangeOn ( self , self . verCrossPlotRangeCti , self . yAxisRangeCti , axisNumber )
def make_pickable_hash ( words , * args , ** kwargs ) : """Creates an ordered , minimal perfect hash function for the given sequence of words . > > > hf = make _ pickable _ hash ( [ ' sun ' , ' mon ' , ' tue ' , ' wed ' , ' thu ' , . . . ' fri ' , ' sat ' ] ) > > > hf ( ' fri ' ) > > > hf ( ' sun ' )"""
return PickableHash ( CzechHashBuilder ( words , * args , ** kwargs ) ) . czech_hash
def open ( self , encoding = None ) : """Opens the file with the appropriate call"""
try : if IS_GZIPPED_FILE . search ( self . _filename ) : _file = gzip . open ( self . _filename , 'rb' ) else : if encoding : _file = io . open ( self . _filename , 'r' , encoding = encoding , errors = 'replace' ) elif self . _encoding : _file = io . open ( self ....
def add_orthologs_by_gene_group ( self , graph , gene_ids ) : """This will get orthologies between human and other vertebrate genomes based on the gene _ group annotation pipeline from NCBI . More information 9can be learned here : http : / / www . ncbi . nlm . nih . gov / news / 03-13-2014 - gene - provides ...
src_key = 'gene_group' LOG . info ( "getting gene groups" ) src_file = '/' . join ( ( self . rawdir , self . files [ src_key ] [ 'file' ] ) ) found_counter = 0 # because many of the orthologous groups are grouped by human gene , # we need to do this by generating two - way hash # group _ id = > orthologs # ortholog id ...
def add_default_values_of_scoped_variables_to_scoped_data ( self ) : """Add the scoped variables default values to the scoped _ data dictionary"""
for key , scoped_var in self . scoped_variables . items ( ) : self . scoped_data [ str ( scoped_var . data_port_id ) + self . state_id ] = ScopedData ( scoped_var . name , scoped_var . default_value , scoped_var . data_type , self . state_id , ScopedVariable , parent = self )
def JSONList ( * args , ** kwargs ) : """Stores a list as JSON on database , with mutability support . If kwargs has a param ` unique _ sorted ` ( which evaluated to True ) , list values are made unique and sorted ."""
type_ = JSON try : if kwargs . pop ( "unique_sorted" ) : type_ = JSONUniqueListType except KeyError : pass return MutationList . as_mutable ( type_ ( * args , ** kwargs ) )
def gifs_categories_get ( self , api_key , ** kwargs ) : """Categories Endpoint . Returns a list of categories . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please define a ` callback ` function to be invoked when receiving the response . > > > def call...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . gifs_categories_get_with_http_info ( api_key , ** kwargs ) else : ( data ) = self . gifs_categories_get_with_http_info ( api_key , ** kwargs ) return data
def to ( self , units , equivalence = None , ** kwargs ) : """Creates a copy of this array with the data converted to the supplied units , and returns it . Optionally , an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions . . . note : : All additional ke...
return self . in_units ( units , equivalence = equivalence , ** kwargs )
def load_system_host_keys ( self , filename = None ) : """Load host keys from a system ( read - only ) file . Host keys read with this method will not be saved back by ` save _ host _ keys ` . This method can be called multiple times . Each new set of host keys will be merged with the existing set ( new repla...
if filename is None : # try the user ' s . ssh key file , and mask exceptions filename = os . path . expanduser ( "~/.ssh/known_hosts" ) try : self . _system_host_keys . load ( filename ) except IOError : pass return self . _system_host_keys . load ( filename )
def dot ( self , vec ) : """Dot product with another vector"""
if not isinstance ( vec , self . __class__ ) : raise TypeError ( 'Dot product operand must be a VectorArray' ) if self . nV != 1 and vec . nV != 1 and self . nV != vec . nV : raise ValueError ( 'Dot product operands must have the same ' 'number of elements.' ) return np . sum ( ( getattr ( self , d ) * getattr ...
def InitializeContext ( self , args ) : """Initializes the context of this hunt ."""
if args is None : args = rdf_hunts . HuntRunnerArgs ( ) context = rdf_hunts . HuntContext ( create_time = rdfvalue . RDFDatetime . Now ( ) , creator = self . token . username , duration = args . expiry_time , start_time = rdfvalue . RDFDatetime . Now ( ) , usage_stats = rdf_stats . ClientResourcesStats ( ) ) return...
def starlike ( x ) : "weird things happen to cardinality when working with * in comma - lists . this detects when to do that ."
# todo : is ' * as name ' a thing ? return isinstance ( x , sqparse2 . AsterX ) or isinstance ( x , sqparse2 . AttrX ) and isinstance ( x . attr , sqparse2 . AsterX )
def config_set_acl ( args ) : """Assign an ACL role to a list of users for a config ."""
acl_updates = [ { "user" : user , "role" : args . role } for user in set ( expand_fc_groups ( args . users ) ) if user != fapi . whoami ( ) ] id = args . snapshot_id if not id : # get the latest snapshot _ id for this method from the methods repo r = fapi . list_repository_configs ( namespace = args . namespace , n...
def thread_setup ( read_and_decode_fn , example_serialized , num_threads ) : """Sets up the threads within each reader"""
decoded_data = list ( ) for _ in range ( num_threads ) : decoded_data . append ( read_and_decode_fn ( example_serialized ) ) return decoded_data
def _transaction_func ( entering , exiting , using ) : """Takes 3 things , an entering function ( what to do to start this block of transaction management ) , an exiting function ( what to do to end it , on both success and failure , and using which can be : None , indiciating transaction should occur on all ...
# Note that although the first argument is * called * ` using ` , it # may actually be a function ; @ autocommit and @ autocommit ( ' foo ' ) # are both allowed forms . if callable ( using ) : return Transaction ( entering , exiting , None ) ( using ) return Transaction ( entering , exiting , using )
def do_action_to_ancestors ( analysis_request , transition_id ) : """Promotes the transitiion passed in to ancestors , if any"""
parent_ar = analysis_request . getParentAnalysisRequest ( ) if parent_ar : do_action_for ( parent_ar , transition_id )
def _get_file ( self , fn , timeout = 30 ) : '''Request a SiriDB configuration file . This method is used by the SiriDB manage tool and should not be used otherwise . Full access rights are required for this request .'''
msg = FILE_MAP . get ( fn , None ) if msg is None : raise FileNotFoundError ( 'Cannot get file {!r}. Available file ' 'requests are: {}' . format ( fn , ', ' . join ( FILE_MAP . keys ( ) ) ) ) result = self . _loop . run_until_complete ( self . _protocol . send_package ( msg , timeout = timeout ) ) return result
def validate_labels ( known_classes , passed_labels , argument_name ) : """Validates the labels passed into the true _ labels or pred _ labels arguments in the plot _ confusion _ matrix function . Raises a ValueError exception if any of the passed labels are not in the set of known classes or if there are dup...
known_classes = np . array ( known_classes ) passed_labels = np . array ( passed_labels ) unique_labels , unique_indexes = np . unique ( passed_labels , return_index = True ) if len ( passed_labels ) != len ( unique_labels ) : indexes = np . arange ( 0 , len ( passed_labels ) ) duplicate_indexes = indexes [ ~ n...
def initialize ( self , symbolic_vm : LaserEVM ) : """Initializes the instruction coverage plugin Introduces hooks for each instruction : param symbolic _ vm : : return :"""
self . coverage = { } self . initial_coverage = 0 self . tx_id = 0 @ symbolic_vm . laser_hook ( "stop_sym_exec" ) def stop_sym_exec_hook ( ) : # Print results for code , code_cov in self . coverage . items ( ) : cov_percentage = sum ( code_cov [ 1 ] ) / float ( code_cov [ 0 ] ) * 100 log . info ( "A...
def cd ( path ) : """Context manager to temporarily change working directories : param str path : The directory to move into > > > print ( os . path . abspath ( os . curdir ) ) ' / home / user / code / myrepo ' > > > with cd ( " / home / user / code / otherdir / subdir " ) : . . . print ( " Changed direct...
if not path : return prev_cwd = Path . cwd ( ) . as_posix ( ) if isinstance ( path , Path ) : path = path . as_posix ( ) os . chdir ( str ( path ) ) try : yield finally : os . chdir ( prev_cwd )
def get_javascript_error ( self , return_type = 'string' ) : """Return the gathered javascript error Args : return _ type : ' string ' | ' list ' ; default : ' string '"""
if BROME_CONFIG [ 'proxy_driver' ] [ 'intercept_javascript_error' ] : js_errors = self . _driver . execute_script ( 'return window.jsErrors; window.jsErrors = [];' ) if not js_errors : js_errors = [ ] if return_type == 'list' : if len ( js_errors ) : return js_errors else...
def dump ( self , full = True , redact = False ) : """Dump the Configuration object to a YAML file . The order of the keys is determined from the default configuration file . All keys not in the default configuration will be appended to the end of the file . : param filename : The file to dump the configura...
if full : out_dict = self . flatten ( redact = redact ) else : # Exclude defaults when flattening . sources = [ s for s in self . sources if not s . default ] temp_root = RootView ( sources ) temp_root . redactions = self . redactions out_dict = temp_root . flatten ( redact = redact ) yaml_out = yam...
def get_nested_dicts_with_key_value ( parent_dict : dict , key , value ) : """Return all nested dictionaries that contain a key with a specific value . A sub - case of NestedLookup ."""
references = [ ] NestedLookup ( parent_dict , references , NestedLookup . key_value_equality_factory ( key , value ) ) return ( document for document , _ in references )
def do_measurement ( self , qubit : int ) -> int : """Measure a qubit and collapse the wavefunction : return : The measurement result . A 1 or a 0."""
if self . rs is None : raise ValueError ( "You have tried to perform a stochastic operation without setting the " "random state of the simulator. Might I suggest using a PyQVM object?" ) measure_0 = lifted_gate_matrix ( matrix = P0 , qubit_inds = [ qubit ] , n_qubits = self . n_qubits ) prob_zero = np . trace ( mea...
def lattice ( prng , n_features , alpha , random_sign = False , low = 0.3 , high = 0.7 ) : """Returns the adjacency matrix for a lattice network . The resulting network is a Toeplitz matrix with random values summing between - 1 and 1 and zeros along the diagonal . The range of the values can be controlled vi...
degree = int ( 1 + np . round ( alpha * n_features / 2. ) ) if random_sign : sign_row = - 1.0 * np . ones ( degree ) + 2 * ( prng . uniform ( low = 0 , high = 1 , size = degree ) > .5 ) else : sign_row = - 1.0 * np . ones ( degree ) # in the * very unlikely * event that we draw a bad row that sums to zero # ( w...
def create_context ( require = None ) -> Context : '''Create a ModernGL context by loading OpenGL functions from an existing OpenGL context . An OpenGL context must exists . If rendering is done without a window please use the : py : func : ` create _ standalone _ context ` instead . Example : : # Accept th...
ctx = Context . __new__ ( Context ) ctx . mglo , ctx . version_code = mgl . create_context ( ) ctx . _screen = ctx . detect_framebuffer ( 0 ) ctx . fbo = ctx . detect_framebuffer ( ) ctx . mglo . fbo = ctx . fbo . mglo ctx . _info = None ctx . extra = None if require is not None and ctx . version_code < require : r...
def get_bulk_modify ( self , value ) : """Return value in format for bulk modify"""
if self . multiselect : value = value or [ ] return [ self . cast_to_bulk_modify ( child ) for child in value ] return self . cast_to_bulk_modify ( value )
def get_user ( path , follow_symlinks = True ) : '''Return the user that owns a given file Symlinks are followed by default to mimic Unix behavior . Specify ` follow _ symlinks = False ` to turn off this behavior . Args : path ( str ) : The path to the file or directory follow _ symlinks ( bool ) : If t...
if not os . path . exists ( path ) : raise CommandExecutionError ( 'Path not found: {0}' . format ( path ) ) # Under Windows , if the path is a symlink , the user that owns the symlink is # returned , not the user that owns the file / directory the symlink is # pointing to . This behavior is * different * to * nix ...
def get_all_targets ( self ) : """Returns all targets for all batches of this Executor ."""
result = [ ] for batch in self . batches : result . extend ( batch . targets ) return result
def _parse_frange_part ( frange ) : """Internal method : parse a discrete frame range part . Args : frange ( str ) : single part of a frame range as a string ( ie " 1-100x5 " ) Returns : tuple : ( start , end , modifier , chunk ) Raises : : class : ` . ParseException ` : if the frame range can not b...
match = FRANGE_RE . match ( frange ) if not match : msg = 'Could not parse "{0}": did not match {1}' raise ParseException ( msg . format ( frange , FRANGE_RE . pattern ) ) start , end , modifier , chunk = match . groups ( ) start = int ( start ) end = int ( end ) if end is not None else start if end > start and...
def calculate ( self , atoms ) : '''Blocking / Non - blocking calculate method If we are in blocking mode we just run , wait for the job to end and read in the results . Easy . . . The non - blocking mode is a little tricky . We need to start the job and guard against it reading back possible old data fro...
with work_dir ( self . working_dir ) : self . prepare_calc_dir ( ) self . calc_running = True # print ( ' Run VASP . calculate ' ) try : Vasp . calculate ( self , atoms ) self . calc_running = False # print ( ' VASP . calculate returned ' ) except _NonBlockingRunException as ...
def execute ( cmd ) : """execute command , return rc and output string . The cmd argument can be a string or a list composed of the command name and each of its argument . eg , [ ' / usr / bin / cp ' , ' - r ' , ' src ' , ' dst ' ]"""
# Parse cmd string to a list if not isinstance ( cmd , list ) : cmd = shlex . split ( cmd ) # Execute command rc = 0 output = "" try : output = subprocess . check_output ( cmd , close_fds = True , stderr = subprocess . STDOUT ) except subprocess . CalledProcessError as err : rc = err . returncode output...
def read_file ( filename , prepend_paths = [ ] ) : """Returns the contents of * filename * ( UTF - 8 ) . If * prepend _ paths * is set , join those before the * fielname * . If it is ` True ` , prepend the path to ` setup . py ` ."""
if prepend_paths is True : prepend_paths = [ os . path . abspath ( os . path . dirname ( __file__ ) ) , ] if prepend_paths : prepend_paths . append ( filename ) filename = os . path . join ( * prepend_paths ) print ( filename ) with open ( filename , encoding = 'utf-8' ) as f : return f . read ( )
def login ( self , user = None , password = None , ** kwargs ) : """雪球登陆 , 需要设置 cookies : param cookies : 雪球登陆需要设置 cookies , 具体见 https : / / smalltool . github . io / 2016/08/02 / cookie / : return :"""
cookies = kwargs . get ( 'cookies' ) if cookies is None : raise TypeError ( '雪球登陆需要设置 cookies, 具体见' 'https://smalltool.github.io/2016/08/02/cookie/' ) headers = self . _generate_headers ( ) self . s . headers . update ( headers ) self . s . get ( self . LOGIN_PAGE ) cookie_dict = helpers . parse_cookies_str ( cooki...
def aloha_to_html ( html_source ) : """Converts HTML5 from Aloha to a more structured HTML5"""
xml = aloha_to_etree ( html_source ) return etree . tostring ( xml , pretty_print = True )
def upload_files ( self , file_paths , file_size_sum = 0 , dcp_type = "data" , target_filename = None , use_transfer_acceleration = True , report_progress = False , sync = True ) : """A function that takes in a list of file paths and other optional args for parallel file upload"""
self . _setup_s3_agent_for_file_upload ( file_count = len ( file_paths ) , file_size_sum = file_size_sum , use_transfer_acceleration = use_transfer_acceleration ) pool = ThreadPool ( ) if report_progress : print ( "\nStarting upload of %s files to upload area %s" % ( len ( file_paths ) , self . uuid ) ) for file_pa...
def _maybe_download_corpora ( tmp_dir ) : """Download corpora for multinli . Args : tmp _ dir : a string Returns : a string"""
mnli_filename = "MNLI.zip" mnli_finalpath = os . path . join ( tmp_dir , "MNLI" ) if not tf . gfile . Exists ( mnli_finalpath ) : zip_filepath = generator_utils . maybe_download ( tmp_dir , mnli_filename , _MNLI_URL ) zip_ref = zipfile . ZipFile ( zip_filepath , "r" ) zip_ref . extractall ( tmp_dir ) zi...
def import_from_string ( val ) : """Attempt to import a class from a string representation ."""
try : module_path , class_name = val . rsplit ( '.' , 1 ) module = import_module ( module_path ) return getattr ( module , class_name ) except ( ImportError , AttributeError ) as e : msg = f"Could not import {val}. {e.__class__.__name__}: {e}" raise ImportError ( msg )
def getWorkingSeatedZeroPoseToRawTrackingPose ( self ) : """Returns the preferred seated position from the working copy ."""
fn = self . function_table . getWorkingSeatedZeroPoseToRawTrackingPose pmatSeatedZeroPoseToRawTrackingPose = HmdMatrix34_t ( ) result = fn ( byref ( pmatSeatedZeroPoseToRawTrackingPose ) ) return result , pmatSeatedZeroPoseToRawTrackingPose
def log_cert_info ( logger , msg_str , cert_obj ) : """Dump basic certificate values to the log . Args : logger : Logger Logger to which to write the certificate values . msg _ str : str A message to write to the log before the certificate values . cert _ obj : cryptography . Certificate Certificate c...
list ( map ( logger , [ "{}:" . format ( msg_str ) ] + [ " {}" . format ( v ) for v in [ "Subject: {}" . format ( _get_val_str ( cert_obj , [ "subject" , "value" ] , reverse = True ) ) , "Issuer: {}" . format ( _get_val_str ( cert_obj , [ "issuer" , "value" ] , reverse = True ) ) , "Not Valid Before: {}" . format ( ce...
def date_to_knx ( dateval ) : """Convert a date to a 3 byte KNX data array"""
if ( dateval . year < 1990 ) or ( dateval . year > 2089 ) : raise KNXException ( "Year has to be between 1990 and 2089" ) if dateval . year < 2000 : year = dateval . year - 1900 else : year = dateval . year - 2000 return ( [ dateval . day , dateval . month , year ] )
def _to_image_partial_overlap ( self , image ) : """Return an image of the mask in a 2D array , where the mask is not fully within the image ( i . e . partial or no overlap ) ."""
# find the overlap of the mask on the output image shape slices_large , slices_small = self . _overlap_slices ( image . shape ) if slices_small is None : return None # no overlap # insert the mask into the output image image [ slices_large ] = self . data [ slices_small ] return image
def GetMemSwappedMB ( self ) : '''Retrieves the amount of memory that has been reclaimed from this virtual machine by transparently swapping guest memory to disk .'''
counter = c_uint ( ) ret = vmGuestLib . VMGuestLib_GetMemSwappedMB ( self . handle . value , byref ( counter ) ) if ret != VMGUESTLIB_ERROR_SUCCESS : raise VMGuestLibException ( ret ) return counter . value
def verify_multisig ( address , hash_hex , scriptSig ) : """verify that a p2sh address is signed by the given scriptsig"""
script_parts = virtualchain . btc_script_deserialize ( scriptSig ) if len ( script_parts ) < 2 : log . warn ( "Verfiying multisig failed, couldn't grab script parts" ) return False redeem_script = script_parts [ - 1 ] script_sigs = script_parts [ 1 : - 1 ] if virtualchain . address_reencode ( virtualchain . btc...
def _check_state_value ( cls ) : """Check initial state value - if is proper and translate it . Initial state is required ."""
state_value = cls . context . get_config ( 'initial_state' , None ) state_value = state_value or getattr ( cls . context . new_class , cls . context . state_name , None ) if not state_value : raise ValueError ( "Empty state is disallowed, yet no initial state is given!" ) state_value = ( cls . context . new_meta [ ...
def endpoint_activate ( endpoint_id , myproxy , myproxy_username , myproxy_password , myproxy_lifetime , web , no_browser , delegate_proxy , proxy_lifetime , no_autoactivate , force , ) : """Executor for ` globus endpoint activate `"""
default_myproxy_username = lookup_option ( MYPROXY_USERNAME_OPTNAME ) client = get_client ( ) # validate options if web + myproxy + bool ( delegate_proxy ) > 1 : raise click . UsageError ( "--web, --myproxy, and --delegate-proxy are mutually exclusive." ) if no_autoactivate and not ( myproxy or web or delegate_prox...
def read_creds_from_ecs_container_metadata ( ) : """Read credentials from ECS instance metadata ( IAM role ) : return :"""
creds = init_creds ( ) try : ecs_metadata_relative_uri = os . environ [ 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ] credentials = requests . get ( 'http://169.254.170.2' + ecs_metadata_relative_uri , timeout = 1 ) . json ( ) for c in [ 'AccessKeyId' , 'SecretAccessKey' ] : creds [ c ] = credentials [...
def translateprotocolmask ( protocol ) : """Translate CardConnection protocol mask into PCSC protocol mask ."""
pcscprotocol = 0 if None != protocol : if CardConnection . T0_protocol & protocol : pcscprotocol |= SCARD_PROTOCOL_T0 if CardConnection . T1_protocol & protocol : pcscprotocol |= SCARD_PROTOCOL_T1 if CardConnection . RAW_protocol & protocol : pcscprotocol |= SCARD_PROTOCOL_RAW if...
def get ( self , resource , params = None , ** kwargs ) : """Shortcut for ` ` request ( ' GET ' , resource ) ` ` ."""
return self . request ( 'GET' , resource , params = params , ** kwargs )
def build_one ( self , package_dir , filename , source_map = False ) : """Builds one Sass / SCSS file . : param package _ dir : the path of package directory : type package _ dir : : class : ` str ` , : class : ` basestring ` : param filename : the filename of Sass / SCSS source to compile : type filename :...
sass_filename , css_filename = self . resolve_filename ( package_dir , filename , ) root_path = os . path . join ( package_dir , self . sass_path ) css_path = os . path . join ( package_dir , self . css_path , css_filename ) if source_map : source_map_path = css_filename + '.map' css , source_map = compile ( fi...
def calculate_positions ( self , first_bee_val , second_bee_val , value_range ) : '''Calculate the new value / position for two given bee values Args : first _ bee _ val ( int or float ) : value from the first bee second _ bee _ val ( int or float ) : value from the second bee value _ ranges ( tuple ) : " (...
value = first_bee_val + np . random . uniform ( - 1 , 1 ) * ( first_bee_val - second_bee_val ) if value_range [ 0 ] == 'int' : value = int ( value ) if value > value_range [ 1 ] [ 1 ] : value = value_range [ 1 ] [ 1 ] if value < value_range [ 1 ] [ 0 ] : value = value_range [ 1 ] [ 0 ] return value
def make_input ( self , with_header = False ) : """Construct the input file of the calculation ."""
s = str ( self . input ) if with_header : s = str ( self ) + "\n" + s return s
def write_octet ( self , n , pack = Struct ( 'B' ) . pack ) : """Write an integer as an unsigned 8 - bit value ."""
if 0 <= n <= 255 : self . _output_buffer . append ( pack ( n ) ) else : raise ValueError ( 'Octet %d out of range 0..255' , n ) return self
def modified_environ ( * remove : str , ** update : str ) -> Iterator [ None ] : """Temporarily updates the ` ` os . environ ` ` dictionary in - place and resets it to the original state when finished . ( https : / / stackoverflow . com / questions / 2059482/ python - temporarily - modify - the - current - pr...
env = os . environ update = update or { } remove = remove or ( ) # List of environment variables being updated or removed . stomped = ( set ( update . keys ( ) ) | set ( remove ) ) & set ( env . keys ( ) ) # Environment variables and values to restore on exit . update_after = { k : env [ k ] for k in stomped } # Enviro...
def parse_string_value_from_substring ( substring ) -> str : '''Returns the ascii value in the expected string " N : aa11bb22 " , where " N " is the key , and " aa11bb22 " is string value to be returned'''
try : value = substring . split ( ':' ) [ 1 ] return str ( value ) except ( ValueError , IndexError , TypeError , AttributeError ) : log . exception ( 'Unexpected arg to parse_string_value_from_substring:' ) raise ParseError ( 'Unexpected arg to parse_string_value_from_substring: {}' . format ( substrin...
def flattenPorts ( root : LNode ) : """Flatten ports to simplify layout generation : attention : children property is destroyed , parent property stays same"""
for u in root . children : u . west = _flattenPortsSide ( u . west ) u . east = _flattenPortsSide ( u . east ) u . north = _flattenPortsSide ( u . north ) u . south = _flattenPortsSide ( u . south )