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 [... | 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 . ... | 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 ... | 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 . ba... | 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 ( ) ... | 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 : ... | 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 . re... | 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 ac... | 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_in... | 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 ... | 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 :... | 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... | 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 ( hom... | 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... | 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 ... | 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 IOE... | 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_DO... | 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... | 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 ... | 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' ) ... | 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 (... | 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... | 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 envi... | 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 .... | 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 wa... | 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 ) ... | 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 ' +... | 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 . pack... | 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 = s... | 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 . p... | 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 . s... | 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... | 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... | 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 p... | 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 , block... | 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_u... | 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" ) i... | 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 , blockch... | 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 [... | 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 (... | 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... | 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_instanc... | 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 ) , ... | 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_accou... | 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... | 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 = ope... | 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 ) :... | 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 =... | 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_inst... | 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" ) acc... | 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" )... | 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.