signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def do_status_progress ( p , hide = False ) : """: type p ProgressBar : type hide bool"""
p . start ( 10 ) for i in range ( 1 , 60 ) : p . progress_inc ( new_status = "count %s" % i ) time . sleep ( 0.1 ) p . stop ( hide_progress = hide , new_status = "done" )
def restore_artifact ( src_path : str , artifact_hash : str , conf : Config ) : """Restore the artifact whose hash is ` artifact _ hash ` to ` src _ path ` . Return True if cached artifact is found , valid , and restored successfully . Otherwise return False ."""
cache_dir = conf . get_artifacts_cache_dir ( ) if not isdir ( cache_dir ) : return False cached_artifact_path = join ( cache_dir , artifact_hash ) if isfile ( cached_artifact_path ) or isdir ( cached_artifact_path ) : # verify cached item hash matches expected hash actual_hash = hash_tree ( cached_artifact_path...
def find_port ( addr , user ) : """Find local port in existing tunnels"""
import pwd home = pwd . getpwuid ( os . getuid ( ) ) . pw_dir for name in os . listdir ( '%s/.ssh/' % home ) : if name . startswith ( 'unixpipe_%s@%s_' % ( user , addr , ) ) : return int ( name . split ( '_' ) [ 2 ] )
def get_entry ( journal_location , date ) : """args date - date object returns entry text or None if entry doesn ' t exist"""
if not isinstance ( date , datetime . date ) : return None try : with open ( build_journal_path ( journal_location , date ) , "r" ) as entry_file : return entry_file . read ( ) except IOError : return None
def new_root ( self , vd , seqnum , log_block_size ) : # type : ( headervd . PrimaryOrSupplementaryVD , int , int ) - > None '''Create a new root Directory Record . Parameters : vd - The Volume Descriptor this record is part of . seqnum - The sequence number for this directory record . log _ block _ size - ...
if self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'Directory Record already initialized' ) self . _new ( vd , b'\x00' , None , seqnum , True , log_block_size , False )
def execute ( self , jvm_options = None , args = None , executor = None , workunit_factory = None , workunit_name = None , workunit_labels = None ) : """Executes the ivy commandline client with the given args . Raises Ivy . Error if the command fails for any reason . : param executor : Java executor to run ivy ...
# NB ( gmalmquist ) : It should be OK that we can ' t declare a subsystem _ dependency in this file # ( because it ' s just a plain old object ) , because Ivy is only constructed by Bootstrapper , which # makes an explicit call to IvySubsystem . global _ instance ( ) in its constructor , which in turn has # a declared ...
def _ProcessPathSpec ( self , extraction_worker , parser_mediator , path_spec ) : """Processes a path specification . Args : extraction _ worker ( worker . ExtractionWorker ) : extraction worker . parser _ mediator ( ParserMediator ) : parser mediator . path _ spec ( dfvfs . PathSpec ) : path specification ...
self . _current_display_name = parser_mediator . GetDisplayNameForPathSpec ( path_spec ) try : extraction_worker . ProcessPathSpec ( parser_mediator , path_spec ) except KeyboardInterrupt : self . _abort = True self . _processing_status . aborted = True if self . _status_update_callback : self ....
def validate ( metadata ) : """Validator of the metadata composition : param metadata : conforming to the Metadata accepted by Ocean Protocol , dict : return : bool"""
# validate required sections and their sub items for section_key in Metadata . REQUIRED_SECTIONS : if section_key not in metadata or not metadata [ section_key ] or not isinstance ( metadata [ section_key ] , dict ) : return False section = Metadata . MAIN_SECTIONS [ section_key ] section_metadata =...
def DOMDebugger_setDOMBreakpoint ( self , nodeId , type ) : """Function path : DOMDebugger . setDOMBreakpoint Domain : DOMDebugger Method name : setDOMBreakpoint Parameters : Required arguments : ' nodeId ' ( type : DOM . NodeId ) - > Identifier of the node to set breakpoint on . ' type ' ( type : DOMBr...
subdom_funcs = self . synchronous_command ( 'DOMDebugger.setDOMBreakpoint' , nodeId = nodeId , type = type ) return subdom_funcs
def _getSuitableClasses ( self , data ) : """Returns the class which holds the suitable classes for the loaded file"""
classes = None if data [ EI . CLASS ] == ELFCLASS . BITS_32 : if data [ EI . DATA ] == ELFDATA . LSB : classes = LSB_32 elif data [ EI . DATA ] == ELFDATA . MSB : classes = MSB_32 elif data [ EI . CLASS ] == ELFCLASS . BITS_64 : if data [ EI . DATA ] == ELFDATA . LSB : classes = LSB_...
def plot_meshes ( self , ax = None , marker = '+' , color = 'blue' , outlines = False , ** kwargs ) : """Plot the low - resolution mesh boxes on a matplotlib Axes instance . Parameters ax : ` matplotlib . axes . Axes ` instance , optional If ` None ` , then the current ` ` Axes ` ` instance is used . mark...
import matplotlib . pyplot as plt kwargs [ 'color' ] = color if ax is None : ax = plt . gca ( ) ax . scatter ( self . x , self . y , marker = marker , color = color ) if outlines : from . . aperture import RectangularAperture xy = np . column_stack ( [ self . x , self . y ] ) apers = RectangularAperture...
def _adaptSynapses ( self , inputVector , activeColumns , overlaps ) : """The primary method in charge of learning . Adapts the permanence values of the synapses based on the input vector , and the chosen columns after inhibition round . Permanence values are increased for synapses connected to input bits tha...
inputIndices = np . where ( inputVector > 0 ) [ 0 ] permChanges = np . zeros ( self . _numInputs , dtype = realDType ) permChanges . fill ( - 1 * self . _synPermInactiveDec ) permChanges [ inputIndices ] = self . _synPermActiveInc for columnIndex in activeColumns : perm = self . _permanences [ columnIndex ] mas...
def refactor_rename_at_point ( self , offset , new_name , in_hierarchy , docs ) : """Rename the symbol at point ."""
try : refactor = Rename ( self . project , self . resource , offset ) except RefactoringError as e : raise Fault ( str ( e ) , code = 400 ) return self . _get_changes ( refactor , new_name , in_hierarchy = in_hierarchy , docs = docs )
def post_refund_request ( self , id , ** data ) : """POST / refund _ requests / : id / Update a : format : ` refund - request ` for a specific order . Each element in items is a : format : ` refund - item ` error NOT _ AUTHORIZED Only the order ' s buyer can create a refund request error FIELD _ UNKNOWN T...
return self . post ( "/refund_requests/{0}/" . format ( id ) , data = data )
def as_wfn ( self ) : """Returns the CPE Name as Well - Formed Name string of version 2.3. If edition component is not packed , only shows the first seven components , otherwise shows all . : return : CPE Name as WFN string : rtype : string : exception : TypeError - incompatible version"""
if self . _str . find ( CPEComponent2_3_URI . SEPARATOR_PACKED_EDITION ) == - 1 : # Edition unpacked , only show the first seven components wfn = [ ] wfn . append ( CPE2_3_WFN . CPE_PREFIX ) for ck in CPEComponent . CPE_COMP_KEYS : lc = self . _get_attribute_components ( ck ) if len ( lc ) >...
def update ( self , ** kwargs ) : """Update all resources in this collection ."""
self . inflate ( ) for model in self . _models : model . update ( ** kwargs ) return self
def _toconf ( self , conf ) : """Convert input parameter to a Configuration . : param conf : configuration to convert to a Configuration object . : type conf : Configuration , Category or Parameter . : rtype : Configuration"""
result = conf if result is None : result = Configuration ( ) elif isinstance ( result , Category ) : result = configuration ( result ) elif isinstance ( result , Parameter ) : result = configuration ( category ( '' , result ) ) elif isinstance ( result , list ) : result = configuration ( category ( '' ,...
def update ( self , data ) : """Hash data ."""
view = memoryview ( data ) bs = self . block_size if self . _buf : need = bs - len ( self . _buf ) if len ( view ) < need : self . _buf += view . tobytes ( ) return self . _add_block ( self . _buf + view [ : need ] . tobytes ( ) ) view = view [ need : ] while len ( view ) >= bs : sel...
def _construct_url ( self , base_api , params ) : """Construct geocoding request url . Overridden . : param str base _ api : Geocoding function base address - self . api or self . reverse _ api . : param dict params : Geocoding params . : return : string URL ."""
params [ 'key' ] = self . api_key return super ( OpenMapQuest , self ) . _construct_url ( base_api , params )
def justify ( texts , max_len , mode = 'right' ) : """Perform ljust , center , rjust against string or list - like"""
if mode == 'left' : return [ x . ljust ( max_len ) for x in texts ] elif mode == 'center' : return [ x . center ( max_len ) for x in texts ] else : return [ x . rjust ( max_len ) for x in texts ]
def _grouper ( iterable , n , fillvalue = 0 ) : """Collect data into fixed - length chunks or blocks . Args : n ( int ) : The size of the chunk . fillvalue ( int ) : The fill value . Returns : iterator : An iterator over the chunks ."""
args = [ iter ( iterable ) ] * n return zip_longest ( fillvalue = fillvalue , * args )
def image ( self , captcha_str ) : """Generate a greyscale captcha image representing number string Parameters captcha _ str : str string a characters for captcha image Returns numpy . ndarray Generated greyscale image in np . ndarray float type with values normalized to [ 0 , 1]"""
img = self . captcha . generate ( captcha_str ) img = np . fromstring ( img . getvalue ( ) , dtype = 'uint8' ) img = cv2 . imdecode ( img , cv2 . IMREAD_GRAYSCALE ) img = cv2 . resize ( img , ( self . h , self . w ) ) img = img . transpose ( 1 , 0 ) img = np . multiply ( img , 1 / 255.0 ) return img
def fetch_withdrawals_since ( self , since : int ) -> List [ Withdrawal ] : """Fetch all withdrawals since the given timestamp ."""
return self . _transactions_since ( self . _withdrawals_since , 'withdrawals' , since )
def _run_pre_command ( self , pre_cmd ) : '''Run a pre command to get external args for a command'''
logger . debug ( 'Executing pre-command: %s' , pre_cmd ) try : pre_proc = Popen ( pre_cmd , stdout = PIPE , stderr = STDOUT , shell = True ) except OSError as err : if err . errno == errno . ENOENT : logger . debug ( 'Command %s not found' , pre_cmd ) return stdout , stderr = pre_proc . communicate ...
def getCatIds ( self , catNms = [ ] , supNms = [ ] , catIds = [ ] ) : """filtering parameters . default skips that filter . : param catNms ( str array ) : get cats for given cat names : param supNms ( str array ) : get cats for given supercategory names : param catIds ( int array ) : get cats for given cat id...
catNms = catNms if type ( catNms ) == list else [ catNms ] supNms = supNms if type ( supNms ) == list else [ supNms ] catIds = catIds if type ( catIds ) == list else [ catIds ] if len ( catNms ) == len ( supNms ) == len ( catIds ) == 0 : cats = self . dataset [ 'categories' ] else : cats = self . dataset [ 'cat...
def mavloss ( logfile ) : '''work out signal loss times for a log file'''
print ( "Processing log %s" % filename ) mlog = mavutil . mavlink_connection ( filename , planner_format = args . planner , notimestamps = args . notimestamps , dialect = args . dialect , robust_parsing = args . robust ) # Track the reasons for MAVLink parsing errors and print them all out at the end . reason_ids = set...
def keyevent2tuple ( event ) : """Convert QKeyEvent instance into a tuple"""
return ( event . type ( ) , event . key ( ) , event . modifiers ( ) , event . text ( ) , event . isAutoRepeat ( ) , event . count ( ) )
def inspect_func ( self , namesrc ) : """Take a function ' s ( name , sourcecode ) and return a triple of ( name , sourcecode , signature )"""
( name , src ) = namesrc glbls = { } lcls = { } exec ( src , glbls , lcls ) assert name in lcls func = lcls [ name ] return name , src , signature ( func )
def emit ( self , record ) : """Override emit ( ) method in handler parent for sending log to RESTful API"""
pid = os . getpid ( ) if pid != self . pid : self . pid = pid self . logs = [ ] self . timer = self . _flushAndRepeatTimer ( ) atexit . register ( self . _stopFlushTimer ) # avoid infinite recursion if record . name . startswith ( 'requests' ) : return self . logs . append ( self . _prepPayload ( re...
def cmd_block ( self , is_retry = False ) : '''Prepare the pre - check command to send to the subsystem 1 . execute SHIM + command 2 . check if SHIM returns a master request or if it completed 3 . handle any master request 4 . re - execute SHIM + command 5 . split SHIM results from command results 6 . r...
self . argv = _convert_args ( self . argv ) log . debug ( 'Performing shimmed, blocking command as follows:\n%s' , ' ' . join ( [ six . text_type ( arg ) for arg in self . argv ] ) ) cmd_str = self . _cmd_str ( ) stdout , stderr , retcode = self . shim_cmd ( cmd_str ) log . trace ( 'STDOUT %s\n%s' , self . target [ 'ho...
def delete ( self ) : """Delete this file"""
if not self . remote : if not os . path . exists ( self . projectpath + self . basedir + '/' + self . filename ) : return False else : os . unlink ( self . projectpath + self . basedir + '/' + self . filename ) # Remove metadata metafile = self . projectpath + self . basedir + '/' + self...
def executemany ( self , query , args ) : """Run several data against one query PyMySQL can execute bulkinsert for query like ' INSERT . . . VALUES ( % s ) ' . In other form of queries , just run : meth : ` execute ` many times ."""
if not args : return m = RE_INSERT_VALUES . match ( query ) if m : q_prefix = m . group ( 1 ) q_values = m . group ( 2 ) . rstrip ( ) q_postfix = m . group ( 3 ) or '' assert q_values [ 0 ] == '(' and q_values [ - 1 ] == ')' yield self . _do_execute_many ( q_prefix , q_values , q_postfix , args ...
def to_dict ( obj , ** kwargs ) : """Convert an object into dictionary . Uses singledispatch to allow for clean extensions for custom class types . Reference : https : / / pypi . python . org / pypi / singledispatch : param obj : object instance : param kwargs : keyword arguments such as suppress _ private ...
# if is _ related , then iterate attrs . if is_model ( obj . __class__ ) : return related_obj_to_dict ( obj , ** kwargs ) # else , return obj directly . register a custom to _ dict if you need to ! # reference : https : / / pypi . python . org / pypi / singledispatch else : return obj
def additionalAssignment ( MobileAllocation_presence = 0 , StartingTime_presence = 0 ) : """ADDITIONAL ASSIGNMENT Section 9.1.1"""
# Mandatory a = TpPd ( pd = 0x6 ) b = MessageType ( mesType = 0x3B ) # 00111011 c = ChannelDescription ( ) packet = a / b / c # Not Mandatory if MobileAllocation_presence is 1 : d = MobileAllocationHdr ( ieiMA = 0x72 , eightBitMA = 0x0 ) packet = packet / d if StartingTime_presence is 1 : e = StartingTimeHd...
def recursive_walk ( rootdir ) : """Yields : str : All files in rootdir , recursively ."""
for r , dirs , files in os . walk ( rootdir ) : for f in files : yield os . path . join ( r , f )
def remove ( self , source_id , resource_ids ) : """Remove one or more resources from a Managed Source Uses API documented at http : / / dev . datasift . com / docs / api / rest - api / endpoints / sourceresourceremove : param source _ id : target Source ID : type source _ id : str : param resources : An ar...
params = { 'id' : source_id , 'resource_ids' : resource_ids } return self . request . post ( 'remove' , params )
def modify_log_flags ( self , settings ) : """Modifies the debug or release logger flags . in settings of type str The flags settings string . See iprt / log . h for details . To target the release logger , prefix the string with " release : " ."""
if not isinstance ( settings , basestring ) : raise TypeError ( "settings can only be an instance of type basestring" ) self . _call ( "modifyLogFlags" , in_p = [ settings ] )
def parse_tokens ( self , tokens , debug = False ) : """Parse a series of tokens and return the syntax tree ."""
# XXX Move the prefix computation into a wrapper around tokenize . p = parse . Parser ( self . grammar , self . convert ) p . setup ( ) lineno = 1 column = 0 type = value = start = end = line_text = None prefix = u"" for quintuple in tokens : type , value , start , end , line_text = quintuple if start != ( line...
def plot ( self , data , height = 1000 , render_large_data = False ) : """Plots a detail view of data . Args : data : a Pandas dataframe . height : the height of the output ."""
import IPython if not isinstance ( data , pd . DataFrame ) : raise ValueError ( 'Expect a DataFrame.' ) if ( len ( data ) > 10000 and not render_large_data ) : raise ValueError ( 'Facets dive may not work well with more than 10000 rows. ' + 'Reduce data or set "render_large_data" to True.' ) jsonstr = data . to...
def network_security_group_create_or_update ( name , resource_group , ** kwargs ) : # pylint : disable = invalid - name '''. . versionadded : : 2019.2.0 Create or update a network security group . : param name : The name of the network security group to create . : param resource _ group : The resource group n...
if 'location' not in kwargs : rg_props = __salt__ [ 'azurearm_resource.resource_group_get' ] ( resource_group , ** kwargs ) if 'error' in rg_props : log . error ( 'Unable to determine location from resource group specified.' ) return False kwargs [ 'location' ] = rg_props [ 'location' ] netc...
def busy_connections ( self ) : """Return a list of active / busy connections : rtype : list"""
return [ c for c in self . connections . values ( ) if c . busy and not c . closed ]
def dollar_signs ( value , failure_string = 'N/A' ) : """Converts an integer into the corresponding number of dollar sign symbols . If the submitted value isn ' t a string , returns the ` failure _ string ` keyword argument . Meant to emulate the illustration of price range on Yelp ."""
try : count = int ( value ) except ValueError : return failure_string string = '' for i in range ( 0 , count ) : string += '$' return string
def make_wcs ( shape , galactic = False ) : """Create a simple celestial WCS object in either the ICRS or Galactic coordinate frame . Parameters shape : 2 - tuple of int The shape of the 2D array to be used with the output ` ~ astropy . wcs . WCS ` object . galactic : bool , optional If ` True ` , the...
wcs = WCS ( naxis = 2 ) rho = np . pi / 3. scale = 0.1 / 3600. if astropy_version < '3.1' : wcs . _naxis1 = shape [ 1 ] # nx wcs . _naxis2 = shape [ 0 ] # ny else : wcs . pixel_shape = shape wcs . wcs . crpix = [ shape [ 1 ] / 2 , shape [ 0 ] / 2 ] # 1 - indexed ( x , y ) wcs . wcs . crval = [ 197.8...
def get_metric_by_name ( self , metric_name , ** kwargs ) : """get a metric by name Args : metric _ name ( string ) : name of metric Returns : dictionary of response"""
return self . _get_object_by_name ( self . _METRIC_ENDPOINT_SUFFIX , metric_name , ** kwargs )
def _BuildScanTreeNode ( self , path_filter_table , ignore_list ) : """Builds a scan tree node . Args : path _ filter _ table : a path filter table object ( instance of _ PathFilterTable ) . ignore _ list : a list of path segment indexes to ignore , where 0 is the index of the first path segment relative ...
# Make a copy of the lists because the function is going to alter them # and the changes must remain in scope of the function . paths_list = list ( path_filter_table . paths ) ignore_list = list ( ignore_list ) similarity_weights = _PathSegmentWeights ( ) occurrence_weights = _PathSegmentWeights ( ) value_weights = _Pa...
def __get_grants ( self , target_file , all_grant_data ) : """Return grant permission , grant owner , grant owner email and grant id as a list . It needs you to set k . key to a key on amazon ( file path ) before running this . note that Amazon returns a list of grants for each file . options : - private : ...
self . k . key = target_file the_grants = self . k . get_acl ( ) . acl . grants grant_list = [ ] for grant in the_grants : if all_grant_data : grant_list . append ( { "permission" : grant . permission , "name" : grant . display_name , "email" : grant . email_address , "id" : grant . id } ) else : ...
def translate_src ( src , cortex ) : """Convert source nodes to new surface ( without medial wall ) ."""
src_new = np . array ( np . where ( np . in1d ( cortex , src ) ) [ 0 ] , dtype = np . int32 ) return src_new
def __preprocess_arguments ( root ) : """Preprocesses occurrences of Argument within the root . Argument XML values reference other values within the document by name . The referenced value does not contain a switch . This function will add the switch associated with the argument ."""
# Set the flags to require a value flags = ',' . join ( vsflags ( VSFlags . UserValueRequired ) ) # Search through the arguments arguments = root . getElementsByTagName ( 'Argument' ) for argument in arguments : reference = __get_attribute ( argument , 'Property' ) found = None # Look for the argument withi...
def show_stack ( name = None , profile = None ) : '''Return details about a specific stack ( heat stack - show ) name Name of the stack profile Profile to use CLI Example : . . code - block : : bash salt ' * ' heat . show _ stack name = mystack profile = openstack1'''
h_client = _auth ( profile ) if not name : return { 'result' : False , 'comment' : 'Parameter name missing or None' } try : ret = { } stack = h_client . stacks . get ( name ) links = { } for link in stack . links : links [ link [ 'rel' ] ] = link [ 'href' ] ret [ stack . stack_name ] = {...
def goto ( self , iroute : "InstanceRoute" ) -> "InstanceNode" : """Move the focus to an instance inside the receiver ' s value . Args : iroute : Instance route ( relative to the receiver ) . Returns : The instance node corresponding to the target instance . Raises : InstanceValueError : If ` iroute ` i...
inst = self for sel in iroute : inst = sel . goto_step ( inst ) return inst
def to_enum ( gtype , value ) : """Turn a string into an enum value ready to be passed into libvips ."""
if isinstance ( value , basestring if _is_PY2 else str ) : enum_value = vips_lib . vips_enum_from_nick ( b'pyvips' , gtype , _to_bytes ( value ) ) if enum_value < 0 : raise Error ( 'no value {0} in gtype {1} ({2})' . format ( value , type_name ( gtype ) , gtype ) ) else : enum_value = value return e...
def header ( self ) : """A list of text representing the full header ( the first 8 lines ) of the EPW ."""
self . _load_header_check ( ) loc = self . location loc_str = 'LOCATION,{},{},{},{},{},{},{},{},{}\n' . format ( loc . city , loc . state , loc . country , loc . source , loc . station_id , loc . latitude , loc . longitude , loc . time_zone , loc . elevation ) winter_found = bool ( self . _heating_dict ) summer_found =...
def register ( self , server_info ) : """Register attributes that can be computed with the server info ."""
# Path relative to the server directory self . path = os . path . relpath ( self . filename , start = server_info [ 'notebook_dir' ] ) # Replace backslashes on Windows if os . name == 'nt' : self . path = self . path . replace ( '\\' , '/' ) # Server url to send requests to self . server_url = server_info [ 'url' ]...
def begin ( self ) : """Start a new transaction ."""
if self . in_transaction : # we ' re already in a transaction . . . if self . _auto_transaction : self . _auto_transaction = False return self . commit ( ) self . in_transaction = True for collection , store in self . stores . items ( ) : store . begin ( ) indexes = self . indexes [ coll...
def is_able_to_convert_detailed ( self , strict : bool , from_type : Type [ Any ] , to_type : Type [ Any ] ) : """Overrides the parent method to delegate left check to the first ( left ) converter of the chain and right check to the last ( right ) converter of the chain . This includes custom checking if they hav...
# check if first and last converters are happy if not self . _converters_list [ 0 ] . is_able_to_convert ( strict , from_type = from_type , to_type = JOKER ) : return False , None , None elif not self . _converters_list [ - 1 ] . is_able_to_convert ( strict , from_type = JOKER , to_type = to_type ) : return Fal...
def deploy ( www_dir , bucket_name ) : """Deploy to the configured S3 bucket ."""
# Set up the connection to an S3 bucket . conn = boto . connect_s3 ( ) bucket = conn . get_bucket ( bucket_name ) # Deploy each changed file in www _ dir os . chdir ( www_dir ) for root , dirs , files in os . walk ( '.' ) : for f in files : # Use full relative path . Normalize to remove dot . file_path = os...
def is_dirty ( using = None ) : """Returns True if the current transaction requires a commit for changes to happen ."""
if using is None : dirty = False for using in tldap . backend . connections : connection = tldap . backend . connections [ using ] if connection . is_dirty ( ) : dirty = True return dirty connection = tldap . backend . connections [ using ] return connection . is_dirty ( )
def fmt_part ( part , node_labels = None ) : """Format a | Part | . The returned string looks like : : 0,1"""
def nodes ( x ) : # pylint : disable = missing - docstring return ',' . join ( labels ( x , node_labels ) ) if x else EMPTY_SET numer = nodes ( part . mechanism ) denom = nodes ( part . purview ) width = max ( 3 , len ( numer ) , len ( denom ) ) divider = HORIZONTAL_BAR * width return ( '{numer:^{width}}\n' '{divid...
def iexists ( irods_path ) : """Returns True of iRODS path exists , otherwise False"""
try : subprocess . check_output ( 'ils {}' . format ( irods_path ) , shell = True , stderr = subprocess . PIPE , ) return True except subprocess . CalledProcessError : return False
def get_normalised_generator ( frequencies , rate_matrix = None ) : """Calculates the normalised generator from the rate matrix and character state frequencies . : param frequencies : character state frequencies . : type frequencies : numpy . array : param rate _ matrix : ( optional ) rate matrix ( by default...
if rate_matrix is None : n = len ( frequencies ) rate_matrix = np . ones ( shape = ( n , n ) , dtype = np . float64 ) - np . eye ( n ) generator = rate_matrix * frequencies generator -= np . diag ( generator . sum ( axis = 1 ) ) mu = - generator . diagonal ( ) . dot ( frequencies ) generator /= mu return genera...
def _list_keys ( user = None , gnupghome = None , secret = False ) : '''Helper function for Listing keys'''
gpg = _create_gpg ( user , gnupghome ) _keys = gpg . list_keys ( secret ) return _keys
def setpathcost ( self , port , cost ) : """Set port path cost value for STP protocol ."""
_runshell ( [ brctlexe , 'setpathcost' , self . name , port , str ( cost ) ] , "Could not set path cost in port %s in %s." % ( port , self . name ) )
def set_representative_sequence ( self , force_rerun = False ) : """Automatically consolidate loaded sequences ( manual , UniProt , or KEGG ) and set a single representative sequence . Manually set representative sequences override all existing mappings . UniProt mappings override KEGG mappings except when KE...
if len ( self . sequences ) == 0 : log . error ( '{}: no sequences mapped' . format ( self . id ) ) return self . representative_sequence kegg_mappings = self . filter_sequences ( KEGGProp ) if len ( kegg_mappings ) > 0 : kegg_to_use = kegg_mappings [ 0 ] if len ( kegg_mappings ) > 1 : log . war...
def _justDisplay ( self , tool ) : """Displays the given tool . Does not register it in the tools list ."""
self . header . title . set_text ( tool . name ) body , _options = self . widget . contents [ "body" ] overlay = urwid . Overlay ( tool . widget , body , * tool . position ) self . _surface = urwid . AttrMap ( overlay , "foreground" ) self . widget . contents [ "body" ] = self . _surface , None
def cooling_degree_days ( T , T_base = 283.15 , truncate = True ) : r'''Calculates the cooling degree days for a period of time . . . math : : \ text { cooling degree days } = max ( T _ { base } - T , 0) Parameters T : float Measured temperature ; sometimes an average over a length of time is used , oth...
dd = T_base - T if truncate and dd < 0.0 : dd = 0.0 return dd
def _get_fault_type_dummy_variables ( self , rup ) : """The original classification considers four style of faulting categories ( normal , strike - slip , reverse - oblique and reverse ) ."""
Fn , Fr = 0 , 0 if rup . rake >= - 112.5 and rup . rake <= - 67.5 : # normal Fn = 1 elif rup . rake >= 22.5 and rup . rake <= 157.5 : # Joins both the reverse and reverse - oblique categories Fr = 1 return Fn , Fr
def validateDayOfWeek ( value , blank = False , strip = None , allowlistRegexes = None , blocklistRegexes = None , dayNames = ENGLISH_DAYS_OF_WEEK , excMsg = None ) : """Raises ValidationException if value is not a day of the week , such as ' Mon ' or ' Friday ' . Returns the titlecased day of the week . * valu...
# TODO - reuse validateChoice for this function # returns full day of the week str , e . g . ' Sunday ' # Reuses validateMonth . try : return validateMonth ( value , blank = blank , strip = strip , allowlistRegexes = allowlistRegexes , blocklistRegexes = blocklistRegexes , monthNames = ENGLISH_DAYS_OF_WEEK ) except...
def dynamic_content_item_create ( self , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / dynamic _ content # create - item"
api_path = "/api/v2/dynamic_content/items.json" return self . call ( api_path , method = "POST" , data = data , ** kwargs )
def cache_param ( self , value ) : '''Returns a troposphere Ref to a value cached as a parameter .'''
if value not in self . cf_parameters : keyname = chr ( ord ( 'A' ) + len ( self . cf_parameters ) ) param = self . cf_template . add_parameter ( troposphere . Parameter ( keyname , Type = "String" , Default = value , tags = self . tags ) ) self . cf_parameters [ value ] = param return troposphere . Ref ( se...
def updateData ( self , data ) : """Updates the data used by the renderer ."""
# pylab . ion ( ) fig = pylab . figure ( 1 ) n_agent = len ( data ) idx = 1 for i , adata in enumerate ( data ) : saxis = fig . add_subplot ( 3 , n_agent , i + 1 ) saxis . plot ( adata [ 0 ] ) idx += 1 aaxis = fig . add_subplot ( 3 , n_agent , i + 1 + n_agent ) aaxis . plot ( adata [ 1 ] ) idx +...
def fit_overlays ( self , text , run_matchers = None , ** kw ) : """First all matchers will run and then I will try to combine them . Use run _ matchers to force running ( True ) or not running ( False ) the matchers . See ListMatcher for arguments ."""
self . _maybe_run_matchers ( text , run_matchers ) for i in self . _list_match . fit_overlay ( text , ** kw ) : yield i
def get ( ctx , dataset , rm , keep_compressed , dont_process , dont_download , keep_raw , kwargs ) : "performs the operations download , extract , rm _ compressed , processes and rm _ raw , in sequence . KWARGS must be in the form : key = value , and are fowarded to all opeartions ."
kwargs = parse_kwargs ( kwargs ) process = not dont_process rm_raw = not keep_raw rm_compressed = not keep_compressed download = not dont_download data ( dataset , ** ctx . obj ) . get ( download = download , rm = rm , rm_compressed = rm_compressed , process = process , rm_raw = rm_raw , ** kwargs )
def used_by ( self , bundle ) : """Indicates that this reference is being used by the given bundle . This method should only be used by the framework . : param bundle : A bundle using this reference"""
if bundle is None or bundle is self . __bundle : # Ignore return with self . __usage_lock : self . __using_bundles . setdefault ( bundle , _UsageCounter ( ) ) . inc ( )
def _GetLink ( self ) : """Retrieves the link . Returns : str : path of the linked file ."""
if self . _link is None : self . _link = '' if not self . _IsLink ( self . _fsntfs_file_entry . file_attribute_flags ) : return self . _link link = self . _fsntfs_file_entry . reparse_point_print_name if link : # Strip off the drive letter , we assume the link is within # the same volume . ...
def create_object ( self , name , experiment_id , model_id , argument_defs , arguments = None , properties = None ) : """Create a model run object with the given list of arguments . The initial state of the object is RUNNING . Raises ValueError if given arguments are invalid . Parameters name : string Use...
# Create a new object identifier . identifier = str ( uuid . uuid4 ( ) ) . replace ( '-' , '' ) # Directory for successful model run resource files . Directories are # simply named by object identifier directory = os . path . join ( self . directory , identifier ) # Create the directory if it doesn ' t exists if not os...
def _ProcessDirectory ( self , mediator , file_entry ) : """Processes a directory file entry . Args : mediator ( ParserMediator ) : mediates the interactions between parsers and other components , such as storage and abort signals . file _ entry ( dfvfs . FileEntry ) : file entry of the directory ."""
self . processing_status = definitions . STATUS_INDICATOR_COLLECTING if self . _processing_profiler : self . _processing_profiler . StartTiming ( 'collecting' ) for sub_file_entry in file_entry . sub_file_entries : if self . _abort : break try : if not sub_file_entry . IsAllocated ( ) : ...
def RecordEvent ( self , metric_name , value , fields = None ) : """See base class ."""
self . _event_metrics [ metric_name ] . Record ( value , fields )
def T_sigma ( self , sigma ) : """Given a policy ` sigma ` , return the T _ sigma operator . Parameters sigma : array _ like ( int , ndim = 1) Policy vector , of length n . Returns callable The T _ sigma operator ."""
R_sigma , Q_sigma = self . RQ_sigma ( sigma ) return lambda v : R_sigma + self . beta * Q_sigma . dot ( v )
def parse_reports ( self ) : """Find RSeQC bam _ stat reports and parse their data"""
# Set up vars self . bam_stat_data = dict ( ) regexes = { 'total_records' : r"Total records:\s*(\d+)" , 'qc_failed' : r"QC failed:\s*(\d+)" , 'optical_pcr_duplicate' : r"Optical/PCR duplicate:\s*(\d+)" , 'non_primary_hits' : r"Non primary hits\s*(\d+)" , 'unmapped_reads' : r"Unmapped reads:\s*(\d+)" , 'mapq_lt_mapq_cut...
def update_dvs ( dvs_dict , dvs , service_instance = None ) : '''Updates a distributed virtual switch ( DVS ) . Note : Updating the product info , capability , uplinks of a DVS is not supported so the corresponding entries in ` ` dvs _ dict ` ` will be ignored . dvs _ dict Dictionary with the values the D...
# Remove ignored properties log . trace ( 'Updating dvs \'%s\' with dict = %s' , dvs , dvs_dict ) for prop in [ 'product_info' , 'capability' , 'uplink_names' , 'name' ] : if prop in dvs_dict : del dvs_dict [ prop ] proxy_type = get_proxy_type ( ) if proxy_type == 'esxdatacenter' : datacenter = __salt__...
def taskDefined ( self , * args , ** kwargs ) : """Task Defined Messages When a task is created or just defined a message is posted to this exchange . This message exchange is mainly useful when tasks are scheduled by a scheduler that uses ` defineTask ` as this does not make the task ` pending ` . Thus ,...
ref = { 'exchange' : 'task-defined' , 'name' : 'taskDefined' , 'routingKey' : [ { 'constant' : 'primary' , 'multipleWords' : False , 'name' : 'routingKeyKind' , } , { 'multipleWords' : False , 'name' : 'taskId' , } , { 'multipleWords' : False , 'name' : 'runId' , } , { 'multipleWords' : False , 'name' : 'workerGroup' ,...
def folderitem ( self , obj , item , index ) : """Service triggered each time an item is iterated in folderitems . The use of this service prevents the extra - loops in child objects . : obj : the instance of the class to be foldered : item : dict containing the properties of the object to be used by the te...
cat = obj . getCategoryTitle ( ) cat_order = self . an_cats_order . get ( cat ) if self . do_cats : # category groups entries item [ "category" ] = cat if ( cat , cat_order ) not in self . categories : self . categories . append ( ( cat , cat_order ) ) # Category category = obj . getCategory ( ) if cate...
def angular_distribution ( labels , resolution = 100 , weights = None ) : '''For each object in labels , compute the angular distribution around the centers of mass . Returns an i x j matrix , where i is the number of objects in the label matrix , and j is the resolution of the distribution ( default 100 ) , ...
if weights is None : weights = np . ones ( labels . shape ) maxlabel = labels . max ( ) ci , cj = centers_of_labels ( labels ) j , i = np . meshgrid ( np . arange ( labels . shape [ 0 ] ) , np . arange ( labels . shape [ 1 ] ) ) # compute deltas from pixels to object centroids , and mask to labels di = i [ labels >...
def sg_pool ( tensor , opt ) : r"""Performs the 2 - D pooling on the ` tensor ` . Mostly used with sg _ conv ( ) . Args : tensor : A 4 - D ` Tensor ` ( automatically given by chain ) . opt : size : A tuple or list of integers of length 2 representing ` [ kernel height , kernel width ] ` . Can be an int ...
# default stride and pad opt += tf . sg_opt ( stride = ( 1 , 2 , 2 , 1 ) , pad = 'VALID' ) # shape stride opt . stride = opt . stride if isinstance ( opt . stride , ( list , tuple ) ) else [ 1 , opt . stride , opt . stride , 1 ] opt . stride = [ 1 , opt . stride [ 0 ] , opt . stride [ 1 ] , 1 ] if len ( opt . stride ) ...
def update_actions ( self ) : """Updates the list of actions ."""
self . clear ( ) self . recent_files_actions [ : ] = [ ] for file in self . manager . get_recent_files ( ) : action = QtWidgets . QAction ( self ) action . setText ( os . path . split ( file ) [ 1 ] ) action . setToolTip ( file ) action . setStatusTip ( file ) action . setData ( file ) action . ...
async def bluetooth ( dev : Device , target , value ) : """Get or set bluetooth settings ."""
if target and value : await dev . set_bluetooth_settings ( target , value ) print_settings ( await dev . get_bluetooth_settings ( ) )
def set_config ( name , xpath = None , value = None , commit = False ) : '''Sets a Palo Alto XPATH to a specific value . This will always overwrite the existing value , even if it is not changed . You can add or create a new object at a specified location in the configuration hierarchy . Use the xpath parameter...
ret = _default_ret ( name ) result , msg = _set_config ( xpath , value ) ret . update ( { 'comment' : msg , 'result' : result } ) if not result : return ret if commit is True : ret . update ( { 'commit' : __salt__ [ 'panos.commit' ] ( ) , 'result' : True } ) return ret
def Format ( self , format_string , rdf ) : """Apply string formatting templates to rdf data . Uses some heuristics to coerce rdf values into a form compatible with string formatter rules . Repeated items are condensed into a single comma separated list . Unlike regular string . Formatter operations , we use ...
result = [ ] for literal_text , field_name , _ , _ in self . parse ( format_string ) : # output the literal text if literal_text : result . append ( literal_text ) # if there ' s a field , output it if field_name is not None : rslts = [ ] objs = self . expander ( rdf , field_name ) ...
def add ( self , other ) : """Add an Interval to the IntervalSet by taking the union of the given Interval object with the existing Interval objects in self . This has no effect if the Interval is already represented . : param other : an Interval to add to this IntervalSet ."""
if other . empty ( ) : return to_add = set ( ) for inter in self : if inter . overlaps ( other ) : # if it overlaps with this interval then the union will be a single interval to_add . add ( inter . union ( other ) ) if len ( to_add ) == 0 : # other must not overlap with any interval in self ( self coul...
def _dump ( self ) : # pragma : no cover """Dump contents for debugging / testing ."""
print ( 70 * "-" ) print ( "ID lookup table:" ) for name in self . __id_lut : id_ = self . __id_lut [ name ] print ( " %s -> %d" % ( name , id_ ) ) print ( 70 * "-" ) print ( "%-4s %-60s %s" % ( "ID" , "Filename" , "Refcount" ) ) print ( 70 * "-" ) for id_ in self . __entries : entry = self . __entries [ i...
def toposort ( data ) : """Dependencies are expressed as a dictionary whose keys are items and whose values are a set of dependent items . Output is a list of sets in topological order . The first set consists of items with no dependences , each subsequent set consists of items that depend upon items in the...
# Special case empty input . if len ( data ) == 0 : return # Copy the input so as to leave it unmodified . data = data . copy ( ) # Ignore self dependencies . for k , v in data . items ( ) : v . discard ( k ) # Find all items that don ' t depend on anything . extra_items_in_deps = reduce ( set . union , data . ...
def _responsify ( api_spec , error , status ) : """Take a bravado - core model representing an error , and return a Flask Response with the given error code and error instance as body"""
result_json = api_spec . model_to_json ( error ) r = jsonify ( result_json ) r . status_code = status return r
def resolve ( self , nobuiltin = False ) : """Resolve the node ' s type reference and return the referenced type node . Returns self if the type is defined locally , e . g . as a < complexType > subnode . Otherwise returns the referenced external node . @ param nobuiltin : Flag indicating whether resolving to...
cached = self . resolved_cache . get ( nobuiltin ) if cached is not None : return cached resolved = self . __resolve_type ( nobuiltin ) self . resolved_cache [ nobuiltin ] = resolved return resolved
def action_approve ( self ) : """Set a change request as approved ."""
for rec in self : if rec . state not in [ 'draft' , 'to approve' ] : raise UserError ( _ ( "Can't approve page in '%s' state." ) % rec . state ) if not rec . am_i_approver : raise UserError ( _ ( 'You are not authorized to do this.\r\n' 'Only approvers with these groups can approve this: ' ) % '...
def p_ioport_head ( self , p ) : 'ioport _ head : sigtypes portname'
p [ 0 ] = self . create_ioport ( p [ 1 ] , p [ 2 ] , lineno = p . lineno ( 2 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
async def tuple ( self , elem = None , elem_type = None , params = None ) : """Loads / dumps tuple : return :"""
if hasattr ( elem_type , 'blob_serialize' ) : container = elem_type ( ) if elem is None else elem return await container . blob_serialize ( self , elem = elem , elem_type = elem_type , params = params ) if self . writing : return await self . dump_tuple ( elem , elem_type , params ) else : return await ...
def images ( self ) : """: return : An iterator of all the images in the Renderer ."""
if len ( self . _plain_images ) <= 0 : self . _convert_images ( ) return iter ( self . _plain_images )
def mark_quality ( self , start_time , length , qual_name ) : """Mark signal quality , only add the new ones . Parameters start _ time : int start time in s of the epoch being scored . length : int duration in s of the epoch being scored . qual _ name : str one of the stages defined in global stages ....
y_pos = BARS [ 'quality' ] [ 'pos0' ] height = 10 # the - 1 is really important , otherwise we stay on the edge of the rect old_score = self . scene . itemAt ( start_time + length / 2 , y_pos + height - 1 , self . transform ( ) ) # check we are not removing the black border if old_score is not None and old_score . pen ...
def get_hidden_fields_errors ( self , form ) : '''Returns a dict to add in response when something is wrong with hidden fields'''
if not self . include_hidden_fields or form . is_valid ( ) : return { } response = { self . hidden_field_error_key : { } } for field in form . hidden_fields ( ) : if field . errors : response [ self . hidden_field_error_key ] [ field . html_name ] = self . _get_field_error_dict ( field ) return response
def fileName ( self ) : """Returns the filename . : return < str >"""
if self . _filename : return self . _filename filename = nativestring ( super ( XSettings , self ) . fileName ( ) ) if self . _customFormat : filename , ext = os . path . splitext ( filename ) filename += '.' + self . _customFormat . extension ( ) return filename