idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
230,600
def cmd_terrain_check ( self , args ) : if len ( args ) >= 2 : latlon = ( float ( args [ 0 ] ) , float ( args [ 1 ] ) ) else : try : latlon = self . module ( 'map' ) . click_position except Exception : print ( "No map available" ) return if latlon is None : print ( "No map click position available" ) return self . chec...
check a piece of terrain data
230,601
def idle_task ( self ) : if self . current_request is None : return if time . time ( ) - self . last_send_time < 0.2 : return self . send_terrain_data ( )
called when idle
230,602
def unknown_command ( self , args ) : mode_mapping = self . master . mode_mapping ( ) mode = args [ 0 ] . upper ( ) if mode in mode_mapping : self . master . set_mode ( mode_mapping [ mode ] ) return True return False
handle mode switch by mode name as command
230,603
def cmd_guided ( self , args ) : if len ( args ) != 1 and len ( args ) != 3 : print ( "Usage: guided ALTITUDE | guided LAT LON ALTITUDE" ) return if len ( args ) == 3 : latitude = float ( args [ 0 ] ) longitude = float ( args [ 1 ] ) altitude = float ( args [ 2 ] ) latlon = ( latitude , longitude ) else : try : latlon ...
set GUIDED target
230,604
def check_sim_in ( self ) : try : pkt = self . sim_in . recv ( 17 * 8 + 4 ) except socket . error as e : if not e . errno in [ errno . EAGAIN , errno . EWOULDBLOCK ] : raise return if len ( pkt ) != 17 * 8 + 4 : print ( "wrong size %u" % len ( pkt ) ) return ( latitude , longitude , altitude , heading , v_north , v_eas...
check for FDM packets from runsim
230,605
def check_sim_out ( self ) : now = time . time ( ) if now - self . last_sim_send_time < 0.02 or self . rc_channels_scaled is None : return self . last_sim_send_time = now servos = [ ] for ch in range ( 1 , 9 ) : servos . append ( self . scale_channel ( ch , getattr ( self . rc_channels_scaled , 'chan%u_scaled' % ch ) )...
check if we should send new servos to flightgear
230,606
def check_apm_out ( self ) : now = time . time ( ) if now - self . last_apm_send_time < 0.02 : return self . last_apm_send_time = now if self . hil_state_msg is not None : self . master . mav . send ( self . hil_state_msg )
check if we should send new data to the APM
230,607
def convert_body_frame ( self , phi , theta , phiDot , thetaDot , psiDot ) : p = phiDot - psiDot * math . sin ( theta ) q = math . cos ( phi ) * thetaDot + math . sin ( phi ) * psiDot * math . cos ( theta ) r = math . cos ( phi ) * psiDot * math . cos ( theta ) - math . sin ( phi ) * thetaDot return ( p , q , r )
convert a set of roll rates from earth frame to body frame
230,608
def append ( self , v ) : if isinstance ( v , MPSetting ) : setting = v else : ( name , type , default ) = v label = name tab = None if len ( v ) > 3 : label = v [ 3 ] if len ( v ) > 4 : tab = v [ 4 ] setting = MPSetting ( name , type , default , label = label , tab = tab ) if setting . tab is None : setting . tab = se...
add a new setting
230,609
def get ( self , name ) : if not name in self . _vars : raise AttributeError setting = self . _vars [ name ] return setting . value
get a setting
230,610
def command ( self , args ) : if len ( args ) == 0 : self . show_all ( ) return if getattr ( self , args [ 0 ] , [ None ] ) == [ None ] : print ( "Unknown setting '%s'" % args [ 0 ] ) return if len ( args ) == 1 : self . show ( args [ 0 ] ) else : self . set ( args [ 0 ] , args [ 1 ] )
control options from cmdline
230,611
def all_checks_enabled ( self ) : arming_mask = int ( self . get_mav_param ( "ARMING_CHECK" , 0 ) ) if arming_mask == 1 : return True for bit in arming_masks . values ( ) : if not arming_mask & bit and bit != 1 : return False return True
returns true if the UAV is skipping any arming checks
230,612
def handle_px4_param_value ( self , m ) : if m . param_type == mavutil . mavlink . MAV_PARAM_TYPE_REAL32 : return m . param_value is_px4_params = False if m . get_srcComponent ( ) in [ mavutil . mavlink . MAV_COMP_ID_UDP_BRIDGE ] : is_px4_params = True sysid = m . get_srcSystem ( ) if self . autopilot_type_by_sysid . g...
special handling for the px4 style of PARAM_VALUE
230,613
def param_help_download ( self ) : files = [ ] for vehicle in [ 'APMrover2' , 'ArduCopter' , 'ArduPlane' , 'ArduSub' , 'AntennaTracker' ] : url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml' % vehicle path = mp_util . dot_mavproxy ( "%s.xml" % vehicle ) files . append ( ( url , path ) ) url = 'http://auto...
download XML files for parameters
230,614
def param_help_tree ( self ) : if self . xml_filepath is not None : print ( "param: using xml_filepath=%s" % self . xml_filepath ) path = self . xml_filepath else : if self . vehicle_name is None : print ( "Unknown vehicle type" ) return None path = mp_util . dot_mavproxy ( "%s.xml" % self . vehicle_name ) if not os . ...
return a help tree a map between a parameter and its metadata . May return None if help is not available
230,615
def param_apropos ( self , args ) : if len ( args ) == 0 : print ( "Usage: param apropos keyword" ) return htree = self . param_help_tree ( ) if htree is None : return contains = { } for keyword in args : for param in htree . keys ( ) : if str ( htree [ param ] ) . find ( keyword ) != - 1 : contains [ param ] = True fo...
search parameter help for a keyword list those parameters
230,616
def get_component_id_list ( self , system_id ) : ret = [ ] for ( s , c ) in self . mpstate . mav_param_by_sysid . keys ( ) : if s == system_id : ret . append ( c ) return ret
get list of component IDs with parameters for a given system ID
230,617
def get_sysid ( self ) : component = self . target_component if component == 0 : component = 1 return ( self . target_system , component )
get sysid tuple to use for parameters
230,618
def parse_args ( self , args = None , values = None ) : q = multiproc . Queue ( ) p = multiproc . Process ( target = self . _parse_args , args = ( q , args , values ) ) p . start ( ) ret = q . get ( ) p . join ( ) return ret
multiprocessing wrapper around _parse_args
230,619
def _parse_args ( self , q , args , values ) : if wx . GetApp ( ) is None : self . app = wx . App ( False ) option_values , args = self . SUPER . parse_args ( self , args , values ) for option in self . option_list : if option . dest and hasattr ( option_values , option . dest ) : default = getattr ( option_values , op...
This is the heart of it all - overrides optparse . OptionParser . parse_args
230,620
def distance_from ( self , lat , lon ) : lat1 = self . pkt [ 'I105' ] [ 'Lat' ] [ 'val' ] lon1 = self . pkt [ 'I105' ] [ 'Lon' ] [ 'val' ] return mp_util . gps_distance ( lat1 , lon1 , lat , lon )
get distance from a point
230,621
def randpos ( self ) : self . setpos ( gen_settings . home_lat , gen_settings . home_lon ) self . move ( random . uniform ( 0 , 360 ) , random . uniform ( 0 , gen_settings . region_width ) )
random initial position
230,622
def ground_height ( self ) : lat = self . pkt [ 'I105' ] [ 'Lat' ] [ 'val' ] lon = self . pkt [ 'I105' ] [ 'Lon' ] [ 'val' ] global ElevationMap ret = ElevationMap . GetElevation ( lat , lon ) ret -= gen_settings . wgs84_to_AMSL return ret * 3.2807
return height above ground in feet
230,623
def move ( self , bearing , distance ) : lat = self . pkt [ 'I105' ] [ 'Lat' ] [ 'val' ] lon = self . pkt [ 'I105' ] [ 'Lon' ] [ 'val' ] ( lat , lon ) = mp_util . gps_newpos ( lat , lon , bearing , distance ) self . setpos ( lat , lon )
move position by bearing and distance
230,624
def update ( self , deltat = 1.0 ) : DNFZ . update ( self , deltat ) self . dist_flown += self . speed * deltat if self . dist_flown > self . circuit_width : self . desired_heading = self . heading + 90 self . dist_flown = 0 if self . getalt ( ) < self . ground_height ( ) or self . getalt ( ) > self . ground_height ( )...
fly a square circuit
230,625
def update ( self , deltat = 1.0 ) : DNFZ . update ( self , deltat ) self . time_circling += deltat self . setheading ( self . heading + self . turn_rate * deltat ) self . move ( self . drift_heading , self . drift_speed ) if self . getalt ( ) > self . max_alt or self . getalt ( ) < self . ground_height ( ) : if self ....
fly circles then dive
230,626
def update ( self , deltat = 1.0 ) : DNFZ . update ( self , deltat ) if ( self . distance_from_home ( ) > gen_settings . region_width or self . getalt ( ) < self . ground_height ( ) or self . getalt ( ) > self . ground_height ( ) + 1000 ) : self . randpos ( ) self . randalt ( )
fly in long curves
230,627
def update ( self , deltat = 1.0 ) : DNFZ . update ( self , deltat ) self . lifetime -= deltat if self . lifetime <= 0 : self . randpos ( ) self . lifetime = random . uniform ( 300 , 600 )
straight lines with short life
230,628
def cmd_dropobject ( self , obj ) : latlon = self . module ( 'map' ) . click_position if self . last_click is not None and self . last_click == latlon : return self . last_click = latlon if latlon is not None : obj . setpos ( latlon [ 0 ] , latlon [ 1 ] ) self . aircraft . append ( obj )
drop an object on the map
230,629
def cmd_genobstacles ( self , args ) : usage = "usage: genobstacles <start|stop|restart|clearall|status|set>" if len ( args ) == 0 : print ( usage ) return if args [ 0 ] == "set" : gen_settings . command ( args [ 1 : ] ) elif args [ 0 ] == "start" : if self . have_home : self . start ( ) else : self . pending_start = T...
genobstacles command parser
230,630
def start ( self ) : if self . sock is not None : self . sock . close ( ) self . sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM , socket . IPPROTO_UDP ) self . sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) self . sock . connect ( ( '' , gen_settings . port ) ) global track_count...
start sending packets
230,631
def mavlink_packet ( self , m ) : if not self . have_home and m . get_type ( ) == 'GPS_RAW_INT' and m . fix_type >= 3 : gen_settings . home_lat = m . lat * 1.0e-7 gen_settings . home_lon = m . lon * 1.0e-7 self . have_home = True if self . pending_start : self . start ( ) if m . get_type ( ) != 'ATTITUDE' : return t = ...
trigger sends from ATTITUDE packets
230,632
def update ( self , state , tnow ) : self . state = state self . update_time = tnow
update the threat state
230,633
def cmd_ADSB ( self , args ) : usage = "usage: adsb <set>" if len ( args ) == 0 : print ( usage ) return if args [ 0 ] == "status" : print ( "total threat count: %u active threat count: %u" % ( len ( self . threat_vehicles ) , len ( self . active_threat_ids ) ) ) for id in self . threat_vehicles . keys ( ) : print ( "...
adsb command parser
230,634
def update_threat_distances ( self , latlonalt ) : for id in self . threat_vehicles . keys ( ) : threat_latlonalt = ( self . threat_vehicles [ id ] . state [ 'lat' ] * 1e-7 , self . threat_vehicles [ id ] . state [ 'lon' ] * 1e-7 , self . threat_vehicles [ id ] . state [ 'altitude' ] ) self . threat_vehicles [ id ] . h...
update the distance between threats and vehicle
230,635
def check_threat_timeout ( self ) : for id in self . threat_vehicles . keys ( ) : if self . threat_vehicles [ id ] . update_time == 0 : self . threat_vehicles [ id ] . update_time = self . get_time ( ) dt = self . get_time ( ) - self . threat_vehicles [ id ] . update_time if dt > self . ADSB_settings . timeout : del se...
check and handle threat time out
230,636
def cmd_gopro_status ( self , args ) : master = self . master if 'GOPRO_HEARTBEAT' in master . messages : print ( master . messages [ 'GOPRO_HEARTBEAT' ] ) else : print ( "No GOPRO_HEARTBEAT messages" )
show gopro status
230,637
def on_text_url ( self , event ) : try : import webbrowser except ImportError : return mouse_event = event . GetMouseEvent ( ) if mouse_event . LeftDClick ( ) : url_start = event . GetURLStart ( ) url_end = event . GetURLEnd ( ) url = self . control . GetRange ( url_start , url_end ) try : browser_controller = webbrows...
handle double clicks on URL text
230,638
def update_channels ( self ) : self . interlock_channel = - 1 self . override_channel = - 1 self . zero_I_channel = - 1 self . no_vtol_channel = - 1 self . rsc_out_channel = 9 self . fwd_thr_channel = 10 for ch in range ( 1 , 16 ) : option = self . get_mav_param ( "RC%u_OPTION" % ch , 0 ) if option == 32 : self . inter...
update which channels provide input
230,639
def rallyloader ( self ) : if not self . target_system in self . rallyloader_by_sysid : self . rallyloader_by_sysid [ self . target_system ] = mavwp . MAVRallyLoader ( self . settings . target_system , self . settings . target_component ) return self . rallyloader_by_sysid [ self . target_system ]
rally loader by system ID
230,640
def packet_is_for_me ( self , m ) : if m . target_system != self . master . mav . srcSystem : return False if m . target_component != self . master . mav . srcComponent : return False if self . sender is not None : if ( m . get_srcSystem ( ) , m . get_srcComponent ( ) ) != self . sender : return False return True
returns true if this packet is appropriately addressed
230,641
def _convert_agg_to_wx_image ( agg , bbox ) : if bbox is None : image = wx . EmptyImage ( int ( agg . width ) , int ( agg . height ) ) image . SetData ( agg . tostring_rgb ( ) ) return image else : return wx . ImageFromBitmap ( _WX28_clipped_agg_as_bitmap ( agg , bbox ) )
Convert the region of the agg buffer bounded by bbox to a wx . Image . If bbox is None the entire buffer is converted .
230,642
def _convert_agg_to_wx_bitmap ( agg , bbox ) : if bbox is None : return wx . BitmapFromBufferRGBA ( int ( agg . width ) , int ( agg . height ) , agg . buffer_rgba ( ) ) else : return _WX28_clipped_agg_as_bitmap ( agg , bbox )
Convert the region of the agg buffer bounded by bbox to a wx . Bitmap . If bbox is None the entire buffer is converted .
230,643
def _WX28_clipped_agg_as_bitmap ( agg , bbox ) : l , b , width , height = bbox . bounds r = l + width t = b + height srcBmp = wx . BitmapFromBufferRGBA ( int ( agg . width ) , int ( agg . height ) , agg . buffer_rgba ( ) ) srcDC = wx . MemoryDC ( ) srcDC . SelectObject ( srcBmp ) destBmp = wx . EmptyBitmap ( int ( widt...
Convert the region of a the agg buffer bounded by bbox to a wx . Bitmap .
230,644
def draw ( self , drawDC = None ) : DEBUG_MSG ( "draw()" , 1 , self ) FigureCanvasAgg . draw ( self ) self . bitmap = _convert_agg_to_wx_bitmap ( self . get_renderer ( ) , None ) self . _isDrawn = True self . gui_repaint ( drawDC = drawDC )
Render the figure using agg .
230,645
def blit ( self , bbox = None ) : if bbox is None : self . bitmap = _convert_agg_to_wx_bitmap ( self . get_renderer ( ) , None ) self . gui_repaint ( ) return l , b , w , h = bbox . bounds r = l + w t = b + h x = int ( l ) y = int ( self . bitmap . GetHeight ( ) - t ) srcBmp = _convert_agg_to_wx_bitmap ( self . get_ren...
Transfer the region of the agg buffer defined by bbox to the display . If bbox is None the entire buffer is transferred .
230,646
def cmd_antenna ( self , args ) : if len ( args ) != 2 : if self . gcs_location is None : print ( "GCS location not set" ) else : print ( "GCS location %s" % str ( self . gcs_location ) ) return self . gcs_location = ( float ( args [ 0 ] ) , float ( args [ 1 ] ) )
set gcs location
230,647
def passphrase_to_key ( self , passphrase ) : import hashlib h = hashlib . new ( 'sha256' ) h . update ( passphrase ) return h . digest ( )
convert a passphrase to a 32 byte key
230,648
def cmd_signing_setup ( self , args ) : if len ( args ) == 0 : print ( "usage: signing setup passphrase" ) return if not self . master . mavlink20 ( ) : print ( "You must be using MAVLink2 for signing" ) return passphrase = args [ 0 ] key = self . passphrase_to_key ( passphrase ) secret_key = [ ] for b in key : secret_...
setup signing key on board
230,649
def allow_unsigned ( self , mav , msgId ) : if self . allow is None : self . allow = { mavutil . mavlink . MAVLINK_MSG_ID_RADIO : True , mavutil . mavlink . MAVLINK_MSG_ID_RADIO_STATUS : True } if msgId in self . allow : return True if self . settings . allow_unsigned : return True return False
see if an unsigned packet should be allowed
230,650
def cmd_signing_key ( self , args ) : if len ( args ) == 0 : print ( "usage: signing setup passphrase" ) return if not self . master . mavlink20 ( ) : print ( "You must be using MAVLink2 for signing" ) return passphrase = args [ 0 ] key = self . passphrase_to_key ( passphrase ) self . master . setup_signing ( key , sig...
set signing key on connection
230,651
def cmd_signing_remove ( self , args ) : if not self . master . mavlink20 ( ) : print ( "You must be using MAVLink2 for signing" ) return self . master . mav . setup_signing_send ( self . target_system , self . target_component , [ 0 ] * 32 , 0 ) self . master . disable_signing ( ) print ( "Removed signing" )
remove signing from server
230,652
def cmd_output ( self , args ) : if len ( args ) < 1 or args [ 0 ] == "list" : self . cmd_output_list ( ) elif args [ 0 ] == "add" : if len ( args ) != 2 : print ( "Usage: output add OUTPUT" ) return self . cmd_output_add ( args [ 1 : ] ) elif args [ 0 ] == "remove" : if len ( args ) != 2 : print ( "Usage: output remov...
handle output commands
230,653
def cmd_output_add ( self , args ) : device = args [ 0 ] print ( "Adding output %s" % device ) try : conn = mavutil . mavlink_connection ( device , input = False , source_system = self . settings . source_system ) conn . mav . srcComponent = self . settings . source_component except Exception : print ( "Failed to conne...
add new output
230,654
def cmd_output_sysid ( self , args ) : sysid = int ( args [ 0 ] ) device = args [ 1 ] print ( "Adding output %s for sysid %u" % ( device , sysid ) ) try : conn = mavutil . mavlink_connection ( device , input = False , source_system = self . settings . source_system ) conn . mav . srcComponent = self . settings . source...
add new output for a specific MAVLink sysID
230,655
def cmd_output_remove ( self , args ) : device = args [ 0 ] for i in range ( len ( self . mpstate . mav_outputs ) ) : conn = self . mpstate . mav_outputs [ i ] if str ( i ) == device or conn . address == device : print ( "Removing output %s" % conn . address ) try : mp_util . child_fd_list_add ( conn . port . fileno ( ...
remove an output
230,656
def set_center ( self , lat , lon ) : self . object_queue . put ( SlipCenter ( ( lat , lon ) ) )
set center of view
230,657
def get_event ( self ) : if self . event_queue . qsize ( ) == 0 : return None evt = self . event_queue . get ( ) while isinstance ( evt , win_layout . WinLayout ) : win_layout . set_layout ( evt , self . set_layout ) if self . event_queue . qsize ( ) == 0 : return None evt = self . event_queue . get ( ) return evt
return next event or None
230,658
def cmd_layout ( self , args ) : from MAVProxy . modules . lib import win_layout if len ( args ) < 1 : print ( "usage: layout <save|load>" ) return if args [ 0 ] == "load" : win_layout . load_layout ( self . mpstate . settings . vehicle_name ) elif args [ 0 ] == "save" : win_layout . save_layout ( self . mpstate . sett...
handle layout command
230,659
def download_files ( files ) : for ( url , file ) in files : print ( "Downloading %s as %s" % ( url , file ) ) data = download_url ( url ) if data is None : continue try : open ( file , mode = 'wb' ) . write ( data ) except Exception as e : print ( "Failed to save to %s : %s" % ( file , e ) )
download an array of files
230,660
def null_term ( str ) : if sys . version_info . major < 3 : return str if isinstance ( str , bytes ) : str = str . decode ( "utf-8" ) idx = str . find ( "\0" ) if idx != - 1 : str = str [ : idx ] return str
null terminate a string for py3
230,661
def decode_devid ( devid , pname ) : devid = int ( devid ) if devid == 0 : return bus_type = devid & 0x07 bus = ( devid >> 3 ) & 0x1F address = ( devid >> 8 ) & 0xFF devtype = ( devid >> 16 ) bustypes = { 1 : "I2C" , 2 : "SPI" , 3 : "UAVCAN" , 4 : "SITL" } compass_types = { 0x01 : "DEVTYPE_HMC5883_OLD" , 0x07 : "DEVTYP...
decode one device ID . Used for devid command in mavproxy and MAVExplorer
230,662
def _authenticate_user_dn ( self , password ) : if self . dn is None : raise self . AuthenticationFailed ( "failed to map the username to a DN." ) try : sticky = self . settings . BIND_AS_AUTHENTICATING_USER self . _bind_as ( self . dn , password , sticky = sticky ) except ldap . INVALID_CREDENTIALS : raise self . Auth...
Binds to the LDAP server with the user s DN and password . Raises AuthenticationFailed on failure .
230,663
def _load_user_dn ( self ) : if self . _using_simple_bind_mode ( ) : self . _user_dn = self . _construct_simple_user_dn ( ) else : if self . settings . CACHE_TIMEOUT > 0 : cache_key = valid_cache_key ( "django_auth_ldap.user_dn.{}" . format ( self . _username ) ) self . _user_dn = cache . get_or_set ( cache_key , self ...
Populates self . _user_dn with the distinguished name of our user .
230,664
def _search_for_user_dn ( self ) : search = self . settings . USER_SEARCH if search is None : raise ImproperlyConfigured ( "AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance." ) results = search . execute ( self . connection , { "user" : self . _username } ) if results is not None and len ( results ) == 1 : ( user_d...
Searches the directory for a user matching AUTH_LDAP_USER_SEARCH . Populates self . _user_dn and self . _user_attrs .
230,665
def _normalize_group_dns ( self , group_dns ) : if isinstance ( group_dns , LDAPGroupQuery ) : query = group_dns elif isinstance ( group_dns , str ) : query = LDAPGroupQuery ( group_dns ) elif isinstance ( group_dns , ( list , tuple ) ) and len ( group_dns ) > 0 : query = reduce ( operator . or_ , map ( LDAPGroupQuery ...
Converts one or more group DNs to an LDAPGroupQuery .
230,666
def _normalize_mirror_settings ( self ) : def malformed_mirror_groups_except ( ) : return ImproperlyConfigured ( "{} must be a collection of group names" . format ( self . settings . _name ( "MIRROR_GROUPS_EXCEPT" ) ) ) def malformed_mirror_groups ( ) : return ImproperlyConfigured ( "{} must be True or a collection of ...
Validates the group mirroring settings and converts them as necessary .
230,667
def _get_groups ( self ) : if self . _groups is None : self . _groups = _LDAPUserGroups ( self ) return self . _groups
Returns an _LDAPUserGroups object which can determine group membership .
230,668
def _bind ( self ) : self . _bind_as ( self . settings . BIND_DN , self . settings . BIND_PASSWORD , sticky = True )
Binds to the LDAP server with AUTH_LDAP_BIND_DN and AUTH_LDAP_BIND_PASSWORD .
230,669
def _bind_as ( self , bind_dn , bind_password , sticky = False ) : self . _get_connection ( ) . simple_bind_s ( bind_dn , bind_password ) self . _connection_bound = sticky
Binds to the LDAP server with the given credentials . This does not trap exceptions .
230,670
def _init_group_settings ( self ) : self . _group_type = self . settings . GROUP_TYPE if self . _group_type is None : raise ImproperlyConfigured ( "AUTH_LDAP_GROUP_TYPE must be an LDAPGroupType instance." ) self . _group_search = self . settings . GROUP_SEARCH if self . _group_search is None : raise ImproperlyConfigure...
Loads the settings we need to deal with groups .
230,671
def get_group_names ( self ) : if self . _group_names is None : self . _load_cached_attr ( "_group_names" ) if self . _group_names is None : group_infos = self . _get_group_infos ( ) self . _group_names = { self . _group_type . group_name_from_info ( group_info ) for group_info in group_infos } self . _cache_attr ( "_g...
Returns the set of Django group names that this user belongs to by virtue of LDAP group memberships .
230,672
def is_member_of ( self , group_dn ) : is_member = None group_dn = group_dn . lower ( ) if self . _group_dns is None : is_member = self . _group_type . is_member ( self . _ldap_user , group_dn ) if is_member is None : is_member = group_dn in self . get_group_dns ( ) logger . debug ( "{} is{}a member of {}" . format ( s...
Returns true if our user is a member of the given group .
230,673
def get_ldap ( cls , global_options = None ) : if not cls . _ldap_configured and global_options is not None : for opt , value in global_options . items ( ) : ldap . set_option ( opt , value ) cls . _ldap_configured = True return ldap
Returns the configured ldap module .
230,674
def search_with_additional_terms ( self , term_dict , escape = True ) : term_strings = [ self . filterstr ] for name , value in term_dict . items ( ) : if escape : value = self . ldap . filter . escape_filter_chars ( value ) term_strings . append ( "({}={})" . format ( name , value ) ) filterstr = "(&{})" . format ( ""...
Returns a new search object with additional search terms and - ed to the filter string . term_dict maps attribute names to assertion values . If you don t want the values escaped pass escape = False .
230,675
def user_groups ( self , ldap_user , group_search ) : groups = [ ] try : user_uid = ldap_user . attrs [ "uid" ] [ 0 ] if "gidNumber" in ldap_user . attrs : user_gid = ldap_user . attrs [ "gidNumber" ] [ 0 ] filterstr = "(|(gidNumber={})(memberUid={}))" . format ( self . ldap . filter . escape_filter_chars ( user_gid ) ...
Searches for any group that is either the user s primary or contains the user as a member .
230,676
def is_member ( self , ldap_user , group_dn ) : try : user_uid = ldap_user . attrs [ "uid" ] [ 0 ] try : is_member = ldap_user . connection . compare_s ( group_dn , "memberUid" , user_uid . encode ( ) ) except ( ldap . UNDEFINED_TYPE , ldap . NO_SUCH_ATTRIBUTE ) : is_member = False if not is_member : try : user_gid = l...
Returns True if the group is the user s primary group or if the user is listed in the group s memberUid attribute .
230,677
def user_groups ( self , ldap_user , group_search ) : group_info_map = { } member_dn_set = { ldap_user . dn } handled_dn_set = set ( ) while len ( member_dn_set ) > 0 : group_infos = self . find_groups_with_any_member ( member_dn_set , group_search , ldap_user . connection ) new_group_info_map = { info [ 0 ] : info for...
This searches for all of a user s groups from the bottom up . In other words it returns the groups that the user belongs to the groups that those groups belong to etc . Circular references will be detected and pruned .
230,678
def aggregator ( self ) : if self . connector == self . AND : aggregator = all elif self . connector == self . OR : aggregator = any else : raise ValueError ( self . connector ) return aggregator
Returns a function for aggregating a sequence of sub - results .
230,679
def _resolve_children ( self , ldap_user , groups ) : for child in self . children : if isinstance ( child , LDAPGroupQuery ) : yield child . resolve ( ldap_user , groups ) else : yield groups . is_member_of ( child )
Generates the query result for each child .
230,680
def gather_positions ( tree ) : pos = { 'data-x' : 'r0' , 'data-y' : 'r0' , 'data-z' : 'r0' , 'data-rotate-x' : 'r0' , 'data-rotate-y' : 'r0' , 'data-rotate-z' : 'r0' , 'data-scale' : 'r0' , 'is_path' : False } steps = 0 default_movement = True for step in tree . findall ( 'step' ) : steps += 1 for key in POSITION_ATTR...
Makes a list of positions and position commands from the tree
230,681
def calculate_positions ( positions ) : current_position = { 'data-x' : 0 , 'data-y' : 0 , 'data-z' : 0 , 'data-rotate-x' : 0 , 'data-rotate-y' : 0 , 'data-rotate-z' : 0 , 'data-scale' : 1 , } positer = iter ( positions ) position = next ( positer ) _update_position ( current_position , position ) while True : if 'path...
Calculates position information
230,682
def update_positions ( tree , positions ) : for step , pos in zip ( tree . findall ( 'step' ) , positions ) : for key in sorted ( pos ) : value = pos . get ( key ) if key . endswith ( "-rel" ) : abs_key = key [ : key . index ( "-rel" ) ] if value is not None : els = tree . findall ( ".//*[@id='" + value + "']" ) for el...
Updates the tree with new positions
230,683
def position_slides ( tree ) : positions = gather_positions ( tree ) positions = calculate_positions ( positions ) update_positions ( tree , positions )
Position the slides in the tree
230,684
def copy_node ( node ) : element = node . makeelement ( node . tag ) element . text = node . text element . tail = node . tail for key , value in node . items ( ) : element . set ( key , value ) return element
Makes a copy of a node with the same attributes and text but no children .
230,685
def copy_resource ( self , resource , targetdir ) : final_path = resource . final_path ( ) if final_path [ 0 ] == '/' or ( ':' in final_path ) or ( '?' in final_path ) : return source_path = self . get_source_path ( resource ) if resource . resource_type == DIRECTORY_RESOURCE : for file_path in glob . iglob ( os . path...
Copies a resource file and returns the source path for monitoring
230,686
def generate ( args ) : source_files = { args . presentation } template_info = Template ( args . template ) if args . css : presentation_dir = os . path . split ( args . presentation ) [ 0 ] target_path = os . path . relpath ( args . css , presentation_dir ) template_info . add_resource ( args . css , CSS_RESOURCE , ta...
Generates the presentation and returns a list of files used
230,687
def port ( self , port = None ) : if ( port is None ) or ( port == self . __port ) : return self . __port self . close ( ) if 0 < int ( port ) < 65536 : self . __port = int ( port ) return self . __port else : return None
Get or set TCP port
230,688
def unit_id ( self , unit_id = None ) : if unit_id is None : return self . __unit_id if 0 <= int ( unit_id ) < 256 : self . __unit_id = int ( unit_id ) return self . __unit_id else : return None
Get or set unit ID field
230,689
def timeout ( self , timeout = None ) : if timeout is None : return self . __timeout if 0 < float ( timeout ) < 3600 : self . __timeout = float ( timeout ) return self . __timeout else : return None
Get or set timeout field
230,690
def debug ( self , state = None ) : if state is None : return self . __debug self . __debug = bool ( state ) return self . __debug
Get or set debug mode
230,691
def auto_open ( self , state = None ) : if state is None : return self . __auto_open self . __auto_open = bool ( state ) return self . __auto_open
Get or set automatic TCP connect mode
230,692
def _can_read ( self ) : if self . __sock is None : return None if select . select ( [ self . __sock ] , [ ] , [ ] , self . __timeout ) [ 0 ] : return True else : self . __last_error = const . MB_TIMEOUT_ERR self . __debug_msg ( 'timeout error' ) self . close ( ) return None
Wait data available for socket read
230,693
def _send ( self , data ) : if self . __sock is None : self . __debug_msg ( 'call _send on close socket' ) return None data_l = len ( data ) try : send_l = self . __sock . send ( data ) except socket . error : send_l = None if ( send_l is None ) or ( send_l != data_l ) : self . __last_error = const . MB_SEND_ERR self ....
Send data over current socket
230,694
def _recv ( self , max_size ) : if not self . _can_read ( ) : self . close ( ) return None try : r_buffer = self . __sock . recv ( max_size ) except socket . error : r_buffer = None if not r_buffer : self . __last_error = const . MB_RECV_ERR self . __debug_msg ( '_recv error' ) self . close ( ) return None return r_buf...
Receive data over current socket
230,695
def _send_mbus ( self , frame ) : if self . __auto_open and not self . is_open ( ) : self . open ( ) bytes_send = self . _send ( frame ) if bytes_send : if self . __debug : self . _pretty_dump ( 'Tx' , frame ) return bytes_send else : return None
Send modbus frame
230,696
def _recv_mbus ( self ) : if self . __mode == const . MODBUS_TCP : rx_buffer = self . _recv_all ( 7 ) if not ( rx_buffer and len ( rx_buffer ) == 7 ) : self . __last_error = const . MB_RECV_ERR self . __debug_msg ( '_recv MBAP error' ) self . close ( ) return None rx_frame = rx_buffer ( rx_hd_tr_id , rx_hd_pr_id , rx_h...
Receive a modbus frame
230,697
def _wc_hard_wrap ( line , length ) : chars = [ ] chars_len = 0 for char in line : char_len = wcwidth ( char ) if chars_len + char_len > length : yield "" . join ( chars ) chars = [ ] chars_len = 0 chars . append ( char ) chars_len += char_len if chars : yield "" . join ( chars )
Wrap text to length characters breaking when target length is reached taking into account character width .
230,698
def wc_wrap ( text , length ) : line_words = [ ] line_len = 0 words = re . split ( r"\s+" , text . strip ( ) ) for word in words : word_len = wcswidth ( word ) if line_words and line_len + word_len > length : line = " " . join ( line_words ) if line_len <= length : yield line else : yield from _wc_hard_wrap ( line , le...
Wrap text to given length breaking on whitespace and taking into account character width .
230,699
def trunc ( text , length ) : if length < 1 : raise ValueError ( "length should be 1 or larger" ) text = text . strip ( ) text_length = wcswidth ( text ) if text_length <= length : return text chars_to_truncate = 0 trunc_length = 0 for char in reversed ( text ) : chars_to_truncate += 1 trunc_length += wcwidth ( char ) ...
Truncates text to given length taking into account wide characters .