idx
int64 0
63k
| question
stringlengths 61
4.03k
| target
stringlengths 6
1.23k
|
|---|---|---|
9,400
|
def _get_param ( self , section , key , config , default = None ) : if section in config and key in config [ section ] : return config [ section ] [ key ] if default is not None : return default else : raise MissingParameter ( section , key )
|
Get configuration parameter key from config
|
9,401
|
def _get_groups ( self , username ) : ret = { } for b in self . backends : ret [ b ] = self . backends [ b ] . get_groups ( username ) cherrypy . log . error ( msg = "user '" + username + "' groups: " + str ( ret ) , severity = logging . DEBUG , ) return ret
|
Get groups of a user
|
9,402
|
def _get_roles ( self , username ) : groups = self . _get_groups ( username ) user_roles = self . roles . get_roles ( groups ) cherrypy . log . error ( msg = "user '" + username + "' roles: " + str ( user_roles ) , severity = logging . DEBUG , ) return user_roles
|
Get roles of a user
|
9,403
|
def _is_admin ( self , username ) : roles = self . _get_roles ( username ) return self . roles . is_admin ( roles [ 'roles' ] )
|
Check if a user is an ldapcherry administrator
|
9,404
|
def _check_backends ( self ) : backends = self . backends_params . keys ( ) for b in self . roles . get_backends ( ) : if b not in backends : raise MissingBackend ( b , 'role' ) for b in self . attributes . get_backends ( ) : if b not in backends : raise MissingBackend ( b , 'attribute' )
|
Check that every backend in roles and attributes is declared in main configuration
|
9,405
|
def _init_backends ( self , config ) : self . backends_params = { } self . backends = { } self . backends_display_names = { } for entry in config [ 'backends' ] : backend , sep , param = entry . partition ( '.' ) value = config [ 'backends' ] [ entry ] if backend not in self . backends_params : self . backends_params [ backend ] = { } self . backends_params [ backend ] [ param ] = value for backend in self . backends_params : try : self . backends_display_names [ backend ] = self . backends_params [ backend ] [ 'display_name' ] except Exception as e : self . backends_display_names [ backend ] = backend self . backends_params [ backend ] [ 'display_name' ] = backend params = self . backends_params [ backend ] try : module = params [ 'module' ] except Exception as e : raise MissingParameter ( 'backends' , backend + '.module' ) try : bc = __import__ ( module , globals ( ) , locals ( ) , [ 'Backend' ] , 0 ) except Exception as e : self . _handle_exception ( e ) raise BackendModuleLoadingFail ( module ) try : attrslist = self . attributes . get_backend_attributes ( backend ) key = self . attributes . get_backend_key ( backend ) self . backends [ backend ] = bc . Backend ( params , cherrypy . log . error , backend , attrslist , key , ) except MissingParameter as e : raise except Exception as e : self . _handle_exception ( e ) raise BackendModuleInitFail ( module )
|
Init all backends
|
9,406
|
def _set_access_log ( self , config , level ) : access_handler = self . _get_param ( 'global' , 'log.access_handler' , config , 'syslog' , ) syslog_formatter = logging . Formatter ( "ldapcherry[%(process)d]: %(message)s" ) if access_handler == 'syslog' : cherrypy . log . access_log . handlers = [ ] handler = logging . handlers . SysLogHandler ( address = '/dev/log' , facility = 'user' , ) handler . setFormatter ( syslog_formatter ) cherrypy . log . access_log . addHandler ( handler ) elif access_handler == 'stdout' : cherrypy . log . access_log . handlers = [ ] handler = logging . StreamHandler ( sys . stdout ) formatter = logging . Formatter ( 'ldapcherry.access - %(levelname)s - %(message)s' ) handler . setFormatter ( formatter ) cherrypy . log . access_log . addHandler ( handler ) elif access_handler == 'file' : pass elif access_handler == 'none' : cherrypy . log . access_log . handlers = [ ] handler = logging . NullHandler ( ) cherrypy . log . access_log . addHandler ( handler ) cherrypy . log . access_log . setLevel ( level )
|
Configure access logs
|
9,407
|
def _set_error_log ( self , config , level , debug = False ) : error_handler = self . _get_param ( 'global' , 'log.error_handler' , config , 'syslog' ) syslog_formatter = logging . Formatter ( "ldapcherry[%(process)d]: %(message)s" , ) if error_handler == 'syslog' : cherrypy . log . error_log . handlers = [ ] cherrypy . log . error = syslog_error handler = logging . handlers . SysLogHandler ( address = '/dev/log' , facility = 'user' , ) handler . setFormatter ( syslog_formatter ) cherrypy . log . error_log . addHandler ( handler ) elif error_handler == 'stdout' : cherrypy . log . error_log . handlers = [ ] handler = logging . StreamHandler ( sys . stdout ) formatter = logging . Formatter ( 'ldapcherry.app - %(levelname)s - %(message)s' ) handler . setFormatter ( formatter ) cherrypy . log . error_log . addHandler ( handler ) elif error_handler == 'file' : pass elif error_handler == 'none' : cherrypy . log . error_log . handlers = [ ] handler = logging . NullHandler ( ) cherrypy . log . error_log . addHandler ( handler ) cherrypy . log . error_log . setLevel ( level ) if debug : cherrypy . log . error_log . handlers = [ ] handler = logging . StreamHandler ( sys . stderr ) handler . setLevel ( logging . DEBUG ) cherrypy . log . error_log . addHandler ( handler ) cherrypy . log . error_log . setLevel ( logging . DEBUG )
|
Configure error logs
|
9,408
|
def _auth ( self , user , password ) : if self . auth_mode == 'none' : return { 'connected' : True , 'isadmin' : True } elif self . auth_mode == 'and' : ret1 = True for b in self . backends : ret1 = self . backends [ b ] . auth ( user , password ) and ret1 elif self . auth_mode == 'or' : ret1 = False for b in self . backends : ret1 = self . backends [ b ] . auth ( user , password ) or ret1 elif self . auth_mode == 'custom' : ret1 = self . auth . auth ( user , password ) else : raise Exception ( ) if not ret1 : return { 'connected' : False , 'isadmin' : False } else : isadmin = self . _is_admin ( user ) return { 'connected' : True , 'isadmin' : isadmin }
|
authenticate a user
|
9,409
|
def _add_notification ( self , message ) : sess = cherrypy . session username = sess . get ( SESSION_KEY , None ) if username not in self . notifications : self . notifications [ username ] = [ ] self . notifications [ username ] . append ( message )
|
add a notification in the notification queue of a user
|
9,410
|
def _empty_notification ( self ) : sess = cherrypy . session username = sess . get ( SESSION_KEY , None ) if username in self . notifications : ret = self . notifications [ username ] else : ret = [ ] self . notifications [ username ] = [ ] return ret
|
empty and return list of message notification
|
9,411
|
def _merge_user_attrs ( self , attrs_backend , attrs_out , backend_name ) : for attr in attrs_backend : if attr in self . attributes . backend_attributes [ backend_name ] : attrid = self . attributes . backend_attributes [ backend_name ] [ attr ] if attrid not in attrs_out : attrs_out [ attrid ] = attrs_backend [ attr ]
|
merge attributes from one backend search to the attributes dict output
|
9,412
|
def index ( self ) : self . _check_auth ( must_admin = False ) is_admin = self . _check_admin ( ) sess = cherrypy . session user = sess . get ( SESSION_KEY , None ) if self . auth_mode == 'none' : user_attrs = None else : user_attrs = self . _get_user ( user ) attrs_list = self . attributes . get_search_attributes ( ) return self . temp [ 'index.tmpl' ] . render ( is_admin = is_admin , attrs_list = attrs_list , searchresult = user_attrs , notifications = self . _empty_notification ( ) , )
|
main page rendering
|
9,413
|
def adduser ( self , ** params ) : self . _check_auth ( must_admin = True ) is_admin = self . _check_admin ( ) if cherrypy . request . method . upper ( ) == 'POST' : params = self . _parse_params ( params ) self . _adduser ( params ) self . _add_notification ( "User added" ) graph = { } for r in self . roles . graph : s = list ( self . roles . graph [ r ] [ 'sub_roles' ] ) p = list ( self . roles . graph [ r ] [ 'parent_roles' ] ) graph [ r ] = { 'sub_roles' : s , 'parent_roles' : p } graph_js = json . dumps ( graph , separators = ( ',' , ':' ) ) display_names = { } for r in self . roles . flatten : display_names [ r ] = self . roles . flatten [ r ] [ 'display_name' ] roles_js = json . dumps ( display_names , separators = ( ',' , ':' ) ) try : form = self . temp [ 'form.tmpl' ] . render ( attributes = self . attributes . attributes , values = None , modify = False , autofill = True ) roles = self . temp [ 'roles.tmpl' ] . render ( roles = self . roles . flatten , graph = self . roles . graph , graph_js = graph_js , roles_js = roles_js , current_roles = None , ) return self . temp [ 'adduser.tmpl' ] . render ( form = form , roles = roles , is_admin = is_admin , custom_js = self . custom_js , notifications = self . _empty_notification ( ) , ) except NameError : raise TemplateRenderError ( exceptions . text_error_template ( ) . render ( ) )
|
add user page
|
9,414
|
def delete ( self , user ) : self . _check_auth ( must_admin = True ) is_admin = self . _check_admin ( ) try : referer = cherrypy . request . headers [ 'Referer' ] except Exception as e : referer = '/' self . _deleteuser ( user ) self . _add_notification ( 'User Deleted' ) raise cherrypy . HTTPRedirect ( referer )
|
remove user page
|
9,415
|
def modify ( self , user = None , ** params ) : self . _check_auth ( must_admin = True ) is_admin = self . _check_admin ( ) if cherrypy . request . method . upper ( ) == 'POST' : params = self . _parse_params ( params ) self . _modify ( params ) self . _add_notification ( "User modified" ) try : referer = cherrypy . request . headers [ 'Referer' ] except Exception as e : referer = '/' raise cherrypy . HTTPRedirect ( referer ) graph = { } for r in self . roles . graph : s = list ( self . roles . graph [ r ] [ 'sub_roles' ] ) p = list ( self . roles . graph [ r ] [ 'parent_roles' ] ) graph [ r ] = { 'sub_roles' : s , 'parent_roles' : p } graph_js = json . dumps ( graph , separators = ( ',' , ':' ) ) display_names = { } for r in self . roles . flatten : display_names [ r ] = self . roles . flatten [ r ] [ 'display_name' ] if user is None : cherrypy . response . status = 400 return self . temp [ 'error.tmpl' ] . render ( is_admin = is_admin , alert = 'warning' , message = "No user requested" ) user_attrs = self . _get_user ( user ) if user_attrs == { } : cherrypy . response . status = 400 return self . temp [ 'error.tmpl' ] . render ( is_admin = is_admin , alert = 'warning' , message = "User '" + user + "' does not exist" ) tmp = self . _get_roles ( user ) user_roles = tmp [ 'roles' ] standalone_groups = tmp [ 'unusedgroups' ] roles_js = json . dumps ( display_names , separators = ( ',' , ':' ) ) key = self . attributes . get_key ( ) try : form = self . temp [ 'form.tmpl' ] . render ( attributes = self . attributes . attributes , values = user_attrs , modify = True , keyattr = key , autofill = False ) roles = self . temp [ 'roles.tmpl' ] . render ( roles = self . roles . flatten , graph = self . roles . graph , graph_js = graph_js , roles_js = roles_js , current_roles = user_roles , ) glued_template = self . temp [ 'modify.tmpl' ] . render ( form = form , roles = roles , is_admin = is_admin , standalone_groups = standalone_groups , backends_display_names = self . backends_display_names , custom_js = self . custom_js , notifications = self . _empty_notification ( ) , ) except NameError : raise TemplateRenderError ( exceptions . text_error_template ( ) . render ( ) ) return glued_template
|
modify user page
|
9,416
|
def selfmodify ( self , ** params ) : self . _check_auth ( must_admin = False ) is_admin = self . _check_admin ( ) sess = cherrypy . session user = sess . get ( SESSION_KEY , None ) if self . auth_mode == 'none' : return self . temp [ 'error.tmpl' ] . render ( is_admin = is_admin , alert = 'warning' , message = "Not accessible with authentication disabled." ) if cherrypy . request . method . upper ( ) == 'POST' : params = self . _parse_params ( params ) self . _selfmodify ( params ) self . _add_notification ( "Self modification done" ) user_attrs = self . _get_user ( user ) try : if user_attrs == { } : return self . temp [ 'error.tmpl' ] . render ( is_admin = is_admin , alert = 'warning' , message = "User doesn't exist" ) form = self . temp [ 'form.tmpl' ] . render ( attributes = self . attributes . get_selfattributes ( ) , values = user_attrs , modify = True , autofill = False ) return self . temp [ 'selfmodify.tmpl' ] . render ( form = form , is_admin = is_admin , notifications = self . _empty_notification ( ) , ) except NameError : raise TemplateRenderError ( exceptions . text_error_template ( ) . render ( ) )
|
self modify user page
|
9,417
|
def render_to_response ( self , context , * args , ** kwargs ) : preview_outputs = [ ] file_outputs = [ ] bast_ctx = context added = set ( ) for output_group , output_files in context [ 'job_info' ] [ 'file_groups' ] . items ( ) : for output_file_content in output_files : if output_group : bast_ctx . update ( { 'job_info' : context [ 'job_info' ] , 'output_group' : output_group , 'output_file_content' : output_file_content , } ) preview = render_to_string ( 'wooey/preview/%s.html' % output_group , bast_ctx ) preview_outputs . append ( preview ) for file_info in context [ 'job_info' ] [ 'all_files' ] : if file_info and file_info . get ( 'name' ) not in added : row_ctx = dict ( file = file_info , ** context ) table_row = render_to_string ( 'wooey/jobs/results/table_row.html' , row_ctx ) file_outputs . append ( table_row ) added . add ( file_info . get ( 'name' ) ) return JsonResponse ( { 'status' : context [ 'job_info' ] [ 'status' ] . lower ( ) , 'command' : context [ 'job_info' ] [ 'job' ] . command , 'stdout' : context [ 'job_info' ] [ 'job' ] . get_stdout ( ) , 'stderr' : context [ 'job_info' ] [ 'job' ] . get_stderr ( ) , 'preview_outputs_html' : preview_outputs , 'file_outputs_html' : file_outputs , } )
|
Build dictionary of content
|
9,418
|
def cleanup_dead_jobs ( ) : from . models import WooeyJob inspect = celery_app . control . inspect ( ) active_tasks = { task [ 'id' ] for worker , tasks in six . iteritems ( inspect . active ( ) ) for task in tasks } active_jobs = WooeyJob . objects . filter ( status = WooeyJob . RUNNING ) to_disable = set ( ) for job in active_jobs : if job . celery_id not in active_tasks : to_disable . add ( job . pk ) WooeyJob . objects . filter ( pk__in = to_disable ) . update ( status = WooeyJob . FAILED )
|
This cleans up jobs that have been marked as ran but are not queue d in celery . It is meant to cleanup jobs that have been lost due to a server crash or some other reason a job is in limbo .
|
9,419
|
def normalize_query ( query_string , findterms = re . compile ( r'"([^"]+)"|(\S+)' ) . findall , normspace = re . compile ( r'\s{2,}' ) . sub ) : return [ normspace ( ' ' , ( t [ 0 ] or t [ 1 ] ) . strip ( ) ) for t in findterms ( query_string ) ]
|
Split the query string into individual keywords discarding spaces and grouping quoted words together .
|
9,420
|
def save ( self , * args , ** kwargs ) : super ( ModelDiffMixin , self ) . save ( * args , ** kwargs ) self . __initial = self . _dict
|
Saves model and set initial state .
|
9,421
|
def _load_text_assets ( self , text_image_file , text_file ) : text_pixels = self . load_image ( text_image_file , False ) with open ( text_file , 'r' ) as f : loaded_text = f . read ( ) self . _text_dict = { } for index , s in enumerate ( loaded_text ) : start = index * 40 end = start + 40 char = text_pixels [ start : end ] self . _text_dict [ s ] = char
|
Internal . Builds a character indexed dictionary of pixels used by the show_message function below
|
9,422
|
def _trim_whitespace ( self , char ) : psum = lambda x : sum ( sum ( x , [ ] ) ) if psum ( char ) > 0 : is_empty = True while is_empty : row = char [ 0 : 8 ] is_empty = psum ( row ) == 0 if is_empty : del char [ 0 : 8 ] is_empty = True while is_empty : row = char [ - 8 : ] is_empty = psum ( row ) == 0 if is_empty : del char [ - 8 : ] return char
|
Internal . Trims white space pixels from the front and back of loaded text characters
|
9,423
|
def _get_settings_file ( self , imu_settings_file ) : ini_file = '%s.ini' % imu_settings_file home_dir = pwd . getpwuid ( os . getuid ( ) ) [ 5 ] home_path = os . path . join ( home_dir , self . SETTINGS_HOME_PATH ) if not os . path . exists ( home_path ) : os . makedirs ( home_path ) home_file = os . path . join ( home_path , ini_file ) home_exists = os . path . isfile ( home_file ) system_file = os . path . join ( '/etc' , ini_file ) system_exists = os . path . isfile ( system_file ) if system_exists and not home_exists : shutil . copyfile ( system_file , home_file ) return RTIMU . Settings ( os . path . join ( home_path , imu_settings_file ) )
|
Internal . Logic to check for a system wide RTIMU ini file . This is copied to the home folder if one is not already found there .
|
9,424
|
def set_rotation ( self , r = 0 , redraw = True ) : if r in self . _pix_map . keys ( ) : if redraw : pixel_list = self . get_pixels ( ) self . _rotation = r if redraw : self . set_pixels ( pixel_list ) else : raise ValueError ( 'Rotation must be 0, 90, 180 or 270 degrees' )
|
Sets the LED matrix rotation for viewing adjust if the Pi is upside down or sideways . 0 is with the Pi HDMI port facing downwards
|
9,425
|
def flip_h ( self , redraw = True ) : pixel_list = self . get_pixels ( ) flipped = [ ] for i in range ( 8 ) : offset = i * 8 flipped . extend ( reversed ( pixel_list [ offset : offset + 8 ] ) ) if redraw : self . set_pixels ( flipped ) return flipped
|
Flip LED matrix horizontal
|
9,426
|
def load_image ( self , file_path , redraw = True ) : if not os . path . exists ( file_path ) : raise IOError ( '%s not found' % file_path ) img = Image . open ( file_path ) . convert ( 'RGB' ) pixel_list = list ( map ( list , img . getdata ( ) ) ) if redraw : self . set_pixels ( pixel_list ) return pixel_list
|
Accepts a path to an 8 x 8 image file and updates the LED matrix with the image
|
9,427
|
def _get_char_pixels ( self , s ) : if len ( s ) == 1 and s in self . _text_dict . keys ( ) : return list ( self . _text_dict [ s ] ) else : return list ( self . _text_dict [ '?' ] )
|
Internal . Safeguards the character indexed dictionary for the show_message function below
|
9,428
|
def show_message ( self , text_string , scroll_speed = .1 , text_colour = [ 255 , 255 , 255 ] , back_colour = [ 0 , 0 , 0 ] ) : previous_rotation = self . _rotation self . _rotation -= 90 if self . _rotation < 0 : self . _rotation = 270 dummy_colour = [ None , None , None ] string_padding = [ dummy_colour ] * 64 letter_padding = [ dummy_colour ] * 8 scroll_pixels = [ ] scroll_pixels . extend ( string_padding ) for s in text_string : scroll_pixels . extend ( self . _trim_whitespace ( self . _get_char_pixels ( s ) ) ) scroll_pixels . extend ( letter_padding ) scroll_pixels . extend ( string_padding ) coloured_pixels = [ text_colour if pixel == [ 255 , 255 , 255 ] else back_colour for pixel in scroll_pixels ] scroll_length = len ( coloured_pixels ) // 8 for i in range ( scroll_length - 8 ) : start = i * 8 end = start + 64 self . set_pixels ( coloured_pixels [ start : end ] ) time . sleep ( scroll_speed ) self . _rotation = previous_rotation
|
Scrolls a string of text across the LED matrix using the specified speed and colours
|
9,429
|
def show_letter ( self , s , text_colour = [ 255 , 255 , 255 ] , back_colour = [ 0 , 0 , 0 ] ) : if len ( s ) > 1 : raise ValueError ( 'Only one character may be passed into this method' ) previous_rotation = self . _rotation self . _rotation -= 90 if self . _rotation < 0 : self . _rotation = 270 dummy_colour = [ None , None , None ] pixel_list = [ dummy_colour ] * 8 pixel_list . extend ( self . _get_char_pixels ( s ) ) pixel_list . extend ( [ dummy_colour ] * 16 ) coloured_pixels = [ text_colour if pixel == [ 255 , 255 , 255 ] else back_colour for pixel in pixel_list ] self . set_pixels ( coloured_pixels ) self . _rotation = previous_rotation
|
Displays a single text character on the LED matrix using the specified colours
|
9,430
|
def gamma_reset ( self ) : with open ( self . _fb_device ) as f : fcntl . ioctl ( f , self . SENSE_HAT_FB_FBIORESET_GAMMA , self . SENSE_HAT_FB_GAMMA_DEFAULT )
|
Resets the LED matrix gamma correction to default
|
9,431
|
def _init_humidity ( self ) : if not self . _humidity_init : self . _humidity_init = self . _humidity . humidityInit ( ) if not self . _humidity_init : raise OSError ( 'Humidity Init Failed' )
|
Internal . Initialises the humidity sensor via RTIMU
|
9,432
|
def _init_pressure ( self ) : if not self . _pressure_init : self . _pressure_init = self . _pressure . pressureInit ( ) if not self . _pressure_init : raise OSError ( 'Pressure Init Failed' )
|
Internal . Initialises the pressure sensor via RTIMU
|
9,433
|
def get_humidity ( self ) : self . _init_humidity ( ) humidity = 0 data = self . _humidity . humidityRead ( ) if ( data [ 0 ] ) : humidity = data [ 1 ] return humidity
|
Returns the percentage of relative humidity
|
9,434
|
def get_temperature_from_humidity ( self ) : self . _init_humidity ( ) temp = 0 data = self . _humidity . humidityRead ( ) if ( data [ 2 ] ) : temp = data [ 3 ] return temp
|
Returns the temperature in Celsius from the humidity sensor
|
9,435
|
def get_temperature_from_pressure ( self ) : self . _init_pressure ( ) temp = 0 data = self . _pressure . pressureRead ( ) if ( data [ 2 ] ) : temp = data [ 3 ] return temp
|
Returns the temperature in Celsius from the pressure sensor
|
9,436
|
def get_pressure ( self ) : self . _init_pressure ( ) pressure = 0 data = self . _pressure . pressureRead ( ) if ( data [ 0 ] ) : pressure = data [ 1 ] return pressure
|
Returns the pressure in Millibars
|
9,437
|
def _init_imu ( self ) : if not self . _imu_init : self . _imu_init = self . _imu . IMUInit ( ) if self . _imu_init : self . _imu_poll_interval = self . _imu . IMUGetPollInterval ( ) * 0.001 self . set_imu_config ( True , True , True ) else : raise OSError ( 'IMU Init Failed' )
|
Internal . Initialises the IMU sensor via RTIMU
|
9,438
|
def _read_imu ( self ) : self . _init_imu ( ) attempts = 0 success = False while not success and attempts < 3 : success = self . _imu . IMURead ( ) attempts += 1 time . sleep ( self . _imu_poll_interval ) return success
|
Internal . Tries to read the IMU sensor three times before giving up
|
9,439
|
def _get_raw_data ( self , is_valid_key , data_key ) : result = None if self . _read_imu ( ) : data = self . _imu . getIMUData ( ) if data [ is_valid_key ] : raw = data [ data_key ] result = { 'x' : raw [ 0 ] , 'y' : raw [ 1 ] , 'z' : raw [ 2 ] } return result
|
Internal . Returns the specified raw data from the IMU when valid
|
9,440
|
def get_orientation_radians ( self ) : raw = self . _get_raw_data ( 'fusionPoseValid' , 'fusionPose' ) if raw is not None : raw [ 'roll' ] = raw . pop ( 'x' ) raw [ 'pitch' ] = raw . pop ( 'y' ) raw [ 'yaw' ] = raw . pop ( 'z' ) self . _last_orientation = raw return deepcopy ( self . _last_orientation )
|
Returns a dictionary object to represent the current orientation in radians using the aircraft principal axes of pitch roll and yaw
|
9,441
|
def get_orientation_degrees ( self ) : orientation = self . get_orientation_radians ( ) for key , val in orientation . items ( ) : deg = math . degrees ( val ) orientation [ key ] = deg + 360 if deg < 0 else deg return orientation
|
Returns a dictionary object to represent the current orientation in degrees 0 to 360 using the aircraft principal axes of pitch roll and yaw
|
9,442
|
def get_compass ( self ) : self . set_imu_config ( True , False , False ) orientation = self . get_orientation_degrees ( ) if type ( orientation ) is dict and 'yaw' in orientation . keys ( ) : return orientation [ 'yaw' ] else : return None
|
Gets the direction of North from the magnetometer in degrees
|
9,443
|
def get_gyroscope_raw ( self ) : raw = self . _get_raw_data ( 'gyroValid' , 'gyro' ) if raw is not None : self . _last_gyro_raw = raw return deepcopy ( self . _last_gyro_raw )
|
Gyroscope x y z raw data in radians per second
|
9,444
|
def get_accelerometer_raw ( self ) : raw = self . _get_raw_data ( 'accelValid' , 'accel' ) if raw is not None : self . _last_accel_raw = raw return deepcopy ( self . _last_accel_raw )
|
Accelerometer x y z raw data in Gs
|
9,445
|
def _stick_device ( self ) : for evdev in glob . glob ( '/sys/class/input/event*' ) : try : with io . open ( os . path . join ( evdev , 'device' , 'name' ) , 'r' ) as f : if f . read ( ) . strip ( ) == self . SENSE_HAT_EVDEV_NAME : return os . path . join ( '/dev' , 'input' , os . path . basename ( evdev ) ) except IOError as e : if e . errno != errno . ENOENT : raise raise RuntimeError ( 'unable to locate SenseHAT joystick device' )
|
Discovers the filename of the evdev device that represents the Sense HAT s joystick .
|
9,446
|
def _read ( self ) : event = self . _stick_file . read ( self . EVENT_SIZE ) ( tv_sec , tv_usec , type , code , value ) = struct . unpack ( self . EVENT_FORMAT , event ) if type == self . EV_KEY : return InputEvent ( timestamp = tv_sec + ( tv_usec / 1000000 ) , direction = { self . KEY_UP : DIRECTION_UP , self . KEY_DOWN : DIRECTION_DOWN , self . KEY_LEFT : DIRECTION_LEFT , self . KEY_RIGHT : DIRECTION_RIGHT , self . KEY_ENTER : DIRECTION_MIDDLE , } [ code ] , action = { self . STATE_PRESS : ACTION_PRESSED , self . STATE_RELEASE : ACTION_RELEASED , self . STATE_HOLD : ACTION_HELD , } [ value ] ) else : return None
|
Reads a single event from the joystick blocking until one is available . Returns None if a non - key event was read or an InputEvent tuple describing the event otherwise .
|
9,447
|
def wait_for_event ( self , emptybuffer = False ) : if emptybuffer : while self . _wait ( 0 ) : self . _read ( ) while self . _wait ( ) : event = self . _read ( ) if event : return event
|
Waits until a joystick event becomes available . Returns the event as an InputEvent tuple .
|
9,448
|
def get_events ( self ) : result = [ ] while self . _wait ( 0 ) : event = self . _read ( ) if event : result . append ( event ) return result
|
Returns a list of all joystick events that have occurred since the last call to get_events . The list contains events in the order that they occurred . If no events have occurred in the intervening time the result is an empty list .
|
9,449
|
def signal_handler ( sig , frame ) : for client in connected_clients [ : ] : if client . is_asyncio_based ( ) : client . start_background_task ( client . disconnect , abort = True ) else : client . disconnect ( abort = True ) return original_signal_handler ( sig , frame )
|
SIGINT handler .
|
9,450
|
def start_background_task ( self , target , * args , ** kwargs ) : th = threading . Thread ( target = target , args = args , kwargs = kwargs ) th . start ( ) return th
|
Start a background task .
|
9,451
|
def _get_engineio_url ( self , url , engineio_path , transport ) : engineio_path = engineio_path . strip ( '/' ) parsed_url = urllib . parse . urlparse ( url ) if transport == 'polling' : scheme = 'http' elif transport == 'websocket' : scheme = 'ws' else : raise ValueError ( 'invalid transport' ) if parsed_url . scheme in [ 'https' , 'wss' ] : scheme += 's' return ( '{scheme}://{netloc}/{path}/?{query}' '{sep}transport={transport}&EIO=3' ) . format ( scheme = scheme , netloc = parsed_url . netloc , path = engineio_path , query = parsed_url . query , sep = '&' if parsed_url . query else '' , transport = transport )
|
Generate the Engine . IO connection URL .
|
9,452
|
def _ping_loop ( self ) : self . pong_received = True self . ping_loop_event . clear ( ) while self . state == 'connected' : if not self . pong_received : self . logger . info ( 'PONG response has not been received, aborting' ) if self . ws : self . ws . close ( ) self . queue . put ( None ) break self . pong_received = False self . _send_packet ( packet . Packet ( packet . PING ) ) self . ping_loop_event . wait ( timeout = self . ping_interval ) self . logger . info ( 'Exiting ping task' )
|
This background task sends a PING to the server at the requested interval .
|
9,453
|
def _read_loop_polling ( self ) : while self . state == 'connected' : self . logger . info ( 'Sending polling GET request to ' + self . base_url ) r = self . _send_request ( 'GET' , self . base_url + self . _get_url_timestamp ( ) ) if r is None : self . logger . warning ( 'Connection refused by the server, aborting' ) self . queue . put ( None ) break if r . status_code != 200 : self . logger . warning ( 'Unexpected status code %s in server ' 'response, aborting' , r . status_code ) self . queue . put ( None ) break try : p = payload . Payload ( encoded_payload = r . content ) except ValueError : self . logger . warning ( 'Unexpected packet from server, aborting' ) self . queue . put ( None ) break for pkt in p . packets : self . _receive_packet ( pkt ) self . logger . info ( 'Waiting for write loop task to end' ) self . write_loop_task . join ( ) self . logger . info ( 'Waiting for ping loop task to end' ) self . ping_loop_event . set ( ) self . ping_loop_task . join ( ) if self . state == 'connected' : self . _trigger_event ( 'disconnect' , run_async = False ) try : connected_clients . remove ( self ) except ValueError : pass self . _reset ( ) self . logger . info ( 'Exiting read loop task' )
|
Read packets by polling the Engine . IO server .
|
9,454
|
def _read_loop_websocket ( self ) : while self . state == 'connected' : p = None try : p = self . ws . recv ( ) except websocket . WebSocketConnectionClosedException : self . logger . warning ( 'WebSocket connection was closed, aborting' ) self . queue . put ( None ) break except Exception as e : self . logger . info ( 'Unexpected error "%s", aborting' , str ( e ) ) self . queue . put ( None ) break if isinstance ( p , six . text_type ) : p = p . encode ( 'utf-8' ) pkt = packet . Packet ( encoded_packet = p ) self . _receive_packet ( pkt ) self . logger . info ( 'Waiting for write loop task to end' ) self . write_loop_task . join ( ) self . logger . info ( 'Waiting for ping loop task to end' ) self . ping_loop_event . set ( ) self . ping_loop_task . join ( ) if self . state == 'connected' : self . _trigger_event ( 'disconnect' , run_async = False ) try : connected_clients . remove ( self ) except ValueError : pass self . _reset ( ) self . logger . info ( 'Exiting read loop task' )
|
Read packets from the Engine . IO WebSocket connection .
|
9,455
|
def _upgrades ( self , sid , transport ) : if not self . allow_upgrades or self . _get_socket ( sid ) . upgraded or self . _async [ 'websocket' ] is None or transport == 'websocket' : return [ ] return [ 'websocket' ]
|
Return the list of possible upgrades for a client connection .
|
9,456
|
def _get_socket ( self , sid ) : try : s = self . sockets [ sid ] except KeyError : raise KeyError ( 'Session not found' ) if s . closed : del self . sockets [ sid ] raise KeyError ( 'Session is disconnected' ) return s
|
Return the socket object for a given session .
|
9,457
|
def _ok ( self , packets = None , headers = None , b64 = False ) : if packets is not None : if headers is None : headers = [ ] if b64 : headers += [ ( 'Content-Type' , 'text/plain; charset=UTF-8' ) ] else : headers += [ ( 'Content-Type' , 'application/octet-stream' ) ] return { 'status' : '200 OK' , 'headers' : headers , 'response' : payload . Payload ( packets = packets ) . encode ( b64 ) } else : return { 'status' : '200 OK' , 'headers' : [ ( 'Content-Type' , 'text/plain' ) ] , 'response' : b'OK' }
|
Generate a successful HTTP response .
|
9,458
|
def _cors_headers ( self , environ ) : if isinstance ( self . cors_allowed_origins , six . string_types ) : if self . cors_allowed_origins == '*' : allowed_origins = None else : allowed_origins = [ self . cors_allowed_origins ] else : allowed_origins = self . cors_allowed_origins if allowed_origins is not None and environ . get ( 'HTTP_ORIGIN' , '' ) not in allowed_origins : return [ ] if 'HTTP_ORIGIN' in environ : headers = [ ( 'Access-Control-Allow-Origin' , environ [ 'HTTP_ORIGIN' ] ) ] else : headers = [ ( 'Access-Control-Allow-Origin' , '*' ) ] if environ [ 'REQUEST_METHOD' ] == 'OPTIONS' : headers += [ ( 'Access-Control-Allow-Methods' , 'OPTIONS, GET, POST' ) ] if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in environ : headers += [ ( 'Access-Control-Allow-Headers' , environ [ 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' ] ) ] if self . cors_credentials : headers += [ ( 'Access-Control-Allow-Credentials' , 'true' ) ] return headers
|
Return the cross - origin - resource - sharing headers .
|
9,459
|
def _gzip ( self , response ) : bytesio = six . BytesIO ( ) with gzip . GzipFile ( fileobj = bytesio , mode = 'w' ) as gz : gz . write ( response ) return bytesio . getvalue ( )
|
Apply gzip compression to a response .
|
9,460
|
def close ( self ) : uwsgi . disconnect ( ) if self . _req_ctx is None : self . _select_greenlet . kill ( ) self . _event . set ( )
|
Disconnects uWSGI from the client .
|
9,461
|
def _send ( self , msg ) : if isinstance ( msg , six . binary_type ) : method = uwsgi . websocket_send_binary else : method = uwsgi . websocket_send if self . _req_ctx is not None : method ( msg , request_context = self . _req_ctx ) else : method ( msg )
|
Transmits message either in binary or UTF - 8 text mode depending on its type .
|
9,462
|
def _decode_received ( self , msg ) : if not isinstance ( msg , six . binary_type ) : return msg type = six . byte2int ( msg [ 0 : 1 ] ) if type >= 48 : return msg . decode ( 'utf-8' ) return msg
|
Returns either bytes or str depending on message type .
|
9,463
|
def send ( self , msg ) : if self . _req_ctx is not None : self . _send ( msg ) else : self . _send_queue . put ( msg ) self . _event . set ( )
|
Queues a message for sending . Real transmission is done in wait method . Sends directly if uWSGI version is new enough .
|
9,464
|
def attach ( self , app , engineio_path = 'engine.io' ) : engineio_path = engineio_path . strip ( '/' ) self . _async [ 'create_route' ] ( app , self , '/{}/' . format ( engineio_path ) )
|
Attach the Engine . IO server to an application .
|
9,465
|
def handle_get_request ( self , environ , start_response ) : connections = [ s . strip ( ) for s in environ . get ( 'HTTP_CONNECTION' , '' ) . lower ( ) . split ( ',' ) ] transport = environ . get ( 'HTTP_UPGRADE' , '' ) . lower ( ) if 'upgrade' in connections and transport in self . upgrade_protocols : self . server . logger . info ( '%s: Received request to upgrade to %s' , self . sid , transport ) return getattr ( self , '_upgrade_' + transport ) ( environ , start_response ) try : packets = self . poll ( ) except exceptions . QueueEmpty : exc = sys . exc_info ( ) self . close ( wait = False ) six . reraise ( * exc ) return packets
|
Handle a long - polling GET request from the client .
|
9,466
|
def close ( self , wait = True , abort = False ) : if not self . closed and not self . closing : self . closing = True self . server . _trigger_event ( 'disconnect' , self . sid , run_async = False ) if not abort : self . send ( packet . Packet ( packet . CLOSE ) ) self . closed = True self . queue . put ( None ) if wait : self . queue . join ( )
|
Close the socket connection .
|
9,467
|
async def connect ( self , url , headers = { } , transports = None , engineio_path = 'engine.io' ) : if self . state != 'disconnected' : raise ValueError ( 'Client is not in a disconnected state' ) valid_transports = [ 'polling' , 'websocket' ] if transports is not None : if isinstance ( transports , six . text_type ) : transports = [ transports ] transports = [ transport for transport in transports if transport in valid_transports ] if not transports : raise ValueError ( 'No valid transports provided' ) self . transports = transports or valid_transports self . queue = self . create_queue ( ) return await getattr ( self , '_connect_' + self . transports [ 0 ] ) ( url , headers , engineio_path )
|
Connect to an Engine . IO server .
|
9,468
|
async def _connect_polling ( self , url , headers , engineio_path ) : if aiohttp is None : self . logger . error ( 'aiohttp not installed -- cannot make HTTP ' 'requests!' ) return self . base_url = self . _get_engineio_url ( url , engineio_path , 'polling' ) self . logger . info ( 'Attempting polling connection to ' + self . base_url ) r = await self . _send_request ( 'GET' , self . base_url + self . _get_url_timestamp ( ) , headers = headers ) if r is None : self . _reset ( ) raise exceptions . ConnectionError ( 'Connection refused by the server' ) if r . status != 200 : raise exceptions . ConnectionError ( 'Unexpected status code {} in server response' . format ( r . status ) ) try : p = payload . Payload ( encoded_payload = await r . read ( ) ) except ValueError : six . raise_from ( exceptions . ConnectionError ( 'Unexpected response from server' ) , None ) open_packet = p . packets [ 0 ] if open_packet . packet_type != packet . OPEN : raise exceptions . ConnectionError ( 'OPEN packet not returned by server' ) self . logger . info ( 'Polling connection accepted with ' + str ( open_packet . data ) ) self . sid = open_packet . data [ 'sid' ] self . upgrades = open_packet . data [ 'upgrades' ] self . ping_interval = open_packet . data [ 'pingInterval' ] / 1000.0 self . ping_timeout = open_packet . data [ 'pingTimeout' ] / 1000.0 self . current_transport = 'polling' self . base_url += '&sid=' + self . sid self . state = 'connected' client . connected_clients . append ( self ) await self . _trigger_event ( 'connect' , run_async = False ) for pkt in p . packets [ 1 : ] : await self . _receive_packet ( pkt ) if 'websocket' in self . upgrades and 'websocket' in self . transports : if await self . _connect_websocket ( url , headers , engineio_path ) : return self . ping_loop_task = self . start_background_task ( self . _ping_loop ) self . write_loop_task = self . start_background_task ( self . _write_loop ) self . read_loop_task = self . start_background_task ( self . _read_loop_polling )
|
Establish a long - polling connection to the Engine . IO server .
|
9,469
|
async def _receive_packet ( self , pkt ) : packet_name = packet . packet_names [ pkt . packet_type ] if pkt . packet_type < len ( packet . packet_names ) else 'UNKNOWN' self . logger . info ( 'Received packet %s data %s' , packet_name , pkt . data if not isinstance ( pkt . data , bytes ) else '<binary>' ) if pkt . packet_type == packet . MESSAGE : await self . _trigger_event ( 'message' , pkt . data , run_async = True ) elif pkt . packet_type == packet . PONG : self . pong_received = True elif pkt . packet_type == packet . NOOP : pass else : self . logger . error ( 'Received unexpected packet of type %s' , pkt . packet_type )
|
Handle incoming packets from the server .
|
9,470
|
async def _send_packet ( self , pkt ) : if self . state != 'connected' : return await self . queue . put ( pkt ) self . logger . info ( 'Sending packet %s data %s' , packet . packet_names [ pkt . packet_type ] , pkt . data if not isinstance ( pkt . data , bytes ) else '<binary>' )
|
Queue a packet to be sent to the server .
|
9,471
|
def encode ( self , b64 = False ) : encoded_payload = b'' for pkt in self . packets : encoded_packet = pkt . encode ( b64 = b64 ) packet_len = len ( encoded_packet ) if b64 : encoded_payload += str ( packet_len ) . encode ( 'utf-8' ) + b':' + encoded_packet else : binary_len = b'' while packet_len != 0 : binary_len = six . int2byte ( packet_len % 10 ) + binary_len packet_len = int ( packet_len / 10 ) if not pkt . binary : encoded_payload += b'\0' else : encoded_payload += b'\1' encoded_payload += binary_len + b'\xff' + encoded_packet return encoded_payload
|
Encode the payload for transmission .
|
9,472
|
def decode ( self , encoded_payload ) : self . packets = [ ] while encoded_payload : if six . byte2int ( encoded_payload [ 0 : 1 ] ) <= 1 : packet_len = 0 i = 1 while six . byte2int ( encoded_payload [ i : i + 1 ] ) != 255 : packet_len = packet_len * 10 + six . byte2int ( encoded_payload [ i : i + 1 ] ) i += 1 self . packets . append ( packet . Packet ( encoded_packet = encoded_payload [ i + 1 : i + 1 + packet_len ] ) ) else : i = encoded_payload . find ( b':' ) if i == - 1 : raise ValueError ( 'invalid payload' ) packet_len = int ( encoded_payload [ 0 : i ] ) pkt = encoded_payload . decode ( 'utf-8' , errors = 'ignore' ) [ i + 1 : i + 1 + packet_len ] . encode ( 'utf-8' ) self . packets . append ( packet . Packet ( encoded_packet = pkt ) ) packet_len = len ( pkt ) encoded_payload = encoded_payload [ i + 1 + packet_len : ]
|
Decode a transmitted payload .
|
9,473
|
async def receive ( self , pkt ) : self . server . logger . info ( '%s: Received packet %s data %s' , self . sid , packet . packet_names [ pkt . packet_type ] , pkt . data if not isinstance ( pkt . data , bytes ) else '<binary>' ) if pkt . packet_type == packet . PING : self . last_ping = time . time ( ) await self . send ( packet . Packet ( packet . PONG , pkt . data ) ) elif pkt . packet_type == packet . MESSAGE : await self . server . _trigger_event ( 'message' , self . sid , pkt . data , run_async = self . server . async_handlers ) elif pkt . packet_type == packet . UPGRADE : await self . send ( packet . Packet ( packet . NOOP ) ) elif pkt . packet_type == packet . CLOSE : await self . close ( wait = False , abort = True ) else : raise exceptions . UnknownPacketError ( )
|
Receive packet from the client .
|
9,474
|
async def check_ping_timeout ( self ) : if self . closed : raise exceptions . SocketIsClosedError ( ) if time . time ( ) - self . last_ping > self . server . ping_interval + 5 : self . server . logger . info ( '%s: Client is gone, closing socket' , self . sid ) await self . close ( wait = False , abort = False ) return False return True
|
Make sure the client is still sending pings .
|
9,475
|
async def send ( self , pkt ) : if not await self . check_ping_timeout ( ) : return if self . upgrading : self . packet_backlog . append ( pkt ) else : await self . queue . put ( pkt ) self . server . logger . info ( '%s: Sending packet %s data %s' , self . sid , packet . packet_names [ pkt . packet_type ] , pkt . data if not isinstance ( pkt . data , bytes ) else '<binary>' )
|
Send a packet to the client .
|
9,476
|
async def handle_post_request ( self , environ ) : length = int ( environ . get ( 'CONTENT_LENGTH' , '0' ) ) if length > self . server . max_http_buffer_size : raise exceptions . ContentTooLongError ( ) else : body = await environ [ 'wsgi.input' ] . read ( length ) p = payload . Payload ( encoded_payload = body ) for pkt in p . packets : await self . receive ( pkt )
|
Handle a long - polling POST request from the client .
|
9,477
|
async def _upgrade_websocket ( self , environ ) : if self . upgraded : raise IOError ( 'Socket has been upgraded already' ) if self . server . _async [ 'websocket' ] is None : return self . server . _bad_request ( ) ws = self . server . _async [ 'websocket' ] ( self . _websocket_handler ) return await ws ( environ )
|
Upgrade the connection from polling to websocket .
|
9,478
|
def decodeRPCErrorMsg ( e ) : found = re . search ( ( "(10 assert_exception: Assert Exception\n|" "3030000 tx_missing_posting_auth)" ".*: (.*)\n" ) , str ( e ) , flags = re . M , ) if found : return found . group ( 2 ) . strip ( ) else : return str ( e )
|
Helper function to decode the raised Exception and give it a python Exception class
|
9,479
|
def transfer ( self , to , amount , asset , memo = "" , account = None , ** kwargs ) : from . memo import Memo if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , blockchain_instance = self ) amount = Amount ( amount , asset , blockchain_instance = self ) to = Account ( to , blockchain_instance = self ) memoObj = Memo ( from_account = account , to_account = to , blockchain_instance = self ) op = operations . Transfer ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "from" : account [ "id" ] , "to" : to [ "id" ] , "amount" : { "amount" : int ( amount ) , "asset_id" : amount . asset [ "id" ] } , "memo" : memoObj . encrypt ( memo ) , "prefix" : self . prefix , } ) return self . finalizeOp ( op , account , "active" , ** kwargs )
|
Transfer an asset to another account .
|
9,480
|
def upgrade_account ( self , account = None , ** kwargs ) : if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , blockchain_instance = self ) op = operations . Account_upgrade ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "account_to_upgrade" : account [ "id" ] , "upgrade_to_lifetime_member" : True , "prefix" : self . prefix , } ) return self . finalizeOp ( op , account [ "name" ] , "active" , ** kwargs )
|
Upgrade an account to Lifetime membership
|
9,481
|
def allow ( self , foreign , weight = None , permission = "active" , account = None , threshold = None , ** kwargs ) : from copy import deepcopy if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) if permission not in [ "owner" , "active" ] : raise ValueError ( "Permission needs to be either 'owner', or 'active" ) account = Account ( account , blockchain_instance = self ) if not weight : weight = account [ permission ] [ "weight_threshold" ] authority = deepcopy ( account [ permission ] ) try : pubkey = PublicKey ( foreign , prefix = self . prefix ) authority [ "key_auths" ] . append ( [ str ( pubkey ) , weight ] ) except Exception : try : foreign_account = Account ( foreign , blockchain_instance = self ) authority [ "account_auths" ] . append ( [ foreign_account [ "id" ] , weight ] ) except Exception : raise ValueError ( "Unknown foreign account or invalid public key" ) if threshold : authority [ "weight_threshold" ] = threshold self . _test_weights_treshold ( authority ) op = operations . Account_update ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "account" : account [ "id" ] , permission : authority , "extensions" : { } , "prefix" : self . prefix , } ) if permission == "owner" : return self . finalizeOp ( op , account [ "name" ] , "owner" , ** kwargs ) else : return self . finalizeOp ( op , account [ "name" ] , "active" , ** kwargs )
|
Give additional access to an account by some other public key or account .
|
9,482
|
def update_memo_key ( self , key , account = None , ** kwargs ) : if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) PublicKey ( key , prefix = self . prefix ) account = Account ( account , blockchain_instance = self ) account [ "options" ] [ "memo_key" ] = key op = operations . Account_update ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "account" : account [ "id" ] , "new_options" : account [ "options" ] , "extensions" : { } , "prefix" : self . prefix , } ) return self . finalizeOp ( op , account [ "name" ] , "active" , ** kwargs )
|
Update an account s memo public key
|
9,483
|
def approveworker ( self , workers , account = None , ** kwargs ) : if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , blockchain_instance = self ) options = account [ "options" ] if not isinstance ( workers , ( list , set , tuple ) ) : workers = { workers } for worker in workers : worker = Worker ( worker , blockchain_instance = self ) options [ "votes" ] . append ( worker [ "vote_for" ] ) options [ "votes" ] = list ( set ( options [ "votes" ] ) ) options [ "voting_account" ] = "1.2.5" op = operations . Account_update ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "account" : account [ "id" ] , "new_options" : options , "extensions" : { } , "prefix" : self . prefix , } ) return self . finalizeOp ( op , account [ "name" ] , "active" , ** kwargs )
|
Approve a worker
|
9,484
|
def set_proxy ( self , proxy_account , account = None , ** kwargs ) : if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , blockchain_instance = self ) proxy = Account ( proxy_account , blockchain_instance = self ) options = account [ "options" ] options [ "voting_account" ] = proxy [ "id" ] op = operations . Account_update ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "account" : account [ "id" ] , "new_options" : options , "extensions" : { } , "prefix" : self . prefix , } ) return self . finalizeOp ( op , account [ "name" ] , "active" , ** kwargs )
|
Set a specific proxy for account
|
9,485
|
def cancel ( self , orderNumbers , account = None , ** kwargs ) : if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , full = False , blockchain_instance = self ) if not isinstance ( orderNumbers , ( list , set , tuple ) ) : orderNumbers = { orderNumbers } op = [ ] for order in orderNumbers : op . append ( operations . Limit_order_cancel ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "fee_paying_account" : account [ "id" ] , "order" : order , "extensions" : [ ] , "prefix" : self . prefix , } ) ) return self . finalizeOp ( op , account [ "name" ] , "active" , ** kwargs )
|
Cancels an order you have placed in a given market . Requires only the orderNumbers . An order number takes the form 1 . 7 . xxx .
|
9,486
|
def vesting_balance_withdraw ( self , vesting_id , amount = None , account = None , ** kwargs ) : if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , blockchain_instance = self ) if not amount : obj = Vesting ( vesting_id , blockchain_instance = self ) amount = obj . claimable op = operations . Vesting_balance_withdraw ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "vesting_balance" : vesting_id , "owner" : account [ "id" ] , "amount" : { "amount" : int ( amount ) , "asset_id" : amount [ "asset" ] [ "id" ] } , "prefix" : self . prefix , } ) return self . finalizeOp ( op , account [ "name" ] , "active" )
|
Withdraw vesting balance
|
9,487
|
def publish_price_feed ( self , symbol , settlement_price , cer = None , mssr = 110 , mcr = 200 , account = None ) : assert mcr > 100 assert mssr > 100 assert isinstance ( settlement_price , Price ) , "settlement_price needs to be instance of `bitshares.price.Price`!" assert cer is None or isinstance ( cer , Price ) , "cer needs to be instance of `bitshares.price.Price`!" if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , blockchain_instance = self ) asset = Asset ( symbol , blockchain_instance = self , full = True ) backing_asset = asset [ "bitasset_data" ] [ "options" ] [ "short_backing_asset" ] assert ( asset [ "id" ] == settlement_price [ "base" ] [ "asset" ] [ "id" ] or asset [ "id" ] == settlement_price [ "quote" ] [ "asset" ] [ "id" ] ) , "Price needs to contain the asset of the symbol you'd like to produce a feed for!" assert asset . is_bitasset , "Symbol needs to be a bitasset!" assert ( settlement_price [ "base" ] [ "asset" ] [ "id" ] == backing_asset or settlement_price [ "quote" ] [ "asset" ] [ "id" ] == backing_asset ) , "The Price needs to be relative to the backing collateral!" settlement_price = settlement_price . as_base ( symbol ) if cer : cer = cer . as_base ( symbol ) if cer [ "quote" ] [ "asset" ] [ "id" ] != "1.3.0" : raise ValueError ( "CER must be defined against core asset '1.3.0'" ) else : if settlement_price [ "quote" ] [ "asset" ] [ "id" ] != "1.3.0" : raise ValueError ( "CER must be manually provided because it relates to core asset '1.3.0'" ) cer = settlement_price . as_quote ( symbol ) * 0.95 op = operations . Asset_publish_feed ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "publisher" : account [ "id" ] , "asset_id" : asset [ "id" ] , "feed" : { "settlement_price" : settlement_price . as_base ( symbol ) . json ( ) , "core_exchange_rate" : cer . as_base ( symbol ) . json ( ) , "maximum_short_squeeze_ratio" : int ( mssr * 10 ) , "maintenance_collateral_ratio" : int ( mcr * 10 ) , } , "prefix" : self . prefix , } ) return self . finalizeOp ( op , account [ "name" ] , "active" )
|
Publish a price feed for a market - pegged asset
|
9,488
|
def update_witness ( self , witness_identifier , url = None , key = None , ** kwargs ) : witness = Witness ( witness_identifier ) account = witness . account op = operations . Witness_update ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "prefix" : self . prefix , "witness" : witness [ "id" ] , "witness_account" : account [ "id" ] , "new_url" : url , "new_signing_key" : key , } ) return self . finalizeOp ( op , account [ "name" ] , "active" , ** kwargs )
|
Upgrade a witness account
|
9,489
|
def create_worker ( self , name , daily_pay , end , url = "" , begin = None , payment_type = "vesting" , pay_vesting_period_days = 0 , account = None , ** kwargs ) : from bitsharesbase . transactions import timeformat assert isinstance ( daily_pay , Amount ) assert daily_pay [ "asset" ] [ "id" ] == "1.3.0" if not begin : begin = datetime . utcnow ( ) + timedelta ( seconds = 30 ) if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , blockchain_instance = self ) if payment_type == "refund" : initializer = [ 0 , { } ] elif payment_type == "vesting" : initializer = [ 1 , { "pay_vesting_period_days" : pay_vesting_period_days } ] elif payment_type == "burn" : initializer = [ 2 , { } ] else : raise ValueError ( 'payment_type not in ["burn", "refund", "vesting"]' ) op = operations . Worker_create ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "owner" : account [ "id" ] , "work_begin_date" : begin . strftime ( timeformat ) , "work_end_date" : end . strftime ( timeformat ) , "daily_pay" : int ( daily_pay ) , "name" : name , "url" : url , "initializer" : initializer , } ) return self . finalizeOp ( op , account , "active" , ** kwargs )
|
Create a worker
|
9,490
|
def create_committee_member ( self , url = "" , account = None , ** kwargs ) : if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , blockchain_instance = self ) op = operations . Committee_member_create ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "committee_member_account" : account [ "id" ] , "url" : url , } ) return self . finalizeOp ( op , account , "active" , ** kwargs )
|
Create a committee member
|
9,491
|
def reset_subscriptions ( self , accounts = [ ] , markets = [ ] , objects = [ ] ) : self . websocket . reset_subscriptions ( accounts , self . get_market_ids ( markets ) , objects )
|
Change the subscriptions of a running Notify instance
|
9,492
|
def process_market ( self , data ) : for d in data : if not d : continue if isinstance ( d , str ) : log . debug ( "Calling on_market with Order()" ) self . on_market ( Order ( d , blockchain_instance = self . blockchain ) ) continue elif isinstance ( d , dict ) : d = [ d ] for p in d : if not isinstance ( p , list ) : p = [ p ] for i in p : if isinstance ( i , dict ) : if "pays" in i and "receives" in i : self . on_market ( FilledOrder ( i , blockchain_instance = self . blockchain ) ) elif "for_sale" in i and "sell_price" in i : self . on_market ( Order ( i , blockchain_instance = self . blockchain ) ) elif "collateral" in i and "call_price" in i : self . on_market ( UpdateCallOrder ( i , blockchain_instance = self . blockchain ) ) else : if i : log . error ( "Unknown market update type: %s" % i )
|
This method is used for post processing of market notifications . It will return instances of either
|
9,493
|
def returnFees ( self ) : from bitsharesbase . operations import operations r = { } obj , base = self . blockchain . rpc . get_objects ( [ "2.0.0" , "1.3.0" ] ) fees = obj [ "parameters" ] [ "current_fees" ] [ "parameters" ] scale = float ( obj [ "parameters" ] [ "current_fees" ] [ "scale" ] ) for f in fees : op_name = "unknown %d" % f [ 0 ] for name in operations : if operations [ name ] == f [ 0 ] : op_name = name fs = f [ 1 ] for _type in fs : fs [ _type ] = float ( fs [ _type ] ) * scale / 1e4 / 10 ** base [ "precision" ] r [ op_name ] = fs return r
|
Returns a dictionary of all fees that apply through the network
|
9,494
|
def close_debt_position ( self , symbol , account = None ) : if not account : if "default_account" in self . blockchain . config : account = self . blockchain . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , full = True , blockchain_instance = self . blockchain ) debts = self . list_debt_positions ( account ) if symbol not in debts : raise ValueError ( "No call position open for %s" % symbol ) debt = debts [ symbol ] asset = debt [ "debt" ] [ "asset" ] collateral_asset = debt [ "collateral" ] [ "asset" ] op = operations . Call_order_update ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "delta_debt" : { "amount" : int ( - float ( debt [ "debt" ] ) * 10 ** asset [ "precision" ] ) , "asset_id" : asset [ "id" ] , } , "delta_collateral" : { "amount" : int ( - float ( debt [ "collateral" ] ) * 10 ** collateral_asset [ "precision" ] ) , "asset_id" : collateral_asset [ "id" ] , } , "funding_account" : account [ "id" ] , "extensions" : [ ] , } ) return self . blockchain . finalizeOp ( op , account [ "name" ] , "active" )
|
Close a debt position and reclaim the collateral
|
9,495
|
def adjust_debt ( self , delta , new_collateral_ratio = None , account = None , target_collateral_ratio = None , ) : if not account : if "default_account" in self . blockchain . config : account = self . blockchain . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , full = True , blockchain_instance = self . blockchain ) symbol = delta [ "symbol" ] asset = Asset ( symbol , full = True , blockchain_instance = self . blockchain ) if not asset . is_bitasset : raise ValueError ( "%s is not a bitasset!" % symbol ) bitasset = asset [ "bitasset_data" ] backing_asset_id = bitasset [ "options" ] [ "short_backing_asset" ] current_debts = self . list_debt_positions ( account ) if not new_collateral_ratio and symbol not in current_debts : new_collateral_ratio = ( bitasset [ "current_feed" ] [ "maintenance_collateral_ratio" ] / 1000 ) elif not new_collateral_ratio and symbol in current_debts : new_collateral_ratio = current_debts [ symbol ] [ "ratio" ] collateral_asset = Asset ( backing_asset_id , blockchain_instance = self . blockchain ) settlement_price = Price ( bitasset [ "current_feed" ] [ "settlement_price" ] , blockchain_instance = self . blockchain , ) if symbol in current_debts : amount_of_collateral = ( ( float ( current_debts [ symbol ] [ "debt" ] ) + float ( delta [ "amount" ] ) ) * new_collateral_ratio / float ( settlement_price ) ) amount_of_collateral -= float ( current_debts [ symbol ] [ "collateral" ] ) else : amount_of_collateral = ( float ( delta [ "amount" ] ) * new_collateral_ratio / float ( settlement_price ) ) fundsNeeded = amount_of_collateral + float ( self . returnFees ( ) [ "call_order_update" ] [ "fee" ] ) fundsHave = account . balance ( collateral_asset [ "symbol" ] ) or 0 if fundsHave <= fundsNeeded : raise ValueError ( "Not enough funds available. Need %f %s, but only %f %s are available" % ( fundsNeeded , collateral_asset [ "symbol" ] , fundsHave , collateral_asset [ "symbol" ] , ) ) payload = { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "delta_debt" : { "amount" : int ( float ( delta ) * 10 ** asset [ "precision" ] ) , "asset_id" : asset [ "id" ] , } , "delta_collateral" : { "amount" : int ( float ( amount_of_collateral ) * 10 ** collateral_asset [ "precision" ] ) , "asset_id" : collateral_asset [ "id" ] , } , "funding_account" : account [ "id" ] , "extensions" : { } , } if target_collateral_ratio : payload [ "extensions" ] . update ( dict ( target_collateral_ratio = int ( target_collateral_ratio * 100 ) ) ) op = operations . Call_order_update ( ** payload ) return self . blockchain . finalizeOp ( op , account [ "name" ] , "active" )
|
Adjust the amount of debt for an asset
|
9,496
|
def adjust_collateral_ratio ( self , symbol , new_collateral_ratio , account = None , target_collateral_ratio = None ) : if not account : if "default_account" in self . blockchain . config : account = self . blockchain . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , full = True , blockchain_instance = self . blockchain ) current_debts = self . list_debt_positions ( account ) if symbol not in current_debts : raise ValueError ( "No Call position available to adjust! Please borrow first!" ) return self . adjust_debt ( Amount ( 0 , symbol ) , new_collateral_ratio , account , target_collateral_ratio = target_collateral_ratio , )
|
Adjust the collataral ratio of a debt position
|
9,497
|
def getOperationNameForId ( i ) : for key in operations : if int ( operations [ key ] ) is int ( i ) : return key return "Unknown Operation ID %d" % i
|
Convert an operation id into the corresponding string
|
9,498
|
def getOperationName ( id : str ) : if isinstance ( id , str ) : assert id in operations . keys ( ) , "Unknown operation {}" . format ( id ) return id elif isinstance ( id , int ) : return getOperationNameForId ( id ) else : raise ValueError
|
This method returns the name representation of an operation given its value as used in the API
|
9,499
|
def get_account ( self , name , ** kwargs ) : if len ( name . split ( "." ) ) == 3 : return self . get_objects ( [ name ] ) [ 0 ] else : return self . get_account_by_name ( name , ** kwargs )
|
Get full account details from account name or id
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.