idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
17,000 | def kill_process ( self ) : if self . process . poll ( ) is not None : return try : if hasattr ( self . process , 'terminate' ) : self . process . terminate ( ) elif os . name != 'nt' : os . kill ( self . process . pid , 9 ) else : import ctypes handle = int ( self . process . _handle ) ctypes . windll . kernel32 . TerminateProcess ( handle , - 1 ) except OSError : pass | Stop the process |
17,001 | def get_matches ( self , code , start = 0 , end = None , skip = None ) : if end is None : end = len ( self . source ) for match in self . _get_matched_asts ( code ) : match_start , match_end = match . get_region ( ) if start <= match_start and match_end <= end : if skip is not None and ( skip [ 0 ] < match_end and skip [ 1 ] > match_start ) : continue yield match | Search for code in source and return a list of Match \ es |
17,002 | def _get_children ( self , node ) : children = ast . get_children ( node ) return [ child for child in children if not isinstance ( child , ast . expr_context ) ] | Return not ast . expr_context children of node |
17,003 | def get_imports ( project , pydefined ) : pymodule = pydefined . get_module ( ) module = module_imports . ModuleImports ( project , pymodule ) if pymodule == pydefined : return [ stmt . import_info for stmt in module . imports ] return module . get_used_imports ( pydefined ) | A shortcut for getting the ImportInfo \ s used in a scope |
17,004 | def get_from_import ( self , resource , name ) : module_name = libutils . modname ( resource ) names = [ ] if isinstance ( name , list ) : names = [ ( imported , None ) for imported in name ] else : names = [ ( name , None ) , ] return FromImport ( module_name , 0 , tuple ( names ) ) | The from import statement for name in resource |
17,005 | def create_finder ( project , name , pyname , only_calls = False , imports = True , unsure = None , docs = False , instance = None , in_hierarchy = False , keywords = True ) : pynames_ = set ( [ pyname ] ) filters = [ ] if only_calls : filters . append ( CallsFilter ( ) ) if not imports : filters . append ( NoImportsFilter ( ) ) if not keywords : filters . append ( NoKeywordsFilter ( ) ) if isinstance ( instance , pynames . ParameterName ) : for pyobject in instance . get_objects ( ) : try : pynames_ . add ( pyobject [ name ] ) except exceptions . AttributeNotFoundError : pass for pyname in pynames_ : filters . append ( PyNameFilter ( pyname ) ) if in_hierarchy : filters . append ( InHierarchyFilter ( pyname ) ) if unsure : filters . append ( UnsureFilter ( unsure ) ) return Finder ( project , name , filters = filters , docs = docs ) | A factory for Finder |
17,006 | def same_pyname ( expected , pyname ) : if expected is None or pyname is None : return False if expected == pyname : return True if type ( expected ) not in ( pynames . ImportedModule , pynames . ImportedName ) and type ( pyname ) not in ( pynames . ImportedModule , pynames . ImportedName ) : return False return expected . get_definition_location ( ) == pyname . get_definition_location ( ) and expected . get_object ( ) == pyname . get_object ( ) | Check whether expected and pyname are the same |
17,007 | def unsure_pyname ( pyname , unbound = True ) : if pyname is None : return True if unbound and not isinstance ( pyname , pynames . UnboundName ) : return False if pyname . get_object ( ) == pyobjects . get_unknown ( ) : return True | Return True if we don t know what this name references |
17,008 | def find_occurrences ( self , resource = None , pymodule = None ) : tools = _OccurrenceToolsCreator ( self . project , resource = resource , pymodule = pymodule , docs = self . docs ) for offset in self . _textual_finder . find_offsets ( tools . source_code ) : occurrence = Occurrence ( tools , offset ) for filter in self . filters : result = filter ( occurrence ) if result is None : continue if result : yield occurrence break | Generate Occurrence instances |
17,009 | def create_generate ( kind , project , resource , offset ) : generate = eval ( 'Generate' + kind . title ( ) ) return generate ( project , resource , offset ) | A factory for creating Generate objects |
17,010 | def create_module ( project , name , sourcefolder = None ) : if sourcefolder is None : sourcefolder = project . root packages = name . split ( '.' ) parent = sourcefolder for package in packages [ : - 1 ] : parent = parent . get_child ( package ) return parent . create_file ( packages [ - 1 ] + '.py' ) | Creates a module and returns a rope . base . resources . File |
17,011 | def create_package ( project , name , sourcefolder = None ) : if sourcefolder is None : sourcefolder = project . root packages = name . split ( '.' ) parent = sourcefolder for package in packages [ : - 1 ] : parent = parent . get_child ( package ) made_packages = parent . create_folder ( packages [ - 1 ] ) made_packages . create_file ( '__init__.py' ) return made_packages | Creates a package and returns a rope . base . resources . Folder |
17,012 | def rename_in_module ( occurrences_finder , new_name , resource = None , pymodule = None , replace_primary = False , region = None , reads = True , writes = True ) : if resource is not None : source_code = resource . read ( ) else : source_code = pymodule . source_code change_collector = codeanalyze . ChangeCollector ( source_code ) for occurrence in occurrences_finder . find_occurrences ( resource , pymodule ) : if replace_primary and occurrence . is_a_fixed_primary ( ) : continue if replace_primary : start , end = occurrence . get_primary_range ( ) else : start , end = occurrence . get_word_range ( ) if ( not reads and not occurrence . is_written ( ) ) or ( not writes and occurrence . is_written ( ) ) : continue if region is None or region [ 0 ] <= start < region [ 1 ] : change_collector . add_change ( start , end , new_name ) return change_collector . get_changed ( ) | Returns the changed source or None if there is no changes |
17,013 | def get_changes ( self , new_name , in_file = None , in_hierarchy = False , unsure = None , docs = False , resources = None , task_handle = taskhandle . NullTaskHandle ( ) ) : if unsure in ( True , False ) : warnings . warn ( 'unsure parameter should be a function that returns ' 'True or False' , DeprecationWarning , stacklevel = 2 ) def unsure_func ( value = unsure ) : return value unsure = unsure_func if in_file is not None : warnings . warn ( '`in_file` argument has been deprecated; use `resources` ' 'instead. ' , DeprecationWarning , stacklevel = 2 ) if in_file : resources = [ self . resource ] if _is_local ( self . old_pyname ) : resources = [ self . resource ] if resources is None : resources = self . project . get_python_files ( ) changes = ChangeSet ( 'Renaming <%s> to <%s>' % ( self . old_name , new_name ) ) finder = occurrences . create_finder ( self . project , self . old_name , self . old_pyname , unsure = unsure , docs = docs , instance = self . old_instance , in_hierarchy = in_hierarchy and self . is_method ( ) ) job_set = task_handle . create_jobset ( 'Collecting Changes' , len ( resources ) ) for file_ in resources : job_set . started_job ( file_ . path ) new_content = rename_in_module ( finder , new_name , resource = file_ ) if new_content is not None : changes . add_change ( ChangeContents ( file_ , new_content ) ) job_set . finished_job ( ) if self . _is_renaming_a_module ( ) : resource = self . old_pyname . get_object ( ) . get_resource ( ) if self . _is_allowed_to_move ( resources , resource ) : self . _rename_module ( resource , new_name , changes ) return changes | Get the changes needed for this refactoring |
17,014 | def real_code ( source ) : collector = codeanalyze . ChangeCollector ( source ) for start , end in ignored_regions ( source ) : if source [ start ] == '#' : replacement = ' ' * ( end - start ) else : replacement = '"%s"' % ( ' ' * ( end - start - 2 ) ) collector . add_change ( start , end , replacement ) source = collector . get_changed ( ) or source collector = codeanalyze . ChangeCollector ( source ) parens = 0 for match in _parens . finditer ( source ) : i = match . start ( ) c = match . group ( ) if c in '({[' : parens += 1 if c in ')}]' : parens -= 1 if c == '\n' and parens > 0 : collector . add_change ( i , i + 1 , ' ' ) source = collector . get_changed ( ) or source return source . replace ( '\\\n' , ' ' ) . replace ( '\t' , ' ' ) . replace ( ';' , '\n' ) | Simplify source for analysis |
17,015 | def ignored_regions ( source ) : return [ ( match . start ( ) , match . end ( ) ) for match in _str . finditer ( source ) ] | Return ignored regions like strings and comments in source |
17,016 | def move ( self , new_location ) : self . _perform_change ( change . MoveResource ( self , new_location ) , 'Moving <%s> to <%s>' % ( self . path , new_location ) ) | Move resource to new_location |
17,017 | def get_children ( self ) : try : children = os . listdir ( self . real_path ) except OSError : return [ ] result = [ ] for name in children : try : child = self . get_child ( name ) except exceptions . ResourceNotFoundError : continue if not self . project . is_ignored ( child ) : result . append ( self . get_child ( name ) ) return result | Return the children of this folder |
17,018 | def _create_indexes ( self ) : self . collection . ensure_index ( [ ( 'time' , pymongo . DESCENDING ) ] ) self . collection . ensure_index ( 'name' ) | Ensures the proper fields are indexed |
17,019 | def send ( self , event ) : try : self . collection . insert ( event , manipulate = False ) except ( PyMongoError , BSONError ) : msg = 'Error inserting to MongoDB event tracker backend' log . exception ( msg ) | Insert the event in to the Mongo collection |
17,020 | def create_backends_from_settings ( self ) : config = getattr ( settings , DJANGO_BACKEND_SETTING_NAME , { } ) backends = self . instantiate_objects ( config ) return backends | Expects the Django setting EVENT_TRACKING_BACKENDS to be defined and point to a dictionary of backend engine configurations . |
17,021 | def instantiate_objects ( self , node ) : result = node if isinstance ( node , dict ) : if 'ENGINE' in node : result = self . instantiate_from_dict ( node ) else : result = { } for key , value in six . iteritems ( node ) : result [ key ] = self . instantiate_objects ( value ) elif isinstance ( node , list ) : result = [ ] for child in node : result . append ( self . instantiate_objects ( child ) ) return result | Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated |
17,022 | def instantiate_from_dict ( self , values ) : name = values [ 'ENGINE' ] options = values . get ( 'OPTIONS' , { } ) parts = name . split ( '.' ) module_name = '.' . join ( parts [ : - 1 ] ) class_name = parts [ - 1 ] try : module = import_module ( module_name ) cls = getattr ( module , class_name ) except ( ValueError , AttributeError , TypeError , ImportError ) : raise ValueError ( 'Cannot find class %s' % name ) options = self . instantiate_objects ( options ) return cls ( ** options ) | Constructs an object given a dictionary containing an ENGINE key which contains the full module path to the class and an OPTIONS key which contains a dictionary that will be passed in to the constructor as keyword args . |
17,023 | def create_processors_from_settings ( self ) : config = getattr ( settings , DJANGO_PROCESSOR_SETTING_NAME , [ ] ) processors = self . instantiate_objects ( config ) return processors | Expects the Django setting EVENT_TRACKING_PROCESSORS to be defined and point to a list of backend engine configurations . |
17,024 | def register_backend ( self , name , backend ) : if not hasattr ( backend , 'send' ) or not callable ( backend . send ) : raise ValueError ( 'Backend %s does not have a callable "send" method.' % backend . __class__ . __name__ ) else : self . backends [ name ] = backend | Register a new backend that will be called for each processed event . |
17,025 | def register_processor ( self , processor ) : if not callable ( processor ) : raise ValueError ( 'Processor %s is not callable.' % processor . __class__ . __name__ ) else : self . processors . append ( processor ) | Register a new processor . |
17,026 | def send ( self , event ) : try : processed_event = self . process_event ( event ) except EventEmissionExit : return else : self . send_to_backends ( processed_event ) | Process the event using all registered processors and send it to all registered backends . |
17,027 | def send_to_backends ( self , event ) : for name , backend in six . iteritems ( self . backends ) : try : backend . send ( event ) except Exception : LOG . exception ( 'Unable to send event to backend: %s' , name ) | Sends the event to all registered backends . |
17,028 | def emit ( self , name = None , data = None ) : event = { 'name' : name or UNKNOWN_EVENT_TYPE , 'timestamp' : datetime . now ( UTC ) , 'data' : data or { } , 'context' : self . resolve_context ( ) } self . routing_backend . send ( event ) | Emit an event annotated with the UTC time when this function was called . |
17,029 | def resolve_context ( self ) : merged = dict ( ) for context in self . located_context . values ( ) : merged . update ( context ) return merged | Create a new dictionary that corresponds to the union of all of the contexts that have been entered but not exited at this point . |
17,030 | def context ( self , name , ctx ) : self . enter_context ( name , ctx ) try : yield finally : self . exit_context ( name ) | Execute the block with the given context applied . This manager ensures that the context is removed even if an exception is raised within the context . |
17,031 | def get ( self ) : if not self . thread_local_data : self . thread_local_data = threading . local ( ) if not hasattr ( self . thread_local_data , 'context' ) : self . thread_local_data . context = OrderedDict ( ) return self . thread_local_data . context | Return a reference to a thread - specific context |
17,032 | def send ( self , event ) : event_str = json . dumps ( event , cls = DateTimeJSONEncoder ) if self . max_event_size is None or len ( event_str ) <= self . max_event_size : self . log ( event_str ) | Send the event to the standard python logger |
17,033 | def default ( self , obj ) : if isinstance ( obj , datetime ) : if obj . tzinfo is None : obj = UTC . localize ( obj ) else : obj = obj . astimezone ( UTC ) return obj . isoformat ( ) elif isinstance ( obj , date ) : return obj . isoformat ( ) return super ( DateTimeJSONEncoder , self ) . default ( obj ) | Serialize datetime and date objects of iso format . |
17,034 | def get_html_theme_path ( ) : theme_path = os . path . abspath ( os . path . dirname ( __file__ ) ) return [ theme_path ] | Return list of HTML theme paths . |
17,035 | def get_rev ( tag = True ) : rev_cmd = "git describe --always --tag" if tag in ( True , "True" ) else "git rev-parse HEAD" return local ( rev_cmd , capture = True ) . strip ( ) | Get build revision . |
17,036 | def zip_bundle ( tag = True ) : rev = __version__ print ( "Cleaning old build files." ) clean ( ) local ( "mkdir -p build" ) print ( "Bundling new files." ) with lcd ( "sphinx_bootstrap_theme/bootstrap" ) : local ( "zip -r ../../build/bootstrap.zip ." ) dest = os . path . abspath ( os . path . join ( DL_DIR , rev ) ) with lcd ( "build" ) : local ( "mkdir -p %s" % dest ) local ( "cp bootstrap.zip %s" % dest ) print ( "Verifying contents." ) local ( "unzip -l bootstrap.zip" ) | Create zip file upload bundles . |
17,037 | def save_model ( self , request , obj , form , change ) : obj . save ( ) if notification : if obj . parent_msg is None : sender_label = 'messages_sent' recipients_label = 'messages_received' else : sender_label = 'messages_replied' recipients_label = 'messages_reply_received' notification . send ( [ obj . sender ] , sender_label , { 'message' : obj , } ) if form . cleaned_data [ 'group' ] == 'all' : recipients = User . objects . exclude ( pk = obj . recipient . pk ) else : recipients = [ ] group = form . cleaned_data [ 'group' ] if group : group = Group . objects . get ( pk = group ) recipients . extend ( list ( group . user_set . exclude ( pk = obj . recipient . pk ) ) ) for user in recipients : obj . pk = None obj . recipient = user obj . save ( ) if notification : notification . send ( [ user ] , recipients_label , { 'message' : obj , } ) | Saves the message for the recipient and looks in the form instance for other possible recipients . Prevents duplication by excludin the original recipient from the list of optional recipients . |
17,038 | def inbox_count_for ( user ) : return Message . objects . filter ( recipient = user , read_at__isnull = True , recipient_deleted_at__isnull = True ) . count ( ) | returns the number of unread messages for the given user but does not mark them seen |
17,039 | def trash_for ( self , user ) : return self . filter ( recipient = user , recipient_deleted_at__isnull = False , ) | self . filter ( sender = user , sender_deleted_at__isnull = False , ) | Returns all messages that were either received or sent by the given user and are marked as deleted . |
17,040 | def delete ( request , message_id , success_url = None ) : user = request . user now = timezone . now ( ) message = get_object_or_404 ( Message , id = message_id ) deleted = False if success_url is None : success_url = reverse ( 'messages_inbox' ) if 'next' in request . GET : success_url = request . GET [ 'next' ] if message . sender == user : message . sender_deleted_at = now deleted = True if message . recipient == user : message . recipient_deleted_at = now deleted = True if deleted : message . save ( ) messages . info ( request , _ ( u"Message successfully deleted." ) ) if notification : notification . send ( [ user ] , "messages_deleted" , { 'message' : message , } ) return HttpResponseRedirect ( success_url ) raise Http404 | Marks a message as deleted by sender or recipient . The message is not really removed from the database because two users must delete a message before it s save to remove it completely . A cron - job should prune the database and remove old messages which are deleted by both users . As a side effect this makes it easy to implement a trash with undelete . |
17,041 | def view ( request , message_id , form_class = ComposeForm , quote_helper = format_quote , subject_template = _ ( u"Re: %(subject)s" ) , template_name = 'django_messages/view.html' ) : user = request . user now = timezone . now ( ) message = get_object_or_404 ( Message , id = message_id ) if ( message . sender != user ) and ( message . recipient != user ) : raise Http404 if message . read_at is None and message . recipient == user : message . read_at = now message . save ( ) context = { 'message' : message , 'reply_form' : None } if message . recipient == user : form = form_class ( initial = { 'body' : quote_helper ( message . sender , message . body ) , 'subject' : subject_template % { 'subject' : message . subject } , 'recipient' : [ message . sender , ] } ) context [ 'reply_form' ] = form return render ( request , template_name , context ) | Shows a single message . message_id argument is required . The user is only allowed to see the message if he is either the sender or the recipient . If the user is not allowed a 404 is raised . If the user is the recipient and the message is unread read_at is set to the current datetime . If the user is the recipient a reply form will be added to the tenplate context otherwise reply_form will be None . |
17,042 | def format_quote ( sender , body ) : lines = wrap ( body , 55 ) . split ( '\n' ) for i , line in enumerate ( lines ) : lines [ i ] = "> %s" % line quote = '\n' . join ( lines ) return ugettext ( u"%(sender)s wrote:\n%(body)s" ) % { 'sender' : sender , 'body' : quote } | Wraps text at 55 chars and prepends each line with > . Used for quoting messages in replies . |
17,043 | def get ( self , ** params ) : return self . client . get ( '/v1/reference-data/locations/{0}' . format ( self . location_id ) , ** params ) | Returns details for a specific airport . |
17,044 | def get ( self , ** params ) : return self . client . get ( '/v2/shopping/hotel-offers/{0}' . format ( self . offer_id ) , ** params ) | Returns details for a specific offer . |
17,045 | def buffer_typechecks ( self , call_id , payload ) : if self . currently_buffering_typechecks : for note in payload [ 'notes' ] : self . buffered_notes . append ( note ) | Adds typecheck events to the buffer |
17,046 | def buffer_typechecks_and_display ( self , call_id , payload ) : self . buffer_typechecks ( call_id , payload ) self . editor . display_notes ( self . buffered_notes ) | Adds typecheck events to the buffer and displays them right away . |
17,047 | def handle_typecheck_complete ( self , call_id , payload ) : self . log . debug ( 'handle_typecheck_complete: in' ) if not self . currently_buffering_typechecks : self . log . debug ( 'Completed typecheck was not requested by user, not displaying notes' ) return self . editor . display_notes ( self . buffered_notes ) self . currently_buffering_typechecks = False self . buffered_notes = [ ] | Handles NewScalaNotesEvent . |
17,048 | def execute_with_client ( quiet = False , bootstrap_server = False , create_client = True ) : def wrapper ( f ) : def wrapper2 ( self , * args , ** kwargs ) : client = self . current_client ( quiet = quiet , bootstrap_server = bootstrap_server , create_client = create_client ) if client and client . running : return f ( self , client , * args , ** kwargs ) return wrapper2 return wrapper | Decorator that gets a client and performs an operation on it . |
17,049 | def client_status ( self , config_path ) : c = self . client_for ( config_path ) status = "stopped" if not c or not c . ensime : status = 'unloaded' elif c . ensime . is_ready ( ) : status = 'ready' elif c . ensime . is_running ( ) : status = 'startup' elif c . ensime . aborted ( ) : status = 'aborted' return status | Get status of client for a project given path to its config . |
17,050 | def current_client ( self , quiet , bootstrap_server , create_client ) : current_file = self . _vim . current . buffer . name config_path = ProjectConfig . find_from ( current_file ) if config_path : return self . client_for ( config_path , quiet = quiet , bootstrap_server = bootstrap_server , create_client = create_client ) | Return the client for current file in the editor . |
17,051 | def client_for ( self , config_path , quiet = False , bootstrap_server = False , create_client = False ) : client = None abs_path = os . path . abspath ( config_path ) if abs_path in self . clients : client = self . clients [ abs_path ] elif create_client : client = self . create_client ( config_path ) if client . setup ( quiet = quiet , bootstrap_server = bootstrap_server ) : self . clients [ abs_path ] = client return client | Get a cached client for a project otherwise create one . |
17,052 | def disable_plugin ( self ) : for path in self . runtime_paths ( ) : self . _vim . command ( 'set runtimepath-={}' . format ( path ) ) | Disable ensime - vim in the event of an error we can t usefully recover from . |
17,053 | def runtime_paths ( self ) : runtimepath = self . _vim . options [ 'runtimepath' ] plugin = "ensime-vim" paths = [ ] for path in runtimepath . split ( ',' ) : if plugin in path : paths . append ( os . path . expanduser ( path ) ) return paths | All the runtime paths of ensime - vim plugin files . |
17,054 | def tick_clients ( self ) : if not self . _ticker : self . _create_ticker ( ) for client in self . clients . values ( ) : self . _ticker . tick ( client ) | Trigger the periodic tick function in the client . |
17,055 | def fun_en_complete_func ( self , client , findstart_and_base , base = None ) : if isinstance ( findstart_and_base , list ) : findstart = findstart_and_base [ 0 ] base = findstart_and_base [ 1 ] else : findstart = findstart_and_base return client . complete_func ( findstart , base ) | Invokable function from vim and neovim to perform completion . |
17,056 | def append ( self , text , afterline = None ) : if afterline : self . _vim . current . buffer . append ( text , afterline ) else : self . _vim . current . buffer . append ( text ) | Append text to the current buffer . |
17,057 | def getline ( self , lnum = None ) : return self . _vim . current . buffer [ lnum ] if lnum else self . _vim . current . line | Get a line from the current buffer . |
17,058 | def getlines ( self , bufnr = None ) : buf = self . _vim . buffers [ bufnr ] if bufnr else self . _vim . current . buffer return buf [ : ] | Get all lines of a buffer as a list . |
17,059 | def menu ( self , prompt , choices ) : menu = [ prompt ] + [ "{0}. {1}" . format ( * choice ) for choice in enumerate ( choices , start = 1 ) ] command = 'inputlist({})' . format ( repr ( menu ) ) choice = int ( self . _vim . eval ( command ) ) if not 0 < choice < len ( menu ) : return return choices [ choice - 1 ] | Presents a selection menu and returns the user s choice . |
17,060 | def set_buffer_options ( self , options , bufnr = None ) : buf = self . _vim . buffers [ bufnr ] if bufnr else self . _vim . current . buffer filetype = options . pop ( 'filetype' , None ) if filetype : self . set_filetype ( filetype ) for opt , value in options . items ( ) : buf . options [ opt ] = value | Set buffer - local options for a buffer defaulting to current . |
17,061 | def set_filetype ( self , filetype , bufnr = None ) : if bufnr : self . _vim . command ( str ( bufnr ) + 'bufdo set filetype=' + filetype ) else : self . _vim . command ( 'set filetype=' + filetype ) | Set filetype for a buffer . |
17,062 | def split_window ( self , fpath , vertical = False , size = None , bufopts = None ) : command = 'split {}' . format ( fpath ) if fpath else 'new' if vertical : command = 'v' + command if size : command = str ( size ) + command self . _vim . command ( command ) if bufopts : self . set_buffer_options ( bufopts ) | Open file in a new split window . |
17,063 | def write ( self , noautocmd = False ) : cmd = 'noautocmd write' if noautocmd else 'write' self . _vim . command ( cmd ) | Writes the file of the current buffer . |
17,064 | def initialize ( self ) : if 'EnErrorStyle' not in self . _vim . vars : self . _vim . vars [ 'EnErrorStyle' ] = 'EnError' self . _vim . command ( 'highlight EnErrorStyle ctermbg=red gui=underline' ) self . _vim . command ( 'set omnifunc=EnCompleteFunc' ) self . _vim . command ( 'autocmd FileType package_info nnoremap <buffer> <Space> :call EnPackageDecl()<CR>' ) self . _vim . command ( 'autocmd FileType package_info setlocal splitright' ) | Sets up initial ensime - vim editor settings . |
17,065 | def set_cursor ( self , row , col ) : self . _vim . current . window . cursor = ( row , col ) | Set cursor position to given row and column in the current window . |
17,066 | def word_under_cursor_pos ( self ) : self . _vim . command ( 'normal e' ) end = self . cursor ( ) self . _vim . command ( 'normal b' ) beg = self . cursor ( ) return beg , end | Return start and end positions of the cursor respectively . |
17,067 | def selection_pos ( self ) : buff = self . _vim . current . buffer beg = buff . mark ( '<' ) end = buff . mark ( '>' ) return beg , end | Return start and end positions of the visual selection respectively . |
17,068 | def ask_input ( self , prompt ) : self . _vim . command ( 'call inputsave()' ) self . _vim . command ( 'let user_input = input("{} ")' . format ( prompt ) ) self . _vim . command ( 'call inputrestore()' ) response = self . _vim . eval ( 'user_input' ) self . _vim . command ( 'unlet user_input' ) return response | Prompt user for input and return the entered value . |
17,069 | def lazy_display_error ( self , filename ) : position = self . cursor ( ) error = self . get_error_at ( position ) if error : report = error . get_truncated_message ( position , self . width ( ) - 1 ) self . raw_message ( report ) | Display error when user is over it . |
17,070 | def get_error_at ( self , cursor ) : for error in self . _errors : if error . includes ( self . _vim . eval ( "expand('%:p')" ) , cursor ) : return error return None | Return error at position cursor . |
17,071 | def clean_errors ( self ) : self . _vim . eval ( 'clearmatches()' ) self . _errors = [ ] self . _matches = [ ] self . _vim . current . buffer . vars [ 'ensime_notes' ] = [ ] | Clean errors and unhighlight them in vim . |
17,072 | def raw_message ( self , message , silent = False ) : vim = self . _vim cmd = 'echo "{}"' . format ( message . replace ( '"' , '\\"' ) ) if silent : cmd = 'silent ' + cmd if self . isneovim : vim . async_call ( vim . command , cmd ) else : vim . command ( cmd ) | Display a message in the Vim status line . |
17,073 | def symbol_for_inspector_line ( self , lineno ) : def indent ( line ) : n = 0 for char in line : if char == ' ' : n += 1 else : break return n / 2 lines = self . _vim . current . buffer [ : lineno ] i = indent ( lines [ - 1 ] ) fqn = [ lines [ - 1 ] . split ( ) [ - 1 ] ] for line in reversed ( lines ) : if indent ( line ) == i - 1 : i -= 1 fqn . insert ( 0 , line . split ( ) [ - 1 ] ) return "." . join ( fqn ) | Given a line number for the Package Inspector window returns the fully - qualified name for the symbol on that line . |
17,074 | def display_notes ( self , notes ) : hassyntastic = bool ( int ( self . _vim . eval ( 'exists(":SyntasticCheck")' ) ) ) if hassyntastic : self . __display_notes_with_syntastic ( notes ) else : self . __display_notes ( notes ) self . _vim . command ( 'redraw!' ) | Renders notes reported by ENSIME such as typecheck errors . |
17,075 | def formatted_completion_sig ( completion ) : f_result = completion [ "name" ] if is_basic_type ( completion ) : return f_result elif len ( completion [ "typeInfo" ] [ "paramSections" ] ) == 0 : return f_result sections = completion [ "typeInfo" ] [ "paramSections" ] f_sections = [ formatted_param_section ( ps ) for ps in sections ] return u"{}{}" . format ( f_result , "" . join ( f_sections ) ) | Regenerate signature for methods . Return just the name otherwise |
17,076 | def formatted_param_section ( section ) : implicit = "implicit " if section [ "isImplicit" ] else "" s_params = [ ( p [ 0 ] , formatted_param_type ( p [ 1 ] ) ) for p in section [ "params" ] ] return "({}{})" . format ( implicit , concat_params ( s_params ) ) | Format a parameters list . Supports the implicit list |
17,077 | def formatted_param_type ( ptype ) : pt_name = ptype [ "name" ] if pt_name . startswith ( "<byname>" ) : pt_name = pt_name . replace ( "<byname>[" , "=> " ) [ : - 1 ] elif pt_name . startswith ( "<repeated>" ) : pt_name = pt_name . replace ( "<repeated>[" , "" ) [ : - 1 ] + "*" return pt_name | Return the short name for a type . Special treatment for by - name and var args |
17,078 | def register_responses_handlers ( self ) : self . handlers [ "SymbolInfo" ] = self . handle_symbol_info self . handlers [ "IndexerReadyEvent" ] = self . handle_indexer_ready self . handlers [ "AnalyzerReadyEvent" ] = self . handle_analyzer_ready self . handlers [ "NewScalaNotesEvent" ] = self . buffer_typechecks self . handlers [ "NewJavaNotesEvent" ] = self . buffer_typechecks_and_display self . handlers [ "BasicTypeInfo" ] = self . show_type self . handlers [ "ArrowTypeInfo" ] = self . show_type self . handlers [ "FullTypeCheckCompleteEvent" ] = self . handle_typecheck_complete self . handlers [ "StringResponse" ] = self . handle_string_response self . handlers [ "CompletionInfoList" ] = self . handle_completion_info_list self . handlers [ "TypeInspectInfo" ] = self . handle_type_inspect self . handlers [ "SymbolSearchResults" ] = self . handle_symbol_search self . handlers [ "SourcePositions" ] = self . handle_source_positions self . handlers [ "DebugOutputEvent" ] = self . handle_debug_output self . handlers [ "DebugBreakEvent" ] = self . handle_debug_break self . handlers [ "DebugBacktrace" ] = self . handle_debug_backtrace self . handlers [ "DebugVmError" ] = self . handle_debug_vm_error self . handlers [ "RefactorDiffEffect" ] = self . apply_refactor self . handlers [ "ImportSuggestions" ] = self . handle_import_suggestions self . handlers [ "PackageInfo" ] = self . handle_package_info self . handlers [ "FalseResponse" ] = self . handle_false_response | Register handlers for responses from the server . |
17,079 | def handle_incoming_response ( self , call_id , payload ) : self . log . debug ( 'handle_incoming_response: in [typehint: %s, call ID: %s]' , payload [ 'typehint' ] , call_id ) typehint = payload [ "typehint" ] handler = self . handlers . get ( typehint ) def feature_not_supported ( m ) : msg = feedback [ "handler_not_implemented" ] self . editor . raw_message ( msg . format ( typehint , self . launcher . ensime_version ) ) if handler : with catch ( NotImplementedError , feature_not_supported ) : handler ( call_id , payload ) else : self . log . warning ( 'Response has not been handled: %s' , Pretty ( payload ) ) | Get a registered handler for a given response and execute it . |
17,080 | def handle_symbol_search ( self , call_id , payload ) : self . log . debug ( 'handle_symbol_search: in %s' , Pretty ( payload ) ) syms = payload [ "syms" ] qfList = [ ] for sym in syms : p = sym . get ( "pos" ) if p : item = self . editor . to_quickfix_item ( str ( p [ "file" ] ) , p [ "line" ] , str ( sym [ "name" ] ) , "info" ) qfList . append ( item ) self . editor . write_quickfix_list ( qfList , "Symbol Search" ) | Handler for symbol search results |
17,081 | def handle_symbol_info ( self , call_id , payload ) : with catch ( KeyError , lambda e : self . editor . message ( "unknown_symbol" ) ) : decl_pos = payload [ "declPos" ] f = decl_pos . get ( "file" ) call_options = self . call_options [ call_id ] self . log . debug ( 'handle_symbol_info: call_options %s' , call_options ) display = call_options . get ( "display" ) if display and f : self . editor . raw_message ( f ) open_definition = call_options . get ( "open_definition" ) if open_definition and f : self . editor . clean_errors ( ) self . editor . doautocmd ( 'BufLeave' ) if call_options . get ( "split" ) : vert = call_options . get ( "vert" ) self . editor . split_window ( f , vertical = vert ) else : self . editor . edit ( f ) self . editor . doautocmd ( 'BufReadPre' , 'BufRead' , 'BufEnter' ) self . set_position ( decl_pos ) del self . call_options [ call_id ] | Handler for response SymbolInfo . |
17,082 | def handle_string_response ( self , call_id , payload ) : self . log . debug ( 'handle_string_response: in [typehint: %s, call ID: %s]' , payload [ 'typehint' ] , call_id ) url = payload [ 'text' ] if not url . startswith ( 'http' ) : port = self . ensime . http_port ( ) url = gconfig [ 'localhost' ] . format ( port , url ) options = self . call_options . get ( call_id ) if options and options . get ( 'browse' ) : self . _browse_doc ( url ) del self . call_options [ call_id ] else : self . log . debug ( 'EnDocUri %s' , url ) return url | Handler for response StringResponse . |
17,083 | def handle_completion_info_list ( self , call_id , payload ) : self . log . debug ( 'handle_completion_info_list: in' ) completions = [ c for c in payload [ "completions" ] if "typeInfo" in c ] self . suggestions = [ completion_to_suggest ( c ) for c in completions ] self . log . debug ( 'handle_completion_info_list: %s' , Pretty ( self . suggestions ) ) | Handler for a completion response . |
17,084 | def handle_type_inspect ( self , call_id , payload ) : style = 'fullName' if self . full_types_enabled else 'name' interfaces = payload . get ( "interfaces" ) ts = [ i [ "type" ] [ style ] for i in interfaces ] prefix = "( " + ", " . join ( ts ) + " ) => " self . editor . raw_message ( prefix + payload [ "type" ] [ style ] ) | Handler for responses TypeInspectInfo . |
17,085 | def show_type ( self , call_id , payload ) : if self . full_types_enabled : tpe = payload [ 'fullName' ] else : tpe = payload [ 'name' ] self . log . info ( 'Displayed type %s' , tpe ) self . editor . raw_message ( tpe ) | Show type of a variable or scala type . |
17,086 | def handle_source_positions ( self , call_id , payload ) : self . log . debug ( 'handle_source_positions: in %s' , Pretty ( payload ) ) call_options = self . call_options [ call_id ] word_under_cursor = call_options . get ( "word_under_cursor" ) positions = payload [ "positions" ] if not positions : self . editor . raw_message ( "No usages of <{}> found" . format ( word_under_cursor ) ) return qf_list = [ ] for p in positions : position = p [ "position" ] preview = str ( p [ "preview" ] ) if "preview" in p else "<no preview>" item = self . editor . to_quickfix_item ( str ( position [ "file" ] ) , position [ "line" ] , preview , "info" ) qf_list . append ( item ) qf_sorted = sorted ( qf_list , key = itemgetter ( 'filename' , 'lnum' ) ) self . editor . write_quickfix_list ( qf_sorted , "Usages of <{}>" . format ( word_under_cursor ) ) | Handler for source positions |
17,087 | def _start_refresh_timer ( self ) : if not self . _timer : self . _timer = self . _vim . eval ( "timer_start({}, 'EnTick', {{'repeat': -1}})" . format ( REFRESH_TIMER ) ) | Start the Vim timer . |
17,088 | def queue_poll ( self , sleep_t = 0.5 ) : connection_alive = True while self . running : if self . ws : def logger_and_close ( msg ) : self . log . error ( 'Websocket exception' , exc_info = True ) if not self . running : connection_alive = False else : if not self . number_try_connection : self . teardown ( ) self . _display_ws_warning ( ) with catch ( websocket . WebSocketException , logger_and_close ) : result = self . ws . recv ( ) self . queue . put ( result ) if connection_alive : time . sleep ( sleep_t ) | Put new messages on the queue as they arrive . Blocking in a thread . |
17,089 | def setup ( self , quiet = False , bootstrap_server = False ) : def lazy_initialize_ensime ( ) : if not self . ensime : called_by = inspect . stack ( ) [ 4 ] [ 3 ] self . log . debug ( str ( inspect . stack ( ) ) ) self . log . debug ( 'setup(quiet=%s, bootstrap_server=%s) called by %s()' , quiet , bootstrap_server , called_by ) installed = self . launcher . strategy . isinstalled ( ) if not installed and not bootstrap_server : if not quiet : scala = self . launcher . config . get ( 'scala-version' ) msg = feedback [ "prompt_server_install" ] . format ( scala_version = scala ) self . editor . raw_message ( msg ) return False try : self . ensime = self . launcher . launch ( ) except InvalidJavaPathError : self . editor . message ( 'invalid_java' ) return bool ( self . ensime ) def ready_to_connect ( ) : if not self . ws and self . ensime . is_ready ( ) : self . connect_ensime_server ( ) return True return self . running and lazy_initialize_ensime ( ) and ready_to_connect ( ) | Check the classpath and connect to the server if necessary . |
17,090 | def send ( self , msg ) : def reconnect ( e ) : self . log . error ( 'send error, reconnecting...' , exc_info = True ) self . connect_ensime_server ( ) if self . ws : self . ws . send ( msg + "\n" ) self . log . debug ( 'send: in' ) if self . running and self . ws : with catch ( websocket . WebSocketException , reconnect ) : self . log . debug ( 'send: sending JSON on WebSocket' ) self . ws . send ( msg + "\n" ) | Send something to the ensime server . |
17,091 | def connect_ensime_server ( self ) : self . log . debug ( 'connect_ensime_server: in' ) server_v2 = isinstance ( self , EnsimeClientV2 ) def disable_completely ( e ) : if e : self . log . error ( 'connection error: %s' , e , exc_info = True ) self . shutdown_server ( ) self . _display_ws_warning ( ) if self . running and self . number_try_connection : self . number_try_connection -= 1 if not self . ensime_server : port = self . ensime . http_port ( ) uri = "websocket" if server_v2 else "jerky" self . ensime_server = gconfig [ "ensime_server" ] . format ( port , uri ) with catch ( websocket . WebSocketException , disable_completely ) : options = { "subprotocols" : [ "jerky" ] } if server_v2 else { } options [ 'enable_multithread' ] = True self . log . debug ( "About to connect to %s with options %s" , self . ensime_server , options ) self . ws = websocket . create_connection ( self . ensime_server , ** options ) if self . ws : self . send_request ( { "typehint" : "ConnectionInfoReq" } ) else : disable_completely ( None ) | Start initial connection with the server . |
17,092 | def shutdown_server ( self ) : self . log . debug ( 'shutdown_server: in' ) if self . ensime and self . toggle_teardown : self . ensime . stop ( ) | Shut down server if it is alive . |
17,093 | def teardown ( self ) : self . log . debug ( 'teardown: in' ) self . running = False self . shutdown_server ( ) shutil . rmtree ( self . tmp_diff_folder , ignore_errors = True ) | Tear down the server or keep it alive . |
17,094 | def set_position ( self , decl_pos ) : if decl_pos [ "typehint" ] == "LineSourcePosition" : self . editor . set_cursor ( decl_pos [ 'line' ] , 0 ) else : point = decl_pos [ "offset" ] row , col = self . editor . point2pos ( point + 1 ) self . editor . set_cursor ( row , col ) | Set editor position from ENSIME declPos data . |
17,095 | def get_position ( self , row , col ) : result = col self . log . debug ( '%s %s' , row , col ) lines = self . editor . getlines ( ) [ : row - 1 ] result += sum ( [ len ( l ) + 1 for l in lines ] ) self . log . debug ( result ) return result | Get char position in all the text from row and column . |
17,096 | def send_at_point ( self , what , row , col ) : pos = self . get_position ( row , col ) self . send_request ( { "typehint" : what + "AtPointReq" , "file" : self . _file_info ( ) , "point" : pos } ) | Ask the server to perform an operation at a given point . |
17,097 | def type_check_cmd ( self , args , range = None ) : self . log . debug ( 'type_check_cmd: in' ) self . start_typechecking ( ) self . type_check ( "" ) self . editor . message ( 'typechecking' ) | Sets the flag to begin buffering typecheck notes & clears any stale notes before requesting a typecheck from the server |
17,098 | def doc_uri ( self , args , range = None ) : self . log . debug ( 'doc_uri: in' ) self . send_at_position ( "DocUri" , False , "point" ) | Request doc of whatever at cursor . |
17,099 | def usages ( self ) : row , col = self . editor . cursor ( ) self . log . debug ( 'usages: in' ) self . call_options [ self . call_id ] = { "word_under_cursor" : self . editor . current_word ( ) , "false_resp_msg" : "Not a valid symbol under the cursor" } self . send_at_point ( "UsesOfSymbol" , row , col ) | Request usages of whatever at cursor . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.