idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
13,400 | def enable_scanners_by_group ( self , group ) : if group == 'all' : self . logger . debug ( 'Enabling all scanners' ) return self . zap . ascan . enable_all_scanners ( ) try : scanner_list = self . scanner_group_map [ group ] except KeyError : raise ZAPError ( 'Invalid group "{0}" provided. Valid groups are: {1}' . format ( group , ', ' . join ( self . scanner_groups ) ) ) self . logger . debug ( 'Enabling scanner group {0}' . format ( group ) ) return self . enable_scanners_by_ids ( scanner_list ) | Enables the scanners in the group if it matches one in the scanner_group_map . |
13,401 | def disable_scanners_by_group ( self , group ) : if group == 'all' : self . logger . debug ( 'Disabling all scanners' ) return self . zap . ascan . disable_all_scanners ( ) try : scanner_list = self . scanner_group_map [ group ] except KeyError : raise ZAPError ( 'Invalid group "{0}" provided. Valid groups are: {1}' . format ( group , ', ' . join ( self . scanner_groups ) ) ) self . logger . debug ( 'Disabling scanner group {0}' . format ( group ) ) return self . disable_scanners_by_ids ( scanner_list ) | Disables the scanners in the group if it matches one in the scanner_group_map . |
13,402 | def set_scanner_attack_strength ( self , scanner_ids , attack_strength ) : for scanner_id in scanner_ids : self . logger . debug ( 'Setting strength for scanner {0} to {1}' . format ( scanner_id , attack_strength ) ) result = self . zap . ascan . set_scanner_attack_strength ( scanner_id , attack_strength ) if result != 'OK' : raise ZAPError ( 'Error setting strength for scanner with ID {0}: {1}' . format ( scanner_id , result ) ) | Set the attack strength for the given scanners . |
13,403 | def enable_policies_by_ids ( self , policy_ids ) : policy_ids = ',' . join ( policy_ids ) self . logger . debug ( 'Setting enabled policies to IDs {0}' . format ( policy_ids ) ) self . zap . ascan . set_enabled_policies ( policy_ids ) | Set enabled policy from a list of IDs . |
13,404 | def set_policy_attack_strength ( self , policy_ids , attack_strength ) : for policy_id in policy_ids : self . logger . debug ( 'Setting strength for policy {0} to {1}' . format ( policy_id , attack_strength ) ) result = self . zap . ascan . set_policy_attack_strength ( policy_id , attack_strength ) if result != 'OK' : raise ZAPError ( 'Error setting strength for policy with ID {0}: {1}' . format ( policy_id , result ) ) | Set the attack strength for the given policies . |
13,405 | def exclude_from_all ( self , exclude_regex ) : try : re . compile ( exclude_regex ) except re . error : raise ZAPError ( 'Invalid regex "{0}" provided' . format ( exclude_regex ) ) self . logger . debug ( 'Excluding {0} from proxy, spider and active scanner.' . format ( exclude_regex ) ) self . zap . core . exclude_from_proxy ( exclude_regex ) self . zap . spider . exclude_from_scan ( exclude_regex ) self . zap . ascan . exclude_from_scan ( exclude_regex ) | Exclude a pattern from proxy spider and active scanner . |
13,406 | def xml_report ( self , file_path ) : self . logger . debug ( 'Generating XML report' ) report = self . zap . core . xmlreport ( ) self . _write_report ( report , file_path ) | Generate and save XML report |
13,407 | def md_report ( self , file_path ) : self . logger . debug ( 'Generating MD report' ) report = self . zap . core . mdreport ( ) self . _write_report ( report , file_path ) | Generate and save MD report |
13,408 | def html_report ( self , file_path ) : self . logger . debug ( 'Generating HTML report' ) report = self . zap . core . htmlreport ( ) self . _write_report ( report , file_path ) | Generate and save HTML report . |
13,409 | def _write_report ( report , file_path ) : with open ( file_path , mode = 'wb' ) as f : if not isinstance ( report , binary_type ) : report = report . encode ( 'utf-8' ) f . write ( report ) | Write report to the given file path . |
13,410 | def get_context_info ( self , context_name ) : context_info = self . zap . context . context ( context_name ) if not isinstance ( context_info , dict ) : raise ZAPError ( 'Context with name "{0}" wasn\'t found' . format ( context_name ) ) return context_info | Get the context ID for a given context name . |
13,411 | def _get_context_and_user_ids ( self , context_name , user_name ) : if context_name is None : return None , None context_id = self . get_context_info ( context_name ) [ 'id' ] user_id = None if user_name : user_id = self . _get_user_id_from_name ( context_id , user_name ) return context_id , user_id | Helper to get the context ID and user ID from the given names . |
13,412 | def _get_user_id_from_name ( self , context_id , user_name ) : users = self . zap . users . users_list ( context_id ) for user in users : if user [ 'name' ] == user_name : return user [ 'id' ] raise ZAPError ( 'No user with the name "{0}"" was found for context {1}' . format ( user_name , context_id ) ) | Get a user ID from the user name . |
13,413 | def list_scripts ( zap_helper ) : scripts = zap_helper . zap . script . list_scripts output = [ ] for s in scripts : if 'enabled' not in s : s [ 'enabled' ] = 'N/A' output . append ( [ s [ 'name' ] , s [ 'type' ] , s [ 'engine' ] , s [ 'enabled' ] ] ) click . echo ( tabulate ( output , headers = [ 'Name' , 'Type' , 'Engine' , 'Enabled' ] , tablefmt = 'grid' ) ) | List scripts currently loaded into ZAP . |
13,414 | def list_engines ( zap_helper ) : engines = zap_helper . zap . script . list_engines console . info ( 'Available engines: {}' . format ( ', ' . join ( engines ) ) ) | List engines that can be used to run scripts . |
13,415 | def enable_script ( zap_helper , script_name ) : with zap_error_handler ( ) : console . debug ( 'Enabling script "{0}"' . format ( script_name ) ) result = zap_helper . zap . script . enable ( script_name ) if result != 'OK' : raise ZAPError ( 'Error enabling script: {0}' . format ( result ) ) console . info ( 'Script "{0}" enabled' . format ( script_name ) ) | Enable a script . |
13,416 | def disable_script ( zap_helper , script_name ) : with zap_error_handler ( ) : console . debug ( 'Disabling script "{0}"' . format ( script_name ) ) result = zap_helper . zap . script . disable ( script_name ) if result != 'OK' : raise ZAPError ( 'Error disabling script: {0}' . format ( result ) ) console . info ( 'Script "{0}" disabled' . format ( script_name ) ) | Disable a script . |
13,417 | def remove_script ( zap_helper , script_name ) : with zap_error_handler ( ) : console . debug ( 'Removing script "{0}"' . format ( script_name ) ) result = zap_helper . zap . script . remove ( script_name ) if result != 'OK' : raise ZAPError ( 'Error removing script: {0}' . format ( result ) ) console . info ( 'Script "{0}" removed' . format ( script_name ) ) | Remove a script . |
13,418 | def load_script ( zap_helper , ** options ) : with zap_error_handler ( ) : if not os . path . isfile ( options [ 'file_path' ] ) : raise ZAPError ( 'No file found at "{0}", cannot load script.' . format ( options [ 'file_path' ] ) ) if not _is_valid_script_engine ( zap_helper . zap , options [ 'engine' ] ) : engines = zap_helper . zap . script . list_engines raise ZAPError ( 'Invalid script engine provided. Valid engines are: {0}' . format ( ', ' . join ( engines ) ) ) console . debug ( 'Loading script "{0}" from "{1}"' . format ( options [ 'name' ] , options [ 'file_path' ] ) ) result = zap_helper . zap . script . load ( options [ 'name' ] , options [ 'script_type' ] , options [ 'engine' ] , options [ 'file_path' ] , scriptdescription = options [ 'description' ] ) if result != 'OK' : raise ZAPError ( 'Error loading script: {0}' . format ( result ) ) console . info ( 'Script "{0}" loaded' . format ( options [ 'name' ] ) ) | Load a script from a file . |
13,419 | def _is_valid_script_engine ( zap , engine ) : engine_names = zap . script . list_engines short_names = [ e . split ( ' : ' ) [ 1 ] for e in engine_names ] return engine in engine_names or engine in short_names | Check if given script engine is valid . |
13,420 | def start_zap_daemon ( zap_helper , start_options ) : console . info ( 'Starting ZAP daemon' ) with helpers . zap_error_handler ( ) : zap_helper . start ( options = start_options ) | Helper to start the daemon using the current config . |
13,421 | def check_status ( zap_helper , timeout ) : with helpers . zap_error_handler ( ) : if zap_helper . is_running ( ) : console . info ( 'ZAP is running' ) elif timeout is not None : zap_helper . wait_for_zap ( timeout ) console . info ( 'ZAP is running' ) else : console . error ( 'ZAP is not running' ) sys . exit ( 2 ) | Check if ZAP is running and able to receive API calls . |
13,422 | def open_url ( zap_helper , url ) : console . info ( 'Accessing URL {0}' . format ( url ) ) zap_helper . open_url ( url ) | Open a URL using the ZAP proxy . |
13,423 | def spider_url ( zap_helper , url , context_name , user_name ) : console . info ( 'Running spider...' ) with helpers . zap_error_handler ( ) : zap_helper . run_spider ( url , context_name , user_name ) | Run the spider against a URL . |
13,424 | def active_scan ( zap_helper , url , scanners , recursive , context_name , user_name ) : console . info ( 'Running an active scan...' ) with helpers . zap_error_handler ( ) : if scanners : zap_helper . set_enabled_scanners ( scanners ) zap_helper . run_active_scan ( url , recursive , context_name , user_name ) | Run an Active Scan against a URL . |
13,425 | def show_alerts ( zap_helper , alert_level , output_format , exit_code ) : alerts = zap_helper . alerts ( alert_level ) helpers . report_alerts ( alerts , output_format ) if exit_code : code = 1 if len ( alerts ) > 0 else 0 sys . exit ( code ) | Show alerts at the given alert level . |
13,426 | def quick_scan ( zap_helper , url , ** options ) : if options [ 'self_contained' ] : console . info ( 'Starting ZAP daemon' ) with helpers . zap_error_handler ( ) : zap_helper . start ( options [ 'start_options' ] ) console . info ( 'Running a quick scan for {0}' . format ( url ) ) with helpers . zap_error_handler ( ) : if options [ 'scanners' ] : zap_helper . set_enabled_scanners ( options [ 'scanners' ] ) if options [ 'exclude' ] : zap_helper . exclude_from_all ( options [ 'exclude' ] ) zap_helper . open_url ( url ) if options [ 'spider' ] : zap_helper . run_spider ( url , options [ 'context_name' ] , options [ 'user_name' ] ) if options [ 'ajax_spider' ] : zap_helper . run_ajax_spider ( url ) zap_helper . run_active_scan ( url , options [ 'recursive' ] , options [ 'context_name' ] , options [ 'user_name' ] ) alerts = zap_helper . alerts ( options [ 'alert_level' ] ) helpers . report_alerts ( alerts , options [ 'output_format' ] ) if options [ 'self_contained' ] : console . info ( 'Shutting down ZAP daemon' ) with helpers . zap_error_handler ( ) : zap_helper . shutdown ( ) exit_code = 1 if len ( alerts ) > 0 else 0 sys . exit ( exit_code ) | Run a quick scan of a site by opening a URL optionally spidering the URL running an Active Scan and reporting any issues found . |
13,427 | def report ( zap_helper , output , output_format ) : if output_format == 'html' : zap_helper . html_report ( output ) elif output_format == 'md' : zap_helper . md_report ( output ) else : zap_helper . xml_report ( output ) console . info ( 'Report saved to "{0}"' . format ( output ) ) | Generate XML MD or HTML report . |
13,428 | def validate_ids ( ctx , param , value ) : if not value : return None ids = [ x . strip ( ) for x in value . split ( ',' ) ] for id_item in ids : if not id_item . isdigit ( ) : raise click . BadParameter ( 'Non-numeric value "{0}" provided for an ID.' . format ( id_item ) ) return ids | Validate a list of IDs and convert them to a list . |
13,429 | def validate_scanner_list ( ctx , param , value ) : if not value : return None valid_groups = ctx . obj . scanner_groups scanners = [ x . strip ( ) for x in value . split ( ',' ) ] if 'all' in scanners : return [ 'all' ] scanner_ids = [ ] for scanner in scanners : if scanner . isdigit ( ) : scanner_ids . append ( scanner ) elif scanner in valid_groups : scanner_ids += ctx . obj . scanner_group_map [ scanner ] else : raise click . BadParameter ( 'Invalid scanner "{0}" provided. Must be a valid group or numeric ID.' . format ( scanner ) ) return scanner_ids | Validate a comma - separated list of scanners and extract it into a list of groups and IDs . |
13,430 | def validate_regex ( ctx , param , value ) : if not value : return None try : re . compile ( value ) except re . error : raise click . BadParameter ( 'Invalid regex "{0}" provided' . format ( value ) ) return value | Validate that a provided regex compiles . |
13,431 | def report_alerts ( alerts , output_format = 'table' ) : num_alerts = len ( alerts ) if output_format == 'json' : click . echo ( json . dumps ( alerts , indent = 4 ) ) else : console . info ( 'Issues found: {0}' . format ( num_alerts ) ) if num_alerts > 0 : click . echo ( tabulate ( [ [ a [ 'alert' ] , a [ 'risk' ] , a [ 'cweid' ] , a [ 'url' ] ] for a in alerts ] , headers = [ 'Alert' , 'Risk' , 'CWE ID' , 'URL' ] , tablefmt = 'grid' ) ) | Print our alerts in the given format . |
13,432 | def filter_by_ids ( original_list , ids_to_filter ) : if not ids_to_filter : return original_list return [ i for i in original_list if i [ 'id' ] in ids_to_filter ] | Filter a list of dicts by IDs using an id key on each dict . |
13,433 | def save_session ( zap_helper , file_path ) : console . debug ( 'Saving the session to "{0}"' . format ( file_path ) ) zap_helper . zap . core . save_session ( file_path , overwrite = 'true' ) | Save the session . |
13,434 | def load_session ( zap_helper , file_path ) : with zap_error_handler ( ) : if not os . path . isfile ( file_path ) : raise ZAPError ( 'No file found at "{0}", cannot load session.' . format ( file_path ) ) console . debug ( 'Loading session from "{0}"' . format ( file_path ) ) zap_helper . zap . core . load_session ( file_path ) | Load a given session . |
13,435 | def context_list ( zap_helper ) : contexts = zap_helper . zap . context . context_list if len ( contexts ) : console . info ( 'Available contexts: {0}' . format ( contexts [ 1 : - 1 ] ) ) else : console . info ( 'No contexts available in the current session' ) | List the available contexts . |
13,436 | def context_new ( zap_helper , name ) : console . info ( 'Creating context with name: {0}' . format ( name ) ) res = zap_helper . zap . context . new_context ( contextname = name ) console . info ( 'Context "{0}" created with ID: {1}' . format ( name , res ) ) | Create a new context . |
13,437 | def context_include ( zap_helper , name , pattern ) : console . info ( 'Including regex {0} in context with name: {1}' . format ( pattern , name ) ) with zap_error_handler ( ) : result = zap_helper . zap . context . include_in_context ( contextname = name , regex = pattern ) if result != 'OK' : raise ZAPError ( 'Including regex from context failed: {}' . format ( result ) ) | Include a pattern in a given context . |
13,438 | def context_exclude ( zap_helper , name , pattern ) : console . info ( 'Excluding regex {0} from context with name: {1}' . format ( pattern , name ) ) with zap_error_handler ( ) : result = zap_helper . zap . context . exclude_from_context ( contextname = name , regex = pattern ) if result != 'OK' : raise ZAPError ( 'Excluding regex from context failed: {}' . format ( result ) ) | Exclude a pattern from a given context . |
13,439 | def context_info ( zap_helper , context_name ) : with zap_error_handler ( ) : info = zap_helper . get_context_info ( context_name ) console . info ( 'ID: {}' . format ( info [ 'id' ] ) ) console . info ( 'Name: {}' . format ( info [ 'name' ] ) ) console . info ( 'Authentication type: {}' . format ( info [ 'authType' ] ) ) console . info ( 'Included regexes: {}' . format ( info [ 'includeRegexs' ] ) ) console . info ( 'Excluded regexes: {}' . format ( info [ 'excludeRegexs' ] ) ) | Get info about the given context . |
13,440 | def context_list_users ( zap_helper , context_name ) : with zap_error_handler ( ) : info = zap_helper . get_context_info ( context_name ) users = zap_helper . zap . users . users_list ( info [ 'id' ] ) if len ( users ) : user_list = ', ' . join ( [ user [ 'name' ] for user in users ] ) console . info ( 'Available users for the context {0}: {1}' . format ( context_name , user_list ) ) else : console . info ( 'No users configured for the context {}' . format ( context_name ) ) | List the users available for a given context . |
13,441 | def context_import ( zap_helper , file_path ) : with zap_error_handler ( ) : result = zap_helper . zap . context . import_context ( file_path ) if not result . isdigit ( ) : raise ZAPError ( 'Importing context from file failed: {}' . format ( result ) ) console . info ( 'Imported context from {}' . format ( file_path ) ) | Import a saved context file . |
13,442 | def context_export ( zap_helper , name , file_path ) : with zap_error_handler ( ) : result = zap_helper . zap . context . export_context ( name , file_path ) if result != 'OK' : raise ZAPError ( 'Exporting context to file failed: {}' . format ( result ) ) console . info ( 'Exported context {0} to {1}' . format ( name , file_path ) ) | Export a given context to a file . |
13,443 | def _get_value ( obj , key , default = missing ) : if "." in key : return _get_value_for_keys ( obj , key . split ( "." ) , default ) else : return _get_value_for_key ( obj , key , default ) | Slightly - modified version of marshmallow . utils . get_value . If a dot - delimited key is passed and any attribute in the path is None return None . |
13,444 | def _rapply ( d , func , * args , ** kwargs ) : if isinstance ( d , ( tuple , list ) ) : return [ _rapply ( each , func , * args , ** kwargs ) for each in d ] if isinstance ( d , dict ) : return { key : _rapply ( value , func , * args , ** kwargs ) for key , value in iteritems ( d ) } else : return func ( d , * args , ** kwargs ) | Apply a function to all values in a dictionary or list of dictionaries recursively . |
13,445 | def _url_val ( val , key , obj , ** kwargs ) : if isinstance ( val , URLFor ) : return val . serialize ( key , obj , ** kwargs ) else : return val | Function applied by HyperlinksField to get the correct value in the schema . |
13,446 | def _attach_fields ( obj ) : for attr in base_fields . __all__ : if not hasattr ( obj , attr ) : setattr ( obj , attr , getattr ( base_fields , attr ) ) for attr in fields . __all__ : setattr ( obj , attr , getattr ( fields , attr ) ) | Attach all the marshmallow fields classes to obj including Flask - Marshmallow s custom fields . |
13,447 | def init_app ( self , app ) : app . extensions = getattr ( app , "extensions" , { } ) if has_sqla and "sqlalchemy" in app . extensions : db = app . extensions [ "sqlalchemy" ] . db self . ModelSchema . OPTIONS_CLASS . session = db . session app . extensions [ EXTENSION_NAME ] = self | Initializes the application with the extension . |
13,448 | def jsonify ( self , obj , many = sentinel , * args , ** kwargs ) : if many is sentinel : many = self . many if _MARSHMALLOW_VERSION_INFO [ 0 ] >= 3 : data = self . dump ( obj , many = many ) else : data = self . dump ( obj , many = many ) . data return flask . jsonify ( data , * args , ** kwargs ) | Return a JSON response containing the serialized data . |
13,449 | def _hjoin_multiline ( join_char , strings ) : cstrings = [ string . split ( "\n" ) for string in strings ] max_num_lines = max ( len ( item ) for item in cstrings ) pp = [ ] for k in range ( max_num_lines ) : p = [ cstring [ k ] for cstring in cstrings ] pp . append ( join_char + join_char . join ( p ) + join_char ) return "\n" . join ( [ p . rstrip ( ) for p in pp ] ) | Horizontal join of multiline strings |
13,450 | def chunks ( raw ) : for i in range ( 0 , len ( raw ) , EVENT_SIZE ) : yield struct . unpack ( EVENT_FORMAT , raw [ i : i + EVENT_SIZE ] ) | Yield successive EVENT_SIZE sized chunks from raw . |
13,451 | def convert_timeval ( seconds_since_epoch ) : frac , whole = math . modf ( seconds_since_epoch ) microseconds = math . floor ( frac * 1000000 ) seconds = math . floor ( whole ) return seconds , microseconds | Convert time into C style timeval . |
13,452 | def quartz_mouse_process ( pipe ) : import Quartz class QuartzMouseListener ( QuartzMouseBaseListener ) : def install_handle_input ( self ) : NSMachPort = Quartz . CGEventTapCreate ( Quartz . kCGSessionEventTap , Quartz . kCGHeadInsertEventTap , Quartz . kCGEventTapOptionDefault , Quartz . CGEventMaskBit ( Quartz . kCGEventLeftMouseDown ) | Quartz . CGEventMaskBit ( Quartz . kCGEventLeftMouseUp ) | Quartz . CGEventMaskBit ( Quartz . kCGEventRightMouseDown ) | Quartz . CGEventMaskBit ( Quartz . kCGEventRightMouseUp ) | Quartz . CGEventMaskBit ( Quartz . kCGEventMouseMoved ) | Quartz . CGEventMaskBit ( Quartz . kCGEventLeftMouseDragged ) | Quartz . CGEventMaskBit ( Quartz . kCGEventRightMouseDragged ) | Quartz . CGEventMaskBit ( Quartz . kCGEventScrollWheel ) | Quartz . CGEventMaskBit ( Quartz . kCGEventTabletPointer ) | Quartz . CGEventMaskBit ( Quartz . kCGEventTabletProximity ) | Quartz . CGEventMaskBit ( Quartz . kCGEventOtherMouseDown ) | Quartz . CGEventMaskBit ( Quartz . kCGEventOtherMouseUp ) | Quartz . CGEventMaskBit ( Quartz . kCGEventOtherMouseDragged ) , self . handle_input , None ) CFRunLoopSourceRef = Quartz . CFMachPortCreateRunLoopSource ( None , NSMachPort , 0 ) CFRunLoopRef = Quartz . CFRunLoopGetCurrent ( ) Quartz . CFRunLoopAddSource ( CFRunLoopRef , CFRunLoopSourceRef , Quartz . kCFRunLoopDefaultMode ) Quartz . CGEventTapEnable ( NSMachPort , True ) def listen ( self ) : while self . active : Quartz . CFRunLoopRunInMode ( Quartz . kCFRunLoopDefaultMode , 5 , False ) def uninstall_handle_input ( self ) : self . active = False def _get_mouse_button_number ( self , event ) : return Quartz . CGEventGetIntegerValueField ( event , Quartz . kCGMouseEventButtonNumber ) def _get_click_state ( self , event ) : return Quartz . CGEventGetIntegerValueField ( event , Quartz . kCGMouseEventClickState ) def _get_scroll ( self , event ) : scroll_y = Quartz . CGEventGetIntegerValueField ( event , Quartz . kCGScrollWheelEventDeltaAxis1 ) scroll_x = Quartz . CGEventGetIntegerValueField ( event , Quartz . kCGScrollWheelEventDeltaAxis2 ) return scroll_x , scroll_y def _get_absolute ( self , event ) : return Quartz . CGEventGetLocation ( event ) def _get_relative ( self , event ) : delta_x = Quartz . CGEventGetIntegerValueField ( event , Quartz . kCGMouseEventDeltaX ) delta_y = Quartz . CGEventGetIntegerValueField ( event , Quartz . kCGMouseEventDeltaY ) return delta_x , delta_y mouse = QuartzMouseListener ( pipe ) mouse . listen ( ) | Single subprocess for reading mouse events on Mac using newer Quartz . |
13,453 | def appkit_mouse_process ( pipe ) : from Foundation import NSObject from AppKit import NSApplication , NSApp from Cocoa import ( NSEvent , NSLeftMouseDownMask , NSLeftMouseUpMask , NSRightMouseDownMask , NSRightMouseUpMask , NSMouseMovedMask , NSLeftMouseDraggedMask , NSRightMouseDraggedMask , NSMouseEnteredMask , NSMouseExitedMask , NSScrollWheelMask , NSOtherMouseDownMask , NSOtherMouseUpMask ) from PyObjCTools import AppHelper import objc class MacMouseSetup ( NSObject ) : @ objc . python_method def init_with_handler ( self , handler ) : self = super ( MacMouseSetup , self ) . init ( ) self . handler = handler return self def applicationDidFinishLaunching_ ( self , notification ) : mask = ( NSLeftMouseDownMask | NSLeftMouseUpMask | NSRightMouseDownMask | NSRightMouseUpMask | NSMouseMovedMask | NSLeftMouseDraggedMask | NSRightMouseDraggedMask | NSScrollWheelMask | NSMouseEnteredMask | NSMouseExitedMask | NSOtherMouseDownMask | NSOtherMouseUpMask ) NSEvent . addGlobalMonitorForEventsMatchingMask_handler_ ( mask , self . handler ) class MacMouseListener ( AppKitMouseBaseListener ) : def install_handle_input ( self ) : self . app = NSApplication . sharedApplication ( ) delegate = MacMouseSetup . alloc ( ) . init_with_handler ( self . handle_input ) NSApp ( ) . setDelegate_ ( delegate ) AppHelper . runEventLoop ( ) def __del__ ( self ) : AppHelper . stopEventLoop ( ) mouse = MacMouseListener ( pipe , events = [ ] ) | Single subprocess for reading mouse events on Mac using older AppKit . |
13,454 | def mac_keyboard_process ( pipe ) : from AppKit import NSApplication , NSApp from Foundation import NSObject from Cocoa import ( NSEvent , NSKeyDownMask , NSKeyUpMask , NSFlagsChangedMask ) from PyObjCTools import AppHelper import objc class MacKeyboardSetup ( NSObject ) : @ objc . python_method def init_with_handler ( self , handler ) : self = super ( MacKeyboardSetup , self ) . init ( ) self . handler = handler return self def applicationDidFinishLaunching_ ( self , notification ) : mask = NSKeyDownMask | NSKeyUpMask | NSFlagsChangedMask NSEvent . addGlobalMonitorForEventsMatchingMask_handler_ ( mask , self . handler ) class MacKeyboardListener ( AppKitKeyboardListener ) : def install_handle_input ( self ) : self . app = NSApplication . sharedApplication ( ) delegate = MacKeyboardSetup . alloc ( ) . init_with_handler ( self . handle_input ) NSApp ( ) . setDelegate_ ( delegate ) AppHelper . runEventLoop ( ) def __del__ ( self ) : AppHelper . stopEventLoop ( ) keyboard = MacKeyboardListener ( pipe ) | Single subprocesses for reading keyboard on Mac . |
13,455 | def delay_and_stop ( duration , dll , device_number ) : xinput = getattr ( ctypes . windll , dll ) time . sleep ( duration / 1000 ) xinput_set_state = xinput . XInputSetState xinput_set_state . argtypes = [ ctypes . c_uint , ctypes . POINTER ( XinputVibration ) ] xinput_set_state . restype = ctypes . c_uint vibration = XinputVibration ( 0 , 0 ) xinput_set_state ( device_number , ctypes . byref ( vibration ) ) | Stop vibration aka force feedback aka rumble on Windows after duration miliseconds . |
13,456 | def create_event_object ( self , event_type , code , value , timeval = None ) : if not timeval : self . update_timeval ( ) timeval = self . timeval try : event_code = self . type_codes [ event_type ] except KeyError : raise UnknownEventType ( "We don't know what kind of event a %s is." % event_type ) event = struct . pack ( EVENT_FORMAT , timeval [ 0 ] , timeval [ 1 ] , event_code , code , value ) return event | Create an evdev style structure . |
13,457 | def emulate_wheel ( self , data , direction , timeval ) : if direction == 'x' : code = 0x06 elif direction == 'z' : code = 0x07 else : code = 0x08 if WIN : data = data // 120 return self . create_event_object ( "Relative" , code , data , timeval ) | Emulate rel values for the mouse wheel . |
13,458 | def emulate_rel ( self , key_code , value , timeval ) : return self . create_event_object ( "Relative" , key_code , value , timeval ) | Emulate the relative changes of the mouse cursor . |
13,459 | def emulate_press ( self , key_code , scan_code , value , timeval ) : scan_event = self . create_event_object ( "Misc" , 0x04 , scan_code , timeval ) key_event = self . create_event_object ( "Key" , key_code , value , timeval ) return scan_event , key_event | Emulate a button press . |
13,460 | def emulate_abs ( self , x_val , y_val , timeval ) : x_event = self . create_event_object ( "Absolute" , 0x00 , x_val , timeval ) y_event = self . create_event_object ( "Absolute" , 0x01 , y_val , timeval ) return x_event , y_event | Emulate the absolute co - ordinates of the mouse cursor . |
13,461 | def listen ( ) : msg = MSG ( ) ctypes . windll . user32 . GetMessageA ( ctypes . byref ( msg ) , 0 , 0 , 0 ) | Listen for keyboard input . |
13,462 | def get_fptr ( self ) : cmpfunc = ctypes . CFUNCTYPE ( ctypes . c_int , WPARAM , LPARAM , ctypes . POINTER ( KBDLLHookStruct ) ) return cmpfunc ( self . handle_input ) | Get the function pointer . |
13,463 | def install_handle_input ( self ) : self . pointer = self . get_fptr ( ) self . hooked = ctypes . windll . user32 . SetWindowsHookExA ( 13 , self . pointer , ctypes . windll . kernel32 . GetModuleHandleW ( None ) , 0 ) if not self . hooked : return False return True | Install the hook . |
13,464 | def uninstall_handle_input ( self ) : if self . hooked is None : return ctypes . windll . user32 . UnhookWindowsHookEx ( self . hooked ) self . hooked = None | Remove the hook . |
13,465 | def emulate_mouse ( self , key_code , x_val , y_val , data ) : self . update_timeval ( ) events = [ ] if key_code == 0x0200 : pass elif key_code == 0x020A : events . append ( self . emulate_wheel ( data , 'y' , self . timeval ) ) elif key_code == 0x020E : events . append ( self . emulate_wheel ( data , 'x' , self . timeval ) ) else : if key_code == 0x020B and data == 2 : key_code = 0x020B2 elif key_code == 0x020C and data == 2 : key_code = 0x020C2 code , value , scan_code = self . mouse_codes [ key_code ] scan_event , key_event = self . emulate_press ( code , scan_code , value , self . timeval ) events . append ( scan_event ) events . append ( key_event ) x_event , y_event = self . emulate_abs ( x_val , y_val , self . timeval ) events . append ( x_event ) events . append ( y_event ) events . append ( self . sync_marker ( self . timeval ) ) self . write_to_pipe ( events ) | Emulate the ev codes using the data Windows has given us . |
13,466 | def handle_button ( self , event , event_type ) : mouse_button_number = self . _get_mouse_button_number ( event ) if event_type in ( 25 , 26 ) : event_type = event_type + ( mouse_button_number * 0.1 ) event_type_string , event_code , value , scan = self . codes [ event_type ] if event_type_string == "Key" : scan_event , key_event = self . emulate_press ( event_code , scan , value , self . timeval ) self . events . append ( scan_event ) self . events . append ( key_event ) click_state = self . _get_click_state ( event ) repeat = self . emulate_repeat ( click_state , self . timeval ) self . events . append ( repeat ) | Convert the button information from quartz into evdev format . |
13,467 | def handle_relative ( self , event ) : delta_x , delta_y = self . _get_relative ( event ) if delta_x : self . events . append ( self . emulate_rel ( 0x00 , delta_x , self . timeval ) ) if delta_y : self . events . append ( self . emulate_rel ( 0x01 , delta_y , self . timeval ) ) | Relative mouse movement . |
13,468 | def handle_input ( self , proxy , event_type , event , refcon ) : self . update_timeval ( ) self . events = [ ] if event_type in ( 1 , 2 , 3 , 4 , 25 , 26 , 27 ) : self . handle_button ( event , event_type ) if event_type == 22 : self . handle_scrollwheel ( event ) self . handle_absolute ( event ) self . handle_relative ( event ) self . events . append ( self . sync_marker ( self . timeval ) ) self . write_to_pipe ( self . events ) | Handle an input event . |
13,469 | def _get_deltas ( event ) : delta_x = round ( event . deltaX ( ) ) delta_y = round ( event . deltaY ( ) ) delta_z = round ( event . deltaZ ( ) ) return delta_x , delta_y , delta_z | Get the changes from the appkit event . |
13,470 | def handle_button ( self , event , event_type ) : mouse_button_number = self . _get_mouse_button_number ( event ) if event_type in ( 25 , 26 ) : event_type = event_type + ( mouse_button_number * 0.1 ) event_type_name , event_code , value , scan = self . codes [ event_type ] if event_type_name == "Key" : scan_event , key_event = self . emulate_press ( event_code , scan , value , self . timeval ) self . events . append ( scan_event ) self . events . append ( key_event ) | Handle mouse click . |
13,471 | def handle_scrollwheel ( self , event ) : delta_x , delta_y , delta_z = self . _get_deltas ( event ) if delta_x : self . events . append ( self . emulate_wheel ( delta_x , 'x' , self . timeval ) ) if delta_y : self . events . append ( self . emulate_wheel ( delta_y , 'y' , self . timeval ) ) if delta_z : self . events . append ( self . emulate_wheel ( delta_z , 'z' , self . timeval ) ) | Make endev from appkit scroll wheel event . |
13,472 | def handle_relative ( self , event ) : delta_x , delta_y , delta_z = self . _get_deltas ( event ) if delta_x : self . events . append ( self . emulate_rel ( 0x00 , delta_x , self . timeval ) ) if delta_y : self . events . append ( self . emulate_rel ( 0x01 , delta_y , self . timeval ) ) if delta_z : self . events . append ( self . emulate_rel ( 0x02 , delta_z , self . timeval ) ) | Get the position of the mouse on the screen . |
13,473 | def handle_input ( self , event ) : self . update_timeval ( ) self . events = [ ] code = self . _get_event_type ( event ) self . handle_button ( event , code ) if code == 22 : self . handle_scrollwheel ( event ) else : self . handle_relative ( event ) self . handle_absolute ( event ) self . events . append ( self . sync_marker ( self . timeval ) ) self . write_to_pipe ( self . events ) | Process the mouse event . |
13,474 | def _get_key_value ( self , event , event_type ) : if event_type == 10 : value = 1 elif event_type == 11 : value = 0 elif event_type == 12 : value = self . _get_flag_value ( event ) else : value = - 1 return value | Get the key value . |
13,475 | def handle_input ( self , event ) : self . update_timeval ( ) self . events = [ ] code = self . _get_event_key_code ( event ) if code in self . codes : new_code = self . codes [ code ] else : new_code = 0 event_type = self . _get_event_type ( event ) value = self . _get_key_value ( event , event_type ) scan_event , key_event = self . emulate_press ( new_code , code , value , self . timeval ) self . events . append ( scan_event ) self . events . append ( key_event ) self . events . append ( self . sync_marker ( self . timeval ) ) self . write_to_pipe ( self . events ) | Process they keyboard input . |
13,476 | def _get_path_infomation ( self ) : long_identifier = self . _device_path . split ( '/' ) [ 4 ] protocol , remainder = long_identifier . split ( '-' , 1 ) identifier , _ , device_type = remainder . rsplit ( '-' , 2 ) return ( protocol , identifier , device_type ) | Get useful infomation from the device path . |
13,477 | def _get_total_read_size ( self ) : if self . read_size : read_size = EVENT_SIZE * self . read_size else : read_size = EVENT_SIZE return read_size | How much event data to process at once . |
13,478 | def _make_event ( self , tv_sec , tv_usec , ev_type , code , value ) : event_type = self . manager . get_event_type ( ev_type ) eventinfo = { "ev_type" : event_type , "state" : value , "timestamp" : tv_sec + ( tv_usec / 1000000 ) , "code" : self . manager . get_event_string ( event_type , code ) } return InputEvent ( self , eventinfo ) | Create a friendly Python object from an evdev style event . |
13,479 | def _pipe ( self ) : if self . _evdev : return None if not self . __pipe : target_function = self . _get_target_function ( ) if not target_function : return None self . __pipe , child_conn = Pipe ( duplex = False ) self . _listener = Process ( target = target_function , args = ( child_conn , ) , daemon = True ) self . _listener . start ( ) return self . __pipe | On Windows we use a pipe to emulate a Linux style character buffer . |
13,480 | def _number_xpad ( self ) : js_path = self . _device_path . replace ( '-event' , '' ) js_chardev = os . path . realpath ( js_path ) try : number_text = js_chardev . split ( 'js' ) [ 1 ] except IndexError : return try : number = int ( number_text ) except ValueError : return self . __device_number = number | Get the number of the joystick . |
13,481 | def __check_state ( self ) : state = self . __read_device ( ) if not state : raise UnpluggedError ( "Gamepad %d is not connected" % self . __device_number ) if state . packet_number != self . __last_state . packet_number : self . __handle_changed_state ( state ) self . __last_state = state | On Windows check the state and fill the event character device . |
13,482 | def create_event_object ( self , event_type , code , value , timeval = None ) : if not timeval : timeval = self . __get_timeval ( ) try : event_code = self . manager . codes [ 'type_codes' ] [ event_type ] except KeyError : raise UnknownEventType ( "We don't know what kind of event a %s is." % event_type ) event = struct . pack ( EVENT_FORMAT , timeval [ 0 ] , timeval [ 1 ] , event_code , code , value ) return event | Create an evdev style object . |
13,483 | def __write_to_character_device ( self , event_list , timeval = None ) : pos = self . _character_device . tell ( ) self . _character_device . seek ( 0 , 2 ) for event in event_list : self . _character_device . write ( event ) sync = self . create_event_object ( "Sync" , 0 , 0 , timeval ) self . _character_device . write ( sync ) self . _character_device . seek ( pos ) | Emulate the Linux character device on other platforms such as Windows . |
13,484 | def __get_button_events ( self , state , timeval = None ) : changed_buttons = self . __detect_button_events ( state ) events = self . __emulate_buttons ( changed_buttons , timeval ) return events | Get the button events from xinput . |
13,485 | def __get_axis_events ( self , state , timeval = None ) : axis_changes = self . __detect_axis_events ( state ) events = self . __emulate_axis ( axis_changes , timeval ) return events | Get the stick events from xinput . |
13,486 | def __emulate_axis ( self , axis_changes , timeval = None ) : events = [ ] for axis in axis_changes : code , value = self . __map_axis ( axis ) event = self . create_event_object ( "Absolute" , code , value , timeval = timeval ) events . append ( event ) return events | Make the axis events use the Linux style format . |
13,487 | def __emulate_buttons ( self , changed_buttons , timeval = None ) : events = [ ] for button in changed_buttons : code , value , ev_type = self . __map_button ( button ) event = self . create_event_object ( ev_type , code , value , timeval = timeval ) events . append ( event ) return events | Make the button events use the Linux style format . |
13,488 | def __get_bit_values ( self , number , size = 32 ) : res = list ( self . __gen_bit_values ( number ) ) res . reverse ( ) res = [ 0 ] * ( size - len ( res ) ) + res return res | Get bit values as a list for a given number |
13,489 | def __read_device ( self ) : state = XinputState ( ) res = self . manager . xinput . XInputGetState ( self . __device_number , ctypes . byref ( state ) ) if res == XINPUT_ERROR_SUCCESS : return state if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED : raise RuntimeError ( "Unknown error %d attempting to get state of device %d" % ( res , self . __device_number ) ) return None | Read the state of the gamepad . |
13,490 | def _start_vibration_win ( self , left_motor , right_motor ) : xinput_set_state = self . manager . xinput . XInputSetState xinput_set_state . argtypes = [ ctypes . c_uint , ctypes . POINTER ( XinputVibration ) ] xinput_set_state . restype = ctypes . c_uint vibration = XinputVibration ( int ( left_motor * 65535 ) , int ( right_motor * 65535 ) ) xinput_set_state ( self . __device_number , ctypes . byref ( vibration ) ) | Start the vibration which will run until stopped . |
13,491 | def _stop_vibration_win ( self ) : xinput_set_state = self . manager . xinput . XInputSetState xinput_set_state . argtypes = [ ctypes . c_uint , ctypes . POINTER ( XinputVibration ) ] xinput_set_state . restype = ctypes . c_uint stop_vibration = ctypes . byref ( XinputVibration ( 0 , 0 ) ) xinput_set_state ( self . __device_number , stop_vibration ) | Stop the vibration . |
13,492 | def _set_vibration_win ( self , left_motor , right_motor , duration ) : self . _start_vibration_win ( left_motor , right_motor ) stop_process = Process ( target = delay_and_stop , args = ( duration , self . manager . xinput_dll , self . __device_number ) ) stop_process . start ( ) | Control the motors on Windows . |
13,493 | def __get_vibration_code ( self , left_motor , right_motor , duration ) : inner_event = struct . pack ( '2h6x2h2x2H28x' , 0x50 , - 1 , duration , 0 , int ( left_motor * 65535 ) , int ( right_motor * 65535 ) ) buf_conts = ioctl ( self . _write_device , 1076905344 , inner_event ) return int ( codecs . encode ( buf_conts [ 1 : 3 ] , 'hex' ) , 16 ) | This is some crazy voodoo if you can simplify it please do . |
13,494 | def _set_vibration_nix ( self , left_motor , right_motor , duration ) : code = self . __get_vibration_code ( left_motor , right_motor , duration ) secs , msecs = convert_timeval ( time . time ( ) ) outer_event = struct . pack ( EVENT_FORMAT , secs , msecs , 0x15 , code , 1 ) self . _write_device . write ( outer_event ) self . _write_device . flush ( ) | Control the motors on Linux . Duration is in miliseconds . |
13,495 | def max_brightness ( self ) : status_filename = os . path . join ( self . path , 'max_brightness' ) with open ( status_filename ) as status_fp : result = status_fp . read ( ) status_text = result . strip ( ) try : status = int ( status_text ) except ValueError : return status_text return status | Get the device s maximum brightness level . |
13,496 | def _write_device ( self ) : if not self . _write_file : if not NIX : return None try : self . _write_file = io . open ( self . _character_device_path , 'wb' ) except PermissionError : raise PermissionError ( PERMISSIONS_ERROR_TEXT ) except IOError as err : if err . errno == 13 : raise PermissionError ( PERMISSIONS_ERROR_TEXT ) else : raise return self . _write_file | The output device . |
13,497 | def _post_init ( self ) : self . _led_type_code = self . manager . get_typecode ( 'LED' ) self . device_path = os . path . realpath ( os . path . join ( self . path , 'device' ) ) if '::' in self . name : chardev , code_name = self . name . split ( '::' ) if code_name in self . manager . codes [ 'LED_type_codes' ] : self . code = self . manager . codes [ 'LED_type_codes' ] [ code_name ] try : event_number = chardev . split ( 'input' ) [ 1 ] except IndexError : print ( "Failed with" , self . name ) raise else : self . _character_device_path = '/dev/input/event' + event_number self . _match_device ( ) | Set up the device path and type code . |
13,498 | def _match_device ( self ) : for device in self . manager . all_devices : if ( device . get_char_device_path ( ) == self . _character_device_path ) : self . device = device device . leds . append ( self ) break | If the LED is connected to an input device associate the objects . |
13,499 | def _post_init ( self ) : if WIN : self . _find_devices_win ( ) elif MAC : self . _find_devices_mac ( ) else : self . _find_devices ( ) self . _update_all_devices ( ) if NIX : self . _find_leds ( ) | Call the find devices method for the relevant platform . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.