idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
11,500 | async def clone ( self , token ) : token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/acl/clone" , token_id ) return consul ( response ) | Creates a new token by cloning an existing token | 57 | 10 |
11,501 | async def items ( self ) : response = await self . _api . get ( "/v1/acl/list" ) results = [ decode_token ( r ) for r in response . body ] return consul ( results , meta = extract_meta ( response . headers ) ) | Lists all the active tokens | 60 | 6 |
11,502 | async def replication ( self , * , dc = None ) : params = { "dc" : dc } response = await self . _api . get ( "/v1/acl/replication" , params = params ) return response . body | Checks status of ACL replication | 51 | 6 |
11,503 | def make_unique_endings ( strings_collection ) : res = [ ] for i in range ( len ( strings_collection ) ) : # NOTE(msdubov): a trick to handle 'narrow' python installation issues. hex_code = hex ( consts . String . UNICODE_SPECIAL_SYMBOLS_START + i ) hex_code = r"\U" + "0" * ( 8 - len ( hex_code ) + 2 ) + hex_code [ 2 : ] res . append ( strings_collection [ i ] + hex_code . decode ( "unicode-escape" ) ) return res | Make each string in the collection end with a unique character . Essential for correct builiding of a generalized annotated suffix tree . Returns the updated strings collection encoded in Unicode . | 139 | 35 |
11,504 | async def datacenters ( self ) : response = await self . _api . get ( "/v1/coordinate/datacenters" ) return { data [ "Datacenter" ] : data for data in response . body } | Queries for WAN coordinates of Consul servers | 51 | 10 |
11,505 | def resizeToContents ( self ) : if self . count ( ) : item = self . item ( self . count ( ) - 1 ) rect = self . visualItemRect ( item ) height = rect . bottom ( ) + 8 height = max ( 28 , height ) self . setFixedHeight ( height ) else : self . setFixedHeight ( self . minimumHeight ( ) ) | Resizes the list widget to fit its contents vertically . | 79 | 11 |
11,506 | def parse_status_file ( status_file , nas_addr ) : session_users = { } flag1 = False flag2 = False with open ( status_file ) as stlines : for line in stlines : if line . startswith ( "Common Name" ) : flag1 = True continue if line . startswith ( "ROUTING TABLE" ) : flag1 = False continue if line . startswith ( "Virtual Address" ) : flag2 = True continue if line . startswith ( "GLOBAL STATS" ) : flag2 = False continue if flag1 : try : username , realaddr , inbytes , outbytes , _ = line . split ( ',' ) realip , realport = realaddr . split ( ':' ) session_id = md5 ( nas_addr + realip + realport ) . hexdigest ( ) session_users . setdefault ( session_id , { } ) . update ( dict ( session_id = session_id , username = username , realip = realip , realport = realport , inbytes = inbytes , outbytes = outbytes ) ) except : traceback . print_exc ( ) if flag2 : try : userip , username , realaddr , _ = line . split ( ',' ) realip , realport = realaddr . split ( ':' ) session_id = md5 ( nas_addr + realip + realport ) . hexdigest ( ) session_users . setdefault ( session_id , { } ) . update ( dict ( session_id = session_id , username = username , realip = realip , realport = realport , userip = userip , ) ) except : traceback . print_exc ( ) return session_users | parse openvpn status log | 377 | 6 |
11,507 | def update_status ( dbfile , status_file , nas_addr ) : try : total = 0 params = [ ] for sid , su in parse_status_file ( status_file , nas_addr ) . items ( ) : if 'session_id' in su and 'inbytes' in su and 'outbytes' in su : params . append ( ( su [ 'inbytes' ] , su [ 'outbytes' ] , su [ 'session_id' ] ) ) total += 1 statusdb . batch_update_client ( dbfile , params ) log . msg ( 'update_status total = %s' % total ) except Exception , e : log . err ( 'batch update status error' ) log . err ( e ) | update status db | 159 | 3 |
11,508 | def accounting ( dbfile , config ) : try : nas_id = config . get ( 'DEFAULT' , 'nas_id' ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) secret = config . get ( 'DEFAULT' , 'radius_secret' ) radius_addr = config . get ( 'DEFAULT' , 'radius_addr' ) radius_acct_port = config . getint ( 'DEFAULT' , 'radius_acct_port' ) radius_timeout = config . getint ( 'DEFAULT' , 'radius_timeout' ) status_dbfile = config . get ( 'DEFAULT' , 'statusdb' ) clients = statusdb . query_client ( status_dbfile ) ctime = int ( time . time ( ) ) for cli in clients : if ( ctime - int ( cli [ 'uptime' ] ) ) < int ( cli [ 'acct_interval' ] ) : continue session_id = cli [ 'session_id' ] req = { 'User-Name' : cli [ 'username' ] } req [ 'Acct-Status-Type' ] = ACCT_UPDATE req [ 'Acct-Session-Id' ] = session_id req [ "Acct-Output-Octets" ] = int ( cli [ 'outbytes' ] ) req [ "Acct-Input-Octets" ] = int ( cli [ 'inbytes' ] ) req [ 'Acct-Session-Time' ] = ( ctime - int ( cli [ 'ctime' ] ) ) req [ "NAS-IP-Address" ] = nas_addr req [ "NAS-Port-Id" ] = '0/0/0:0.0' req [ "NAS-Port" ] = 0 req [ "Service-Type" ] = "Login-User" req [ "NAS-Identifier" ] = nas_id req [ "Called-Station-Id" ] = '00:00:00:00:00:00' req [ "Calling-Station-Id" ] = '00:00:00:00:00:00' req [ "Framed-IP-Address" ] = cli [ 'userip' ] def update_uptime ( radresp ) : statusdb . update_client_uptime ( status_dbfile , session_id ) log . msg ( 'online<%s> client accounting update' % session_id ) def onresp ( r ) : try : update_uptime ( r ) except Exception as e : log . err ( 'online update uptime error' ) log . err ( e ) d = client . send_acct ( str ( secret ) , get_dictionary ( ) , radius_addr , acctport = radius_acct_port , debug = True , * * req ) d . addCallbacks ( onresp , log . err ) except Exception , e : log . err ( 'accounting error' ) log . err ( e ) | update radius accounting | 659 | 3 |
11,509 | def main ( conf ) : config = init_config ( conf ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) status_file = config . get ( 'DEFAULT' , 'statusfile' ) status_dbfile = config . get ( 'DEFAULT' , 'statusdb' ) nas_coa_port = config . get ( 'DEFAULT' , 'nas_coa_port' ) def do_update_status_task ( ) : d = deferToThread ( update_status , status_dbfile , status_file , nas_addr ) d . addCallback ( log . msg , 'do_update_status_task done!' ) d . addErrback ( log . err ) reactor . callLater ( 60.0 , do_update_status_task ) def do_accounting_task ( ) : d = deferToThread ( accounting , status_dbfile , config ) d . addCallback ( log . msg , 'do_accounting_task done!' ) d . addErrback ( log . err ) reactor . callLater ( 60.0 , do_accounting_task ) do_update_status_task ( ) do_accounting_task ( ) coa_protocol = Authorized ( config ) reactor . listenUDP ( int ( nas_coa_port ) , coa_protocol , interface = '0.0.0.0' ) reactor . run ( ) | OpenVPN status daemon | 315 | 4 |
11,510 | def _filter_by_simple_schema ( self , qs , lookup , sublookup , value , schema ) : value_lookup = 'attrs__value_%s' % schema . datatype if sublookup : value_lookup = '%s__%s' % ( value_lookup , sublookup ) return { 'attrs__schema' : schema , str ( value_lookup ) : value } | Filters given entity queryset by an attribute which is linked to given schema and has given value in the field for schema s datatype . | 97 | 30 |
11,511 | def _filter_by_m2m_schema ( self , qs , lookup , sublookup , value , schema , model = None ) : model = model or self . model schemata = dict ( ( s . name , s ) for s in model . get_schemata_for_model ( ) ) # TODO cache this dict, see above too try : schema = schemata [ lookup ] except KeyError : # TODO: smarter error message, i.e. how could this happen and what to do raise ValueError ( u'Could not find schema for lookup "%s"' % lookup ) sublookup = '__%s' % sublookup if sublookup else '' return { 'attrs__schema' : schema , 'attrs__choice%s' % sublookup : value , # TODO: can we filter by id, not name? } | Filters given entity queryset by an attribute which is linked to given many - to - many schema . | 192 | 22 |
11,512 | def create ( self , * * kwargs ) : fields = self . model . _meta . get_all_field_names ( ) schemata = dict ( ( s . name , s ) for s in self . model . get_schemata_for_model ( ) ) # check if all attributes are known possible_names = set ( fields ) | set ( schemata . keys ( ) ) wrong_names = set ( kwargs . keys ( ) ) - possible_names if wrong_names : raise NameError ( 'Cannot create %s: unknown attribute(s) "%s". ' 'Available fields: (%s). Available schemata: (%s).' % ( self . model . _meta . object_name , '", "' . join ( wrong_names ) , ', ' . join ( fields ) , ', ' . join ( schemata ) ) ) # init entity with fields instance = self . model ( * * dict ( ( k , v ) for k , v in kwargs . items ( ) if k in fields ) ) # set attributes; instance will check schemata on save for name , value in kwargs . items ( ) : setattr ( instance , name , value ) # save instance and EAV attributes instance . save ( force_insert = True ) return instance | Creates entity instance and related Attr instances . | 281 | 10 |
11,513 | def removeProfile ( self ) : manager = self . parent ( ) prof = manager . currentProfile ( ) opts = QMessageBox . Yes | QMessageBox . No question = 'Are you sure you want to remove "%s"?' % prof . name ( ) answer = QMessageBox . question ( self , 'Remove Profile' , question , opts ) if ( answer == QMessageBox . Yes ) : manager . removeProfile ( prof ) | Removes the current profile from the system . | 94 | 9 |
11,514 | def saveProfile ( self ) : manager = self . parent ( ) prof = manager . currentProfile ( ) # save the current profile save_prof = manager . viewWidget ( ) . saveProfile ( ) prof . setXmlElement ( save_prof . xmlElement ( ) ) | Saves the current profile to the current settings from the view widget . | 58 | 14 |
11,515 | def saveProfileAs ( self ) : name , ok = QInputDialog . getText ( self , 'Create Profile' , 'Name:' ) if ( not name ) : return manager = self . parent ( ) prof = manager . viewWidget ( ) . saveProfile ( ) prof . setName ( nativestring ( name ) ) self . parent ( ) . addProfile ( prof ) | Saves the current profile as a new profile to the manager . | 81 | 13 |
11,516 | def hexdump ( logger , s , width = 16 , skip = True , hexii = False , begin = 0 , highlight = None ) : s = _flat ( s ) return '\n' . join ( hexdump_iter ( logger , StringIO ( s ) , width , skip , hexii , begin , highlight ) ) | r Return a hexdump - dump of a string . | 70 | 11 |
11,517 | def adjustText ( self ) : pos = self . cursorPosition ( ) self . blockSignals ( True ) super ( XLineEdit , self ) . setText ( self . formatText ( self . text ( ) ) ) self . setCursorPosition ( pos ) self . blockSignals ( False ) | Updates the text based on the current format options . | 64 | 11 |
11,518 | def adjustButtons ( self ) : y = 1 for btn in self . buttons ( ) : btn . setIconSize ( self . iconSize ( ) ) btn . setFixedSize ( QSize ( self . height ( ) - 2 , self . height ( ) - 2 ) ) # adjust the location for the left buttons left_buttons = self . _buttons . get ( Qt . AlignLeft , [ ] ) x = ( self . cornerRadius ( ) / 2.0 ) + 2 for btn in left_buttons : btn . move ( x , y ) x += btn . width ( ) # adjust the location for the right buttons right_buttons = self . _buttons . get ( Qt . AlignRight , [ ] ) w = self . width ( ) bwidth = sum ( [ btn . width ( ) for btn in right_buttons ] ) bwidth += ( self . cornerRadius ( ) / 2.0 ) + 1 for btn in right_buttons : btn . move ( w - bwidth , y ) bwidth -= btn . width ( ) self . _buttonWidth = sum ( [ btn . width ( ) for btn in self . buttons ( ) ] ) self . adjustTextMargins ( ) | Adjusts the placement of the buttons for this line edit . | 276 | 12 |
11,519 | def adjustTextMargins ( self ) : left_buttons = self . _buttons . get ( Qt . AlignLeft , [ ] ) if left_buttons : bwidth = left_buttons [ - 1 ] . pos ( ) . x ( ) + left_buttons [ - 1 ] . width ( ) - 4 else : bwidth = 0 + ( max ( 8 , self . cornerRadius ( ) ) - 8 ) ico = self . icon ( ) if ico and not ico . isNull ( ) : bwidth += self . iconSize ( ) . width ( ) self . setTextMargins ( bwidth , 0 , 0 , 0 ) | Adjusts the margins for the text based on the contents to be displayed . | 144 | 15 |
11,520 | def clear ( self ) : super ( XLineEdit , self ) . clear ( ) self . textEntered . emit ( '' ) self . textChanged . emit ( '' ) self . textEdited . emit ( '' ) | Clears the text from the edit . | 46 | 8 |
11,521 | def get ( cap , * args , * * kwargs ) : # Hack for readthedocs.org if 'READTHEDOCS' in os . environ : return '' if kwargs != { } : raise TypeError ( "get(): No such argument %r" % kwargs . popitem ( ) [ 0 ] ) if _cache == { } : # Fix for BPython try : curses . setupterm ( ) except : pass s = _cache . get ( cap ) if not s : s = curses . tigetstr ( cap ) if s == None : s = curses . tigetnum ( cap ) if s == - 2 : s = curses . tigetflag ( cap ) if s == - 1 : # default to empty string so tparm doesn't fail s = '' else : s = bool ( s ) _cache [ cap ] = s # if 's' is not set 'curses.tparm' will throw an error if given arguments if args and s : r = curses . tparm ( s , * args ) return r . decode ( 'utf-8' ) else : if isinstance ( s , bytes ) : return s . decode ( 'utf-8' ) else : return s | Get a terminal capability exposes through the curses module . | 268 | 10 |
11,522 | def registerThermostat ( self , thermostat ) : try : type ( thermostat ) == heatmiser . HeatmiserThermostat if thermostat . address in self . thermostats . keys ( ) : raise ValueError ( "Key already present" ) else : self . thermostats [ thermostat . address ] = thermostat except ValueError : pass except Exception as e : logging . info ( "You're not adding a HeatmiiserThermostat Object" ) logging . info ( e . message ) return self . _serport | Registers a thermostat with the UH1 | 120 | 11 |
11,523 | def refresh ( self ) : self . clear ( ) for i , filename in enumerate ( self . filenames ( ) ) : name = '%i. %s' % ( i + 1 , os . path . basename ( filename ) ) action = self . addAction ( name ) action . setData ( wrapVariant ( filename ) ) | Clears out the actions for this menu and then loads the files . | 74 | 14 |
11,524 | def values ( self , values ) : if isinstance ( values , dict ) : l = [ ] for column in self . _columns : l . append ( values [ column ] ) self . _values . append ( tuple ( l ) ) else : self . _values . append ( values ) return self | The values for insert it can be a dict row or list tuple row . | 64 | 15 |
11,525 | def adjustMinimumWidth ( self ) : pw = self . pixmapSize ( ) . width ( ) # allow 1 pixel space between the icons self . setMinimumWidth ( pw * self . maximum ( ) + 3 * self . maximum ( ) ) | Modifies the minimum width to factor in the size of the pixmaps and the number for the maximum . | 54 | 22 |
11,526 | def cli ( conf ) : config = init_config ( conf ) nas_id = config . get ( 'DEFAULT' , 'nas_id' ) secret = config . get ( 'DEFAULT' , 'radius_secret' ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) radius_addr = config . get ( 'DEFAULT' , 'radius_addr' ) radius_acct_port = config . getint ( 'DEFAULT' , 'radius_acct_port' ) radius_timeout = config . getint ( 'DEFAULT' , 'radius_timeout' ) status_dbfile = config . get ( 'DEFAULT' , 'statusdb' ) username = os . environ . get ( 'username' ) userip = os . environ . get ( 'ifconfig_pool_remote_ip' ) realip = os . environ . get ( 'trusted_ip' ) realport = os . environ . get ( 'trusted_port' ) session_id = md5 ( nas_addr + realip + realport ) . hexdigest ( ) req = { 'User-Name' : username } req [ 'Acct-Status-Type' ] = ACCT_STOP req [ 'Acct-Session-Id' ] = session_id req [ "Acct-Output-Octets" ] = 0 req [ "Acct-Input-Octets" ] = 0 req [ 'Acct-Session-Time' ] = 0 req [ "NAS-IP-Address" ] = nas_addr req [ "NAS-Port-Id" ] = '0/0/0:0.0' req [ "NAS-Port" ] = 0 req [ "Service-Type" ] = "Login-User" req [ "NAS-Identifier" ] = nas_id req [ "Called-Station-Id" ] = '00:00:00:00:00:00' req [ "Calling-Station-Id" ] = '00:00:00:00:00:00' req [ "Framed-IP-Address" ] = userip def shutdown ( exitcode = 0 ) : reactor . addSystemEventTrigger ( 'after' , 'shutdown' , os . _exit , exitcode ) reactor . stop ( ) def onresp ( r ) : try : statusdb . del_client ( status_dbfile , session_id ) log . msg ( 'delete online<%s> client from db' % session_id ) except Exception as e : log . err ( 'del client online error' ) log . err ( e ) shutdown ( 0 ) def onerr ( e ) : log . err ( e ) shutdown ( 1 ) d = client . send_acct ( str ( secret ) , get_dictionary ( ) , radius_addr , acctport = radius_acct_port , debug = True , * * req ) d . addCallbacks ( onresp , onerr ) reactor . callLater ( radius_timeout , shutdown , 1 ) reactor . run ( ) | OpenVPN client_disconnect method | 665 | 7 |
11,527 | def viewAt ( self , point ) : widget = self . childAt ( point ) if widget : return projexui . ancestor ( widget , XView ) else : return None | Looks up the view at the inputed point . | 38 | 10 |
11,528 | def draw ( canvas , mol ) : mol . require ( "ScaleAndCenter" ) mlb = mol . size2d [ 2 ] if not mol . atom_count ( ) : return bond_type_fn = { 1 : { 0 : single_bond , 1 : wedged_single , 2 : dashed_wedged_single , 3 : wave_single , } , 2 : { 0 : cw_double , 1 : counter_cw_double , 2 : double_bond , 3 : cross_double } , 3 : { 0 : triple_bond } } # Draw bonds for u , v , bond in mol . bonds_iter ( ) : if not bond . visible : continue if ( u < v ) == bond . is_lower_first : f , s = ( u , v ) else : s , f = ( u , v ) p1 = mol . atom ( f ) . coords p2 = mol . atom ( s ) . coords if p1 == p2 : continue # avoid zero division if mol . atom ( f ) . visible : p1 = gm . t_seg ( p1 , p2 , F_AOVL , 2 ) [ 0 ] if mol . atom ( s ) . visible : p2 = gm . t_seg ( p1 , p2 , F_AOVL , 1 ) [ 1 ] color1 = mol . atom ( f ) . color color2 = mol . atom ( s ) . color bond_type_fn [ bond . order ] [ bond . type ] ( canvas , p1 , p2 , color1 , color2 , mlb ) # Draw atoms for n , atom in mol . atoms_iter ( ) : if not atom . visible : continue p = atom . coords color = atom . color # Determine text direction if atom . H_count : cosnbrs = [ ] hrzn = ( p [ 0 ] + 1 , p [ 1 ] ) for nbr in mol . graph . neighbors ( n ) : pnbr = mol . atom ( nbr ) . coords try : cosnbrs . append ( gm . dot_product ( hrzn , pnbr , p ) / gm . distance ( p , pnbr ) ) except ZeroDivisionError : pass if not cosnbrs or min ( cosnbrs ) > 0 : # [atom]< or isolated node(ex. H2O, HCl) text = atom . formula_html ( True ) canvas . draw_text ( p , text , color , "right" ) continue elif max ( cosnbrs ) < 0 : # >[atom] text = atom . formula_html ( ) canvas . draw_text ( p , text , color , "left" ) continue # -[atom]- or no hydrogens text = atom . formula_html ( ) canvas . draw_text ( p , text , color , "center" ) | Draw molecule structure image . | 632 | 5 |
11,529 | def smiles_to_compound ( smiles , assign_descriptors = True ) : it = iter ( smiles ) mol = molecule ( ) try : for token in it : mol ( token ) result , _ = mol ( None ) except KeyError as err : raise ValueError ( "Unsupported Symbol: {}" . format ( err ) ) result . graph . remove_node ( 0 ) logger . debug ( result ) if assign_descriptors : molutil . assign_descriptors ( result ) return result | Convert SMILES text to compound object | 108 | 9 |
11,530 | def salm2map ( salm , s , lmax , Ntheta , Nphi ) : if Ntheta < 2 or Nphi < 1 : raise ValueError ( "Input values of Ntheta={0} and Nphi={1} " . format ( Ntheta , Nphi ) + "are not allowed; they must be greater than 1 and 0, respectively." ) if lmax < 1 : raise ValueError ( "Input value of lmax={0} " . format ( lmax ) + "is not allowed; it must be greater than 0 and should be greater " + "than |s|={0}." . format ( abs ( s ) ) ) import numpy as np salm = np . ascontiguousarray ( salm , dtype = np . complex128 ) if salm . shape [ - 1 ] < N_lm ( lmax ) : raise ValueError ( "The input `salm` array of shape {0} is too small for the stated `lmax` of {1}. " . format ( salm . shape , lmax ) + "Perhaps you forgot to include the (zero) modes with ell<|s|." ) map = np . empty ( salm . shape [ : - 1 ] + ( Ntheta , Nphi ) , dtype = np . complex128 ) if salm . ndim > 1 : s = np . ascontiguousarray ( s , dtype = np . intc ) if s . ndim != salm . ndim - 1 or np . product ( s . shape ) != np . product ( salm . shape [ : - 1 ] ) : s = s * np . ones ( salm . shape [ : - 1 ] , dtype = np . intc ) _multi_salm2map ( salm , map , s , lmax , Ntheta , Nphi ) else : _salm2map ( salm , map , s , lmax , Ntheta , Nphi ) return map | Convert mode weights of spin - weighted function to values on a grid | 430 | 14 |
11,531 | def map2salm ( map , s , lmax ) : import numpy as np map = np . ascontiguousarray ( map , dtype = np . complex128 ) salm = np . empty ( map . shape [ : - 2 ] + ( N_lm ( lmax ) , ) , dtype = np . complex128 ) if map . ndim > 2 : s = np . ascontiguousarray ( s , dtype = np . intc ) if s . ndim != map . ndim - 2 or np . product ( s . shape ) != np . product ( map . shape [ : - 2 ] ) : s = s * np . ones ( map . shape [ : - 2 ] , dtype = np . intc ) _multi_map2salm ( map , salm , s , lmax ) else : _map2salm ( map , salm , s , lmax ) return salm | Convert values of spin - weighted function on a grid to mode weights | 201 | 14 |
11,532 | def Imm ( extended_map , s , lmax ) : import numpy as np extended_map = np . ascontiguousarray ( extended_map , dtype = np . complex128 ) NImm = ( 2 * lmax + 1 ) ** 2 imm = np . empty ( NImm , dtype = np . complex128 ) _Imm ( extended_map , imm , s , lmax ) return imm | Take the fft of the theta extended map then zero pad and reorganize it | 87 | 17 |
11,533 | def _query ( self , url , xpath ) : return self . session . query ( CachedRequest ) . filter ( CachedRequest . url == url ) . filter ( CachedRequest . xpath == xpath ) | Base query for an url and xpath | 47 | 8 |
11,534 | def get ( self , url , store_on_error = False , xpath = None , rate_limit = None , log_hits = True , log_misses = True ) : try : # get cached request - if none is found, this throws a NoResultFound exception cached = self . _query ( url , xpath ) . one ( ) if log_hits : config . logger . info ( "Request cache hit: " + url ) # if the cached value is from a request that resulted in an error, throw an exception if cached . status_code != requests . codes . ok : raise RuntimeError ( "Cached request returned an error, code " + str ( cached . status_code ) ) except NoResultFound : if log_misses : config . logger . info ( "Request cache miss: " + url ) # perform the request try : # rate limit if rate_limit is not None and self . last_query is not None : to_sleep = rate_limit - ( datetime . datetime . now ( ) - self . last_query ) . total_seconds ( ) if to_sleep > 0 : time . sleep ( to_sleep ) self . last_query = datetime . datetime . now ( ) response = requests . get ( url ) status_code = response . status_code # get 'text', not 'content', because then we are sure to get unicode content = response . text response . close ( ) if xpath is not None : doc = html . fromstring ( content ) nodes = doc . xpath ( xpath ) if len ( nodes ) == 0 : # xpath not found; set content and status code, exception is raised below content = "xpath not found: " + xpath status_code = ERROR_XPATH_NOT_FOUND else : # extract desired node only content = html . tostring ( nodes [ 0 ] , encoding = 'unicode' ) except requests . ConnectionError as e : # on a connection error, write exception information to a response object status_code = ERROR_CONNECTION_ERROR content = str ( e ) # a new request cache object cached = CachedRequest ( url = str ( url ) , content = content , status_code = status_code , xpath = xpath , queried_on = datetime . datetime . now ( ) ) # if desired, store the response even if an error occurred if status_code == requests . codes . ok or store_on_error : self . session . add ( cached ) self . session . commit ( ) if status_code != requests . codes . ok : raise RuntimeError ( "Error processing the request, " + str ( status_code ) + ": " + content ) return cached . content | Get a URL via the cache . | 585 | 7 |
11,535 | def get_timestamp ( self , url , xpath = None ) : if not path . exists ( self . db_path ) : return None if self . _query ( url , xpath ) . count ( ) > 0 : return self . _query ( url , xpath ) . one ( ) . queried_on | Get time stamp of cached query result . | 69 | 8 |
11,536 | def set_logger ( self ) : logger = logging . getLogger ( __name__ ) logger . setLevel ( level = logging . INFO ) logger_file = os . path . join ( self . logs_path , 'dingtalk_sdk.logs' ) logger_handler = logging . FileHandler ( logger_file ) logger_handler . setLevel ( logging . INFO ) logger_formatter = logging . Formatter ( '[%(asctime)s | %(name)s | %(levelname)s] %(message)s' ) logger_handler . setFormatter ( logger_formatter ) logger . addHandler ( logger_handler ) return logger | Method to build the base logging system . By default logging level is set to INFO . | 146 | 17 |
11,537 | def get_response ( self ) : request = getattr ( requests , self . request_method , None ) if request is None and self . _request_method is None : raise ValueError ( "A effective http request method must be set" ) if self . request_url is None : raise ValueError ( "Fatal error occurred, the class property \"request_url\" is" "set to None, reset it with an effective url of dingtalk api." ) response = request ( self . request_url , * * self . kwargs ) self . response = response return response | Get the original response of requests | 123 | 6 |
11,538 | def sendCommand ( self , * * msg ) : assert 'type' in msg , 'Message type is required.' msg [ 'id' ] = self . next_message_id self . next_message_id += 1 if self . next_message_id >= maxint : self . next_message_id = 1 self . sendMessage ( json . dumps ( msg ) ) return msg [ 'id' ] | Sends a raw command to the Slack server generating a message ID automatically . | 87 | 15 |
11,539 | def sendChatMessage ( self , text , id = None , user = None , group = None , channel = None , parse = 'none' , link_names = True , unfurl_links = True , unfurl_media = False , send_with_api = False , icon_emoji = None , icon_url = None , username = None , attachments = None , thread_ts = None , reply_broadcast = False ) : if id is not None : assert user is None , 'id and user cannot both be set.' assert group is None , 'id and group cannot both be set.' assert channel is None , 'id and channel cannot both be set.' elif user is not None : assert group is None , 'user and group cannot both be set.' assert channel is None , 'user and channel cannot both be set.' # Private message to user, get the IM name id = self . meta . find_im_by_user_name ( user , auto_create = True ) [ 0 ] elif group is not None : assert channel is None , 'group and channel cannot both be set.' # Message to private group, get the group name. id = self . meta . find_group_by_name ( group ) [ 0 ] elif channel is not None : # Message sent to a channel id = self . meta . find_channel_by_name ( channel ) [ 0 ] else : raise Exception , 'Should not reach here.' if send_with_api : return self . meta . api . chat . postMessage ( token = self . meta . token , channel = id , text = text , parse = parse , link_names = link_names , unfurl_links = unfurl_links , unfurl_media = unfurl_media , icon_url = icon_url , icon_emoji = icon_emoji , username = username , attachments = attachments , thread_ts = thread_ts , reply_broadcast = reply_broadcast , ) else : assert icon_url is None , 'icon_url can only be set if send_with_api is True' assert icon_emoji is None , 'icon_emoji can only be set if send_with_api is True' assert username is None , 'username can only be set if send_with_api is True' return self . sendCommand ( type = 'message' , channel = id , text = text , parse = parse , link_names = link_names , unfurl_links = unfurl_links , unfurl_media = unfurl_media , thread_ts = thread_ts , reply_broadcast = reply_broadcast , ) | Sends a chat message to a given id user group or channel . | 563 | 14 |
11,540 | def run ( ) : options = btoptions . Options ( ) btlog . initialize_logging ( options . log_level , options . log_file ) app = btapp . get_application ( ) app . run ( ) | Entry point for the bolt executable . | 51 | 7 |
11,541 | def mols_to_file ( mols , path ) : with open ( path , 'w' ) as f : f . write ( mols_to_text ( mols ) ) | Save molecules to the SDFile format file | 41 | 9 |
11,542 | def listen ( self ) : logger . info ( "Listening on port " + str ( self . listener . listen_port ) ) self . listener . listen ( ) | Starts the client listener to listen for server responses . | 35 | 11 |
11,543 | def retransmit ( self , data ) : # Handle retransmitting REGISTER requests if we don't hear back from # the server. if data [ "method" ] == "REGISTER" : if not self . registered and self . register_retries < self . max_retries : logger . debug ( "<%s> Timeout exceeded. " % str ( self . cuuid ) + "Retransmitting REGISTER request." ) self . register_retries += 1 self . register ( data [ "address" ] , retry = False ) else : logger . debug ( "<%s> No need to retransmit." % str ( self . cuuid ) ) if data [ "method" ] == "EVENT" : if data [ "euuid" ] in self . event_uuids : # Increment the current retry count of the euuid self . event_uuids [ data [ "euuid" ] ] [ "retry" ] += 1 if self . event_uuids [ data [ "euuid" ] ] [ "retry" ] > self . max_retries : logger . debug ( "<%s> Max retries exceeded. Timed out waiting " "for server for event: %s" % ( data [ "cuuid" ] , data [ "euuid" ] ) ) logger . debug ( "<%s> <euuid:%s> Deleting event from currently " "processing event uuids" % ( data [ "cuuid" ] , str ( data [ "euuid" ] ) ) ) del self . event_uuids [ data [ "euuid" ] ] else : # Retransmit that shit self . listener . send_datagram ( serialize_data ( data , self . compression , self . encryption , self . server_key ) , self . server ) # Then we set another schedule to check again logger . debug ( "<%s> <euuid:%s> Scheduling to retry in %s " "seconds" % ( data [ "cuuid" ] , str ( data [ "euuid" ] ) , str ( self . timeout ) ) ) self . listener . call_later ( self . timeout , self . retransmit , data ) else : logger . debug ( "<%s> <euuid:%s> No need to " "retransmit." % ( str ( self . cuuid ) , str ( data [ "euuid" ] ) ) ) | Processes messages that have been delivered from the transport protocol . | 543 | 12 |
11,544 | def handle_message ( self , msg , host ) : logger . debug ( "Executing handle_message method." ) response = None # Unserialize the data packet # If encryption is enabled, and we've receive the server's public key # already, try to decrypt if self . encryption and self . server_key : msg_data = unserialize_data ( msg , self . compression , self . encryption ) else : msg_data = unserialize_data ( msg , self . compression ) # Log the packet logger . debug ( "Packet received: " + pformat ( msg_data ) ) # If the message data is blank, return none if not msg_data : return response if "method" in msg_data : if msg_data [ "method" ] == "OHAI Client" : logger . debug ( "<%s> Autodiscover response from server received " "from: %s" % ( self . cuuid , host [ 0 ] ) ) self . discovered_servers [ host ] = [ msg_data [ "version" ] , msg_data [ "server_name" ] ] # Try to register with the discovered server if self . autoregistering : self . register ( host ) self . autoregistering = False elif msg_data [ "method" ] == "NOTIFY" : self . event_notifies [ msg_data [ "euuid" ] ] = msg_data [ "event_data" ] logger . debug ( "<%s> Notify received" % self . cuuid ) logger . debug ( "<%s> Notify event buffer: %s" % ( self . cuuid , pformat ( self . event_notifies ) ) ) # Send an OK NOTIFY to the server confirming we got the message response = serialize_data ( { "cuuid" : str ( self . cuuid ) , "method" : "OK NOTIFY" , "euuid" : msg_data [ "euuid" ] } , self . compression , self . encryption , self . server_key ) elif msg_data [ "method" ] == "OK REGISTER" : logger . debug ( "<%s> Ok register received" % self . cuuid ) self . registered = True self . server = host # If the server sent us their public key, store it if "encryption" in msg_data and self . encryption : self . server_key = PublicKey ( msg_data [ "encryption" ] [ 0 ] , msg_data [ "encryption" ] [ 1 ] ) elif ( msg_data [ "method" ] == "LEGAL" or msg_data [ "method" ] == "ILLEGAL" ) : logger . debug ( "<%s> Legality message received" % str ( self . cuuid ) ) self . legal_check ( msg_data ) # Send an OK EVENT response to the server confirming we # received the message response = serialize_data ( { "cuuid" : str ( self . cuuid ) , "method" : "OK EVENT" , "euuid" : msg_data [ "euuid" ] } , self . compression , self . encryption , self . server_key ) logger . debug ( "Packet processing completed" ) return response | Processes messages that have been delivered from the transport protocol | 719 | 11 |
11,545 | def autodiscover ( self , autoregister = True ) : logger . debug ( "<%s> Sending autodiscover message to broadcast " "address" % str ( self . cuuid ) ) if not self . listener . listening : logger . warning ( "Neteria client is not listening. The client " "will not be able to process responses from the server" ) message = serialize_data ( { "method" : "OHAI" , "version" : self . version , "cuuid" : str ( self . cuuid ) } , self . compression , encryption = False ) if autoregister : self . autoregistering = True self . listener . send_datagram ( message , ( "<broadcast>" , self . server_port ) , message_type = "broadcast" ) | This function will send out an autodiscover broadcast to find a Neteria server . Any servers that respond with an OHAI CLIENT packet are servers that we can connect to . Servers that respond are stored in the discovered_servers list . | 178 | 50 |
11,546 | def register ( self , address , retry = True ) : logger . debug ( "<%s> Sending REGISTER request to: %s" % ( str ( self . cuuid ) , str ( address ) ) ) if not self . listener . listening : logger . warning ( "Neteria client is not listening." ) # Construct the message to send message = { "method" : "REGISTER" , "cuuid" : str ( self . cuuid ) } # If we have encryption enabled, send our public key with our REGISTER # request if self . encryption : message [ "encryption" ] = [ self . encryption . n , self . encryption . e ] # Send a REGISTER to the server self . listener . send_datagram ( serialize_data ( message , self . compression , encryption = False ) , address ) if retry : # Reset the current number of REGISTER retries self . register_retries = 0 # Schedule a task to run in x seconds to check to see if we've timed # out in receiving a response from the server self . listener . call_later ( self . timeout , self . retransmit , { "method" : "REGISTER" , "address" : address } ) | This function will send a register packet to the discovered Neteria server . | 262 | 14 |
11,547 | def event ( self , event_data , priority = "normal" , event_method = "EVENT" ) : logger . debug ( "event: " + str ( event_data ) ) # Generate an event UUID for this event euuid = uuid . uuid1 ( ) logger . debug ( "<%s> <euuid:%s> Sending event data to server: " "%s" % ( str ( self . cuuid ) , str ( euuid ) , str ( self . server ) ) ) if not self . listener . listening : logger . warning ( "Neteria client is not listening." ) # If we're not even registered, don't even bother. if not self . registered : logger . warning ( "<%s> <euuid:%s> Client is currently not registered. " "Event not sent." % ( str ( self . cuuid ) , str ( euuid ) ) ) return False # Send the event data to the server packet = { "method" : event_method , "cuuid" : str ( self . cuuid ) , "euuid" : str ( euuid ) , "event_data" : event_data , "timestamp" : str ( datetime . now ( ) ) , "retry" : 0 , "priority" : priority } self . listener . send_datagram ( serialize_data ( packet , self . compression , self . encryption , self . server_key ) , self . server ) logger . debug ( "<%s> Sending EVENT Packet: %s" % ( str ( self . cuuid ) , pformat ( packet ) ) ) # Set the sent event to our event buffer to see if we need to roll back # or anything self . event_uuids [ str ( euuid ) ] = packet # Now we need to reschedule a timeout/retransmit check logger . debug ( "<%s> Scheduling retry in %s seconds" % ( str ( self . cuuid ) , str ( self . timeout ) ) ) self . listener . call_later ( self . timeout , self . retransmit , packet ) return euuid | This function will send event packets to the server . This is the main method you would use to send data from your application to the server . | 469 | 28 |
11,548 | def legal_check ( self , message ) : # If the event was legal, remove it from our event buffer if message [ "method" ] == "LEGAL" : logger . debug ( "<%s> <euuid:%s> Event LEGAL" % ( str ( self . cuuid ) , message [ "euuid" ] ) ) logger . debug ( "<%s> <euuid:%s> Removing event from event " "buffer." % ( str ( self . cuuid ) , message [ "euuid" ] ) ) # If the message was a high priority, then we keep track of legal # events too if message [ "priority" ] == "high" : self . event_confirmations [ message [ "euuid" ] ] = self . event_uuids [ message [ "euuid" ] ] logger . debug ( "<%s> <euuid:%s> Event was high priority. Adding " "to confirmations buffer." % ( str ( self . cuuid ) , message [ "euuid" ] ) ) logger . debug ( "<%s> <euuid:%s> Current event confirmation " "buffer: %s" % ( str ( self . cuuid ) , message [ "euuid" ] , pformat ( self . event_confirmations ) ) ) # Try and remove the event from the currently processing events try : del self . event_uuids [ message [ "euuid" ] ] except KeyError : logger . warning ( "<%s> <euuid:%s> Euuid does not exist in event " "buffer. Key was removed before we could process " "it." % ( str ( self . cuuid ) , message [ "euuid" ] ) ) # If the event was illegal, remove it from our event buffer and add it # to our rollback list elif message [ "method" ] == "ILLEGAL" : logger . debug ( "<%s> <euuid:%s> Event ILLEGAL" % ( str ( self . cuuid ) , message [ "euuid" ] ) ) logger . debug ( "<%s> <euuid:%s> Removing event from event buffer and " "adding to rollback buffer." % ( str ( self . cuuid ) , message [ "euuid" ] ) ) self . event_rollbacks [ message [ "euuid" ] ] = self . event_uuids [ message [ "euuid" ] ] del self . event_uuids [ message [ "euuid" ] ] | This method handles event legality check messages from the server . | 573 | 11 |
11,549 | def search ( self , category = None , cuisine = None , location = ( None , None ) , radius = None , tl_coord = ( None , None ) , br_coord = ( None , None ) , name = None , country = None , locality = None , region = None , postal_code = None , street_address = None , website_url = None , has_menu = None , open_at = None ) : params = self . _get_params ( category = category , cuisine = cuisine , location = location , radius = radius , tl_coord = tl_coord , br_coord = br_coord , name = name , country = country , locality = locality , region = region , postal_code = postal_code , street_address = street_address , website_url = website_url , has_menu = has_menu , open_at = open_at ) return self . _create_query ( 'search' , params ) | Locu Venue Search API Call Wrapper | 206 | 9 |
11,550 | def search_next ( self , obj ) : if 'meta' in obj and 'next' in obj [ 'meta' ] and obj [ 'meta' ] [ 'next' ] != None : uri = self . api_url % obj [ 'meta' ] [ 'next' ] header , content = self . _http_uri_request ( uri ) resp = json . loads ( content ) if not self . _is_http_response_ok ( header ) : error = resp . get ( 'error_message' , 'Unknown Error' ) raise HttpException ( header . status , header . reason , error ) return resp return { } | Takes the dictionary that is returned by search or search_next function and gets the next batch of results | 139 | 21 |
11,551 | def get_details ( self , ids ) : if isinstance ( ids , list ) : if len ( ids ) > 5 : ids = ids [ : 5 ] id_param = ';' . join ( ids ) + '/' else : ids = str ( ids ) id_param = ids + '/' header , content = self . _http_request ( id_param ) resp = json . loads ( content ) if not self . _is_http_response_ok ( header ) : error = resp . get ( 'error_message' , 'Unknown Error' ) raise HttpException ( header . status , header . reason , error ) return resp | Locu Venue Details API Call Wrapper | 147 | 9 |
11,552 | def get_menus ( self , id ) : resp = self . get_details ( [ id ] ) menus = [ ] for obj in resp [ 'objects' ] : if obj [ 'has_menu' ] : menus += obj [ 'menus' ] return menus | Given a venue id returns a list of menus associated with a venue | 58 | 13 |
11,553 | def is_open ( self , id , time , day ) : details = self . get_details ( id ) has_data = False for obj in details [ "objects" ] : hours = obj [ "open_hours" ] [ day ] if hours : has_data = True for interval in hours : interval = interval . replace ( ' ' , '' ) . split ( '-' ) open_time = interval [ 0 ] close_time = interval [ 1 ] if open_time < time < close_time : return True if has_data : return False else : return None | Checks if the venue is open at the time of day given a venue id . | 122 | 17 |
11,554 | def search ( self , name = None , category = None , description = None , price = None , price__gt = None , price__gte = None , price__lt = None , price__lte = None , location = ( None , None ) , radius = None , tl_coord = ( None , None ) , br_coord = ( None , None ) , country = None , locality = None , region = None , postal_code = None , street_address = None , website_url = None ) : params = self . _get_params ( name = name , description = description , price = price , price__gt = price__gt , price__gte = price__gte , price__lt = price__lt , price__lte = price__lte , location = location , radius = radius , tl_coord = tl_coord , br_coord = br_coord , country = country , locality = locality , region = region , postal_code = postal_code , street_address = street_address , website_url = website_url ) return self . _create_query ( 'search' , params ) | Locu Menu Item Search API Call Wrapper | 244 | 9 |
11,555 | def main ( ctx , root_project_dir , verbose ) : root_project_dir = discover_conf_py_directory ( root_project_dir ) # Subcommands should use the click.pass_obj decorator to get this # ctx.obj object as the first argument. ctx . obj = { 'root_project_dir' : root_project_dir , 'verbose' : verbose } # Set up application logging. This ensures that only documenteer's # logger is activated. If necessary, we can add other app's loggers too. if verbose : log_level = logging . DEBUG else : log_level = logging . INFO logger = logging . getLogger ( 'documenteer' ) logger . addHandler ( logging . StreamHandler ( ) ) logger . setLevel ( log_level ) | stack - docs is a CLI for building LSST Stack documentation such as pipelines . lsst . io . | 177 | 21 |
11,556 | def help ( ctx , topic , * * kw ) : # The help command implementation is taken from # https://www.burgundywall.com/post/having-click-help-subcommand if topic is None : click . echo ( ctx . parent . get_help ( ) ) else : click . echo ( main . commands [ topic ] . get_help ( ctx ) ) | Show help for any command . | 84 | 6 |
11,557 | def clean ( ctx ) : logger = logging . getLogger ( __name__ ) dirnames = [ 'py-api' , '_build' , 'modules' , 'packages' ] dirnames = [ os . path . join ( ctx . obj [ 'root_project_dir' ] , dirname ) for dirname in dirnames ] for dirname in dirnames : if os . path . isdir ( dirname ) : shutil . rmtree ( dirname ) logger . debug ( 'Cleaned up %r' , dirname ) else : logger . debug ( 'Did not clean up %r (missing)' , dirname ) | Clean Sphinx build products . | 140 | 6 |
11,558 | def query_with_attributes ( type_to_query , client ) : session = client . create_session ( ) # query all data query = session . query ( Attribute . name , Attribute . value , Entity . id ) . join ( Entity ) . filter ( Entity . type == type_to_query ) df = client . df_query ( query ) session . close ( ) # don't store NaN values df = df . dropna ( how = 'any' ) # pivot attribute names to columns, drop column names to one level # ('unstack' generated multi-level names) df = df . set_index ( [ 'id' , 'name' ] ) . unstack ( ) . reset_index ( ) # noinspection PyUnresolvedReferences df . columns = [ 'id' ] + list ( df . columns . get_level_values ( 1 ) [ 1 : ] ) return df | Query all entities of a specific type with their attributes | 196 | 10 |
11,559 | def reset ( self ) : for name in self . __dict__ : if name . startswith ( "_" ) : continue attr = getattr ( self , name ) setattr ( self , name , attr and attr . __class__ ( ) ) | Reset all fields of this object to class defaults | 56 | 10 |
11,560 | def geojson_polygon_to_mask ( feature , shape , lat_idx , lon_idx ) : import matplotlib # specify 'agg' renderer, Mac renderer does not support what we want to do below matplotlib . use ( 'agg' ) import matplotlib . pyplot as plt from matplotlib import patches import numpy as np # we can only do polygons right now if feature . geometry . type not in ( 'Polygon' , 'MultiPolygon' ) : raise ValueError ( "Cannot handle feature of type " + feature . geometry . type ) # fictional dpi - don't matter in the end dpi = 100 # -- start documentation include: poly-setup # make a new figure with no frame, no axes, with the correct size, black background fig = plt . figure ( frameon = False , dpi = dpi , ) fig . set_size_inches ( shape [ 1 ] / float ( dpi ) , shape [ 0 ] / float ( dpi ) ) ax = plt . Axes ( fig , [ 0. , 0. , 1. , 1. ] ) ax . set_axis_off ( ) # noinspection PyTypeChecker ax . set_xlim ( [ 0 , shape [ 1 ] ] ) # noinspection PyTypeChecker ax . set_ylim ( [ 0 , shape [ 0 ] ] ) fig . add_axes ( ax ) # -- end documentation include: poly-setup # for normal polygons make coordinates iterable if feature . geometry . type == 'Polygon' : coords = [ feature . geometry . coordinates ] else : coords = feature . geometry . coordinates for poly_coords in coords : # the polygon may contain multiple outlines; the first is # always the outer one, the others are 'holes' for i , outline in enumerate ( poly_coords ) : # inside/outside fill value: figure background is white by # default, draw inverted polygon and invert again later value = 0. if i == 0 else 1. # convert lats/lons to row/column indices in the array outline = np . array ( outline ) xs = lon_idx ( outline [ : , 0 ] ) ys = lat_idx ( outline [ : , 1 ] ) # draw the polygon poly = patches . Polygon ( list ( zip ( xs , ys ) ) , facecolor = ( value , value , value ) , edgecolor = 'none' , antialiased = True ) ax . add_patch ( poly ) # -- start documentation include: poly-extract # extract the figure to a numpy array, fig . canvas . draw ( ) data = np . fromstring ( fig . canvas . tostring_rgb ( ) , dtype = np . uint8 , sep = '' ) # reshape to a proper numpy array, keep one channel only data = data . reshape ( fig . canvas . get_width_height ( ) [ : : - 1 ] + ( 3 , ) ) [ : , : , 0 ] # -- end documentation include: poly-extract # make sure we get the right shape back assert data . shape [ 0 ] == shape [ 0 ] assert data . shape [ 1 ] == shape [ 1 ] # convert from uints back to floats and invert to get black background data = 1. - data . astype ( float ) / 255. # type: np.array # image is flipped horizontally w.r.t. map data = data [ : : - 1 , : ] # done, clean up plt . close ( 'all' ) return data | Convert a GeoJSON polygon feature to a numpy array | 784 | 13 |
11,561 | def load ( self ) : # read file, keep all values as strings df = pd . read_csv ( self . input_file , sep = ',' , quotechar = '"' , encoding = 'utf-8' , dtype = object ) # wer are only interested in the NUTS code and description, rename them also df = df [ [ 'NUTS-Code' , 'Description' ] ] df . columns = [ 'key' , 'name' ] # we only want NUTS2 regions (4-digit codes) df = df [ df [ 'key' ] . str . len ( ) == 4 ] # drop 'Extra Regio' codes ending in 'ZZ' df = df [ df [ 'key' ] . str [ 2 : ] != 'ZZ' ] return df | Load data from default location | 173 | 5 |
11,562 | def input_file ( self ) : return path . join ( path . dirname ( __file__ ) , 'data' , 'tgs{:s}.tsv' . format ( self . number ) ) | Returns the input file name with a default relative path | 45 | 10 |
11,563 | def load ( self , key_filter = None , header_preproc = None ) : # read file, keep all values as strings df = pd . read_csv ( self . input_file , sep = '\t' , dtype = object ) if key_filter is not None : # filter on key column (first column) df = df [ df [ df . columns [ 0 ] ] . str . match ( key_filter ) ] # first column contains metadata, with NUTS2 region key as last (comma-separated) value meta_col = df . columns [ 0 ] df [ meta_col ] = df [ meta_col ] . str . split ( ',' ) . str [ - 1 ] # convert columns to numbers, skip first column (containing metadata) for col_name in df . columns [ 1 : ] : # some values have lower-case characters indicating footnotes, strip them stripped = df [ col_name ] . str . replace ( r'[a-z]' , '' ) # convert to numbers, convert any remaining empty values (indicated by ':' in the input table) to NaN df [ col_name ] = pd . to_numeric ( stripped , errors = 'coerce' ) # preprocess headers if header_preproc is not None : df . columns = list ( df . columns [ : 1 ] ) + [ header_preproc ( c ) for c in df . columns [ 1 : ] ] # rename columns, convert years to integers # noinspection PyTypeChecker df . columns = [ 'key' ] + [ int ( y ) for y in df . columns [ 1 : ] ] return df | Load data table from tsv file from default location | 358 | 10 |
11,564 | def load ( self ) : from scipy . io import netcdf_file from scipy import interpolate import numpy as np # load file f = netcdf_file ( self . input_file ) # extract data, make explicity copies of data out = dict ( ) lats = f . variables [ 'lat' ] [ : ] . copy ( ) lons = f . variables [ 'lon' ] [ : ] . copy ( ) # lons start at 0, this is bad for working with data in Europe because the map border runs right through; # roll array by half its width to get Europe into the map center out [ 'data' ] = np . roll ( f . variables [ self . variable_name ] [ : , : , : ] . copy ( ) , shift = len ( lons ) // 2 , axis = 2 ) lons = np . roll ( lons , shift = len ( lons ) // 2 ) # avoid wraparound problems around zero by setting lon range to -180...180, this is # also the format used in the GeoJSON NUTS2 polygons lons [ lons > 180 ] -= 360 # data contains some very negative value (~ -9e36) as 'invalid data' flag, convert this to a masked array out [ 'data' ] = np . ma . array ( out [ 'data' ] ) out [ 'data' ] [ out [ 'data' ] < - 1.e6 ] = np . ma . masked # -- start documentation include: climate-input-interp # build interpolators to convert lats/lons to row/column indices out [ 'lat_idx' ] = interpolate . interp1d ( x = lats , y = np . arange ( len ( lats ) ) ) out [ 'lon_idx' ] = interpolate . interp1d ( x = lons , y = np . arange ( len ( lons ) ) ) # -- end documentation include: climate-input-interp # clean up f . close ( ) return out | Load the climate data as a map | 446 | 7 |
11,565 | def clear ( self ) : # mark this task as incomplete self . mark_incomplete ( ) # Delete the indicator metadata, this also deletes values by cascading. for suffix in list ( CLIMATE_SEASON_SUFFIXES . values ( ) ) : try : # noinspection PyUnresolvedReferences indicator = self . session . query ( models . ClimateIndicator ) . filter ( models . ClimateIndicator . description == self . description + suffix ) . one ( ) self . session . delete ( indicator ) except NoResultFound : # Data didn't exist yet, no problem pass self . close_session ( ) | Clear output of one climate variable | 133 | 6 |
11,566 | def run ( self ) : import numpy as np # get all NUTS region IDs, for linking values to region objects query = self . session . query ( models . NUTS2Region . key , models . NUTS2Region . id ) region_ids = self . client . df_query ( query ) . set_index ( 'key' ) [ 'id' ] . to_dict ( ) # load climate data and NUTS2 polygons data = next ( self . requires ( ) ) . load ( ) nuts = NUTS2GeoJSONInputFile ( ) . load ( ) # generated indicator IDs, keyed by season indicator_ids = dict ( ) # climate data by season t_data = dict ( ) # create new indicator objects for summer and winter, create averaged climate data for season , suffix in CLIMATE_SEASON_SUFFIXES . items ( ) : # noinspection PyUnresolvedReferences indicator = models . ClimateIndicator ( description = self . description + suffix ) self . session . add ( indicator ) # commit, to get indicator ID filled self . session . commit ( ) indicator_ids [ season ] = indicator . id # select winter or summer data by month index, average over time range if season == 'summer' : t_data [ season ] = np . ma . average ( data [ 'data' ] [ 3 : 9 , : , : ] , axis = 0 ) else : # noinspection PyTypeChecker t_data [ season ] = np . ma . average ( 0.5 * ( data [ 'data' ] [ 0 : 3 , : , : ] + data [ 'data' ] [ 9 : 12 , : , : ] ) , axis = 0 ) # container for output objects, for bulk saving objects = [ ] # start value for manual object id generation current_value_id = models . ClimateValue . get_max_id ( self . session ) # for each region, get a mask, average climate variable over the mask and store the indicator value; # loop over features first, then over seasons, because mask generation is expensive for feature in nuts : # draw region mask (doesn't matter for which season we take the map shape) mask = geojson_polygon_to_mask ( feature = feature , shape = t_data [ 'summer' ] . shape , lat_idx = data [ 'lat_idx' ] , lon_idx = data [ 'lon_idx' ] ) # create indicator values for summer and winter for season in list ( CLIMATE_SEASON_SUFFIXES . keys ( ) ) : # weighted average from region mask value = np . ma . average ( t_data [ season ] , weights = mask ) # region ID must be cast to int (DBs don't like numpy dtypes from pandas) region_id = region_ids . get ( feature . properties [ 'NUTS_ID' ] , None ) if region_id is not None : region_id = int ( region_id ) # append an indicator value, manually generate object IDs for bulk saving current_value_id += 1 objects . append ( models . ClimateValue ( id = current_value_id , value = value , region_id = region_id , indicator_id = indicator_ids [ season ] ) ) # # print some debugging output # print self.variable_name + ' ' + season, feature.properties['NUTS_ID'], value # # generate some plots for debugging # from matplotlib import pyplot as plt # plt.subplot(211) # plt.imshow(0.02 * t_data + mask * t_data, interpolation='none') # plt.subplot(212) # plt.imshow(t_data, interpolation='none') # plt.savefig('/tmp/' + feature.properties['NUTS_ID'] + '.png') # bulk-save all objects self . session . bulk_save_objects ( objects ) self . session . commit ( ) self . done ( ) | Load climate data and convert to indicator objects | 879 | 8 |
11,567 | def lose ( spin ) : try : spin . close ( ) except Exception as excpt : err = excpt . args [ 0 ] spin . drive ( CLOSE_ERR , err ) finally : spin . destroy ( ) spin . drive ( LOST ) | It is used to close TCP connection and unregister the Spin instance from untwisted reactor . | 54 | 19 |
11,568 | def create_server ( addr , port , backlog ) : server = Spin ( ) server . bind ( ( addr , port ) ) server . listen ( backlog ) Server ( server ) server . add_map ( ACCEPT , lambda server , spin : install_basic_handles ( spin ) ) return server | Set up a TCP server and installs the basic handles Stdin Stdout in the clients . | 64 | 19 |
11,569 | def create_client ( addr , port ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) # First attempt to connect otherwise it leaves # an unconnected spin instance in the reactor. sock . connect_ex ( ( addr , port ) ) spin = Spin ( sock ) Client ( spin ) spin . add_map ( CONNECT , install_basic_handles ) spin . add_map ( CONNECT_ERR , lambda con , err : lose ( con ) ) return spin | Set up a TCP client and installs the basic handles Stdin Stdout . | 111 | 16 |
11,570 | def main ( argv = None ) : # type: (Union[NoneType, List[str]]) -> NoneType app = application . Application ( ) app . run ( argv ) app . exit ( ) | Execute the main bit of the application . | 45 | 9 |
11,571 | def fingerprint_similarity ( mol1 , mol2 ) : idmol1 = to_real_mol ( mol1 ) idmol2 = to_real_mol ( mol2 ) fp1 = idmol1 . fingerprint ( "sim" ) fp2 = idmol2 . fingerprint ( "sim" ) return round ( idg . similarity ( fp1 , fp2 , "tanimoto" ) , 2 ) | Calculate Indigo fingerprint similarity | 92 | 6 |
11,572 | def devmodel_to_array ( model_name , train_fraction = 1 ) : model_outputs = - 6 + model_name . Data_summary . shape [ 0 ] devmodel = model_name rawdf = devmodel . Data rawdf = rawdf . sample ( frac = 1 ) datadf = rawdf . select_dtypes ( include = [ np . number ] ) data = np . array ( datadf ) n = data . shape [ 0 ] d = data . shape [ 1 ] d -= model_outputs n_train = int ( n * train_fraction ) # set fraction for training n_test = n - n_train X_train = np . zeros ( ( n_train , d ) ) # prepare train/test arrays X_test = np . zeros ( ( n_test , d ) ) Y_train = np . zeros ( ( n_train , model_outputs ) ) Y_test = np . zeros ( ( n_test , model_outputs ) ) X_train [ : ] = data [ : n_train , : - model_outputs ] Y_train [ : ] = ( data [ : n_train , - model_outputs : ] . astype ( float ) ) X_test [ : ] = data [ n_train : , : - model_outputs ] Y_test [ : ] = ( data [ n_train : , - model_outputs : ] . astype ( float ) ) return X_train , Y_train , X_test , Y_test | a standardized method of turning a dev_model object into training and testing arrays | 341 | 15 |
11,573 | def dapply ( self , fn , pairwise = False , symmetric = True , diagonal = False , block = None , * * kwargs ) : search_keys = [ k for k , v in kwargs . items ( ) if isinstance ( v , list ) and len ( v ) > 1 ] functions = util . make_list ( fn ) search = list ( product ( functions , util . dict_product ( kwargs ) ) ) results = [ ] for fn , kw in search : if not pairwise : r = self . index . to_series ( ) . apply ( lambda step : fn ( step , * * kw ) ) else : r = apply_pairwise ( self , fn , symmetric = symmetric , diagonal = diagonal , block = block , * * kw ) name = [ ] if len ( functions ) == 1 else [ fn . __name__ ] name += util . dict_subset ( kw , search_keys ) . values ( ) if isinstance ( r , pd . DataFrame ) : columns = pd . MultiIndex . from_tuples ( [ tuple ( name + util . make_list ( c ) ) for c in r . columns ] ) r . columns = columns else : r . name = tuple ( name ) results . append ( r ) if len ( results ) > 1 : result = pd . concat ( results , axis = 1 ) # get subset of parameters that were searched over column_names = [ ] if len ( functions ) == 1 else [ None ] column_names += search_keys column_names += [ None ] * ( len ( result . columns . names ) - len ( column_names ) ) result . columns . names = column_names return StepFrame ( result ) else : result = results [ 0 ] if isinstance ( result , pd . DataFrame ) : return StepFrame ( result ) else : result . name = functions [ 0 ] . __name__ return StepSeries ( result ) | Apply function to each step object in the index | 423 | 9 |
11,574 | def _identifyBranches ( self ) : if self . debug : sys . stdout . write ( "Identifying branches: " ) start = time . clock ( ) seen = set ( ) self . branches = set ( ) # Find all of the branching nodes in the tree, degree > 1 # That is, they appear in more than one edge for e1 , e2 in self . edges : if e1 not in seen : seen . add ( e1 ) else : self . branches . add ( e1 ) if e2 not in seen : seen . add ( e2 ) else : self . branches . add ( e2 ) if self . debug : end = time . clock ( ) sys . stdout . write ( "%f s\n" % ( end - start ) ) | A helper function for determining all of the branches in the tree . This should be called after the tree has been fully constructed and its nodes and edges are populated . | 166 | 32 |
11,575 | def _identifySuperGraph ( self ) : if self . debug : sys . stdout . write ( "Condensing Graph: " ) start = time . clock ( ) G = nx . DiGraph ( ) G . add_edges_from ( self . edges ) if self . short_circuit : self . superNodes = G . nodes ( ) self . superArcs = G . edges ( ) # There should be a way to populate this from the data we # have... return self . augmentedEdges = { } N = len ( self . Y ) processed = np . zeros ( N ) for node in range ( N ) : # We can short circuit this here, since some of the nodes # will be handled within the while loops below. if processed [ node ] : continue # Loop through each internal node (see if below for # determining what is internal), trace up and down to a # node's first non-internal node in either direction # removing all of the internal nodes and pushing them into a # list. This list (removedNodes) will be put into a # dictionary keyed on the endpoints of the final super arc. if G . in_degree ( node ) == 1 and G . out_degree ( node ) == 1 : # The sorted list of nodes that will be condensed by # this super arc removedNodes = [ ] # Trace down to a non-internal node lower_link = list ( G . in_edges ( node ) ) [ 0 ] [ 0 ] while ( G . in_degree ( lower_link ) == 1 and G . out_degree ( lower_link ) == 1 ) : new_lower_link = list ( G . in_edges ( lower_link ) ) [ 0 ] [ 0 ] G . add_edge ( new_lower_link , node ) G . remove_node ( lower_link ) removedNodes . append ( lower_link ) lower_link = new_lower_link removedNodes . reverse ( ) removedNodes . append ( node ) # Trace up to a non-internal node upper_link = list ( G . out_edges ( node ) ) [ 0 ] [ 1 ] while ( G . in_degree ( upper_link ) == 1 and G . out_degree ( upper_link ) == 1 ) : new_upper_link = list ( G . out_edges ( upper_link ) ) [ 0 ] [ 1 ] G . add_edge ( node , new_upper_link ) G . remove_node ( upper_link ) removedNodes . append ( upper_link ) upper_link = new_upper_link G . add_edge ( lower_link , upper_link ) G . remove_node ( node ) self . augmentedEdges [ ( lower_link , upper_link ) ] = removedNodes # This is to help speed up the process by skipping nodes # we have already condensed, and to prevent us from not # being able to find nodes that have already been # removed. processed [ removedNodes ] = 1 self . superNodes = G . nodes ( ) self . superArcs = G . edges ( ) if self . debug : end = time . clock ( ) sys . stdout . write ( "%f s\n" % ( end - start ) ) | A helper function for determining the condensed representation of the tree . That is one that does not hold all of the internal nodes of the graph . The results will be stored in ContourTree . superNodes and ContourTree . superArcs . These two can be used to potentially speed up queries by limiting the searching on the graph to only nodes on these super arcs . | 702 | 75 |
11,576 | def get_seeds ( self , threshold ) : seeds = [ ] for e1 , e2 in self . superArcs : # Because we did some extra work in _process_tree, we can # safely assume e1 is lower than e2 if self . Y [ e1 ] <= threshold <= self . Y [ e2 ] : if ( e1 , e2 ) in self . augmentedEdges : # These should be sorted edgeList = self . augmentedEdges [ ( e1 , e2 ) ] elif ( e2 , e1 ) in self . augmentedEdges : e1 , e2 = e2 , e1 # These should be reverse sorted edgeList = list ( reversed ( self . augmentedEdges [ ( e1 , e2 ) ] ) ) else : continue startNode = e1 for endNode in edgeList + [ e2 ] : if self . Y [ endNode ] >= threshold : # Stop when you find the first point above the # threshold break startNode = endNode seeds . append ( startNode ) seeds . append ( endNode ) return seeds | Returns a list of seed points for isosurface extraction given a threshold value | 230 | 16 |
11,577 | def _construct_nx_tree ( self , thisTree , thatTree = None ) : if self . debug : sys . stdout . write ( "Networkx Tree construction: " ) start = time . clock ( ) nxTree = nx . DiGraph ( ) nxTree . add_edges_from ( thisTree . edges ) nodesOfThatTree = [ ] if thatTree is not None : nodesOfThatTree = thatTree . nodes . keys ( ) # Fully or partially augment the join tree for ( superNode , _ ) , nodes in thisTree . augmentedEdges . items ( ) : superNodeEdge = list ( nxTree . out_edges ( superNode ) ) if len ( superNodeEdge ) > 1 : warnings . warn ( "The supernode {} should have only a single " "emanating edge. Merge tree is invalidly " "structured" . format ( superNode ) ) endNode = superNodeEdge [ 0 ] [ 1 ] startNode = superNode nxTree . remove_edge ( startNode , endNode ) for node in nodes : if thatTree is None or node in nodesOfThatTree : nxTree . add_edge ( startNode , node ) startNode = node # Make sure this is not the root node trying to connect to # itself if startNode != endNode : nxTree . add_edge ( startNode , endNode ) if self . debug : end = time . clock ( ) sys . stdout . write ( "%f s\n" % ( end - start ) ) return nxTree | A function for creating networkx instances that can be used more efficiently for graph manipulation than the MergeTree class . | 334 | 22 |
11,578 | def read_git_branch ( ) : if os . getenv ( 'TRAVIS' ) : return os . getenv ( 'TRAVIS_BRANCH' ) else : try : repo = git . repo . base . Repo ( search_parent_directories = True ) return repo . active_branch . name except Exception : return '' | Obtain the current branch name from the Git repository . If on Travis CI use the TRAVIS_BRANCH environment variable . | 77 | 26 |
11,579 | def read_git_commit_timestamp ( repo_path = None ) : repo = git . repo . base . Repo ( path = repo_path , search_parent_directories = True ) head_commit = repo . head . commit return head_commit . committed_datetime | Obtain the timestamp from the current head commit of a Git repository . | 61 | 14 |
11,580 | def read_git_commit_timestamp_for_file ( filepath , repo_path = None ) : repo = git . repo . base . Repo ( path = repo_path , search_parent_directories = True ) head_commit = repo . head . commit # most recent commit datetime of the given file for commit in head_commit . iter_parents ( filepath ) : return commit . committed_datetime # Only get here if git could not find the file path in the history raise IOError ( 'File {} not found' . format ( filepath ) ) | Obtain the timestamp for the most recent commit to a given file in a Git repository . | 123 | 18 |
11,581 | def get_filepaths_with_extension ( extname , root_dir = '.' ) : # needed for comparison with os.path.splitext if not extname . startswith ( '.' ) : extname = '.' + extname # for case-insensitivity extname = extname . lower ( ) root_dir = os . path . abspath ( root_dir ) selected_filenames = [ ] for dirname , sub_dirnames , filenames in os . walk ( root_dir ) : for filename in filenames : if os . path . splitext ( filename ) [ - 1 ] . lower ( ) == extname : full_filename = os . path . join ( dirname , filename ) selected_filenames . append ( os . path . relpath ( full_filename , start = root_dir ) ) return selected_filenames | Get relative filepaths of files in a directory and sub - directories with the given extension . | 193 | 19 |
11,582 | def get_project_content_commit_date ( root_dir = '.' , exclusions = None ) : logger = logging . getLogger ( __name__ ) # Supported 'content' extensions extensions = ( 'rst' , 'ipynb' , 'png' , 'jpeg' , 'jpg' , 'svg' , 'gif' ) content_paths = [ ] for extname in extensions : content_paths += get_filepaths_with_extension ( extname , root_dir = root_dir ) # Known files that should be excluded; lower case for comparison exclude = Matcher ( exclusions if exclusions else [ 'readme.rst' , 'license.rst' ] ) # filter out excluded files content_paths = [ p for p in content_paths if not ( exclude ( p ) or exclude ( p . split ( os . path . sep ) [ 0 ] ) ) ] logger . debug ( 'Found content paths: {}' . format ( ', ' . join ( content_paths ) ) ) if not content_paths : raise RuntimeError ( 'No content files found in {}' . format ( root_dir ) ) commit_datetimes = [ ] for filepath in content_paths : try : datetime = read_git_commit_timestamp_for_file ( filepath , repo_path = root_dir ) commit_datetimes . append ( datetime ) except IOError : logger . warning ( 'Could not get commit for {}, skipping' . format ( filepath ) ) if not commit_datetimes : raise RuntimeError ( 'No content commits could be found' ) latest_datetime = max ( commit_datetimes ) return latest_datetime | Get the datetime for the most recent commit to a project that affected Sphinx content . | 373 | 18 |
11,583 | def form_ltd_edition_name ( git_ref_name = None ) : if git_ref_name is None : name = read_git_branch ( ) else : name = git_ref_name # First, try to use the JIRA ticket number m = TICKET_BRANCH_PATTERN . match ( name ) if m is not None : return m . group ( 1 ) # Or use a tagged version m = TAG_PATTERN . match ( name ) if m is not None : return name if name == 'master' : # using this terminology for LTD Dasher name = 'Current' # Otherwise, reproduce the LTD slug name = name . replace ( '/' , '-' ) name = name . replace ( '_' , '-' ) name = name . replace ( '.' , '-' ) return name | Form the LSST the Docs edition name for this branch using the same logic as LTD Keeper does for transforming branch names into edition names . | 182 | 28 |
11,584 | def itersheets ( self ) : for ws in self . worksheets : # Expression with no explicit table specified will use None # when calling get_table, which should return the current worksheet/table prev_ws = self . active_worksheet self . active_worksheet = ws try : yield ws finally : self . active_worksheet = prev_ws | Iterates over the worksheets in the book and sets the active worksheet as the current one before yielding . | 81 | 23 |
11,585 | def to_xlsx ( self , * * kwargs ) : from xlsxwriter . workbook import Workbook as _Workbook self . workbook_obj = _Workbook ( * * kwargs ) self . workbook_obj . set_calc_mode ( self . calc_mode ) for worksheet in self . itersheets ( ) : worksheet . to_xlsx ( workbook = self ) self . workbook_obj . filename = self . filename if self . filename : self . workbook_obj . close ( ) return self . workbook_obj | Write workbook to a . xlsx file using xlsxwriter . Return a xlsxwriter . workbook . Workbook . | 129 | 29 |
11,586 | def get_table ( self , name ) : if name is None : assert self . active_table , "Can't get table without name unless an active table is set" name = self . active_table . name if self . active_worksheet : table = self . active_worksheet . get_table ( name ) assert table is self . active_table , "Active table is not from the active sheet" return table , self . active_worksheet for ws in self . worksheets : try : table = ws . get_table ( name ) if table is self . active_table : return table , ws except KeyError : pass raise RuntimeError ( "Active table not found in any sheet" ) # if the tablename explicitly uses the sheetname find the right sheet if "!" in name : ws_name , table_name = map ( lambda x : x . strip ( "'" ) , name . split ( "!" , 1 ) ) for ws in self . worksheets : if ws . name == ws_name : table = ws . get_table ( table_name ) return table , ws raise KeyError ( name ) # otherwise look in the current table if self . active_worksheet : table = self . active_worksheet . get_table ( name ) return table , self . active_worksheet # or fallback to the first matching name in any table for ws in self . worksheets : try : table = ws . get_table ( name ) return table , ws except KeyError : pass raise KeyError ( name ) | Return a table worksheet pair for the named table | 340 | 10 |
11,587 | def send_message ( self , output ) : file_system_event = None if self . my_action_input : file_system_event = self . my_action_input . file_system_event or None output_action = ActionInput ( file_system_event , output , self . name , "*" ) Global . MESSAGE_DISPATCHER . send_message ( output_action ) | Send a message to the socket | 90 | 6 |
11,588 | def stop ( self ) : Global . LOGGER . debug ( f"action {self.name} stopped" ) self . is_running = False self . on_stop ( ) | Stop the current action | 38 | 4 |
11,589 | def run ( self ) : Global . LOGGER . debug ( f"action {self.name} is running" ) for tmp_monitored_input in self . monitored_input : sender = "*" + tmp_monitored_input + "*" Global . LOGGER . debug ( f"action {self.name} is monitoring {sender}" ) while self . is_running : try : time . sleep ( Global . CONFIG_MANAGER . sleep_interval ) self . on_cycle ( ) except Exception as exc : Global . LOGGER . error ( f"error while running the action {self.name}: {str(exc)}" ) | Start the action | 141 | 3 |
11,590 | def create_action_for_code ( cls , action_code , name , configuration , managed_input ) : Global . LOGGER . debug ( f"creating action {name} for code {action_code}" ) Global . LOGGER . debug ( f"configuration length: {len(configuration)}" ) Global . LOGGER . debug ( f"input: {managed_input}" ) # get the actions catalog my_actions_file = Action . search_actions ( ) # load custom actions to find the right one for filename in my_actions_file : module_name = os . path . basename ( os . path . normpath ( filename ) ) [ : - 3 ] # garbage collect all the modules you load if they are not necessary context = { } Action . load_module ( module_name , filename ) for subclass in Action . __subclasses__ ( ) : if subclass . type == action_code : action_class = subclass action = action_class ( name , configuration , managed_input ) return action subclass = None gc . collect ( ) | Factory method to create an instance of an Action from an input code | 228 | 13 |
11,591 | def extract_class ( jar , name ) : with jar . open ( name ) as entry : return LinkableClass ( javatools . unpack_class ( entry ) ) | Extracts a LinkableClass from a jar . | 38 | 11 |
11,592 | def _format_summary_node ( self , task_class ) : modulename = task_class . __module__ classname = task_class . __name__ nodes = [ ] nodes . append ( self . _format_class_nodes ( task_class ) ) nodes . append ( self . _format_config_nodes ( modulename , classname ) ) methods = ( 'run' , 'runDataRef' ) for method in methods : if hasattr ( task_class , method ) : method_obj = getattr ( task_class , method ) nodes . append ( self . _format_method_nodes ( method_obj , modulename , classname ) ) return nodes | Format a section node containg a summary of a Task class s key APIs . | 151 | 17 |
11,593 | def _format_class_nodes ( self , task_class ) : # Patterned after PyObject.handle_signature in Sphinx. # https://github.com/sphinx-doc/sphinx/blob/3e57ea0a5253ac198c1bff16c40abe71951bb586/sphinx/domains/python.py#L246 modulename = task_class . __module__ classname = task_class . __name__ fullname = '.' . join ( ( modulename , classname ) ) # The signature term signature = Signature ( task_class , bound_method = False ) desc_sig_node = self . _format_signature ( signature , modulename , classname , fullname , 'py:class' ) # The content is the one-sentence summary. content_node = desc_content ( ) content_node += self . _create_doc_summary ( task_class , fullname , 'py:class' ) desc_node = desc ( ) desc_node [ 'noindex' ] = True desc_node [ 'domain' ] = 'py' desc_node [ 'objtype' ] = 'class' desc_node += desc_sig_node desc_node += content_node return desc_node | Create a desc node summarizing the class docstring . | 287 | 11 |
11,594 | def _format_method_nodes ( self , task_method , modulename , classname ) : methodname = task_method . __name__ fullname = '.' . join ( ( modulename , classname , methodname ) ) # The signature term signature = Signature ( task_method , bound_method = True ) desc_sig_node = self . _format_signature ( signature , modulename , classname , fullname , 'py:meth' ) # The content is the one-sentence summary. content_node = desc_content ( ) content_node += self . _create_doc_summary ( task_method , fullname , 'py:meth' ) desc_node = desc ( ) desc_node [ 'noindex' ] = True desc_node [ 'domain' ] = 'py' desc_node [ 'objtype' ] = 'method' desc_node += desc_sig_node desc_node += content_node return desc_node | Create a desc node summarizing a method docstring . | 216 | 11 |
11,595 | def _create_doc_summary ( self , obj , fullname , refrole ) : summary_text = extract_docstring_summary ( get_docstring ( obj ) ) summary_text = summary_text . strip ( ) # Strip the last "." because the linked ellipses take its place if summary_text . endswith ( '.' ) : summary_text = summary_text . rstrip ( '.' ) content_node_p = nodes . paragraph ( text = summary_text ) content_node_p += self . _create_api_details_link ( fullname , refrole ) return content_node_p | Create a paragraph containing the object s one - sentence docstring summary with a link to further documentation . | 136 | 20 |
11,596 | def _create_api_details_link ( self , fullname , refrole ) : ref_text = '... <{}>' . format ( fullname ) xref = PyXRefRole ( ) xref_nodes , _ = xref ( refrole , ref_text , ref_text , self . lineno , self . state . inliner ) return xref_nodes | Appends a link to the API docs labelled as ... that is appended to the content paragraph of an API description . | 85 | 24 |
11,597 | def _format_config_nodes ( self , modulename , classname ) : fullname = '{0}.{1}.config' . format ( modulename , classname ) # The signature term desc_sig_node = desc_signature ( ) desc_sig_node [ 'module' ] = modulename desc_sig_node [ 'class' ] = classname desc_sig_node [ 'fullname' ] = fullname prefix = 'attribute' desc_sig_node += desc_annotation ( prefix , prefix ) desc_sig_name_node = desc_addname ( 'config' , 'config' ) # Fakes the look of a cross reference. desc_sig_name_node [ 'classes' ] . extend ( [ 'xref' , 'py' ] ) desc_sig_node += desc_sig_name_node # The content is the one-sentence summary. summary_text = ( 'Access configuration fields and retargetable subtasks.' ) content_node_p = nodes . paragraph ( text = summary_text ) content_node = desc_content ( ) content_node += content_node_p desc_node = desc ( ) desc_node [ 'noindex' ] = True desc_node [ 'domain' ] = 'py' desc_node [ 'objtype' ] = 'attribute' desc_node += desc_sig_node desc_node += content_node return desc_node | Create a desc node summarizing the config attribute | 323 | 9 |
11,598 | def _format_import_example ( self , task_class ) : code = 'from {0.__module__} import {0.__name__}' . format ( task_class ) # This is a bare-bones version of what Sphinx's code-block directive # does. The 'language' attr triggers the pygments treatment. literal_node = nodes . literal_block ( code , code ) literal_node [ 'language' ] = 'py' return [ literal_node ] | Generate nodes that show a code sample demonstrating how to import the task class . | 106 | 16 |
11,599 | def _format_api_docs_link_message ( self , task_class ) : fullname = '{0.__module__}.{0.__name__}' . format ( task_class ) p_node = nodes . paragraph ( ) _ = 'See the ' p_node += nodes . Text ( _ , _ ) xref = PyXRefRole ( ) xref_nodes , _ = xref ( 'py:class' , '~' + fullname , '~' + fullname , self . lineno , self . state . inliner ) p_node += xref_nodes _ = ' API reference for complete details.' p_node += nodes . Text ( _ , _ ) seealso_node = seealso ( ) seealso_node += p_node return [ seealso_node ] | Format a message referring the reader to the full API docs . | 178 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.