signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def writeline ( self , line = b'' , sep = b'\n' , echo = None ) : """Write a byte sequences to the channel and terminate it with carriage return and line feed . Args : line ( bytes ) : The line to send . sep ( bytes ) : The separator to use after each line . echo ( bool ) : Whether to echo the written dat...
self . writelines ( [ line ] , sep , echo )
def parse ( url ) : """Parse a URL . > > > parse ( ' http : / / example . com / foo / ' ) URL ( scheme = ' http ' , . . . , domain = ' example ' , tld = ' com ' , . . . , path = ' / foo / ' , . . . )"""
parts = split ( url ) if parts . scheme : username , password , host , port = split_netloc ( parts . netloc ) subdomain , domain , tld = split_host ( host ) else : username = password = subdomain = domain = tld = port = '' return URL ( parts . scheme , username , password , subdomain , domain , tld , port ,...
def streamer ( frontend , backend ) : """Simple push / pull streamer : param int frontend : fontend zeromq port : param int backend : backend zeromq port"""
try : context = zmq . Context ( ) front_pull = context . socket ( zmq . PULL ) front_pull . set_hwm ( 0 ) front_pull . bind ( "tcp://*:%d" % frontend ) back_push = context . socket ( zmq . PUSH ) back_push . bind ( "tcp://*:%d" % backend ) print ( "streamer started, backend on port : %d\tfro...
def load_config ( json_path ) : """Load config info from a . json file and return it ."""
with open ( json_path , 'r' ) as json_file : config = json . loads ( json_file . read ( ) ) # sanity - test the config : assert ( config [ 'tree' ] [ 0 ] [ 'page' ] == 'index' ) return config
def load ( self , session_id = None ) : """Load the session from the store . session _ id can be : - None : load from cookie - ' ' : create a new cookieless session _ id - a string which is the session _ id to be used ."""
if session_id is None : cookie_name = self . _config . cookie_name self . _data [ "session_id" ] = web . cookies ( ) . get ( cookie_name ) self . _data [ "cookieless" ] = False else : if session_id == '' : self . _data [ "session_id" ] = None # will be created else : self . _...
def get_media_descriptions_metadata ( self ) : """Gets the metadata for all media descriptions . return : ( osid . Metadata ) - metadata for the media descriptions * compliance : mandatory - - This method must be implemented . *"""
metadata = dict ( self . _media_descriptions_metadata ) metadata . update ( { 'existing_string_values' : [ t [ 'text' ] for t in self . my_osid_object_form . _my_map [ 'mediaDescriptions' ] ] } ) return Metadata ( ** metadata )
def _dfs_preorder ( node , visited ) : """Iterate through nodes in DFS pre - order ."""
if node not in visited : visited . add ( node ) yield node if node . lo is not None : yield from _dfs_preorder ( node . lo , visited ) if node . hi is not None : yield from _dfs_preorder ( node . hi , visited )
def mergeTablets ( self , login , tableName , startRow , endRow ) : """Parameters : - login - tableName - startRow - endRow"""
self . send_mergeTablets ( login , tableName , startRow , endRow ) self . recv_mergeTablets ( )
def do_join ( self , cmdargs , nick , msgtype , send , c ) : """Join a channel . | Checks if bot is already joined to channel ."""
if not cmdargs : send ( "Join what?" ) return if cmdargs == '0' : send ( "I'm sorry, Dave. I'm afraid I can't do that." ) return if not cmdargs . startswith ( ( '#' , '+' , '@' ) ) : cmdargs = '#' + cmdargs cmd = cmdargs . split ( ) # FIXME : use argparse if cmd [ 0 ] in self . channels and not ( le...
def _tag_type_to_explicit_implicit ( params ) : """Converts old - style " tag _ type " and " tag " params to " explicit " and " implicit " : param params : A dict of parameters to convert from tag _ type / tag to explicit / implicit"""
if 'tag_type' in params : if params [ 'tag_type' ] == 'explicit' : params [ 'explicit' ] = ( params . get ( 'class' , 2 ) , params [ 'tag' ] ) elif params [ 'tag_type' ] == 'implicit' : params [ 'implicit' ] = ( params . get ( 'class' , 2 ) , params [ 'tag' ] ) del params [ 'tag_type' ] ...
def browse_httpauth_write_apis ( request , database_name = None , collection_name = None ) : """Deprecated"""
name = "Write APIs Using HTTPAuth Authentication" if database_name and collection_name : wapis = WriteAPIHTTPAuth . objects . filter ( database_name = database_name , collection_name = collection_name ) else : wapis = WriteAPIHTTPAuth . objects . all ( ) context = { 'name' : name , 'wapis' : wapis , 'database_n...
def parse_partition ( rule ) : '''Parse the partition line'''
parser = argparse . ArgumentParser ( ) rules = shlex . split ( rule ) rules . pop ( 0 ) parser . add_argument ( 'mntpoint' ) parser . add_argument ( '--size' , dest = 'size' , action = 'store' ) parser . add_argument ( '--grow' , dest = 'grow' , action = 'store_true' ) parser . add_argument ( '--maxsize' , dest = 'maxs...
def find_lines_wo_child ( config = None , config_path = None , parent_regex = None , child_regex = None , ignore_ws = False , saltenv = 'base' ) : '''Return a list of parent ` ` ciscoconfparse . IOSCfgLine ` ` lines as text , which matched the ` ` parent _ regex ` ` and whose children did * not * match ` ` child ...
lines = find_objects_wo_child ( config = config , config_path = config_path , parent_regex = parent_regex , child_regex = child_regex , ignore_ws = ignore_ws , saltenv = saltenv ) return [ line . text for line in lines ]
def append_items ( self , items , ** kwargs ) : """Method to append data to multiple : class : ` ~ . Item ` objects . This method differs from the normal : meth : ` append _ multi ` in that each ` Item ` ' s ` value ` field is updated with the appended data upon successful completion of the operation . : pa...
rv = self . append_multi ( items , ** kwargs ) # Assume this is an ' ItemOptionDict ' for k , v in items . dict . items ( ) : if k . success : k . value += v [ 'fragment' ] return rv
def _GetDistinctValues ( self , field_name ) : """Query database for unique field types . Args : field _ name ( str ) : name of the filed to retrieve . Returns : dict [ str , int ] : counts of field types by name ."""
self . _cursor . execute ( 'SELECT {0:s}, COUNT({0:s}) FROM log2timeline GROUP BY {0:s}' . format ( field_name ) ) result = { } row = self . _cursor . fetchone ( ) while row : if row [ 0 ] : result [ row [ 0 ] ] = row [ 1 ] row = self . _cursor . fetchone ( ) return result
def _notify_mutated ( self , obj , old , hint = None ) : '''A method to call when a container is mutated " behind our back " and we detect it with our | PropertyContainer | wrappers . Args : obj ( HasProps ) : The object who ' s container value was mutated old ( object ) : The " old " value of the conta...
value = self . __get__ ( obj , obj . __class__ ) # re - validate because the contents of ' old ' have changed , # in some cases this could give us a new object for the value value = self . property . prepare_value ( obj , self . name , value ) self . _real_set ( obj , old , value , hint = hint )
def default_logging ( grab_log = None , # ' / tmp / grab . log ' , network_log = None , # ' / tmp / grab . network . log ' , level = logging . DEBUG , mode = 'a' , propagate_network_logger = False ) : """Customize logging output to display all log messages except grab network logs . Redirect grab network logs i...
logging . basicConfig ( level = level ) network_logger = logging . getLogger ( 'grab.network' ) network_logger . propagate = propagate_network_logger if network_log : hdl = logging . FileHandler ( network_log , mode ) network_logger . addHandler ( hdl ) network_logger . setLevel ( level ) grab_logger = logg...
def get_ceph_nodes ( relation = 'ceph' ) : """Query named relation to determine current nodes ."""
hosts = [ ] for r_id in relation_ids ( relation ) : for unit in related_units ( r_id ) : hosts . append ( relation_get ( 'private-address' , unit = unit , rid = r_id ) ) return hosts
def _compute_diff ( configured , expected ) : '''Computes the differences between the actual config and the expected config'''
diff = { 'add' : { } , 'update' : { } , 'remove' : { } } configured_users = set ( configured . keys ( ) ) expected_users = set ( expected . keys ( ) ) add_usernames = expected_users - configured_users remove_usernames = configured_users - expected_users common_usernames = expected_users & configured_users add = dict ( ...
def getbit ( self , name , offset ) : """Returns a boolean indicating the value of ` ` offset ` ` in ` ` name ` ` Like * * Redis . GETBIT * * : param string name : the key name : param int offset : the bit position : param bool val : the bit value : return : the bit at the ` ` offset ` ` , ` ` False ` ` i...
offset = get_positive_integer ( 'offset' , offset ) return self . execute_command ( 'getbit' , name , offset )
def Rohsenow ( rhol , rhog , mul , kl , Cpl , Hvap , sigma , Te = None , q = None , Csf = 0.013 , n = 1.7 ) : r'''Calculates heat transfer coefficient for a evaporator operating in the nucleate boiling regime according to [ 2 ] _ as presented in [ 1 ] _ . Either heat flux or excess temperature is required . W...
if Te : return mul * Hvap * ( g * ( rhol - rhog ) / sigma ) ** 0.5 * ( Cpl * Te ** ( 2 / 3. ) / Csf / Hvap / ( Cpl * mul / kl ) ** n ) ** 3 elif q : A = mul * Hvap * ( g * ( rhol - rhog ) / sigma ) ** 0.5 * ( Cpl / Csf / Hvap / ( Cpl * mul / kl ) ** n ) ** 3 return A ** ( 1 / 3. ) * q ** ( 2 / 3. ) else : ...
def start ( self , * args , ** kw ) : """Start the daemon ."""
pid = None if os . path . exists ( self . pidfile ) : with open ( self . pidfile , 'r' ) as fp : pid = int ( fp . read ( ) . strip ( ) ) if pid : msg = 'pidfile (%s) exists. Daemon already running?\n' sys . stderr . write ( msg % self . pidfile ) sys . exit ( 1 ) self . daemonize ( ) self . run ...
def gpio_properties ( self ) : """Returns the properties of the user - controllable GPIOs . Provided the device supports user - controllable GPIOs , they will be returned by this method . Args : self ( JLink ) : the ` ` JLink ` ` instance Returns : A list of ` ` JLinkGPIODescriptor ` ` instances totalli...
res = self . _dll . JLINK_EMU_GPIO_GetProps ( 0 , 0 ) if res < 0 : raise errors . JLinkException ( res ) num_props = res buf = ( structs . JLinkGPIODescriptor * num_props ) ( ) res = self . _dll . JLINK_EMU_GPIO_GetProps ( ctypes . byref ( buf ) , num_props ) if res < 0 : raise errors . JLinkException ( res ) r...
def _get_node ( template , context , name ) : '''taken originally from http : / / stackoverflow . com / questions / 2687173 / django - how - can - i - get - a - block - from - a - template'''
for node in template : if isinstance ( node , BlockNode ) and node . name == name : return node . nodelist . render ( context ) elif isinstance ( node , ExtendsNode ) : return _get_node ( node . nodelist , context , name ) # raise Exception ( " Node ' % s ' could not be found in template . " % n...
def register_view ( self , view ) : """Called when the View was registered"""
super ( MenuBarController , self ) . register_view ( view ) data_flow_mode = global_runtime_config . get_config_value ( "DATA_FLOW_MODE" , False ) view [ "data_flow_mode" ] . set_active ( data_flow_mode ) show_data_flows = global_runtime_config . get_config_value ( "SHOW_DATA_FLOWS" , True ) view [ "show_data_flows" ] ...
def to_dict ( self ) -> Dict : """Export the CAG to a dict that can be serialized to JSON ."""
return { "name" : self . name , "dateCreated" : str ( self . dateCreated ) , "variables" : lmap ( lambda n : self . export_node ( n ) , self . nodes ( data = True ) ) , "timeStep" : str ( self . Δt ) , "edge_data" : lmap ( export_edge , self . edges ( data = True ) ) , }
def _Open ( self , path_spec , mode = 'rb' ) : """Opens the file system defined by path specification . Args : path _ spec ( PathSpec ) : a path specification . mode ( Optional [ str ] ) ) : file access mode . The default is ' rb ' read - only binary . Raises : AccessError : if the access to open the fi...
if not path_spec . HasParent ( ) : raise errors . PathSpecError ( 'Unsupported path specification without parent.' ) file_object = resolver . Resolver . OpenFileObject ( path_spec . parent , resolver_context = self . _resolver_context ) try : fsapfs_container = pyfsapfs . container ( ) fsapfs_container . op...
def set_param ( self , idx ) : """Adds the parameter to the conversion modifier . : param idx : Provides the ending index of the parameter string ."""
self . modifier . set_param ( self . format [ self . param_begin : idx ] )
def node_path ( self , node ) : """Return two lists describing the path from this node to another Parameters node : instance of Node The other node . Returns p1 : list First path ( see below ) . p2 : list Second path ( see below ) . Notes The first list starts with this node and ends with the co...
p1 = self . parent_chain ( ) p2 = node . parent_chain ( ) cp = None for p in p1 : if p in p2 : cp = p break if cp is None : raise RuntimeError ( "No single-path common parent between nodes %s " "and %s." % ( self , node ) ) p1 = p1 [ : p1 . index ( cp ) + 1 ] p2 = p2 [ : p2 . index ( cp ) ] [ : ...
def _get_path ( self , file ) : """Creates the cache directory if it doesn ' t already exist . Returns the full path to the specified file inside the cache directory ."""
dir = self . _cache_directory ( ) if not os . path . exists ( dir ) : os . makedirs ( dir ) return os . path . join ( dir , file )
def load_or_create_client_key ( pem_path ) : """Load the client key from a directory , creating it if it does not exist . . . note : : The client key that will be created will be a 2048 - bit RSA key . : type pem _ path : ` ` twisted . python . filepath . FilePath ` ` : param pem _ path : The certificate dire...
acme_key_file = pem_path . asTextMode ( ) . child ( u'client.key' ) if acme_key_file . exists ( ) : key = serialization . load_pem_private_key ( acme_key_file . getContent ( ) , password = None , backend = default_backend ( ) ) else : key = generate_private_key ( u'rsa' ) acme_key_file . setContent ( key . ...
def parsePoint ( line ) : """Parse a line of text into an MLlib LabeledPoint object ."""
values = [ float ( s ) for s in line . split ( ' ' ) ] if values [ 0 ] == - 1 : # Convert - 1 labels to 0 for MLlib values [ 0 ] = 0 return LabeledPoint ( values [ 0 ] , values [ 1 : ] )
def root ( self : BoardT ) -> BoardT : """Returns a copy of the root position ."""
if self . _stack : board = type ( self ) ( None , chess960 = self . chess960 ) self . _stack [ 0 ] . restore ( board ) return board else : return self . copy ( stack = False )
def generate ( env ) : """Add Builders and construction variables for Visual Age linker to an Environment ."""
link . generate ( env ) env [ 'SMARTLINKFLAGS' ] = smart_linkflags env [ 'LINKFLAGS' ] = SCons . Util . CLVar ( '$SMARTLINKFLAGS' ) env [ 'SHLINKFLAGS' ] = SCons . Util . CLVar ( '$LINKFLAGS -qmkshrobj -qsuppress=1501-218' ) env [ 'SHLIBSUFFIX' ] = '.a'
def decompress ( self , image_path , quiet = True ) : '''decompress will ( properly ) decompress an image'''
if not os . path . exists ( image_path ) : bot . exit ( "Cannot find image %s" % image_path ) extracted_file = image_path . replace ( '.gz' , '' ) cmd = [ 'gzip' , '-d' , '-f' , image_path ] result = self . run_command ( cmd , quiet = quiet ) # exits if return code ! = 0 return extracted_file
def long_to_bytes ( n , blocksize = 0 ) : """long _ to _ bytes ( n : long , blocksize : int ) : string Convert a long integer to a byte string . If optional blocksize is given and greater than zero , pad the front of the byte string with binary zeros so that the length is a multiple of blocksize ."""
# after much testing , this algorithm was deemed to be the fastest s = b'' if USING_PYTHON2 : n = long ( n ) # noqa pack = struct . pack while n > 0 : s = pack ( b'>I' , n & 0xffffffff ) + s n = n >> 32 # strip off leading zeros for i in range ( len ( s ) ) : if s [ i ] != b'\000' [ 0 ] : br...
def getScoreProperties ( self ) : """Returns the accidental dignity score of the object as dict ."""
obj = self . obj score = { } # Peregrine isPeregrine = essential . isPeregrine ( obj . id , obj . sign , obj . signlon ) score [ 'peregrine' ] = - 5 if isPeregrine else 0 # Ruler - Ruler and Exalt - Exalt mutual receptions mr = self . eqMutualReceptions ( ) score [ 'mr_ruler' ] = + 5 if 'ruler' in mr else 0 score [ 'mr...
def create_title ( article , language , title , slug = None , description = None , page_title = None , menu_title = None , meta_description = None , creation_date = None , image = None ) : """Create an article title ."""
# validate article assert isinstance ( article , Article ) # validate language : assert language in get_language_list ( article . tree . node . site_id ) # validate creation date if creation_date : assert isinstance ( creation_date , datetime . date ) # set default slug : if not slug : slug = settings . CMS_ART...
def _set_launcher_property ( self , driver_arg_key , spark_property_key ) : """Handler for a special property that exists in both the launcher arguments and the spark conf dictionary . This will use the launcher argument if set falling back to the spark conf argument . If neither are set this is a noop ( which ...
value = self . _spark_launcher_args . get ( driver_arg_key , self . conf . _conf_dict . get ( spark_property_key ) ) if value : self . _spark_launcher_args [ driver_arg_key ] = value self . conf [ spark_property_key ] = value
def FIELD_DECL ( self , cursor ) : """Handles Field declarations . Some specific treatment for a bitfield ."""
# name , type parent = cursor . semantic_parent # field name : # either its cursor . spelling or it is an anonymous field # we do NOT rely on get _ unique _ name for a Field name . # Anonymous Field : # We have to create a name # it will be the indice of the field ( _ 0 , _ 1 , . . . ) # offset of field : # we will nee...
def invoke_editor ( before_editing , cluster_name ) : """Starts editor command to edit configuration in human readable format : param before _ editing : human representation before editing : returns tuple of human readable and parsed datastructure after changes"""
editor_cmd = os . environ . get ( 'EDITOR' ) if not editor_cmd : raise PatroniCtlException ( 'EDITOR environment variable is not set' ) with temporary_file ( contents = before_editing . encode ( 'utf-8' ) , suffix = '.yaml' , prefix = '{0}-config-' . format ( cluster_name ) ) as tmpfile : ret = subprocess . cal...
def importDirectory ( self , login , tableName , importDir , failureDir , setTime ) : """Parameters : - login - tableName - importDir - failureDir - setTime"""
self . send_importDirectory ( login , tableName , importDir , failureDir , setTime ) self . recv_importDirectory ( )
def is_double_reversed_equal ( num : int ) -> bool : """Given an integer num , this function reverses num to get reversed1 , then reverses reversed1 to get reversed2. The function returns True if reversed2 equals num , and False otherwise . Leading zeros in the reversed integers are not retained . Parameters ...
reversed1 = int ( str ( num ) [ : : - 1 ] ) reversed2 = int ( str ( reversed1 ) [ : : - 1 ] ) return reversed2 == num
def possible_parameter ( nb , jsonable_parameter = True , end_cell_index = None ) : """Find the possible parameters from a jupyter notebook ( python3 only ) . The possible parameters are obtained by parsing the abstract syntax tree of the python code generated from the jupyter notebook . For a jupuyter notebo...
jh = _JupyterNotebookHelper ( nb , jsonable_parameter , end_cell_index ) if jsonable_parameter is True : PossibleParameter = collections . namedtuple ( 'PossibleParameter' , [ 'name' , 'value' , 'cell_index' ] ) else : PossibleParameter = collections . namedtuple ( 'PossibleParameter' , [ 'name' , 'cell_index' ...
def update_index_for_direction ( self , index_direction , index ) : """: type index _ direction : SliceDirection : type index : int"""
indexes = self . _slice_data_source . indexes_for_direction ( index_direction ) if index < 0 : index = 0 elif index >= len ( indexes ) : index = len ( indexes ) - 1 for m in self . _available_slice_models : if m . index_direction == index_direction : m . index = index if m . x_index_direction ==...
def list_of_lists_to_dict ( l ) : """Convert list of key , value lists to dict [ [ ' id ' , 1 ] , [ ' id ' , 2 ] , [ ' id ' , 3 ] , [ ' foo ' : 4 ] ] { ' id ' : [ 1 , 2 , 3 ] , ' foo ' : [ 4 ] }"""
d = { } for key , val in l : d . setdefault ( key , [ ] ) . append ( val ) return d
def minimum_needs_unit ( field , feature , parent ) : """Retrieve units of the given minimum needs field name . For instance : * minimum _ needs _ unit ( ' minimum _ needs _ _ clean _ water ' ) - > ' l / weekly '"""
_ = feature , parent # NOQA field_definition = definition ( field , 'field_name' ) if field_definition : unit_abbreviation = None frequency = None if field_definition . get ( 'need_parameter' ) : need = field_definition [ 'need_parameter' ] if isinstance ( need , ResourceParameter ) : ...
def validate_filters ( self , branchset_node , uncertainty_type , filters ) : """See superclass ' method for description and signature specification . Checks that the following conditions are met : * " sourceModel " uncertainties can not have filters . * Absolute uncertainties must have only one filter - - ...
if uncertainty_type == 'sourceModel' and filters : raise LogicTreeError ( branchset_node , self . filename , 'filters are not allowed on source model uncertainty' ) if len ( filters ) > 1 : raise LogicTreeError ( branchset_node , self . filename , "only one filter is allowed per branchset" ) if 'applyToTectonic...
def delete ( self , key ) : """Remove a value from the ` DotDict ` . The ` key ` parameter can either be a regular string key , e . g . " foo " , or it can be a string key with dot notation , e . g . " foo . bar . baz " , to signify a nested element . If the key does not exist in the ` DotDict ` , it will c...
dct = self keys = key . split ( '.' ) last_key = keys [ - 1 ] for k in keys : # if the key is the last one , e . g . ' z ' in ' x . y . z ' , try # to delete it from its dict . if k == last_key : del dct [ k ] break # if the dct is a DotDict , get the value for the key ` k ` from it . if isi...
def import_from_dict ( cls , session , dict_rep , parent = None , recursive = True , sync = [ ] ) : """Import obj from a dictionary"""
parent_refs = cls . _parent_foreign_key_mappings ( ) export_fields = set ( cls . export_fields ) | set ( parent_refs . keys ( ) ) new_children = { c : dict_rep . get ( c ) for c in cls . export_children if c in dict_rep } unique_constrains = cls . _unique_constrains ( ) filters = [ ] # Using these filters to check if o...
def get_list_dimensions ( _list ) : """Takes a nested list and returns the size of each dimension followed by the element type in the list"""
if isinstance ( _list , list ) or isinstance ( _list , tuple ) : return [ len ( _list ) ] + get_list_dimensions ( _list [ 0 ] ) return [ ]
def closePanel ( self ) : """Closes a full view panel ."""
# make sure we can close all the widgets in the view first for i in range ( self . count ( ) ) : if not self . widget ( i ) . canClose ( ) : return False container = self . parentWidget ( ) viewWidget = self . viewWidget ( ) # close all the child views for i in xrange ( self . count ( ) - 1 , - 1 , - 1 ) : ...
def pixy_value_update ( blocks ) : """Prints the Pixy blocks data ."""
if len ( blocks ) > 0 : pan_error = X_CENTER - blocks [ 0 ] [ "x" ] tilt_error = blocks [ 0 ] [ "y" ] - Y_CENTER pan_loop . update ( pan_error ) tilt_loop . update ( tilt_error ) loop = asyncio . get_event_loop ( ) if loop . is_running ( ) : # This is the version that will be used since we are i...
def build_specfile ( target , source , env ) : """Builds a RPM specfile from a dictionary with string metadata and by analyzing a tree of nodes ."""
file = open ( target [ 0 ] . get_abspath ( ) , 'w' ) try : file . write ( build_specfile_header ( env ) ) file . write ( build_specfile_sections ( env ) ) file . write ( build_specfile_filesection ( env , source ) ) file . close ( ) # call a user specified function if 'CHANGE_SPECFILE' in env : ...
def enable_broadcasting ( self ) : """Begin accumulating broadcast reports received from all devices . This method will allocate a queue to receive broadcast reports that will be filled asynchronously as broadcast reports are received . Returns : queue . Queue : A queue that will be filled with braodcast re...
if self . _broadcast_reports is not None : _clear_queue ( self . _broadcast_reports ) return self . _broadcast_reports self . _broadcast_reports = queue . Queue ( ) return self . _broadcast_reports
def _checkAndConvertIndex ( self , index ) : """Check integer index , convert from less than zero notation"""
if index < 0 : index = len ( self ) + index if index < 0 or index >= self . _doc . blockCount ( ) : raise IndexError ( 'Invalid block index' , index ) return index
def Deserialize ( self , reader ) : """Deserialize full object . Args : reader ( neo . IO . BinaryReader ) :"""
self . Script = reader . ReadVarBytes ( ) self . ParameterList = reader . ReadVarBytes ( ) self . ReturnType = reader . ReadByte ( )
def _get_proj4_name ( self , projection ) : """Map CF projection name to PROJ . 4 name ."""
gmap_name = projection . attrs [ 'grid_mapping_name' ] proj = { 'geostationary' : 'geos' , 'lambert_conformal_conic' : 'lcc' , 'polar_stereographic' : 'stere' , 'mercator' : 'merc' , } . get ( gmap_name , gmap_name ) return proj
def build_class_graph ( modules , klass = None , graph = None ) : """Builds up a graph of the DictCell subclass structure"""
if klass is None : class_graph = nx . DiGraph ( ) for name , classmember in inspect . getmembers ( modules , inspect . isclass ) : if issubclass ( classmember , Referent ) and classmember is not Referent : TaxonomyCell . build_class_graph ( modules , classmember , class_graph ) return cl...
def load_units ( self ) : """Build a set of systemd units that Ellis will watch . This set will be used to filter journald entries so that we only process entries that were produced by these units . This should result in better performance ."""
# Of course , we only consider valid Rules . for rule in self . rules : try : systemd_unit = self . config . get ( rule . name , 'systemd_unit' ) except configparser . NoOptionError : warnings . warn ( "Rule '{0}' doesn't have a `systemd_unit` " "option set.\nThe filters will be checked " "again...
def _volumes ( self ) : """returns a map { volume _ id : { serial : , vendor _ id : , product _ id : , tty : }"""
# to find all the possible mbed volumes , we look for registry entries # under all possible USB tree which have a " BSD Name " that starts with # " disk " # ( i . e . this is a USB disk ) , and have a IORegistryEntryName that # matches / \ cmbed / # Once we ' ve found a disk , we can search up for a parent with a valid...
def calculate ( self , order , transaction ) : """Pay commission based on dollar value of shares ."""
cost_per_share = transaction . price * self . cost_per_dollar return abs ( transaction . amount ) * cost_per_share
def create_namedlayer ( self , name ) : """Create a L { NamedLayer } in this SLD . @ type name : string @ param name : The name of the layer . @ rtype : L { NamedLayer } @ return : The named layer , attached to this SLD ."""
namedlayer = self . get_or_create_element ( 'sld' , 'NamedLayer' ) namedlayer . Name = name return namedlayer
def clean_markup ( self , markup , parser = None ) : """Apply ` ` Cleaner ` ` to markup string or document and return a cleaned string or document ."""
result_type = type ( markup ) if isinstance ( markup , six . string_types ) : doc = fromstring ( markup , parser = parser ) else : doc = copy . deepcopy ( markup ) self ( doc ) if issubclass ( result_type , six . binary_type ) : return tostring ( doc , encoding = 'utf-8' ) elif issubclass ( result_type , si...
def send_keyevents_long_press ( self , keyevent : int ) -> None : '''Simulates typing keyevents long press .'''
self . _execute ( '-s' , self . device_sn , 'shell' , 'input' , 'keyevent' , '--longpress' , str ( keyevent ) )
def move_to ( self , target , position = 'first-child' ) : """Invalidate cache when moving"""
# Invalidate both in case position matters , # otherwise only target is needed . self . invalidate ( ) target . invalidate ( ) super ( Page , self ) . move_to ( target , position = position )
def get_parents ( obj , ** kwargs ) : """Return the MRO of an object . Do regex on each element to remove the " < class . . . " bit ."""
num_of_mro = kwargs . get ( "num_of_mro" , 5 ) mro = getmro ( obj . __class__ ) mro_string = ', ' . join ( [ extract_type ( str ( t ) ) for t in mro [ : num_of_mro ] ] ) return "Hierarchy: {}" . format ( mro_string )
def _compute_head_process_tail ( self , audio_file_mfcc ) : """Set the audio file head or tail , by either reading the explicit values from the Task configuration , or using SD to determine them . This function returns the lengths , in seconds , of the ( head , process , tail ) . : rtype : tuple ( float...
head_length = self . task . configuration [ "i_a_head" ] process_length = self . task . configuration [ "i_a_process" ] tail_length = self . task . configuration [ "i_a_tail" ] head_max = self . task . configuration [ "i_a_head_max" ] head_min = self . task . configuration [ "i_a_head_min" ] tail_max = self . task . co...
def save_plain_image_as_file ( self , filepath , format = 'png' , quality = 90 ) : """Used for generating thumbnails . Does not include overlaid graphics ."""
pixbuf = self . get_plain_image_as_pixbuf ( ) options = { } if format == 'jpeg' : options [ 'quality' ] = str ( quality ) pixbuf . save ( filepath , format , options )
def bootstrap_alert ( visitor , items ) : """Format : [ [ alert ( class = error ) ] ] : message"""
txt = [ ] for x in items : cls = x [ 'kwargs' ] . get ( 'class' , '' ) if cls : cls = 'alert-%s' % cls txt . append ( '<div class="alert %s">' % cls ) if 'close' in x [ 'kwargs' ] : txt . append ( '<button class="close" data-dismiss="alert">&times;</button>' ) text = visitor . parse_...
def __get_config ( self , data_sources = None ) : """Build a dictionary with the Report configuration with the data sources and metrics to be included in each section of the report : param data _ sources : list of data sources to be included in the report : return : a dict with the data sources and metrics to...
if not data_sources : # For testing data_sources = [ "gerrit" , "git" , "github_issues" , "mls" ] # In new _ config a dict with all the metrics for all data sources is created new_config = { } for ds in data_sources : ds_config = self . ds2class [ ds ] . get_section_metrics ( ) for section in ds_config : ...
def close ( self ) : """Write final shp , shx , and dbf headers , close opened files ."""
# Check if any of the files have already been closed shp_open = self . shp and not ( hasattr ( self . shp , 'closed' ) and self . shp . closed ) shx_open = self . shx and not ( hasattr ( self . shx , 'closed' ) and self . shx . closed ) dbf_open = self . dbf and not ( hasattr ( self . dbf , 'closed' ) and self . dbf . ...
def UpdateFlows ( self , client_id_flow_id_pairs , pending_termination = db . Database . unchanged ) : """Updates flow objects in the database ."""
for client_id , flow_id in client_id_flow_id_pairs : try : self . UpdateFlow ( client_id , flow_id , pending_termination = pending_termination ) except db . UnknownFlowError : pass
def _make_fast_url_quote ( charset = "utf-8" , errors = "strict" , safe = "/:" , unsafe = "" ) : """Precompile the translation table for a URL encoding function . Unlike : func : ` url _ quote ` , the generated function only takes the string to quote . : param charset : The charset to encode the result with ....
if isinstance ( safe , text_type ) : safe = safe . encode ( charset , errors ) if isinstance ( unsafe , text_type ) : unsafe = unsafe . encode ( charset , errors ) safe = ( frozenset ( bytearray ( safe ) ) | _always_safe ) - frozenset ( bytearray ( unsafe ) ) table = [ chr ( c ) if c in safe else "%%%02X" % c f...
def find_n_nearest ( self , lat , lng , n = 5 , radius = None ) : """Find n nearest point within certain distance from a point . : param lat : latitude of center point . : param lng : longitude of center point . : param n : max number of record to return . : param radius : only search point within ` ` radiu...
engine , t_point = self . engine , self . t_point if radius : # Use a simple box filter to minimize candidates # Define latitude longitude boundary dist_btwn_lat_deg = 69.172 dist_btwn_lon_deg = cos ( lat ) * 69.172 lat_degr_rad = abs ( radius * 1.05 / dist_btwn_lat_deg ) lon_degr_rad = abs ( radius * 1...
def get_output_files ( self ) : """Returns a list of the files output by the job , querying the server if necessary . If the job has output no files , an empty list will be returned ."""
# Lazily load info if self . info is None : self . get_info ( ) if 'outputFiles' in self . info : return [ GPFile ( self . server_data , f [ 'link' ] [ 'href' ] ) for f in self . info [ 'outputFiles' ] ] else : return [ ]
def iter_stack_frames ( frames = None ) : """Given an optional list of frames ( defaults to current stack ) , iterates over all frames that do not contain the ` ` _ _ traceback _ hide _ _ ` ` local variable ."""
if not frames : frames = inspect . stack ( ) [ 1 : ] for frame , lineno in ( ( f [ 0 ] , f [ 2 ] ) for f in reversed ( frames ) ) : f_locals = getattr ( frame , 'f_locals' , { } ) if not _getitem_from_frame ( f_locals , '__traceback_hide__' ) : yield frame , lineno
def row ( self , content = '' , align = 'left' ) : """A row of the menu , which comprises the left and right verticals plus the given content . Returns : str : A row of this menu component with the specified content ."""
return u"{lm}{vert}{cont}{vert}" . format ( lm = ' ' * self . margins . left , vert = self . border_style . outer_vertical , cont = self . _format_content ( content , align ) )
def _zero_many ( self , i , j ) : """Sets value at each ( i , j ) to zero , preserving sparsity structure . Here ( i , j ) index major and minor respectively ."""
i , j , M , N = self . _prepare_indices ( i , j ) n_samples = len ( i ) offsets = np . empty ( n_samples , dtype = self . indices . dtype ) ret = _sparsetools . csr_sample_offsets ( M , N , self . indptr , self . indices , n_samples , i , j , offsets ) if ret == 1 : # rinse and repeat self . sum_duplicates ( ) ...
def load_p2th_privkey_into_local_node ( provider : RpcNode , prod : bool = True ) -> None : '''Load PeerAssets P2TH privkey into the local node .'''
assert isinstance ( provider , RpcNode ) , { "error" : "Import only works with local node." } error = { "error" : "Loading P2TH privkey failed." } pa_params = param_query ( provider . network ) if prod : provider . importprivkey ( pa_params . P2TH_wif , "PAPROD" ) # now verify if ismine = = True if not prov...
def string_to_34_array ( sou = None , pin = None , man = None , honors = None ) : """Method to convert one line string tiles format to the 34 array We need it to increase readability of our tests"""
results = TilesConverter . string_to_136_array ( sou , pin , man , honors ) results = TilesConverter . to_34_array ( results ) return results
def cudaMemcpy_dtoh ( dst , src , count ) : """Copy memory from device to host . Copy data from device memory to host memory . Parameters dst : ctypes pointer Host memory pointer . src : ctypes pointer Device memory pointer . count : int Number of bytes to copy ."""
status = _libcudart . cudaMemcpy ( dst , src , ctypes . c_size_t ( count ) , cudaMemcpyDeviceToHost ) cudaCheckStatus ( status )
def getPlayAreaRect ( self ) : """Returns the 4 corner positions of the Play Area ( formerly named Soft Bounds ) . Corners are in counter - clockwise order . Standing center ( 0,0,0 ) is the center of the Play Area . It ' s a rectangle . 2 sides are parallel to the X axis and 2 sides are parallel to the Z a...
fn = self . function_table . getPlayAreaRect rect = HmdQuad_t ( ) result = fn ( byref ( rect ) ) return result , rect
def Nu_horizontal_cylinder_Morgan ( Pr , Gr ) : r'''Calculates Nusselt number for natural convection around a horizontal cylinder according to the Morgan [ 1 ] _ correlations , a product of a very large review of the literature . Sufficiently common as to be shown in [ 2 ] _ . Cylinder must be isothermal . ...
Ra = Pr * Gr if Ra < 1E-2 : C , n = 0.675 , 0.058 elif Ra < 1E2 : C , n = 1.02 , 0.148 elif Ra < 1E4 : C , n = 0.850 , 0.188 elif Ra < 1E7 : C , n = 0.480 , 0.250 else : # up to 1E12 C , n = 0.125 , 0.333 return C * Ra ** n
def get_voltage ( self , channel , unit = 'V' ) : '''Reading voltage'''
kwargs = self . _ch_map [ channel ] [ 'ADCV' ] voltage_raw = self . _get_adc_value ( ** kwargs ) voltage = ( voltage_raw - self . _ch_cal [ channel ] [ 'ADCV' ] [ 'offset' ] ) / self . _ch_cal [ channel ] [ 'ADCV' ] [ 'gain' ] if unit == 'raw' : return voltage_raw elif unit == 'V' : return voltage elif unit == ...
def make_step_rcont ( transition ) : """Return a ufunc - like step function that is right - continuous . Returns 1 if x > = transition , 0 otherwise ."""
if not np . isfinite ( transition ) : raise ValueError ( '"transition" argument must be finite number; got %r' % transition ) def step_rcont ( x ) : x = np . asarray ( x ) x1 = np . atleast_1d ( x ) r = ( x1 >= transition ) . astype ( x . dtype ) if x . ndim == 0 : return np . asscalar ( r )...
def load_cert_chain ( self , certfile , keyfile = None ) : """Load a private key and the corresponding certificate . The certfile string must be the path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate ' s authenticity . Th...
self . _certfile = certfile self . _keyfile = keyfile
def GetHashObject ( self ) : """Returns a ` Hash ` object with appropriate fields filled - in ."""
hash_object = rdf_crypto . Hash ( ) hash_object . num_bytes = self . _bytes_read for algorithm in self . _hashers : setattr ( hash_object , algorithm , self . _hashers [ algorithm ] . digest ( ) ) return hash_object
def iterate ( self , params , repetition , iteration ) : """For each iteration try to infer the object represented by the ' iteration ' parameter returning Whether or not the object was unambiguously classified . : param params : Specific parameters for this iteration . See ' experiments . cfg ' for list of p...
objname , sensations = self . objects . items ( ) [ iteration ] # Select sensations to infer np . random . shuffle ( sensations [ 0 ] ) sensations = [ sensations [ 0 ] [ : self . numOfSensations ] ] self . network . sendReset ( ) # Collect all statistics for every inference . # See L246aNetwork . _ updateInferenceStats...
def get_gradebook_column_gradebook_assignment_session ( self , proxy ) : """Gets the session for assigning gradebook column to gradebook mappings . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . grading . GradebookColumnGradebookAssignmentSession ) - a ` ` GradebookColumnGradebookAssignmentS...
if not self . supports_gradebook_column_gradebook_assignment ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . GradebookColumnGradebookAssignmentSession ( proxy = proxy , runtime = self . _runtime )
def values ( service , id , ranges ) : """Fetch and return spreadsheet cell values with Google sheets API ."""
params = { 'majorDimension' : 'ROWS' , 'valueRenderOption' : 'UNFORMATTED_VALUE' , 'dateTimeRenderOption' : 'FORMATTED_STRING' } params . update ( spreadsheetId = id , ranges = ranges ) response = service . spreadsheets ( ) . values ( ) . batchGet ( ** params ) . execute ( ) return response [ 'valueRanges' ]
def _bnot8 ( ins ) : """Negates ( BITWISE NOT ) top of the stack ( 8 bits in AF )"""
output = _8bit_oper ( ins . quad [ 2 ] ) output . append ( 'cpl' ) # Gives carry only if A = 0 output . append ( 'push af' ) return output
def combine ( line , left , intersect , right ) : """Zip borders between items in ` line ` . e . g . ( ' l ' , ' 1 ' , ' c ' , ' 2 ' , ' c ' , ' 3 ' , ' r ' ) : param iter line : List to iterate . : param left : Left border . : param intersect : Column separator . : param right : Right border . : return...
# Yield left border . if left : yield left # Yield items with intersect characters . if intersect : try : for j , i in enumerate ( line , start = - len ( line ) + 1 ) : yield i if j : yield intersect except TypeError : # Generator . try : i...
def activate ( ) : """Usage : containment activate"""
# This is derived from the clone cli = CommandLineInterface ( ) cli . ensure_config ( ) cli . write_dockerfile ( ) cli . build ( ) cli . run ( )
def clean ( self ) : """Make sure there is at least a translation has been filled in . If a default language has been specified , make sure that it exists amongst translations ."""
# First make sure the super ' s clean method is called upon . super ( TranslationFormSet , self ) . clean ( ) if settings . HIDE_LANGUAGE : return if len ( self . forms ) > 0 : # If a default language has been provided , make sure a translation # is available if settings . DEFAULT_LANGUAGE and not any ( self . ...
def libvlc_audio_set_format_callbacks ( mp , setup , cleanup ) : '''Set decoded audio format . This only works in combination with L { libvlc _ audio _ set _ callbacks } ( ) . @ param mp : the media player . @ param setup : callback to select the audio format ( cannot be NULL ) . @ param cleanup : callback ...
f = _Cfunctions . get ( 'libvlc_audio_set_format_callbacks' , None ) or _Cfunction ( 'libvlc_audio_set_format_callbacks' , ( ( 1 , ) , ( 1 , ) , ( 1 , ) , ) , None , None , MediaPlayer , AudioSetupCb , AudioCleanupCb ) return f ( mp , setup , cleanup )
def halt ( self , subid , params = None ) : '''/ v1 / server / halt POST - account Halt a virtual machine . This is a hard power off ( basically , unplugging the machine ) . The data on the machine will not be modified , and you will still be billed for the machine . To completely delete a machine , see v...
params = update_params ( params , { 'SUBID' : subid } ) return self . request ( '/v1/server/halt' , params , 'POST' )
def _import_data ( self ) : """Import data from a stat file ."""
# set default state to ironpython for very old ironpython ( 2.7.0) iron_python = True try : iron_python = True if platform . python_implementation ( ) == 'IronPython' else False except ValueError as e : # older versions of IronPython fail to parse version correctly # failed to parse IronPython sys . version : ' 2.7...
def connect ( self , signal , slot , transform = None , condition = None ) : """Defines a connection between this objects signal and another objects slot signal : the signal this class will emit , to cause the slot method to be called receiver : the object containing the slot method to be called slot : the sl...
if not signal in self . signals : print ( "WARNING: {0} is trying to connect a slot to an undefined signal: {1}" . format ( self . __class__ . __name__ , str ( signal ) ) ) return if not hasattr ( self , 'connections' ) : self . connections = { } connection = self . connections . setdefault ( signal , { } )...
def get_min_vertex_distance ( coor , guess ) : """Can miss the minimum , but is enough for our purposes ."""
# Sort by x . ix = nm . argsort ( coor [ : , 0 ] ) scoor = coor [ ix ] mvd = 1e16 # Get mvd in chunks potentially smaller than guess . n_coor = coor . shape [ 0 ] print n_coor i0 = i1 = 0 x0 = scoor [ i0 , 0 ] while 1 : while ( ( scoor [ i1 , 0 ] - x0 ) < guess ) and ( i1 < ( n_coor - 1 ) ) : i1 += 1 # ...