idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
18,400
def find_enclosing_bracket_right ( self , left_ch , right_ch , end_pos = None ) : if self . current_char == right_ch : return 0 if end_pos is None : end_pos = len ( self . text ) else : end_pos = min ( len ( self . text ) , end_pos ) stack = 1 for i in range ( self . cursor_position + 1 , end_pos ) : c = self . text [ ...
Find the right bracket enclosing current position . Return the relative position to the cursor position .
18,401
def find_enclosing_bracket_left ( self , left_ch , right_ch , start_pos = None ) : if self . current_char == left_ch : return 0 if start_pos is None : start_pos = 0 else : start_pos = max ( 0 , start_pos ) stack = 1 for i in range ( self . cursor_position - 1 , start_pos - 1 , - 1 ) : c = self . text [ i ] if c == righ...
Find the left bracket enclosing current position . Return the relative position to the cursor position .
18,402
def find_matching_bracket_position ( self , start_pos = None , end_pos = None ) : for A , B in '()' , '[]' , '{}' , '<>' : if self . current_char == A : return self . find_enclosing_bracket_right ( A , B , end_pos = end_pos ) or 0 elif self . current_char == B : return self . find_enclosing_bracket_left ( A , B , start...
Return relative cursor position of matching [ ( { or < bracket .
18,403
def get_start_of_line_position ( self , after_whitespace = False ) : if after_whitespace : current_line = self . current_line return len ( current_line ) - len ( current_line . lstrip ( ) ) - self . cursor_position_col else : return - len ( self . current_line_before_cursor )
Relative position for the start of this line .
18,404
def empty_line_count_at_the_end ( self ) : count = 0 for line in self . lines [ : : - 1 ] : if not line or line . isspace ( ) : count += 1 else : break return count
Return number of empty lines at the end of the document .
18,405
def insert_after ( self , text ) : return Document ( text = self . text + text , cursor_position = self . cursor_position , selection = self . selection )
Create a new document with this text inserted after the buffer . It keeps selection ranges and cursor position in sync .
18,406
def insert_before ( self , text ) : selection_state = self . selection if selection_state : selection_state = SelectionState ( original_cursor_position = selection_state . original_cursor_position + len ( text ) , type = selection_state . type ) return Document ( text = text + self . text , cursor_position = self . cur...
Create a new document with this text inserted before the buffer . It keeps selection ranges and cursor position in sync .
18,407
def load_key_bindings ( get_search_state = None , enable_abort_and_exit_bindings = False , enable_system_bindings = False , enable_search = False , enable_open_in_editor = False , enable_extra_page_navigation = False , enable_auto_suggest_bindings = False ) : assert get_search_state is None or callable ( get_search_sta...
Create a Registry object that contains the default key bindings .
18,408
def load_key_bindings_for_prompt ( ** kw ) : kw . setdefault ( 'enable_abort_and_exit_bindings' , True ) kw . setdefault ( 'enable_search' , True ) kw . setdefault ( 'enable_auto_suggest_bindings' , True ) return load_key_bindings ( ** kw )
Create a Registry object with the defaults key bindings for an input prompt .
18,409
def _split_multiline_prompt ( get_prompt_tokens ) : def has_before_tokens ( cli ) : for token , char in get_prompt_tokens ( cli ) : if '\n' in char : return True return False def before ( cli ) : result = [ ] found_nl = False for token , char in reversed ( explode_tokens ( get_prompt_tokens ( cli ) ) ) : if found_nl : ...
Take a get_prompt_tokens function and return three new functions instead . One that tells whether this prompt consists of multiple lines ; one that returns the tokens to be shown on the lines above the input ; and another one with the tokens to be shown at the first line of the input .
18,410
def prompt ( message = '' , ** kwargs ) : patch_stdout = kwargs . pop ( 'patch_stdout' , False ) return_asyncio_coroutine = kwargs . pop ( 'return_asyncio_coroutine' , False ) true_color = kwargs . pop ( 'true_color' , False ) refresh_interval = kwargs . pop ( 'refresh_interval' , 0 ) eventloop = kwargs . pop ( 'eventl...
Get input from the user and return it .
18,411
def run_application ( application , patch_stdout = False , return_asyncio_coroutine = False , true_color = False , refresh_interval = 0 , eventloop = None ) : assert isinstance ( application , Application ) if return_asyncio_coroutine : eventloop = create_asyncio_eventloop ( ) else : eventloop = eventloop or create_eve...
Run a prompt toolkit application .
18,412
def _create_ansi_color_dict ( color_cls ) : " Create a table that maps the 16 named ansi colors to their Windows code. " return { 'ansidefault' : color_cls . BLACK , 'ansiblack' : color_cls . BLACK , 'ansidarkgray' : color_cls . BLACK | color_cls . INTENSITY , 'ansilightgray' : color_cls . GRAY , 'ansiwhite' : color_cl...
Create a table that maps the 16 named ansi colors to their Windows code .
18,413
def _winapi ( self , func , * a , ** kw ) : self . flush ( ) if _DEBUG_RENDER_OUTPUT : self . LOG . write ( ( '%r' % func . __name__ ) . encode ( 'utf-8' ) + b'\n' ) self . LOG . write ( b' ' + ', ' . join ( [ '%r' % i for i in a ] ) . encode ( 'utf-8' ) + b'\n' ) self . LOG . write ( b' ' + ', ' . join ( [ '%r...
Flush and call win API function .
18,414
def get_win32_screen_buffer_info ( self ) : self . flush ( ) sbinfo = CONSOLE_SCREEN_BUFFER_INFO ( ) success = windll . kernel32 . GetConsoleScreenBufferInfo ( self . hconsole , byref ( sbinfo ) ) if success : return sbinfo else : raise NoConsoleScreenBufferError
Return Screen buffer info .
18,415
def enter_alternate_screen ( self ) : if not self . _in_alternate_screen : GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 handle = self . _winapi ( windll . kernel32 . CreateConsoleScreenBuffer , GENERIC_READ | GENERIC_WRITE , DWORD ( 0 ) , None , DWORD ( 1 ) , None ) self . _winapi ( windll . kernel32 . SetConso...
Go to alternate screen buffer .
18,416
def quit_alternate_screen ( self ) : if self . _in_alternate_screen : stdout = self . _winapi ( windll . kernel32 . GetStdHandle , STD_OUTPUT_HANDLE ) self . _winapi ( windll . kernel32 . SetConsoleActiveScreenBuffer , stdout ) self . _winapi ( windll . kernel32 . CloseHandle , self . hconsole ) self . hconsole = stdou...
Make stdout again the active buffer .
18,417
def win32_refresh_window ( cls ) : handle = windll . kernel32 . GetConsoleWindow ( ) RDW_INVALIDATE = 0x0001 windll . user32 . RedrawWindow ( handle , None , None , c_uint ( RDW_INVALIDATE ) )
Call win32 API to refresh the whole Window .
18,418
def _build_color_table ( ) : FG = FOREGROUND_COLOR BG = BACKROUND_COLOR return [ ( 0x00 , 0x00 , 0x00 , FG . BLACK , BG . BLACK ) , ( 0x00 , 0x00 , 0xaa , FG . BLUE , BG . BLUE ) , ( 0x00 , 0xaa , 0x00 , FG . GREEN , BG . GREEN ) , ( 0x00 , 0xaa , 0xaa , FG . CYAN , BG . CYAN ) , ( 0xaa , 0x00 , 0x00 , FG . RED , BG . ...
Build an RGB - to - 256 color conversion table
18,419
def log_tensor_stats ( self , tensor , name ) : if ( isinstance ( tensor , tuple ) or isinstance ( tensor , list ) ) : while ( isinstance ( tensor , tuple ) or isinstance ( tensor , list ) ) and ( isinstance ( tensor [ 0 ] , tuple ) or isinstance ( tensor [ 0 ] , list ) ) : tensor = [ item for sublist in tensor for ite...
Add distribution statistics on a tensor s elements to the current History entry
18,420
def get_height_for_line ( self , lineno , width ) : try : return self . _line_heights [ lineno , width ] except KeyError : text = token_list_to_text ( self . get_line ( lineno ) ) result = self . get_height_for_text ( text , width ) self . _line_heights [ lineno , width ] = result return result
Return the height that a given line would need if it is rendered in a space with the given width .
18,421
def preferred_width ( self , cli , max_available_width ) : text = token_list_to_text ( self . _get_tokens_cached ( cli ) ) line_lengths = [ get_cwidth ( l ) for l in text . split ( '\n' ) ] return max ( line_lengths )
Return the preferred width for this control . That is the width of the longest line .
18,422
def mouse_handler ( self , cli , mouse_event ) : if self . _tokens : tokens_for_line = list ( split_lines ( self . _tokens ) ) try : tokens = tokens_for_line [ mouse_event . position . y ] except IndexError : return NotImplemented else : xpos = mouse_event . position . x count = 0 for item in tokens : count += len ( it...
Handle mouse events .
18,423
def _get_tokens_for_line_func ( self , cli , document ) : def get_tokens_for_line ( ) : return self . lexer . lex_document ( cli , document ) return self . _token_cache . get ( document . text , get_tokens_for_line )
Create a function that returns the tokens for a given line .
18,424
def create_content ( self , cli , width , height ) : buffer = self . _buffer ( cli ) def preview_now ( ) : return bool ( self . preview_search ( cli ) and cli . buffers [ self . search_buffer_name ] . text ) if preview_now ( ) : if self . get_search_state : ss = self . get_search_state ( cli ) else : ss = cli . search_...
Create a UIContent .
18,425
def mouse_handler ( self , cli , mouse_event ) : buffer = self . _buffer ( cli ) position = mouse_event . position if self . has_focus ( cli ) : if self . _last_get_processed_line : processed_line = self . _last_get_processed_line ( position . y ) xpos = processed_line . display_to_source ( position . x ) index = buffe...
Mouse handler for this control .
18,426
def _get_arg_tokens ( cli ) : arg = cli . input_processor . arg return [ ( Token . Prompt . Arg , '(arg: ' ) , ( Token . Prompt . Arg . Text , str ( arg ) ) , ( Token . Prompt . Arg , ') ' ) , ]
Tokens for the arg - prompt .
18,427
def from_message ( cls , message = '> ' ) : assert isinstance ( message , text_type ) def get_message_tokens ( cli ) : return [ ( Token . Prompt , message ) ] return cls ( get_message_tokens )
Create a default prompt with a static message text .
18,428
def write_jsonl_file ( fname , data ) : if not isinstance ( data , list ) : print ( 'warning: malformed json data for file' , fname ) return with open ( fname , 'w' ) as of : for row in data : if row . strip ( ) : of . write ( '%s\n' % row . strip ( ) )
Writes a jsonl file .
18,429
def received_winch ( self ) : def process_winch ( ) : if self . _callbacks : self . _callbacks . terminal_size_changed ( ) self . call_from_executor ( process_winch )
Notify the event loop that SIGWINCH has been received
18,430
def add_reader ( self , fd , callback ) : " Add read file descriptor to the event loop. " fd = fd_to_int ( fd ) self . _read_fds [ fd ] = callback self . selector . register ( fd )
Add read file descriptor to the event loop .
18,431
def remove_reader ( self , fd ) : " Remove read file descriptor from the event loop. " fd = fd_to_int ( fd ) if fd in self . _read_fds : del self . _read_fds [ fd ] self . selector . unregister ( fd )
Remove read file descriptor from the event loop .
18,432
def memoized ( maxsize = 1024 ) : cache = SimpleCache ( maxsize = maxsize ) def decorator ( obj ) : @ wraps ( obj ) def new_callable ( * a , ** kw ) : def create_new ( ) : return obj ( * a , ** kw ) key = ( a , tuple ( kw . items ( ) ) ) return cache . get ( key , create_new ) return new_callable return decorator
Momoization decorator for immutable classes and pure functions .
18,433
def get ( self , key , getter_func ) : try : return self . _data [ key ] except KeyError : value = getter_func ( ) self . _data [ key ] = value self . _keys . append ( key ) if len ( self . _data ) > self . maxsize : key_to_remove = self . _keys . popleft ( ) if key_to_remove in self . _data : del self . _data [ key_to...
Get object from the cache . If not found call getter_func to resolve it and put that on the top of the cache instead .
18,434
def add_binding ( self , * keys , ** kwargs ) : filter = to_cli_filter ( kwargs . pop ( 'filter' , True ) ) eager = to_cli_filter ( kwargs . pop ( 'eager' , False ) ) save_before = kwargs . pop ( 'save_before' , lambda e : True ) to_cli_filter ( kwargs . pop ( 'invalidate_ui' , True ) ) assert not kwargs assert keys as...
Decorator for annotating key bindings .
18,435
def remove_binding ( self , function ) : assert callable ( function ) for b in self . key_bindings : if b . handler == function : self . key_bindings . remove ( b ) self . _clear_cache ( ) return raise ValueError ( 'Binding not found: %r' % ( function , ) )
Remove a key binding .
18,436
def _update_cache ( self ) : " If the original registry was changed. Update our copy version. " expected_version = ( self . registry . _version , self . _extra_registry . _version ) if self . _last_version != expected_version : registry2 = Registry ( ) for reg in ( self . registry , self . _extra_registry ) : for b in ...
If the original registry was changed . Update our copy version .
18,437
def _update_cache ( self ) : expected_version = ( tuple ( r . _version for r in self . registries ) + ( self . _extra_registry . _version , ) ) if self . _last_version != expected_version : registry2 = Registry ( ) for reg in self . registries : registry2 . key_bindings . extend ( reg . key_bindings ) registry2 . key_b...
If one of the original registries was changed . Update our merged version .
18,438
def nest ( thing ) : tfutil = util . get_module ( 'tensorflow.python.util' ) if tfutil : return tfutil . nest . flatten ( thing ) else : return [ thing ]
Use tensorflows nest function if available otherwise just wrap object in an array
18,439
def val_to_json ( key , val , mode = "summary" , step = None ) : converted = val typename = util . get_full_typename ( val ) if util . is_matplotlib_typename ( typename ) : val = util . ensure_matplotlib_figure ( val ) if any ( len ( ax . images ) > 0 for ax in val . axes ) : PILImage = util . get_module ( "PIL.Image" ...
Converts a wandb datatype to its JSON representation
18,440
def to_json ( payload , mode = "history" ) : for key , val in six . iteritems ( payload ) : if isinstance ( val , dict ) : payload [ key ] = to_json ( val , mode ) else : payload [ key ] = val_to_json ( key , val , mode , step = payload . get ( "_step" ) ) return payload
Converts all keys in a potentially nested array into their JSON representation
18,441
def guess_mode ( self , data ) : if data . ndim == 2 : return "L" elif data . shape [ - 1 ] == 3 : return "RGB" elif data . shape [ - 1 ] == 4 : return "RGBA" else : raise ValueError ( "Un-supported shape for image conversion %s" % list ( data . shape ) )
Guess what type of image the np . array is representing
18,442
def transform ( images , out_dir , fname ) : from PIL import Image as PILImage base = os . path . join ( out_dir , "media" , "images" ) width , height = images [ 0 ] . image . size num_images_to_log = len ( images ) if num_images_to_log > Image . MAX_IMAGES : logging . warn ( "The maximum number of images to store per ...
Combines a list of images into a single sprite returning meta information
18,443
def _handle_command ( self , command ) : logger . info ( 'Handle command %r' , command ) def in_executor ( ) : self . handling_command = True try : if self . callback is not None : self . callback ( self , command ) finally : self . server . call_from_executor ( done ) def done ( ) : self . handling_command = False if ...
Handle command . This will run in a separate thread in order not to block the event loop .
18,444
def erase_screen ( self ) : self . vt100_output . erase_screen ( ) self . vt100_output . cursor_goto ( 0 , 0 ) self . vt100_output . flush ( )
Erase output screen .
18,445
def send ( self , data ) : assert isinstance ( data , text_type ) self . stdout . write ( data . replace ( '\n' , '\r\n' ) ) self . stdout . flush ( )
Send text to the client .
18,446
def _process_callbacks ( self ) : os . read ( self . _schedule_pipe [ 0 ] , 1024 ) calls_from_executor , self . _calls_from_executor = self . _calls_from_executor , [ ] for c in calls_from_executor : c ( )
Process callbacks from call_from_executor in eventloop .
18,447
def run ( self ) : listen_socket = self . create_socket ( self . host , self . port ) logger . info ( 'Listening for telnet connections on %s port %r' , self . host , self . port ) try : while True : self . connections = set ( [ c for c in self . connections if not c . closed ] ) connections = set ( [ c for c in self ....
Run the eventloop for the telnet server .
18,448
def _accept ( self , listen_socket ) : conn , addr = listen_socket . accept ( ) connection = TelnetConnection ( conn , addr , self . application , self , encoding = self . encoding ) self . connections . add ( connection ) logger . info ( 'New connection %r %r' , * addr )
Accept new incoming connection .
18,449
def _handle_incoming_data ( self , conn ) : connection = [ c for c in self . connections if c . conn == conn ] [ 0 ] data = conn . recv ( 1024 ) if data : connection . feed ( data ) else : self . connections . remove ( connection )
Handle incoming data on socket .
18,450
def execute ( self , * args , ** kwargs ) : try : return self . client . execute ( * args , ** kwargs ) except requests . exceptions . HTTPError as err : res = err . response logger . error ( "%s response executing GraphQL." % res . status_code ) logger . error ( res . text ) self . display_gorilla_error_if_found ( res...
Wrapper around execute that logs in cases of failure .
18,451
def save_pip ( self , out_dir ) : try : import pkg_resources installed_packages = [ d for d in iter ( pkg_resources . working_set ) ] installed_packages_list = sorted ( [ "%s==%s" % ( i . key , i . version ) for i in installed_packages ] ) with open ( os . path . join ( out_dir , 'requirements.txt' ) , 'w' ) as f : f ....
Saves the current working set of pip packages to requirements . txt
18,452
def save_patches ( self , out_dir ) : if not self . git . enabled : return False try : root = self . git . root if self . git . dirty : patch_path = os . path . join ( out_dir , 'diff.patch' ) if self . git . has_submodule_diff : with open ( patch_path , 'wb' ) as patch : subprocess . check_call ( [ 'git' , 'diff' , '-...
Save the current state of this repository to one or more patches .
18,453
def list_projects ( self , entity = None ) : query = gql ( ) return self . _flatten_edges ( self . gql ( query , variable_values = { 'entity' : entity or self . settings ( 'entity' ) } ) [ 'models' ] )
Lists projects in W&B scoped by entity .
18,454
def list_runs ( self , project , entity = None ) : query = gql ( ) return self . _flatten_edges ( self . gql ( query , variable_values = { 'entity' : entity or self . settings ( 'entity' ) , 'model' : project or self . settings ( 'project' ) } ) [ 'model' ] [ 'buckets' ] )
Lists runs in W&B scoped by project .
18,455
def launch_run ( self , command , project = None , entity = None , run_id = None ) : query = gql ( ) patch = BytesIO ( ) if self . git . dirty : self . git . repo . git . execute ( [ 'git' , 'diff' ] , output_stream = patch ) patch . seek ( 0 ) cwd = "." if self . git . enabled : cwd = cwd + os . getcwd ( ) . replace (...
Launch a run in the cloud .
18,456
def run_config ( self , project , run = None , entity = None ) : query = gql ( ) response = self . gql ( query , variable_values = { 'name' : project , 'run' : run , 'entity' : entity } ) if response [ 'model' ] == None : raise ValueError ( "Run {}/{}/{} not found" . format ( entity , project , run ) ) run = response [...
Get the relevant configs for a run
18,457
def run_resume_status ( self , entity , project_name , name ) : query = gql ( ) response = self . gql ( query , variable_values = { 'entity' : entity , 'project' : project_name , 'name' : name , } ) if 'model' not in response or 'bucket' not in response [ 'model' ] : return None project = response [ 'model' ] self . se...
Check if a run exists and get resume information .
18,458
def upsert_run ( self , id = None , name = None , project = None , host = None , group = None , tags = None , config = None , description = None , entity = None , state = None , repo = None , job_type = None , program_path = None , commit = None , sweep_name = None , summary_metrics = None , num_retries = None ) : muta...
Update a run
18,459
def upload_urls ( self , project , files , run = None , entity = None , description = None ) : query = gql ( ) run_id = run or self . settings ( 'run' ) entity = entity or self . settings ( 'entity' ) query_result = self . gql ( query , variable_values = { 'name' : project , 'run' : run_id , 'entity' : entity , 'descri...
Generate temporary resumeable upload urls
18,460
def download_file ( self , url ) : response = requests . get ( url , stream = True ) response . raise_for_status ( ) return ( int ( response . headers . get ( 'content-length' , 0 ) ) , response )
Initiate a streaming download
18,461
def upload_file ( self , url , file , callback = None , extra_headers = { } ) : extra_headers = extra_headers . copy ( ) response = None if os . stat ( file . name ) . st_size == 0 : raise CommError ( "%s is an empty file" % file . name ) try : progress = Progress ( file , callback = callback ) response = requests . pu...
Uploads a file to W&B with failure resumption
18,462
def register_agent ( self , host , sweep_id = None , project_name = None ) : mutation = gql ( ) if project_name is None : project_name = self . settings ( 'project' ) def no_retry_400 ( e ) : if not isinstance ( e , requests . HTTPError ) : return True if e . response . status_code != 400 : return True body = json . lo...
Register a new agent
18,463
def agent_heartbeat ( self , agent_id , metrics , run_states ) : mutation = gql ( ) try : response = self . gql ( mutation , variable_values = { 'id' : agent_id , 'metrics' : json . dumps ( metrics ) , 'runState' : json . dumps ( run_states ) } ) except Exception as e : message = ast . literal_eval ( e . args [ 0 ] ) [...
Notify server about agent state receive commands .
18,464
def upsert_sweep ( self , config ) : mutation = gql ( ) def no_retry_400_or_404 ( e ) : if not isinstance ( e , requests . HTTPError ) : return True if e . response . status_code != 400 and e . response . status_code != 404 : return True body = json . loads ( e . response . content ) raise UsageError ( body [ 'errors' ...
Upsert a sweep object .
18,465
def file_current ( self , fname , md5 ) : return os . path . isfile ( fname ) and util . md5_file ( fname ) == md5
Checksum a file and compare the md5 with the known md5
18,466
def pull ( self , project , run = None , entity = None ) : project , run = self . parse_slug ( project , run = run ) urls = self . download_urls ( project , run , entity ) responses = [ ] for fileName in urls : _ , response = self . download_write_file ( urls [ fileName ] ) if response : responses . append ( response )...
Download files from W&B
18,467
def push ( self , files , run = None , entity = None , project = None , description = None , force = True , progress = False ) : if project is None : project = self . get_project ( ) if project is None : raise CommError ( "No project configured." ) if run is None : run = self . current_run_id run_id , result = self . u...
Uploads multiple files to W&B
18,468
def get_file_stream_api ( self ) : if not self . _file_stream_api : if self . _current_run_id is None : raise UsageError ( 'Must have a current run to use file stream API.' ) self . _file_stream_api = FileStreamApi ( self , self . _current_run_id ) return self . _file_stream_api
This creates a new file pusher thread . Call start to initiate the thread that talks to W&B
18,469
def _status_request ( self , url , length ) : return requests . put ( url = url , headers = { 'Content-Length' : '0' , 'Content-Range' : 'bytes */%i' % length } )
Ask google how much we ve uploaded
18,470
def get_common_complete_suffix ( document , completions ) : def doesnt_change_before_cursor ( completion ) : end = completion . text [ : - completion . start_position ] return document . text_before_cursor . endswith ( end ) completions2 = [ c for c in completions if doesnt_change_before_cursor ( c ) ] if len ( complet...
Return the common prefix for all completions .
18,471
def get_width ( self , cli , ui_content ) : " Width to report to the `Window`. " text = token_list_to_text ( self . get_prompt_tokens ( cli ) ) return get_cwidth ( text )
Width to report to the Window .
18,472
def prompt_for_project ( ctx , entity ) : result = ctx . invoke ( projects , entity = entity , display = False ) try : if len ( result ) == 0 : project = click . prompt ( "Enter a name for your first project" ) project = api . upsert_project ( project , entity = entity ) [ "name" ] else : project_names = [ project [ "n...
Ask the user for a project creating one if necessary .
18,473
def cli ( ctx ) : wandb . try_to_set_up_global_logging ( ) if ctx . invoked_subcommand is None : click . echo ( ctx . get_help ( ) )
Weights & Biases .
18,474
def _load_values ( self ) : path = self . _config_path ( ) if path is not None and os . path . isfile ( path ) : self . _load_file ( path )
Load config . yaml from the run directory if available .
18,475
def load_json ( self , json ) : for key in json : if key == "wandb_version" : continue self . _items [ key ] = json [ key ] . get ( 'value' ) self . _descriptions [ key ] = json [ key ] . get ( 'desc' )
Loads existing config from JSON
18,476
def persist ( self ) : path = self . _config_path ( ) if path is None : return with open ( path , "w" ) as conf_file : conf_file . write ( str ( self ) )
Stores the current configuration for pushing to W&B
18,477
def get_upstream_fork_point ( self ) : possible_relatives = [ ] try : if not self . repo : return None try : active_branch = self . repo . active_branch except ( TypeError , ValueError ) : logger . debug ( "git is in a detached head state" ) return None else : tracking_branch = active_branch . tracking_branch ( ) if tr...
Get the most recent ancestor of HEAD that occurs on an upstream branch .
18,478
def create_text_object_decorator ( registry ) : assert isinstance ( registry , BaseRegistry ) operator_given = ViWaitingForTextObjectMode ( ) navigation_mode = ViNavigationMode ( ) selection_mode = ViSelectionMode ( ) def text_object_decorator ( * keys , ** kw ) : filter = kw . pop ( 'filter' , Always ( ) ) no_move_han...
Create a decorator that can be used to register Vi text object implementations .
18,479
def create_operator_decorator ( registry ) : assert isinstance ( registry , BaseRegistry ) operator_given = ViWaitingForTextObjectMode ( ) navigation_mode = ViNavigationMode ( ) selection_mode = ViSelectionMode ( ) def operator_decorator ( * keys , ** kw ) : filter = kw . pop ( 'filter' , Always ( ) ) eager = kw . pop ...
Create a decorator that can be used for registering Vi operators .
18,480
def load_vi_open_in_editor_bindings ( ) : registry = Registry ( ) navigation_mode = ViNavigationMode ( ) registry . add_binding ( 'v' , filter = navigation_mode ) ( get_by_name ( 'edit-and-execute-command' ) ) return registry
Pressing v in navigation mode will open the buffer in an external editor .
18,481
def cut ( self , buffer ) : from_ , to = self . operator_range ( buffer . document ) from_ += buffer . cursor_position to += buffer . cursor_position to -= 1 document = Document ( buffer . text , to , SelectionState ( original_cursor_position = from_ , type = self . selection_type ) ) new_document , clipboard_data = do...
Turn text object into ClipboardData instance .
18,482
def get_sync_start_position ( self , document , lineno ) : " Scan backwards, and find a possible position to start. " pattern = self . _compiled_pattern lines = document . lines for i in range ( lineno , max ( - 1 , lineno - self . MAX_BACKWARDS ) , - 1 ) : match = pattern . match ( lines [ i ] ) if match : return i , ...
Scan backwards and find a possible position to start .
18,483
def from_filename ( cls , filename , sync_from_start = True ) : from pygments . util import ClassNotFound from pygments . lexers import get_lexer_for_filename try : pygments_lexer = get_lexer_for_filename ( filename ) except ClassNotFound : return SimpleLexer ( ) else : return cls ( pygments_lexer . __class__ , sync_fr...
Create a Lexer from a filename .
18,484
def _bisearch ( ucs , table ) : lbound = 0 ubound = len ( table ) - 1 if ucs < table [ 0 ] [ 0 ] or ucs > table [ ubound ] [ 1 ] : return 0 while ubound >= lbound : mid = ( lbound + ubound ) // 2 if ucs > table [ mid ] [ 1 ] : lbound = mid + 1 elif ucs < table [ mid ] [ 0 ] : ubound = mid - 1 else : return 1 return 0
Auxiliary function for binary search in interval table .
18,485
def wcwidth ( wc ) : r ucs = ord ( wc ) if ( ucs == 0 or ucs == 0x034F or 0x200B <= ucs <= 0x200F or ucs == 0x2028 or ucs == 0x2029 or 0x202A <= ucs <= 0x202E or 0x2060 <= ucs <= 0x2063 ) : return 0 if ucs < 32 or 0x07F <= ucs < 0x0A0 : return - 1 if _bisearch ( ucs , ZERO_WIDTH ) : return 0 return 1 + _bisearch ( ucs ...
r Given one unicode character return its printable length on a terminal .
18,486
def wcswidth ( pwcs , n = None ) : end = len ( pwcs ) if n is None else n idx = slice ( 0 , end ) width = 0 for char in pwcs [ idx ] : wcw = wcwidth ( char ) if wcw < 0 : return - 1 else : width += wcw return width
Given a unicode string return its printable length on a terminal .
18,487
def _per_file_event_handler ( self ) : file_event_handler = PatternMatchingEventHandler ( ) file_event_handler . on_created = self . _on_file_created file_event_handler . on_modified = self . _on_file_modified file_event_handler . on_moved = self . _on_file_moved file_event_handler . _patterns = [ os . path . join ( se...
Create a Watchdog file event handler that does different things for every file
18,488
def _get_file_event_handler ( self , file_path , save_name ) : self . _file_pusher . update_file ( save_name , file_path ) if save_name not in self . _file_event_handlers : if save_name == 'wandb-history.jsonl' : self . _file_event_handlers [ 'wandb-history.jsonl' ] = FileEventHandlerTextStream ( file_path , 'wandb-his...
Get or create an event handler for a particular file .
18,489
def mirror_stdout_stderr ( self ) : fs_api = self . _api . get_file_stream_api ( ) io_wrap . SimpleTee ( sys . stdout , streaming_log . TextStreamPusher ( fs_api , OUTPUT_FNAME , prepend_timestamp = True ) ) io_wrap . SimpleTee ( sys . stderr , streaming_log . TextStreamPusher ( fs_api , OUTPUT_FNAME , prepend_timestam...
Simple STDOUT and STDERR mirroring used by _init_jupyter
18,490
def _get_stdout_stderr_streams ( self ) : if six . PY2 or not hasattr ( sys . stdout , "buffer" ) : if hasattr ( sys . stdout , "fileno" ) and sys . stdout . isatty ( ) : try : stdout = os . fdopen ( sys . stdout . fileno ( ) , "w+" , 0 ) stderr = os . fdopen ( sys . stderr . fileno ( ) , "w+" , 0 ) except OSError : st...
Sets up STDOUT and STDERR streams . Only call this once .
18,491
def _close_stdout_stderr_streams ( self ) : if self . _stdout_tee . tee_file is not None : self . _stdout_tee . tee_file . close ( ) if self . _stderr_tee . tee_file is not None : self . _stderr_tee . tee_file . close ( ) self . _stdout_tee . close_join ( ) self . _stderr_tee . close_join ( ) if self . _cloud : self . ...
Close output - capturing stuff . This also flushes anything left in the buffers .
18,492
def shutdown ( self , exitcode = 0 ) : logger . info ( "shutting down system stats and metadata service" ) self . _system_stats . shutdown ( ) self . _meta . shutdown ( ) if self . _cloud : logger . info ( "stopping streaming files and file change observer" ) self . _stop_file_observer ( ) self . _end_file_syncing ( ex...
Stops system stats streaming handlers and uploads files without output used by wandb . monitor
18,493
def run_user_process ( self , program , args , env ) : stdout_streams , stderr_streams = self . _get_stdout_stderr_streams ( ) if sys . platform == "win32" : self . _stdout_tee = io_wrap . Tee . pipe ( * stdout_streams ) self . _stderr_tee = io_wrap . Tee . pipe ( * stderr_streams ) else : self . _stdout_tee = io_wrap ...
Launch a user process capture its output and sync its files to the backend .
18,494
def wrap_existing_process ( self , pid , stdout_read_fd , stderr_read_fd , port = None ) : stdout_read_file = os . fdopen ( stdout_read_fd , 'rb' ) stderr_read_file = os . fdopen ( stderr_read_fd , 'rb' ) stdout_streams , stderr_streams = self . _get_stdout_stderr_streams ( ) self . _stdout_tee = io_wrap . Tee ( stdout...
Do syncing etc . for an already - running process .
18,495
def token_list_len ( tokenlist ) : ZeroWidthEscape = Token . ZeroWidthEscape return sum ( len ( item [ 1 ] ) for item in tokenlist if item [ 0 ] != ZeroWidthEscape )
Return the amount of characters in this token list .
18,496
def token_list_to_text ( tokenlist ) : ZeroWidthEscape = Token . ZeroWidthEscape return '' . join ( item [ 1 ] for item in tokenlist if item [ 0 ] != ZeroWidthEscape )
Concatenate all the text parts again .
18,497
def iter_token_lines ( tokenlist ) : line = [ ] for token , c in explode_tokens ( tokenlist ) : line . append ( ( token , c ) ) if c == '\n' : yield line line = [ ] yield line
Iterator that yields tokenlists for each line .
18,498
def _process ( self ) : buffer = self . key_buffer retry = False while True : if retry : retry = False else : buffer . append ( ( yield ) ) if buffer : is_prefix_of_longer_match = self . _is_prefix_of_longer_match ( buffer ) matches = self . _get_matches ( buffer ) eager_matches = [ m for m in matches if m . eager ( se...
Coroutine implementing the key match algorithm . Key strokes are sent into this generator and it calls the appropriate handlers .
18,499
def arg ( self ) : if self . _arg == '-' : return - 1 result = int ( self . _arg or 1 ) if int ( result ) >= 1000000 : result = 1 return result
Repetition argument .