signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_url_authcode_flow_user ( client_id , redirect_uri , display = "page" , scope = None , state = None ) : """Authorization Code Flow for User Access Token Use Authorization Code Flow to run VK API methods from the server side of an application . Access token received this way is not bound to an ip address ...
url = "https://oauth.vk.com/authorize" params = { "client_id" : client_id , "redirect_uri" : redirect_uri , "display" : display , "response_type" : "code" } if scope : params [ 'scope' ] = scope if state : params [ 'state' ] = state return u"{url}?{params}" . format ( url = url , params = urlencode ( params ) )
def convert_list_to_tuple ( lst ) : """A function that transforms a list into a tuple . Example : convert _ list _ to _ tuple ( [ 5 , 10 , 7 , 4 , 15 , 3 ] ) - > ( 5 , 10 , 7 , 4 , 15 , 3) convert _ list _ to _ tuple ( [ 2 , 4 , 5 , 6 , 2 , 3 , 4 , 4 , 7 ] ) - > ( 2 , 4 , 5 , 6 , 2 , 3 , 4 , 4 , 7) convert ...
return tuple ( lst )
def isLocked ( self ) : '''Checks if the device screen is locked . @ return True if the device screen is locked'''
self . __checkTransport ( ) lockScreenRE = re . compile ( 'mShowingLockscreen=(true|false)' ) dwp = self . shell ( 'dumpsys window policy' ) m = lockScreenRE . search ( dwp ) if m : return m . group ( 1 ) == 'true' dreamingLockscreenRE = re . compile ( 'mDreamingLockscreen=(true|false)' ) m = dreamingLockscreenRE ....
def forward_request ( self , method , path = None , json = None , params = None , headers = None ) : """Makes HTTP requests to the configured nodes . Retries connection errors ( e . g . DNS failures , refused connection , etc ) . A user may choose to retry other errors by catching the corresponding except...
error_trace = [ ] timeout = self . timeout backoff_cap = NO_TIMEOUT_BACKOFF_CAP if timeout is None else timeout / 2 while timeout is None or timeout > 0 : connection = self . connection_pool . get_connection ( ) start = time ( ) try : response = connection . request ( method = method , path = path ,...
def from_command_line ( ) : """Run CGI var to gVCF conversion from the command line ."""
# Parse options parser = argparse . ArgumentParser ( description = 'Convert Complete Genomics var files to gVCF format.' ) parser . add_argument ( '-d' , '--refseqdir' , metavar = 'REFSEQDIR' , required = True , dest = 'refseqdir' , help = 'Directory twobit reference genomes files are stored.' ) parser . add_argument (...
def database_caller_creator ( self , number_of_rows , username , password , host , port , name = None , custom = None ) : '''creates a postgresql db returns the related connection object which will be later used to spawn the cursor'''
cursor = None conn = None if name : dbname = name else : dbname = 'postgresql_' + str_generator ( self ) . lower ( ) try : # createdb conn = psycopg2 . connect ( user = username , password = password , host = host , port = port ) conn . set_isolation_level ( ISOLATION_LEVEL_AUTOCOMMIT ) cur = conn ....
def request_absolute_cursor_position ( self ) : """Get current cursor position . For vt100 : Do CPR request . ( answer will arrive later . ) For win32 : Do API call . ( Answer comes immediately . )"""
# Only do this request when the cursor is at the top row . ( after a # clear or reset ) . We will rely on that in ` report _ absolute _ cursor _ row ` . assert self . _cursor_pos . y == 0 # For Win32 , we have an API call to get the number of rows below the # cursor . if is_windows ( ) : self . _min_available_heigh...
def get_header ( changelog ) : """Return line number of the first version - like header . We check for patterns like ' 2.10 ( unreleased ) ' , so with either ' unreleased ' or a date between parenthesis as that ' s the format we ' re using . As an alternative , we support an alternative format used by some zo...
pattern = re . compile ( r""" (?P<version>.+) # Version string \( # Opening ( (?P<date>.+) # Date \) # Closing ) \W*$ # Possible whitespace at end of line. """ , re . VERBOSE ) alt_pattern = re . compile ( r""" ^ # Start of line ...
def _credit_card_type ( self , card_type = None ) : """Returns a random credit card type instance ."""
if card_type is None : card_type = self . random_element ( self . credit_card_types . keys ( ) ) elif isinstance ( card_type , CreditCard ) : return card_type return self . credit_card_types [ card_type ]
def _learn_init_params ( self , n_calib_beats = 8 ) : """Find a number of consecutive beats and use them to initialize : - recent qrs amplitude - recent noise amplitude - recent rr interval - qrs detection threshold The learning works as follows : - Find all local maxima ( largest sample within ` qrs _ ...
if self . verbose : print ( 'Learning initial signal parameters...' ) last_qrs_ind = - self . rr_max qrs_inds = [ ] qrs_amps = [ ] noise_amps = [ ] ricker_wavelet = signal . ricker ( self . qrs_radius * 2 , 4 ) . reshape ( - 1 , 1 ) # Find the local peaks of the signal . peak_inds_f = find_local_peaks ( self . sig_...
def make_label ( loss , key ) : '''Create a legend label for an optimization run .'''
algo , rate , mu , half , reg = key slots , args = [ '{:.3f}' , '{}' , 'm={:.3f}' ] , [ loss , algo , mu ] if algo in 'SGD NAG RMSProp Adam ESGD' . split ( ) : slots . append ( 'lr={:.2e}' ) args . append ( rate ) if algo in 'RMSProp ADADELTA ESGD' . split ( ) : slots . append ( 'rmsh={}' ) args . appen...
def KL ( self , other ) : """Compute the KL divergence to another NormalPosterior Object . This only holds , if the two NormalPosterior objects have the same shape , as we do computational tricks for the multivariate normal KL divergence ."""
return .5 * ( np . sum ( self . variance / other . variance ) + ( ( other . mean - self . mean ) ** 2 / other . variance ) . sum ( ) - self . num_data * self . input_dim + np . sum ( np . log ( other . variance ) ) - np . sum ( np . log ( self . variance ) ) )
def load ( self , filething , ** kwargs ) : """Load stream and tag information from a file ."""
fileobj = filething . fileobj try : self . tags = _IFFID3 ( fileobj , ** kwargs ) except ID3NoHeaderError : self . tags = None except ID3Error as e : raise error ( e ) else : self . tags . filename = self . filename fileobj . seek ( 0 , 0 ) self . info = AIFFInfo ( fileobj )
def get_img ( self , url , headers = None , cookies = None , timeout = 60 , verify = False , proxies = None , allow_redirects = True , params = None ) : """get方式获取 img 二进制信息 : param url : 访问Url : param headers : 请求头 : param cookies : 请求cookies : param timeout : 超时时间 : param verify : ssl验证 : param proxie...
if self . session : r = self . session . get ( url , headers = odict ( headers ) , cookies = cookies , timeout = timeout , verify = verify , proxies = proxies , allow_redirects = allow_redirects , params = params ) else : r = requests . get ( url , headers = odict ( headers ) , cookies = cookies , timeout = tim...
def get_throttled_by_consumed_read_percent ( table_name , lookback_window_start = 15 , lookback_period = 5 ) : """Returns the number of throttled read events in percent of consumption : type table _ name : str : param table _ name : Name of the DynamoDB table : type lookback _ window _ start : int : param l...
try : metrics1 = __get_aws_metric ( table_name , lookback_window_start , lookback_period , 'ConsumedReadCapacityUnits' ) metrics2 = __get_aws_metric ( table_name , lookback_window_start , lookback_period , 'ReadThrottleEvents' ) except BotoServerError : raise if metrics1 and metrics2 : lookback_seconds ...
def type_last ( self , obj : JsonObj ) -> JsonObj : """Move the type identifiers to the end of the object for print purposes"""
def _tl_list ( v : List ) -> List : return [ self . type_last ( e ) if isinstance ( e , JsonObj ) else _tl_list ( e ) if isinstance ( e , list ) else e for e in v if e is not None ] rval = JsonObj ( ) for k in as_dict ( obj ) . keys ( ) : v = obj [ k ] if v is not None and k not in ( 'type' , '_context' ) :...
def make_middleware ( cls , app , ** options ) : """Creates the application WSGI middleware in charge of serving local files . A Depot middleware is required if your application wants to serve files from storages that don ' t directly provide and HTTP interface like : class : ` depot . io . local . LocalFileS...
from depot . middleware import DepotMiddleware mw = DepotMiddleware ( app , ** options ) cls . set_middleware ( mw ) return mw
def _deref ( self ) -> List [ "InstanceNode" ] : """XPath : return the list of nodes that the receiver refers to ."""
return ( [ ] if self . is_internal ( ) else self . schema_node . type . _deref ( self ) )
def approximating_model_reg ( self , beta , T , Z , R , Q , h_approx , data , X , state_no ) : """Creates approximating Gaussian model for Poisson measurement density - dynamic regression model Parameters beta : np . array Contains untransformed starting values for latent variables T , Z , R , Q : np . ar...
H = np . ones ( data . shape [ 0 ] ) mu = np . zeros ( data . shape [ 0 ] ) alpha = np . zeros ( [ state_no , data . shape [ 0 ] ] ) tol = 100.0 it = 0 while tol > 10 ** - 7 and it < 5 : old_alpha = np . sum ( X * alpha . T , axis = 1 ) alpha , V = nld_univariate_KFS ( data , Z , H , T , Q , R , mu ) H = np...
def _prepare_method ( self , pandas_func , ** kwargs ) : """Prepares methods given various metadata . Args : pandas _ func : The function to prepare . Returns Helper function which handles potential transpose ."""
if self . _is_transposed : def helper ( df , internal_indices = [ ] ) : if len ( internal_indices ) > 0 : return pandas_func ( df . T , internal_indices = internal_indices , ** kwargs ) return pandas_func ( df . T , ** kwargs ) else : def helper ( df , internal_indices = [ ] ) : ...
def _play ( self ) : """Send play command to receiver command via HTTP post ."""
# Use pause command only for sources which support NETAUDIO if self . _input_func in self . _netaudio_func_list : body = { "cmd0" : "PutNetAudioCommand/CurEnter" , "cmd1" : "aspMainZone_WebUpdateStatus/" , "ZoneName" : "MAIN ZONE" } try : if self . send_post_command ( self . _urls . command_netaudio_pos...
def to_ipv6 ( self , ip_type = '6-to-4' ) : """Convert ( an IPv4 ) IP address to an IPv6 address . > > > ip = IP ( ' 192.0.2.42 ' ) > > > print ( ip . to _ ipv6 ( ) ) 2002 : c000:022a : 0000:0000:0000:0000:0000 > > > print ( ip . to _ ipv6 ( ' compat ' ) ) 0000:0000:0000:0000:0000:0000 : c000:022a > > >...
assert ip_type in [ '6-to-4' , 'compat' , 'mapped' ] , 'Conversion ip_type not supported' if self . v == 4 : if ip_type == '6-to-4' : return IP ( BASE_6TO4 | int ( self ) << 80 , version = 6 ) elif ip_type == 'compat' : return IP ( int ( self ) , version = 6 ) elif ip_type == 'mapped' : ...
def get_file ( self , hash_list ) : """Returns the path of the file - but verifies that the hash is actually present ."""
assert len ( hash_list ) == 1 self . _check_hashes ( hash_list ) return self . object_path ( hash_list [ 0 ] )
def gen ( name , data ) : """Generate dataentry * name * from * data * ."""
return '---- dataentry %s ----\n%s\n----' % ( name , '\n' . join ( '%s:%s' % ( attr , value ) for attr , value in data . items ( ) ) )
def checked_emit ( self , value : Any ) -> asyncio . Future : """Casting and checking in one call"""
if not isinstance ( self . _subject , Subscriber ) : raise TypeError ( 'Topic %r has to be a subscriber' % self . _path ) value = self . cast ( value ) self . check ( value ) return self . _subject . emit ( value , who = self )
def make_pymol ( pdb_file , cutoff = 7.0 , min_kihs = 2 , outfile = None ) : """Pymol script for viewing classic coiled - coil Socket output . Notes For examples of these views , browse the CC + database here : http : / / coiledcoils . chm . bris . ac . uk / ccplus / search / . Parameters pdb _ file : str ...
a = convert_pdb_to_ampal ( pdb = pdb_file , path = True ) kg = KnobGroup . from_helices ( a , cutoff = cutoff ) g = kg . filter_graph ( kg . graph , cutoff = cutoff , min_kihs = min_kihs ) ccs = sorted_connected_components ( g ) # Opens pymol script , initial set up of screen script_lines = [ 'load {0}' . format ( pdb_...
def _filter_version_specific_options ( self , tmos_ver , ** kwargs ) : '''Filter version - specific optional parameters Some optional parameters only exist in v12.1.0 and greater , filter these out for earlier versions to allow backward comatibility .'''
if LooseVersion ( tmos_ver ) < LooseVersion ( '12.1.0' ) : for k , parms in self . _meta_data [ 'optional_parameters' ] . items ( ) : for r in kwargs . get ( k , [ ] ) : for parm in parms : value = r . pop ( parm , None ) if value is not None : ...
def _lock_renewer ( lockref , interval , stop ) : """Renew the lock key in redis every ` interval ` seconds for as long as ` self . _ lock _ renewal _ thread . should _ exit ` is False ."""
log = getLogger ( "%s.lock_refresher" % __name__ ) while not stop . wait ( timeout = interval ) : log . debug ( "Refreshing lock" ) lock = lockref ( ) if lock is None : log . debug ( "The lock no longer exists, " "stopping lock refreshing" ) break lock . extend ( expire = lock . _expire ...
def all ( self , page = 1 , per_page = 10 , order_by = "latest" ) : """Get a single page from the list of all photos . : param page [ integer ] : Page number to retrieve . ( Optional ; default : 1) : param per _ page [ integer ] : Number of items per page . ( Optional ; default : 10) : param order _ by [ stri...
return self . _all ( "/photos" , page = page , per_page = per_page , order_by = order_by )
def post_mark_translated ( self , post_id , check_translation , partially_translated ) : """Mark post as translated ( Requires login ) ( UNTESTED ) . If you set check _ translation and partially _ translated to 1 post will be tagged as ' translated _ request ' Parameters : post _ id ( int ) : check _ tran...
param = { 'post[check_translation]' : check_translation , 'post[partially_translated]' : partially_translated } return self . _get ( 'posts/{0}/mark_as_translated.json' . format ( post_id ) , param , method = 'PUT' , auth = True )
def Profiler_setSamplingInterval ( self , interval ) : """Function path : Profiler . setSamplingInterval Domain : Profiler Method name : setSamplingInterval Parameters : Required arguments : ' interval ' ( type : integer ) - > New sampling interval in microseconds . No return value . Description : Cha...
assert isinstance ( interval , ( int , ) ) , "Argument 'interval' must be of type '['int']'. Received type: '%s'" % type ( interval ) subdom_funcs = self . synchronous_command ( 'Profiler.setSamplingInterval' , interval = interval ) return subdom_funcs
def _isClauseFinal ( wordID , clauseTokens ) : '''Teeb kindlaks , kas etteantud ID - ga s6na on osalause l6pus : - - s6nale ei j2rgne ykski teine s6na ; - - s6nale j2rgnevad vaid punktuatsioonim2rgid ja / v6i sidendid JA / NING / EGA / VÕI ; Tagastab True , kui eeltoodud tingimused on t2idetud , vastasel juh...
jaNingEgaVoi = WordTemplate ( { ROOT : '^(ja|ning|ega|v[\u014D\u00F5]i)$' , POSTAG : '[DJ]' } ) punktuatsioon = WordTemplate ( { POSTAG : 'Z' } ) for i in range ( len ( clauseTokens ) ) : token = clauseTokens [ i ] if token [ WORD_ID ] == wordID : if i + 1 == len ( clauseTokens ) : return Tr...
def StopHuntIfCPUOrNetworkLimitsExceeded ( hunt_id ) : """Stops the hunt if average limites are exceeded ."""
hunt_obj = data_store . REL_DB . ReadHuntObject ( hunt_id ) # Do nothing if the hunt is already stopped . if hunt_obj . hunt_state == rdf_hunt_objects . Hunt . HuntState . STOPPED : return hunt_obj hunt_counters = data_store . REL_DB . ReadHuntCounters ( hunt_id ) # Check global hunt network bytes limit first . if ...
def largest_compartment_id_met ( model ) : """Return the ID of the compartment with the most metabolites . Parameters model : cobra . Model The metabolic model under investigation . Returns string Compartment ID of the compartment with the most metabolites ."""
# Sort compartments by decreasing size and extract the largest two . candidate , second = sorted ( ( ( c , len ( metabolites_per_compartment ( model , c ) ) ) for c in model . compartments ) , reverse = True , key = itemgetter ( 1 ) ) [ : 2 ] # Compare the size of the compartments . if candidate [ 1 ] == second [ 1 ] :...
def get_queryset ( self ) : "Reduce the number of queries and speed things up ."
qs = super ( ) . get_queryset ( ) qs = qs . select_related ( 'publication__series' ) . prefetch_related ( 'publication__roles__creator' ) return qs
def _preprocess_individuals ( self , individuals ) : """Preprocess DEAP individuals before pipeline evaluation . Parameters individuals : a list of DEAP individual One individual is a list of pipeline operators and model parameters that can be compiled by DEAP into a callable function Returns operator _...
# update self . _ pbar . total if not ( self . max_time_mins is None ) and not self . _pbar . disable and self . _pbar . total <= self . _pbar . n : self . _pbar . total += self . _lambda # Check we do not evaluate twice the same individual in one pass . _ , unique_individual_indices = np . unique ( [ str ( ind ) f...
def calculate_totals ( self , children , local_children = None ) : """Calculate our cumulative totals from children and / or local children"""
for field , local_field in ( ( 'recursive' , 'calls' ) , ( 'cumulative' , 'local' ) ) : values = [ ] for child in children : if isinstance ( child , PStatGroup ) or not self . LOCAL_ONLY : values . append ( getattr ( child , field , 0 ) ) elif isinstance ( child , PStatRow ) and self...
def hide ( input_image : Union [ str , IO [ bytes ] ] , message : str , encoding : str = "UTF-8" , auto_convert_rgb : bool = False , ) : """Hide a message ( string ) in an image with the LSB ( Least Significant Bit ) technique ."""
message_length = len ( message ) assert message_length != 0 , "message length is zero" img = tools . open_image ( input_image ) if img . mode not in [ "RGB" , "RGBA" ] : if not auto_convert_rgb : print ( "The mode of the image is not RGB. Mode is {}" . format ( img . mode ) ) answer = input ( "Conve...
def add_agent_pool ( self , pool ) : """AddAgentPool . [ Preview API ] Create an agent pool . : param : class : ` < TaskAgentPool > < azure . devops . v5_1 . task _ agent . models . TaskAgentPool > ` pool : Details about the new agent pool : rtype : : class : ` < TaskAgentPool > < azure . devops . v5_1 . task...
content = self . _serialize . body ( pool , 'TaskAgentPool' ) response = self . _send ( http_method = 'POST' , location_id = 'a8c47e17-4d56-4a56-92bb-de7ea7dc65be' , version = '5.1-preview.1' , content = content ) return self . _deserialize ( 'TaskAgentPool' , response )
def dispatch ( self , state_change : StateChange ) -> List [ Event ] : """Apply the ` state _ change ` in the current machine and return the resulting events . Args : state _ change : An object representation of a state change . Return : A list of events produced by the state transition . It ' s the u...
assert isinstance ( state_change , StateChange ) # the state objects must be treated as immutable , so make a copy of the # current state and pass the copy to the state machine to be modified . next_state = deepcopy ( self . current_state ) # update the current state by applying the change iteration = self . state_tran...
def _compute_dk_dtau_on_partition ( self , tau , p ) : """Evaluate the term inside the sum of Faa di Bruno ' s formula for the given partition . Parameters tau : : py : class : ` Matrix ` , ( ` M ` , ` D ` ) ` M ` inputs with dimension ` D ` . p : list of : py : class : ` Array ` Each element is a block o...
y , r2l2 = self . _compute_y ( tau , return_r2l2 = True ) # Compute the d ^ ( | pi | ) f / dy term : dk_dtau = self . _compute_dk_dy ( y , len ( p ) ) # Multiply in each of the block terms : for b in p : dk_dtau *= self . _compute_dy_dtau ( tau , b , r2l2 ) return dk_dtau
def pause_with_reason ( self , reason ) : """Internal method for triggering a VM pause with a specified reason code . The reason code can be interpreted by device / drivers and thus it might behave slightly differently than a normal VM pause . : py : func : ` IConsole . pause ` in reason of type : class : `...
if not isinstance ( reason , Reason ) : raise TypeError ( "reason can only be an instance of type Reason" ) self . _call ( "pauseWithReason" , in_p = [ reason ] )
def patched ( attrs , updates ) : """A context in which some attributes temporarily have a modified value ."""
orig = patch ( attrs , updates . items ( ) ) try : yield orig finally : patch ( attrs , orig . items ( ) )
def parse_instancepath ( self , tup_tree ) : """Parse an INSTANCEPATH element and return the instance path it represents as a CIMInstanceName object . < ! ELEMENT INSTANCEPATH ( NAMESPACEPATH , INSTANCENAME ) >"""
self . check_node ( tup_tree , 'INSTANCEPATH' ) k = kids ( tup_tree ) if len ( k ) != 2 : raise CIMXMLParseError ( _format ( "Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(NAMESPACEPATH, INSTANCENAME))" , name ( tup_tree ) , k ) , conn_id = self . conn_id ) host , nam...
def schoice ( self , seq : str , end : int = 10 ) -> str : """Choice function which returns string created from sequence . : param seq : Sequence of letters or digits . : type seq : tuple or list : param end : Max value . : return : Single string ."""
return '' . join ( self . choice ( list ( seq ) ) for _ in range ( end ) )
def restore_default_settings ( ) : """Restore settings to default values ."""
global __DEFAULTS __DEFAULTS . CACHE_DIR = defaults . CACHE_DIR __DEFAULTS . SET_SEED = defaults . SET_SEED __DEFAULTS . SEED = defaults . SEED logging . info ( 'Settings reverted to their default values.' )
def invoke ( self , ctx ) : """Given a context , this invokes the attached callback ( if it exists ) in the right way ."""
_maybe_show_deprecated_notice ( self ) if self . callback is not None : return ctx . invoke ( self . callback , ** ctx . params )
def echo ( text , fg = None , bg = None , style = None , file = None , err = False , color = None ) : """Write the given text to the provided stream or * * sys . stdout * * by default . Provides optional foreground and background colors from the ansi defaults : * * grey * * , * * red * * , * * green * * , * * y...
if file and not hasattr ( file , "write" ) : raise TypeError ( "Expected a writable stream, received {0!r}" . format ( file ) ) if not file : if err : file = _text_stderr ( ) else : file = _text_stdout ( ) if text and not isinstance ( text , ( six . string_types , bytes , bytearray ) ) : ...
def ceiling ( value , mod = 1 ) : """RETURN SMALLEST INTEGER GREATER THAN value"""
if value == None : return None mod = int ( mod ) v = int ( math_floor ( value + mod ) ) return v - ( v % mod )
def AddSourceRestriction ( self , cidr ) : """Add and commit a single source IP restriction policy . > > > clc . v2 . Server ( " WA1BTDIX01 " ) . PublicIPs ( ) . public _ ips [ 0] . AddSourceRestriction ( cidr = " 132.200.20.1/32 " ) . WaitUntilComplete ( )"""
self . source_restrictions . append ( SourceRestriction ( self , cidr ) ) return ( self . Update ( ) )
def pmllpmbb_to_pmrapmdec ( pmll , pmbb , l , b , degree = False , epoch = 2000.0 ) : """NAME : pmllpmbb _ to _ pmrapmdec PURPOSE : rotate proper motions in ( l , b ) into proper motions in ( ra , dec ) INPUT : pmll - proper motion in l ( multplied with cos ( b ) ) [ mas / yr ] pmbb - proper motion in b...
theta , dec_ngp , ra_ngp = get_epoch_angles ( epoch ) # Whether to use degrees and scalar input is handled by decorators radec = lb_to_radec ( l , b , degree = False , epoch = epoch ) ra = radec [ : , 0 ] dec = radec [ : , 1 ] dec [ dec == dec_ngp ] += 10. ** - 16 # deal w / pole . sindec_ngp = nu . sin ( dec_ngp ) cos...
def format ( self , indent_level , indent_size = 4 ) : """Format this verifier Returns : string : A formatted string"""
name = self . format_name ( 'Boolean' , indent_size ) if self . _require_value is not None : if self . long_desc is not None : name += '\n' name += self . wrap_lines ( 'must be %s\n' % str ( self . _require_value ) . lower ( ) , 1 , indent_size ) return self . wrap_lines ( name , indent_level , indent_s...
def compute_result_enum ( self ) -> RobotScanResultEnum : """Look at the server ' s response to each ROBOT payload and return the conclusion of the analysis ."""
# Ensure the results were consistent for payload_enum , server_responses in self . _payload_responses . items ( ) : # We ran the check twice per payload and the two responses should be the same if server_responses [ 0 ] != server_responses [ 1 ] : return RobotScanResultEnum . UNKNOWN_INCONSISTENT_RESULTS # ...
def pivot ( self , binned = False ) : """Calculate : ref : ` pysynphot - formula - pivwv ` . Parameters binned : bool This is reserved for use by ` ~ pysynphot . observation . Observation ` . If ` True ` , binned wavelength set is used . Default is ` False ` . Returns ans : float Pivot wavelength . ...
if binned : try : wave = self . binwave except AttributeError : raise AttributeError ( 'Class ' + str ( type ( self ) ) + ' does not support binning.' ) else : wave = self . wave countmulwave = self ( wave ) * wave countdivwave = self ( wave ) / wave num = self . trapezoidIntegration ( wave ...
def _clone ( self ) : """Make a ( shallow ) copy of the set . There is a ' clone protocol ' that subclasses of this class should use . To make a copy , first call your super ' s _ clone ( ) method , and use the object returned as the new instance . Then make shallow copies of the attributes defined in the s...
cls = self . __class__ obj = cls . __new__ ( cls ) obj . items = list ( self . items ) return obj
def GetScriptHashesForVerifying ( self ) : """Get a list of script hashes for verifying transactions . Raises : Exception : if there are no valid transactions to claim from . Returns : list : of UInt160 type script hashes ."""
hashes = super ( ClaimTransaction , self ) . GetScriptHashesForVerifying ( ) for hash , group in groupby ( self . Claims , lambda x : x . PrevHash ) : tx , height = Blockchain . Default ( ) . GetTransaction ( hash ) if tx is None : raise Exception ( "Invalid Claim Operation" ) for claim in group : ...
def pop_event ( self ) : """Pop an event from event _ list ."""
if len ( self . event_list ) > 0 : evt = self . event_list . pop ( 0 ) return evt return None
def makeParser ( ) : """Create the SCOOP module arguments parser ."""
# TODO : Add environment variable ( all + selection ) parser = argparse . ArgumentParser ( description = "Starts a parallel program using SCOOP." , prog = "{0} -m scoop" . format ( sys . executable ) , ) group = parser . add_mutually_exclusive_group ( ) group . add_argument ( '--hosts' , '--host' , help = "The list of ...
def as_nonlinear ( self , params = None ) : """Return a ` Model ` equivalent to this object . The nonlinear solver is less efficient , but lets you freeze parameters , compute uncertainties , etc . If the ` params ` argument is provided , solve ( ) will be called on the returned object with those parameters ....
if params is None : params = self . params nlm = Model ( None , self . data , self . invsigma ) nlm . set_func ( lambda p , x : npoly . polyval ( x , p ) , self . pnames , args = ( self . x , ) ) if params is not None : nlm . solve ( params ) return nlm
def _parse_document ( self ) : """Parse system . profile doc , copy all values to member variables ."""
self . _reset ( ) doc = self . _profile_doc self . _split_tokens_calculated = True self . _split_tokens = None self . _duration_calculated = True self . _duration = doc [ u'millis' ] self . _datetime_calculated = True self . _datetime = doc [ u'ts' ] if self . _datetime . tzinfo is None : self . _datetime = self . ...
def set_rss_element ( self ) : """Set each of the basic rss elements ."""
self . set_author ( ) self . set_categories ( ) self . set_comments ( ) self . set_creative_commons ( ) self . set_description ( ) self . set_enclosure ( ) self . set_guid ( ) self . set_link ( ) self . set_published_date ( ) self . set_title ( )
def is_archlinux ( ) : """return True if the current distribution is running on debian like OS ."""
if platform . system ( ) . lower ( ) == 'linux' : if platform . linux_distribution ( ) == ( '' , '' , '' ) : # undefined distribution . Fixed in python 3. if os . path . exists ( '/etc/arch-release' ) : return True return False
def consumer ( site , uri ) : """Consume URI using site config ."""
config = load_site_config ( site ) model = _get_model ( 'consume' , config , uri ) consumestore = get_consumestore ( model = model , method = _config . get ( 'storage' , 'file' ) , bucket = _config . get ( 's3_data_bucket' , None ) ) consumestore . save_media ( ) consumestore . save_data ( )
def get_domain ( self ) : """Returns the dictionary of variables with keys as variable name and values as domain of the variables . Returns dict : dictionary containing variables and their domains Example > > > reader = UAIReader ( ' TestUAI . uai ' ) > > > reader . get _ domain ( ) { ' var _ 0 ' : ' ...
domain = { } var_domain = self . grammar . parseString ( self . network ) [ 'domain_variables' ] for var in range ( 0 , len ( var_domain ) ) : domain [ "var_" + str ( var ) ] = var_domain [ var ] return domain
def get_klass_parents ( gi_name ) : '''Returns a sorted list of qualified symbols representing the parents of the klass - like symbol named gi _ name'''
res = [ ] parents = __HIERARCHY_GRAPH . predecessors ( gi_name ) if not parents : return [ ] __get_parent_link_recurse ( parents [ 0 ] , res ) return res
def getOr ( subject , predicate , * args , ** kwargs ) : """Retrieve a metadata node or generate a new one : param subject : Subject to which the metadata node should be connected : param predicate : Predicate by which the metadata node should be connected : return : Metadata for given node : rtype : Metada...
if ( subject , predicate , None ) in get_graph ( ) : return Metadata ( node = get_graph ( ) . objects ( subject , predicate ) . __next__ ( ) ) return Metadata ( * args , ** kwargs )
def is_opening_code_fence ( line : str , parser : str = 'github' ) : r"""Determine if the given line is possibly the opening of a fenced code block . : parameter line : a single markdown line to evaluate . : parameter parser : decides rules on how to generate the anchor text . Defaults to ` ` github ` ` . :...
if ( parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parser == 'commonmarker' ) : markers = md_parser [ 'github' ] [ 'code fence' ] [ 'marker' ] marker_min_length = md_parser [ 'github' ] [ 'code fence' ] [ 'min_marker_characters' ] if not is_valid_code_fence_indent ( line ) : retur...
def confirm_operation ( prompt , prefix = None , assume_yes = False , err = False ) : """Prompt the user for confirmation for dangerous actions ."""
if assume_yes : return True prefix = prefix or click . style ( "Are you %s certain you want to" % ( click . style ( "absolutely" , bold = True ) ) ) prompt = "%(prefix)s %(prompt)s?" % { "prefix" : prefix , "prompt" : prompt } if click . confirm ( prompt , err = err ) : return True click . echo ( err = err ) cl...
def position_result_list ( change_list ) : """Returns a template which iters through the models and appends a new position column ."""
result = result_list ( change_list ) # Remove sortable attributes for x in range ( 0 , len ( result [ 'result_headers' ] ) ) : result [ 'result_headers' ] [ x ] [ 'sorted' ] = False if result [ 'result_headers' ] [ x ] [ 'sortable' ] : result [ 'result_headers' ] [ x ] [ 'class_attrib' ] = mark_safe ( '...
def main ( ) : """Start the DQL client ."""
parse = argparse . ArgumentParser ( description = main . __doc__ ) parse . add_argument ( "-c" , "--command" , help = "Run this command and exit" ) region = os . environ . get ( "AWS_REGION" , "us-west-1" ) parse . add_argument ( "-r" , "--region" , default = region , help = "AWS region to connect to (default %(default...
def _get_designation_type ( self ) : """Extracts the designation type of the stored routine ."""
positions = self . _get_specification_positions ( ) if positions [ 0 ] != - 1 and positions [ 1 ] != - 1 : pattern = re . compile ( r'^\s*--\s+type\s*:\s*(\w+)\s*(.+)?\s*' , re . IGNORECASE ) for line_number in range ( positions [ 0 ] , positions [ 1 ] + 1 ) : matches = pattern . findall ( self . _routi...
def cart2spol ( X ) : """Performs coordinate transformation from cartesian to spherical polar coordinates with ( r , phi , theta ) having usual meanings ."""
x , y , z , vx , vy , vz = X r = np . sqrt ( x * x + y * y + z * z ) p = np . arctan2 ( y , x ) t = np . arccos ( z / r ) vr = ( vx * np . cos ( p ) + vy * np . sin ( p ) ) * np . sin ( t ) + np . cos ( t ) * vz vp = - vx * np . sin ( p ) + vy * np . cos ( p ) vt = ( vx * np . cos ( p ) + vy * np . sin ( p ) ) * np . c...
def load_cufflinks_fpkm_dict ( * args , ** kwargs ) : """Returns dictionary mapping feature identifier ( either transcript or gene ID ) to FPKM expression value ."""
return { row . id : row . fpkm for ( _ , row ) in load_cufflinks_dataframe ( * args , ** kwargs ) . iterrows ( ) }
async def create_vm ( self , preset_name : str , image : str , flavor : str , security_groups : List = None , userdata : Dict = None , key_name : str = None , availability_zone : str = None , subnets : List = None ) -> Any : """Create ( boot ) a new server . : arg string preset _ name : Name of vm group where vm ...
raise NotImplementedError
def _ParseCommon2003CachedEntry ( self , value_data , cached_entry_offset ) : """Parses the cached entry structure common for Windows 2003 , Vista and 7. Args : value _ data ( bytes ) : value data . cached _ entry _ offset ( int ) : offset of the first cached entry data relative to the start of the value da...
data_type_map = self . _GetDataTypeMap ( 'appcompatcache_cached_entry_2003_common' ) try : cached_entry = self . _ReadStructureFromByteStream ( value_data [ cached_entry_offset : ] , cached_entry_offset , data_type_map ) except ( ValueError , errors . ParseError ) as exception : raise errors . ParseError ( 'Una...
def month_roll ( self ) : """Define default roll function to be called in apply method ."""
if self . _prefix . endswith ( 'S' ) : # MonthBegin roll_func = self . m_offset . rollback else : # MonthEnd roll_func = self . m_offset . rollforward return roll_func
def event_loop ( self ) : """Event loop ."""
try : zmq . eventloop . ioloop . IOLoop . current ( ) . start ( ) except KeyboardInterrupt : zmq . eventloop . ioloop . IOLoop . current ( ) . stop ( )
def autoset_margins ( self ) : """auto - set margins left , bottom , right , top according to the specified margins ( in pixels ) and axes extent ( taking into account labels , title , axis )"""
if not self . conf . auto_margins : return # coordinates in px - > [ 0,1 ] in figure coordinates trans = self . fig . transFigure . inverted ( ) . transform # Static margins if not self . use_dates : self . conf . margins = l , t , r , b = self . get_default_margins ( ) self . gridspec . update ( left = l ,...
def get_first_language ( self , site_id = None ) : """Return the first language for the current site . This can be used for user interfaces , where the languages are displayed in tabs ."""
if site_id is None : site_id = getattr ( settings , 'SITE_ID' , None ) try : return self [ site_id ] [ 0 ] [ 'code' ] except ( KeyError , IndexError ) : # No configuration , always fallback to default language . # This is essentially a non - multilingual configuration . return self [ 'default' ] [ 'code' ]
def enclosure_directed ( self ) : """Networkx DiGraph of polygon enclosure"""
root , enclosure = polygons . enclosure_tree ( self . polygons_closed ) self . _cache [ 'root' ] = root return enclosure
def __branch_point_dfs ( dfs_data ) : """DFS that calculates the b ( u ) and N ( u ) lookups , and also reorders the adjacency lists ."""
u = dfs_data [ 'ordering' ] [ 0 ] large_n = { } large_n [ u ] = 0 stem = { } stem [ u ] = u b = { } b [ u ] = 1 __branch_point_dfs_recursive ( u , large_n , b , stem , dfs_data ) dfs_data [ 'N_u_lookup' ] = large_n dfs_data [ 'b_u_lookup' ] = b return
def set_environ ( inherit = True , append = { } ) : """Helper method for passing environment variables to the subprocess ."""
_environ = { } if not inherit else environ for k , v in append . iteritems ( ) : _environ [ k ] = v return _environ
def get_pickup_time_estimates ( self , latitude , longitude , ride_type = None ) : """Get pickup time estimates ( ETA ) for products at a given location . Parameters latitude ( float ) The latitude component of a location . longitude ( float ) The longitude component of a location . ride _ type ( str ) ...
args = OrderedDict ( [ ( 'lat' , latitude ) , ( 'lng' , longitude ) , ( 'ride_type' , ride_type ) , ] ) return self . _api_call ( 'GET' , 'v1/eta' , args = args )
def _build_url_rewriter ( cls , session : AppSession ) : '''Build URL rewriter if needed .'''
if session . args . escaped_fragment or session . args . strip_session_id : return session . factory . new ( 'URLRewriter' , hash_fragment = session . args . escaped_fragment , session_id = session . args . strip_session_id )
def _get_beacons ( self , include_opts = True , include_pillar = True ) : '''Return the beacons data structure'''
beacons = { } if include_pillar : pillar_beacons = self . opts . get ( 'pillar' , { } ) . get ( 'beacons' , { } ) if not isinstance ( pillar_beacons , dict ) : raise ValueError ( 'Beacons must be of type dict.' ) beacons . update ( pillar_beacons ) if include_opts : opts_beacons = self . opts . ...
def normalize ( self ) : """Returns a new normalized ( sorted and compacted ) : class : ` FrameSet ` . Returns : : class : ` FrameSet ` :"""
return FrameSet ( FrameSet . framesToFrameRange ( self . items , sort = True , compress = False ) )
def facilityNetToMs ( ) : """FACILITY Section 9.3.9.1"""
a = TpPd ( pd = 0x3 ) b = MessageType ( mesType = 0x3a ) # 00111010 c = Facility ( ) packet = a / b / c return packet
def clone ( self , label ) : """Clones this volume to a new volume in the same region with the given label : param label : The label for the new volume . : returns : The new volume object ."""
result = self . _client . post ( '{}/clone' . format ( Volume . api_endpoint ) , model = self , data = { 'label' : label } ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response cloning volume!' ) return Volume ( self . _client , result [ 'id' ] , result )
def _none_accepter ( validation_callable # type : Callable ) : # type : ( . . . ) - > Callable """Wraps the given validation callable to accept None values silently . When a None value is received by the wrapper , it is not passed to the validation _ callable and instead this function will return True . When any ...
# option ( a ) use the ` decorate ( ) ` helper method to preserve name and signature of the inner object # = = > NO , we want to support also non - function callable objects # option ( b ) simply create a wrapper manually def accept_none ( x ) : if x is not None : # proceed with validation as usual return v...
def area ( boxes ) : """Args : boxes : nx4 floatbox Returns :"""
x_min , y_min , x_max , y_max = tf . split ( boxes , 4 , axis = 1 ) return tf . squeeze ( ( y_max - y_min ) * ( x_max - x_min ) , [ 1 ] )
def resend_transaction_frames ( self , connection , transaction ) : """Resend the messages that were ACK ' d in specified transaction . This is called by the engine when there is an abort command . @ param connection : The client connection that aborted the transaction . @ type connection : L { coilmq . serve...
for frame in self . _transaction_frames [ connection ] [ transaction ] : self . send ( frame )
def all ( cls ) : """Wrapper around _ all ( ) to cache and return all results of something > > > ec2 . instances . all ( )"""
if not hasattr ( cls , '_cache' ) : cls . _cache = cls . _all ( ) return cls . _cache
def children ( args ) : """% prog children gff _ file Get the children that have the same parent ."""
p = OptionParser ( children . __doc__ ) p . add_option ( "--parents" , default = "gene" , help = "list of features to extract, use comma to separate (e.g." "'gene,mRNA') [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) gff_file , = args g = ma...
def _close_connection ( self , frame_in ) : """Connection Close . : param specification . Connection . Close frame _ in : Amqp frame . : return :"""
self . _set_connection_state ( Stateful . CLOSED ) if frame_in . reply_code != 200 : reply_text = try_utf8_decode ( frame_in . reply_text ) message = ( 'Connection was closed by remote server: %s' % reply_text ) exception = AMQPConnectionError ( message , reply_code = frame_in . reply_code ) self . _con...
def notify_mail ( title , message , recipient = None , sender = None , smtp_host = None , smtp_port = None , ** kwargs ) : """Mail notification method taking a * title * and a string * message * . * recipient * , * sender * , * smtp _ host * and * smtp _ port * default to the configuration values in the [ notific...
cfg = Config . instance ( ) if not recipient : recipient = cfg . get_expanded ( "notifications" , "mail_recipient" ) if not sender : sender = cfg . get_expanded ( "notifications" , "mail_sender" ) if not smtp_host : smtp_host = cfg . get_expanded ( "notifications" , "mail_smtp_host" ) if not smtp_port : ...
def global_variable_id_generator ( size = 10 , chars = string . ascii_uppercase ) : """Create a new and unique global variable id Generates an id for a global variable . It randomly samples from random ascii uppercase letters size times and concatenates them . If the id already exists it draws a new one . : p...
new_global_variable_id = '' . join ( random . choice ( chars ) for x in range ( size ) ) while new_global_variable_id in used_global_variable_ids : new_global_variable_id = '' . join ( random . choice ( chars ) for x in range ( size ) ) used_global_variable_ids . append ( new_global_variable_id ) return new_global_...
def read_pixels ( viewport = None , alpha = True , out_type = 'unsigned_byte' ) : """Read pixels from the currently selected buffer . Under most circumstances , this function reads from the front buffer . Unlike all other functions in vispy . gloo , this function directly executes an OpenGL command . Parame...
# Check whether the GL context is direct or remote context = get_current_canvas ( ) . context if context . shared . parser . is_remote ( ) : raise RuntimeError ( 'Cannot use read_pixels() with remote GLIR parser' ) finish ( ) # noqa - finish first , also flushes GLIR commands type_dict = { 'unsigned_byte' : gl . GL...
def pick_best_methods ( stochastic ) : """Picks the StepMethods best suited to handle a stochastic variable ."""
# Keep track of most competent methohd max_competence = 0 # Empty set of appropriate StepMethods best_candidates = set ( [ ] ) # Loop over StepMethodRegistry for method in StepMethodRegistry : # Parse method and its associated competence try : competence = method . competence ( stochastic ) except : ...
def __add_tokenization ( self , tree ) : """adds a node for each token ID in the document"""
for token_id in self . get_token_ids ( tree ) : self . add_node ( token_id , layers = { self . ns } ) self . tokens . append ( token_id )
def soundex ( self , name , length = 8 ) : '''Calculate soundex of given string This function calculates soundex for Indian language string as well as English string . This function is exposed as service method for JSONRPC in SILPA framework . : param name : String whose Soundex value to be calculated :...
sndx = [ ] fc = name [ 0 ] # translate alpha chars in name to soundex digits for c in name [ 1 : ] . lower ( ) : d = str ( self . soundexCode ( c ) ) # remove all 0s from the soundex code if d == '0' : continue # duplicate consecutive soundex digits are skipped if len ( sndx ) == 0 : ...