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}' . for... | 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}' . ... | 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 !=... | 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' : ... | 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_fr... | 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' , 'En... | 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 ... | 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 ( 'Scr... | 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 ... | 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 = ... | 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 ( ) ... | 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 ( scann... | 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... | 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 ( f... | 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 ( 'Includ... | 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 ( 'Ex... | 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' ] ... | 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... | 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 ,... | 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 , ... | 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 ) r... | 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 . kCG... | 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 , NSMo... | 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 (... | 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 =... | 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 . p... | 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 . tim... | 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 ... | 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_relativ... | 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 , ke... | 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 ... | 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 . app... | 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 . syn... | 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... | 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 ( s... | 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 . ... | 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 = stru... | 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 . writ... | 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 %... | 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 ... | 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 . __d... | 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 ... | 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 )... | 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_ERR... | 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' ] : se... | 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.