signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def fix_config ( self , options ) : """Fixes the options , if necessary . I . e . , it adds all required elements to the dictionary . : param options : the options to fix : type options : dict : return : the ( potentially ) fixed options : rtype : dict"""
options = super ( Console , self ) . fix_config ( options ) opt = "prefix" if opt not in options : options [ opt ] = "" if opt not in self . help : self . help [ opt ] = "The prefix for the output (string)." return options
def rotate ( self , vecs ) : """Rotate input vector ( s ) by the rotation matrix . ` Args : vecs ( np . ndarray ) : Input vector ( s ) with dtype = np . float32. The shape can be a single vector ( D , ) or several vectors ( N , D ) Returns : np . ndarray : Rotated vectors with the same shape and dtype to ...
assert vecs . dtype == np . float32 assert vecs . ndim in [ 1 , 2 ] if vecs . ndim == 2 : return vecs @ self . R elif vecs . ndim == 1 : return ( vecs . reshape ( 1 , - 1 ) @ self . R ) . reshape ( - 1 )
def get_invitation ( self , invitation_id , ** kwargs ) : # noqa : E501 """Details of a user invitation . # noqa : E501 An endpoint for retrieving the details of an active user invitation sent for a new or an existing user to join the account . * * Example usage : * * ` curl https : / / api . us - east - 1 . mbed...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . get_invitation_with_http_info ( invitation_id , ** kwargs ) # noqa : E501 else : ( data ) = self . get_invitation_with_http_info ( invitation_id , ** kwargs ) # noqa : E501 return data
def _determine_colorspace ( self , colorspace = None , ** kwargs ) : """Determine the colorspace from the supplied inputs . Parameters colorspace : str , optional Either ' rgb ' or ' gray ' ."""
if colorspace is None : # Must infer the colorspace from the image dimensions . if len ( self . shape ) < 3 : # A single channel image is grayscale . self . _colorspace = opj2 . CLRSPC_GRAY elif self . shape [ 2 ] == 1 or self . shape [ 2 ] == 2 : # A single channel image or an image with two channels i...
def create_css ( self , fileid = None ) : """Generate the final CSS string"""
if fileid : rules = self . _rules . get ( fileid ) or [ ] else : rules = self . rules compress = self . _scss_opts . get ( 'compress' , True ) if compress : sc , sp , tb , nl = False , '' , '' , '' else : sc , sp , tb , nl = True , ' ' , ' ' , '\n' scope = set ( ) return self . _create_css ( rules , sc...
def _rollback ( self , where ) : """Truncate the output buffer at offset I { where } , and remove any compression table entries that pointed beyond the truncation point . @ param where : the offset @ type where : int"""
self . output . seek ( where ) self . output . truncate ( ) keys_to_delete = [ ] for k , v in self . compress . iteritems ( ) : if v >= where : keys_to_delete . append ( k ) for k in keys_to_delete : del self . compress [ k ]
def _check_remote_option ( self , option ) : """Test the status of remote negotiated Telnet options ."""
if not self . telnet_opt_dict . has_key ( option ) : self . telnet_opt_dict [ option ] = TelnetOption ( ) return self . telnet_opt_dict [ option ] . remote_option
def members_data_for_in ( self , leaderboard_name , members ) : '''Retrieve the optional member data for a given list of members in the named leaderboard . @ param leaderboard _ name [ String ] Name of the leaderboard . @ param members [ Array ] Member names . @ return Array of strings of optional member data...
return self . redis_connection . hmget ( self . _member_data_key ( leaderboard_name ) , members )
def run_from_argv ( self , argv ) : """Set the default Gherkin test runner for its options to be parsed ."""
self . test_runner = test_runner_class super ( Command , self ) . run_from_argv ( argv )
def previous_unwrittable_on_col ( view , coords ) : """Return position of the previous ( in column ) letter that is unwrittable"""
x , y = coords miny = - 1 for offset in range ( y - 1 , miny , - 1 ) : letter = view [ x , offset ] if letter not in REWRITABLE_LETTERS : return offset return None
def join ( strings : Optional [ Sequence [ str ] ] , separator : str = "" ) -> str : """Join strings in a given sequence . Return an empty string if it is None or empty , otherwise join all items together separated by separator if provided ."""
return separator . join ( s for s in strings if s ) if strings else ""
def tokenize ( self , string ) : '''Yield tokens from the input string or throw ConfigParseError'''
pos = 0 while pos < len ( string ) : m = SKIP_RE . match ( string , pos = pos ) if m : skip_lines = m . group ( 0 ) . split ( '\n' ) if len ( skip_lines ) > 1 : self . row += len ( skip_lines ) - 1 self . column = 1 + len ( skip_lines [ - 1 ] ) else : ...
def escape ( x , lb = False ) : """Ensure a string does not contain HTML - reserved characters ( including double quotes ) Optionally also insert a linebreak if the string is too long"""
# Insert a linebreak ? Roughly around the middle of the string , if lb : l = len ( x ) if l >= 10 : l >>= 1 # middle of the string s1 = x . find ( ' ' , l ) # first ws to the right s2 = x . rfind ( ' ' , 0 , l ) # first ws to the left if s2 > 0 : ...
def getbfs ( coords , gbasis ) : """Convenience function for both wavefunction and density based on PyQuante Ints . py ."""
sym2powerlist = { 'S' : [ ( 0 , 0 , 0 ) ] , 'P' : [ ( 1 , 0 , 0 ) , ( 0 , 1 , 0 ) , ( 0 , 0 , 1 ) ] , 'D' : [ ( 2 , 0 , 0 ) , ( 0 , 2 , 0 ) , ( 0 , 0 , 2 ) , ( 1 , 1 , 0 ) , ( 0 , 1 , 1 ) , ( 1 , 0 , 1 ) ] , 'F' : [ ( 3 , 0 , 0 ) , ( 2 , 1 , 0 ) , ( 2 , 0 , 1 ) , ( 1 , 2 , 0 ) , ( 1 , 1 , 1 ) , ( 1 , 0 , 2 ) , ( 0 , 3 ...
def getVoxelsScalar ( self , vmin = None , vmax = None ) : """Return voxel content as a ` ` numpy . array ` ` . : param float vmin : rescale scalar content to match ` vmin ` and ` vmax ` range . : param float vmax : rescale scalar content to match ` vmin ` and ` vmax ` range ."""
nx , ny , nz = self . image . GetDimensions ( ) voxdata = np . zeros ( [ nx , ny , nz ] ) lsx = range ( nx ) lsy = range ( ny ) lsz = range ( nz ) renorm = vmin is not None and vmax is not None for i in lsx : for j in lsy : for k in lsz : s = self . image . GetScalarComponentAsFloat ( i , j , k ...
def set_state_data ( cls , entity , data ) : """Sets the state data for the given entity to the given data . This also works for unmanaged entities ."""
attr_names = get_domain_class_attribute_names ( type ( entity ) ) nested_items = [ ] for attr , new_attr_value in iteritems_ ( data ) : if not attr . entity_attr in attr_names : raise ValueError ( 'Can not set attribute "%s" for entity ' '"%s".' % ( attr . entity_attr , entity ) ) if '.' in attr . entit...
def reverseCommit ( self ) : """Re - insert the previously removed character ( s ) ."""
# Get the text cursor for the current document . tc = self . qteWidget . textCursor ( ) # Mark the previously inserted text and remove it . tc . setPosition ( self . cursorPos0 , QtGui . QTextCursor . MoveAnchor ) tc . setPosition ( self . cursorPos1 , QtGui . QTextCursor . KeepAnchor ) tc . removeSelectedText ( ) tc ....
def gracefulShutdown ( self ) : """Start shutting down"""
if not self . bf . perspective : log . msg ( "No active connection, shutting down NOW" ) reactor . stop ( ) return log . msg ( "Telling the master we want to shutdown after any running builds are finished" ) d = self . bf . perspective . callRemote ( "shutdown" ) def _shutdownfailed ( err ) : if err . c...
def _pick_inserted_ops_moment_indices ( operations : Sequence [ ops . Operation ] , start : int = 0 , frontier : Dict [ ops . Qid , int ] = None ) -> Tuple [ Sequence [ int ] , Dict [ ops . Qid , int ] ] : """Greedily assigns operations to moments . Args : operations : The operations to assign to moments . st...
if frontier is None : frontier = defaultdict ( lambda : 0 ) moment_indices = [ ] for op in operations : op_start = max ( start , max ( frontier [ q ] for q in op . qubits ) ) moment_indices . append ( op_start ) for q in op . qubits : frontier [ q ] = max ( frontier [ q ] , op_start + 1 ) return...
def stochastic_from_dist ( name , logp , random = None , logp_partial_gradients = { } , dtype = np . float , mv = False ) : """Return a Stochastic subclass made from a particular distribution . : Parameters : name : string The name of the new class . logp : function The log - probability function . rand...
( args , defaults ) = utils . get_signature ( logp ) parent_names = args [ 1 : ] try : parents_default = dict ( zip ( args [ - len ( defaults ) : ] , defaults ) ) except TypeError : # No parents at all . parents_default = { } name = capitalize ( name ) # Build docstring from distribution parents_str = '' if par...
def _summarize_inputs ( samples , out_dir ) : """Summarize inputs for MultiQC reporting in display ."""
logger . info ( "summarize target information" ) if samples [ 0 ] . get ( "analysis" , "" ) . lower ( ) in [ "variant" , "variant2" ] : metrics_dir = utils . safe_makedir ( os . path . join ( out_dir , "report" , "metrics" ) ) samples = _merge_target_information ( samples , metrics_dir ) logger . info ( "summar...
def post_authentication ( self , user , request , sid , ** kwargs ) : """Things that are done after a successful authentication . : param user : : param request : : param sid : : param kwargs : : return : A dictionary with ' response _ args '"""
response_info = { } # Do the authorization try : permission = self . endpoint_context . authz ( user , client_id = request [ 'client_id' ] ) except ToOld as err : return self . error_response ( response_info , 'access_denied' , 'Authentication to old {}' . format ( err . args ) ) except Exception as err : r...
def _set_priv ( self , v , load = False ) : """Setter method for priv , mapped from YANG variable / rbridge _ id / snmp _ server / user / priv ( enumeration ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ priv is considered as a private method . Backends looking to ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'AES128' : { 'value' : 2 } , u'DES' : { 'value' : 0 } , u'nopriv' : { 'value' : 1 } } , ) , default = unicode ( "nopriv" ) , is_...
def _MergeMessage ( node , source , destination , replace_message , replace_repeated ) : """Merge all fields specified by a sub - tree from source to destination ."""
source_descriptor = source . DESCRIPTOR for name in node : child = node [ name ] field = source_descriptor . fields_by_name [ name ] if field is None : raise ValueError ( 'Error: Can\'t find field {0} in message {1}.' . format ( name , source_descriptor . full_name ) ) if child : # Sub - paths a...
def output_size ( self ) : """Returns the module output size ."""
if callable ( self . _output_size ) : self . _output_size = self . _output_size ( ) return self . _output_size
def atlas_peer_refresh_zonefile_inventory ( my_hostport , peer_hostport , byte_offset , timeout = None , peer_table = None , con = None , path = None , local_inv = None ) : """Refresh a peer ' s zonefile recent inventory vector entries , by removing every bit after byte _ offset and re - synchronizing them . Th...
if timeout is None : timeout = atlas_inv_timeout ( ) if local_inv is None : # get local zonefile inv inv_len = atlasdb_zonefile_inv_length ( con = con , path = path ) local_inv = atlas_make_zonefile_inventory ( 0 , inv_len , con = con , path = path ) maxlen = len ( local_inv ) with AtlasPeerTableLocked ( pe...
def visualize_explanation ( explanation , label = None ) : """Given the output of the explain ( ) endpoint , produces a terminal visual that plots response strength over a sequence"""
if not sys . version_info [ : 2 ] >= ( 3 , 5 ) : raise IndicoError ( "Python >= 3.5+ is required for explanation visualization" ) try : from colr import Colr as C except ImportError : raise IndicoError ( "Package colr >= 0.8.1 is required for explanation visualization." ) cursor = 0 text = explanation [ 'te...
def _with_retries ( self , pool , fn ) : """Performs the passed function with retries against the given pool . : param pool : the connection pool to use : type pool : Pool : param fn : the function to pass a transport : type fn : function"""
skip_nodes = [ ] def _skip_bad_nodes ( transport ) : return transport . _node not in skip_nodes retry_count = self . retries - 1 first_try = True current_try = 0 while True : try : with pool . transaction ( _filter = _skip_bad_nodes , yield_resource = True ) as resource : transport = resourc...
def prepend_name_scope ( name , import_scope ) : """Prepends name scope to a name ."""
# Based on tensorflow / python / framework / ops . py implementation . if import_scope : try : str_to_replace = r"([\^]|loc:@|^)(.*)" return re . sub ( str_to_replace , r"\1" + import_scope + r"/\2" , tf . compat . as_str_any ( name ) ) except TypeError as e : # If the name is not of a type we c...
def get_element_id ( self , complete_name ) : """Get the TocElement element id - number of the element with the supplied name ."""
[ group , name ] = complete_name . split ( '.' ) element = self . get_element ( group , name ) if element : return element . ident else : logger . warning ( 'Unable to find variable [%s]' , complete_name ) return None
def edit_message_text ( self , chat_id : Union [ int , str ] , message_id : int , text : str , parse_mode : str = "" , disable_web_page_preview : bool = None , reply_markup : "pyrogram.InlineKeyboardMarkup" = None ) -> "pyrogram.Message" : """Use this method to edit text messages . Args : chat _ id ( ` ` int ` ...
style = self . html if parse_mode . lower ( ) == "html" else self . markdown r = self . send ( functions . messages . EditMessage ( peer = self . resolve_peer ( chat_id ) , id = message_id , no_webpage = disable_web_page_preview or None , reply_markup = reply_markup . write ( ) if reply_markup else None , ** style . pa...
def website_verificable ( self , website ) : """True if the website is LetsEncrypt verificable : it should have the verification app on the / . well - known path"""
required_app = [ self . LETSENCRYPT_VERIFY_APP_NAME , '/.well-known' ] for app in website [ 'website_apps' ] : if app == required_app : return True return False
def show_health_monitor ( self , health_monitor , ** _params ) : """Fetches information of a certain load balancer health monitor ."""
return self . get ( self . health_monitor_path % ( health_monitor ) , params = _params )
def get_identifier ( self ) : """For methods this is the return type , the name and the ( non - pretty ) argument descriptor . For fields it is simply the name . The return - type of methods is attached to the identifier when it is a bridge method , which can technically allow two methods with the same name...
ident = self . get_name ( ) if self . is_method : args = "," . join ( self . get_arg_type_descriptors ( ) ) if self . is_bridge ( ) : ident = "%s(%s):%s" % ( ident , args , self . get_descriptor ( ) ) else : ident = "%s(%s)" % ( ident , args ) return ident
def next_frame_glow_shapes ( ) : """Hparams for qualitative and quantitative results on shapes dataset ."""
hparams = next_frame_glow_bair_quant ( ) hparams . video_num_input_frames = 1 hparams . video_num_target_frames = 2 hparams . num_train_frames = 2 hparams . num_cond_latents = 1 hparams . coupling = "additive" hparams . coupling_width = 512 hparams . latent_encoder_depth = 10 hparams . latent_skip = False hparams . lea...
def validate ( self , options ) : """Validate the options or exit ( )"""
if not options . port : self . parser . error ( "'port' is required" ) if options . port == options . monitor_port : self . parser . error ( "'port' and 'monitor-port' must not be the same." ) if options . buffer_size <= 0 : self . parser . error ( "'buffer_size' must be > 0." ) try : codecs . getencode...
def stop_transmit ( self , fd ) : """Stop yielding writeability events for ` fd ` . Redundant calls to : meth : ` stop _ transmit ` are silently ignored , this may change in future ."""
self . _wfds . pop ( fd , None ) self . _update ( fd )
def _get_user ( self , username ) : """Custom helper method to retrieve a user ' s data from Redis ."""
data = self . client . get ( self . _key ( username ) ) if data is None : return None return json . loads ( data . decode ( ) )
def get_extensions ( extstr ) : """Return zero or greater Annotation Extensions , given a line of text ."""
# Extension examples : # has _ direct _ input ( UniProtKB : P37840 ) , occurs _ in ( GO : 0005576) # part _ of ( UBERON : 0006618 ) , part _ of ( UBERON : 0002302) # occurs _ in ( CL : 0000988 ) | occurs _ in ( CL : 0001021) if not extstr : return None exts = [ ] for ext_lst in extstr . split ( '|' ) : grp = [ ...
def block_specification_to_number ( block : BlockSpecification , web3 : Web3 ) -> BlockNumber : """Converts a block specification to an actual block number"""
if isinstance ( block , str ) : msg = f"string block specification can't contain {block}" assert block in ( 'latest' , 'pending' ) , msg number = web3 . eth . getBlock ( block ) [ 'number' ] elif isinstance ( block , T_BlockHash ) : number = web3 . eth . getBlock ( block ) [ 'number' ] elif isinstance (...
def is_koish ( board , c ) : 'Check if c is surrounded on all sides by 1 color , and return that color'
if board [ c ] != EMPTY : return None neighbors = { board [ n ] for n in NEIGHBORS [ c ] } if len ( neighbors ) == 1 and EMPTY not in neighbors : return list ( neighbors ) [ 0 ] else : return None
def connect_sqs ( aws_access_key_id = None , aws_secret_access_key = None , ** kwargs ) : """: type aws _ access _ key _ id : string : param aws _ access _ key _ id : Your AWS Access Key ID : type aws _ secret _ access _ key : string : param aws _ secret _ access _ key : Your AWS Secret Access Key : rtype :...
from boto . sqs . connection import SQSConnection return SQSConnection ( aws_access_key_id , aws_secret_access_key , ** kwargs )
def vq_discrete_bottleneck ( x , hparams ) : """Simple vector quantized discrete bottleneck ."""
tf . logging . info ( "Using EMA with beta = {}" . format ( hparams . beta ) ) bottleneck_size = 2 ** hparams . bottleneck_bits x_shape = common_layers . shape_list ( x ) x = tf . reshape ( x , [ - 1 , hparams . hidden_size ] ) x_means_hot , e_loss = vq_nearest_neighbor ( x , hparams ) means , ema_means , ema_count = (...
from typing import List def even_length_sorted ( strings : List [ str ] ) -> List [ str ] : """A function that receives a list of strings as input , removes strings with odd length from it , and returns the altered list sorted in ascending order . The input list always contains strings and could include dupli...
# Sorting alphabetically strings . sort ( ) # Removing odd length strings and sorting by length even_length_strings = sorted ( [ s for s in strings if len ( s ) % 2 == 0 ] , key = len ) return even_length_strings
def check_for_insufficient_eth ( self , transaction_name : str , transaction_executed : bool , required_gas : int , block_identifier : BlockSpecification , ) : """After estimate gas failure checks if our address has enough balance . If the account did not have enough ETH balance to execute the , transaction the...
if transaction_executed : return our_address = to_checksum_address ( self . address ) balance = self . web3 . eth . getBalance ( our_address , block_identifier ) required_balance = required_gas * self . gas_price ( ) if balance < required_balance : msg = f'Failed to execute {transaction_name} due to insufficien...
def _f_lcs ( llcs , m , n ) : """Computes the LCS - based F - measure score Source : http : / / research . microsoft . com / en - us / um / people / cyl / download / papers / rouge - working - note - v1.3.1 . pdf : param llcs : Length of LCS : param m : number of words in reference summary : param n : num...
r_lcs = llcs / m p_lcs = llcs / n beta = p_lcs / r_lcs num = ( 1 + ( beta ** 2 ) ) * r_lcs * p_lcs denom = r_lcs + ( ( beta ** 2 ) * p_lcs ) return num / denom
def applyFilters ( self , endpoint ) : """Apply filter functions to an endpoint until one of them returns non - None ."""
for filter_function in self . filter_functions : e = filter_function ( endpoint ) if e is not None : # Once one of the filters has returned an # endpoint , do not apply any more . return e return None
def from_rdmol ( rdmol , assign_descriptor = True ) : """Convert RDMol to molecule"""
mol = Compound ( ) conf = rdmol . GetConformer ( ) Chem . Kekulize ( rdmol ) for atom in rdmol . GetAtoms ( ) : key = atom . GetIdx ( ) a = Atom ( atom . GetSymbol ( ) ) a . coords = conf . GetAtomPosition ( key ) mol . add_atom ( key , a ) for bond in rdmol . GetBonds ( ) : u = bond . GetBeginAtomI...
def import_syscal_bin ( self , filename , ** kwargs ) : """Syscal import timestep : int or : class : ` datetime . datetime ` if provided use this value to set the ' timestep ' column of the produced dataframe . Default : 0"""
timestep = kwargs . get ( 'timestep' , None ) if 'timestep' in kwargs : del ( kwargs [ 'timestep' ] ) self . logger . info ( 'IRIS Syscal Pro bin import' ) with LogDataChanges ( self , filter_action = 'import' ) : data , electrodes , topography = reda_syscal . import_bin ( filename , ** kwargs ) if timestep...
def on_message ( self , unused_channel , basic_deliver , properties , body ) : """Invoked by pika when a message is delivered from RabbitMQ . The channel is passed for your convenience . The basic _ deliver object that is passed in carries the exchange , routing key , delivery tag and a redelivered flag for t...
logger . info ( 'Received message' , delivery_tag = basic_deliver . delivery_tag , app_id = properties . app_id , msg = body , ) self . acknowledge_message ( basic_deliver . delivery_tag )
def _url_to ( self , page ) : """Get the url of a page"""
anchor = "" if "#" in page : page , anchor = page . split ( "#" ) anchor = "#" + anchor meta = self . _get_page_meta ( page ) return meta . get ( "url" )
def get_new_user_credentials ( self ) : """Gets new credentials : return : New user credentials file upon user prompt"""
# OAuth2.0 authorization flow flow = client . flow_from_clientsecrets ( self . app_secrets , self . scope ) flow . user_agent = self . app_name return tools . run_flow ( flow , self . store )
def _handle_socket ( self , event : int , fd : int , multi : Any , data : bytes ) -> None : """Called by libcurl when it wants to change the file descriptors it cares about ."""
event_map = { pycurl . POLL_NONE : ioloop . IOLoop . NONE , pycurl . POLL_IN : ioloop . IOLoop . READ , pycurl . POLL_OUT : ioloop . IOLoop . WRITE , pycurl . POLL_INOUT : ioloop . IOLoop . READ | ioloop . IOLoop . WRITE , } if event == pycurl . POLL_REMOVE : if fd in self . _fds : self . io_loop . remove_h...
def memory ( self , name , mem = 0 , swap = 0 ) : """Set / Get memory cgroup specification / limitation the call to this method will always GET the current set values for both mem and swap . If mem is not zero , the memory will set the memory limit to the given value , and swap to the given value ( even 0) : ...
args = { 'name' : name , 'mem' : mem , 'swap' : swap , } self . _memory_spec . check ( args ) return self . _client . json ( 'cgroup.memory.spec' , args )
def colorbrewer2_url ( self ) : """URL that can be used to view the color map at colorbrewer2 . org ."""
url = 'http://colorbrewer2.org/index.html?type={0}&scheme={1}&n={2}' return url . format ( self . type . lower ( ) , self . name , self . number )
def parse_relation ( obj : dict ) -> BioCRelation : """Deserialize a dict obj to a BioCRelation object"""
rel = BioCRelation ( ) rel . id = obj [ 'id' ] rel . infons = obj [ 'infons' ] for node in obj [ 'nodes' ] : rel . add_node ( BioCNode ( node [ 'refid' ] , node [ 'role' ] ) ) return rel
def _handle_status ( self , key , value ) : """Parse a status code from the attached GnuPG process . : raises : : exc : ` ~ exceptions . ValueError ` if the status message is unknown ."""
if key in ( "DELETE_PROBLEM" , "KEY_CONSIDERED" ) : self . status = self . problem_reason . get ( value , "Unknown error: %r" % value ) else : raise ValueError ( "Unknown status message: %r" % key )
def breslauer_corrections ( seq , pars_error ) : '''Sum corrections for Breslauer ' 84 method . : param seq : sequence for which to calculate corrections . : type seq : str : param pars _ error : dictionary of error corrections : type pars _ error : dict : returns : Corrected delta _ H and delta _ S param...
deltas_corr = [ 0 , 0 ] contains_gc = 'G' in str ( seq ) or 'C' in str ( seq ) only_at = str ( seq ) . count ( 'A' ) + str ( seq ) . count ( 'T' ) == len ( seq ) symmetric = seq == seq . reverse_complement ( ) terminal_t = str ( seq ) [ 0 ] == 'T' + str ( seq ) [ - 1 ] == 'T' for i , delta in enumerate ( [ 'delta_h' , ...
def angle_to_cartesian ( lon , lat ) : """Convert spherical coordinates to cartesian unit vectors ."""
theta = np . array ( np . pi / 2. - lat ) return np . vstack ( ( np . sin ( theta ) * np . cos ( lon ) , np . sin ( theta ) * np . sin ( lon ) , np . cos ( theta ) ) ) . T
def read_data ( self , chan = None , begtime = None , endtime = None , begsam = None , endsam = None , s_freq = None ) : """Read the data and creates a ChanTime instance Parameters chan : list of strings names of the channels to read begtime : int or datedelta or datetime or list start of the data to read...
data = ChanTime ( ) data . start_time = self . header [ 'start_time' ] data . s_freq = s_freq = s_freq if s_freq else self . header [ 's_freq' ] if chan is None : chan = self . header [ 'chan_name' ] if not ( isinstance ( chan , list ) or isinstance ( chan , tuple ) ) : raise TypeError ( 'Parameter "chan" shoul...
def gen_cannon_grad_spec ( choose , coeffs , pivots ) : """Generate Cannon gradient spectra Parameters labels : default values for [ teff , logg , feh , cfe , nfe , afe , ak ] choose : val of cfe or nfe , whatever you ' re varying low : lowest val of cfe or nfe , whatever you ' re varying high : highest v...
base_labels = [ 4800 , 2.5 , 0.03 , 0.10 , - 0.17 , - 0.17 , 0 , - 0.16 , - 0.13 , - 0.15 , 0.13 , 0.08 , 0.17 , - 0.062 ] label_names = np . array ( [ 'TEFF' , 'LOGG' , 'AK' , 'Al' , 'Ca' , 'C' , 'Fe' , 'Mg' , 'Mn' , 'Ni' , 'N' , 'O' , 'Si' , 'Ti' ] ) label_atnum = np . array ( [ 0 , 1 , - 1 , 13 , 20 , 6 , 26 , 12 , ...
def _parse_for_element_meta_data ( self , meta_data ) : """Load meta data for state elements The meta data of the state meta data file also contains the meta data for state elements ( data ports , outcomes , etc ) . This method parses the loaded meta data for each state element model . The meta data of the el...
# print ( " _ parse meta data " , meta _ data ) for data_port_m in self . input_data_ports : self . _copy_element_meta_data_from_meta_file_data ( meta_data , data_port_m , "input_data_port" , data_port_m . data_port . data_port_id ) for data_port_m in self . output_data_ports : self . _copy_element_meta_data_fr...
def close ( self ) : """Closes the lvm and vg _ t handle . Usually you would never need to use this method unless you are doing operations using the ctypes function wrappers in conversion . py * Raises : * * HandleError"""
if self . handle : cl = lvm_vg_close ( self . handle ) if cl != 0 : raise HandleError ( "Failed to close VG handle after init check." ) self . __vgh = None self . lvm . close ( )
def set_type ( spec , obj_type ) : """Updates type integer in the cerate UO specification . Type has to already have generations flags set correctly . Generation field is set accordingly . : param spec : : param obj _ type : : return :"""
if spec is None : raise ValueError ( 'Spec cannot be None' ) if TemplateFields . generation not in spec : spec [ TemplateFields . generation ] = { } spec [ TemplateFields . generation ] [ TemplateFields . commkey ] = Gen . CLIENT if ( obj_type & ( int ( 1 ) << TemplateFields . FLAG_COMM_GEN ) ) > 0 else Gen . L...
def generate_molecule_object_dict ( source , format , values ) : """Generate a dictionary that represents a Squonk MoleculeObject when written as JSON : param source : Molecules in molfile or smiles format : param format : The format of the molecule . Either ' mol ' or ' smiles ' : param values : Optional d...
m = { "uuid" : str ( uuid . uuid4 ( ) ) , "source" : source , "format" : format } if values : m [ "values" ] = values return m
def is_square_product ( val : int ) -> bool : """This function determines if a given number can be obtained as the product of two squares . Args : val ( int ) : Input number . Returns : bool : Returns True if the given number can be expressed as the product of squares of two numbers . Otherwise , False . ...
for i in range ( 2 , val + 1 ) : if i * i > val : break for j in range ( 2 , val + 1 ) : if i * i * j * j == val : return True return False
def match_regex ( self , regex : Pattern , required : bool = False , meaning : str = "" ) -> str : """Parse input based on a regular expression . Args : regex : Compiled regular expression object . required : Should the exception be raised on unexpected input ? meaning : Meaning of ` regex ` ( for use in er...
mo = regex . match ( self . input , self . offset ) if mo : self . offset = mo . end ( ) return mo . group ( ) if required : raise UnexpectedInput ( self , meaning )
def add_tab ( self , tab , title = '' , icon = None ) : """Adds a tab to main tab widget . : param tab : Widget to add as a new tab of the main tab widget . : param title : Tab title : param icon : Tab icon"""
if icon : tab . _icon = icon if not hasattr ( tab , 'clones' ) : tab . clones = [ ] if not hasattr ( tab , 'original' ) : tab . original = None if icon : self . main_tab_widget . addTab ( tab , icon , title ) else : self . main_tab_widget . addTab ( tab , title ) self . main_tab_widget . setCurrentI...
def add_isohybrid ( self , part_entry = 1 , mbr_id = None , part_offset = 0 , geometry_sectors = 32 , geometry_heads = 64 , part_type = 0x17 , mac = False ) : # type : ( int , Optional [ int ] , int , int , int , int , bool ) - > None '''Make an ISO a ' hybrid ' , which means that it can be booted either from a C...
if not self . _initialized : raise pycdlibexception . PyCdlibInvalidInput ( 'This object is not yet initialized; call either open() or new() to create an ISO' ) if self . eltorito_boot_catalog is None : raise pycdlibexception . PyCdlibInvalidInput ( 'The ISO must have an El Torito Boot Record to add isohybrid s...
def get_response ( self , request , parent , * args , ** kwargs ) : """Render this collected content to a response . : param request : the request : param parent : the parent collection : param args : : param kwargs : : return :"""
context = { 'page' : self , } try : return TemplateResponse ( request , self . get_layout_template_name ( ) , context ) except AttributeError : raise AttributeError ( "You need to define " "`get_layout_template_name()` on your `%s` model, " "or override `get_response()`" % type ( self ) . __name__ )
def save_spec ( spec , filename ) : """Save a protobuf model specification to file . Parameters spec : Model _ pb Protobuf representation of the model filename : str File path where the spec gets saved . Examples . . sourcecode : : python > > > coremltools . utils . save _ spec ( spec , ' HousePrice...
name , ext = _os . path . splitext ( filename ) if not ext : filename = "%s.mlmodel" % filename else : if ext != '.mlmodel' : raise Exception ( "Extension must be .mlmodel (not %s)" % ext ) with open ( filename , 'wb' ) as f : s = spec . SerializeToString ( ) f . write ( s )
def truncate ( hmac_result , length = 6 ) : """Perform the truncating ."""
assert ( len ( hmac_result ) == 20 ) offset = ord ( hmac_result [ 19 ] ) & 0xf bin_code = ( ord ( hmac_result [ offset ] ) & 0x7f ) << 24 | ( ord ( hmac_result [ offset + 1 ] ) & 0xff ) << 16 | ( ord ( hmac_result [ offset + 2 ] ) & 0xff ) << 8 | ( ord ( hmac_result [ offset + 3 ] ) & 0xff ) return bin_code % ( 10 ** l...
def phred_13_to_18 ( self , new_path = None , in_place = True ) : """Illumina - 1.3 format conversion to Illumina - 1.8 format via BioPython ."""
# New file # if new_path is None : new_fastq = self . __class__ ( new_temp_path ( suffix = self . extension ) ) else : new_fastq = self . __class__ ( new_path ) # Do it # self . format = 'fastq-illumina' new_fastq . open ( 'w' ) new_fastq . handle . writelines ( seq . format ( 'fastq-sanger' ) for seq in self )...
def RIBSystemRouteLimitExceeded_RIBRouteLimit ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) RIBSystemRouteLimitExceeded = ET . SubElement ( config , "RIBSystemRouteLimitExceeded" , xmlns = "http://brocade.com/ns/brocade-notification-stream" ) RIBRouteLimit = ET . SubElement ( RIBSystemRouteLimitExceeded , "RIBRouteLimit" ) RIBRouteLimit . text = kwargs . pop ( 'RIBRouteLimit...
def have_all_block_data ( self ) : """Have we received all block data ?"""
if not ( self . num_blocks_received == self . num_blocks_requested ) : log . debug ( "num blocks received = %s, num requested = %s" % ( self . num_blocks_received , self . num_blocks_requested ) ) return False return True
def execute_sparql_query ( query , prefix = None , endpoint = 'https://query.wikidata.org/sparql' , user_agent = config [ 'USER_AGENT_DEFAULT' ] , as_dataframe = False ) : """Static method which can be used to execute any SPARQL query : param prefix : The URI prefixes required for an endpoint , default is the Wik...
if not endpoint : endpoint = 'https://query.wikidata.org/sparql' if prefix : query = prefix + '\n' + query params = { 'query' : '#Tool: PBB_core fastrun\n' + query , 'format' : 'json' } headers = { 'Accept' : 'application/sparql-results+json' , 'User-Agent' : user_agent } response = requests . get ( endpoint , ...
def _extract_dot15d4address ( pkt , source = True ) : """This function extracts the source / destination address of a 6LoWPAN from its upper Dot15d4Data ( 802.15.4 data ) layer . params : - source : if True , the address is the source one . Otherwise , it is the destination . returns : the packed & proces...
underlayer = pkt . underlayer while underlayer is not None and not isinstance ( underlayer , Dot15d4Data ) : # noqa : E501 underlayer = underlayer . underlayer if type ( underlayer ) == Dot15d4Data : addr = underlayer . src_addr if source else underlayer . dest_addr if underlayer . underlayer . fcf_destaddr...
def estimateabundance ( self ) : """Estimate the abundance of taxonomic groups"""
logging . info ( 'Estimating abundance of taxonomic groups' ) # Create and start threads for i in range ( self . cpus ) : # Send the threads to the appropriate destination function threads = Thread ( target = self . estimate , args = ( ) ) # Set the daemon to true - something to do with thread management th...
def resize_pty ( self , width = 80 , height = 24 , width_pixels = 0 , height_pixels = 0 ) : """Resize the pseudo - terminal . This can be used to change the width and height of the terminal emulation created in a previous ` get _ pty ` call . : param int width : new width ( in characters ) of the terminal scree...
m = Message ( ) m . add_byte ( cMSG_CHANNEL_REQUEST ) m . add_int ( self . remote_chanid ) m . add_string ( "window-change" ) m . add_boolean ( False ) m . add_int ( width ) m . add_int ( height ) m . add_int ( width_pixels ) m . add_int ( height_pixels ) self . transport . _send_user_message ( m )
def run ( ) : """Run the workbench server"""
# Load the configuration file relative to this script location config_path = os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , 'config.ini' ) workbench_conf = ConfigParser . ConfigParser ( ) config_ini = workbench_conf . read ( config_path ) if not config_ini : print 'Could not locate c...
def open ( self ) : """Open a connection to an IOS - XR device . Connects to the device using SSH and drops into XML mode ."""
try : self . device = ConnectHandler ( device_type = 'cisco_xr' , ip = self . hostname , port = self . port , username = self . username , password = self . password , ** self . netmiko_kwargs ) self . device . timeout = self . timeout self . _xml_agent_alive = True # successfully open thus alive except...
def get_form ( self , request , obj = None , ** kwargs ) : """Returns a Form class for use in the admin add view . This is used by add _ view and change _ view ."""
parent_id = request . GET . get ( 'parent_id' , None ) if not parent_id : parent_id = request . POST . get ( 'parent_id' , None ) if parent_id : return AddFolderPopupForm else : folder_form = super ( FolderAdmin , self ) . get_form ( request , obj = None , ** kwargs ) def folder_form_clean ( form_obj ) ...
def read_struct ( fstream ) : """Read a likwid struct from the text stream . Args : fstream : Likwid ' s filestream . Returns ( dict ( str : str ) ) : A dict containing all likwid ' s struct info as key / value pairs ."""
line = fstream . readline ( ) . strip ( ) fragments = line . split ( "," ) fragments = [ x for x in fragments if x is not None ] partition = dict ( ) if not len ( fragments ) >= 3 : return None partition [ "struct" ] = fragments [ 0 ] partition [ "info" ] = fragments [ 1 ] partition [ "num_lines" ] = fragments [ 2 ...
def get_client_alg_keys ( client ) : """Takes a client and returns the set of keys associated with it . Returns a list of keys ."""
if client . jwt_alg == 'RS256' : keys = [ ] for rsakey in RSAKey . objects . all ( ) : keys . append ( jwk_RSAKey ( key = importKey ( rsakey . key ) , kid = rsakey . kid ) ) if not keys : raise Exception ( 'You must add at least one RSA Key.' ) elif client . jwt_alg == 'HS256' : keys = [...
def safeprint ( message , write_to_stderr = False , newline = True ) : """Wrapper around click . echo used to encapsulate its functionality . Also protects against EPIPE during click . echo calls , as this can happen normally in piped commands when the consumer closes before the producer ."""
try : click . echo ( message , nl = newline , err = write_to_stderr ) except IOError as err : if err . errno is errno . EPIPE : pass else : raise
def getAppExt ( self , loops = float ( 'inf' ) ) : """getAppExt ( loops = float ( ' inf ' ) ) Application extention . This part specifies the amount of loops . If loops is 0 or inf , it goes on infinitely ."""
if loops == 0 or loops == float ( 'inf' ) : loops = 2 ** 16 - 1 # bb = " " application extension should not be used # ( the extension interprets zero loops # to mean an infinite number of loops ) # Mmm , does not seem to work if True : bb = "\x21\xFF\x0B" # application extension bb += "N...
def create_message_buffer ( size , type ) : """Create a message buffer"""
rtn = wrapper . nn_allocmsg ( size , type ) if rtn is None : raise NanoMsgAPIError ( ) return rtn
def keyPressEvent ( self , event ) : """Handles the key press event . When the user hits F5 , the current code edit will be executed within the console ' s scope . : param event | < QtCore . QKeyEvent >"""
if event . key ( ) == QtCore . Qt . Key_F5 or ( event . key ( ) == QtCore . Qt . Key_E and event . modifiers ( ) == QtCore . Qt . ControlModifier ) : code = str ( self . _edit . toPlainText ( ) ) scope = self . viewWidget ( ) . codeScope ( ) exec code in scope , scope else : super ( XScriptView , self )...
def endpointlist_post_save ( instance , * args , ** kwargs ) : """Used to process the lines of the endpoint list ."""
with open ( instance . upload . file . name , mode = 'rb' ) as f : lines = f . readlines ( ) for url in lines : if len ( url ) > 255 : LOGGER . debug ( 'Skipping this endpoint, as it is more than 255 characters: %s' % url ) else : if Endpoint . objects . filter ( url = url , catalog = instan...
def from_dict ( cls , d ) : """Validates a dict instance and transforms it in a : py : class : ` gemstone . core . structs . JsonRpcRequest ` instance : param d : The dict instance : return : A : py : class : ` gemstone . core . structs . JsonRpcRequest ` if everything goes well , or None if the validatio...
for key in ( "method" , "jsonrpc" ) : if key not in d : raise JsonRpcInvalidRequestError ( ) # check jsonrpc version jsonrpc = d . get ( "jsonrpc" , None ) if jsonrpc != "2.0" : raise JsonRpcInvalidRequestError ( ) # check method method = d . get ( "method" , None ) if not method : raise JsonRpcInva...
def _extract_format_keys ( self , fmt_string ) : """Extract the keys of a format string ( the ' stuff ' in ' % ( stuff ) s '"""
class AccessSaver : def __init__ ( self ) : self . keys = [ ] def __getitem__ ( self , key ) : self . keys . append ( key ) a = AccessSaver ( ) fmt_string % a return a . keys
def execute_bytecode ( self , origin : Address , gas_price : int , gas : int , to : Address , sender : Address , value : int , data : bytes , code : bytes , code_address : Address = None , ) -> BaseComputation : """Execute raw bytecode in the context of the current state of the virtual machine ."""
if origin is None : origin = sender # Construct a message message = Message ( gas = gas , to = to , sender = sender , value = value , data = data , code = code , code_address = code_address , ) # Construction a tx context transaction_context = self . state . get_transaction_context_class ( ) ( gas_price = gas_price...
def html_page_context ( app , pagename , templatename , context , doctree ) : '''Collect page names for the sitemap as HTML pages are built .'''
site = context [ 'SITEMAP_BASE_URL' ] version = context [ 'version' ] app . sitemap_links . add ( site + version + '/' + pagename + ".html" )
def run_calculation ( self , atoms = None , properties = [ 'energy' ] , system_changes = all_changes ) : '''Internal calculation executor . We cannot use FileIOCalculator directly since we need to support remote execution . This calculator is different from others . It prepares the directory , launches the re...
self . calc . calculate ( self , atoms , properties , system_changes ) self . write_input ( self . atoms , properties , system_changes ) if self . command is None : raise RuntimeError ( 'Please configure Remote calculator!' ) olddir = os . getcwd ( ) errorcode = 0 try : os . chdir ( self . directory ) outpu...
def dispatchlist ( self , * , author = None , category = None , subcategory = None , sort = 'new' ) : """Find dispatches by certain criteria . Parameters author : str Name of the nation authoring the dispatch . category : str Dispatch ' s primary category . subcategory : str Dispatch ' s secondary cat...
params = { 'sort' : sort } if author : params [ 'dispatchauthor' ] = author # Here we do need to ensure that our categories are valid , cause # NS just ignores the categories it doesn ' t recognise and returns # whatever it feels like . if category and subcategory : if ( category not in dispatch_categories or s...
def set_pointer0d ( subseqs ) : """Set _ pointer function for 0 - dimensional link sequences ."""
print ( ' . set_pointer0d' ) lines = Lines ( ) lines . add ( 1 , 'cpdef inline set_pointer0d' '(self, str name, pointerutils.PDouble value):' ) for seq in subseqs : lines . add ( 2 , 'if name == "%s":' % seq . name ) lines . add ( 3 , 'self.%s = value.p_value' % seq . name ) return lines
def _get_prop_infos ( self , prop ) : """Return the infos configured for this specific prop , merging the different configuration level"""
info_dict = self . get_info_field ( prop ) main_infos = info_dict . get ( 'export' , { } ) . copy ( ) infos = main_infos . get ( self . config_key , { } ) main_infos [ 'label' ] = self . _get_title ( prop , main_infos , info_dict ) main_infos [ 'name' ] = prop . key main_infos [ 'key' ] = prop . key main_infos . update...
def errdp ( marker , number ) : """Substitute a double precision number for the first occurrence of a marker found in the current long error message . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / errdp _ c . html : param marker : A substring of the error message to be replac...
marker = stypes . stringToCharP ( marker ) number = ctypes . c_double ( number ) libspice . errdp_c ( marker , number )
def iter_archive ( self , resource ) : """Returns iterator over files within archive . * * Important Note * * : caller should read files as they are yielded . Reading out of order is slow . Args : resource : path to archive or ` tfds . download . Resource ` . Returns : Generator yielding tuple ( path _ ...
if isinstance ( resource , six . string_types ) : resource = resource_lib . Resource ( path = resource ) return extractor . iter_archive ( resource . path , resource . extract_method )
def list_upgrades ( refresh = True , ** kwargs ) : '''Check whether or not an upgrade is available for all packages The ` ` fromrepo ` ` , ` ` enablerepo ` ` , and ` ` disablerepo ` ` arguments are supported , as used in pkg states , and the ` ` disableexcludes ` ` option is also supported . . . versionadde...
options = _get_options ( ** kwargs ) if salt . utils . data . is_true ( refresh ) : refresh_db ( check_update = False , ** kwargs ) cmd = [ '--quiet' ] cmd . extend ( options ) cmd . extend ( [ 'list' , 'upgrades' if _yum ( ) == 'dnf' else 'updates' ] ) out = _call_yum ( cmd , ignore_retcode = True ) if out [ 'retc...