signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def start ( self , local_port , remote_address , remote_port ) : """Start ssh tunnel type : local _ port : int param : local _ port : local tunnel endpoint ip binding type : remote _ address : str param : remote _ address : Remote tunnel endpoing ip binding type : remote _ port : int param : remote _ po...
self . local_port = local_port self . remote_address = remote_address self . remote_port = remote_port logger . debug ( ( "Starting ssh tunnel {0}:{1}:{2} for " "{3}@{4}" . format ( local_port , remote_address , remote_port , self . username , self . address ) ) ) self . forward = Forward ( local_port , remote_address ...
def get_gtf_db ( gtf , in_memory = False ) : """create a gffutils DB , in memory if we don ' t have write permissions"""
db_file = gtf + ".db" if file_exists ( db_file ) : return gffutils . FeatureDB ( db_file ) if not os . access ( os . path . dirname ( db_file ) , os . W_OK | os . X_OK ) : in_memory = True db_file = ":memory:" if in_memory else db_file if in_memory or not file_exists ( db_file ) : infer_extent = guess_infer...
def _get_redirect_url ( self , request ) : """Next gathered from session , then GET , then POST , then users absolute url ."""
if 'next' in request . session : next_url = request . session [ 'next' ] del request . session [ 'next' ] elif 'next' in request . GET : next_url = request . GET . get ( 'next' ) elif 'next' in request . POST : next_url = request . POST . get ( 'next' ) else : next_url = request . user . get_absolut...
def reverse ( self ) : """This is a delayed reversing function . All it really does is to invert the _ reversed property of this StridedInterval object . : return : None"""
if self . bits == 8 : # We cannot reverse a one - byte value return self si = self . copy ( ) si . _reversed = not si . _reversed return si
def lookup_rdap ( self , inc_raw = False , retry_count = 3 , depth = 0 , excluded_entities = None , bootstrap = False , rate_limit_timeout = 120 , asn_alts = None , extra_org_map = None , inc_nir = True , nir_field_list = None , asn_methods = None , get_asn_description = True ) : """The function for retrieving and ...
from . rdap import RDAP # Create the return dictionary . results = { 'nir' : None } asn_data = None response = None if not bootstrap : # Retrieve the ASN information . log . debug ( 'ASN lookup for {0}' . format ( self . address_str ) ) asn_data = self . ipasn . lookup ( inc_raw = inc_raw , retry_count = retry_...
def _next_shape_id ( self ) : """Return a unique shape id suitable for use with a new shape . The returned id is 1 greater than the maximum shape id used so far . In practice , the minimum id is 2 because the spTree element is always assigned id = " 1 " ."""
# - - - presence of cached - max - shape - id indicates turbo mode is on - - - if self . _cached_max_shape_id is not None : self . _cached_max_shape_id += 1 return self . _cached_max_shape_id return self . _spTree . max_shape_id + 1
def make_big_empty_files ( self ) : """Write out a empty file so the workers can seek to where they should write and write their data ."""
for file_url in self . file_urls : local_path = file_url . get_local_path ( self . dest_directory ) with open ( local_path , "wb" ) as outfile : if file_url . size > 0 : outfile . seek ( int ( file_url . size ) - 1 ) outfile . write ( b'\0' )
def load_object ( import_path ) : """Shamelessly stolen from https : / / github . com / ojii / django - load Loads an object from an ' import _ path ' , like in MIDDLEWARE _ CLASSES and the likes . Import paths should be : " mypackage . mymodule . MyObject " . It then imports the module up until the last do...
if '.' not in import_path : raise TypeError ( "'import_path' argument to 'load_object' must " "contain at least one dot." ) module_name , object_name = import_path . rsplit ( '.' , 1 ) module = import_module ( module_name ) return getattr ( module , object_name )
def hash_args ( * args , ** kwargs ) : """Define a unique string for any set of representable args ."""
arg_string = '_' . join ( [ str ( arg ) for arg in args ] ) kwarg_string = '_' . join ( [ str ( key ) + '=' + str ( value ) for key , value in iteritems ( kwargs ) ] ) combined = ':' . join ( [ arg_string , kwarg_string ] ) hasher = md5 ( ) hasher . update ( b ( combined ) ) return hasher . hexdigest ( )
def modify_target ( self , to_state , to_key ) : """Set both to _ state and to _ key at the same time to modify data flow target : param str to _ state : State id of the target state : param int to _ key : Data port id of the target port : raises exceptions . ValueError : If parameters have wrong types or the...
if not isinstance ( to_state , string_types ) : raise ValueError ( "Invalid data flow target port: from_state must be a string" ) if not isinstance ( to_key , int ) : raise ValueError ( "Invalid data flow target port: from_outcome must be of type int" ) old_to_state = self . to_state old_to_key = self . to_key ...
def create_like ( self , repository_id , pull_request_id , thread_id , comment_id , project = None ) : """CreateLike . [ Preview API ] Add a like on a comment . : param str repository _ id : The repository ID of the pull request ' s target branch . : param int pull _ request _ id : ID of the pull request . ...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_id is not None : route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' ) if pull_request_id is not None : route_values ...
def object_to_json ( obj , indent = 2 ) : """transform object to json"""
instance_json = json . dumps ( obj , indent = indent , ensure_ascii = False , cls = DjangoJSONEncoder ) return instance_json
def append_position_to_token_list ( token_list ) : """Converts a list of Token into a list of Token , asuming size = = 1"""
return [ PositionToken ( value . content , value . gd , index , index + 1 ) for ( index , value ) in enumerate ( token_list ) ]
def find_video_detail_by_id ( self , video_id , ext = None ) : """doc : http : / / cloud . youku . com / docs ? id = 46"""
url = 'https://api.youku.com/videos/show.json' params = { 'client_id' : self . client_id , 'video_id' : video_id } if ext : params [ 'ext' ] = ext r = requests . get ( url , params = params ) check_error ( r ) return r . json ( )
def _to_str ( uniq ) : """Serializes a MOC to the STRING format . HEALPix cells are separated by a comma . The HEALPix cell at order 0 and number 10 is encoded by the string : " 0/10 " , the first digit representing the depth and the second the HEALPix cell number for this depth . HEALPix cells next to each o...
def write_cells ( serial , a , b , sep = '' ) : if a == b : serial += '{0}{1}' . format ( a , sep ) else : serial += '{0}-{1}{2}' . format ( a , b , sep ) return serial res = '' if uniq . size == 0 : return res depth , ipixels = utils . uniq2orderipix ( uniq ) min_depth = np . min ( dept...
def run ( ) : """This client pulls PCAP files for building report . Returns : A list with ` view _ pcap ` , ` meta ` and ` filename ` objects ."""
global WORKBENCH # Grab grab _ server _ argsrver args args = client_helper . grab_server_args ( ) # Start up workbench connection WORKBENCH = zerorpc . Client ( timeout = 300 , heartbeat = 60 ) WORKBENCH . connect ( 'tcp://' + args [ 'server' ] + ':' + args [ 'port' ] ) data_path = os . path . join ( os . path . dirnam...
def process_text ( text , out_format = 'json_ld' , save_json = 'eidos_output.json' , webservice = None ) : """Return an EidosProcessor by processing the given text . This constructs a reader object via Java and extracts mentions from the text . It then serializes the mentions into JSON and processes the resul...
if not webservice : if eidos_reader is None : logger . error ( 'Eidos reader is not available.' ) return None json_dict = eidos_reader . process_text ( text , out_format ) else : res = requests . post ( '%s/process_text' % webservice , json = { 'text' : text } ) json_dict = res . json ( ...
def elbv2_load_balancer_dns_name ( self , lookup , default = None ) : """Args : lookup : the friendly name of the V2 elb to look up default : value to return in case of no match Returns : The hosted zone ID of the ELB found with a name matching ' lookup ' ."""
try : elb = self . _elbv2_load_balancer ( lookup ) return elb [ 'DNSName' ] except ClientError : return default
def data ( self , index , role ) : """Show tooltip with full path only for the root directory"""
if role == Qt . ToolTipRole : root_dir = self . path_list [ 0 ] . split ( osp . sep ) [ - 1 ] if index . data ( ) == root_dir : return osp . join ( self . root_path , root_dir ) return QSortFilterProxyModel . data ( self , index , role )
def list_persistent_volume_claim_for_all_namespaces ( self , ** kwargs ) : """list or watch objects of kind PersistentVolumeClaim This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . list _ persistent _ volume _ cl...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . list_persistent_volume_claim_for_all_namespaces_with_http_info ( ** kwargs ) else : ( data ) = self . list_persistent_volume_claim_for_all_namespaces_with_http_info ( ** kwargs ) return data
def _setup ( self , lines ) : '''setup required adding content from the host to the rootfs , so we try to capture with with ADD .'''
bot . warning ( 'SETUP is error prone, please check output.' ) for line in lines : # For all lines , replace rootfs with actual root / line = re . sub ( '[$]{?SINGULARITY_ROOTFS}?' , '' , '$SINGULARITY_ROOTFS' ) # If we have nothing left , don ' t continue if line in [ '' , None ] : continue # I...
def get_setup_requires ( ) : """Return the list of packages required for this setup . py run"""
# don ' t force requirements if just asking for help if { '--help' , '--help-commands' } . intersection ( sys . argv ) : return list ( ) # otherwise collect all requirements for all known commands reqlist = [ ] for cmd , dependencies in SETUP_REQUIRES . items ( ) : if cmd in sys . argv : reqlist . exten...
def cumulative_density_at_times ( self , times , label = None ) : """Return a Pandas series of the predicted cumulative density function ( 1 - survival function ) at specific times . Parameters times : iterable or float values to return the survival function at . label : string , optional Rename the serie...
label = coalesce ( label , self . _label ) return pd . Series ( self . _cumulative_density ( self . _fitted_parameters_ , times ) , index = _to_array ( times ) , name = label )
def bounding_box ( obj ) : '''Get the ( x , y , z ) bounding box of an object containing points Returns : 2D numpy array of [ [ min _ x , min _ y , min _ z ] , [ max _ x , max _ y , max _ z ] ]'''
return np . array ( [ np . min ( obj . points [ : , 0 : 3 ] , axis = 0 ) , np . max ( obj . points [ : , 0 : 3 ] , axis = 0 ) ] )
def _load_metadata ( self ) : """( Re ) load metadata from store ."""
if self . _synchronizer is None : self . _load_metadata_nosync ( ) else : mkey = self . _key_prefix + array_meta_key with self . _synchronizer [ mkey ] : self . _load_metadata_nosync ( )
def validate_listeners ( self ) : """Validates that some listeners are actually registered"""
if self . exception : # pylint : disable = raising - bad - type raise self . exception listeners = self . __listeners_for_thread if not sum ( len ( l ) for l in listeners ) : raise ValueError ( "No active listeners" )
def add_limbs ( self , key = None ) : '''Add a new section from the tree into the existing os environment Parameters : key ( str ) : The section name to grab from the environment'''
self . branch_out ( limb = key ) self . add_paths_to_os ( key = key )
def update ( self , incr = 1 , force = False ) : """Args : incr ( int ) : Amount to increment ` ` count ` ` ( Default : 1) force ( bool ) : Force refresh even if ` ` min _ delta ` ` has not been reached Increment progress bar and redraw Progress bar is only redrawn if ` ` min _ delta ` ` seconds past since ...
self . count += incr if self . enabled : currentTime = time . time ( ) # Update if force , 100 % , or minimum delta has been reached if force or self . count == self . total or currentTime - self . last_update >= self . min_delta : self . last_update = currentTime self . refresh ( elapsed = ...
def from_yaml ( cls , yaml_path , filename = None ) : """Split a dictionary into parameters controllers parts blocks defines Args : yaml _ path ( str ) : File path to YAML file , or a file in the same dir filename ( str ) : If give , use this filename as the last element in the yaml _ path ( so yaml _ path ...
if filename : # different filename to support passing _ _ file _ _ yaml_path = os . path . join ( os . path . dirname ( yaml_path ) , filename ) assert yaml_path . endswith ( ".yaml" ) , "Expected a/path/to/<yamlname>.yaml, got %r" % yaml_path yamlname = os . path . basename ( yaml_path ) [ : - 5 ] log . debug ( "P...
def mysql_pub ( mysql_dsn , tables = None , blocking = False , ** kwargs ) : """MySQL row - based binlog events pub . * * General Usage * * Listen and pub all tables events : : mysql _ pub ( mysql _ dsn ) Listen and pub only some tables events : : mysql _ pub ( mysql _ dsn , tables = [ " test " ] ) By d...
# parse mysql settings parsed = urlparse ( mysql_dsn ) mysql_settings = { "host" : parsed . hostname , "port" : parsed . port or 3306 , "user" : parsed . username , "passwd" : parsed . password } # connect to binlog stream stream = pymysqlreplication . BinLogStreamReader ( mysql_settings , server_id = random . randint ...
def write_conf ( self ) : """Write the config to file"""
f = open ( self . output_filename , 'w' ) print ( self . t . render ( prefixes = self . prefixes ) , file = f ) f . close ( )
def get_as_type_with_default ( self , index , value_type , default_value ) : """Converts array element into a value defined by specied typecode . If conversion is not possible it returns default value . : param index : an index of element to get . : param value _ type : the TypeCode that defined the type of t...
value = self [ index ] return TypeConverter . to_type_with_default ( value_type , value , default_value )
def process_result_value ( self , value : Optional [ str ] , dialect : Dialect ) -> List [ int ] : """Convert things on the way from the database to Python ."""
retval = self . _dbstr_to_intlist ( value ) return retval
def put ( self , local_path , destination_s3_path , ** kwargs ) : """Put an object stored locally to an S3 path . : param local _ path : Path to source local file : param destination _ s3 _ path : URL for target S3 location : param kwargs : Keyword arguments are passed to the boto function ` put _ object `"""
self . _check_deprecated_argument ( ** kwargs ) # put the file self . put_multipart ( local_path , destination_s3_path , ** kwargs )
def set_user_profile_photo ( self , photo : str ) -> bool : """Use this method to set a new profile photo . This method only works for Users . Bots profile photos must be set using BotFather . Args : photo ( ` ` str ` ` ) : Profile photo to set . Pass a file path as string to upload a new photo that exi...
return bool ( self . send ( functions . photos . UploadProfilePhoto ( file = self . save_file ( photo ) ) ) )
def refresh ( self ) : """刷新 Answer object 的属性 . 例如赞同数增加了 , 先调用 ` ` refresh ( ) ` ` 再访问 upvote _ num属性 , 可获得更新后的赞同数 . : return : None"""
super ( ) . refresh ( ) self . _html = None self . _upvote_num = None self . _content = None self . _collect_num = None self . _comment_num = None
def create_node ( hostname , username , password , name , address ) : '''Create a new node if it does not already exist . hostname The host / address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to create address The addres...
ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' } if __opts__ [ 'test' ] : return _test_output ( ret , 'create' , params = { 'hostname' : hostname , 'username' : username , 'password' : password , 'name' : name , 'address' : address } ) # is this node currently configured ? existing = __...
def create_bottleneck_file ( bottleneck_path , image_lists , label_name , index , image_dir , category , sess , jpeg_data_tensor , decoded_image_tensor , resized_input_tensor , bottleneck_tensor ) : """Create a single bottleneck file ."""
tf . logging . debug ( 'Creating bottleneck at ' + bottleneck_path ) image_path = get_image_path ( image_lists , label_name , index , image_dir , category ) if not tf . gfile . Exists ( image_path ) : tf . logging . fatal ( 'File does not exist %s' , image_path ) image_data = tf . gfile . GFile ( image_path , 'rb' ...
def open ( filename , flag = 'c' , protocol = None , writeback = False , maxsize = DEFAULT_MAXSIZE , timeout = DEFAULT_TIMEOUT ) : """Open a database file as a persistent dictionary . The persistent dictionary file is opened using : func : ` dbm . open ` , so performance will depend on which : mod : ` dbm ` mod...
import dbm dict = dbm . open ( filename , flag ) if maxsize is None and timeout is None : return Shelf ( dict , protocol , writeback ) elif maxsize is None : return TimeoutShelf ( dict , protocol , writeback , timeout = timeout ) elif timeout is None : return LRUShelf ( dict , protocol , writeback , maxsize...
def Refresh ( ) : """looks up symbols within the inferior and caches their names / values . If debugging information is only partial , this method does its best to find as much information as it can , validation can be done using IsSymbolFileSane ."""
try : GdbCache . DICT = gdb . lookup_type ( 'PyDictObject' ) . pointer ( ) GdbCache . TYPE = gdb . lookup_type ( 'PyTypeObject' ) . pointer ( ) except gdb . error as err : # The symbol file we ' re using doesn ' t seem to provide type information . pass interp_head_name = GdbCache . FuzzySymbolLookup ( 'int...
def enrichment_from_msp ( dfmsp , modification = "Phospho (STY)" ) : """Calculate relative enrichment of peptide modifications from modificationSpecificPeptides . txt . Taking a modifiedsitepeptides ` ` DataFrame ` ` returns the relative enrichment of the specified modification in the table . The returned dat...
dfmsp [ 'Modifications' ] = np . array ( [ modification in m for m in dfmsp [ 'Modifications' ] ] ) dfmsp = dfmsp . set_index ( [ 'Modifications' ] ) dfmsp = dfmsp . filter ( regex = 'Intensity ' ) dfmsp [ dfmsp == 0 ] = np . nan df_r = dfmsp . sum ( axis = 0 , level = 0 ) modified = df_r . loc [ True ] . values total ...
def _kmedoids_run ( X , n_clusters , distance , max_iter , tol , rng ) : """Run a single trial of k - medoids clustering on dataset X , and given number of clusters"""
membs = np . empty ( shape = X . shape [ 0 ] , dtype = int ) centers = kmeans . _kmeans_init ( X , n_clusters , method = '' , rng = rng ) sse_last = 9999.9 n_iter = 0 for it in range ( 1 , max_iter ) : membs = kmeans . _assign_clusters ( X , centers ) centers , sse_arr = _update_centers ( X , membs , n_clusters...
def add_subcommands ( parser , commands ) : "Add commands to a parser"
subps = parser . add_subparsers ( ) for cmd , cls in commands : subp = subps . add_parser ( cmd , help = cls . __doc__ ) add_args = getattr ( cls , 'add_arguments' , None ) if add_args : add_args ( subp ) handler = getattr ( cls , 'handle' , None ) if handler : subp . set_defaults ( ...
def select ( self , * args , ** kwargs ) : '''Query this object and all of its references for objects that match the given selector . There are a few different ways to call the ` ` select ` ` method . The most general is to supply a JSON - like query dictionary as the single argument or as keyword arguments...
selector = _select_helper ( args , kwargs ) # Want to pass selector that is a dictionary return _list_attr_splat ( find ( self . references ( ) , selector , { 'plot' : self } ) )
def _save_cookie ( cookie_name , cookie_value ) : """Save cookie"""
config = ConfigParser . SafeConfigParser ( ) config . read ( _config ) if not config . has_section ( 'cookies' ) : config . add_section ( 'cookies' ) config . set ( 'cookies' , cookie_name , cookie_value ) with open ( _config , 'w' ) as ini : config . write ( ini )
def _descend_namespace ( caller_globals , name ) : """Given a globals dictionary , and a name of the form " a . b . c . d " , recursively walk the globals expanding caller _ globals [ ' a ' ] [ ' b ' ] [ ' c ' ] [ ' d ' ] returning the result . Raises an exception ( IndexError ) on failure ."""
names = name . split ( '.' ) cur = caller_globals for i in names : if type ( cur ) is dict : cur = cur [ i ] else : cur = getattr ( cur , i ) return cur
def add_permission ( self , permission ) : """Add a permission to this Admin User . A role defines permissions that can be enabled or disabled . Elements define the target for permission operations and can be either Access Control Lists , Engines or Policy elements . Domain specifies where the access is grant...
if 'permissions' not in self . data : self . data [ 'superuser' ] = False self . data [ 'permissions' ] = { 'permission' : [ ] } for p in permission : self . data [ 'permissions' ] [ 'permission' ] . append ( p . data ) self . update ( )
def _vec_alpha ( self , donor_catchments ) : """Return vector alpha which is the weights for donor model errors Methodology source : Kjeldsen , Jones & Morris 2014 , eq 10 : param donor _ catchments : Catchments to use as donors : type donor _ catchments : list of : class : ` Catchment ` : return : Vector o...
return np . dot ( linalg . inv ( self . _matrix_omega ( donor_catchments ) ) , self . _vec_b ( donor_catchments ) )
def load_object ( import_path ) : """Loads an object from an ' import _ path ' , like in MIDDLEWARE _ CLASSES and the likes . Import paths should be : " mypackage . mymodule . MyObject " . It then imports the module up until the last dot and tries to get the attribute after that dot from the imported module...
if not isinstance ( import_path , six . string_types ) : return import_path if '.' not in import_path : raise TypeError ( "'import_path' argument to 'django_load.core.load_object' must " "contain at least one dot." ) module_name , object_name = import_path . rsplit ( '.' , 1 ) module = import_module ( module_na...
def run ( items , background = None ) : """Detect copy number variations from batched set of samples using WHAM ."""
if not background : background = [ ] background_bams = [ ] paired = vcfutils . get_paired_bams ( [ x [ "align_bam" ] for x in items ] , items ) if paired : inputs = [ paired . tumor_data ] if paired . normal_bam : background = [ paired . normal_data ] background_bams = [ paired . normal_bam ...
def search_function ( root1 , q , s , f , l , o = 'g' ) : """function to get links"""
global links links = search ( q , o , s , f , l ) root1 . destroy ( ) root1 . quit ( )
def parse_content_stream ( page_or_stream , operators = '' ) : """Parse a PDF content stream into a sequence of instructions . A PDF content stream is list of instructions that describe where to render the text and graphics in a PDF . This is the starting point for analyzing PDFs . If the input is a page an...
if not isinstance ( page_or_stream , Object ) : raise TypeError ( "stream must a PDF object" ) if ( page_or_stream . _type_code != ObjectType . stream and page_or_stream . get ( '/Type' ) != '/Page' ) : raise TypeError ( "parse_content_stream called on page or stream object" ) try : if page_or_stream . get ...
def is_json_file ( filename , show_warnings = False ) : """Check configuration file type is JSON Return a boolean indicating wheather the file is JSON format or not"""
try : config_dict = load_config ( filename , file_type = "json" ) is_json = True except : is_json = False return ( is_json )
def retention_period ( self , value ) : """Set the retention period for items in the bucket . : type value : int : param value : number of seconds to retain items after upload or release from event - based lock . : raises ValueError : if the bucket ' s retention policy is locked ."""
policy = self . _properties . setdefault ( "retentionPolicy" , { } ) if value is not None : policy [ "retentionPeriod" ] = str ( value ) else : policy = None self . _patch_property ( "retentionPolicy" , policy )
def ply2gii ( in_file , metadata , out_file = None ) : """Convert from ply to GIfTI"""
from pathlib import Path from numpy import eye from nibabel . gifti import ( GiftiMetaData , GiftiCoordSystem , GiftiImage , GiftiDataArray , ) from pyntcloud import PyntCloud in_file = Path ( in_file ) surf = PyntCloud . from_file ( str ( in_file ) ) # Update centroid metadata metadata . update ( zip ( ( 'SurfaceCente...
def update_domain_name ( self , domain_name , certificate_name = None , certificate_body = None , certificate_private_key = None , certificate_chain = None , certificate_arn = None , lambda_name = None , stage = None , route53 = True , base_path = None ) : """This updates your certificate information for an existin...
print ( "Updating domain name!" ) certificate_name = certificate_name + str ( time . time ( ) ) api_gateway_domain = self . apigateway_client . get_domain_name ( domainName = domain_name ) if not certificate_arn and certificate_body and certificate_private_key and certificate_chain : acm_certificate = self . acm_cl...
def _bson_to_dict ( data , opts ) : """Decode a BSON string to document _ class ."""
try : obj_size = _UNPACK_INT ( data [ : 4 ] ) [ 0 ] except struct . error as exc : raise InvalidBSON ( str ( exc ) ) if obj_size != len ( data ) : raise InvalidBSON ( "invalid object size" ) if data [ obj_size - 1 : obj_size ] != b"\x00" : raise InvalidBSON ( "bad eoo" ) try : return _elements_to_di...
def get_plugin_folders ( ) : """Get linkchecker plugin folders . Default is ~ / . linkchecker / plugins / ."""
folders = [ ] defaultfolder = normpath ( "~/.linkchecker/plugins" ) if not os . path . exists ( defaultfolder ) and not Portable : try : make_userdir ( defaultfolder ) except Exception as errmsg : msg = _ ( "could not create plugin directory %(dirname)r: %(errmsg)r" ) args = dict ( dirna...
def select ( self , fields = [ 'rowid' , '*' ] , offset = None , limit = None ) : '''return SELECT SQL'''
# base SQL SQL = 'SELECT %s FROM %s' % ( ',' . join ( fields ) , self . _table ) # selectors if self . _selectors : SQL = ' ' . join ( [ SQL , 'WHERE' , self . _selectors ] ) . strip ( ) # modifiers if self . _modifiers : SQL = ' ' . join ( [ SQL , self . _modifiers ] ) # limit if limit is not None and isinstan...
def sync_and_deploy_gateway ( collector ) : """Do a sync followed by deploying the gateway"""
configuration = collector . configuration aws_syncr = configuration [ 'aws_syncr' ] find_gateway ( aws_syncr , configuration ) artifact = aws_syncr . artifact aws_syncr . artifact = "" sync ( collector ) aws_syncr . artifact = artifact deploy_gateway ( collector )
def dispatch_job_hook ( self , link , key , job_config , logfile , stream = sys . stdout ) : """Send a single job to be executed Parameters link : ` fermipy . jobs . chain . Link ` The link used to invoke the command we are running key : str A string that identifies this particular instance of the job j...
full_sub_dict = job_config . copy ( ) full_command = "%s >& %s" % ( link . command_template ( ) . format ( ** full_sub_dict ) , logfile ) logdir = os . path . dirname ( logfile ) if self . _dry_run : sys . stdout . write ( "%s\n" % full_command ) else : try : os . makedirs ( logdir ) except OSError ...
def publish ( self , daap_server , preferred_database = None ) : """Publish a given ` DAAPServer ` instance . The given instances should be fully configured , including the provider . By default Zeroconf only advertises the first database , but the DAAP protocol has support for multiple databases . Therefore ...
if daap_server in self . daap_servers : self . unpublish ( daap_server ) # Zeroconf can advertise the information for one database only . Since # the protocol supports multiple database , let the user decide which # database to advertise . If none is specified , take the first one . provider = daap_server . provide...
def set_status ( self , trial , status ) : """Sets status and checkpoints metadata if needed . Only checkpoints metadata if trial status is a terminal condition . PENDING , PAUSED , and RUNNING switches have checkpoints taken care of in the TrialRunner . Args : trial ( Trial ) : Trial to checkpoint . st...
trial . status = status if status in [ Trial . TERMINATED , Trial . ERROR ] : self . try_checkpoint_metadata ( trial )
def _android_get_installed_platform_tools_version ( self ) : """Crudely parse out the installed platform - tools version"""
platform_tools_dir = os . path . join ( self . android_sdk_dir , 'platform-tools' ) if not os . path . exists ( platform_tools_dir ) : return None data_file = os . path . join ( platform_tools_dir , 'source.properties' ) if not os . path . exists ( data_file ) : return None with open ( data_file , 'r' ) as file...
def _create_model ( self , X , Y ) : """Creates the model given some input data X and Y ."""
# - - - define kernel self . input_dim = X . shape [ 1 ] if self . kernel is None : kern = GPy . kern . RBF ( self . input_dim , variance = 1. ) else : kern = self . kernel self . kernel = None # - - - define model noise_var = Y . var ( ) * 0.01 if self . noise_var is None else self . noise_var self . model...
def beacons ( opts , functions , context = None , proxy = None ) : '''Load the beacon modules : param dict opts : The Salt options dictionary : param dict functions : A dictionary of minion modules , with module names as keys and funcs as values .'''
return LazyLoader ( _module_dirs ( opts , 'beacons' ) , opts , tag = 'beacons' , pack = { '__context__' : context , '__salt__' : functions , '__proxy__' : proxy or { } } , virtual_funcs = [ ] , )
def make_k8s_lando_router ( config , obj , queue_name ) : """Makes MessageRouter which can listen to queue _ name sending messages to the k8s version of lando . : param config : WorkerConfig / ServerConfig : settings for connecting to the queue : param obj : object : implements lando specific methods : param ...
return MessageRouter ( config , obj , queue_name , K8S_LANDO_INCOMING_MESSAGES , processor_constructor = WorkQueueProcessor )
def create_principal ( name , enctypes = None ) : '''Create Principal CLI Example : . . code - block : : bash salt ' kdc . example . com ' kerberos . create _ principal host / example . com'''
ret = { } krb_cmd = 'addprinc -randkey' if enctypes : krb_cmd += ' -e {0}' . format ( enctypes ) krb_cmd += ' {0}' . format ( name ) cmd = __execute_kadmin ( krb_cmd ) if cmd [ 'retcode' ] != 0 or cmd [ 'stderr' ] : if not cmd [ 'stderr' ] . splitlines ( ) [ - 1 ] . startswith ( 'WARNING:' ) : ret [ 'co...
def tree_view_keypress_callback ( self , widget , event ) : """General method to adapt widget view and controller behavior according the key press / release and button release events Here the scrollbar motion to follow key cursor motions in editable is already in . : param Gtk . TreeView widget : The tree vie...
current_row_path , current_focused_column = self . tree_view . get_cursor ( ) # print ( current _ row _ path , current _ focused _ column ) if isinstance ( widget , Gtk . TreeView ) and not self . active_entry_widget : # avoid jumps for active entry widget pass # cursor motion / selection changes ( e . g . also...
def parse_dict ( value ) : """Parse a dict value from the tox config . . . code - block : ini [ travis ] python = 2.7 : py27 , docs 3.5 : py { 35,36} With this config , the value of ` ` python ` ` would be parsed by this function , and would return : : '2.7 ' : ' py27 , docs ' , '3.5 ' : ' py { 35...
lines = [ line . strip ( ) for line in value . strip ( ) . splitlines ( ) ] pairs = [ line . split ( ':' , 1 ) for line in lines if line ] return dict ( ( k . strip ( ) , v . strip ( ) ) for k , v in pairs )
def SendReply ( self , response , tag = None ) : """Allows this flow to send a message to its parent flow . If this flow does not have a parent , the message is ignored . Args : response : An RDFValue ( ) instance to be sent to the parent . tag : If specified , tag the result with this tag . Raises : Va...
if not isinstance ( response , rdfvalue . RDFValue ) : raise ValueError ( "SendReply can only send RDFValues" ) if self . rdf_flow . parent_flow_id : response = rdf_flow_objects . FlowResponse ( client_id = self . rdf_flow . client_id , request_id = self . rdf_flow . parent_request_id , response_id = self . Get...
def LatLngsToGoogleLink ( source , destination ) : """Return a string " < a . . . " for a trip at a random time ."""
dt = GetRandomDatetime ( ) return "<a href='%s'>from:%s to:%s on %s</a>" % ( LatLngsToGoogleUrl ( source , destination , dt ) , FormatLatLng ( source ) , FormatLatLng ( destination ) , dt . ctime ( ) )
def ocsp_no_check ( self , value ) : """A bool - if the certificate should have the OCSP no check extension . Only applicable to certificates created for signing OCSP responses . Such certificates should normally be issued for a very short period of time since they are effectively whitelisted by clients ."""
if value is None : self . _ocsp_no_check = None else : self . _ocsp_no_check = bool ( value )
def get_freesurfer_label ( annot_input , verbose = True ) : """Print freesurfer label names ."""
labels , color_table , names = nib . freesurfer . read_annot ( annot_input ) if verbose : print ( names ) return names
def edit_filename ( filename , prefix = '' , suffix = '' , new_ext = None ) : """Edit a file name by add a prefix , inserting a suffix in front of a file name extension or replacing the extension . Parameters filename : str The file name . prefix : str The prefix to be added . suffix : str The suffi...
base , ext = os . path . splitext ( filename ) if new_ext is None : new_filename = base + suffix + ext else : new_filename = base + suffix + new_ext return new_filename
def _annotate_fn_args ( stack , fn_opname , nargs , nkw = - 1 , consume_fn_name = True ) : """Add commas and equals as appropriate to function argument lists in the stack ."""
kwarg_names = [ ] if nkw == - 1 : if sys . version_info [ 0 ] < 3 : # Compute nkw and nargs from nargs for python 2.7 nargs , nkw = ( nargs % 256 , 2 * nargs // 256 ) else : if fn_opname == 'CALL_FUNCTION_KW' : if qj . _DEBUG_QJ : assert len ( stack ) and stack [ - 1 ...
def is_all_field_none ( self ) : """: rtype : bool"""
if self . _payment is not None : return False if self . _read_only is not None : return False if self . _draft_payment is not None : return False return True
def map_services ( self ) : """Get full Vera device service info ."""
# the Vera rest API is a bit rough so we need to make 2 calls # to get all the info e need self . get_simple_devices_info ( ) j = self . data_request ( { 'id' : 'status' , 'output_format' : 'json' } ) . json ( ) service_map = { } items = j . get ( 'devices' ) for item in items : service_map [ item . get ( 'id' ) ] ...
def get_tiles_list ( element ) : """Returns the list of all tile names from Product _ Organisation element in metadata . xml"""
tiles = { } for el in element : g = ( el . findall ( './/Granules' ) or el . findall ( './/Granule' ) ) [ 0 ] name = g . attrib [ 'granuleIdentifier' ] name_parts = name . split ( '_' ) mgs = name_parts [ - 2 ] tiles [ mgs ] = name return tiles
def table_enumerate ( self , columns , content ) : """Enumerate each table column ."""
columns . insert ( 0 , { 'label' : '#' , 'enumerated' : True } ) i = 0 for row in content : i += 1 row . insert ( 0 , '{:d}' . format ( i ) ) return ( columns , content )
def set_legend_position ( self , legend_position ) : """Sets legend position . Default is ' r ' . b - At the bottom of the chart , legend entries in a horizontal row . bv - At the bottom of the chart , legend entries in a vertical column . t - At the top of the chart , legend entries in a horizontal row . t...
if legend_position : self . legend_position = quote ( legend_position ) else : self . legend_position = None
def _valid_key ( self , key ) : """Return True if supplied key string serves as a valid attribute name : alphanumeric strings beginning with a letter . Leading underscore not allowed . Also test for conflict with protected attribute names ( e . g . dict class instance methods ) ."""
if not isinstance ( key , str ) : return False elif hasattr ( { } , key ) : return False elif key in self . _special_names : return False else : return self . _valid_key_pattern . match ( key )
def simple_response ( self , status , msg = "" ) : """Write a simple response back to the client ."""
status = str ( status ) buf = [ self . server . protocol + " " + status + CRLF , "Content-Length: %s\r\n" % len ( msg ) , "Content-Type: text/plain\r\n" ] if status [ : 3 ] in ( "413" , "414" ) : # Request Entity Too Large / Request - URI Too Long self . close_connection = True if self . response_protocol == 'H...
def iter_links ( self ) : """An iterator over the working links in the machine . Generates a series of ( x , y , link ) tuples ."""
for x in range ( self . width ) : for y in range ( self . height ) : for link in Links : if ( x , y , link ) in self : yield ( x , y , link )
def set_user_passwd ( self , userid , data ) : """Set user password"""
return self . api_call ( ENDPOINTS [ 'users' ] [ 'password' ] , dict ( userid = userid ) , body = data )
def get_assessment_offered ( self , assessment_offered_id ) : """Gets the ` ` AssessmentOffered ` ` specified by its ` ` Id ` ` . In plenary mode , the exact ` ` Id ` ` is found or a ` ` NotFound ` ` results . Otherwise , the returned ` ` AssessmentOffered ` ` may have a different ` ` Id ` ` than requested , ...
# Implemented from template for # osid . resource . ResourceLookupSession . get _ resource # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'assessment' , collection = 'AssessmentOffered' , runtime = self . _runtime ) result = collection . find_one ( dict ( { '_id' : Object...
def sync_subscriber ( subscriber ) : """Sync a Customer with Stripe api data ."""
customer , _created = Customer . get_or_create ( subscriber = subscriber ) try : customer . sync_from_stripe_data ( customer . api_retrieve ( ) ) customer . _sync_subscriptions ( ) customer . _sync_invoices ( ) customer . _sync_cards ( ) customer . _sync_charges ( ) except InvalidRequestError as e :...
def execute ( self , action , parameters ) : """Execute a DynamoDB action with the given parameters . The method will retry requests that failed due to OS level errors or when being throttled by DynamoDB . : param str action : DynamoDB action to invoke : param dict parameters : parameters to send into the a...
measurements = collections . deque ( [ ] , self . _max_retries ) for attempt in range ( 1 , self . _max_retries + 1 ) : try : result = yield self . _execute ( action , parameters , attempt , measurements ) except ( exceptions . InternalServerError , exceptions . RequestException , exceptions . Throttlin...
def print_locals ( * args , ** kwargs ) : """Prints local variables in function . If no arguments all locals are printed . Variables can be specified directly ( variable values passed in ) as varargs or indirectly ( variable names passed in ) in kwargs by using keys and a list of strings ."""
from utool import util_str from utool import util_dbg from utool import util_dict locals_ = util_dbg . get_parent_frame ( ) . f_locals keys = kwargs . get ( 'keys' , None if len ( args ) == 0 else [ ] ) to_print = { } for arg in args : varname = util_dbg . get_varname_from_locals ( arg , locals_ ) to_print [ va...
def log_player_plays_road_builder ( self , player , location1 , location2 ) : """: param player : catan . game . Player : param location1 : string , see hexgrid . location ( ) : param location2 : string , see hexgrid . location ( )"""
self . _logln ( '{0} plays road builder, builds at {1} and {2}' . format ( player . color , location1 , location2 ) )
def _attributeStr ( self , name ) : """Return name = value for a single attribute"""
return "{}={}" . format ( _encodeAttr ( name ) , "," . join ( [ _encodeAttr ( v ) for v in self . attributes [ name ] ] ) )
def map_recursive ( function , iterable ) : """Apply function recursively to every item or value of iterable and returns a new iterable object with the results ."""
if isiterable ( iterable ) : dataOut = iterable . __class__ ( ) for i in iterable : if isinstance ( dataOut , dict ) : dataOut [ i ] = map_recursive ( function , iterable [ i ] ) else : # convert to list and append if not isinstance ( dataOut , list ) : da...
def _complete_url ( self , text , tld_pos , tld ) : """Expand string in both sides to match whole URL . : param str text : text where we want to find URL : param int tld _ pos : position of TLD : param str tld : matched TLD which should be in text : return : returns URL : rtype : str"""
left_ok = True right_ok = True max_len = len ( text ) - 1 end_pos = tld_pos start_pos = tld_pos while left_ok or right_ok : if left_ok : if start_pos <= 0 : left_ok = False else : if text [ start_pos - 1 ] not in self . _stop_chars_left : start_pos -= 1 ...
def _fill ( self , values ) : """Add extra values to fill the line"""
if not self . _previous_line : self . _previous_line = values return super ( StackedLine , self ) . _fill ( values ) new_values = values + list ( reversed ( self . _previous_line ) ) self . _previous_line = values return new_values
def compute_qu ( self ) : """Computes the mean and variance of q ( u ) , the variational distribution on inducing outputs . SVGP with this q ( u ) should predict identically to SGPR . : return : mu , A"""
Kuf = features . Kuf ( self . feature , self . kern , self . X ) Kuu = features . Kuu ( self . feature , self . kern , jitter = settings . jitter ) Sig = Kuu + ( self . likelihood . variance ** - 1 ) * tf . matmul ( Kuf , Kuf , transpose_b = True ) Sig_sqrt = tf . cholesky ( Sig ) Sig_sqrt_Kuu = tf . matrix_triangular_...
def _merge_skyline ( self , skylineq , segment ) : """Arguments : skylineq ( collections . deque ) : segment ( HSegment ) :"""
if len ( skylineq ) == 0 : skylineq . append ( segment ) return if skylineq [ - 1 ] . top == segment . top : s = skylineq [ - 1 ] skylineq [ - 1 ] = HSegment ( s . start , s . length + segment . length ) else : skylineq . append ( segment )
def max ( self , axis = None , skipna = True ) : """Return the maximum value of the Index . Parameters axis : int , optional For compatibility with NumPy . Only 0 or None are allowed . skipna : bool , default True Returns scalar Maximum value . See Also Index . min : Return the minimum value in an...
nv . validate_minmax_axis ( axis ) return nanops . nanmax ( self . _values , skipna = skipna )
def _combine_qc_samples ( samples ) : """Combine split QC analyses into single samples based on BAM files ."""
by_bam = collections . defaultdict ( list ) for data in [ utils . to_single_data ( x ) for x in samples ] : batch = dd . get_batch ( data ) or dd . get_sample_name ( data ) if not isinstance ( batch , ( list , tuple ) ) : batch = [ batch ] batch = tuple ( batch ) by_bam [ ( dd . get_align_bam ( ...
def get_model_path ( self , name ) : """Infer the path to the XML model name ."""
name , ext = os . path . splitext ( name ) ext = '.xml' xmlfile = name + self . config [ 'file_suffix' ] + ext xmlfile = utils . resolve_path ( xmlfile , workdir = self . config [ 'fileio' ] [ 'workdir' ] ) return xmlfile
def safe_repr ( obj ) : """Try to get ` ` _ _ name _ _ ` ` first , ` ` _ _ class _ _ . _ _ name _ _ ` ` second and finally , if we can ' t get anything acceptable , fallback to user a ` ` repr ( ) ` ` call ."""
name = getattr ( obj , '__name__' , getattr ( obj . __class__ , '__name__' ) ) if name == 'ndict' : name = 'dict' return name or repr ( obj )