idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
18,300
def main ( ) : sys . path . insert ( 0 , os . getcwd ( ) ) args , extrargs = parser . parse_known_args ( ) sys . argv = [ 'wdb' ] + args . args + extrargs if args . file : file = os . path . join ( os . getcwd ( ) , args . file ) if args . source : print ( 'The source argument cannot be used with file.' ) sys . exit ( 1 ) if not os . path . exists ( file ) : print ( 'Error:' , file , 'does not exist' ) sys . exit ( 1 ) if args . trace : Wdb . get ( ) . run_file ( file ) else : def wdb_pm ( xtype , value , traceback ) : sys . __excepthook__ ( xtype , value , traceback ) wdb = Wdb . get ( ) wdb . reset ( ) wdb . interaction ( None , traceback , post_mortem = True ) sys . excepthook = wdb_pm with open ( file ) as f : code = compile ( f . read ( ) , file , 'exec' ) execute ( code , globals ( ) , globals ( ) ) else : source = None if args . source : source = os . path . join ( os . getcwd ( ) , args . source ) if not os . path . exists ( source ) : print ( 'Error:' , source , 'does not exist' ) sys . exit ( 1 ) Wdb . get ( ) . shell ( source )
Wdb entry point
18,301
def _patch_tcpserver ( ) : shutdown_request = TCPServer . shutdown_request def shutdown_request_patched ( * args , ** kwargs ) : thread = current_thread ( ) shutdown_request ( * args , ** kwargs ) if thread in _exc_cache : post_mortem_interaction ( * _exc_cache . pop ( thread ) ) TCPServer . shutdown_request = shutdown_request_patched
Patch shutdown_request to open blocking interaction after the end of the request
18,302
def up ( self ) : if self . frame : self . frame = self . frame . f_back return self . frame is None
Go up in stack and return True if top frame
18,303
def set_trace ( frame = None , skip = 0 , server = None , port = None ) : frame = frame or sys . _getframe ( ) . f_back for i in range ( skip ) : if not frame . f_back : break frame = frame . f_back wdb = Wdb . get ( server = server , port = port ) wdb . set_trace ( frame ) return wdb
Set trace on current line or on given frame
18,304
def cleanup ( ) : for sck in list ( Wdb . _sockets ) : try : sck . close ( ) except Exception : log . warn ( 'Error in cleanup' , exc_info = True )
Close all sockets at exit
18,305
def shell ( source = None , vars = None , server = None , port = None ) : Wdb . get ( server = server , port = port ) . shell ( source = source , vars = vars )
Start a shell sourcing source or using vars as locals
18,306
def get ( no_create = False , server = None , port = None , force_uuid = None ) : pid = os . getpid ( ) thread = threading . current_thread ( ) wdb = Wdb . _instances . get ( ( pid , thread ) ) if not wdb and not no_create : wdb = object . __new__ ( Wdb ) Wdb . __init__ ( wdb , server , port , force_uuid ) wdb . pid = pid wdb . thread = thread Wdb . _instances [ ( pid , thread ) ] = wdb elif wdb : if ( server is not None and wdb . server != server or port is not None and wdb . port != port ) : log . warn ( 'Different server/port set, ignoring' ) else : wdb . reconnect_if_needed ( ) return wdb
Get the thread local singleton
18,307
def pop ( ) : pid = os . getpid ( ) thread = threading . current_thread ( ) Wdb . _instances . pop ( ( pid , thread ) )
Remove instance from instance list
18,308
def run_file ( self , filename ) : import __main__ __main__ . __dict__ . clear ( ) __main__ . __dict__ . update ( { "__name__" : "__main__" , "__file__" : filename , "__builtins__" : __builtins__ , } ) with open ( filename , "rb" ) as fp : statement = compile ( fp . read ( ) , filename , 'exec' ) self . run ( statement , filename )
Run the file filename with trace
18,309
def run ( self , cmd , fn = None , globals = None , locals = None ) : if globals is None : import __main__ globals = __main__ . __dict__ if locals is None : locals = globals self . reset ( ) if isinstance ( cmd , str ) : str_cmd = cmd cmd = compile ( str_cmd , fn or "<wdb>" , "exec" ) self . compile_cache [ id ( cmd ) ] = str_cmd if fn : from linecache import getline lno = 1 while True : line = getline ( fn , lno , globals ) if line is None : lno = None break if executable_line ( line ) : break lno += 1 self . start_trace ( ) if lno is not None : self . breakpoints . add ( LineBreakpoint ( fn , lno , temporary = True ) ) try : execute ( cmd , globals , locals ) finally : self . stop_trace ( )
Run the cmd cmd with trace
18,310
def connect ( self ) : log . info ( 'Connecting socket on %s:%d' % ( self . server , self . port ) ) tries = 0 while not self . _socket and tries < 10 : try : time . sleep ( .2 * tries ) self . _socket = Socket ( ( self . server , self . port ) ) except socket . error : tries += 1 log . warning ( 'You must start/install wdb.server ' '(Retrying on %s:%d) [Try #%d/10]' % ( self . server , self . port , tries ) ) self . _socket = None if not self . _socket : log . warning ( 'Could not connect to server' ) return Wdb . _sockets . append ( self . _socket ) self . _socket . send_bytes ( self . uuid . encode ( 'utf-8' ) )
Connect to wdb server
18,311
def trace_dispatch ( self , frame , event , arg ) : fun = getattr ( self , 'handle_' + event , None ) if not fun : return self . trace_dispatch below , continue_below = self . check_below ( frame ) if ( self . state . stops ( frame , event ) or ( event == 'line' and self . breaks ( frame ) ) or ( event == 'exception' and ( self . full or below ) ) ) : fun ( frame , arg ) if event == 'return' and frame == self . state . frame : if self . state . up ( ) : self . stop_trace ( ) return co = self . state . frame . f_code if ( ( co . co_filename . endswith ( 'threading.py' ) and co . co_name . endswith ( '_bootstrap_inner' ) ) or ( self . state . frame . f_code . co_filename . endswith ( os . path . join ( 'multiprocessing' , 'process.py' ) ) and self . state . frame . f_code . co_name == '_bootstrap' ) ) : self . stop_trace ( ) self . die ( ) return if ( event == 'call' and not self . stepping and not self . full and not continue_below and not self . get_file_breaks ( frame . f_code . co_filename ) ) : return return self . trace_dispatch
This function is called every line function call function return and exception during trace
18,312
def trace_debug_dispatch ( self , frame , event , arg ) : trace_log . info ( 'Frame:%s. Event: %s. Arg: %r' % ( pretty_frame ( frame ) , event , arg ) ) trace_log . debug ( 'state %r breaks ? %s stops ? %s' % ( self . state , self . breaks ( frame , no_remove = True ) , self . state . stops ( frame , event ) ) ) if event == 'return' : trace_log . debug ( 'Return: frame: %s, state: %s, state.f_back: %s' % ( pretty_frame ( frame ) , pretty_frame ( self . state . frame ) , pretty_frame ( self . state . frame . f_back ) ) ) if self . trace_dispatch ( frame , event , arg ) : return self . trace_debug_dispatch trace_log . debug ( "No trace %s" % pretty_frame ( frame ) )
Utility function to add debug to tracing
18,313
def start_trace ( self , full = False , frame = None , below = 0 , under = None ) : if self . tracing : return self . reset ( ) log . info ( 'Starting trace' ) frame = frame or sys . _getframe ( ) . f_back self . set_trace ( frame , break_ = False ) self . tracing = True self . below = below self . under = under self . full = full
Start tracing from here
18,314
def set_trace ( self , frame = None , break_ = True ) : trace_log . info ( 'Setting trace %s (stepping %s) (current_trace: %s)' % ( pretty_frame ( frame or sys . _getframe ( ) . f_back ) , self . stepping , sys . gettrace ( ) ) ) if self . stepping or self . closed : return self . reset ( ) trace = ( self . trace_dispatch if trace_log . level >= 30 else self . trace_debug_dispatch ) trace_frame = frame = frame or sys . _getframe ( ) . f_back while frame : frame . f_trace = trace frame = frame . f_back self . state = Step ( trace_frame ) if break_ else Running ( trace_frame ) sys . settrace ( trace )
Break at current state
18,315
def stop_trace ( self , frame = None ) : self . tracing = False self . full = False frame = frame or sys . _getframe ( ) . f_back while frame : del frame . f_trace frame = frame . f_back sys . settrace ( None ) log . info ( 'Stopping trace' )
Stop tracing from here
18,316
def set_until ( self , frame , lineno = None ) : self . state = Until ( frame , frame . f_lineno )
Stop on the next line number .
18,317
def set_continue ( self , frame ) : self . state = Running ( frame ) if not self . tracing and not self . breakpoints : self . stop_trace ( )
Don t stop anymore
18,318
def set_break ( self , filename , lineno = None , temporary = False , cond = None , funcname = None ) : log . info ( 'Setting break fn:%s lno:%s tmp:%s cond:%s fun:%s' % ( filename , lineno , temporary , cond , funcname ) ) breakpoint = self . get_break ( filename , lineno , temporary , cond , funcname ) self . breakpoints . add ( breakpoint ) log . info ( 'Breakpoint %r added' % breakpoint ) return breakpoint
Put a breakpoint for filename
18,319
def clear_break ( self , filename , lineno = None , temporary = False , cond = None , funcname = None ) : log . info ( 'Removing break fn:%s lno:%s tmp:%s cond:%s fun:%s' % ( filename , lineno , temporary , cond , funcname ) ) breakpoint = self . get_break ( filename , lineno , temporary or False , cond , funcname ) if temporary is None and breakpoint not in self . breakpoints : breakpoint = self . get_break ( filename , lineno , True , cond , funcname ) try : self . breakpoints . remove ( breakpoint ) log . info ( 'Breakpoint %r removed' % breakpoint ) except Exception : log . info ( 'Breakpoint %r not removed: not found' % breakpoint )
Remove a breakpoint
18,320
def safe_repr ( self , obj ) : try : return repr ( obj ) except Exception as e : return '??? Broken repr (%s: %s)' % ( type ( e ) . __name__ , e )
Like a repr but without exception
18,321
def safe_better_repr ( self , obj , context = None , html = True , level = 0 , full = False ) : context = context and dict ( context ) or { } recursion = id ( obj ) in context if not recursion : context [ id ( obj ) ] = obj try : rv = self . better_repr ( obj , context , html , level + 1 , full ) except Exception : rv = None if rv : return rv self . obj_cache [ id ( obj ) ] = obj if html : return '<a href="%d" class="inspect">%s%s</a>' % ( id ( obj ) , 'Recursion of ' if recursion else '' , escape ( self . safe_repr ( obj ) ) ) return '%s%s' % ( 'Recursion of ' if recursion else '' , self . safe_repr ( obj ) )
Repr with inspect links on objects
18,322
def capture_output ( self , with_hook = True ) : self . hooked = '' def display_hook ( obj ) : self . hooked += self . safe_better_repr ( obj ) self . last_obj = obj stdout , stderr = sys . stdout , sys . stderr if with_hook : d_hook = sys . displayhook sys . displayhook = display_hook sys . stdout , sys . stderr = StringIO ( ) , StringIO ( ) out , err = [ ] , [ ] try : yield out , err finally : out . extend ( sys . stdout . getvalue ( ) . splitlines ( ) ) err . extend ( sys . stderr . getvalue ( ) . splitlines ( ) ) if with_hook : sys . displayhook = d_hook sys . stdout , sys . stderr = stdout , stderr
Steal stream output return them in string restore them
18,323
def dmp ( self , thing ) : def safe_getattr ( key ) : try : return getattr ( thing , key ) except Exception as e : return 'Error getting attr "%s" from "%s" (%s: %s)' % ( key , thing , type ( e ) . __name__ , e ) return dict ( ( escape ( key ) , { 'val' : self . safe_better_repr ( safe_getattr ( key ) ) , 'type' : type ( safe_getattr ( key ) ) . __name__ } ) for key in dir ( thing ) )
Dump the content of an object in a dict for wdb . js
18,324
def get_file ( self , filename ) : import linecache if filename == '<frozen importlib._bootstrap>' : filename = os . path . join ( os . path . dirname ( linecache . __file__ ) , 'importlib' , '_bootstrap.py' ) return to_unicode_string ( '' . join ( linecache . getlines ( filename ) ) , filename )
Get file source from cache
18,325
def get_stack ( self , f , t ) : stack = [ ] if t and t . tb_frame == f : t = t . tb_next while f is not None : stack . append ( ( f , f . f_lineno ) ) f = f . f_back stack . reverse ( ) i = max ( 0 , len ( stack ) - 1 ) while t is not None : stack . append ( ( t . tb_frame , t . tb_lineno ) ) t = t . tb_next if f is None : i = max ( 0 , len ( stack ) - 1 ) return stack , i
Build the stack from frame and traceback
18,326
def get_trace ( self , frame , tb ) : import linecache frames = [ ] stack , _ = self . get_stack ( frame , tb ) current = 0 for i , ( stack_frame , lno ) in enumerate ( stack ) : code = stack_frame . f_code filename = code . co_filename or '<unspecified>' line = None if filename [ 0 ] == '<' and filename [ - 1 ] == '>' : line = get_source_from_byte_code ( code ) fn = filename else : fn = os . path . abspath ( filename ) if not line : linecache . checkcache ( filename ) line = linecache . getline ( filename , lno , stack_frame . f_globals ) if not line : line = self . compile_cache . get ( id ( code ) , '' ) line = to_unicode_string ( line , filename ) line = line and line . strip ( ) startlnos = dis . findlinestarts ( code ) lastlineno = list ( startlnos ) [ - 1 ] [ 1 ] if frame == stack_frame : current = i frames . append ( { 'file' : fn , 'function' : code . co_name , 'flno' : code . co_firstlineno , 'llno' : lastlineno , 'lno' : lno , 'code' : line , 'level' : i , 'current' : frame == stack_frame } ) return stack , frames , current
Get a dict of the traceback for wdb . js use
18,327
def send ( self , data ) : log . debug ( 'Sending %s' % data ) if not self . _socket : log . warn ( 'No connection' ) return self . _socket . send_bytes ( data . encode ( 'utf-8' ) )
Send data through websocket
18,328
def receive ( self , timeout = None ) : log . debug ( 'Receiving' ) if not self . _socket : log . warn ( 'No connection' ) return try : if timeout : rv = self . _socket . poll ( timeout ) if not rv : log . info ( 'Connection timeouted' ) return 'Quit' data = self . _socket . recv_bytes ( ) except Exception : log . error ( 'Connection lost' ) return 'Quit' log . debug ( 'Got %s' % data ) return data . decode ( 'utf-8' )
Receive data through websocket
18,329
def interaction ( self , frame , tb = None , exception = 'Wdb' , exception_description = 'Stepping' , init = None , shell = False , shell_vars = None , source = None , iframe_mode = False , timeout = None , post_mortem = False ) : log . info ( 'Interaction %r %r %r %r' % ( frame , tb , exception , exception_description ) ) self . reconnect_if_needed ( ) self . stepping = not shell if not iframe_mode : opts = { } if shell : opts [ 'type_' ] = 'shell' if post_mortem : opts [ 'type_' ] = 'pm' self . open_browser ( ** opts ) lvl = len ( self . interaction_stack ) if lvl : exception_description += ' [recursive%s]' % ( '^%d' % lvl if lvl > 1 else '' ) interaction = Interaction ( self , frame , tb , exception , exception_description , init = init , shell = shell , shell_vars = shell_vars , source = source , timeout = timeout ) self . interaction_stack . append ( interaction ) self . _ui = interaction if self . begun : interaction . init ( ) else : self . begun = True interaction . loop ( ) self . interaction_stack . pop ( ) if lvl : self . interaction_stack [ - 1 ] . init ( )
User interaction handling blocking on socket receive
18,330
def breaks ( self , frame , no_remove = False ) : for breakpoint in set ( self . breakpoints ) : if breakpoint . breaks ( frame ) : if breakpoint . temporary and not no_remove : self . breakpoints . remove ( breakpoint ) return True return False
Return True if there s a breakpoint at frame
18,331
def get_file_breaks ( self , filename ) : return [ breakpoint for breakpoint in self . breakpoints if breakpoint . on_file ( filename ) ]
List all file filename breakpoints
18,332
def get_breaks_lno ( self , filename ) : return list ( filter ( lambda x : x is not None , [ getattr ( breakpoint , 'line' , None ) for breakpoint in self . breakpoints if breakpoint . on_file ( filename ) ] ) )
List all line numbers that have a breakpoint
18,333
def die ( self ) : log . info ( 'Time to die' ) if self . connected : try : self . send ( 'Die' ) except Exception : pass if self . _socket : self . _socket . close ( ) self . pop ( )
Time to quit
18,334
def _killall ( self , force = False ) : for_termination = [ ] for n , p in iteritems ( self . _processes ) : if 'returncode' not in p : for_termination . append ( n ) for n in for_termination : p = self . _processes [ n ] signame = 'SIGKILL' if force else 'SIGTERM' self . _system_print ( "sending %s to %s (pid %s)\n" % ( signame , n , p [ 'pid' ] ) ) if force : self . _env . kill ( p [ 'pid' ] ) else : self . _env . terminate ( p [ 'pid' ] )
Kill all remaining processes forcefully if requested .
18,335
def expand_processes ( processes , concurrency = None , env = None , quiet = None , port = None ) : if env is not None and env . get ( "PORT" ) is not None : port = int ( env . get ( "PORT" ) ) if quiet is None : quiet = [ ] con = defaultdict ( lambda : 1 ) if concurrency is not None : con . update ( concurrency ) out = [ ] for name , cmd in compat . iteritems ( processes ) : for i in range ( con [ name ] ) : n = "{0}.{1}" . format ( name , i + 1 ) c = cmd q = name in quiet e = { 'HONCHO_PROCESS_NAME' : n } if env is not None : e . update ( env ) if port is not None : e [ 'PORT' ] = str ( port + i ) params = ProcessParams ( n , c , q , e ) out . append ( params ) if port is not None : port += 100 return out
Get a list of the processes that need to be started given the specified list of process types concurrency environment quietness and base port number .
18,336
def dashrepl ( value ) : patt = re . compile ( r'\W' , re . UNICODE ) return re . sub ( patt , '-' , value )
Replace any non - word characters with a dash .
18,337
def find_sources ( self ) : app_configs = apps . get_app_configs ( ) for app_config in app_configs : ignore_dirs = [ ] for root , dirs , files in os . walk ( app_config . path ) : if [ True for idir in ignore_dirs if root . startswith ( idir ) ] : continue if '__init__.py' not in files : ignore_dirs . append ( root ) continue for filename in files : basename , ext = os . path . splitext ( filename ) if ext != '.py' : continue yield os . path . abspath ( os . path . join ( root , filename ) )
Look for Python sources available for the current configuration .
18,338
def find_templates ( self ) : paths = set ( ) for loader in self . get_loaders ( ) : try : module = import_module ( loader . __module__ ) get_template_sources = getattr ( module , 'get_template_sources' , loader . get_template_sources ) template_sources = get_template_sources ( '' ) paths . update ( [ t . name if isinstance ( t , Origin ) else t for t in template_sources ] ) except ( ImportError , AttributeError ) : pass if not paths : raise CommandError ( "No template paths found. None of the configured template loaders provided template paths" ) templates = set ( ) for path in paths : for root , _ , files in os . walk ( str ( path ) ) : templates . update ( os . path . join ( root , name ) for name in files if not name . startswith ( '.' ) and any ( name . endswith ( ext ) for ext in self . template_exts ) ) if not templates : raise CommandError ( "No templates found. Make sure your TEMPLATE_LOADERS and TEMPLATE_DIRS settings are correct." ) return templates
Look for templates and extract the nodes containing the SASS file .
18,339
def compile_sass ( self , sass_filename , sass_fileurl ) : compile_kwargs = { 'filename' : sass_filename , 'include_paths' : SassProcessor . include_paths + APPS_INCLUDE_DIRS , 'custom_functions' : get_custom_functions ( ) , } if self . sass_precision : compile_kwargs [ 'precision' ] = self . sass_precision if self . sass_output_style : compile_kwargs [ 'output_style' ] = self . sass_output_style content = sass . compile ( ** compile_kwargs ) self . save_to_destination ( content , sass_filename , sass_fileurl ) self . processed_files . append ( sass_filename ) if self . verbosity > 1 : self . stdout . write ( "Compiled SASS/SCSS file: '{0}'\n" . format ( sass_filename ) )
Compile the given SASS file into CSS
18,340
def walk_nodes ( self , node , original ) : try : nodelist = self . parser . get_nodelist ( node , original = original ) except TypeError : nodelist = self . parser . get_nodelist ( node , original = original , context = None ) for node in nodelist : if isinstance ( node , SassSrcNode ) : if node . is_sass : yield node else : for node in self . walk_nodes ( node , original = original ) : yield node
Iterate over the nodes recursively yielding the templatetag sass_src
18,341
def get_custom_functions ( ) : def get_setting ( * args ) : try : return getattr ( settings , args [ 0 ] ) except AttributeError as e : raise TemplateSyntaxError ( str ( e ) ) if hasattr ( get_custom_functions , '_custom_functions' ) : return get_custom_functions . _custom_functions get_custom_functions . _custom_functions = { sass . SassFunction ( 'get-setting' , ( 'key' , ) , get_setting ) } for name , func in getattr ( settings , 'SASS_PROCESSOR_CUSTOM_FUNCTIONS' , { } ) . items ( ) : try : if isinstance ( func , six . string_types ) : func = import_string ( func ) except Exception as e : raise TemplateSyntaxError ( str ( e ) ) else : if not inspect . isfunction ( func ) : raise TemplateSyntaxError ( "{} is not a Python function" . format ( func ) ) if six . PY2 : func_args = inspect . getargspec ( func ) . args else : func_args = inspect . getfullargspec ( func ) . args sass_func = sass . SassFunction ( name , func_args , func ) get_custom_functions . _custom_functions . add ( sass_func ) return get_custom_functions . _custom_functions
Return a dict of function names to be used from inside SASS
18,342
def read ( self , pin , is_differential = False ) : pin = pin if is_differential else pin + 0x04 return self . _read ( pin )
I2C Interface for ADS1x15 - based ADCs reads .
18,343
def _read ( self , pin ) : config = _ADS1X15_CONFIG_OS_SINGLE config |= ( pin & 0x07 ) << _ADS1X15_CONFIG_MUX_OFFSET config |= _ADS1X15_CONFIG_GAIN [ self . gain ] config |= self . mode config |= self . rate_config [ self . data_rate ] config |= _ADS1X15_CONFIG_COMP_QUE_DISABLE self . _write_register ( _ADS1X15_POINTER_CONFIG , config ) while not self . _conversion_complete ( ) : time . sleep ( 0.01 ) return self . get_last_result ( )
Perform an ADC read . Returns the signed integer result of the read .
18,344
def _write_register ( self , reg , value ) : self . buf [ 0 ] = reg self . buf [ 1 ] = ( value >> 8 ) & 0xFF self . buf [ 2 ] = value & 0xFF with self . i2c_device as i2c : i2c . write ( self . buf )
Write 16 bit value to register .
18,345
def _read_register ( self , reg ) : self . buf [ 0 ] = reg with self . i2c_device as i2c : i2c . write ( self . buf , end = 1 , stop = False ) i2c . readinto ( self . buf , end = 2 ) return self . buf [ 0 ] << 8 | self . buf [ 1 ]
Read 16 bit register value .
18,346
def value ( self ) : return self . _ads . read ( self . _pin_setting , is_differential = self . is_differential )
Returns the value of an ADC pin as an integer .
18,347
def voltage ( self ) : raw = self . value volts = raw * ( _ADS1X15_PGA_RANGE [ self . _ads . gain ] / ( 2 ** ( self . _ads . bits - 1 ) - 1 ) ) return volts
Returns the voltage from the ADC pin as a floating point value .
18,348
def sequential_id ( self , client ) : if client . client_id not in self . _sequential_ids : id_ = sequential_id ( "e:{0}:users" . format ( self . name ) , client . client_id ) self . _sequential_ids [ client . client_id ] = id_ return self . _sequential_ids [ client . client_id ]
Return the sequential id for this test for the passed in client
18,349
def record_participation ( self , client , dt = None ) : if dt is None : date = datetime . now ( ) else : date = dt experiment_key = self . experiment . name pipe = self . redis . pipeline ( ) pipe . sadd ( _key ( "p:{0}:years" . format ( experiment_key ) ) , date . strftime ( '%Y' ) ) pipe . sadd ( _key ( "p:{0}:months" . format ( experiment_key ) ) , date . strftime ( '%Y-%m' ) ) pipe . sadd ( _key ( "p:{0}:days" . format ( experiment_key ) ) , date . strftime ( '%Y-%m-%d' ) ) pipe . execute ( ) keys = [ _key ( "p:{0}:_all:all" . format ( experiment_key ) ) , _key ( "p:{0}:_all:{1}" . format ( experiment_key , date . strftime ( '%Y' ) ) ) , _key ( "p:{0}:_all:{1}" . format ( experiment_key , date . strftime ( '%Y-%m' ) ) ) , _key ( "p:{0}:_all:{1}" . format ( experiment_key , date . strftime ( '%Y-%m-%d' ) ) ) , _key ( "p:{0}:{1}:all" . format ( experiment_key , self . name ) ) , _key ( "p:{0}:{1}:{2}" . format ( experiment_key , self . name , date . strftime ( '%Y' ) ) ) , _key ( "p:{0}:{1}:{2}" . format ( experiment_key , self . name , date . strftime ( '%Y-%m' ) ) ) , _key ( "p:{0}:{1}:{2}" . format ( experiment_key , self . name , date . strftime ( '%Y-%m-%d' ) ) ) , ] msetbit ( keys = keys , args = ( [ self . experiment . sequential_id ( client ) , 1 ] * len ( keys ) ) )
Record a user s participation in a test along with a given variation
18,350
def sequential_id ( k , identifier ) : key = _key ( k ) return int ( monotonic_zadd ( keys = [ key ] , args = [ identifier ] ) )
Map an arbitrary string identifier to a set of sequential ids
18,351
def load_emacs_open_in_editor_bindings ( ) : registry = Registry ( ) registry . add_binding ( Keys . ControlX , Keys . ControlE , filter = EmacsMode ( ) & ~ HasSelection ( ) ) ( get_by_name ( 'edit-and-execute-command' ) ) return registry
Pressing C - X C - E will open the buffer in an external editor .
18,352
def _create_event ( ) : return windll . kernel32 . CreateEventA ( pointer ( SECURITY_ATTRIBUTES ( ) ) , BOOL ( True ) , BOOL ( False ) , None )
Creates a Win32 unnamed Event .
18,353
def _ready_for_reading ( self , timeout = None ) : handles = [ self . _event , self . _console_input_reader . handle ] handles . extend ( self . _read_fds . keys ( ) ) return _wait_for_handles ( handles , timeout )
Return the handle that is ready for reading or None on timeout .
18,354
def add_reader ( self , fd , callback ) : " Start watching the file descriptor for read availability. " h = msvcrt . get_osfhandle ( fd ) self . _read_fds [ h ] = callback
Start watching the file descriptor for read availability .
18,355
def remove_reader ( self , fd ) : " Stop watching the file descriptor for read availability. " h = msvcrt . get_osfhandle ( fd ) if h in self . _read_fds : del self . _read_fds [ h ]
Stop watching the file descriptor for read availability .
18,356
def validate_and_handle ( self , cli , buffer ) : if buffer . validate ( ) : if self . handler : self . handler ( cli , buffer ) buffer . append_to_history ( )
Validate buffer and handle the accept action .
18,357
def _set_text ( self , value ) : working_index = self . working_index working_lines = self . _working_lines original_value = working_lines [ working_index ] working_lines [ working_index ] = value if len ( value ) != len ( original_value ) : return True elif value != original_value : return True return False
set text at current working_index . Return whether it changed .
18,358
def _set_cursor_position ( self , value ) : original_position = self . __cursor_position self . __cursor_position = max ( 0 , value ) return value != original_position
Set cursor position . Return whether it changed .
18,359
def cursor_position ( self , value ) : assert isinstance ( value , int ) assert value <= len ( self . text ) changed = self . _set_cursor_position ( value ) if changed : self . _cursor_position_changed ( )
Setting cursor position .
18,360
def transform_lines ( self , line_index_iterator , transform_callback ) : lines = self . text . split ( '\n' ) for index in line_index_iterator : try : lines [ index ] = transform_callback ( lines [ index ] ) except IndexError : pass return '\n' . join ( lines )
Transforms the text on a range of lines . When the iterator yield an index not in the range of lines that the document contains it skips them silently .
18,361
def transform_current_line ( self , transform_callback ) : document = self . document a = document . cursor_position + document . get_start_of_line_position ( ) b = document . cursor_position + document . get_end_of_line_position ( ) self . text = ( document . text [ : a ] + transform_callback ( document . text [ a : b ] ) + document . text [ b : ] )
Apply the given transformation function to the current line .
18,362
def transform_region ( self , from_ , to , transform_callback ) : assert from_ < to self . text = '' . join ( [ self . text [ : from_ ] + transform_callback ( self . text [ from_ : to ] ) + self . text [ to : ] ] )
Transform a part of the input string .
18,363
def delete_before_cursor ( self , count = 1 ) : assert count >= 0 deleted = '' if self . cursor_position > 0 : deleted = self . text [ self . cursor_position - count : self . cursor_position ] new_text = self . text [ : self . cursor_position - count ] + self . text [ self . cursor_position : ] new_cursor_position = self . cursor_position - len ( deleted ) self . document = Document ( new_text , new_cursor_position ) return deleted
Delete specified number of characters before cursor and return the deleted text .
18,364
def delete ( self , count = 1 ) : if self . cursor_position < len ( self . text ) : deleted = self . document . text_after_cursor [ : count ] self . text = self . text [ : self . cursor_position ] + self . text [ self . cursor_position + len ( deleted ) : ] return deleted else : return ''
Delete specified number of characters and Return the deleted text .
18,365
def join_next_line ( self , separator = ' ' ) : if not self . document . on_last_line : self . cursor_position += self . document . get_end_of_line_position ( ) self . delete ( ) self . text = ( self . document . text_before_cursor + separator + self . document . text_after_cursor . lstrip ( ' ' ) )
Join the next line to the current one by deleting the line ending after the current line .
18,366
def join_selected_lines ( self , separator = ' ' ) : assert self . selection_state from_ , to = sorted ( [ self . cursor_position , self . selection_state . original_cursor_position ] ) before = self . text [ : from_ ] lines = self . text [ from_ : to ] . splitlines ( ) after = self . text [ to : ] lines = [ l . lstrip ( ' ' ) + separator for l in lines ] self . document = Document ( text = before + '' . join ( lines ) + after , cursor_position = len ( before + '' . join ( lines [ : - 1 ] ) ) - 1 )
Join the selected lines .
18,367
def swap_characters_before_cursor ( self ) : pos = self . cursor_position if pos >= 2 : a = self . text [ pos - 2 ] b = self . text [ pos - 1 ] self . text = self . text [ : pos - 2 ] + b + a + self . text [ pos : ]
Swap the last two characters before the cursor .
18,368
def go_to_history ( self , index ) : if index < len ( self . _working_lines ) : self . working_index = index self . cursor_position = len ( self . text )
Go to this item in the history .
18,369
def start_history_lines_completion ( self ) : found_completions = set ( ) completions = [ ] current_line = self . document . current_line_before_cursor . lstrip ( ) for i , string in enumerate ( self . _working_lines ) : for j , l in enumerate ( string . split ( '\n' ) ) : l = l . strip ( ) if l and l . startswith ( current_line ) : if l not in found_completions : found_completions . add ( l ) if i == self . working_index : display_meta = "Current, line %s" % ( j + 1 ) else : display_meta = "History %s, line %s" % ( i + 1 , j + 1 ) completions . append ( Completion ( l , start_position = - len ( current_line ) , display_meta = display_meta ) ) self . set_completions ( completions = completions [ : : - 1 ] )
Start a completion based on all the other lines in the document and the history .
18,370
def go_to_completion ( self , index ) : assert index is None or isinstance ( index , int ) assert self . complete_state state = self . complete_state . go_to_index ( index ) new_text , new_cursor_position = state . new_text_and_position ( ) self . document = Document ( new_text , new_cursor_position ) self . complete_state = state
Select a completion from the list of current completions .
18,371
def apply_completion ( self , completion ) : assert isinstance ( completion , Completion ) if self . complete_state : self . go_to_completion ( None ) self . complete_state = None self . delete_before_cursor ( - completion . start_position ) self . insert_text ( completion . text )
Insert a given completion .
18,372
def _set_history_search ( self ) : if self . enable_history_search ( ) : if self . history_search_text is None : self . history_search_text = self . document . text_before_cursor else : self . history_search_text = None
Set history_search_text .
18,373
def history_forward ( self , count = 1 ) : self . _set_history_search ( ) found_something = False for i in range ( self . working_index + 1 , len ( self . _working_lines ) ) : if self . _history_matches ( i ) : self . working_index = i count -= 1 found_something = True if count == 0 : break if found_something : self . cursor_position = 0 self . cursor_position += self . document . get_end_of_line_position ( )
Move forwards through the history .
18,374
def history_backward ( self , count = 1 ) : self . _set_history_search ( ) found_something = False for i in range ( self . working_index - 1 , - 1 , - 1 ) : if self . _history_matches ( i ) : self . working_index = i count -= 1 found_something = True if count == 0 : break if found_something : self . cursor_position = len ( self . text )
Move backwards through history .
18,375
def start_selection ( self , selection_type = SelectionType . CHARACTERS ) : self . selection_state = SelectionState ( self . cursor_position , selection_type )
Take the current cursor position as the start of this selection .
18,376
def paste_clipboard_data ( self , data , paste_mode = PasteMode . EMACS , count = 1 ) : assert isinstance ( data , ClipboardData ) assert paste_mode in ( PasteMode . VI_BEFORE , PasteMode . VI_AFTER , PasteMode . EMACS ) original_document = self . document self . document = self . document . paste_clipboard_data ( data , paste_mode = paste_mode , count = count ) self . document_before_paste = original_document
Insert the data from the clipboard .
18,377
def newline ( self , copy_margin = True ) : if copy_margin : self . insert_text ( '\n' + self . document . leading_whitespace_in_current_line ) else : self . insert_text ( '\n' )
Insert a line ending at the current position .
18,378
def insert_line_above ( self , copy_margin = True ) : if copy_margin : insert = self . document . leading_whitespace_in_current_line + '\n' else : insert = '\n' self . cursor_position += self . document . get_start_of_line_position ( ) self . insert_text ( insert ) self . cursor_position -= 1
Insert a new line above the current one .
18,379
def insert_line_below ( self , copy_margin = True ) : if copy_margin : insert = '\n' + self . document . leading_whitespace_in_current_line else : insert = '\n' self . cursor_position += self . document . get_end_of_line_position ( ) self . insert_text ( insert )
Insert a new line below the current one .
18,380
def insert_text ( self , data , overwrite = False , move_cursor = True , fire_event = True ) : otext = self . text ocpos = self . cursor_position if overwrite : overwritten_text = otext [ ocpos : ocpos + len ( data ) ] if '\n' in overwritten_text : overwritten_text = overwritten_text [ : overwritten_text . find ( '\n' ) ] self . text = otext [ : ocpos ] + data + otext [ ocpos + len ( overwritten_text ) : ] else : self . text = otext [ : ocpos ] + data + otext [ ocpos : ] if move_cursor : self . cursor_position += len ( data ) if fire_event : self . on_text_insert . fire ( )
Insert characters at cursor position .
18,381
def validate ( self ) : if self . validation_state != ValidationState . UNKNOWN : return self . validation_state == ValidationState . VALID if self . validator : try : self . validator . validate ( self . document ) except ValidationError as e : cursor_position = e . cursor_position self . cursor_position = min ( max ( 0 , cursor_position ) , len ( self . text ) ) self . validation_state = ValidationState . INVALID self . validation_error = e return False self . validation_state = ValidationState . VALID self . validation_error = None return True
Returns True if valid .
18,382
def open_in_editor ( self , cli ) : if self . read_only ( ) : raise EditReadOnlyBuffer ( ) descriptor , filename = tempfile . mkstemp ( self . tempfile_suffix ) os . write ( descriptor , self . text . encode ( 'utf-8' ) ) os . close ( descriptor ) succes = cli . run_in_terminal ( lambda : self . _open_file_in_editor ( filename ) ) if succes : with open ( filename , 'rb' ) as f : text = f . read ( ) . decode ( 'utf-8' ) if text . endswith ( '\n' ) : text = text [ : - 1 ] self . document = Document ( text = text , cursor_position = len ( text ) ) os . remove ( filename )
Open code in editor .
18,383
def _open_file_in_editor ( self , filename ) : visual = os . environ . get ( 'VISUAL' ) editor = os . environ . get ( 'EDITOR' ) editors = [ visual , editor , '/usr/bin/editor' , '/usr/bin/nano' , '/usr/bin/pico' , '/usr/bin/vi' , '/usr/bin/emacs' , ] for e in editors : if e : try : returncode = subprocess . call ( shlex . split ( e ) + [ filename ] ) return returncode == 0 except OSError : pass return False
Call editor executable .
18,384
def lines ( self ) : if self . _cache . lines is None : self . _cache . lines = _ImmutableLineList ( self . text . split ( '\n' ) ) return self . _cache . lines
Array of all the lines .
18,385
def _line_start_indexes ( self ) : if self . _cache . line_indexes is None : line_lengths = map ( len , self . lines ) indexes = [ 0 ] append = indexes . append pos = 0 for line_length in line_lengths : pos += line_length + 1 append ( pos ) if len ( indexes ) > 1 : indexes . pop ( ) self . _cache . line_indexes = indexes return self . _cache . line_indexes
Array pointing to the start indexes of all the lines .
18,386
def leading_whitespace_in_current_line ( self ) : current_line = self . current_line length = len ( current_line ) - len ( current_line . lstrip ( ) ) return current_line [ : length ]
The leading whitespace in the left margin of the current line .
18,387
def _find_line_start_index ( self , index ) : indexes = self . _line_start_indexes pos = bisect . bisect_right ( indexes , index ) - 1 return pos , indexes [ pos ]
For the index of a character at a certain line calculate the index of the first character on that line .
18,388
def has_match_at_current_position ( self , sub ) : return self . text . find ( sub , self . cursor_position ) == self . cursor_position
True when this substring is found at the cursor position .
18,389
def find ( self , sub , in_current_line = False , include_current_position = False , ignore_case = False , count = 1 ) : assert isinstance ( ignore_case , bool ) if in_current_line : text = self . current_line_after_cursor else : text = self . text_after_cursor if not include_current_position : if len ( text ) == 0 : return else : text = text [ 1 : ] flags = re . IGNORECASE if ignore_case else 0 iterator = re . finditer ( re . escape ( sub ) , text , flags ) try : for i , match in enumerate ( iterator ) : if i + 1 == count : if include_current_position : return match . start ( 0 ) else : return match . start ( 0 ) + 1 except StopIteration : pass
Find text after the cursor return position relative to the cursor position . Return None if nothing was found .
18,390
def find_all ( self , sub , ignore_case = False ) : flags = re . IGNORECASE if ignore_case else 0 return [ a . start ( ) for a in re . finditer ( re . escape ( sub ) , self . text , flags ) ]
Find all occurances of the substring . Return a list of absolute positions in the document .
18,391
def find_backwards ( self , sub , in_current_line = False , ignore_case = False , count = 1 ) : if in_current_line : before_cursor = self . current_line_before_cursor [ : : - 1 ] else : before_cursor = self . text_before_cursor [ : : - 1 ] flags = re . IGNORECASE if ignore_case else 0 iterator = re . finditer ( re . escape ( sub [ : : - 1 ] ) , before_cursor , flags ) try : for i , match in enumerate ( iterator ) : if i + 1 == count : return - match . start ( 0 ) - len ( sub ) except StopIteration : pass
Find text before the cursor return position relative to the cursor position . Return None if nothing was found .
18,392
def get_word_before_cursor ( self , WORD = False ) : if self . text_before_cursor [ - 1 : ] . isspace ( ) : return '' else : return self . text_before_cursor [ self . find_start_of_previous_word ( WORD = WORD ) : ]
Give the word before the cursor . If we have whitespace before the cursor this returns an empty string .
18,393
def get_word_under_cursor ( self , WORD = False ) : start , end = self . find_boundaries_of_current_word ( WORD = WORD ) return self . text [ self . cursor_position + start : self . cursor_position + end ]
Return the word currently below the cursor . This returns an empty string when the cursor is on a whitespace region .
18,394
def find_next_word_beginning ( self , count = 1 , WORD = False ) : if count < 0 : return self . find_previous_word_beginning ( count = - count , WORD = WORD ) regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE iterator = regex . finditer ( self . text_after_cursor ) try : for i , match in enumerate ( iterator ) : if i == 0 and match . start ( 1 ) == 0 : count += 1 if i + 1 == count : return match . start ( 1 ) except StopIteration : pass
Return an index relative to the cursor position pointing to the start of the next word . Return None if nothing was found .
18,395
def find_next_word_ending ( self , include_current_position = False , count = 1 , WORD = False ) : if count < 0 : return self . find_previous_word_ending ( count = - count , WORD = WORD ) if include_current_position : text = self . text_after_cursor else : text = self . text_after_cursor [ 1 : ] regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE iterable = regex . finditer ( text ) try : for i , match in enumerate ( iterable ) : if i + 1 == count : value = match . end ( 1 ) if include_current_position : return value else : return value + 1 except StopIteration : pass
Return an index relative to the cursor position pointing to the end of the next word . Return None if nothing was found .
18,396
def find_previous_word_ending ( self , count = 1 , WORD = False ) : if count < 0 : return self . find_next_word_ending ( count = - count , WORD = WORD ) text_before_cursor = self . text_after_cursor [ : 1 ] + self . text_before_cursor [ : : - 1 ] regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE iterator = regex . finditer ( text_before_cursor ) try : for i , match in enumerate ( iterator ) : if i == 0 and match . start ( 1 ) == 0 : count += 1 if i + 1 == count : return - match . start ( 1 ) + 1 except StopIteration : pass
Return an index relative to the cursor position pointing to the end of the previous word . Return None if nothing was found .
18,397
def find_next_matching_line ( self , match_func , count = 1 ) : result = None for index , line in enumerate ( self . lines [ self . cursor_position_row + 1 : ] ) : if match_func ( line ) : result = 1 + index count -= 1 if count == 0 : break return result
Look downwards for empty lines . Return the line index relative to the current line .
18,398
def get_cursor_left_position ( self , count = 1 ) : if count < 0 : return self . get_cursor_right_position ( - count ) return - min ( self . cursor_position_col , count )
Relative position for cursor left .
18,399
def get_cursor_right_position ( self , count = 1 ) : if count < 0 : return self . get_cursor_left_position ( - count ) return min ( count , len ( self . current_line_after_cursor ) )
Relative position for cursor_right .