idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
11,500 | def build_options ( self ) : if self . version . build_metadata : return set ( self . version . build_metadata . split ( '.' ) ) else : return set ( ) | The package build options . |
11,501 | def clearSelection ( self ) : first = None editors = self . editors ( ) for editor in editors : if not editor . selectedText ( ) : continue first = first or editor editor . backspace ( ) for editor in editors : editor . setFocus ( ) if first : first . setFocus ( ) | Clears the selected text for this edit . |
11,502 | def cut ( self ) : text = self . selectedText ( ) for editor in self . editors ( ) : editor . cut ( ) QtGui . QApplication . clipboard ( ) . setText ( text ) | Cuts the text from the serial to the clipboard . |
11,503 | def goBack ( self ) : index = self . indexOf ( self . currentEditor ( ) ) if index == - 1 : return previous = self . editorAt ( index - 1 ) if previous : previous . setFocus ( ) previous . setCursorPosition ( self . sectionLength ( ) ) | Moves the cursor to the end of the previous editor |
11,504 | def goForward ( self ) : index = self . indexOf ( self . currentEditor ( ) ) if index == - 1 : return next = self . editorAt ( index + 1 ) if next : next . setFocus ( ) next . setCursorPosition ( 0 ) | Moves the cursor to the beginning of the next editor . |
11,505 | def selectAll ( self ) : self . blockEditorHandling ( True ) for editor in self . editors ( ) : editor . selectAll ( ) self . blockEditorHandling ( False ) | Selects the text within all the editors . |
11,506 | async def disable ( self , reason = None ) : params = { "enable" : True , "reason" : reason } response = await self . _api . put ( "/v1/agent/maintenance" , params = params ) return response . status == 200 | Enters maintenance mode |
11,507 | async def enable ( self , reason = None ) : params = { "enable" : False , "reason" : reason } response = await self . _api . put ( "/v1/agent/maintenance" , params = params ) return response . status == 200 | Resumes normal operation |
11,508 | def parse_datetime ( dt ) : d = datetime . strptime ( dt [ : - 1 ] , ISOFORMAT ) if dt [ - 1 : ] == 'Z' : return timezone ( 'utc' ) . localize ( d ) else : return d | Parse an ISO datetime which Python does buggily . |
11,509 | def refreshRecords ( self ) : table_type = self . tableType ( ) if ( not table_type ) : self . _records = RecordSet ( ) return False search = nativestring ( self . uiSearchTXT . text ( ) ) query = self . query ( ) . copy ( ) terms , search_query = Q . fromSearch ( search ) if ( search_query ) : query &= search_query self . _records = table_type . select ( where = query ) . search ( terms ) return True | Refreshes the records being loaded by this browser . |
11,510 | def refreshResults ( self ) : if ( self . currentMode ( ) == XOrbBrowserWidget . Mode . Detail ) : self . refreshDetails ( ) elif ( self . currentMode ( ) == XOrbBrowserWidget . Mode . Card ) : self . refreshCards ( ) else : self . refreshThumbnails ( ) | Joins together the queries from the fixed system the search and the query builder to generate a query for the browser to display . |
11,511 | def refreshCards ( self ) : cards = self . cardWidget ( ) factory = self . factory ( ) self . setUpdatesEnabled ( False ) self . blockSignals ( True ) cards . setUpdatesEnabled ( False ) cards . blockSignals ( True ) cards . clear ( ) QApplication . instance ( ) . processEvents ( ) if ( self . isGroupingActive ( ) ) : grouping = self . records ( ) . grouped ( ) for groupName , records in sorted ( grouping . items ( ) ) : self . _loadCardGroup ( groupName , records , cards ) else : for record in self . records ( ) : widget = factory . createCard ( cards , record ) if ( not widget ) : continue widget . adjustSize ( ) item = QTreeWidgetItem ( cards ) item . setSizeHint ( 0 , QSize ( 0 , widget . height ( ) ) ) cards . setItemWidget ( item , 0 , widget ) cards . setUpdatesEnabled ( True ) cards . blockSignals ( False ) self . setUpdatesEnabled ( True ) self . blockSignals ( False ) | Refreshes the results for the cards view of the browser . |
11,512 | def refreshDetails ( self ) : tree = self . uiRecordsTREE tree . blockSignals ( True ) tree . setRecordSet ( self . records ( ) ) tree . blockSignals ( False ) | Refreshes the results for the details view of the browser . |
11,513 | def refreshThumbnails ( self ) : widget = self . thumbnailWidget ( ) widget . setUpdatesEnabled ( False ) widget . blockSignals ( True ) widget . clear ( ) widget . setIconSize ( self . thumbnailSize ( ) ) factory = self . factory ( ) if ( self . isGroupingActive ( ) ) : grouping = self . records ( ) . grouped ( ) for groupName , records in sorted ( grouping . items ( ) ) : self . _loadThumbnailGroup ( groupName , records ) else : for record in self . records ( ) : thumbnail = factory . thumbnail ( record ) text = factory . thumbnailText ( record ) RecordListWidgetItem ( thumbnail , text , record , widget ) widget . setUpdatesEnabled ( True ) widget . blockSignals ( False ) | Refreshes the thumbnails view of the browser . |
11,514 | def showGroupMenu ( self ) : group_active = self . isGroupingActive ( ) group_by = self . groupBy ( ) menu = XMenu ( self ) menu . setTitle ( 'Grouping Options' ) menu . setShowTitle ( True ) menu . addAction ( 'Edit Advanced Grouping' ) menu . addSeparator ( ) action = menu . addAction ( 'No Grouping' ) action . setCheckable ( True ) action . setChecked ( not group_active ) action = menu . addAction ( 'Advanced' ) action . setCheckable ( True ) action . setChecked ( group_by == self . GroupByAdvancedKey and group_active ) if ( group_by == self . GroupByAdvancedKey ) : font = action . font ( ) font . setBold ( True ) action . setFont ( font ) menu . addSeparator ( ) tableType = self . tableType ( ) if ( tableType ) : columns = tableType . schema ( ) . columns ( ) columns . sort ( key = lambda x : x . displayName ( ) ) for column in columns : action = menu . addAction ( column . displayName ( ) ) action . setCheckable ( True ) action . setChecked ( group_by == column . displayName ( ) and group_active ) if ( column . displayName ( ) == group_by ) : font = action . font ( ) font . setBold ( True ) action . setFont ( font ) point = QPoint ( 0 , self . uiGroupOptionsBTN . height ( ) ) action = menu . exec_ ( self . uiGroupOptionsBTN . mapToGlobal ( point ) ) if ( not action ) : return elif ( action . text ( ) == 'Edit Advanced Grouping' ) : print 'edit advanced grouping options' elif ( action . text ( ) == 'No Grouping' ) : self . setGroupingActive ( False ) elif ( action . text ( ) == 'Advanced' ) : self . uiGroupBTN . blockSignals ( True ) self . setGroupBy ( self . GroupByAdvancedKey ) self . setGroupingActive ( True ) self . uiGroupBTN . blockSignals ( False ) self . refreshResults ( ) else : self . uiGroupBTN . blockSignals ( True ) self . setGroupBy ( nativestring ( action . text ( ) ) ) self . setGroupingActive ( True ) self . uiGroupBTN . blockSignals ( False ) self . refreshResults ( ) | Displays the group menu to the user for modification . |
11,515 | def get_settings ( ) : s = getattr ( settings , 'CLAMAV_UPLOAD' , { } ) s = { 'CONTENT_TYPE_CHECK_ENABLED' : s . get ( 'CONTENT_TYPE_CHECK_ENABLED' , False ) , 'LAST_HANDLER' : getattr ( settings , 'FILE_UPLOAD_HANDLERS' ) [ - 1 ] } return s | This function returns a dict containing default settings |
11,516 | def clear ( self ) : self . _xroot = ElementTree . Element ( 'settings' ) self . _xroot . set ( 'version' , '1.0' ) self . _xstack = [ self . _xroot ] | Clears the settings for this XML format . |
11,517 | def clear ( self ) : if self . _customFormat : self . _customFormat . clear ( ) else : super ( XSettings , self ) . clear ( ) | Clears out all the settings for this instance . |
11,518 | def endGroup ( self ) : if self . _customFormat : self . _customFormat . endGroup ( ) else : super ( XSettings , self ) . endGroup ( ) | Ends the current group of xml data . |
11,519 | def load ( self ) : if self . _customFormat and os . path . exists ( self . fileName ( ) ) : self . _customFormat . load ( self . fileName ( ) ) | Loads the settings from disk for this XSettings object if it is a custom format . |
11,520 | def sync ( self ) : if self . _customFormat : self . _customFormat . save ( self . fileName ( ) ) else : super ( XSettings , self ) . sync ( ) | Syncs the information for this settings out to the file system . |
11,521 | def clear ( self ) : layout = self . _entryWidget . layout ( ) for i in range ( layout . count ( ) - 1 ) : widget = layout . itemAt ( i ) . widget ( ) widget . close ( ) | Clears out the widgets for this query builder . |
11,522 | def moveDown ( self , entry ) : if not entry : return entries = self . entries ( ) next = entries [ entries . index ( entry ) + 1 ] entry_q = entry . query ( ) next_q = next . query ( ) next . setQuery ( entry_q ) entry . setQuery ( next_q ) | Moves the current query down one entry . |
11,523 | def _selectTree ( self ) : self . uiGanttTREE . blockSignals ( True ) self . uiGanttTREE . clearSelection ( ) for item in self . uiGanttVIEW . scene ( ) . selectedItems ( ) : item . treeItem ( ) . setSelected ( True ) self . uiGanttTREE . blockSignals ( False ) | Matches the tree selection to the views selection . |
11,524 | def _selectView ( self ) : scene = self . uiGanttVIEW . scene ( ) scene . blockSignals ( True ) scene . clearSelection ( ) for item in self . uiGanttTREE . selectedItems ( ) : item . viewItem ( ) . setSelected ( True ) scene . blockSignals ( False ) curr_item = self . uiGanttTREE . currentItem ( ) vitem = curr_item . viewItem ( ) if vitem : self . uiGanttVIEW . centerOn ( vitem ) | Matches the view selection to the trees selection . |
11,525 | def _updateViewRect ( self ) : if not self . updatesEnabled ( ) : return header_h = self . _cellHeight * 2 rect = self . uiGanttVIEW . scene ( ) . sceneRect ( ) sbar_max = self . uiGanttTREE . verticalScrollBar ( ) . maximum ( ) sbar_max += self . uiGanttTREE . viewport ( ) . height ( ) + header_h widget_max = self . uiGanttVIEW . height ( ) widget_max -= ( self . uiGanttVIEW . horizontalScrollBar ( ) . height ( ) + 10 ) rect . setHeight ( max ( widget_max , sbar_max ) ) self . uiGanttVIEW . scene ( ) . setSceneRect ( rect ) | Updates the view rect to match the current tree value . |
11,526 | def syncView ( self ) : if not self . updatesEnabled ( ) : return for item in self . topLevelItems ( ) : try : item . syncView ( recursive = True ) except AttributeError : continue | Syncs all the items to the view . |
11,527 | def get_data_path ( package , resource ) : loader = pkgutil . get_loader ( package ) if loader is None or not hasattr ( loader , 'get_data' ) : raise PackageResourceError ( "Failed to load package: '{0}'" . format ( package ) ) mod = sys . modules . get ( package ) or loader . load_module ( package ) if mod is None or not hasattr ( mod , '__file__' ) : raise PackageResourceError ( "Failed to load module: '{0}'" . format ( package ) ) parts = resource . split ( '/' ) parts . insert ( 0 , os . path . dirname ( mod . __file__ ) ) resource_name = os . path . join ( * parts ) return resource_name | Return the full file path of a resource of a package . |
11,528 | def scrollToEnd ( self ) : vsbar = self . verticalScrollBar ( ) vsbar . setValue ( vsbar . maximum ( ) ) hbar = self . horizontalScrollBar ( ) hbar . setValue ( 0 ) | Scrolls to the end for this console edit . |
11,529 | def assignQuery ( self ) : self . uiRecordTREE . setQuery ( self . _queryWidget . query ( ) , autoRefresh = True ) | Assigns the query from the query widget to the edit . |
11,530 | def refresh ( self ) : table = self . tableType ( ) if table : table . markTableCacheExpired ( ) self . uiRecordTREE . searchRecords ( self . uiSearchTXT . text ( ) ) | Commits changes stored in the interface to the database . |
11,531 | def parse ( self , url ) : parsed_url = urlparse . urlparse ( url ) try : default_config = self . CONFIG [ parsed_url . scheme ] except KeyError : raise ValueError ( 'unrecognised URL scheme for {}: {}' . format ( self . __class__ . __name__ , url ) ) handler = self . get_handler_for_scheme ( parsed_url . scheme ) config = copy . deepcopy ( default_config ) return handler ( parsed_url , config ) | Return a configuration dict from a URL |
11,532 | def get_auto_config ( self ) : methods = [ m for m in dir ( self ) if m . startswith ( 'auto_config_' ) ] for method_name in sorted ( methods ) : auto_config_method = getattr ( self , method_name ) url = auto_config_method ( self . env ) if url : return url | Walk over all available auto_config methods passing them the current environment and seeing if they return a configuration URL |
11,533 | def Process ( self , request , context ) : LOG . debug ( "Process called" ) try : metrics = self . plugin . process ( [ Metric ( pb = m ) for m in request . Metrics ] , ConfigMap ( pb = request . Config ) ) return MetricsReply ( metrics = [ m . pb for m in metrics ] ) except Exception as err : msg = "message: {}\n\nstack trace: {}" . format ( err , traceback . format_exc ( ) ) return MetricsReply ( metrics = [ ] , error = msg ) | Dispatches the request to the plugins process method |
11,534 | async def join ( self , address , * , wan = None ) : response = await self . _api . get ( "/v1/agent/join" , address , params = { "wan" : wan } ) return response . status == 200 | Triggers the local agent to join a node |
11,535 | async def force_leave ( self , node ) : node_id = extract_attr ( node , keys = [ "Node" , "ID" ] ) response = await self . _get ( "/v1/agent/force-leave" , node_id ) return response . status == 200 | Forces removal of a node |
11,536 | def gotoNext ( self ) : index = self . _currentPanel . currentIndex ( ) + 1 if ( self . _currentPanel . count ( ) == index ) : index = 0 self . _currentPanel . setCurrentIndex ( index ) | Goes to the next panel tab . |
11,537 | def gotoPrevious ( self ) : index = self . _currentPanel . currentIndex ( ) - 1 if index < 0 : index = self . _currentPanel . count ( ) - 1 self . _currentPanel . setCurrentIndex ( index ) | Goes to the previous panel tab . |
11,538 | def newPanelTab ( self ) : view = self . _currentPanel . currentView ( ) if view : new_view = view . duplicate ( self . _currentPanel ) self . _currentPanel . addTab ( new_view , new_view . windowTitle ( ) ) | Creates a new panel with a copy of the current widget . |
11,539 | def renamePanel ( self ) : index = self . _currentPanel . currentIndex ( ) title = self . _currentPanel . tabText ( index ) new_title , accepted = QInputDialog . getText ( self , 'Rename Tab' , 'Name:' , QLineEdit . Normal , title ) if accepted : widget = self . _currentPanel . currentView ( ) widget . setWindowTitle ( new_title ) self . _currentPanel . setTabText ( index , new_title ) | Prompts the user for a custom name for the current panel tab . |
11,540 | def reload ( self ) : enum = self . _enum if not enum : return self . clear ( ) if not self . isRequired ( ) : self . addItem ( '' ) if self . sortByKey ( ) : self . addItems ( sorted ( enum . keys ( ) ) ) else : items = enum . items ( ) items . sort ( key = lambda x : x [ 1 ] ) self . addItems ( map ( lambda x : x [ 0 ] , items ) ) | Reloads the contents for this box . |
11,541 | def recalculate ( self ) : scene = self . scene ( ) w = self . calculateSceneWidth ( ) scene . setSceneRect ( 0 , 0 , w , self . height ( ) ) spacing = self . spacing ( ) x = self . width ( ) / 4.0 y = self . height ( ) / 2.0 for item in self . items ( ) : pmap = item . pixmap ( ) item . setPos ( x , y - pmap . height ( ) / 1.5 ) x += pmap . size ( ) . width ( ) + spacing | Recalcualtes the slider scene for this widget . |
11,542 | def _check_token ( self ) : need_token = ( self . _token_info is None or self . auth_handler . is_token_expired ( self . _token_info ) ) if need_token : new_token = self . auth_handler . refresh_access_token ( self . _token_info [ 'refresh_token' ] ) if new_token is None : return self . _token_info = new_token self . _auth_header = { "content-type" : "application/json" , "Authorization" : "Bearer {}" . format ( self . _token_info . get ( 'access_token' ) ) } | Simple Mercedes me API . |
11,543 | def get_location ( self , car_id ) : _LOGGER . debug ( "get_location for %s called" , car_id ) api_result = self . _retrieve_api_result ( car_id , API_LOCATION ) _LOGGER . debug ( "get_location result: %s" , api_result ) location = Location ( ) for loc_option in LOCATION_OPTIONS : curr_loc_option = api_result . get ( loc_option ) value = CarAttribute ( curr_loc_option . get ( "value" ) , curr_loc_option . get ( "retrievalstatus" ) , curr_loc_option . get ( "timestamp" ) ) setattr ( location , loc_option , value ) return location | get refreshed location information . |
11,544 | async def create ( self , token ) : token = encode_token ( token ) response = await self . _api . put ( "/v1/acl/create" , data = token ) return response . body | Creates a new token with a given policy |
11,545 | async def destroy ( self , token ) : token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/acl/destroy" , token_id ) return response . body | Destroys a given token . |
11,546 | async def info ( self , token ) : token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . get ( "/v1/acl/info" , token_id ) meta = extract_meta ( response . headers ) try : result = decode_token ( response . body [ 0 ] ) except IndexError : raise NotFound ( response . body , meta = meta ) return consul ( result , meta = meta ) | Queries the policy of a given token . |
11,547 | 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 |
11,548 | 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 |
11,549 | 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 |
11,550 | def make_unique_endings ( strings_collection ) : res = [ ] for i in range ( len ( strings_collection ) ) : 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 . |
11,551 | 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 |
11,552 | 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 . |
11,553 | 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 |
11,554 | 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 |
11,555 | 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 |
11,556 | 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 |
11,557 | 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 . |
11,558 | 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 ( ) ) try : schema = schemata [ lookup ] except KeyError : 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 , } | Filters given entity queryset by an attribute which is linked to given many - to - many schema . |
11,559 | 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 ( ) ) 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 ) ) ) instance = self . model ( ** dict ( ( k , v ) for k , v in kwargs . items ( ) if k in fields ) ) for name , value in kwargs . items ( ) : setattr ( instance , name , value ) instance . save ( force_insert = True ) return instance | Creates entity instance and related Attr instances . |
11,560 | 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 . |
11,561 | def saveProfile ( self ) : manager = self . parent ( ) prof = manager . currentProfile ( ) save_prof = manager . viewWidget ( ) . saveProfile ( ) prof . setXmlElement ( save_prof . xmlElement ( ) ) | Saves the current profile to the current settings from the view widget . |
11,562 | 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 . |
11,563 | def hexdump ( logger , s , width = 16 , skip = True , hexii = False , begin = 0 , highlight = None ) : r s = _flat ( s ) return '\n' . join ( hexdump_iter ( logger , StringIO ( s ) , width , skip , hexii , begin , highlight ) ) | r Return a hexdump - dump of a string . |
11,564 | 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 . |
11,565 | def adjustButtons ( self ) : y = 1 for btn in self . buttons ( ) : btn . setIconSize ( self . iconSize ( ) ) btn . setFixedSize ( QSize ( self . height ( ) - 2 , self . height ( ) - 2 ) ) 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 ( ) 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 . |
11,566 | 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 . |
11,567 | def clear ( self ) : super ( XLineEdit , self ) . clear ( ) self . textEntered . emit ( '' ) self . textChanged . emit ( '' ) self . textEdited . emit ( '' ) | Clears the text from the edit . |
11,568 | def get ( cap , * args , ** kwargs ) : if 'READTHEDOCS' in os . environ : return '' if kwargs != { } : raise TypeError ( "get(): No such argument %r" % kwargs . popitem ( ) [ 0 ] ) if _cache == { } : 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 : s = '' else : s = bool ( s ) _cache [ cap ] = s 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 . |
11,569 | 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 |
11,570 | 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 . |
11,571 | 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 . |
11,572 | def adjustMinimumWidth ( self ) : pw = self . pixmapSize ( ) . width ( ) 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 . |
11,573 | 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 |
11,574 | 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 . |
11,575 | 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 } } 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 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 ) for n , atom in mol . atoms_iter ( ) : if not atom . visible : continue p = atom . coords color = atom . color 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 : text = atom . formula_html ( True ) canvas . draw_text ( p , text , color , "right" ) continue elif max ( cosnbrs ) < 0 : text = atom . formula_html ( ) canvas . draw_text ( p , text , color , "left" ) continue text = atom . formula_html ( ) canvas . draw_text ( p , text , color , "center" ) | Draw molecule structure image . |
11,576 | 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 |
11,577 | 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 |
11,578 | 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 |
11,579 | 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 |
11,580 | 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 |
11,581 | def get ( self , url , store_on_error = False , xpath = None , rate_limit = None , log_hits = True , log_misses = True ) : try : cached = self . _query ( url , xpath ) . one ( ) if log_hits : config . logger . info ( "Request cache hit: " + url ) 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 ) try : 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 content = response . text response . close ( ) if xpath is not None : doc = html . fromstring ( content ) nodes = doc . xpath ( xpath ) if len ( nodes ) == 0 : content = "xpath not found: " + xpath status_code = ERROR_XPATH_NOT_FOUND else : content = html . tostring ( nodes [ 0 ] , encoding = 'unicode' ) except requests . ConnectionError as e : status_code = ERROR_CONNECTION_ERROR content = str ( e ) cached = CachedRequest ( url = str ( url ) , content = content , status_code = status_code , xpath = xpath , queried_on = datetime . datetime . now ( ) ) 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 . |
11,582 | 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 . |
11,583 | 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 . |
11,584 | 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 |
11,585 | 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 . |
11,586 | 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.' 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.' id = self . meta . find_group_by_name ( group ) [ 0 ] elif channel is not None : 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 . |
11,587 | 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 . |
11,588 | 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 |
11,589 | 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 . |
11,590 | def retransmit ( self , data ) : 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 : 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 : self . listener . send_datagram ( serialize_data ( data , self . compression , self . encryption , self . server_key ) , self . server ) 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 . |
11,591 | def handle_message ( self , msg , host ) : logger . debug ( "Executing handle_message method." ) response = None if self . encryption and self . server_key : msg_data = unserialize_data ( msg , self . compression , self . encryption ) else : msg_data = unserialize_data ( msg , self . compression ) logger . debug ( "Packet received: " + pformat ( msg_data ) ) 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" ] ] 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 ) ) ) 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 "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 ) 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 |
11,592 | 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 . |
11,593 | 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." ) message = { "method" : "REGISTER" , "cuuid" : str ( self . cuuid ) } if self . encryption : message [ "encryption" ] = [ self . encryption . n , self . encryption . e ] self . listener . send_datagram ( serialize_data ( message , self . compression , encryption = False ) , address ) if retry : self . register_retries = 0 self . listener . call_later ( self . timeout , self . retransmit , { "method" : "REGISTER" , "address" : address } ) | This function will send a register packet to the discovered Neteria server . |
11,594 | def event ( self , event_data , priority = "normal" , event_method = "EVENT" ) : logger . debug ( "event: " + str ( event_data ) ) 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 not self . registered : logger . warning ( "<%s> <euuid:%s> Client is currently not registered. " "Event not sent." % ( str ( self . cuuid ) , str ( euuid ) ) ) return False 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 ) ) ) self . event_uuids [ str ( euuid ) ] = packet 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 . |
11,595 | def legal_check ( self , message ) : 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 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 : 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" ] ) ) 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 . |
11,596 | 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 |
11,597 | 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 |
11,598 | 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 |
11,599 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.