idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
46,300 | def convert2wkt ( self , set3D = True ) : features = self . getfeatures ( ) for feature in features : try : feature . geometry ( ) . Set3D ( set3D ) except AttributeError : dim = 3 if set3D else 2 feature . geometry ( ) . SetCoordinateDimension ( dim ) return [ feature . geometry ( ) . ExportToWkt ( ) for feature in features ] | export the geometry of each feature as a wkt string |
46,301 | def getFeatureByAttribute ( self , fieldname , attribute ) : attr = attribute . strip ( ) if isinstance ( attribute , str ) else attribute if fieldname not in self . fieldnames : raise KeyError ( 'invalid field name' ) out = [ ] self . layer . ResetReading ( ) for feature in self . layer : field = feature . GetField ( fieldname ) field = field . strip ( ) if isinstance ( field , str ) else field if field == attr : out . append ( feature . Clone ( ) ) self . layer . ResetReading ( ) if len ( out ) == 0 : return None elif len ( out ) == 1 : return out [ 0 ] else : return out | get features by field attribute |
46,302 | def init_layer ( self ) : self . layer = self . vector . GetLayer ( ) self . __features = [ None ] * self . nfeatures | initialize a layer object |
46,303 | def load ( self ) : self . layer . ResetReading ( ) for i in range ( self . nfeatures ) : if self . __features [ i ] is None : self . __features [ i ] = self . layer [ i ] | load all feature into memory |
46,304 | def reproject ( self , projection ) : srs_out = crsConvert ( projection , 'osr' ) if self . srs . IsSame ( srs_out ) == 0 : coordTrans = osr . CoordinateTransformation ( self . srs , srs_out ) layername = self . layername geomType = self . geomType features = self . getfeatures ( ) feat_def = features [ 0 ] . GetDefnRef ( ) fields = [ feat_def . GetFieldDefn ( x ) for x in range ( 0 , feat_def . GetFieldCount ( ) ) ] self . __init__ ( ) self . addlayer ( layername , srs_out , geomType ) self . layer . CreateFields ( fields ) for feature in features : geom = feature . GetGeometryRef ( ) geom . Transform ( coordTrans ) newfeature = feature . Clone ( ) newfeature . SetGeometry ( geom ) self . layer . CreateFeature ( newfeature ) newfeature = None self . init_features ( ) | in - memory reprojection |
46,305 | def write ( self , outfile , format = 'ESRI Shapefile' , overwrite = True ) : ( outfilepath , outfilename ) = os . path . split ( outfile ) basename = os . path . splitext ( outfilename ) [ 0 ] driver = ogr . GetDriverByName ( format ) if os . path . exists ( outfile ) : if overwrite : driver . DeleteDataSource ( outfile ) else : raise RuntimeError ( 'target file already exists' ) outdataset = driver . CreateDataSource ( outfile ) outlayer = outdataset . CreateLayer ( self . layername , geom_type = self . geomType ) outlayerdef = outlayer . GetLayerDefn ( ) for fieldDef in self . fieldDefs : outlayer . CreateField ( fieldDef ) self . layer . ResetReading ( ) for feature in self . layer : outFeature = ogr . Feature ( outlayerdef ) outFeature . SetGeometry ( feature . GetGeometryRef ( ) ) for name in self . fieldnames : outFeature . SetField ( name , feature . GetField ( name ) ) outlayer . CreateFeature ( outFeature ) outFeature = None self . layer . ResetReading ( ) if format == 'ESRI Shapefile' : srs_out = self . srs . Clone ( ) srs_out . MorphToESRI ( ) with open ( os . path . join ( outfilepath , basename + '.prj' ) , 'w' ) as prj : prj . write ( srs_out . ExportToWkt ( ) ) outdataset = None | write the Vector object to a file |
46,306 | def _init_zmq ( self , port_publish , port_subscribe ) : log . debug ( 'kernel {} publishing on port {}' '' . format ( self . analysis . id_ , port_publish ) ) self . zmq_publish = zmq . Context ( ) . socket ( zmq . PUB ) self . zmq_publish . connect ( 'tcp://127.0.0.1:{}' . format ( port_publish ) ) log . debug ( 'kernel {} subscribed on port {}' '' . format ( self . analysis . id_ , port_subscribe ) ) self . zmq_sub_ctx = zmq . Context ( ) self . zmq_sub = self . zmq_sub_ctx . socket ( zmq . SUB ) self . zmq_sub . setsockopt ( zmq . SUBSCRIBE , self . analysis . id_ . encode ( 'utf-8' ) ) self . zmq_sub . connect ( 'tcp://127.0.0.1:{}' . format ( port_subscribe ) ) self . zmq_stream_sub = zmq . eventloop . zmqstream . ZMQStream ( self . zmq_sub ) self . zmq_stream_sub . on_recv ( self . zmq_listener ) self . zmq_ack = False self . send_handshake ( ) | Initialize zmq messaging . |
46,307 | def emit ( self , signal , message , analysis_id ) : log . debug ( 'kernel {} zmq send ({}): {}' '' . format ( analysis_id , signal , message ) ) self . zmq_publish . send ( json . dumps ( { 'analysis_id' : analysis_id , 'frame' : { 'signal' : signal , 'load' : message } , } , default = json_encoder_default ) . encode ( 'utf-8' ) ) | Emit signal to main . |
46,308 | def set_ports ( self , port0 = 0x00 , port1 = 0x00 ) : 'Writes specified value to the pins defined as output by method. Writing to input pins has no effect.' self . bus . write_byte_data ( self . address , self . CONTROL_PORT0 , port0 ) self . bus . write_byte_data ( self . address , self . CONTROL_PORT0 , port1 ) return | Writes specified value to the pins defined as output by method . Writing to input pins has no effect . |
46,309 | def get_gtf_db ( gtf , in_memory = False ) : db_file = gtf + '.db' if gtf . endswith ( '.gz' ) : db_file = gtf [ : - 3 ] + '.db' if file_exists ( db_file ) : return gffutils . FeatureDB ( db_file ) db_file = ':memory:' if in_memory else db_file if in_memory or not file_exists ( db_file ) : debug ( 'GTF database does not exist, creating...' ) infer_extent = guess_infer_extent ( gtf ) db = gffutils . create_db ( gtf , dbfn = db_file , infer_gene_extent = infer_extent ) return db else : return gffutils . FeatureDB ( db_file ) | create a gffutils DB |
46,310 | def gtf_to_bed ( gtf , alt_out_dir = None ) : out_file = os . path . splitext ( gtf ) [ 0 ] + '.bed' if file_exists ( out_file ) : return out_file if not os . access ( os . path . dirname ( out_file ) , os . W_OK | os . X_OK ) : if not alt_out_dir : raise IOError ( 'Cannot write transcript BED output file %s' % out_file ) else : out_file = os . path . join ( alt_out_dir , os . path . basename ( out_file ) ) with open ( out_file , "w" ) as out_handle : db = get_gtf_db ( gtf ) for feature in db . features_of_type ( 'transcript' , order_by = ( "seqid" , "start" , "end" ) ) : chrom = feature . chrom start = feature . start end = feature . end attributes = feature . attributes . keys ( ) strand = feature . strand name = ( feature [ 'gene_name' ] [ 0 ] if 'gene_name' in attributes else feature [ 'gene_id' ] [ 0 ] ) line = "\t" . join ( [ str ( x ) for x in [ chrom , start , end , name , "." , strand ] ] ) out_handle . write ( line + "\n" ) return out_file | create a BED file of transcript - level features with attached gene name or gene ids |
46,311 | def tx2genefile ( gtf , out_file = None ) : installed_tx2gene = os . path . join ( os . path . dirname ( gtf ) , "tx2gene.csv" ) if file_exists ( installed_tx2gene ) : return installed_tx2gene if file_exists ( out_file ) : return out_file with file_transaction ( out_file ) as tx_out_file : with open ( tx_out_file , "w" ) as out_handle : for k , v in transcript_to_gene ( gtf ) . items ( ) : out_handle . write ( "," . join ( [ k , v ] ) + "\n" ) return out_file | write out a file of transcript - > gene mappings . use the installed tx2gene . csv if it exists else write a new one out |
46,312 | def transcript_to_gene ( gtf ) : gene_lookup = { } for feature in complete_features ( get_gtf_db ( gtf ) ) : gene_id = feature . attributes . get ( 'gene_id' , [ None ] ) [ 0 ] transcript_id = feature . attributes . get ( 'transcript_id' , [ None ] ) [ 0 ] gene_lookup [ transcript_id ] = gene_id return gene_lookup | return a dictionary keyed by transcript_id of the associated gene_id |
46,313 | def set_freq ( self , fout , freq ) : hsdiv_tuple = ( 4 , 5 , 6 , 7 , 9 , 11 ) n1div_tuple = ( 1 , ) + tuple ( range ( 2 , 129 , 2 ) ) fdco_min = 5670.0 hsdiv = self . get_hs_div ( ) n1div = self . get_n1_div ( ) if abs ( ( freq - fout ) * 1e6 / fout ) > 3500 : fdco = fout * hsdiv * n1div fxtal = fdco / self . get_rfreq ( ) for hsdiv_iter in hsdiv_tuple : for n1div_iter in n1div_tuple : fdco_new = freq * hsdiv_iter * n1div_iter if ( fdco_new >= 4850 ) and ( fdco_new <= 5670 ) : if ( fdco_new <= fdco_min ) : fdco_min = fdco_new hsdiv = hsdiv_iter n1div = n1div_iter rfreq = fdco_min / fxtal self . freeze_dco ( ) self . set_hs_div ( hsdiv ) self . set_n1_div ( n1div ) self . set_rfreq ( rfreq ) self . unfreeze_dco ( ) self . new_freq ( ) else : rfreq = self . get_rfreq ( ) * ( freq / fout ) self . freeze_m ( ) self . set_rfreq ( rfreq ) self . unfreeze_m ( ) | Sets new output frequency required parameters are real current frequency at output and new required frequency . |
46,314 | def check_folders ( name ) : if os . getcwd ( ) . endswith ( 'analyses' ) : correct = input ( 'You are in an analyses folder. This will create ' 'another analyses folder inside this one. Do ' 'you want to continue? (y/N)' ) if correct != 'y' : return False if not os . path . exists ( os . path . join ( os . getcwd ( ) , 'analyses' ) ) : correct = input ( 'This is the first analysis here. Do ' 'you want to continue? (y/N)' ) if correct != 'y' : return False if os . path . exists ( os . path . join ( os . getcwd ( ) , 'analyses' , name ) ) : correct = input ( 'An analysis with this name exists already. Do ' 'you want to continue? (y/N)' ) if correct != 'y' : return False return True | Only checks and asks questions . Nothing is written to disk . |
46,315 | def create_analyses ( name , kernel = None ) : if not os . path . exists ( os . path . join ( os . getcwd ( ) , 'analyses' ) ) : os . system ( "mkdir analyses" ) init_path = os . path . join ( os . getcwd ( ) , 'analyses' , '__init__.py' ) if not os . path . exists ( init_path ) : with open ( init_path , 'w' ) as f : pass index_path = os . path . join ( os . getcwd ( ) , 'analyses' , 'index.yaml' ) if not os . path . exists ( index_path ) : with open ( index_path , 'w' ) as f : f . write ( 'title: Analyses\n' ) f . write ( 'description: A short description.\n' ) f . write ( 'version: 0.1.0\n' ) f . write ( '\n' ) f . write ( 'analyses:\n' ) if kernel is None : with open ( index_path , 'a' ) as f : f . write ( ' # automatically inserted by scaffold-databench\n' ) f . write ( ' - name: {}\n' . format ( name ) ) f . write ( ' title: {}\n' . format ( name . title ( ) ) ) f . write ( ' description: A new analysis.\n' ) f . write ( ' watch:\n' ) f . write ( ' - {}/*.js\n' . format ( name ) ) f . write ( ' - {}/*.html\n' . format ( name ) ) | Create an analysis with given name and suffix . |
46,316 | def create_analysis ( name , kernel , src_dir , scaffold_name ) : folder = os . path . join ( os . getcwd ( ) , 'analyses' , name ) if not os . path . exists ( folder ) : os . makedirs ( folder ) else : log . warning ( 'Analysis folder {} already exists.' . format ( folder ) ) for f in os . listdir ( src_dir ) : if f in ( '__pycache__' , ) or any ( f . endswith ( ending ) for ending in ( '.pyc' , ) ) : continue copy_scaffold_file ( os . path . join ( src_dir , f ) , os . path . join ( folder , f ) , name , scaffold_name ) | Create analysis files . |
46,317 | def crsConvert ( crsIn , crsOut ) : if isinstance ( crsIn , osr . SpatialReference ) : srs = crsIn . Clone ( ) else : srs = osr . SpatialReference ( ) if isinstance ( crsIn , int ) : crsIn = 'EPSG:{}' . format ( crsIn ) if isinstance ( crsIn , str ) : try : srs . SetFromUserInput ( crsIn ) except RuntimeError : raise TypeError ( 'crsIn not recognized; must be of type WKT, PROJ4 or EPSG' ) else : raise TypeError ( 'crsIn must be of type int, str or osr.SpatialReference' ) if crsOut == 'wkt' : return srs . ExportToWkt ( ) elif crsOut == 'prettyWkt' : return srs . ExportToPrettyWkt ( ) elif crsOut == 'proj4' : return srs . ExportToProj4 ( ) elif crsOut == 'epsg' : srs . AutoIdentifyEPSG ( ) return int ( srs . GetAuthorityCode ( None ) ) elif crsOut == 'opengis' : srs . AutoIdentifyEPSG ( ) return 'http://www.opengis.net/def/crs/EPSG/0/{}' . format ( srs . GetAuthorityCode ( None ) ) elif crsOut == 'osr' : return srs else : raise ValueError ( 'crsOut not recognized; must be either wkt, proj4, opengis or epsg' ) | convert between different types of spatial references |
46,318 | def haversine ( lat1 , lon1 , lat2 , lon2 ) : radius = 6371000 lat1 , lon1 , lat2 , lon2 = map ( math . radians , [ lat1 , lon1 , lat2 , lon2 ] ) a = math . sin ( ( lat2 - lat1 ) / 2 ) ** 2 + math . cos ( lat1 ) * math . cos ( lat2 ) * math . sin ( ( lon2 - lon1 ) / 2 ) ** 2 c = 2 * math . asin ( math . sqrt ( a ) ) return radius * c | compute the distance in meters between two points in latlon |
46,319 | def gdal_rasterize ( src , dst , options ) : out = gdal . Rasterize ( dst , src , options = gdal . RasterizeOptions ( ** options ) ) out = None | a simple wrapper for gdal . Rasterize |
46,320 | def set_up_dirs ( proc_name , output_dir = None , work_dir = None , log_dir = None ) : output_dir = safe_mkdir ( adjust_path ( output_dir or join ( os . getcwd ( ) , proc_name ) ) , 'output_dir' ) debug ( 'Saving results into ' + output_dir ) work_dir = safe_mkdir ( work_dir or join ( output_dir , 'work' ) , 'working directory' ) info ( 'Using work directory ' + work_dir ) log_fpath = set_up_log ( log_dir or safe_mkdir ( join ( work_dir , 'log' ) ) , proc_name + '.log' ) return output_dir , work_dir , log_fpath | Creates output_dir work_dir and sets up log |
46,321 | def _iter_content_generator ( response , decode_unicode ) : for chunk in response . iter_content ( 100 * 1024 , decode_unicode = decode_unicode ) : if decode_unicode : chunk = chunk . replace ( '\r\n' , '\n' ) chunk = chunk . rstrip ( '\r' ) yield chunk | Generator used to yield 100 KiB chunks for a given response . |
46,322 | def generic_request ( self , class_ , iter_lines = False , iter_content = False , controller = None , parse_types = False , ** kwargs ) : r if iter_lines and iter_content : raise ValueError ( 'iter_lines and iter_content cannot both be True' ) if 'format' in kwargs and parse_types : raise ValueError ( 'parse_types can only be used if format is unset.' ) if controller is None : controller = self . _find_controller ( class_ ) else : classes = self . request_controllers . get ( controller , None ) if classes is None : raise ValueError ( 'Unknown request controller {!r}' . format ( controller ) ) if class_ not in classes : raise ValueError ( 'Unknown request class {!r} for controller {!r}' . format ( class_ , controller ) ) decode = ( class_ != 'download' ) if not decode and iter_lines : error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.' ) raise ValueError ( error ) self . authenticate ( ) url = ( '{0}{1}/query/class/{2}' . format ( self . base_url , controller , class_ ) ) offline_check = ( class_ , controller ) in self . offline_predicates valid_fields = { p . name for p in self . rest_predicates } predicates = None if not offline_check : predicates = self . get_predicates ( class_ , controller ) predicate_fields = { p . name for p in predicates } valid_fields |= predicate_fields else : valid_fields |= self . offline_predicates [ ( class_ , controller ) ] for key , value in kwargs . items ( ) : if key not in valid_fields : raise TypeError ( "'{class_}' got an unexpected argument '{key}'" . format ( class_ = class_ , key = key ) ) if class_ == 'upload' and key == 'file' : continue value = _stringify_predicate_value ( value ) url += '/{key}/{value}' . format ( key = key , value = value ) logger . debug ( requests . utils . requote_uri ( url ) ) if class_ == 'upload' : if 'file' not in kwargs : raise TypeError ( "missing keyword argument: 'file'" ) resp = self . session . post ( url , files = { 'file' : kwargs [ 'file' ] } ) else : resp = self . _ratelimited_get ( url , stream = iter_lines or iter_content ) _raise_for_status ( resp ) if resp . encoding is None : resp . encoding = 'UTF-8' if iter_lines : return _iter_lines_generator ( resp , decode_unicode = decode ) elif iter_content : return _iter_content_generator ( resp , decode_unicode = decode ) else : if 'format' in kwargs : if decode : data = resp . text data = data . replace ( '\r\n' , '\n' ) else : data = resp . content return data else : data = resp . json ( ) if predicates is None or not parse_types : return data else : return self . _parse_types ( data , predicates ) | r Generic Space - Track query . |
46,323 | def _ratelimited_get ( self , * args , ** kwargs ) : with self . _ratelimiter : resp = self . session . get ( * args , ** kwargs ) if resp . status_code == 500 : if 'violated your query rate limit' in resp . text : until = time . time ( ) + self . _ratelimiter . period t = threading . Thread ( target = self . _ratelimit_callback , args = ( until , ) ) t . daemon = True t . start ( ) time . sleep ( self . _ratelimiter . period ) with self . _ratelimiter : resp = self . session . get ( * args , ** kwargs ) return resp | Perform get request handling rate limiting . |
46,324 | def _find_controller ( self , class_ ) : for controller , classes in self . request_controllers . items ( ) : if class_ in classes : return controller else : raise ValueError ( 'Unknown request class {!r}' . format ( class_ ) ) | Find first controller that matches given request class . |
46,325 | def get_predicates ( self , class_ , controller = None ) : if class_ not in self . _predicates : if controller is None : controller = self . _find_controller ( class_ ) else : classes = self . request_controllers . get ( controller , None ) if classes is None : raise ValueError ( 'Unknown request controller {!r}' . format ( controller ) ) if class_ not in classes : raise ValueError ( 'Unknown request class {!r}' . format ( class_ ) ) predicates_data = self . _download_predicate_data ( class_ , controller ) predicate_objects = self . _parse_predicates_data ( predicates_data ) self . _predicates [ class_ ] = predicate_objects return self . _predicates [ class_ ] | Get full predicate information for given request class and cache for subsequent calls . |
46,326 | def get_predicates ( self , class_ ) : return self . client . get_predicates ( class_ = class_ , controller = self . controller ) | Proxy get_predicates to client with stored request controller . |
46,327 | def on_install ( self , editor ) : super ( FoldingPanel , self ) . on_install ( editor ) self . context_menu = QtWidgets . QMenu ( _ ( 'Folding' ) , self . editor ) action = self . action_collapse = QtWidgets . QAction ( _ ( 'Collapse' ) , self . context_menu ) action . setShortcut ( 'Shift+-' ) action . triggered . connect ( self . _on_action_toggle ) self . context_menu . addAction ( action ) action = self . action_expand = QtWidgets . QAction ( _ ( 'Expand' ) , self . context_menu ) action . setShortcut ( 'Shift++' ) action . triggered . connect ( self . _on_action_toggle ) self . context_menu . addAction ( action ) self . context_menu . addSeparator ( ) action = self . action_collapse_all = QtWidgets . QAction ( _ ( 'Collapse all' ) , self . context_menu ) action . setShortcut ( 'Ctrl+Shift+-' ) action . triggered . connect ( self . _on_action_collapse_all_triggered ) self . context_menu . addAction ( action ) action = self . action_expand_all = QtWidgets . QAction ( _ ( 'Expand all' ) , self . context_menu ) action . setShortcut ( 'Ctrl+Shift++' ) action . triggered . connect ( self . _on_action_expand_all_triggered ) self . context_menu . addAction ( action ) self . editor . add_menu ( self . context_menu ) | Add the folding menu to the editor on install . |
46,328 | def _draw_rect ( self , rect , painter ) : c = self . _custom_color if self . _native : c = self . get_system_bck_color ( ) grad = QtGui . QLinearGradient ( rect . topLeft ( ) , rect . topRight ( ) ) if sys . platform == 'darwin' : grad . setColorAt ( 0 , c . lighter ( 100 ) ) grad . setColorAt ( 1 , c . lighter ( 110 ) ) outline = c . darker ( 110 ) else : grad . setColorAt ( 0 , c . lighter ( 110 ) ) grad . setColorAt ( 1 , c . lighter ( 130 ) ) outline = c . darker ( 100 ) painter . fillRect ( rect , grad ) painter . setPen ( QtGui . QPen ( outline ) ) painter . drawLine ( rect . topLeft ( ) + QtCore . QPointF ( 1 , 0 ) , rect . topRight ( ) - QtCore . QPointF ( 1 , 0 ) ) painter . drawLine ( rect . bottomLeft ( ) + QtCore . QPointF ( 1 , 0 ) , rect . bottomRight ( ) - QtCore . QPointF ( 1 , 0 ) ) painter . drawLine ( rect . topRight ( ) + QtCore . QPointF ( 0 , 1 ) , rect . bottomRight ( ) - QtCore . QPointF ( 0 , 1 ) ) painter . drawLine ( rect . topLeft ( ) + QtCore . QPointF ( 0 , 1 ) , rect . bottomLeft ( ) - QtCore . QPointF ( 0 , 1 ) ) | Draw the background rectangle using the current style primitive color or foldIndicatorBackground if nativeFoldingIndicator is true . |
46,329 | def get_system_bck_color ( ) : def merged_colors ( colorA , colorB , factor ) : maxFactor = 100 colorA = QtGui . QColor ( colorA ) colorB = QtGui . QColor ( colorB ) tmp = colorA tmp . setRed ( ( tmp . red ( ) * factor ) / maxFactor + ( colorB . red ( ) * ( maxFactor - factor ) ) / maxFactor ) tmp . setGreen ( ( tmp . green ( ) * factor ) / maxFactor + ( colorB . green ( ) * ( maxFactor - factor ) ) / maxFactor ) tmp . setBlue ( ( tmp . blue ( ) * factor ) / maxFactor + ( colorB . blue ( ) * ( maxFactor - factor ) ) / maxFactor ) return tmp pal = QtWidgets . QApplication . instance ( ) . palette ( ) b = pal . window ( ) . color ( ) h = pal . highlight ( ) . color ( ) return merged_colors ( b , h , 50 ) | Gets a system color for drawing the fold scope background . |
46,330 | def _add_scope_decorations ( self , block , start , end ) : try : parent = FoldScope ( block ) . parent ( ) except ValueError : parent = None if TextBlockHelper . is_fold_trigger ( block ) : base_color = self . _get_scope_highlight_color ( ) factor_step = 5 if base_color . lightness ( ) < 128 : factor_step = 10 factor = 70 else : factor = 100 while parent : parent_start , parent_end = parent . get_range ( ) self . _add_scope_deco ( start , end + 1 , parent_start , parent_end , base_color , factor ) start = parent_start end = parent_end parent = parent . parent ( ) factor += factor_step parent_start = 0 parent_end = self . editor . document ( ) . blockCount ( ) self . _add_scope_deco ( start , end + 1 , parent_start , parent_end , base_color , factor + factor_step ) else : self . _clear_scope_decos ( ) | Show a scope decoration on the editor widget |
46,331 | def _highlight_surrounding_scopes ( self , block ) : scope = FoldScope ( block ) if ( self . _current_scope is None or self . _current_scope . get_range ( ) != scope . get_range ( ) ) : self . _current_scope = scope self . _clear_scope_decos ( ) start , end = scope . get_range ( ) if not TextBlockHelper . is_collapsed ( block ) : self . _add_scope_decorations ( block , start , end ) | Highlights the scopes surrounding the current fold scope . |
46,332 | def leaveEvent ( self , event ) : super ( FoldingPanel , self ) . leaveEvent ( event ) QtWidgets . QApplication . restoreOverrideCursor ( ) self . _highlight_runner . cancel_requests ( ) if not self . highlight_caret_scope : self . _clear_scope_decos ( ) self . _mouse_over_line = None self . _current_scope = None else : self . _block_nbr = - 1 self . _highlight_caret_scope ( ) self . editor . repaint ( ) | Removes scope decorations and background from the editor and the panel if highlight_caret_scope else simply update the scope decorations to match the caret scope . |
46,333 | def verify_signature ( self , payload , headers ) : github_signature = headers . get ( "x-hub-signature" ) if not github_signature : json_abort ( 401 , "X-Hub-Signature header missing." ) gh_webhook_secret = current_app . config [ "GITHUB_WEBHOOK_SECRET" ] signature = "sha1={}" . format ( hmac . new ( gh_webhook_secret . encode ( "utf-8" ) , payload , hashlib . sha1 ) . hexdigest ( ) ) if not hmac . compare_digest ( signature , github_signature ) : json_abort ( 401 , "Request signature does not match calculated signature." ) | Verify that the payload was sent from our GitHub instance . |
46,334 | def get_options ( self ) : ( options , args ) = self . parser . parse_args ( ) visdkrc_opts = self . read_visdkrc ( ) for opt in self . config_vars : if not getattr ( options , opt ) : if visdkrc_opts : if opt in visdkrc_opts : setattr ( options , opt , visdkrc_opts [ opt ] ) for opt in self . required_opts : if opt not in dir ( options ) or getattr ( options , opt ) == None : self . parser . error ( '%s must be set!' % opt ) return options | Get the options that have been set . |
46,335 | def parse_job_files ( self ) : repo_jobs = [ ] for rel_job_file_path , job_info in self . job_files . items ( ) : LOGGER . debug ( "Checking for job definitions in %s" , rel_job_file_path ) jobs = self . parse_job_definitions ( rel_job_file_path , job_info ) LOGGER . debug ( "Found %d job definitions in %s" , len ( jobs ) , rel_job_file_path ) repo_jobs . extend ( jobs ) if not repo_jobs : LOGGER . info ( "No job definitions found in repo '%s'" , self . repo ) else : LOGGER . info ( "Found %d job definitions in repo '%s'" , len ( repo_jobs ) , self . repo ) return repo_jobs | Check for job definitions in known zuul files . |
46,336 | def change_directory ( self , directory ) : self . _process . write ( ( 'cd %s\n' % directory ) . encode ( ) ) if sys . platform == 'win32' : self . _process . write ( ( os . path . splitdrive ( directory ) [ 0 ] + '\r\n' ) . encode ( ) ) self . clear ( ) else : self . _process . write ( b'\x0C' ) | Changes the current directory . |
46,337 | def icon ( self ) : if isinstance ( self . _icon , str ) : if QtGui . QIcon . hasThemeIcon ( self . _icon ) : return QtGui . QIcon . fromTheme ( self . _icon ) else : return QtGui . QIcon ( self . _icon ) elif isinstance ( self . _icon , tuple ) : return QtGui . QIcon . fromTheme ( self . _icon [ 0 ] , QtGui . QIcon ( self . _icon [ 1 ] ) ) elif isinstance ( self . _icon , QtGui . QIcon ) : return self . _icon return QtGui . QIcon ( ) | Gets the icon file name . Read - only . |
46,338 | def add_marker ( self , marker ) : self . _markers . append ( marker ) doc = self . editor . document ( ) assert isinstance ( doc , QtGui . QTextDocument ) block = doc . findBlockByLineNumber ( marker . _position ) marker . block = block d = TextDecoration ( block ) d . set_full_width ( ) if self . _background : d . set_background ( QtGui . QBrush ( self . _background ) ) marker . decoration = d self . editor . decorations . append ( d ) self . repaint ( ) | Adds the marker to the panel . |
46,339 | def remove_marker ( self , marker ) : self . _markers . remove ( marker ) self . _to_remove . append ( marker ) if hasattr ( marker , 'decoration' ) : self . editor . decorations . remove ( marker . decoration ) self . repaint ( ) | Removes a marker from the panel |
46,340 | def _display_tooltip ( self , tooltip , top ) : QtWidgets . QToolTip . showText ( self . mapToGlobal ( QtCore . QPoint ( self . sizeHint ( ) . width ( ) , top ) ) , tooltip , self ) | Display tooltip at the specified top position . |
46,341 | def finditer_noregex ( string , sub , whole_word ) : start = 0 while True : start = string . find ( sub , start ) if start == - 1 : return if whole_word : if start : pchar = string [ start - 1 ] else : pchar = ' ' try : nchar = string [ start + len ( sub ) ] except IndexError : nchar = ' ' if nchar in DocumentWordsProvider . separators and pchar in DocumentWordsProvider . separators : yield start start += len ( sub ) else : yield start start += 1 | Search occurrences using str . find instead of regular expressions . |
46,342 | def complete ( self , code , * args ) : completions = [ ] for word in self . split ( code , self . separators ) : completions . append ( { 'name' : word } ) return completions | Provides completions based on the document words . |
46,343 | def status_to_string ( cls , status ) : strings = { CheckerMessages . INFO : "Info" , CheckerMessages . WARNING : "Warning" , CheckerMessages . ERROR : "Error" } return strings [ status ] | Converts a message status to a string . |
46,344 | def add_messages ( self , messages ) : if len ( messages ) > self . limit : messages = messages [ : self . limit ] _logger ( self . __class__ ) . log ( 5 , 'adding %s messages' % len ( messages ) ) self . _finished = False self . _new_messages = messages self . _to_check = list ( self . _messages ) self . _pending_msg = messages QtCore . QTimer . singleShot ( 1 , self . _remove_batch ) | Adds a message or a list of message . |
46,345 | def remove_message ( self , message ) : import time _logger ( self . __class__ ) . log ( 5 , 'removing message %s' % message ) t = time . time ( ) usd = message . block . userData ( ) if usd : try : usd . messages . remove ( message ) except ( AttributeError , ValueError ) : pass if message . decoration : self . editor . decorations . remove ( message . decoration ) self . _messages . remove ( message ) | Removes a message . |
46,346 | def clear_messages ( self ) : while len ( self . _messages ) : msg = self . _messages . pop ( 0 ) usd = msg . block . userData ( ) if usd and hasattr ( usd , 'messages' ) : usd . messages [ : ] = [ ] if msg . decoration : self . editor . decorations . remove ( msg . decoration ) | Clears all messages . |
46,347 | def _on_work_finished ( self , results ) : messages = [ ] for msg in results : msg = CheckerMessage ( * msg ) if msg . line >= self . editor . blockCount ( ) : msg . line = self . editor . blockCount ( ) - 1 block = self . editor . document ( ) . findBlockByNumber ( msg . line ) msg . block = block messages . append ( msg ) self . add_messages ( messages ) | Display results . |
46,348 | def request_analysis ( self ) : if self . _finished : _logger ( self . __class__ ) . log ( 5 , 'running analysis' ) self . _job_runner . request_job ( self . _request ) elif self . editor : _logger ( self . __class__ ) . log ( 5 , 'delaying analysis (previous analysis not finished)' ) QtCore . QTimer . singleShot ( 500 , self . request_analysis ) | Requests an analysis . |
46,349 | def _request ( self ) : try : self . editor . toPlainText ( ) except ( TypeError , RuntimeError ) : return try : max_line_length = self . editor . modes . get ( 'RightMarginMode' ) . position except KeyError : max_line_length = 79 request_data = { 'code' : self . editor . toPlainText ( ) , 'path' : self . editor . file . path , 'encoding' : self . editor . file . encoding , 'ignore_rules' : self . ignore_rules , 'max_line_length' : max_line_length , } try : self . editor . backend . send_request ( self . _worker , request_data , on_receive = self . _on_work_finished ) self . _finished = False except NotRunning : QtCore . QTimer . singleShot ( 100 , self . _request ) | Requests a checking of the editor content . |
46,350 | def _writen ( fd , data ) : while data : n = os . write ( fd , data ) data = data [ n : ] | Write all the data to a descriptor . |
46,351 | def flush_cache ( self , properties = None ) : if hasattr ( self , '_cache' ) : if properties is None : del ( self . _cache ) else : for prop in properties : if prop in self . _cache : del ( self . _cache [ prop ] ) | Flushes the cache being held for this instance . |
46,352 | def update ( self , properties = None ) : if properties is None : try : self . update_view_data ( properties = list ( self . _cache . keys ( ) ) ) except AttributeError : pass else : self . update_view_data ( properties = properties ) | Updates the properties being held for this instance . |
46,353 | def preload ( self , name , properties = None ) : if properties is None : raise ValueError ( "You must specify some properties to preload. To" " preload all properties use the string \"all\"." ) if not getattr ( self , name ) : return mo_refs = [ ] for item in getattr ( self , name ) : if isinstance ( item , ManagedObject ) is False : raise ValueError ( "Only ManagedObject's can be pre-loaded." ) mo_refs . append ( item . _mo_ref ) views = self . _client . get_views ( mo_refs , properties ) self . _cache [ name ] = ( views , time . time ( ) ) | Pre - loads the requested properties for each object in the name attribute . |
46,354 | def _set_view_data ( self , object_content ) : logger . info ( "Setting view data for a %s" , self . __class__ ) self . _object_content = object_content for dynprop in object_content . propSet : if dynprop . name not in self . _valid_attrs : logger . error ( "Server returned a property '%s' but the object" " hasn't defined it so it is being ignored." % dynprop . name ) continue try : if not len ( dynprop . val ) : logger . info ( "Server returned empty value for %s" , dynprop . name ) except TypeError : logger . info ( "%s of type %s has no len!" , dynprop . name , type ( dynprop . val ) ) pass try : cache = self . _cache except AttributeError : cache = self . _cache = { } if dynprop . val . __class__ . __name__ . startswith ( 'Array' ) : logger . info ( "Setting value of an Array* property" ) logger . debug ( "%s being set to %s" , dynprop . name , dynprop . val [ 0 ] ) now = time . time ( ) cache [ dynprop . name ] = ( dynprop . val [ 0 ] , now ) else : logger . info ( "Setting value of a single-valued property" ) logger . debug ( "DynamicProperty value is a %s: " , dynprop . val . __class__ . __name__ ) logger . debug ( "%s being set to %s" , dynprop . name , dynprop . val ) now = time . time ( ) cache [ dynprop . name ] = ( dynprop . val , now ) | Update the local object from the passed in object_content . |
46,355 | def _initialize_repo_cache ( ) : LOGGER . info ( "Initializing repository cache" ) repo_cache = { } for hit in GitRepo . search ( ) . query ( "match_all" ) . scan ( ) : repo_cache [ hit . repo_name ] = hit . to_dict ( skip_empty = False ) return repo_cache | Initialize the repository cache used for scraping . |
46,356 | def main ( options ) : client = Client ( server = options . server , username = options . username , password = options . password ) print ( 'Successfully connected to %s' % client . server ) lm_info = client . sc . licenseManager . QuerySupportedFeatures ( ) for feature in lm_info : print ( '%s: %s' % ( feature . featureName , feature . state ) ) client . logout ( ) | Obtains supported features from the license manager |
46,357 | def append ( self , mode ) : _logger ( ) . log ( 5 , 'adding mode %r' , mode . name ) self . _modes [ mode . name ] = mode mode . on_install ( self . editor ) return mode | Adds a mode to the editor . |
46,358 | def remove ( self , name_or_klass ) : _logger ( ) . log ( 5 , 'removing mode %r' , name_or_klass ) mode = self . get ( name_or_klass ) mode . on_uninstall ( ) self . _modes . pop ( mode . name ) return mode | Removes a mode from the editor . |
46,359 | def append ( self , decoration ) : if decoration not in self . _decorations : self . _decorations . append ( decoration ) self . _decorations = sorted ( self . _decorations , key = lambda sel : sel . draw_order ) self . editor . setExtraSelections ( self . _decorations ) return True return False | Adds a text decoration on a CodeEdit instance |
46,360 | def clear ( self ) : self . _decorations [ : ] = [ ] try : self . editor . setExtraSelections ( self . _decorations ) except RuntimeError : pass | Removes all text decoration from the editor . |
46,361 | def _on_key_pressed ( self , event ) : if ( int ( event . modifiers ( ) ) & QtCore . Qt . ControlModifier > 0 and not int ( event . modifiers ( ) ) & QtCore . Qt . ShiftModifier ) : if event . key ( ) == QtCore . Qt . Key_0 : self . editor . reset_zoom ( ) event . accept ( ) if event . key ( ) == QtCore . Qt . Key_Plus : self . editor . zoom_in ( ) event . accept ( ) if event . key ( ) == QtCore . Qt . Key_Minus : self . editor . zoom_out ( ) event . accept ( ) | Resets editor font size to the default font size |
46,362 | def _on_wheel_event ( self , event ) : try : delta = event . angleDelta ( ) . y ( ) except AttributeError : delta = event . delta ( ) if int ( event . modifiers ( ) ) & QtCore . Qt . ControlModifier > 0 : if delta < self . prev_delta : self . editor . zoom_out ( ) event . accept ( ) else : self . editor . zoom_in ( ) event . accept ( ) | Increments or decrements editor fonts settings on mouse wheel event if ctrl modifier is on . |
46,363 | def set_writer ( self , writer ) : if self . _writer != writer and self . _writer : self . _writer = None if writer : self . _writer = writer | Changes the writer function to handle writing to the text edit . |
46,364 | def start_process ( self , process , args = None , cwd = None , env = None ) : self . setReadOnly ( False ) if env is None : env = { } if args is None : args = [ ] if not self . _running : self . process = QProcess ( ) self . process . finished . connect ( self . _on_process_finished ) self . process . started . connect ( self . process_started . emit ) self . process . error . connect ( self . _write_error ) self . process . readyReadStandardError . connect ( self . _on_stderr ) self . process . readyReadStandardOutput . connect ( self . _on_stdout ) if cwd : self . process . setWorkingDirectory ( cwd ) e = self . process . systemEnvironment ( ) ev = QProcessEnvironment ( ) for v in e : values = v . split ( '=' ) ev . insert ( values [ 0 ] , '=' . join ( values [ 1 : ] ) ) for k , v in env . items ( ) : ev . insert ( k , v ) self . process . setProcessEnvironment ( ev ) self . _running = True self . _process_name = process self . _args = args if self . _clear_on_start : self . clear ( ) self . _user_stop = False self . _write_started ( ) self . process . start ( process , args ) self . process . waitForStarted ( ) else : _logger ( ) . warning ( 'a process is already running' ) | Starts a process interactively . |
46,365 | def write ( text_edit , text , color ) : try : text_edit . moveCursor ( QTextCursor . End ) text_edit . setTextColor ( color ) text_edit . insertPlainText ( text ) text_edit . moveCursor ( QTextCursor . End ) except RuntimeError : pass | Default write function . Move the cursor to the end and insert text with the specified color . |
46,366 | def apply_color_scheme ( self , color_scheme ) : self . stdout_color = color_scheme . formats [ 'normal' ] . foreground ( ) . color ( ) self . stdin_color = color_scheme . formats [ 'number' ] . foreground ( ) . color ( ) self . app_msg_color = color_scheme . formats [ 'string' ] . foreground ( ) . color ( ) self . background_color = color_scheme . background if self . background_color . lightness ( ) < 128 : self . stderr_color = QColor ( '#FF8080' ) else : self . stderr_color = QColor ( 'red' ) | Apply a pygments color scheme to the console . |
46,367 | def process_block ( self , current_block , previous_block , text ) : prev_fold_level = TextBlockHelper . get_fold_lvl ( previous_block ) if text . strip ( ) == '' : fold_level = prev_fold_level else : fold_level = self . detect_fold_level ( previous_block , current_block ) if fold_level > self . limit : fold_level = self . limit prev_fold_level = TextBlockHelper . get_fold_lvl ( previous_block ) if fold_level > prev_fold_level : block = current_block . previous ( ) while block . isValid ( ) and block . text ( ) . strip ( ) == '' : TextBlockHelper . set_fold_lvl ( block , fold_level ) block = block . previous ( ) TextBlockHelper . set_fold_trigger ( block , True ) if text . strip ( ) : TextBlockHelper . set_fold_trigger ( previous_block , fold_level > prev_fold_level ) TextBlockHelper . set_fold_lvl ( current_block , fold_level ) prev = current_block . previous ( ) if ( prev and prev . isValid ( ) and prev . text ( ) . strip ( ) == '' and TextBlockHelper . is_fold_trigger ( prev ) ) : TextBlockHelper . set_collapsed ( current_block , TextBlockHelper . is_collapsed ( prev ) ) TextBlockHelper . set_fold_trigger ( prev , False ) TextBlockHelper . set_collapsed ( prev , False ) | Processes a block and setup its folding info . |
46,368 | def read_config ( contents ) : file_obj = io . StringIO ( contents ) config = six . moves . configparser . ConfigParser ( ) config . readfp ( file_obj ) return config | Reads pylintrc config into native ConfigParser object . |
46,369 | def load_local_config ( filename ) : if not filename : return imp . new_module ( 'local_pylint_config' ) module = imp . load_source ( 'local_pylint_config' , filename ) return module | Loads the pylint . config . py file . |
46,370 | def determine_final_config ( config_module ) : config = Config ( DEFAULT_LIBRARY_RC_ADDITIONS , DEFAULT_LIBRARY_RC_REPLACEMENTS , DEFAULT_TEST_RC_ADDITIONS , DEFAULT_TEST_RC_REPLACEMENTS ) for field in config . _fields : if hasattr ( config_module , field ) : config = config . _replace ( ** { field : getattr ( config_module , field ) } ) return config | Determines the final additions and replacements . |
46,371 | def lint_fileset ( * dirnames , ** kwargs ) : try : rc_filename = kwargs [ 'rc_filename' ] description = kwargs [ 'description' ] if len ( kwargs ) != 2 : raise KeyError except KeyError : raise KeyError ( _LINT_FILESET_MSG ) pylint_shell_command = [ 'pylint' , '--rcfile' , rc_filename ] pylint_shell_command . extend ( dirnames ) status_code = subprocess . call ( pylint_shell_command ) if status_code != 0 : error_message = _ERROR_TEMPLATE . format ( description , status_code ) print ( error_message , file = sys . stderr ) sys . exit ( status_code ) | Lints a group of files using a given rcfile . |
46,372 | def make_rc ( base_cfg , target_filename , additions = None , replacements = None ) : if additions is None : additions = { } if replacements is None : replacements = { } new_cfg = six . moves . configparser . ConfigParser ( ) new_cfg . _sections = copy . deepcopy ( base_cfg . _sections ) new_sections = new_cfg . _sections for section , opts in additions . items ( ) : curr_section = new_sections . setdefault ( section , collections . OrderedDict ( ) ) for opt , opt_val in opts . items ( ) : curr_val = curr_section . get ( opt ) if curr_val is None : msg = _MISSING_OPTION_ADDITION . format ( opt ) raise KeyError ( msg ) curr_val = curr_val . rstrip ( ',' ) opt_val = _transform_opt ( opt_val ) curr_section [ opt ] = '%s, %s' % ( curr_val , opt_val ) for section , opts in replacements . items ( ) : curr_section = new_sections . setdefault ( section , collections . OrderedDict ( ) ) for opt , opt_val in opts . items ( ) : curr_val = curr_section . get ( opt ) if curr_val is None : msg = _MISSING_OPTION_REPLACE . format ( opt ) print ( msg , file = sys . stderr ) opt_val = _transform_opt ( opt_val ) curr_section [ opt ] = '%s' % ( opt_val , ) with open ( target_filename , 'w' ) as file_obj : new_cfg . write ( file_obj ) | Combines a base rc and additions into single file . |
46,373 | def run_command ( args ) : library_rc = 'pylintrc' test_rc = 'pylintrc.test' if os . path . exists ( library_rc ) : os . remove ( library_rc ) if os . path . exists ( test_rc ) : os . remove ( test_rc ) default_config = read_config ( get_default_config ( ) ) user_config = load_local_config ( args . config ) configuration = determine_final_config ( user_config ) make_rc ( default_config , library_rc , additions = configuration . library_additions , replacements = configuration . library_replacements ) make_rc ( default_config , test_rc , additions = configuration . test_additions , replacements = configuration . test_replacements ) lint_fileset ( * args . library_filesets , rc_filename = library_rc , description = 'Library' ) lint_fileset ( * args . test_filesets , rc_filename = test_rc , description = 'Test' ) | Script entry point . Lints both sets of files . |
46,374 | def login ( self , username = None , password = None ) : if username is None : username = self . username if password is None : password = self . password logger . debug ( "Logging into server" ) self . sc . sessionManager . Login ( userName = username , password = password ) self . _logged_in = True | Login to a vSphere server . |
46,375 | def logout ( self ) : if self . _logged_in is True : self . si . flush_cache ( ) self . sc . sessionManager . Logout ( ) self . _logged_in = False | Logout of a vSphere server . |
46,376 | def invoke ( self , method , _this , ** kwargs ) : if ( self . _logged_in is False and method not in [ "Login" , "RetrieveServiceContent" ] ) : logger . critical ( "Cannot exec %s unless logged in" , method ) raise NotLoggedInError ( "Cannot exec %s unless logged in" % method ) for kwarg in kwargs : kwargs [ kwarg ] = self . _marshal ( kwargs [ kwarg ] ) result = getattr ( self . service , method ) ( _this = _this , ** kwargs ) if hasattr ( result , '__iter__' ) is False : logger . debug ( "Returning non-iterable result" ) return result logger . debug ( result . __class__ ) logger . debug ( "Result: %s" , result ) logger . debug ( "Length: %s" , len ( result ) ) if type ( result ) == list : new_result = [ ] for item in result : new_result . append ( self . _unmarshal ( item ) ) else : new_result = self . _unmarshal ( result ) logger . debug ( "Finished in invoke." ) return new_result | Invoke a method on the server . |
46,377 | def _mor_to_pobject ( self , mo_ref ) : kls = classmapper ( mo_ref . _type ) new_object = kls ( mo_ref , self ) return new_object | Converts a MOR to a psphere object . |
46,378 | def _marshal ( self , obj ) : logger . debug ( "Checking if %s needs to be marshalled" , obj ) if isinstance ( obj , ManagedObject ) : logger . debug ( "obj is a psphere object, converting to MOR" ) return obj . _mo_ref if isinstance ( obj , list ) : logger . debug ( "obj is a list, recursing it" ) new_list = [ ] for item in obj : new_list . append ( self . _marshal ( item ) ) return new_list if not isinstance ( obj , suds . sudsobject . Object ) : logger . debug ( "%s is not a sudsobject subclass, skipping" , obj ) return obj if hasattr ( obj , '__iter__' ) : logger . debug ( "obj is iterable, recursing it" ) for ( name , value ) in obj : setattr ( obj , name , self . _marshal ( value ) ) return obj logger . debug ( "obj doesn't need to be marshalled" ) return obj | Walks an object and marshals any psphere object into MORs . |
46,379 | def _unmarshal ( self , obj ) : if isinstance ( obj , suds . sudsobject . Object ) is False : logger . debug ( "%s is not a suds instance, skipping" , obj ) return obj logger . debug ( "Processing:" ) logger . debug ( obj ) logger . debug ( "...with keylist:" ) logger . debug ( obj . __keylist__ ) if "_type" in obj . __keylist__ : logger . debug ( "obj is a MOR, converting to psphere class" ) return self . _mor_to_pobject ( obj ) new_object = obj . __class__ ( ) for sub_obj in obj : logger . debug ( "Looking at %s of type %s" , sub_obj , type ( sub_obj ) ) if isinstance ( sub_obj [ 1 ] , list ) : new_embedded_objs = [ ] for emb_obj in sub_obj [ 1 ] : new_emb_obj = self . _unmarshal ( emb_obj ) new_embedded_objs . append ( new_emb_obj ) setattr ( new_object , sub_obj [ 0 ] , new_embedded_objs ) continue if not issubclass ( sub_obj [ 1 ] . __class__ , suds . sudsobject . Object ) : logger . debug ( "%s is not a sudsobject subclass, skipping" , sub_obj [ 1 ] . __class__ ) setattr ( new_object , sub_obj [ 0 ] , sub_obj [ 1 ] ) continue logger . debug ( "Obj keylist: %s" , sub_obj [ 1 ] . __keylist__ ) if "_type" in sub_obj [ 1 ] . __keylist__ : logger . debug ( "Converting nested MOR to psphere class:" ) logger . debug ( sub_obj [ 1 ] ) kls = classmapper ( sub_obj [ 1 ] . _type ) logger . debug ( "Setting %s.%s to %s" , new_object . __class__ . __name__ , sub_obj [ 0 ] , sub_obj [ 1 ] ) setattr ( new_object , sub_obj [ 0 ] , kls ( sub_obj [ 1 ] , self ) ) else : logger . debug ( "Didn't find _type in:" ) logger . debug ( sub_obj [ 1 ] ) setattr ( new_object , sub_obj [ 0 ] , self . _unmarshal ( sub_obj [ 1 ] ) ) return new_object | Walks an object and unmarshals any MORs into psphere objects . |
46,380 | def create ( self , type_ , ** kwargs ) : obj = self . factory . create ( "ns0:%s" % type_ ) for key , value in kwargs . items ( ) : setattr ( obj , key , value ) return obj | Create a SOAP object of the requested type . |
46,381 | def get_views ( self , mo_refs , properties = None ) : property_specs = [ ] for mo_ref in mo_refs : property_spec = self . create ( 'PropertySpec' ) property_spec . type = str ( mo_ref . _type ) if properties is None : properties = [ ] else : if properties == "all" : property_spec . all = True else : property_spec . all = False property_spec . pathSet = properties property_specs . append ( property_spec ) object_specs = [ ] for mo_ref in mo_refs : object_spec = self . create ( 'ObjectSpec' ) object_spec . obj = mo_ref object_specs . append ( object_spec ) pfs = self . create ( 'PropertyFilterSpec' ) pfs . propSet = property_specs pfs . objectSet = object_specs object_contents = self . sc . propertyCollector . RetrieveProperties ( specSet = pfs ) views = [ ] for object_content in object_contents : object_content . obj . _set_view_data ( object_content = object_content ) views . append ( object_content . obj ) return views | Get a list of local view s for multiple managed objects . |
46,382 | def get_search_filter_spec ( self , begin_entity , property_spec ) : ss_strings = [ 'resource_pool_traversal_spec' , 'resource_pool_vm_traversal_spec' , 'folder_traversal_spec' , 'datacenter_host_traversal_spec' , 'datacenter_vm_traversal_spec' , 'compute_resource_rp_traversal_spec' , 'compute_resource_host_traversal_spec' , 'host_vm_traversal_spec' , 'datacenter_datastore_traversal_spec' ] selection_specs = [ self . create ( 'SelectionSpec' , name = ss_string ) for ss_string in ss_strings ] rpts = self . create ( 'TraversalSpec' ) rpts . name = 'resource_pool_traversal_spec' rpts . type = 'ResourcePool' rpts . path = 'resourcePool' rpts . selectSet = [ selection_specs [ 0 ] , selection_specs [ 1 ] ] rpvts = self . create ( 'TraversalSpec' ) rpvts . name = 'resource_pool_vm_traversal_spec' rpvts . type = 'ResourcePool' rpvts . path = 'vm' crrts = self . create ( 'TraversalSpec' ) crrts . name = 'compute_resource_rp_traversal_spec' crrts . type = 'ComputeResource' crrts . path = 'resourcePool' crrts . selectSet = [ selection_specs [ 0 ] , selection_specs [ 1 ] ] crhts = self . create ( 'TraversalSpec' ) crhts . name = 'compute_resource_host_traversal_spec' crhts . type = 'ComputeResource' crhts . path = 'host' dhts = self . create ( 'TraversalSpec' ) dhts . name = 'datacenter_host_traversal_spec' dhts . type = 'Datacenter' dhts . path = 'hostFolder' dhts . selectSet = [ selection_specs [ 2 ] ] dsts = self . create ( 'TraversalSpec' ) dsts . name = 'datacenter_datastore_traversal_spec' dsts . type = 'Datacenter' dsts . path = 'datastoreFolder' dsts . selectSet = [ selection_specs [ 2 ] ] dvts = self . create ( 'TraversalSpec' ) dvts . name = 'datacenter_vm_traversal_spec' dvts . type = 'Datacenter' dvts . path = 'vmFolder' dvts . selectSet = [ selection_specs [ 2 ] ] hvts = self . create ( 'TraversalSpec' ) hvts . name = 'host_vm_traversal_spec' hvts . type = 'HostSystem' hvts . path = 'vm' hvts . selectSet = [ selection_specs [ 2 ] ] fts = self . create ( 'TraversalSpec' ) fts . name = 'folder_traversal_spec' fts . type = 'Folder' fts . path = 'childEntity' fts . selectSet = [ selection_specs [ 2 ] , selection_specs [ 3 ] , selection_specs [ 4 ] , selection_specs [ 5 ] , selection_specs [ 6 ] , selection_specs [ 7 ] , selection_specs [ 1 ] , selection_specs [ 8 ] ] obj_spec = self . create ( 'ObjectSpec' ) obj_spec . obj = begin_entity obj_spec . selectSet = [ fts , dvts , dhts , crhts , crrts , rpts , hvts , rpvts , dsts ] pfs = self . create ( 'PropertyFilterSpec' ) pfs . propSet = [ property_spec ] pfs . objectSet = [ obj_spec ] return pfs | Build a PropertyFilterSpec capable of full inventory traversal . By specifying all valid traversal specs we are creating a PFS that can recursively select any object under the given entity . |
46,383 | def find_entity_views ( self , view_type , begin_entity = None , properties = None ) : if properties is None : properties = [ ] if not begin_entity : begin_entity = self . sc . rootFolder . _mo_ref property_spec = self . create ( 'PropertySpec' ) property_spec . type = view_type property_spec . all = False property_spec . pathSet = properties pfs = self . get_search_filter_spec ( begin_entity , property_spec ) obj_contents = self . sc . propertyCollector . RetrieveProperties ( specSet = pfs ) views = [ ] for obj_content in obj_contents : logger . debug ( "In find_entity_view with object of type %s" , obj_content . obj . __class__ . __name__ ) obj_content . obj . update_view_data ( properties = properties ) views . append ( obj_content . obj ) return views | Find all ManagedEntity s of the requested type . |
46,384 | def find_entity_view ( self , view_type , begin_entity = None , filter = { } , properties = None ) : if properties is None : properties = [ ] kls = classmapper ( view_type ) if not begin_entity : begin_entity = self . sc . rootFolder . _mo_ref logger . debug ( "Using %s" , self . sc . rootFolder . _mo_ref ) property_spec = self . create ( 'PropertySpec' ) property_spec . type = view_type property_spec . all = False property_spec . pathSet = list ( filter . keys ( ) ) pfs = self . get_search_filter_spec ( begin_entity , property_spec ) obj_contents = self . sc . propertyCollector . RetrieveProperties ( specSet = pfs ) if not filter : logger . warning ( 'No filter specified, returning first match.' ) logger . debug ( "Creating class in find_entity_view (filter)" ) view = kls ( obj_contents [ 0 ] . obj . _mo_ref , self ) logger . debug ( "Completed creating class in find_entity_view (filter)" ) return view matched = False for obj_content in obj_contents : if not obj_content . propSet : continue matches = 0 for prop in obj_content . propSet : for key in filter . keys ( ) : if prop . name == key : if prop . val == filter [ prop . name ] : matches += 1 else : break else : continue if matches == len ( filter ) : filtered_obj_content = obj_content matched = True break else : continue if matched is not True : raise ObjectNotFoundError ( "No matching objects for filter" ) logger . debug ( "Creating class in find_entity_view" ) view = kls ( filtered_obj_content . obj . _mo_ref , self ) logger . debug ( "Completed creating class in find_entity_view" ) return view | Find a ManagedEntity of the requested type . |
46,385 | def load_template ( name = None ) : if name is None : name = "default" logger . info ( "Loading template with name %s" , name ) try : template_file = open ( "%s/%s.yaml" % ( template_path , name ) ) except IOError : raise TemplateNotFoundError template = yaml . safe_load ( template_file ) template_file . close ( ) if "extends" in template : logger . debug ( "Merging %s with %s" , name , template [ "extends" ] ) template = _merge ( load_template ( template [ "extends" ] ) , template ) return template | Loads a template of the specified name . |
46,386 | def list_templates ( ) : templates = [ f for f in glob . glob ( os . path . join ( template_path , '*.yaml' ) ) ] return templates | Returns a list of all templates . |
46,387 | def create_nic ( client , target , nic ) : for network in target . network : if network . name == nic [ "network_name" ] : net = network break else : return None backing = client . create ( "VirtualEthernetCardNetworkBackingInfo" ) backing . deviceName = nic [ "network_name" ] backing . network = net connect_info = client . create ( "VirtualDeviceConnectInfo" ) connect_info . allowGuestControl = True connect_info . connected = False connect_info . startConnected = True new_nic = client . create ( nic [ "type" ] ) new_nic . backing = backing new_nic . key = 2 new_nic . unitNumber = 1 new_nic . addressType = "generated" new_nic . connectable = connect_info nic_spec = client . create ( "VirtualDeviceConfigSpec" ) nic_spec . device = new_nic nic_spec . fileOperation = None operation = client . create ( "VirtualDeviceConfigSpecOperation" ) nic_spec . operation = ( operation . add ) return nic_spec | Return a NIC spec |
46,388 | def main ( name , options ) : server = config . _config_value ( "general" , "server" , options . server ) if server is None : raise ValueError ( "server must be supplied on command line" " or in configuration file." ) username = config . _config_value ( "general" , "username" , options . username ) if username is None : raise ValueError ( "username must be supplied on command line" " or in configuration file." ) password = config . _config_value ( "general" , "password" , options . password ) if password is None : raise ValueError ( "password must be supplied on command line" " or in configuration file." ) vm_template = None if options . template is not None : try : vm_template = template . load_template ( options . template ) except TemplateNotFoundError : print ( "ERROR: Template \"%s\" could not be found." % options . template ) sys . exit ( 1 ) expected_opts = [ "compute_resource" , "datastore" , "disksize" , "nics" , "memory" , "num_cpus" , "guest_id" , "host" ] vm_opts = { } for opt in expected_opts : vm_opts [ opt ] = getattr ( options , opt ) if vm_opts [ opt ] is None : if vm_template is None : raise ValueError ( "%s not specified on the command line and" " you have not specified any template to" " inherit the value from." % opt ) try : vm_opts [ opt ] = vm_template [ opt ] except AttributeError : raise ValueError ( "%s not specified on the command line and" " no value is provided in the specified" " template." % opt ) client = Client ( server = server , username = username , password = password ) create_vm ( client , name , vm_opts [ "compute_resource" ] , vm_opts [ "datastore" ] , vm_opts [ "disksize" ] , vm_opts [ "nics" ] , vm_opts [ "memory" ] , vm_opts [ "num_cpus" ] , vm_opts [ "guest_id" ] , host = vm_opts [ "host" ] ) client . logout ( ) | The main method for this script . |
46,389 | def add_ignore_patterns ( self , * patterns ) : for ptrn in patterns : if isinstance ( ptrn , list ) : for p in ptrn : self . _ignored_patterns . append ( p ) else : self . _ignored_patterns . append ( ptrn ) | Adds an ignore pattern to the list for ignore patterns . |
46,390 | def set_context_menu ( self , context_menu ) : self . context_menu = context_menu self . context_menu . tree_view = self self . context_menu . init_actions ( ) for action in self . context_menu . actions ( ) : self . addAction ( action ) | Sets the context menu of the tree view . |
46,391 | def filePath ( self , index ) : return self . _fs_model_source . filePath ( self . _fs_model_proxy . mapToSource ( index ) ) | Gets the file path of the item at the specified index . |
46,392 | def fileInfo ( self , index ) : return self . _fs_model_source . fileInfo ( self . _fs_model_proxy . mapToSource ( index ) ) | Gets the file info of the item at the specified index . |
46,393 | def paste_from_clipboard ( self ) : to = self . get_current_path ( ) if os . path . isfile ( to ) : to = os . path . abspath ( os . path . join ( to , os . pardir ) ) mime = QtWidgets . QApplication . clipboard ( ) . mimeData ( ) paste_operation = None if mime . hasFormat ( self . _UrlListMimeData . format ( copy = True ) ) : paste_operation = True elif mime . hasFormat ( self . _UrlListMimeData . format ( copy = False ) ) : paste_operation = False if paste_operation is not None : self . _paste ( self . _UrlListMimeData . list_from ( mime , copy = paste_operation ) , to , copy = paste_operation ) | Pastes files from clipboard . |
46,394 | def _paste ( self , sources , destination , copy ) : for src in sources : debug ( '%s <%s> to <%s>' % ( 'copying' if copy else 'cutting' , src , destination ) ) perform_copy = True ext = os . path . splitext ( src ) [ 1 ] original = os . path . splitext ( os . path . split ( src ) [ 1 ] ) [ 0 ] filename , status = QtWidgets . QInputDialog . getText ( self . tree_view , _ ( 'Copy' ) , _ ( 'New name:' ) , QtWidgets . QLineEdit . Normal , original ) if filename == '' or not status : return filename = filename + ext final_dest = os . path . join ( destination , filename ) if os . path . exists ( final_dest ) : rep = QtWidgets . QMessageBox . question ( self . tree_view , _ ( 'File exists' ) , _ ( 'File <%s> already exists. Do you want to erase it?' ) % final_dest , QtWidgets . QMessageBox . Yes | QtWidgets . QMessageBox . No , QtWidgets . QMessageBox . No ) if rep == QtWidgets . QMessageBox . No : perform_copy = False if not perform_copy : continue try : if os . path . isfile ( src ) : shutil . copy ( src , final_dest ) else : shutil . copytree ( src , final_dest ) except ( IOError , OSError ) as e : QtWidgets . QMessageBox . warning ( self . tree_view , _ ( 'Copy failed' ) , _ ( 'Failed to copy "%s" to "%s".\n\n%s' % ( src , destination , str ( e ) ) ) ) _logger ( ) . exception ( 'failed to copy "%s" to "%s' , src , destination ) else : debug ( 'file copied %s' , src ) if not copy : debug ( 'removing source (cut operation)' ) if os . path . isfile ( src ) : os . remove ( src ) else : shutil . rmtree ( src ) self . tree_view . files_renamed . emit ( [ ( src , final_dest ) ] ) | Copies the files listed in sources to destination . Source are removed if copy is set to False . |
46,395 | def delete ( self ) : urls = self . selected_urls ( ) rep = QtWidgets . QMessageBox . question ( self . tree_view , _ ( 'Confirm delete' ) , _ ( 'Are you sure about deleting the selected files/directories?' ) , QtWidgets . QMessageBox . Yes | QtWidgets . QMessageBox . No , QtWidgets . QMessageBox . Yes ) if rep == QtWidgets . QMessageBox . Yes : deleted_files = [ ] for fn in urls : try : if os . path . isfile ( fn ) : os . remove ( fn ) deleted_files . append ( fn ) else : files = self . _get_files ( fn ) shutil . rmtree ( fn ) deleted_files += files except OSError as e : QtWidgets . QMessageBox . warning ( self . tree_view , _ ( 'Delete failed' ) , _ ( 'Failed to remove "%s".\n\n%s' ) % ( fn , str ( e ) ) ) _logger ( ) . exception ( 'failed to remove %s' , fn ) self . tree_view . files_deleted . emit ( deleted_files ) for d in deleted_files : debug ( '%s removed' , d ) self . tree_view . file_deleted . emit ( os . path . normpath ( d ) ) | Deletes the selected items . |
46,396 | def get_current_path ( self ) : path = self . tree_view . fileInfo ( self . tree_view . currentIndex ( ) ) . filePath ( ) if not path : path = self . tree_view . root_path return path | Gets the path of the currently selected item . |
46,397 | def copy_path_to_clipboard ( self ) : path = self . get_current_path ( ) QtWidgets . QApplication . clipboard ( ) . setText ( path ) debug ( 'path copied: %s' % path ) | Copies the file path to the clipboard |
46,398 | def rename ( self ) : src = self . get_current_path ( ) pardir , name = os . path . split ( src ) new_name , status = QtWidgets . QInputDialog . getText ( self . tree_view , _ ( 'Rename ' ) , _ ( 'New name:' ) , QtWidgets . QLineEdit . Normal , name ) if status : dest = os . path . join ( pardir , new_name ) old_files = [ ] if os . path . isdir ( src ) : old_files = self . _get_files ( src ) else : old_files = [ src ] try : os . rename ( src , dest ) except OSError as e : QtWidgets . QMessageBox . warning ( self . tree_view , _ ( 'Rename failed' ) , _ ( 'Failed to rename "%s" into "%s".\n\n%s' ) % ( src , dest , str ( e ) ) ) else : if os . path . isdir ( dest ) : new_files = self . _get_files ( dest ) else : new_files = [ dest ] self . tree_view . file_renamed . emit ( os . path . normpath ( src ) , os . path . normpath ( dest ) ) renamed_files = [ ] for old_f , new_f in zip ( old_files , new_files ) : self . tree_view . file_renamed . emit ( old_f , new_f ) renamed_files . append ( ( old_f , new_f ) ) self . tree_view . files_renamed . emit ( renamed_files ) | Renames the selected item in the tree view |
46,399 | def create_file ( self ) : src = self . get_current_path ( ) name , status = QtWidgets . QInputDialog . getText ( self . tree_view , _ ( 'Create new file' ) , _ ( 'File name:' ) , QtWidgets . QLineEdit . Normal , '' ) if status : fatal_names = [ '.' , '..' , os . sep ] for i in fatal_names : if i == name : QtWidgets . QMessageBox . critical ( self . tree_view , _ ( "Error" ) , _ ( "Wrong directory name" ) ) return if os . path . isfile ( src ) : src = os . path . dirname ( src ) path = os . path . join ( src , name ) try : with open ( path , 'w' ) : pass except OSError as e : QtWidgets . QMessageBox . warning ( self . tree_view , _ ( 'Failed to create new file' ) , _ ( 'Failed to create file: "%s".\n\n%s' ) % ( path , str ( e ) ) ) else : self . tree_view . file_created . emit ( os . path . normpath ( path ) ) | Creates a file under the current directory . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.