signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def current_line_num ( self ) : '''Get current line number as an integer ( 1 - based ) Translated from PyFrame _ GetLineNumber and PyCode _ Addr2Line See Objects / lnotab _ notes . txt'''
if self . is_optimized_out ( ) : return None f_trace = self . field ( 'f_trace' ) if long ( f_trace ) != 0 : # we have a non - NULL f _ trace : return self . f_lineno else : # try : return self . co . addr2line ( self . f_lasti )
def for_category ( self , category , live_only = False ) : """Returns queryset of EntryTag instances for specified category . : param category : the Category instance . : param live _ only : flag to include only " live " entries . : rtype : django . db . models . query . QuerySet ."""
filters = { 'tag' : category . tag } if live_only : filters . update ( { 'entry__live' : True } ) return self . filter ( ** filters )
def fix_e712 ( self , result ) : """Fix ( trivial case of ) comparison with boolean ."""
( line_index , offset , target ) = get_index_offset_contents ( result , self . source ) # Handle very easy " not " special cases . if re . match ( r'^\s*if [\w."\'\[\]]+ == False:$' , target ) : self . source [ line_index ] = re . sub ( r'if ([\w."\'\[\]]+) == False:' , r'if not \1:' , target , count = 1 ) elif re ...
def makeRequests ( callable_ , args_list , callback = None , exc_callback = _handle_thread_exception ) : """Create several work requests for same callable with different arguments . Convenience function for creating several work requests for the same callable where each invocation of the callable receives diffe...
requests = [ ] for item in args_list : if isinstance ( item , tuple ) : requests . append ( WorkRequest ( callable_ , item [ 0 ] , item [ 1 ] , callback = callback , exc_callback = exc_callback ) ) else : requests . append ( WorkRequest ( callable_ , [ item ] , None , callback = callback , exc_c...
def split_path ( path ) : '''Splits the argument into its constituent directories and returns them as a list .'''
def recurse_path ( path , retlist ) : if len ( retlist ) > 100 : fullpath = os . path . join ( * ( [ path , ] + retlist ) ) print ( "Directory '{}' contains too many levels" . format ( fullpath ) ) exit ( 1 ) head , tail = os . path . split ( path ) if len ( tail ) > 0 : retl...
def zipf_random_sample ( distr_map , sample_len ) : """Helper function : Generate a random Zipf sample of given length . Args : distr _ map : list of float , Zipf ' s distribution over nbr _ symbols . sample _ len : integer , length of sequence to generate . Returns : sample : list of integer , Zipf ' s r...
u = np . random . random ( sample_len ) # Random produces values in range [ 0.0,1.0 ) ; even if it is almost # improbable ( but possible ) that it can generate a clear 0.000 . . 0. return list ( np . searchsorted ( distr_map , u ) )
def features ( self ) : """This method returns the properties features . : return :"""
features = [ ] try : list_items = self . _ad_page_content . select ( "#features li" ) except Exception as e : if self . _debug : logging . error ( "Error getting features. Error message: " + e . args [ 0 ] ) return for li in list_items : features . append ( li . text ) return features
def move ( self , source , dest ) : """the semantic should be like unix ' mv ' command . Unfortunatelly , shutil . move does work differently ! ! ! Consider ( all paths point to directories ) mv / a / b / a / c expected outcome : case 1 . : ' c ' does not exist : b moved over to / a such that / a / c is...
if dest . scheme == 'file' : if source . isdir ( ) and dest . isdir ( ) : dest /= source . basename ( ) return shutil . move ( source . path , dest . path ) else : return super ( LocalFileSystem , self ) . move ( source , dest )
def make_copy ( cls , generator ) : """Creates a copy of the generator . : param generator : the generator to copy : type generator : DataGenerator : return : the copy of the generator : rtype : DataGenerator"""
return from_commandline ( to_commandline ( generator ) , classname = classes . get_classname ( DataGenerator ( ) ) )
def block ( broker ) : """Path : / sys / block directories starting with . or ram or dm - or loop"""
remove = ( "." , "ram" , "dm-" , "loop" ) tmp = "/dev/%s" return [ ( tmp % f ) for f in os . listdir ( "/sys/block" ) if not f . startswith ( remove ) ]
def getTypes ( cls ) : """Get sequence of acceptable model types . Iterates through class attributes and separates the user - defined enumerations from the default attributes implicit to Python classes . i . e . this function returns the names of the attributes explicitly defined above ."""
for attrName in dir ( cls ) : attrValue = getattr ( cls , attrName ) if ( isinstance ( attrValue , type ) ) : yield attrName
def load_entry_point_group_mappings ( self , entry_point_group_mappings ) : """Load actions from an entry point group ."""
for ep in iter_entry_points ( group = entry_point_group_mappings ) : self . register_mappings ( ep . name , ep . module_name )
def get_short_url ( self , obj ) : """Get short URL of blog post like ' / blog / < slug > / ' using ` ` get _ absolute _ url ` ` if available . Removes dependency on reverse URLs of Mezzanine views when deploying Mezzanine only as an API backend ."""
try : url = obj . get_absolute_url ( ) except NoReverseMatch : url = '/blog/' + obj . slug return url
def get_or_create_group ( groupname , gid_preset , system = False , id_dependent = True ) : """Returns the id for the given group , and creates it first in case it does not exist . : param groupname : Group name . : type groupname : unicode : param gid _ preset : Group id to set if a new group is created . ...
gid = get_group_id ( groupname ) if gid is None : create_group ( groupname , gid_preset , system ) return gid_preset elif id_dependent and gid != gid_preset : error ( "Present group id '{0}' does not match the required id of the environment '{1}'." . format ( gid , gid_preset ) ) return gid
def setup_ui ( self , ) : """Create all necessary ui elements for the tool : returns : None : rtype : None : raises : None"""
log . debug ( "Setting up the ui" ) self . setup_prjs_page ( ) self . setup_prj_page ( ) self . setup_seq_page ( ) self . setup_shot_page ( ) self . setup_atype_page ( ) self . setup_asset_page ( ) self . setup_dep_page ( ) self . setup_task_page ( ) self . setup_users_page ( ) self . setup_user_page ( )
def netconf_capability_change_changed_by_server_or_user_server_server ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) netconf_capability_change = ET . SubElement ( config , "netconf-capability-change" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-notifications" ) changed_by = ET . SubElement ( netconf_capability_change , "changed-by" ) server_or_user = ET . SubElement ( changed_by , "server-or-...
def respect_language ( language ) : """Context manager that changes the current translation language for all code inside the following block . Can e . g . be used inside tasks like this : : from celery import task from djcelery . common import respect _ language @ task def my _ task ( language = None ) ...
if language : prev = translation . get_language ( ) translation . activate ( language ) try : yield finally : translation . activate ( prev ) else : yield
def executor ( arg : Union [ Executor , str , Callable ] = None ) : """Decorate a function so that it runs in an : class : ` ~ concurrent . futures . Executor ` . If a resource name is given , the first argument must be a : class : ` ~ . Context ` . Usage : : @ executor def should _ run _ in _ executor ( ) ...
def outer_wrapper ( func : Callable ) : @ wraps ( func ) def inner_wrapper ( * args , ** kwargs ) : try : ctx = next ( arg for arg in args [ : 2 ] if isinstance ( arg , Context ) ) except StopIteration : raise RuntimeError ( 'the first positional argument to {}() has to b...
def check_color ( c ) : """Check and parse color specs as either a single [ r , g , b ] or a list of [ [ r , g , b ] , [ r , g , b ] . . . ]"""
c = asarray ( c ) if c . ndim == 1 : c = c . flatten ( ) c = c [ newaxis , : ] if c . shape [ 1 ] != 3 : raise Exception ( "Color must have three values per point" ) elif c . ndim == 2 : if c . shape [ 1 ] != 3 : raise Exception ( "Color array must have three values per point" ) return c
def url_decode ( s , charset = 'utf-8' , decode_keys = False , include_empty = True , errors = 'replace' , separator = '&' , cls = None ) : """Parse a querystring and return it as : class : ` MultiDict ` . There is a difference in key decoding on different Python versions . On Python 3 keys will always be fully...
if cls is None : cls = MultiDict if isinstance ( s , text_type ) and not isinstance ( separator , text_type ) : separator = separator . decode ( charset or 'ascii' ) elif isinstance ( s , bytes ) and not isinstance ( separator , bytes ) : separator = separator . encode ( charset or 'ascii' ) return cls ( _u...
def debug ( evals , feed_dict = None , breakpoints = None , break_immediately = False , session = None ) : """spawns a new debug session"""
global _dbsession _dbsession = debug_session . DebugSession ( session ) return _dbsession . run ( evals , feed_dict , breakpoints , break_immediately )
def parent_dir ( path ) : '''Return the parent of a directory .'''
return os . path . abspath ( os . path . join ( path , os . pardir , os . pardir , '_build' ) )
def runAndWait ( self ) : '''Called by the engine to start an event loop , process all commands in the queue at the start of the loop , and then exit the loop .'''
self . _push ( self . _engine . endLoop , tuple ( ) ) self . _driver . startLoop ( )
def dimensions ( filenames ) : """given a filename or list of filenames , return a tuple or sequence of tuples ( x , y , filename )"""
single = type ( filenames ) is str if single : filenames = [ filenames ] dims = get_dimensions ( filenames ) if single : dims = dims [ 0 ] return dims
def copy_logstore ( self , from_project , from_logstore , to_logstore , to_project = None , to_client = None ) : """copy logstore , index , logtail config to target logstore , machine group are not included yet . the target logstore will be crated if not existing : type from _ project : string : param from _ ...
return copy_logstore ( self , from_project , from_logstore , to_logstore , to_project = to_project , to_client = to_client )
def adjusted_current_time ( self ) : """Returns calculated current seek time of media in seconds"""
if self . player_state == MEDIA_PLAYER_STATE_PLAYING : # Add time since last update return ( self . current_time + ( datetime . utcnow ( ) - self . last_updated ) . total_seconds ( ) ) # Not playing , return last reported seek time return self . current_time
def decorate ( svg , node , metadata ) : """Add metedata next to a node"""
if not metadata : return node xlink = metadata . get ( 'xlink' ) if xlink : if not isinstance ( xlink , dict ) : xlink = { 'href' : xlink , 'target' : '_blank' } node = svg . node ( node , 'a' , ** xlink ) svg . node ( node , 'desc' , class_ = 'xlink' ) . text = to_unicode ( xlink . get ( 'href'...
def delete_priority_rule ( db , rule_id : int ) -> None : """Delete a file priority rule ."""
with db : cur = db . cursor ( ) cur . execute ( 'DELETE FROM file_priority WHERE id=?' , ( rule_id , ) )
def mat_to_numpy_arr ( self ) : '''convert list to numpy array - numpy arrays can not be saved as json'''
import numpy as np self . dat [ 'mat' ] = np . asarray ( self . dat [ 'mat' ] )
def to_pytime ( self ) : """Converts sql time object into Python ' s time object this will truncate nanoseconds to microseconds @ return : naive time"""
nanoseconds = self . _nsec hours = nanoseconds // 1000000000 // 60 // 60 nanoseconds -= hours * 60 * 60 * 1000000000 minutes = nanoseconds // 1000000000 // 60 nanoseconds -= minutes * 60 * 1000000000 seconds = nanoseconds // 1000000000 nanoseconds -= seconds * 1000000000 return datetime . time ( hours , minutes , secon...
def hilbert_chip_order ( machine ) : """A generator which iterates over a set of chips in a machine in a hilbert path . For use as a chip ordering for the sequential placer ."""
max_dimen = max ( machine . width , machine . height ) hilbert_levels = int ( ceil ( log ( max_dimen , 2.0 ) ) ) if max_dimen >= 1 else 0 return hilbert ( hilbert_levels )
def learn ( self , initial_state_key , limit = 1000 , game_n = 1 ) : '''Multi - Agent Learning . Override . Args : initial _ state _ key : Initial state . limit : Limit of the number of learning . game _ n : The number of games .'''
end_flag_list = [ False ] * len ( self . q_learning_list ) for game in range ( game_n ) : state_key = copy . copy ( initial_state_key ) self . t = 1 while self . t <= limit : for i in range ( len ( self . q_learning_list ) ) : if game + 1 == game_n : self . state_key_list...
def empirical_SVD ( stream_list , linear = True ) : """Depreciated . Use empirical _ svd ."""
warnings . warn ( 'Depreciated, use empirical_svd instead.' ) return empirical_svd ( stream_list = stream_list , linear = linear )
def add_role ( self , role , term , start_date = None , end_date = None , ** kwargs ) : """Examples : leg . add _ role ( ' member ' , term = ' 2009 ' , chamber = ' upper ' , party = ' Republican ' , district = ' 10th ' )"""
self [ 'roles' ] . append ( dict ( role = role , term = term , start_date = start_date , end_date = end_date , ** kwargs ) )
def commit_deposit ( self , deposit_id , ** params ) : """https : / / developers . coinbase . com / api / v2 # commit - a - deposit"""
return self . api_client . commit_deposit ( self . id , deposit_id , ** params )
def out_endpoint ( self ) : """Open a reference to the USB device ' s only OUT endpoint . This method assumes that the USB device configuration has already been set ."""
if getattr ( self , '_out_endpoint' , None ) is None : config = self . device . get_active_configuration ( ) interface_number = config [ ( 0 , 0 ) ] . bInterfaceNumber interface = usb . util . find_descriptor ( config , bInterfaceNumber = interface_number ) self . _out_endpoint = usb . util . find_descr...
async def put ( self , public_key ) : """Reject offer and unfreeze balance Accepts : - cid - buyer public key - buyer address"""
if settings . SIGNATURE_VERIFICATION : super ( ) . verify ( ) # Check if message contains required data try : body = json . loads ( self . request . body ) except : self . set_status ( 400 ) self . write ( { "error" : 400 , "reason" : "Unexpected data format. JSON required" } ) raise tornado . web ....
def ParseFileObject ( self , parser_mediator , file_object ) : """Parses a Firefox cache file - like object . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . file _ object ( dfvfs . FileIO ) : a file - like object . Rai...
filename = parser_mediator . GetFilename ( ) if not self . _CACHE_FILENAME_RE . match ( filename ) : raise errors . UnableToParseFile ( 'Not a Firefox cache2 file.' ) # The file needs to be at least 36 bytes in size for it to contain # a cache2 file metadata header and a 4 - byte offset that points to its # locatio...
def _set_all_partition ( self , v , load = False ) : """Setter method for all _ partition , mapped from YANG variable / cpu _ state / all _ partition ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ all _ partition is considered as a private method . Back...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = all_partition . all_partition , is_container = 'container' , presence = False , yang_name = "all-partition" , rest_name = "all-partition" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods ,...
def resource_list ( cls ) : """Get the possible list of resources ( hostname , id ) ."""
items = cls . list ( { 'items_per_page' : 500 } ) ret = [ vm [ 'hostname' ] for vm in items ] ret . extend ( [ str ( vm [ 'id' ] ) for vm in items ] ) return ret
def apply ( self , event = None ) : """Before self . onOk closes the window , it calls this function to sync the config changes from the GUI back to self . config ."""
for section in self . config . sections ( ) : # Run through the sections to check all the option values : for option , o in self . config . config [ section ] . items ( ) : # Check the actual values against the validators and complain if necessary : if not o [ 'include' ] : continue ...
def convert_celeba_aligned_cropped ( directory , output_directory , output_filename = OUTPUT_FILENAME ) : """Converts the aligned and cropped CelebA dataset to HDF5. Converts the CelebA dataset to an HDF5 dataset compatible with : class : ` fuel . datasets . CelebA ` . The converted dataset is saved as ' cele...
output_path = os . path . join ( output_directory , output_filename ) h5file = _initialize_conversion ( directory , output_path , ( 218 , 178 ) ) features_dataset = h5file [ 'features' ] image_file_path = os . path . join ( directory , IMAGE_FILE ) with zipfile . ZipFile ( image_file_path , 'r' ) as image_file : wi...
def _write_source_code ( tlobject , kind , builder , type_constructors ) : """Writes the source code corresponding to the given TLObject by making use of the ` ` builder ` ` ` SourceBuilder ` . Additional information such as file path depth and the ` ` Type : [ Constructors ] ` ` must be given for proper im...
_write_class_init ( tlobject , kind , type_constructors , builder ) _write_resolve ( tlobject , builder ) _write_to_dict ( tlobject , builder ) _write_to_bytes ( tlobject , builder ) _write_from_reader ( tlobject , builder ) _write_read_result ( tlobject , builder )
def chexdump ( x , dump = False ) : """Build a per byte hexadecimal representation Example : > > > chexdump ( IP ( ) ) 0x45 , 0x00 , 0x00 , 0x14 , 0x00 , 0x01 , 0x00 , 0x00 , 0x40 , 0x00 , 0x7c , 0xe7 , 0x7f , 0x00 , 0x00 , 0x01 , 0x7f , 0x00 , 0x00 , 0x01 # noqa : E501 : param x : a Packet : param dump :...
x = bytes_encode ( x ) s = ", " . join ( "%#04x" % orb ( x ) for x in x ) if dump : return s else : print ( s )
def get_attribute ( self , selector , attribute , by = By . CSS_SELECTOR , timeout = settings . SMALL_TIMEOUT ) : """This method uses JavaScript to get the value of an attribute ."""
if self . timeout_multiplier and timeout == settings . SMALL_TIMEOUT : timeout = self . __get_new_timeout ( timeout ) if page_utils . is_xpath_selector ( selector ) : by = By . XPATH if page_utils . is_link_text_selector ( selector ) : selector = page_utils . get_link_text_from_selector ( selector ) by ...
def get_auth_header ( self ) : """Getting the authorization header according to the authentication procedure : return [ dict ] : Authorization header"""
if self . api . is_authenticated : return { "Authorization" : "Bearer %s" % self . api . access_token } return { "Authorization" : "Client-ID %s" % self . api . client_id }
def inj_spin_pdf ( key , high_spin , spinz ) : '''Estimate the probability density of the injections for the spin distribution . Parameters key : string Injections strategy high _ spin : float Maximum spin used in the strategy spinz : array Spin of the injections ( for one component )'''
# If the data comes from disable _ spin simulation if spinz [ 0 ] == 0 : return np . ones_like ( spinz ) spinz = np . array ( spinz ) bound = np . sign ( np . absolute ( high_spin ) - np . absolute ( spinz ) ) bound += np . sign ( 1 - np . absolute ( spinz ) ) if key == 'precessing' : # Returns the PDF of spins whe...
def insert_record_by_fieldspecs_with_values ( self , table : str , fieldspeclist : FIELDSPECLIST_TYPE ) -> int : """Inserts a record into the database using a list of fieldspecs having their value stored under the ' value ' key ."""
fields = [ ] values = [ ] for fs in fieldspeclist : fields . append ( fs [ "name" ] ) values . append ( fs [ "value" ] ) return self . insert_record ( table , fields , values )
def create_operations ( ctx = None , ** kwargs ) : """Create an alembic operations object ."""
if ctx is None : ctx = create_migration_ctx ( ** kwargs ) operations = Operations ( ctx ) operations . has_table = has_table return operations
def get_property ( node_uri , property_name , ossos_base = True ) : """Retrieves the value associated with a property on a node in VOSpace . @ param node _ uri : @ param property _ name : @ param ossos _ base : @ return :"""
# Must use force or we could have a cached copy of the node from before # properties of interest were set / updated . node = client . get_node ( node_uri , force = True ) property_uri = tag_uri ( property_name ) if ossos_base else property_name if property_uri not in node . props : return None return node . props [...
def field_pklist_from_json ( self , data ) : """Load a PkOnlyQueryset from a JSON dict . This uses the same format as cached _ queryset _ from _ json"""
model = get_model ( data [ 'app' ] , data [ 'model' ] ) return PkOnlyQueryset ( self , model , data [ 'pks' ] )
def get_subdomain_ops_at_txid ( txid , proxy = None , hostport = None ) : """Get the list of subdomain operations added by a txid Returns the list of operations ( [ { . . . } ] ) on success Returns { ' error ' : . . . } on failure"""
assert proxy or hostport , 'Need proxy or hostport' if proxy is None : proxy = connect_hostport ( hostport ) subdomain_ops_schema = { 'type' : 'object' , 'properties' : { 'subdomain_ops' : { 'type' : 'array' , 'items' : { 'type' : 'object' , 'properties' : OP_HISTORY_SCHEMA [ 'properties' ] , 'required' : SUBDOMAIN...
def cmd_led ( self , args ) : '''send LED pattern as override'''
if len ( args ) < 3 : print ( "Usage: led RED GREEN BLUE <RATE>" ) return pattern = [ 0 ] * 24 pattern [ 0 ] = int ( args [ 0 ] ) pattern [ 1 ] = int ( args [ 1 ] ) pattern [ 2 ] = int ( args [ 2 ] ) if len ( args ) == 4 : plen = 4 pattern [ 3 ] = int ( args [ 3 ] ) else : plen = 3 self . master . m...
def killall ( self , exc ) : """Connection / Channel was closed . All subsequent and ongoing requests should raise an error"""
self . connection_exc = exc # Set an exception for all others for method , futs in self . _futures . items ( ) : for fut in futs : if fut . done ( ) : continue fut . set_exception ( exc ) self . _futures . clear ( )
def todegdec ( origin ) : """Convert from [ + / - ] DDD ° MMM ' SSS . SSSS " or [ + / - ] DDD ° MMM . MMMM ' to [ + / - ] DDD . DDDDD"""
# if the input is already a float ( or can be converted to float ) try : return float ( origin ) except ValueError : pass # DMS format m = dms_re . search ( origin ) if m : degrees = int ( m . group ( 'degrees' ) ) minutes = float ( m . group ( 'minutes' ) ) seconds = float ( m . group ( 'seconds' )...
def _return_rows ( self , table , cols , values , return_type ) : """Return fetched rows in the desired type ."""
if return_type is dict : # Pack each row into a dictionary cols = self . get_columns ( table ) if cols is '*' else cols if len ( values ) > 0 and isinstance ( values [ 0 ] , ( set , list , tuple ) ) : return [ dict ( zip ( cols , row ) ) for row in values ] else : return dict ( zip ( cols , ...
def nodes_geometry ( self ) : """The nodes in the scene graph with geometry attached . Returns nodes _ geometry : ( m , ) array , of node names"""
nodes = np . array ( [ n for n in self . transforms . nodes ( ) if 'geometry' in self . transforms . node [ n ] ] ) return nodes
def fill_delegate_proxy_activation_requirements ( requirements_data , cred_file , lifetime_hours = 12 ) : """Given the activation requirements for an endpoint and a filename for X . 509 credentials , extracts the public key from the activation requirements , uses the key and the credentials to make a proxy cred...
# get the public key from the activation requirements for data in requirements_data [ "DATA" ] : if data [ "type" ] == "delegate_proxy" and data [ "name" ] == "public_key" : public_key = data [ "value" ] break else : raise ValueError ( ( "No public_key found in activation requirements, this endp...
def _run ( self , command : List [ str ] , notebook : Optional [ str ] = None ) -> int : """Run command from terminal and notebook and view output from subprocess ."""
if notebook is None : return Popen ( command , cwd = self . _build_dir ) . wait ( ) cmd = Popen ( command , cwd = self . _build_dir , stdout = PIPE , stderr = STDOUT ) while True : line = cmd . stdout . readline ( ) if line == b'' and cmd . poll ( ) is not None : return cmd . poll ( ) print ( li...
def _write_pair_information ( gsd_file , structure ) : """Write the special pairs in the system . Parameters gsd _ file : The file object of the GSD file being written structure : parmed . Structure Parmed structure object holding system information"""
pair_types = [ ] pair_typeid = [ ] pairs = [ ] for ai in structure . atoms : for aj in ai . dihedral_partners : # make sure we don ' t double add if ai . idx > aj . idx : ps = '-' . join ( sorted ( [ ai . type , aj . type ] , key = natural_sort ) ) if ps not in pair_types : ...
def foreach_model ( self , fn ) : """Apply the given function to each model replica in each worker . Returns : List of results from applying the function ."""
results = ray . get ( [ w . foreach_model . remote ( fn ) for w in self . workers ] ) out = [ ] for r in results : out . extend ( r ) return out
def short_codes ( self ) : """Access the short _ codes : returns : twilio . rest . api . v2010 . account . short _ code . ShortCodeList : rtype : twilio . rest . api . v2010 . account . short _ code . ShortCodeList"""
if self . _short_codes is None : self . _short_codes = ShortCodeList ( self . _version , account_sid = self . _solution [ 'sid' ] , ) return self . _short_codes
def from_wif_hex ( cls : Type [ SigningKeyType ] , wif_hex : str ) -> SigningKeyType : """Return SigningKey instance from Duniter WIF in hexadecimal format : param wif _ hex : WIF string in hexadecimal format"""
wif_bytes = Base58Encoder . decode ( wif_hex ) if len ( wif_bytes ) != 35 : raise Exception ( "Error: the size of WIF is invalid" ) # extract data checksum_from_wif = wif_bytes [ - 2 : ] fi = wif_bytes [ 0 : 1 ] seed = wif_bytes [ 1 : - 2 ] seed_fi = wif_bytes [ 0 : - 2 ] # check WIF format flag if fi != b"\x01" : ...
def set_decdel_rts ( self ) : """Figure out the decimal seperator and rows to skip and set corresponding attributes ."""
lnr = max ( self . rows2skip ( ',' ) , self . rows2skip ( '.' ) ) + 1 # If EQUAL _ CNT _ REQ was not met , raise error . Implement ! if self . cnt > EQUAL_CNT_REQ : raise PatternError ( 'Did not find ' + str ( EQUAL_CNT_REQ ) + ' data rows with equal data pattern in file: ' + self . fn ) elif self . cnt < EQUAL_CNT...
def next ( self ) : """for iteration over the header entries"""
if self . _current < len ( self . _record_list ) : rec = self . _record_list [ self . _current ] key = rec [ 'name' ] self . _current += 1 return key else : raise StopIteration
def exhaustive_curie_check ( self , ontology : pd . DataFrame , curie_predicate : str , curie_prefix : str , diff : bool = True , ) -> Tuple [ list ] : '''All entities with conflicting curies gets a full diff to see if they belong Args : ontology : pandas DataFrame created from an ontology where the colnames ar...
inside , outside = [ ] , [ ] curie_prefix = curie_prefix . replace ( ':' , '' ) # just in case I forget a colon isnt in a prefix header = [ 'Index' ] + list ( ontology . columns ) for row in ontology . itertuples ( ) : row = { header [ i ] : val for i , val in enumerate ( row ) } entity_curie = row [ curie_pred...
def to_datetime ( dt , tzinfo = None , format = None ) : """Convert a date or time to datetime with tzinfo"""
if not dt : return dt tz = pick_timezone ( tzinfo , __timezone__ ) if isinstance ( dt , ( str , unicode ) ) : if not format : formats = DEFAULT_DATETIME_INPUT_FORMATS else : formats = list ( format ) d = None for fmt in formats : try : d = datetime . strptime ( dt...
def create_hosting_device_resources ( self , context , complementary_id , tenant_id , mgmt_context , max_hosted ) : """Create resources for a hosting device in a plugin specific way ."""
mgmt_port = None if mgmt_context and mgmt_context . get ( 'mgmt_nw_id' ) and tenant_id : # Create port for mgmt interface p_spec = { 'port' : { 'tenant_id' : tenant_id , 'admin_state_up' : True , 'name' : 'mgmt' , 'network_id' : mgmt_context [ 'mgmt_nw_id' ] , 'mac_address' : bc . constants . ATTR_NOT_SPECIFIED , '...
def _set_optimal_area ( self , data ) : """Reduce the zone to reduce the size of fetched data on refresh"""
lats = [ station [ "latitude" ] for station in data . values ( ) ] longs = [ station [ "longitude" ] for station in data . values ( ) ] self . gps . update ( { "gpsTopLatitude" : max ( lats ) , "gpsTopLongitude" : max ( longs ) , "gpsBotLatitude" : min ( lats ) , "gpsBotLongitude" : min ( longs ) , } )
def spawn ( self , spawn_mapping = None ) : """Return an exact copy of this generator which behaves the same way ( i . e . , produces the same elements in the same order ) but is otherwise independent , i . e . there is no link between the two generators ( as opposed to a cloned generator , which is automatic...
spawn_mapping = spawn_mapping or SpawnMapping ( ) if self . parent is not None : if self . parent in spawn_mapping : # Return new clone of the mapped parent return spawn_mapping [ self . parent ] . clone ( ) else : raise TohuCloneError ( "Cannot spawn a cloned generator without being able to map...
def similarity ( self , track ) : """Compares two tracks based on their topology This method compares the given track against this instance . It only verifies if given track is close to this one , not the other way arround Args : track ( : obj : ` Track ` ) Returns : Two - tuple with global similarity...
idx = index . Index ( ) i = 0 for i , segment in enumerate ( self . segments ) : idx . insert ( i , segment . bounds ( ) , obj = segment ) final_siml = [ ] final_diff = [ ] for i , segment in enumerate ( track . segments ) : query = idx . intersection ( segment . bounds ( ) , objects = True ) res_siml = [ ]...
def close ( self , * args , ** kwargs ) : """write close tag of MRV file and close opened file : param force : force closing of externally opened file or buffer"""
if not self . __finalized : self . _file . write ( '</cml>' ) self . __finalized = True super ( ) . close ( * args , ** kwargs )
def convert ( self , vroot , entry_variables ) : """All functions are replaced with the same ` new ` function . Args : vroot ( : obj : ` Variable ` ) : NNabla Variable entry _ variables ( : obj : ` Variable ` ) : Entry variable from which the conversion starts ."""
self . graph_info = GraphInfo ( vroot ) self . entry_variables = entry_variables cnt = 0 with nn . parameter_scope ( self . name ) : # Function loop in the forward order for t , func in enumerate ( self . graph_info . funcs ) : if func . name == "BatchNormalization" : bn_func = func ...
def auction_history ( self , symbol = 'btcusd' , since = 0 , limit_auction_results = 50 , include_indicative = 1 ) : """Send a request for auction history info , return the response . Arguments : symbol - - currency symbol ( default ' btcusd ' ) since - - only return auction events after this timestamp ( defa...
url = self . base_url + '/v1/auction/' + symbol + '/history' params = { 'since' : since , 'limit_auction_results' : limit_auction_results , 'include_indicative' : include_indicative } return requests . get ( url , params )
def fqdns ( ) : '''Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them ( excluding ' lo ' interface ) .'''
# Provides : # fqdns grains = { } fqdns = set ( ) addresses = salt . utils . network . ip_addrs ( include_loopback = False , interface_data = _get_interfaces ( ) ) addresses . extend ( salt . utils . network . ip_addrs6 ( include_loopback = False , interface_data = _get_interfaces ( ) ) ) err_message = 'Exception durin...
def get_vcs_directory ( context , directory ) : """Get the pathname of the directory containing the version control metadata files ."""
nested = os . path . join ( directory , '.git' ) return nested if context . is_directory ( nested ) else directory
def add_cell_footer ( self ) : """Add footer cell"""
# check if there ' s already a cell footer . . . if true , do not add a second cell footer . # this situation happens when exporting to ipynb and then importing from ipynb . logging . info ( 'Adding footer cell' ) for cell in self . nb [ 'cells' ] : if cell . cell_type == 'markdown' : if 'pynb_footer_tag' i...
def _process_collection ( self , collection_id , label , page ) : """This function will process the data supplied internally about the repository from Coriell . Triples : Repository a ERO : collection rdf : label Literal ( label ) foaf : page Literal ( page ) : param collection _ id : : param label : ...
# # # # # # BUILD THE CELL LINE REPOSITORY # # # # # for graph in [ self . graph , self . testgraph ] : # TODO : How to devise a label for each repository ? model = Model ( graph ) reference = Reference ( graph ) repo_id = 'CoriellCollection:' + collection_id repo_label = label repo_page = page ...
def on_compiled ( self , name = None , key_schema = None , value_schema = None , as_mapping_key = None ) : """When CompiledSchema compiles this marker , it sets informational values onto it . Note that arguments may be provided in two incomplete sets , e . g . ( name , key _ schema , None ) and then ( None , No...
if self . name is None : self . name = name if self . key_schema is None : self . key_schema = key_schema if self . value_schema is None : self . value_schema = value_schema if as_mapping_key : self . as_mapping_key = True return self
def get_stories ( self , userids : Optional [ List [ int ] ] = None ) -> Iterator [ Story ] : """Get available stories from followees or all stories of users whose ID are given . Does not mark stories as seen . To use this , one needs to be logged in : param userids : List of user IDs to be processed in terms...
if not userids : data = self . context . graphql_query ( "d15efd8c0c5b23f0ef71f18bf363c704" , { "only_stories" : True } ) [ "data" ] [ "user" ] if data is None : raise BadResponseException ( 'Bad stories reel JSON.' ) userids = list ( edge [ "node" ] [ "id" ] for edge in data [ "feed_reels_tray" ] [...
def extract_cosponsors ( bill ) : """Return a list of list relating cosponsors to legislation ."""
logger . debug ( "Extracting Cosponsors" ) cosponsor_map = [ ] cosponsors = bill . get ( 'cosponsors' , [ ] ) bill_id = bill . get ( 'bill_id' , None ) for co in cosponsors : co_list = [ ] co_list . append ( co . get ( 'thomas_id' ) ) co_list . append ( bill_id ) co_list . append ( co . get ( 'district'...
def set_user_tag ( self , usertag , pass_to_command_line = True ) : """Set the user tag that is passed to the analysis code . @ param user _ tag : the user tag to identify the job @ bool pass _ to _ command _ line : add user - tag as a variable option ."""
self . __user_tag = usertag if pass_to_command_line : self . add_var_opt ( 'user-tag' , usertag )
def _ensure_create_ha_compliant ( self , router , router_type ) : """To be called in create _ router ( ) BEFORE router is created in DB ."""
details = router . pop ( ha . DETAILS , { } ) if details == ATTR_NOT_SPECIFIED : details = { } res = { ha . ENABLED : router . pop ( ha . ENABLED , ATTR_NOT_SPECIFIED ) , ha . DETAILS : details } if not is_attr_set ( res [ ha . ENABLED ] ) : res [ ha . ENABLED ] = router_type [ 'ha_enabled_by_default' ] if res ...
def run ( version , quiet , no_fetch , push , ** kwargs ) : # pragma : no cover """A nicer ` git pull ` ."""
if version : if NO_DISTRIBUTE : print ( colored ( 'Please install \'git-up\' via pip in order to ' 'get version information.' , 'yellow' ) ) else : GitUp ( sparse = True ) . version_info ( ) return if quiet : sys . stdout = StringIO ( ) try : gitup = GitUp ( ) if push is not None...
def _send_status_0x01_request ( self ) : """Sent status request to device ."""
status_command = StandardSend ( self . _address , COMMAND_LIGHT_STATUS_REQUEST_0X19_0X01 ) self . _send_method ( status_command , self . _status_message_0x01_received )
def _parse_txtinfo ( self , data ) : """Converts the python list returned by self . _ txtinfo _ to _ python ( ) to a NetworkX Graph object , which is then returned ."""
graph = self . _init_graph ( ) for link in data : graph . add_edge ( link [ 'source' ] , link [ 'target' ] , weight = link [ 'cost' ] ) return graph
def binary ( self , name ) : """Returns the path to the command of the given name for this distribution . For example : : : > > > d = Distribution ( ) > > > jar = d . binary ( ' jar ' ) > > > jar ' / usr / bin / jar ' If this distribution has no valid command of the given name raises Distribution . Erro...
if not isinstance ( name , str ) : raise ValueError ( 'name must be a binary name, given {} of type {}' . format ( name , type ( name ) ) ) self . validate ( ) return self . _validated_executable ( name )
def send_stats ( self , start , environ , response_interception , exception = None ) : """Send the actual timing stats . : param start : start time in seconds since the epoch as a floating point number : type start : float : param environ : wsgi environment : type environ : dict : param response _ interce...
# It could happen that start _ response wasn ' t called or it failed , so we might have an empty interception if response_interception : # Create the timer object and send the data to statsd . key_name = self . get_key_name ( environ , response_interception , exception = exception ) timer = self . statsd_client...
def get_qword_from_offset ( self , offset ) : """Return the quad - word value at the given file offset . ( little endian )"""
if offset + 8 > len ( self . __data__ ) : return None return self . get_qword_from_data ( self . __data__ [ offset : offset + 8 ] , 0 )
def _parse_migrations ( self ) : """Build a : class : ` Migration ` instance ."""
migration = self . parsed [ 'migration' ] options = self . _parse_options ( migration ) versions = self . _parse_versions ( migration , options ) return Migration ( versions , options )
def render_markdown ( post ) : """Renders the post as Markdown using the template specified in : attr : ` markdown _ template _ path ` ."""
from engineer . conf import settings # A hack to guarantee the YAML output is in a sensible order . # The order , assuming all metadata should be written , should be : # title # status # timestamp # link # via # via - link # slug # tags # updated # template # content - template # url d = [ ( 'status' , post . status . ...
def min_edit_distance_align ( # TODO Wrangle the typing errors in this function . # TODO This could work on generic sequences but for now it relies on # empty strings . # source : Sequence [ str ] , target : Sequence [ str ] , # ins _ cost : Callable [ . . . , int ] = lambda _ x : 1, # del _ cost : Callable [ . . . , i...
# Initialize an m + 1 by n + 1 array to hold the distances , and an equal sized # array to store the backpointers . Note that the strings start from index # 1 , with index 0 being used to denote the empty string . n = len ( target ) m = len ( source ) dist = [ [ 0 ] * ( n + 1 ) for _ in range ( m + 1 ) ] bptrs = [ [ [ ...
def write_data ( self , buf ) : """Send data to the device . : param buf : the data to send . : type buf : list ( int ) : return : success status . : rtype : bool"""
data = '' . join ( map ( chr , buf ) ) size = len ( data ) if hidapi . hid_write ( self . device , ctypes . c_char_p ( data ) , size ) != size : raise IOError ( 'pywws.device_ctypes_hidapi.USBDevice.write_data failed' ) return True
def make_id ( self ) : """Create a new URL id that is unique to the parent container"""
if self . url_id is None : # Set id only if empty self . url_id = select ( [ func . coalesce ( func . max ( self . __class__ . url_id + 1 ) , 1 ) ] , self . __class__ . parent == self . parent )
def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hide_arp_holder = ET . SubElement ( config , "hide-arp-holder" , xmlns = "urn:brocade.com:mgmt:brocade-arp" ) arp_entry = ET . SubElement ( hide_arp_holder , "arp-entry" ) arp_ip_address_key = ET . SubElement ( arp_entry , "arp-ip-address" ) arp_ip_address_key . text = kwargs . pop ( ...
def generate_airflow_spec ( name , pipeline_spec ) : """Gets the airflow python spec for the Pipeline object ."""
task_definitions = '' up_steam_statements = '' parameters = pipeline_spec . get ( 'parameters' ) for ( task_id , task_details ) in sorted ( pipeline_spec [ 'tasks' ] . items ( ) ) : task_def = PipelineGenerator . _get_operator_definition ( task_id , task_details , parameters ) task_definitions = task_definition...
def progressbar ( iterable = None , length = None , label = None , show_eta = True , show_percent = None , show_pos = False , item_show_func = None , fill_char = '#' , empty_char = '-' , bar_template = '%(label)s [%(bar)s] %(info)s' , info_sep = ' ' , width = 36 , file = None , color = None ) : """This function ...
from . _termui_impl import ProgressBar color = resolve_color_default ( color ) return ProgressBar ( iterable = iterable , length = length , show_eta = show_eta , show_percent = show_percent , show_pos = show_pos , item_show_func = item_show_func , fill_char = fill_char , empty_char = empty_char , bar_template = bar_tem...
def cleanup_unattached_disks ( kwargs = None , conn = None , call = None ) : '''. . versionadded : : 2015.8.0 Cleans up all disks associated with the account , which are not attached . * * * CAUTION * * * This is a destructive function with no undo button , and no " Are you sure ? " confirmation ! CLI Examp...
if call != 'function' : raise SaltCloudSystemExit ( 'The delete_disk function must be called with -f or --function.' ) if kwargs is None : kwargs = { } disks = list_disks ( kwargs = kwargs , conn = conn , call = 'function' ) for disk in disks : if disks [ disk ] [ 'attached_to' ] is None : del_kwarg...
def request ( self , method , url , name = None , ** kwargs ) : """Constructs and sends a : py : class : ` requests . Request ` . Returns : py : class : ` requests . Response ` object . : param method : method for the new : class : ` Request ` object . : param url : URL for the new : class : ` Request ` o...
self . init_meta_data ( ) # record test name self . meta_data [ "name" ] = name # record original request info self . meta_data [ "data" ] [ 0 ] [ "request" ] [ "method" ] = method self . meta_data [ "data" ] [ 0 ] [ "request" ] [ "url" ] = url kwargs . setdefault ( "timeout" , 120 ) self . meta_data [ "data" ] [ 0 ] [...
def get_by_scheme ( path , lookup , default ) : """Helper function used by get * ForPath ( ) ."""
parsed = urlparse ( path ) class_name = lookup . get ( parsed . scheme , default ) if class_name is None : raise NotImplementedError ( "No implementation for scheme " + parsed . scheme ) return class_name