idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
18,500
def append_to_arg_count ( self , data ) : assert data in '-0123456789' current = self . _arg if data == '-' : assert current is None or current == '-' result = data elif current is None : result = data else : result = "%s%s" % ( current , data ) self . input_processor . arg = result
Add digit to the input argument .
18,501
def _get_keys ( self , read , input_records ) : for i in range ( read . value ) : ir = input_records [ i ] if ir . EventType in EventTypes : ev = getattr ( ir . Event , EventTypes [ ir . EventType ] ) if type ( ev ) == KEY_EVENT_RECORD and ev . KeyDown : for key_press in self . _event_to_key_presses ( ev ) : yield key_...
Generator that yields KeyPress objects from the input records .
18,502
def _event_to_key_presses ( self , ev ) : assert type ( ev ) == KEY_EVENT_RECORD and ev . KeyDown result = None u_char = ev . uChar . UnicodeChar ascii_char = u_char . encode ( 'utf-8' ) if u_char == '\x00' : if ev . VirtualKeyCode in self . keycodes : result = KeyPress ( self . keycodes [ ev . VirtualKeyCode ] , '' ) ...
For this KEY_EVENT_RECORD return a list of KeyPress instances .
18,503
def _handle_mouse ( self , ev ) : FROM_LEFT_1ST_BUTTON_PRESSED = 0x1 result = [ ] if ev . ButtonState == FROM_LEFT_1ST_BUTTON_PRESSED : for event_type in [ MouseEventType . MOUSE_DOWN , MouseEventType . MOUSE_UP ] : data = ';' . join ( [ event_type , str ( ev . MousePosition . X ) , str ( ev . MousePosition . Y ) ] ) r...
Handle mouse events . Return a list of KeyPress instances .
18,504
def tokenize_regex ( input ) : p = re . compile ( r , re . VERBOSE ) tokens = [ ] while input : m = p . match ( input ) if m : token , input = input [ : m . end ( ) ] , input [ m . end ( ) : ] if not token . isspace ( ) : tokens . append ( token ) else : raise Exception ( 'Could not tokenize input regex.' ) return toke...
Takes a string representing a regular expression as input and tokenizes it .
18,505
def parse_regex ( regex_tokens ) : tokens = [ ')' ] + regex_tokens [ : : - 1 ] def wrap ( lst ) : if len ( lst ) == 1 : return lst [ 0 ] else : return Sequence ( lst ) def _parse ( ) : or_list = [ ] result = [ ] def wrapped_result ( ) : if or_list == [ ] : return wrap ( result ) else : or_list . append ( result ) retur...
Takes a list of tokens from the tokenizer and returns a parse tree .
18,506
def _divide_heigths ( self , cli , write_position ) : if not self . children : return [ ] given_dimensions = self . get_dimensions ( cli ) if self . get_dimensions else None def get_dimension_for_child ( c , index ) : if given_dimensions and given_dimensions [ index ] is not None : return given_dimensions [ index ] els...
Return the heights for all rows . Or None when there is not enough space .
18,507
def _divide_widths ( self , cli , width ) : if not self . children : return [ ] given_dimensions = self . get_dimensions ( cli ) if self . get_dimensions else None def get_dimension_for_child ( c , index ) : if given_dimensions and given_dimensions [ index ] is not None : return given_dimensions [ index ] else : return...
Return the widths for all columns . Or None when there is not enough space .
18,508
def input_line_to_visible_line ( self ) : result = { } for k , v in self . visible_line_to_input_line . items ( ) : if v in result : result [ v ] = min ( result [ v ] , k ) else : result [ v ] = k return result
Return the dictionary mapping the line numbers of the input buffer to the lines of the screen . When a line spans several rows at the screen the first row appears in the dictionary .
18,509
def last_visible_line ( self , before_scroll_offset = False ) : if before_scroll_offset : return self . displayed_lines [ - 1 - self . applied_scroll_offsets . bottom ] else : return self . displayed_lines [ - 1 ]
Like first_visible_line but for the last visible line .
18,510
def center_visible_line ( self , before_scroll_offset = False , after_scroll_offset = False ) : return ( self . first_visible_line ( after_scroll_offset ) + ( self . last_visible_line ( before_scroll_offset ) - self . first_visible_line ( after_scroll_offset ) ) // 2 )
Like first_visible_line but for the center visible line .
18,511
def _merge_dimensions ( dimension , preferred = None , dont_extend = False ) : dimension = dimension or LayoutDimension ( ) if dimension . preferred_specified : preferred = dimension . preferred if preferred is not None : if dimension . max : preferred = min ( preferred , dimension . max ) if dimension . min : preferre...
Take the LayoutDimension from this Window class and the received preferred size from the UIControl and return a LayoutDimension to report to the parent container .
18,512
def _get_ui_content ( self , cli , width , height ) : def get_content ( ) : return self . content . create_content ( cli , width = width , height = height ) key = ( cli . render_counter , width , height ) return self . _ui_content_cache . get ( key , get_content )
Create a UIContent instance .
18,513
def _get_digraph_char ( self , cli ) : " Return `False`, or the Digraph symbol to be used. " if cli . quoted_insert : return '^' if cli . vi_state . waiting_for_digraph : if cli . vi_state . digraph_symbol1 : return cli . vi_state . digraph_symbol1 return '?' return False
Return False or the Digraph symbol to be used .
18,514
def _highlight_digraph ( self , cli , new_screen ) : digraph_char = self . _get_digraph_char ( cli ) if digraph_char : cpos = new_screen . cursor_position new_screen . data_buffer [ cpos . y ] [ cpos . x ] = _CHAR_CACHE [ digraph_char , Token . Digraph ]
When we are in Vi digraph mode put a question mark underneath the cursor .
18,515
def _show_input_processor_key_buffer ( self , cli , new_screen ) : key_buffer = cli . input_processor . key_buffer if key_buffer and _in_insert_mode ( cli ) and not cli . is_done : data = key_buffer [ - 1 ] . data if get_cwidth ( data ) == 1 : cpos = new_screen . cursor_position new_screen . data_buffer [ cpos . y ] [ ...
When the user is typing a key binding that consists of several keys display the last pressed key if the user is in insert mode and the key is meaningful to be displayed . E . g . Some people want to bind jj to escape in Vi insert mode . But the first j needs to be displayed in order to get some feedback .
18,516
def _copy_margin ( self , cli , lazy_screen , new_screen , write_position , move_x , width ) : xpos = write_position . xpos + move_x ypos = write_position . ypos margin_write_position = WritePosition ( xpos , ypos , width , write_position . height ) self . _copy_body ( cli , lazy_screen , new_screen , margin_write_posi...
Copy characters from the margin screen to the real screen .
18,517
def _mouse_handler ( self , cli , mouse_event ) : if mouse_event . event_type == MouseEventType . SCROLL_DOWN : self . _scroll_down ( cli ) elif mouse_event . event_type == MouseEventType . SCROLL_UP : self . _scroll_up ( cli )
Mouse handler . Called when the UI control doesn t handle this particular event .
18,518
def _scroll_up ( self , cli ) : " Scroll window up. " info = self . render_info if info . vertical_scroll > 0 : if info . cursor_position . y >= info . window_height - 1 - info . configured_scroll_offsets . bottom : self . content . move_cursor_up ( cli ) self . vertical_scroll -= 1
Scroll window up .
18,519
def update ( self , key_vals = None , overwrite = True ) : if not key_vals : return write_items = self . _update ( key_vals , overwrite ) self . _root . _root_set ( self . _path , write_items ) self . _root . _write ( commit = True )
Locked keys will be overwritten unless overwrite = False .
18,520
def _encode ( self , value , path_from_root ) : if isinstance ( value , dict ) : json_value = { } for key , value in six . iteritems ( value ) : json_value [ key ] = self . _encode ( value , path_from_root + ( key , ) ) return json_value else : path = "." . join ( path_from_root ) if util . is_pandas_data_frame ( value...
Normalize compress and encode sub - objects for backend storage .
18,521
def scroll_one_line_down ( event ) : w = find_window_for_buffer_name ( event . cli , event . cli . current_buffer_name ) b = event . cli . current_buffer if w : if w . render_info : info = w . render_info if w . vertical_scroll < info . content_height - info . window_height : if info . cursor_position . y <= info . con...
scroll_offset + = 1
18,522
def scroll_one_line_up ( event ) : w = find_window_for_buffer_name ( event . cli , event . cli . current_buffer_name ) b = event . cli . current_buffer if w : if w . render_info : info = w . render_info if w . vertical_scroll > 0 : first_line_height = info . get_height_for_line ( info . first_visible_line ( ) ) cursor_...
scroll_offset - = 1
18,523
def create_content ( self , cli , width , height ) : complete_state = cli . current_buffer . complete_state if complete_state : completions = complete_state . current_completions index = complete_state . complete_index menu_width = self . _get_menu_width ( width , complete_state ) menu_meta_width = self . _get_menu_met...
Create a UIContent object for this control .
18,524
def _get_menu_width ( self , max_width , complete_state ) : return min ( max_width , max ( self . MIN_WIDTH , max ( get_cwidth ( c . display ) for c in complete_state . current_completions ) + 2 ) )
Return the width of the main column .
18,525
def _get_menu_meta_width ( self , max_width , complete_state ) : if self . _show_meta ( complete_state ) : return min ( max_width , max ( get_cwidth ( c . display_meta ) for c in complete_state . current_completions ) + 2 ) else : return 0
Return the width of the meta column .
18,526
def create_content ( self , cli , width , height ) : complete_state = cli . current_buffer . complete_state column_width = self . _get_column_width ( complete_state ) self . _render_pos_to_completion = { } def grouper ( n , iterable , fillvalue = None ) : " grouper(3, 'ABCDEFG', 'x') args = [ iter ( iterable ) ] * n r...
Create a UIContent object for this menu .
18,527
def _get_column_width ( self , complete_state ) : return max ( get_cwidth ( c . display ) for c in complete_state . current_completions ) + 1
Return the width of each column .
18,528
def mouse_handler ( self , cli , mouse_event ) : b = cli . current_buffer def scroll_left ( ) : b . complete_previous ( count = self . _rendered_rows , disable_wrap_around = True ) self . scroll = max ( 0 , self . scroll - 1 ) def scroll_right ( ) : b . complete_next ( count = self . _rendered_rows , disable_wrap_aroun...
Handle scoll and click events .
18,529
def preferred_width ( self , cli , max_available_width ) : if cli . current_buffer . complete_state : state = cli . current_buffer . complete_state return 2 + max ( get_cwidth ( c . display_meta ) for c in state . current_completions ) else : return 0
Report the width of the longest meta text as the preferred width of this control .
18,530
def set_text ( self , text ) : assert isinstance ( text , six . string_types ) self . set_data ( ClipboardData ( text ) )
Shortcut for setting plain text on clipboard .
18,531
def reset ( self ) : self . counter += 1 local_counter = self . counter def timer_timeout ( ) : if self . counter == local_counter and self . running : self . callback ( ) self . loop . call_later ( self . timeout , timer_timeout )
Reset the timeout . Starts a new timer .
18,532
def sentry_reraise ( exc ) : sentry_exc ( exc ) six . reraise ( type ( exc ) , exc , sys . exc_info ( ) [ 2 ] )
Re - raise an exception after logging it to Sentry
18,533
def vendor_import ( name ) : parent_dir = os . path . abspath ( os . path . dirname ( __file__ ) ) vendor_dir = os . path . join ( parent_dir , 'vendor' ) sys . path . insert ( 1 , vendor_dir ) return import_module ( name )
This enables us to use the vendor directory for packages we don t depend on
18,534
def ensure_matplotlib_figure ( obj ) : import matplotlib from matplotlib . figure import Figure if obj == matplotlib . pyplot : obj = obj . gcf ( ) elif not isinstance ( obj , Figure ) : if hasattr ( obj , "figure" ) : obj = obj . figure if not isinstance ( obj , Figure ) : raise ValueError ( "Only matplotlib.pyplot or...
Extract the current figure from a matplotlib object or return the object if it s a figure . raises ValueError if the object can t be converted .
18,535
def json_friendly ( obj ) : converted = True typename = get_full_typename ( obj ) if is_tf_tensor_typename ( typename ) : obj = obj . eval ( ) elif is_pytorch_tensor_typename ( typename ) : try : if obj . requires_grad : obj = obj . detach ( ) except AttributeError : pass try : obj = obj . data except RuntimeError : pa...
Convert an object into something that s more becoming of JSON
18,536
def launch_browser ( attempt_launch_browser = True ) : _DISPLAY_VARIABLES = [ 'DISPLAY' , 'WAYLAND_DISPLAY' , 'MIR_SOCKET' ] _WEBBROWSER_NAMES_BLACKLIST = [ 'www-browser' , 'lynx' , 'links' , 'elinks' , 'w3m' ] import webbrowser launch_browser = attempt_launch_browser if launch_browser : if ( 'linux' in sys . platform ...
Decide if we should launch a browser
18,537
def parse_tfjob_config ( ) : if os . getenv ( "TF_CONFIG" ) : try : return json . loads ( os . environ [ "TF_CONFIG" ] ) except ValueError : return False else : return False
Attempts to parse TFJob config returning False if it can t find it
18,538
def parse_sm_config ( ) : sagemaker_config = "/opt/ml/input/config/hyperparameters.json" if os . path . exists ( sagemaker_config ) : conf = { } conf [ "sagemaker_training_job_name" ] = os . getenv ( 'TRAINING_JOB_NAME' ) for k , v in six . iteritems ( json . load ( open ( sagemaker_config ) ) ) : cast = v . strip ( '"...
Attempts to parse SageMaker configuration returning False if it can t find it
18,539
def write_netrc ( host , entity , key ) : if len ( key ) != 40 : click . secho ( 'API-key must be exactly 40 characters long: {} ({} chars)' . format ( key , len ( key ) ) ) return None try : normalized_host = host . split ( "/" ) [ - 1 ] . split ( ":" ) [ 0 ] print ( "Appending key for %s to your netrc file: %s" % ( n...
Add our host and key to . netrc
18,540
def request_with_retry ( func , * args , ** kwargs ) : max_retries = kwargs . pop ( 'max_retries' , 30 ) sleep = 2 retry_count = 0 while True : try : response = func ( * args , ** kwargs ) response . raise_for_status ( ) return response except ( requests . exceptions . ConnectionError , requests . exceptions . HTTPErro...
Perform a requests http call retrying with exponential backoff .
18,541
def find_runner ( program ) : if os . path . isfile ( program ) and not os . access ( program , os . X_OK ) : try : opened = open ( program ) except PermissionError : return None first_line = opened . readline ( ) . strip ( ) if first_line . startswith ( '#!' ) : return shlex . split ( first_line [ 2 : ] ) if program ....
Return a command that will run program .
18,542
def downsample ( values , target_length ) : assert target_length > 1 values = list ( values ) if len ( values ) < target_length : return values ratio = float ( len ( values ) - 1 ) / ( target_length - 1 ) result = [ ] for i in range ( target_length ) : result . append ( values [ int ( i * ratio ) ] ) return result
Downsamples 1d values to target_length including start and end .
18,543
def image_from_docker_args ( args ) : bool_args = [ "-t" , "--tty" , "--rm" , "--privileged" , "--oom-kill-disable" , "--no-healthcheck" , "-i" , "--interactive" , "--init" , "--help" , "--detach" , "-d" , "--sig-proxy" , "-it" , "-itd" ] last_flag = - 2 last_arg = "" possible_images = [ ] if len ( args ) > 0 and args ...
This scans docker run args and attempts to find the most likely docker image argument . If excludes any argments that start with a dash and the argument after it if it isn t a boolean switch . This can be improved we currently fallback gracefully when this fails .
18,544
def load_yaml ( file ) : if hasattr ( yaml , "full_load" ) : return yaml . full_load ( file ) else : return yaml . load ( file )
If pyyaml > 5 . 1 use full_load to avoid warning
18,545
def image_id_from_k8s ( ) : token_path = "/var/run/secrets/kubernetes.io/serviceaccount/token" if os . path . exists ( token_path ) : k8s_server = "https://{}:{}/api/v1/namespaces/default/pods/{}" . format ( os . getenv ( "KUBERNETES_SERVICE_HOST" ) , os . getenv ( "KUBERNETES_PORT_443_TCP_PORT" ) , os . getenv ( "HOST...
Pings the k8s metadata service for the image id
18,546
def stopwatch_now ( ) : if six . PY2 : now = time . time ( ) else : now = time . monotonic ( ) return now
Get a timevalue for interval comparisons
18,547
def focus ( self , cli , buffer_name ) : assert isinstance ( buffer_name , six . text_type ) self . focus_stack = [ buffer_name ]
Focus the buffer with the given name .
18,548
def push_focus ( self , cli , buffer_name ) : assert isinstance ( buffer_name , six . text_type ) self . focus_stack . append ( buffer_name )
Push buffer on the focus stack .
18,549
def pop_focus ( self , cli ) : if len ( self . focus_stack ) > 1 : self . focus_stack . pop ( ) else : raise IndexError ( 'Cannot pop last item from the focus stack.' )
Pop buffer from the focus stack .
18,550
def read ( self , size = - 1 ) : bites = self . file . read ( size ) self . bytes_read += len ( bites ) self . callback ( len ( bites ) , self . bytes_read ) return bites
Read bytes and call the callback
18,551
def on_train_begin ( self , ** kwargs ) : "Call watch method to log model topology, gradients & weights" super ( ) . on_train_begin ( ) if not WandbCallback . watch_called : WandbCallback . watch_called = True wandb . watch ( self . learn . model , log = self . log )
Call watch method to log model topology gradients & weights
18,552
def on_epoch_end ( self , epoch , smooth_loss , last_metrics , ** kwargs ) : "Logs training loss, validation loss and custom metrics & log prediction samples & save model" if self . save_model : current = self . get_monitor_value ( ) if current is not None and self . operator ( current , self . best ) : print ( f'Bette...
Logs training loss validation loss and custom metrics & log prediction samples & save model
18,553
def column ( self , key ) : for row in self . rows : if key in row : yield row [ key ]
Iterator over a given column skipping steps that don t have that key
18,554
def add ( self , row = { } , step = None ) : if not isinstance ( row , collections . Mapping ) : raise wandb . Error ( 'history.add expects dict-like object' ) if step is None : self . update ( row ) if not self . batched : self . _write ( ) else : if not isinstance ( step , numbers . Integral ) : raise wandb . Error (...
Adds or updates a history step .
18,555
def update ( self , new_vals ) : for k , v in six . iteritems ( new_vals ) : k = k . strip ( ) if k in self . row : warnings . warn ( "Adding history key ({}) that is already set in this step" . format ( k ) , wandb . WandbWarning ) self . row [ k ] = v
Add a dictionary of values to the current step without writing it to disk .
18,556
def step ( self , compute = True ) : if self . batched : raise wandb . Error ( "Nested History step contexts aren't supported" ) self . batched = True self . compute = compute yield self if compute : self . _write ( ) compute = True
Context manager to gradually build a history row then commit it at the end .
18,557
def _index ( self , row ) : self . rows . append ( row ) self . _keys . update ( row . keys ( ) ) self . _steps += 1
Add a row to the internal list of rows without writing it to disk .
18,558
def wandb_pty ( resize = True ) : master_fd , slave_fd = pty . openpty ( ) try : tty . setraw ( master_fd ) except termios . error : pass if resize : if SIGWINCH_HANDLER is not None : SIGWINCH_HANDLER . add_fd ( master_fd ) return master_fd , slave_fd
Get a PTY set to raw mode and registered to hear about window size changes .
18,559
def spawn_reader_writer ( get_data_fn , put_data_fn ) : def _reader_thread ( ) : while True : out = get_data_fn ( ) put_data_fn ( out ) if not out : break t = threading . Thread ( target = _reader_thread ) t . daemon = True t . start ( ) return t
Spawn a thread that reads from a data source and writes to a sink .
18,560
def restore ( self ) : self . redir_file . flush ( ) os . dup2 ( self . orig_file . fileno ( ) , self . _from_fd )
Restore self . redir_file to its original state .
18,561
def negotiate ( self , data ) : command , payload = data [ 0 : 1 ] , data [ 1 : ] assert isinstance ( command , bytes ) if command == NAWS : self . naws ( payload ) else : logger . info ( 'Negotiate (%r got bytes)' , len ( data ) )
Got negotiate data .
18,562
def _parse_coroutine ( self ) : while True : d = yield if d == int2byte ( 0 ) : pass elif d == IAC : d2 = yield if d2 == IAC : self . received_data ( d2 ) elif d2 in ( NOP , DM , BRK , IP , AO , AYT , EC , EL , GA ) : self . command_received ( d2 , None ) elif d2 in ( DO , DONT , WILL , WONT ) : d3 = yield self . comma...
Parser state machine . Every yield expression returns the next byte .
18,563
def feed ( self , data ) : assert isinstance ( data , binary_type ) for b in iterbytes ( data ) : self . _parser . send ( int2byte ( b ) )
Feed data to the parser .
18,564
def create ( cls , api , run_id = None , project = None , username = None ) : run_id = run_id or util . generate_id ( ) project = project or api . settings . get ( "project" ) mutation = gql ( ) variables = { 'entity' : username , 'project' : project , 'name' : run_id } res = api . client . execute ( mutation , variabl...
Create a run for the given project
18,565
def _exec ( self , query , ** kwargs ) : variables = { 'entity' : self . username , 'project' : self . project , 'name' : self . name } variables . update ( kwargs ) return self . client . execute ( query , variable_values = variables )
Execute a query against the cloud backend
18,566
def _get_closest_ansi_color ( r , g , b , exclude = ( ) ) : assert isinstance ( exclude , tuple ) saturation = abs ( r - g ) + abs ( g - b ) + abs ( b - r ) if saturation > 30 : exclude += ( 'ansilightgray' , 'ansidarkgray' , 'ansiwhite' , 'ansiblack' ) distance = 257 * 257 * 3 match = 'ansidefault' for name , ( r2 , g...
Find closest ANSI color . Return it by name .
18,567
def _get_size ( fileno ) : import fcntl import termios buf = array . array ( b'h' if six . PY2 else u'h' , [ 0 , 0 , 0 , 0 ] ) fcntl . ioctl ( fileno , termios . TIOCGWINSZ , buf ) return buf [ 0 ] , buf [ 1 ]
Get the size of this pseudo terminal .
18,568
def _colors_to_code ( self , fg_color , bg_color ) : " Return a tuple with the vt100 values that represent this color. " fg_ansi = [ ( ) ] def get ( color , bg ) : table = BG_ANSI_COLORS if bg else FG_ANSI_COLORS if color is None : return ( ) elif color in table : return ( table [ color ] , ) else : try : rgb = self ....
Return a tuple with the vt100 values that represent this color .
18,569
def set_attributes ( self , attrs ) : if self . true_color ( ) and not self . ansi_colors_only ( ) : self . write_raw ( self . _escape_code_cache_true_color [ attrs ] ) else : self . write_raw ( self . _escape_code_cache [ attrs ] )
Create new style and output .
18,570
def watch ( models , criterion = None , log = "gradients" , log_freq = 100 ) : global watch_called if run is None : raise ValueError ( "You must call `wandb.init` before calling watch" ) if watch_called : raise ValueError ( "You can only call `wandb.watch` once per process. If you want to watch multiple models, pass th...
Hooks into the torch model to collect gradients and the topology . Should be extended to accept arbitrary ML models .
18,571
def restore ( name , run_path = None , replace = False , root = "." ) : if run_path is None and run is None : raise ValueError ( "You must call `wandb.init` before calling restore or specify a run_path" ) api = Api ( ) api_run = api . run ( run_path or run . path ) root = run . dir if run else root path = os . path . e...
Downloads the specified file from cloud storage into the current run directory if it doesn exist .
18,572
def monitor ( options = { } ) : try : from IPython . display import display except ImportError : def display ( stuff ) : return None class Monitor ( ) : def __init__ ( self , options = { } ) : if os . getenv ( "WANDB_JUPYTER" ) : display ( jupyter . Run ( ) ) else : self . rm = False termerror ( "wandb.monitor is only ...
Starts syncing with W&B if you re in Jupyter . Displays your W&B charts live in a Jupyter notebook . It s currently a context manager for legacy reasons .
18,573
def log ( row = None , commit = True , * args , ** kargs ) : if run is None : raise ValueError ( "You must call `wandb.init` in the same process before calling log" ) if row is None : row = { } if commit : run . history . add ( row , * args , ** kargs ) else : run . history . update ( row , * args , ** kargs )
Log a dict to the global run s history . If commit is false enables multiple calls before commiting .
18,574
def reset_env ( exclude = [ ] ) : if os . getenv ( env . INITED ) : wandb_keys = [ key for key in os . environ . keys ( ) if key . startswith ( 'WANDB_' ) and key not in exclude ] for key in wandb_keys : del os . environ [ key ] return True else : return False
Remove environment variables used in Jupyter notebooks
18,575
def try_to_set_up_global_logging ( ) : root = logging . getLogger ( ) root . setLevel ( logging . DEBUG ) formatter = logging . Formatter ( '%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(filename)s:%(funcName)s():%(lineno)s] %(message)s' ) if env . is_debug ( ) : handler = logging . StreamHandler ( ) han...
Try to set up global W&B debug log that gets re - written by every W&B process .
18,576
def sagemaker_auth ( overrides = { } , path = "." ) : api_key = overrides . get ( env . API_KEY , Api ( ) . api_key ) if api_key is None : raise ValueError ( "Can't find W&B ApiKey, set the WANDB_API_KEY env variable or run `wandb login`" ) overrides [ env . API_KEY ] = api_key with open ( os . path . join ( path , "se...
Write a secrets . env file with the W&B ApiKey and any additional secrets passed .
18,577
def style_from_dict ( style_dict , include_defaults = True ) : assert isinstance ( style_dict , Mapping ) if include_defaults : s2 = { } s2 . update ( DEFAULT_STYLE_EXTENSIONS ) s2 . update ( style_dict ) style_dict = s2 token_to_attrs = { } for ttype , styledef in sorted ( style_dict . items ( ) ) : attrs = DEFAULT_AT...
Create a Style instance from a dictionary or other mapping .
18,578
def rename_file ( self , old_save_name , new_save_name , new_path ) : if old_save_name in self . _files : del self . _files [ old_save_name ] self . update_file ( new_save_name , new_path )
This only updates the name and path we use to track the file s size and upload progress . Doesn t rename it on the back end or make us upload from anywhere else .
18,579
def register ( name ) : assert isinstance ( name , six . text_type ) def decorator ( handler ) : assert callable ( handler ) _readline_commands [ name ] = handler return handler return decorator
Store handler in the _readline_commands dictionary .
18,580
def beginning_of_line ( event ) : " Move to the start of the current line. " buff = event . current_buffer buff . cursor_position += buff . document . get_start_of_line_position ( after_whitespace = False )
Move to the start of the current line .
18,581
def end_of_line ( event ) : " Move to the end of the line. " buff = event . current_buffer buff . cursor_position += buff . document . get_end_of_line_position ( )
Move to the end of the line .
18,582
def forward_char ( event ) : " Move forward a character. " buff = event . current_buffer buff . cursor_position += buff . document . get_cursor_right_position ( count = event . arg )
Move forward a character .
18,583
def backward_char ( event ) : " Move back a character. " buff = event . current_buffer buff . cursor_position += buff . document . get_cursor_left_position ( count = event . arg )
Move back a character .
18,584
def forward_word ( event ) : buff = event . current_buffer pos = buff . document . find_next_word_ending ( count = event . arg ) if pos : buff . cursor_position += pos
Move forward to the end of the next word . Words are composed of letters and digits .
18,585
def backward_word ( event ) : buff = event . current_buffer pos = buff . document . find_previous_word_beginning ( count = event . arg ) if pos : buff . cursor_position += pos
Move back to the start of the current or previous word . Words are composed of letters and digits .
18,586
def accept_line ( event ) : " Accept the line regardless of where the cursor is. " b = event . current_buffer b . accept_action . validate_and_handle ( event . cli , b )
Accept the line regardless of where the cursor is .
18,587
def end_of_history ( event ) : event . current_buffer . history_forward ( count = 10 ** 100 ) buff = event . current_buffer buff . go_to_history ( len ( buff . _working_lines ) - 1 )
Move to the end of the input history i . e . the line currently being entered .
18,588
def reverse_search_history ( event ) : event . cli . current_search_state . direction = IncrementalSearchDirection . BACKWARD event . cli . push_focus ( SEARCH_BUFFER )
Search backward starting at the current line and moving up through the history as necessary . This is an incremental search .
18,589
def delete_char ( event ) : " Delete character before the cursor. " deleted = event . current_buffer . delete ( count = event . arg ) if not deleted : event . cli . output . bell ( )
Delete character before the cursor .
18,590
def backward_delete_char ( event ) : " Delete the character behind the cursor. " if event . arg < 0 : deleted = event . current_buffer . delete ( count = - event . arg ) else : deleted = event . current_buffer . delete_before_cursor ( count = event . arg ) if not deleted : event . cli . output . bell ( )
Delete the character behind the cursor .
18,591
def kill_line ( event ) : buff = event . current_buffer if event . arg < 0 : deleted = buff . delete_before_cursor ( count = - buff . document . get_start_of_line_position ( ) ) else : if buff . document . current_char == '\n' : deleted = buff . delete ( 1 ) else : deleted = buff . delete ( count = buff . document . ge...
Kill the text from the cursor to the end of the line .
18,592
def kill_word ( event ) : buff = event . current_buffer pos = buff . document . find_next_word_ending ( count = event . arg ) if pos : deleted = buff . delete ( count = pos ) event . cli . clipboard . set_text ( deleted )
Kill from point to the end of the current word or if between words to the end of the next word . Word boundaries are the same as forward - word .
18,593
def unix_word_rubout ( event , WORD = True ) : buff = event . current_buffer pos = buff . document . find_start_of_previous_word ( count = event . arg , WORD = WORD ) if pos is None : pos = - buff . cursor_position if pos : deleted = buff . delete_before_cursor ( count = - pos ) if event . is_repeat : deleted += event ...
Kill the word behind point using whitespace as a word boundary . Usually bound to ControlW .
18,594
def delete_horizontal_space ( event ) : " Delete all spaces and tabs around point. " buff = event . current_buffer text_before_cursor = buff . document . text_before_cursor text_after_cursor = buff . document . text_after_cursor delete_before = len ( text_before_cursor ) - len ( text_before_cursor . rstrip ( '\t ' ) ) ...
Delete all spaces and tabs around point .
18,595
def unix_line_discard ( event ) : buff = event . current_buffer if buff . document . cursor_position_col == 0 and buff . document . cursor_position > 0 : buff . delete_before_cursor ( count = 1 ) else : deleted = buff . delete_before_cursor ( count = - buff . document . get_start_of_line_position ( ) ) event . cli . cl...
Kill backward from the cursor to the beginning of the current line .
18,596
def yank ( event ) : event . current_buffer . paste_clipboard_data ( event . cli . clipboard . get_data ( ) , count = event . arg , paste_mode = PasteMode . EMACS )
Paste before cursor .
18,597
def yank_last_arg ( event ) : n = ( event . arg if event . arg_present else None ) event . current_buffer . yank_last_arg ( n )
Like yank_nth_arg but if no argument has been given yank the last word of each line .
18,598
def yank_pop ( event ) : buff = event . current_buffer doc_before_paste = buff . document_before_paste clipboard = event . cli . clipboard if doc_before_paste is not None : buff . document = doc_before_paste clipboard . rotate ( ) buff . paste_clipboard_data ( clipboard . get_data ( ) , paste_mode = PasteMode . EMACS )
Rotate the kill ring and yank the new top . Only works following yank or yank - pop .
18,599
def print_last_kbd_macro ( event ) : " Print the last keboard macro. " def print_macro ( ) : for k in event . cli . input_processor . macro : print ( k ) event . cli . run_in_terminal ( print_macro )
Print the last keboard macro .