idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
23,700 | def aggregate ( self , other = None ) : if not self . status : return self if not other : return self if not other . status : return other return Value ( True , other . index , self . value + other . value , None ) | collect the furthest failure from self and other . |
23,701 | def combinate ( values ) : prev_v = None for v in values : if prev_v : if not v : return prev_v if not v . status : return v out_values = tuple ( [ v . value for v in values ] ) return Value ( True , values [ - 1 ] . index , out_values , None ) | aggregate multiple values into tuple |
23,702 | def parse_partial ( self , text ) : if not isinstance ( text , str ) : raise TypeError ( 'Can only parsing string but got {!r}' . format ( text ) ) res = self ( text , 0 ) if res . status : return ( res . value , text [ res . index : ] ) else : raise ParseError ( res . expected , text , res . index ) | Parse the longest possible prefix of a given string . Return a tuple of the result value and the rest of the string . If failed raise a ParseError . |
23,703 | def bind ( self , fn ) : @ Parser def bind_parser ( text , index ) : res = self ( text , index ) return res if not res . status else fn ( res . value ) ( text , res . index ) return bind_parser | This is the monadic binding operation . Returns a parser which if parser is successful passes the result to fn and continues with the parser returned from fn . |
23,704 | def parsecmap ( self , fn ) : return self . bind ( lambda res : Parser ( lambda _ , index : Value . success ( index , fn ( res ) ) ) ) | Returns a parser that transforms the produced value of parser with fn . |
23,705 | def parsecapp ( self , other ) : return self . bind ( lambda res : other . parsecmap ( lambda x : res ( x ) ) ) | Returns a parser that applies the produced value of this parser to the produced value of other . |
23,706 | def result ( self , res ) : return self >> Parser ( lambda _ , index : Value . success ( index , res ) ) | Return a value according to the parameter res when parse successfully . |
23,707 | def mark ( self ) : def pos ( text , index ) : return ParseError . loc_info ( text , index ) @ Parser def mark_parser ( text , index ) : res = self ( text , index ) if res . status : return Value . success ( res . index , ( pos ( text , index ) , res . value , pos ( text , res . index ) ) ) else : return res return mar... | Mark the line and column information of the result of this parser . |
23,708 | def desc ( self , description ) : return self | Parser ( lambda _ , index : Value . failure ( index , description ) ) | Describe a parser when it failed print out the description text . |
23,709 | def route ( * args ) : def _validate_route ( route ) : if not isinstance ( route , six . string_types ) : raise TypeError ( '%s must be a string' % route ) if route in ( '.' , '..' ) or not re . match ( '^[0-9a-zA-Z-_$\(\)\.~!,;:*+@=]+$' , route ) : raise ValueError ( '%s must be a valid path segment. Keep in mind ' '... | This function is used to define an explicit route for a path segment . |
23,710 | def lookup_controller ( obj , remainder , request = None ) : if request is None : warnings . warn ( ( "The function signature for %s.lookup_controller is changing " "in the next version of pecan.\nPlease update to: " "`lookup_controller(self, obj, remainder, request)`." % ( __name__ , ) ) , DeprecationWarning ) notfoun... | Traverses the requested url path and returns the appropriate controller object including default routes . |
23,711 | def find_object ( obj , remainder , notfound_handlers , request ) : prev_obj = None while True : if obj is None : raise PecanNotFound if iscontroller ( obj ) : if getattr ( obj , 'custom_route' , None ) is None : return obj , remainder _detect_custom_path_segments ( obj ) if remainder : custom_route = __custom_routes__... | Walks the url path in search of an action for which a controller is implemented and returns that controller object along with what s left of the remainder . |
23,712 | def unlocked ( func_or_obj ) : if ismethod ( func_or_obj ) or isfunction ( func_or_obj ) : return _unlocked_method ( func_or_obj ) else : return _UnlockedAttribute ( func_or_obj ) | This method unlocks method or class attribute on a SecureController . Can be used to decorate or wrap an attribute |
23,713 | def secure ( func_or_obj , check_permissions_for_obj = None ) : if _allowed_check_permissions_types ( func_or_obj ) : return _secure_method ( func_or_obj ) else : if not _allowed_check_permissions_types ( check_permissions_for_obj ) : msg = "When securing an object, secure() requires the " + "second argument to be meth... | This method secures a method or class depending on invocation . |
23,714 | def _make_wrapper ( f ) : @ wraps ( f ) def wrapper ( * args , ** kwargs ) : return f ( * args , ** kwargs ) wrapper . _pecan = f . _pecan . copy ( ) return wrapper | return a wrapped function with a copy of the _pecan context |
23,715 | def handle_security ( controller , im_self = None ) : if controller . _pecan . get ( 'secured' , False ) : check_permissions = controller . _pecan [ 'check_permissions' ] if isinstance ( check_permissions , six . string_types ) : check_permissions = getattr ( im_self or six . get_method_self ( controller ) , check_perm... | Checks the security of a controller . |
23,716 | def cross_boundary ( prev_obj , obj ) : if prev_obj is None : return if isinstance ( obj , _SecuredAttribute ) : obj . parent = prev_obj if hasattr ( prev_obj , '_pecan' ) : if obj not in prev_obj . _pecan . get ( 'unlocked' , [ ] ) : handle_security ( prev_obj ) | Check permissions as we move between object instances . |
23,717 | def makedirs ( directory ) : parent = os . path . dirname ( os . path . abspath ( directory ) ) if not os . path . exists ( parent ) : makedirs ( parent ) os . mkdir ( directory ) | Resursively create a named directory . |
23,718 | def substitute_filename ( fn , variables ) : for var , value in variables . items ( ) : fn = fn . replace ( '+%s+' % var , str ( value ) ) return fn | Substitute + variables + in file directory names . |
23,719 | def make_app ( root , ** kw ) : logging = kw . get ( 'logging' , { } ) debug = kw . get ( 'debug' , False ) if logging : if debug : try : from logging import captureWarnings captureWarnings ( True ) warnings . simplefilter ( "default" , DeprecationWarning ) except ImportError : pass if isinstance ( logging , Config ) :... | Utility for creating the Pecan application object . This function should generally be called from the setup_app function in your project s app . py file . |
23,720 | def conf_from_file ( filepath ) : abspath = os . path . abspath ( os . path . expanduser ( filepath ) ) conf_dict = { } if not os . path . isfile ( abspath ) : raise RuntimeError ( '`%s` is not a file.' % abspath ) with open ( abspath , 'rb' ) as f : compiled = compile ( f . read ( ) , abspath , 'exec' ) absname , _ = ... | Creates a configuration dictionary from a file . |
23,721 | def get_conf_path_from_env ( ) : config_path = os . environ . get ( 'PECAN_CONFIG' ) if not config_path : error = "PECAN_CONFIG is not set and " "no config file was passed as an argument." elif not os . path . isfile ( config_path ) : error = "PECAN_CONFIG was set to an invalid path: %s" % config_path else : return con... | If the PECAN_CONFIG environment variable exists and it points to a valid path it will return that otherwise it will raise a RuntimeError . |
23,722 | def conf_from_dict ( conf_dict ) : conf = Config ( filename = conf_dict . get ( '__file__' , '' ) ) for k , v in six . iteritems ( conf_dict ) : if k . startswith ( '__' ) : continue elif inspect . ismodule ( v ) : continue conf [ k ] = v return conf | Creates a configuration dictionary from a dictionary . |
23,723 | def set_config ( config , overwrite = False ) : if config is None : config = get_conf_path_from_env ( ) if overwrite is True : _runtime_conf . empty ( ) if isinstance ( config , six . string_types ) : config = conf_from_file ( config ) _runtime_conf . update ( config ) if config . __file__ : _runtime_conf . __file__ = ... | Updates the global configuration . |
23,724 | def update ( self , conf_dict ) : if isinstance ( conf_dict , dict ) : iterator = six . iteritems ( conf_dict ) else : iterator = iter ( conf_dict ) for k , v in iterator : if not IDENTIFIER . match ( k ) : raise ValueError ( '\'%s\' is not a valid indentifier' % k ) cur_val = self . __values__ . get ( k ) if isinstanc... | Updates this configuration with a dictionary . |
23,725 | def to_dict ( self , prefix = None ) : conf_obj = dict ( self ) return self . __dictify__ ( conf_obj , prefix ) | Converts recursively the Config object into a valid dictionary . |
23,726 | def override_template ( template , content_type = None ) : request . pecan [ 'override_template' ] = template if content_type : request . pecan [ 'override_content_type' ] = content_type | Call within a controller to override the template that is used in your response . |
23,727 | def abort ( status_code , detail = '' , headers = None , comment = None , ** kw ) : try : _ , _ , traceback = sys . exc_info ( ) webob_exception = exc . status_map [ status_code ] ( detail = detail , headers = headers , comment = comment , ** kw ) if six . PY3 : raise webob_exception . with_traceback ( traceback ) else... | Raise an HTTP status code as specified . Useful for returning status codes like 401 Unauthorized or 403 Forbidden . |
23,728 | def redirect ( location = None , internal = False , code = None , headers = { } , add_slash = False , request = None ) : request = request or state . request if add_slash : if location is None : split_url = list ( urlparse . urlsplit ( request . url ) ) new_proto = request . environ . get ( 'HTTP_X_FORWARDED_PROTO' , s... | Perform a redirect either internal or external . An internal redirect performs the redirect server - side while the external redirect utilizes an HTTP 302 status code . |
23,729 | def load_app ( config , ** kwargs ) : from . configuration import _runtime_conf , set_config set_config ( config , overwrite = True ) for package_name in getattr ( _runtime_conf . app , 'modules' , [ ] ) : module = __import__ ( package_name , fromlist = [ 'app' ] ) if hasattr ( module , 'app' ) and hasattr ( module . a... | Used to load a Pecan application and its environment based on passed configuration . |
23,730 | def route ( self , req , node , path ) : path = path . split ( '/' ) [ 1 : ] try : node , remainder = lookup_controller ( node , path , req ) return node , remainder except NonCanonicalPath as e : if self . force_canonical and not _cfg ( e . controller ) . get ( 'accept_noncanonical' , False ) : if req . method == 'POS... | Looks up a controller from a node based upon the specified path . |
23,731 | def determine_hooks ( self , controller = None ) : controller_hooks = [ ] if controller : controller_hooks = _cfg ( controller ) . get ( 'hooks' , [ ] ) if controller_hooks : return list ( sorted ( chain ( controller_hooks , self . hooks ) , key = operator . attrgetter ( 'priority' ) ) ) return self . hooks | Determines the hooks to be run in which order . |
23,732 | def handle_hooks ( self , hooks , hook_type , * args ) : if hook_type not in [ 'before' , 'on_route' ] : hooks = reversed ( hooks ) for hook in hooks : result = getattr ( hook , hook_type ) ( * args ) if hook_type == 'on_error' and isinstance ( result , WebObResponse ) : return result | Processes hooks of the specified type . |
23,733 | def get_args ( self , state , all_params , remainder , argspec , im_self ) : args = [ ] varargs = [ ] kwargs = dict ( ) valid_args = argspec . args [ : ] if ismethod ( state . controller ) or im_self : valid_args . pop ( 0 ) pecan_state = state . request . pecan remainder = [ x for x in remainder if x ] if im_self is n... | Determines the arguments for a controller based upon parameters passed the argument specification for the controller . |
23,734 | def run ( self , args ) : super ( ShellCommand , self ) . run ( args ) app = self . load_app ( ) locs = dict ( __name__ = 'pecan-admin' ) locs [ 'wsgiapp' ] = app locs [ 'app' ] = TestApp ( app ) model = self . load_model ( app . config ) if model : locs [ 'model' ] = model from pecan import abort , conf , redirect , r... | Load the pecan app prepare the locals sets the banner and invokes the python shell . |
23,735 | def load_model ( self , config ) : for package_name in getattr ( config . app , 'modules' , [ ] ) : module = __import__ ( package_name , fromlist = [ 'model' ] ) if hasattr ( module , 'model' ) : return module . model return None | Load the model extension module |
23,736 | def _handle_bad_rest_arguments ( self , controller , remainder , request ) : argspec = self . _get_args_for_controller ( controller ) fixed_args = len ( argspec ) - len ( request . pecan . get ( 'routing_args' , [ ] ) ) if len ( remainder ) < fixed_args : abort ( 404 ) | Ensure that the argspec for a discovered controller actually matched the positional arguments in the request path . If not raise a webob . exc . HTTPBadRequest . |
23,737 | def _route ( self , args , request = None ) : if request is None : from pecan import request method = request . params . get ( '_method' , request . method ) . lower ( ) if request . method == 'GET' and method in ( 'delete' , 'put' ) : abort ( 405 ) result = self . _find_sub_controllers ( args , request ) if result : r... | Routes a request to the appropriate controller and returns its result . |
23,738 | def _find_controller ( self , * args ) : for name in args : obj = self . _lookup_child ( name ) if obj and iscontroller ( obj ) : return obj return None | Returns the appropriate controller for routing a custom action . |
23,739 | def _find_sub_controllers ( self , remainder , request ) : method = None for name in ( 'get_one' , 'get' ) : if hasattr ( self , name ) : method = name break if not method : return args = self . _get_args_for_controller ( getattr ( self , method ) ) fixed_args = len ( args ) - len ( request . pecan . get ( 'routing_arg... | Identifies the correct controller to route to by analyzing the request URI . |
23,740 | def _handle_get ( self , method , remainder , request = None ) : if request is None : self . _raise_method_deprecation_warning ( self . _handle_get ) if not remainder or remainder == [ '' ] : remainder = list ( six . moves . filter ( bool , remainder ) ) controller = self . _find_controller ( 'get_all' , 'get' ) if con... | Routes GET actions to the appropriate controller . |
23,741 | def _handle_delete ( self , method , remainder , request = None ) : if request is None : self . _raise_method_deprecation_warning ( self . _handle_delete ) if remainder : match = self . _handle_custom_action ( method , remainder , request ) if match : return match controller = self . _lookup_child ( remainder [ 0 ] ) i... | Routes DELETE actions to the appropriate controller . |
23,742 | def _handle_post ( self , method , remainder , request = None ) : if request is None : self . _raise_method_deprecation_warning ( self . _handle_post ) if remainder : match = self . _handle_custom_action ( method , remainder , request ) if match : return match controller = self . _lookup_child ( remainder [ 0 ] ) if co... | Routes POST requests . |
23,743 | def format_line_context ( filename , lineno , context = 10 ) : with open ( filename ) as f : lines = f . readlines ( ) lineno = lineno - 1 if lineno > 0 : start_lineno = max ( lineno - context , 0 ) end_lineno = lineno + context lines = [ escape ( l , True ) for l in lines [ start_lineno : end_lineno ] ] i = lineno - s... | Formats the the line context for error rendering . |
23,744 | def make_ns ( self , ns ) : if self . namespace : val = { } val . update ( self . namespace ) val . update ( ns ) return val else : return ns | Returns the lazily created template namespace . |
23,745 | def get ( self , name , template_path ) : if name not in self . _renderers : cls = self . _renderer_classes . get ( name ) if cls is None : return None else : self . _renderers [ name ] = cls ( template_path , self . extra_vars ) return self . _renderers [ name ] | Returns the renderer object . |
23,746 | def default ( self , obj ) : if hasattr ( obj , '__json__' ) and six . callable ( obj . __json__ ) : return obj . __json__ ( ) elif isinstance ( obj , ( date , datetime ) ) : return str ( obj ) elif isinstance ( obj , Decimal ) : return float ( obj ) elif is_saobject ( obj ) : props = { } for key in obj . __dict__ : if... | Converts an object and returns a JSON - friendly structure . |
23,747 | def getargspec ( method ) : argspec = _getargspec ( method ) args = argspec [ 0 ] if args and args [ 0 ] == 'self' : return argspec if hasattr ( method , '__func__' ) : method = method . __func__ func_closure = six . get_function_closure ( method ) if not func_closure : return argspec closure = None func_closure = filt... | Drill through layers of decorators attempting to locate the actual argspec for a method . |
23,748 | def gunicorn_run ( ) : try : from gunicorn . app . wsgiapp import WSGIApplication except ImportError as exc : args = exc . args arg0 = args [ 0 ] if args else '' arg0 += ' (are you sure `gunicorn` is installed?)' exc . args = ( arg0 , ) + args [ 1 : ] raise class PecanApplication ( WSGIApplication ) : def init ( self ,... | The gunicorn_pecan command for launching pecan applications |
23,749 | def serve ( self , app , conf ) : if self . args . reload : try : self . watch_and_spawn ( conf ) except ImportError : print ( 'The `--reload` option requires `watchdog` to be ' 'installed.' ) print ( ' $ pip install watchdog' ) else : self . _serve ( app , conf ) | A very simple approach for a WSGI server . |
23,750 | def log_message ( self , format , * args ) : code = args [ 1 ] [ 0 ] levels = { '4' : 'warning' , '5' : 'error' } log_handler = getattr ( logger , levels . get ( code , 'info' ) ) log_handler ( format % args ) | overrides the log_message method from the wsgiref server so that normal logging works with whatever configuration the application has been set to . |
23,751 | def expose ( template = None , generic = False , route = None , ** kw ) : content_type = kw . get ( 'content_type' , 'text/html' ) if template == 'json' : content_type = 'application/json' def decorate ( f ) : f . exposed = True cfg = _cfg ( f ) cfg [ 'explicit_content_type' ] = 'content_type' in kw if route : from pec... | Decorator used to flag controller methods as being exposed for access via HTTP and to configure that access . |
23,752 | def to_dict ( self ) : return { "timestamp" : int ( self . timestamp ) , "timezone" : self . timezone , "time_of_day" : self . time_of_day , "day_of_week" : self . day_of_week , "day_of_month" : self . day_of_month , "month_of_year" : self . month_of_year , "utc_iso" : self . utc_iso } | Returns the Time instance as a usable dictionary for craftai |
23,753 | def timestamp_from_datetime ( date_time ) : if date_time . tzinfo is None : return time . mktime ( ( date_time . year , date_time . month , date_time . day , date_time . hour , date_time . minute , date_time . second , - 1 , - 1 , - 1 ) ) + date_time . microsecond / 1e6 return ( date_time - _EPOCH ) . total_seconds ( ) | Returns POSIX timestamp as float |
23,754 | def create_agent ( self , configuration , agent_id = "" ) : ct_header = { "Content-Type" : "application/json; charset=utf-8" } payload = { "configuration" : configuration } if agent_id != "" : self . _check_agent_id ( agent_id ) payload [ "id" ] = agent_id try : json_pl = json . dumps ( payload ) except TypeError as er... | Create an agent . |
23,755 | def delete_agent ( self , agent_id ) : self . _check_agent_id ( agent_id ) req_url = "{}/agents/{}" . format ( self . _base_url , agent_id ) resp = self . _requests_session . delete ( req_url ) decoded_resp = self . _decode_response ( resp ) return decoded_resp | Delete an agent . |
23,756 | def delete_agents_bulk ( self , payload ) : valid_indices , invalid_indices , invalid_agents = self . _check_agent_id_bulk ( payload ) valid_agents = self . _create_and_send_json_bulk ( [ payload [ i ] for i in valid_indices ] , "{}/bulk/agents" . format ( self . _base_url ) , "DELETE" ) if invalid_indices == [ ] : ret... | Delete a group of agents |
23,757 | def add_operations ( self , agent_id , operations ) : self . _check_agent_id ( agent_id ) ct_header = { "Content-Type" : "application/json; charset=utf-8" } offset = 0 is_looping = True while is_looping : next_offset = offset + self . config [ "operationsChunksSize" ] try : json_pl = json . dumps ( operations [ offset ... | Add operations to an agent . |
23,758 | def _add_operations_bulk ( self , chunked_data ) : url = "{}/bulk/context" . format ( self . _base_url ) ct_header = { "Content-Type" : "application/json; charset=utf-8" } responses = [ ] for chunk in chunked_data : if len ( chunk ) > 1 : try : json_pl = json . dumps ( chunk ) except TypeError as err : raise CraftAiBad... | Tool for the function add_operations_bulk . It send the requests to add the operations to the agents . |
23,759 | def add_operations_bulk ( self , payload ) : valid_indices , _ , _ = self . _check_agent_id_bulk ( payload ) valid_payload = [ payload [ i ] for i in valid_indices ] chunked_data = [ ] current_chunk = [ ] current_chunk_size = 0 for agent in valid_payload : if ( agent [ "operations" ] and isinstance ( agent [ "operation... | Add operations to a group of agents . |
23,760 | def _get_decision_tree ( self , agent_id , timestamp , version ) : headers = self . _headers . copy ( ) headers [ "x-craft-ai-tree-version" ] = version if timestamp is None : req_url = "{}/agents/{}/decision/tree?" . format ( self . _base_url , agent_id ) else : req_url = "{}/agents/{}/decision/tree?t={}" . format ( se... | Tool for the function get_decision_tree . |
23,761 | def get_decision_tree ( self , agent_id , timestamp = None , version = DEFAULT_DECISION_TREE_VERSION ) : self . _check_agent_id ( agent_id ) if self . _config [ "decisionTreeRetrievalTimeout" ] is False : return self . _get_decision_tree ( agent_id , timestamp , version ) start = current_time_ms ( ) while True : now = ... | Get decision tree . |
23,762 | def _get_decision_trees_bulk ( self , payload , valid_indices , invalid_indices , invalid_dts ) : valid_dts = self . _create_and_send_json_bulk ( [ payload [ i ] for i in valid_indices ] , "{}/bulk/decision_tree" . format ( self . _base_url ) , "POST" ) if invalid_indices == [ ] : return valid_dts return self . _recrea... | Tool for the function get_decision_trees_bulk . |
23,763 | def get_decision_trees_bulk ( self , payload , version = DEFAULT_DECISION_TREE_VERSION ) : headers = self . _headers . copy ( ) headers [ "x-craft-ai-tree-version" ] = version valid_indices , invalid_indices , invalid_dts = self . _check_agent_id_bulk ( payload ) if self . _config [ "decisionTreeRetrievalTimeout" ] is ... | Get a group of decision trees . |
23,764 | def _decode_response ( response ) : status_code = response . status_code message = "Status code " + str ( status_code ) try : message = CraftAIClient . _parse_body ( response ) [ "message" ] except ( CraftAiInternalError , KeyError , TypeError ) : pass if status_code in [ 200 , 201 , 204 , 207 ] : return CraftAIClient ... | Decode the response of a request . |
23,765 | def _decode_response_bulk ( response_bulk ) : resp = [ ] for response in response_bulk : if ( "status" in response ) and ( response . get ( "status" ) == 201 ) : agent = { "id" : response [ "id" ] , "message" : response [ "message" ] } resp . append ( agent ) elif "status" in response : status_code = response [ "status... | Decode the response of each agent given by a bulk function . |
23,766 | def _get_error_from_status ( status_code , message ) : if status_code == 202 : err = CraftAiLongRequestTimeOutError ( message ) elif status_code == 401 or status_code == 403 : err = CraftAiCredentialsError ( message ) elif status_code == 400 : err = CraftAiBadRequestError ( message ) elif status_code == 404 : err = Cra... | Give the error corresponding to the status code . |
23,767 | def _check_agent_id ( agent_id ) : if ( not isinstance ( agent_id , six . string_types ) or AGENT_ID_PATTERN . match ( agent_id ) is None ) : raise CraftAiBadRequestError ( ERROR_ID_MESSAGE ) | Checks that the given agent_id is a valid non - empty string . |
23,768 | def _check_agent_id_bulk ( self , payload ) : invalid_agent_indices = [ ] valid_agent_indices = [ ] invalid_payload = [ ] for index , agent in enumerate ( payload ) : try : if "id" in agent : self . _check_agent_id ( agent [ "id" ] ) except CraftAiBadRequestError : invalid_agent_indices . append ( index ) invalid_paylo... | Checks that all the given agent ids are valid non - empty strings and if the agents are serializable . |
23,769 | def _recreate_list_with_indices ( indices1 , values1 , indices2 , values2 ) : list_indices = sorted ( indices1 + indices2 ) for i , index in enumerate ( list_indices ) : if i != index : raise CraftAiInternalError ( "The agents's indices are not continuous" ) full_list = [ None ] * ( len ( indices1 ) + len ( indices2 ) ... | Create a list in the right order . |
23,770 | def _create_and_send_json_bulk ( self , payload , req_url , request_type = "POST" ) : ct_header = { "Content-Type" : "application/json; charset=utf-8" } try : json_pl = json . dumps ( payload ) except TypeError as err : raise CraftAiBadRequestError ( "Error while dumping the payload into json" "format when converting i... | Create a json do a request to the URL and process the response . |
23,771 | def construct_ctcp ( * parts ) : message = ' ' . join ( parts ) message = message . replace ( '\0' , CTCP_ESCAPE_CHAR + '0' ) message = message . replace ( '\n' , CTCP_ESCAPE_CHAR + 'n' ) message = message . replace ( '\r' , CTCP_ESCAPE_CHAR + 'r' ) message = message . replace ( CTCP_ESCAPE_CHAR , CTCP_ESCAPE_CHAR + CT... | Construct CTCP message . |
23,772 | def parse_ctcp ( query ) : query = query . strip ( CTCP_DELIMITER ) query = query . replace ( CTCP_ESCAPE_CHAR + '0' , '\0' ) query = query . replace ( CTCP_ESCAPE_CHAR + 'n' , '\n' ) query = query . replace ( CTCP_ESCAPE_CHAR + 'r' , '\r' ) query = query . replace ( CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR , CTCP_ESCAPE_CH... | Strip and de - quote CTCP messages . |
23,773 | async def on_ctcp_version ( self , by , target , contents ) : import pydle version = '{name} v{ver}' . format ( name = pydle . __name__ , ver = pydle . __version__ ) self . ctcp_reply ( by , 'VERSION' , version ) | Built - in CTCP version as some networks seem to require it . |
23,774 | async def ctcp ( self , target , query , contents = None ) : if self . is_channel ( target ) and not self . in_channel ( target ) : raise client . NotInChannel ( target ) await self . message ( target , construct_ctcp ( query , contents ) ) | Send a CTCP request to a target . |
23,775 | async def ctcp_reply ( self , target , query , response ) : if self . is_channel ( target ) and not self . in_channel ( target ) : raise client . NotInChannel ( target ) await self . notice ( target , construct_ctcp ( query , response ) ) | Send a CTCP reply to a target . |
23,776 | async def on_raw_privmsg ( self , message ) : nick , metadata = self . _parse_user ( message . source ) target , msg = message . params if is_ctcp ( msg ) : self . _sync_user ( nick , metadata ) type , contents = parse_ctcp ( msg ) attr = 'on_ctcp_' + pydle . protocol . identifierify ( type ) if hasattr ( self , attr )... | Modify PRIVMSG to redirect CTCP messages . |
23,777 | async def on_raw_notice ( self , message ) : nick , metadata = self . _parse_user ( message . source ) target , msg = message . params if is_ctcp ( msg ) : self . _sync_user ( nick , metadata ) type , response = parse_ctcp ( msg ) attr = 'on_ctcp_' + pydle . protocol . identifierify ( type ) + '_reply' if hasattr ( sel... | Modify NOTICE to redirect CTCP messages . |
23,778 | async def _register ( self ) : if self . registered : self . logger . debug ( "skipping cap registration, already registered!" ) return await self . rawmsg ( 'CAP' , 'LS' , '302' ) await super ( ) . _register ( ) | Hijack registration to send a CAP LS first . |
23,779 | async def _capability_negotiated ( self , capab ) : self . _capabilities_negotiating . discard ( capab ) if not self . _capabilities_requested and not self . _capabilities_negotiating : await self . rawmsg ( 'CAP' , 'END' ) | Mark capability as negotiated and end negotiation if we re done . |
23,780 | async def on_raw_cap ( self , message ) : target , subcommand = message . params [ : 2 ] params = message . params [ 2 : ] attr = 'on_raw_cap_' + pydle . protocol . identifierify ( subcommand ) if hasattr ( self , attr ) : await getattr ( self , attr ) ( params ) else : self . logger . warning ( 'Unknown CAP subcommand... | Handle CAP message . |
23,781 | async def on_raw_cap_ls ( self , params ) : to_request = set ( ) for capab in params [ 0 ] . split ( ) : capab , value = self . _capability_normalize ( capab ) if capab in self . _capabilities : continue attr = 'on_capability_' + pydle . protocol . identifierify ( capab ) + '_available' supported = ( await getattr ( se... | Update capability mapping . Request capabilities . |
23,782 | async def on_raw_cap_list ( self , params ) : self . _capabilities = { capab : False for capab in self . _capabilities } for capab in params [ 0 ] . split ( ) : capab , value = self . _capability_normalize ( capab ) self . _capabilities [ capab ] = value if value else True | Update active capabilities . |
23,783 | async def on_raw_410 ( self , message ) : self . logger . error ( 'Server sent "Unknown CAP subcommand: %s". Aborting capability negotiation.' , message . params [ 0 ] ) self . _capabilities_requested = set ( ) self . _capabilities_negotiating = set ( ) await self . rawmsg ( 'CAP' , 'END' ) | Unknown CAP subcommand or CAP error . Force - end negotiations . |
23,784 | async def _sasl_start ( self , mechanism ) : await self . rawmsg ( 'AUTHENTICATE' , mechanism ) _sasl_partial = partial ( self . _sasl_abort , timeout = True ) self . _sasl_timer = self . eventloop . call_later ( self . SASL_TIMEOUT , _sasl_partial ) | Initiate SASL authentication . |
23,785 | async def _sasl_abort ( self , timeout = False ) : if timeout : self . logger . error ( 'SASL authentication timed out: aborting.' ) else : self . logger . error ( 'SASL authentication aborted.' ) if self . _sasl_timer : self . _sasl_timer . cancel ( ) self . _sasl_timer = None await self . rawmsg ( 'AUTHENTICATE' , AB... | Abort SASL authentication . |
23,786 | async def _sasl_end ( self ) : if self . _sasl_timer : self . _sasl_timer . cancel ( ) self . _sasl_timer = None await self . _capability_negotiated ( 'sasl' ) | Finalize SASL authentication . |
23,787 | async def _sasl_respond ( self ) : if self . _sasl_client : try : response = self . _sasl_client . process ( self . _sasl_challenge ) except puresasl . SASLError : response = None if response is None : self . logger . warning ( 'SASL challenge processing failed: aborting SASL authentication.' ) await self . _sasl_abort... | Respond to SASL challenge with response . |
23,788 | async def on_capability_sasl_available ( self , value ) : if value : self . _sasl_mechanisms = value . upper ( ) . split ( ',' ) else : self . _sasl_mechanisms = None if self . sasl_mechanism == 'EXTERNAL' or ( self . sasl_username and self . sasl_password ) : if self . sasl_mechanism == 'EXTERNAL' or puresasl : return... | Check whether or not SASL is available . |
23,789 | async def on_capability_sasl_enabled ( self ) : if self . sasl_mechanism : if self . _sasl_mechanisms and self . sasl_mechanism not in self . _sasl_mechanisms : self . logger . warning ( 'Requested SASL mechanism is not in server mechanism list: aborting SASL authentication.' ) return cap . failed mechanisms = [ self .... | Start SASL authentication . |
23,790 | async def on_raw_authenticate ( self , message ) : if self . _sasl_timer : self . _sasl_timer . cancel ( ) self . _sasl_timer = None response = ' ' . join ( message . params ) if response != EMPTY_MESSAGE : self . _sasl_challenge += base64 . b64decode ( response ) if len ( response ) % RESPONSE_LIMIT > 0 : await self .... | Received part of the authentication challenge . |
23,791 | def monitor ( self , target ) : if 'monitor-notify' in self . _capabilities and not self . is_monitoring ( target ) : yield from self . rawmsg ( 'MONITOR' , '+' , target ) self . _monitoring . add ( target ) return True else : return False | Start monitoring the online status of a user . Returns whether or not the server supports monitoring . |
23,792 | def unmonitor ( self , target ) : if 'monitor-notify' in self . _capabilities and self . is_monitoring ( target ) : yield from self . rawmsg ( 'MONITOR' , '-' , target ) self . _monitoring . remove ( target ) return True else : return False | Stop monitoring the online status of a user . Returns whether or not the server supports monitoring . |
23,793 | async def on_raw_730 ( self , message ) : for nick in message . params [ 1 ] . split ( ',' ) : self . _create_user ( nick ) await self . on_user_online ( nickname ) | Someone we are monitoring just came online . |
23,794 | async def on_raw_731 ( self , message ) : for nick in message . params [ 1 ] . split ( ',' ) : self . _destroy_user ( nick , monitor_override = True ) await self . on_user_offline ( nickname ) | Someone we are monitoring got offline . |
23,795 | async def on_raw_account ( self , message ) : if not self . _capabilities . get ( 'account-notify' , False ) : return nick , metadata = self . _parse_user ( message . source ) account = message . params [ 0 ] if nick not in self . users : return self . _sync_user ( nick , metadata ) if account == NO_ACCOUNT : self . _s... | Changes in the associated account for a nickname . |
23,796 | async def on_raw_away ( self , message ) : if 'away-notify' not in self . _capabilities or not self . _capabilities [ 'away-notify' ] : return nick , metadata = self . _parse_user ( message . source ) if nick not in self . users : return self . _sync_user ( nick , metadata ) self . users [ nick ] [ 'away' ] = len ( mes... | Process AWAY messages . |
23,797 | async def on_raw_join ( self , message ) : if 'extended-join' in self . _capabilities and self . _capabilities [ 'extended-join' ] : nick , metadata = self . _parse_user ( message . source ) channels , account , realname = message . params self . _sync_user ( nick , metadata ) fakemsg = self . _create_message ( 'JOIN' ... | Process extended JOIN messages . |
23,798 | async def on_raw_metadata ( self , message ) : target , targetmeta = self . _parse_user ( message . params [ 0 ] ) key , visibility , value = message . params [ 1 : 4 ] if visibility == VISIBLITY_ALL : visibility = None if target in self . users : self . _sync_user ( target , targetmeta ) await self . on_metadata ( tar... | Metadata event . |
23,799 | async def on_raw_762 ( self , message ) : if not self . _metadata_queue : return nickname = self . _metadata_queue . pop ( ) future = self . _pending [ 'metadata' ] . pop ( nickname ) future . set_result ( self . _metadata_info . pop ( nickname ) ) | End of metadata . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.