_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q32600
AliasManager.detect_alias_config_change
train
def detect_alias_config_change(self): """ Change if the alias configuration has changed since the last run. Returns: False if the alias configuration file has not been changed since the last run. Otherwise, return True. """ # Do not load the entire comman...
python
{ "resource": "" }
q32601
AliasManager.transform
train
def transform(self, args): """ Transform any aliases in args to their respective commands. Args: args: A list of space-delimited command input extracted directly from the console. Returns: A list of transformed commands according to the alias configuration file....
python
{ "resource": "" }
q32602
AliasManager.get_full_alias
train
def get_full_alias(self, query): """ Get the full alias given a search query. Args: query: The query this function performs searching on. Returns: The full alias (with the placeholders, if any). """ if query in self.alias_table.sections(): ...
python
{ "resource": "" }
q32603
AliasManager.load_full_command_table
train
def load_full_command_table(self): """ Perform a full load of the command table to get all the reserved command words. """ load_cmd_tbl_func = self.kwargs.get('load_cmd_tbl_func', lambda _: {}) cache_reserved_commands(load_cmd_tbl_func) telemetry.set_full_command_table_lo...
python
{ "resource": "" }
q32604
AliasManager.post_transform
train
def post_transform(self, args): """ Inject environment variables, and write hash to alias hash file after transforming alias to commands. Args: args: A list of args to post-transform. """ # Ignore 'az' if it is the first command args = args[1:] if args and ar...
python
{ "resource": "" }
q32605
AliasManager.build_collision_table
train
def build_collision_table(aliases, levels=COLLISION_CHECK_LEVEL_DEPTH): """ Build the collision table according to the alias configuration file against the entire command table. self.collided_alias is structured as: { 'collided_alias': [the command level at which collision h...
python
{ "resource": "" }
q32606
AliasManager.write_alias_config_hash
train
def write_alias_config_hash(alias_config_hash='', empty_hash=False): """ Write self.alias_config_hash to the alias hash file. Args: empty_hash: True if we want to write an empty string into the file. Empty string in the alias hash file means that we have to perform a...
python
{ "resource": "" }
q32607
AliasManager.write_collided_alias
train
def write_collided_alias(collided_alias_dict): """ Write the collided aliases string into the collided alias file. """ # w+ creates the alias config file if it does not exist open_mode = 'r+' if os.path.exists(GLOBAL_COLLIDED_ALIAS_PATH) else 'w+' with open(GLOBAL_COLLIDE...
python
{ "resource": "" }
q32608
AliasManager.process_exception_message
train
def process_exception_message(exception): """ Process an exception message. Args: exception: The exception to process. Returns: A filtered string summarizing the exception. """ exception_message = str(exception) for replace_char in ['\t',...
python
{ "resource": "" }
q32609
get_network_resource_property_entry
train
def get_network_resource_property_entry(resource, prop): """ Factory method for creating get functions. """ def get_func(cmd, resource_group_name, resource_name, item_name): client = getattr(network_client_factory(cmd.cli_ctx), resource) items = getattr(client.get(resource_group_name, resource_...
python
{ "resource": "" }
q32610
transform_file_directory_result
train
def transform_file_directory_result(cli_ctx): """ Transform a the result returned from file and directory listing API. This transformer add and remove properties from File and Directory objects in the given list in order to align the object's properties so as to offer a better view to the file and dir ...
python
{ "resource": "" }
q32611
SubscriptionFactoryOperations.create_subscription_in_enrollment_account
train
def create_subscription_in_enrollment_account( self, enrollment_account_name, body, custom_headers=None, raw=False, polling=True, **operation_config): """Creates an Azure subscription. :param enrollment_account_name: The name of the enrollment account to which the subscription will...
python
{ "resource": "" }
q32612
transform_gateway
train
def transform_gateway(result): """Transform a gateway list to table output. """ return OrderedDict([('Name', result.get('name')), ('ResourceGroup', result.get('resourceGroup')), ('Location', result.get('location')), ('ProvisioningState', re...
python
{ "resource": "" }
q32613
collect_blobs
train
def collect_blobs(blob_service, container, pattern=None): """ List the blobs in the given blob container, filter the blob by comparing their path to the given pattern. """ if not blob_service: raise ValueError('missing parameter blob_service') if not container: raise ValueError('mis...
python
{ "resource": "" }
q32614
glob_files_locally
train
def glob_files_locally(folder_path, pattern): """glob files in local folder based on the given pattern""" pattern = os.path.join( folder_path, pattern.lstrip('/')) if pattern else None len_folder_path = len(folder_path) + 1 for root, _, files in os.walk(folder_path): for f in files: ...
python
{ "resource": "" }
q32615
glob_files_remotely
train
def glob_files_remotely(cmd, client, share_name, pattern): """glob the files in remote file share based on the given pattern""" from collections import deque t_dir, t_file = cmd.get_models('file.models#Directory', 'file.models#File') queue = deque([""]) while queue: current_dir = queue.pop(...
python
{ "resource": "" }
q32616
StorageCommandGroup._register_data_plane_account_arguments
train
def _register_data_plane_account_arguments(self, command_name): """ Add parameters required to create a storage client """ from azure.cli.core.commands.parameters import get_resource_name_completion_list from ._validators import validate_client_parameters command = self.command_loader.co...
python
{ "resource": "" }
q32617
get_k8s_upgrades_completion_list
train
def get_k8s_upgrades_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument """Return Kubernetes versions available for upgrading an existing cluster.""" resource_group = getattr(namespace, 'resource_group_name', None) name = getattr(namespace, 'name', None) return get_k8s...
python
{ "resource": "" }
q32618
get_k8s_versions_completion_list
train
def get_k8s_versions_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument """Return Kubernetes versions available for provisioning a new cluster.""" location = _get_location(cmd.cli_ctx, namespace) return get_k8s_versions(cmd.cli_ctx, location) if location else None
python
{ "resource": "" }
q32619
get_k8s_versions
train
def get_k8s_versions(cli_ctx, location): """Return a list of Kubernetes versions available for a new cluster.""" from ._client_factory import cf_container_services from jmespath import search # pylint: disable=import-error results = cf_container_services(cli_ctx).list_orchestrators(location, resource_...
python
{ "resource": "" }
q32620
get_vm_size_completion_list
train
def get_vm_size_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument """Return the intersection of the VM sizes allowed by the ACS SDK with those returned by the Compute Service.""" location = _get_location(cmd.cli_ctx, namespace) result = get_vm_sizes(cmd.cli_ctx, location...
python
{ "resource": "" }
q32621
normalize_placeholders
train
def normalize_placeholders(arg, inject_quotes=False): """ Normalize placeholders' names so that the template can be ingested into Jinja template engine. - Jinja does not accept numbers as placeholder names, so add a "_" before the numbers to make them valid placeholder names. - Surround placehol...
python
{ "resource": "" }
q32622
build_pos_args_table
train
def build_pos_args_table(full_alias, args, start_index): """ Build a dictionary where the key is placeholder name and the value is the position argument value. Args: full_alias: The full alias (including any placeholders). args: The arguments that the user inputs in the terminal. st...
python
{ "resource": "" }
q32623
render_template
train
def render_template(cmd_derived_from_alias, pos_args_table): """ Render cmd_derived_from_alias as a Jinja template with pos_args_table as the arguments. Args: cmd_derived_from_alias: The string to be injected with positional arguemnts. pos_args_table: The dictionary used to rendered. R...
python
{ "resource": "" }
q32624
float_to_decimal
train
def float_to_decimal(f): """ Convert a floating point number to a Decimal with no loss of information. Intended for Python 2.6 where casting float to Decimal does not work. """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) ctx = Context(prec=60) result =...
python
{ "resource": "" }
q32625
rule_variable
train
def rule_variable(field_type, label=None, options=None): """ Decorator to make a function into a rule variable """ options = options or [] def wrapper(func): if not (type(field_type) == type and issubclass(field_type, BaseType)): raise AssertionError("{0} is not instance of BaseType ...
python
{ "resource": "" }
q32626
type_operator
train
def type_operator(input_type, label=None, assert_type_for_arguments=True): """ Decorator to make a function into a type operator. - assert_type_for_arguments - if True this patches the operator function so that arguments passed to it will have _assert_valid_value_and_cast called o...
python
{ "resource": "" }
q32627
rule_action
train
def rule_action(label=None, params=None): """ Decorator to make a function into a rule action """ def wrapper(func): params_ = params if isinstance(params, dict): params_ = [dict(label=fn_name_to_pretty_label(name), name=name, ...
python
{ "resource": "" }
q32628
check_condition
train
def check_condition(condition, defined_variables): """ Checks a single rule condition - the condition will be made up of variables, values, and the comparison operator. The defined_variables object must have a variable defined for any variables in this condition. """ name, op, value = condition['nam...
python
{ "resource": "" }
q32629
_do_operator_comparison
train
def _do_operator_comparison(operator_type, operator_name, comparison_value): """ Finds the method on the given operator_type and compares it to the given comparison_value. operator_type should be an instance of operators.BaseType comparison_value is whatever python type to compare to returns a bool...
python
{ "resource": "" }
q32630
CaptchaAnswerInput.build_attrs
train
def build_attrs(self, *args, **kwargs): """Disable automatic corrections and completions.""" attrs = super(CaptchaAnswerInput, self).build_attrs(*args, **kwargs) attrs['autocapitalize'] = 'off' attrs['autocomplete'] = 'off' attrs['autocorrect'] = 'off' attrs['spellcheck']...
python
{ "resource": "" }
q32631
BaseCaptchaTextInput.fetch_captcha_store
train
def fetch_captcha_store(self, name, value, attrs=None, generator=None): """ Fetches a new CaptchaStore This has to be called inside render """ try: reverse('captcha-image', args=('dummy',)) except NoReverseMatch: raise ImproperlyConfigured('Make su...
python
{ "resource": "" }
q32632
CaptchaTextInput.get_context
train
def get_context(self, name, value, attrs): """Add captcha specific variables to context.""" context = super(CaptchaTextInput, self).get_context(name, value, attrs) context['image'] = self.image_url() context['audio'] = self.audio_url() return context
python
{ "resource": "" }
q32633
CaptchaTextInput._direct_render
train
def _direct_render(self, name, attrs): """Render the widget the old way - using field_template or output_format.""" context = { 'image': self.image_url(), 'name': name, 'key': self._key, 'id': u'%s_%s' % (self.id_prefix, attrs.get('id')) if self.id_prefix ...
python
{ "resource": "" }
q32634
captcha_refresh
train
def captcha_refresh(request): """ Return json with new captcha for ajax refresh request """ if not request.is_ajax(): raise Http404 new_key = CaptchaStore.pick() to_json_response = { 'key': new_key, 'image_url': captcha_image_url(new_key), 'audio_url': captcha_audio_url...
python
{ "resource": "" }
q32635
ZohoWebClient._add_zoho_token
train
def _add_zoho_token( self, uri, http_method="GET", body=None, headers=None, token_placement=None ): """Add a zoho token to the request uri, body or authorization header. follows bearer pattern""" headers = self.prepare_zoho_headers(self.access_token, headers) return uri, headers, bod...
python
{ "resource": "" }
q32636
ZohoWebClient.prepare_zoho_headers
train
def prepare_zoho_headers(token, headers=None): """Add a `Zoho Token`_ to the request URI. Recommended method of passing bearer tokens. Authorization: Zoho-oauthtoken h480djs93hd8 .. _`Zoho-oauthtoken Token`: custom zoho token """ headers = headers or {} headers[...
python
{ "resource": "" }
q32637
timestamp_from_datetime
train
def timestamp_from_datetime(dt): """ Given a datetime, in UTC, return a float that represents the timestamp for that datetime. http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python#8778548 """ dt = dt.replace(tzinfo=utc) if hasattr(dt, "timestamp") a...
python
{ "resource": "" }
q32638
abs_timedelta
train
def abs_timedelta(delta): """Returns an "absolute" value for a timedelta, always representing a time distance.""" if delta.days < 0: now = _now() return now - (now + delta) return delta
python
{ "resource": "" }
q32639
naturaltime
train
def naturaltime(value, future=False, months=True): """Given a datetime or a number of seconds, return a natural representation of that time in a resolution that makes sense. This is more or less compatible with Django's ``naturaltime`` filter. ``future`` is ignored for datetimes, where the tense is al...
python
{ "resource": "" }
q32640
naturalday
train
def naturalday(value, format='%b %d'): """For date values that are tomorrow, today or yesterday compared to present day returns representing string. Otherwise, returns a string formatted according to ``format``.""" try: value = date(value.year, value.month, value.day) except AttributeError: ...
python
{ "resource": "" }
q32641
naturaldate
train
def naturaldate(value): """Like naturalday, but will append a year for dates that are a year ago or more.""" try: value = date(value.year, value.month, value.day) except AttributeError: # Passed value wasn't date-ish return value except (OverflowError, ValueError): # ...
python
{ "resource": "" }
q32642
activate
train
def activate(locale, path=None): """Set 'locale' as current locale. Search for locale in directory 'path' @param locale: language name, eg 'en_GB'""" if path is None: path = _DEFAULT_LOCALE_PATH if locale not in _TRANSLATIONS: translation = gettext_module.translation('humanize', path, [l...
python
{ "resource": "" }
q32643
pgettext
train
def pgettext(msgctxt, message): """'Particular gettext' function. It works with 'msgctxt' .po modifiers and allow duplicate keys with different translations. Python 2 don't have support for this GNU gettext function, so we reimplement it. It works by joining msgctx and msgid by '4' byte.""" key ...
python
{ "resource": "" }
q32644
intcomma
train
def intcomma(value): """Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. To maintain some compatability with Django's intcomma, this function also accepts floats.""" try: if isinstance(value, compat.string_ty...
python
{ "resource": "" }
q32645
apnumber
train
def apnumber(value): """For numbers 1-9, returns the number spelled out. Otherwise, returns the number. This follows Associated Press style. This always returns a string unless the value was not int-able, unlike the Django filter.""" try: value = int(value) except (TypeError, ValueError): ...
python
{ "resource": "" }
q32646
keywords
train
def keywords(text): """get the top 10 keywords and their frequency scores ignores blacklisted words in stopWords, counts the number of occurrences of each word """ text = split_words(text) numWords = len(text) # of words before removing blacklist words freq = Counter(x for x in text if x no...
python
{ "resource": "" }
q32647
sentence_position
train
def sentence_position(i, size): """different sentence positions indicate different probability of being an important sentence""" normalized = i*1.0 / size if 0 < normalized <= 0.1: return 0.17 elif 0.1 < normalized <= 0.2: return 0.23 elif 0.2 < normalized <= 0.3: return...
python
{ "resource": "" }
q32648
ContentExtractor.split_title
train
def split_title(self, title, splitter): """\ Split the title to best part possible """ large_text_length = 0 large_text_index = 0 title_pieces = splitter.split(title) # find the largest title piece for i in range(len(title_pieces)): current = ...
python
{ "resource": "" }
q32649
ContentExtractor.is_boostable
train
def is_boostable(self, node): """\ alot of times the first paragraph might be the caption under an image so we'll want to make sure if we're going to boost a parent node that it should be connected to other paragraphs, at least for the first n paragraphs so we'll want to make sur...
python
{ "resource": "" }
q32650
ContentExtractor.get_siblings_content
train
def get_siblings_content(self, current_sibling, baselinescore_siblings_para): """\ adds any siblings that may have a decent score to this node """ if current_sibling.tag == 'p' and len(self.parser.getText(current_sibling)) > 0: e0 = current_sibling if e0.tail: ...
python
{ "resource": "" }
q32651
AsyncioEventLoop.connection_made
train
def connection_made(self, transport): """Used to signal `asyncio.Protocol` of a successful connection.""" self._transport = transport self._raw_transport = transport if isinstance(transport, asyncio.SubprocessTransport): self._transport = transport.get_pipe_transport(0)
python
{ "resource": "" }
q32652
AsyncioEventLoop.data_received
train
def data_received(self, data): """Used to signal `asyncio.Protocol` of incoming data.""" if self._on_data: self._on_data(data) return self._queued_data.append(data)
python
{ "resource": "" }
q32653
AsyncioEventLoop.pipe_data_received
train
def pipe_data_received(self, fd, data): """Used to signal `asyncio.SubprocessProtocol` of incoming data.""" if fd == 2: # stderr fd number self._on_stderr(data) elif self._on_data: self._on_data(data) else: self._queued_data.append(data)
python
{ "resource": "" }
q32654
format_exc_skip
train
def format_exc_skip(skip, limit=None): """Like traceback.format_exc but allow skipping the first frames.""" etype, val, tb = sys.exc_info() for i in range(skip): tb = tb.tb_next return (''.join(format_exception(etype, val, tb, limit))).rstrip()
python
{ "resource": "" }
q32655
AsyncSession.request
train
def request(self, method, args, response_cb): """Send a msgpack-rpc request to Nvim. A msgpack-rpc with method `method` and argument `args` is sent to Nvim. The `response_cb` function is called with when the response is available. """ request_id = self._next_request_id ...
python
{ "resource": "" }
q32656
Response.send
train
def send(self, value, error=False): """Send the response. If `error` is True, it will be sent as an error. """ if error: resp = [1, self._request_id, value, None] else: resp = [1, self._request_id, None, value] debug('sending response to request %...
python
{ "resource": "" }
q32657
start_host
train
def start_host(session=None): """Promote the current process into python plugin host for Nvim. Start msgpack-rpc event loop for `session`, listening for Nvim requests and notifications. It registers Nvim commands for loading/unloading python plugins. The sys.stdout and sys.stderr streams are redir...
python
{ "resource": "" }
q32658
attach
train
def attach(session_type, address=None, port=None, path=None, argv=None, decode=None): """Provide a nicer interface to create python api sessions. Previous machinery to create python api sessions is still there. This only creates a facade function to make things easier for the most usual cases. ...
python
{ "resource": "" }
q32659
setup_logging
train
def setup_logging(name): """Setup logging according to environment variables.""" logger = logging.getLogger(__name__) if 'NVIM_PYTHON_LOG_FILE' in os.environ: prefix = os.environ['NVIM_PYTHON_LOG_FILE'].strip() major_version = sys.version_info[0] logfile = '{}_py{}_{}'.format(prefix,...
python
{ "resource": "" }
q32660
main
train
def main(argv=sys.argv[1:]): """Parses the command line comments.""" usage = 'usage: %prog [options] FILE\n\n' + __doc__ parser = OptionParser(usage) # options parser.add_option("-f", "--force", action='store_true', default=False, help="make changes even ...
python
{ "resource": "" }
q32661
comment_lines
train
def comment_lines(lines): """Comment out the given list of lines and return them. The hash mark will be inserted before the first non-whitespace character on each line.""" ret = [] for line in lines: ws_prefix, rest, ignore = RE_LINE_SPLITTER_COMMENT.match(line).groups() ret.append(ws_p...
python
{ "resource": "" }
q32662
uncomment_lines
train
def uncomment_lines(lines): """Uncomment the given list of lines and return them. The first hash mark following any amount of whitespace will be removed on each line.""" ret = [] for line in lines: ws_prefix, rest, ignore = RE_LINE_SPLITTER_UNCOMMENT.match(line).groups() ret.append(ws_p...
python
{ "resource": "" }
q32663
get_level_value
train
def get_level_value(level): """Returns the logging value associated with a particular level name. The argument must be present in LEVELS_DICT or be an integer constant. Otherwise None will be returned.""" try: # integral constants also work: they are the level value return int(level) ...
python
{ "resource": "" }
q32664
get_logging_level
train
def get_logging_level(logging_stmt, commented_out=False): """Determines the level of logging in a given logging statement. The string representing this level is returned. False is returned if the method is not a logging statement and thus has no level. None is returned if a level should have been fou...
python
{ "resource": "" }
q32665
level_is_between
train
def level_is_between(level, min_level_value, max_level_value): """Returns True if level is between the specified min or max, inclusive.""" level_value = get_level_value(level) if level_value is None: # unknown level value return False return level_value >= min_level_value and level_value...
python
{ "resource": "" }
q32666
split_call
train
def split_call(lines, open_paren_line=0): """Returns a 2-tuple where the first element is the list of lines from the first open paren in lines to the matching closed paren. The second element is all remaining lines in a list.""" num_open = 0 num_closed = 0 for i, line in enumerate(lines): ...
python
{ "resource": "" }
q32667
modify_logging
train
def modify_logging(input_fn, output_fn, min_level_value, max_level_value, restore, force): """Modifies logging statements in the specified file.""" # read in all the lines logging.info('reading in %s' % input_fn) fh = open(input_fn, 'r') lines = fh.readlines() fh.close() original_contents = ...
python
{ "resource": "" }
q32668
check_level
train
def check_level(logging_stmt, logging_stmt_is_commented_out, min_level_value, max_level_value): """Extracts the level of the logging statement and returns True if the level falls betwen min and max_level_value. If the level cannot be extracted, then a warning is logged.""" level = get_logging_level(log...
python
{ "resource": "" }
q32669
disable_logging
train
def disable_logging(lines, min_level_value, max_level_value): """Disables logging statements in these lines whose logging level falls between the specified minimum and maximum levels.""" output = '' while lines: line = lines[0] ret = RE_LOGGING_START.match(line) if not ret: ...
python
{ "resource": "" }
q32670
check_async
train
def check_async(async_, kwargs, default): """Return a value of 'async' in kwargs or default when async_ is None. This helper function exists for backward compatibility (See #274). It shows a warning message when 'async' in kwargs is used to note users. """ if async_ is not None: return asyn...
python
{ "resource": "" }
q32671
plugin
train
def plugin(cls): """Tag a class as a plugin. This decorator is required to make the class methods discoverable by the plugin_load method of the host. """ cls._nvim_plugin = True # the _nvim_bind attribute is set to True by default, meaning that # decorated functions have a bound Nvim instan...
python
{ "resource": "" }
q32672
rpc_export
train
def rpc_export(rpc_method_name, sync=False): """Export a function or plugin method as a msgpack-rpc request handler.""" def dec(f): f._nvim_rpc_method_name = rpc_method_name f._nvim_rpc_sync = sync f._nvim_bind = True f._nvim_prefix_plugin_path = False return f return...
python
{ "resource": "" }
q32673
command
train
def command(name, nargs=0, complete=None, range=None, count=None, bang=False, register=False, sync=False, allow_nested=False, eval=None): """Tag a function or plugin method as a Nvim command handler.""" def dec(f): f._nvim_rpc_method_name = 'command:{}'.format(name) f._nvim_rpc_sync ...
python
{ "resource": "" }
q32674
autocmd
train
def autocmd(name, pattern='*', sync=False, allow_nested=False, eval=None): """Tag a function or plugin method as a Nvim autocommand handler.""" def dec(f): f._nvim_rpc_method_name = 'autocmd:{}:{}'.format(name, pattern) f._nvim_rpc_sync = sync f._nvim_bind = True f._nvim_prefix_p...
python
{ "resource": "" }
q32675
function
train
def function(name, range=False, sync=False, allow_nested=False, eval=None): """Tag a function or plugin method as a Nvim function handler.""" def dec(f): f._nvim_rpc_method_name = 'function:{}'.format(name) f._nvim_rpc_sync = sync f._nvim_bind = True f._nvim_prefix_plugin_path = ...
python
{ "resource": "" }
q32676
Nvim.from_session
train
def from_session(cls, session): """Create a new Nvim instance for a Session instance. This method must be called to create the first Nvim instance, since it queries Nvim metadata for type information and sets a SessionHook for creating specialized objects from Nvim remote handles. ...
python
{ "resource": "" }
q32677
Nvim.from_nvim
train
def from_nvim(cls, nvim): """Create a new Nvim instance from an existing instance.""" return cls(nvim._session, nvim.channel_id, nvim.metadata, nvim.types, nvim._decode, nvim._err_cb)
python
{ "resource": "" }
q32678
Nvim.request
train
def request(self, name, *args, **kwargs): r"""Send an API request or notification to nvim. It is rarely needed to call this function directly, as most API functions have python wrapper functions. The `api` object can be also be used to call API functions as methods: vim.api...
python
{ "resource": "" }
q32679
Nvim.with_decode
train
def with_decode(self, decode=True): """Initialize a new Nvim instance.""" return Nvim(self._session, self.channel_id, self.metadata, self.types, decode, self._err_cb)
python
{ "resource": "" }
q32680
Nvim.ui_attach
train
def ui_attach(self, width, height, rgb=None, **kwargs): """Register as a remote UI. After this method is called, the client will receive redraw notifications. """ options = kwargs if rgb is not None: options['rgb'] = rgb return self.request('nvim_ui_a...
python
{ "resource": "" }
q32681
Nvim.call
train
def call(self, name, *args, **kwargs): """Call a vimscript function.""" return self.request('nvim_call_function', name, args, **kwargs)
python
{ "resource": "" }
q32682
Nvim.exec_lua
train
def exec_lua(self, code, *args, **kwargs): """Execute lua code. Additional parameters are available as `...` inside the lua chunk. Only statements are executed. To evaluate an expression, prefix it with `return`: `return my_function(...)` There is a shorthand syntax to call lu...
python
{ "resource": "" }
q32683
Nvim.feedkeys
train
def feedkeys(self, keys, options='', escape_csi=True): """Push `keys` to Nvim user input buffer. Options can be a string with the following character flags: - 'm': Remap keys. This is default. - 'n': Do not remap keys. - 't': Handle keys as if typed; otherwise they are handled a...
python
{ "resource": "" }
q32684
Nvim.replace_termcodes
train
def replace_termcodes(self, string, from_part=False, do_lt=True, special=True): r"""Replace any terminal code strings by byte sequences. The returned sequences are Nvim's internal representation of keys, for example: <esc> -> '\x1b' <cr> -> '\r' ...
python
{ "resource": "" }
q32685
Nvim.err_write
train
def err_write(self, msg, **kwargs): r"""Print `msg` as an error message. The message is buffered (won't display) until linefeed ("\n"). """ if self._thread_invalid(): # special case: if a non-main thread writes to stderr # i.e. due to an uncaught exception, pass ...
python
{ "resource": "" }
q32686
Nvim.async_call
train
def async_call(self, fn, *args, **kwargs): """Schedule `fn` to be called by the event loop soon. This function is thread-safe, and is the only way code not on the main thread could interact with nvim api objects. This function can also be called in a synchronous event handler, ...
python
{ "resource": "" }
q32687
Buffer.append
train
def append(self, lines, index=-1): """Append a string or list of lines to the buffer.""" if isinstance(lines, (basestring, bytes)): lines = [lines] return self.request('nvim_buf_set_lines', index, index, True, lines)
python
{ "resource": "" }
q32688
Buffer.add_highlight
train
def add_highlight(self, hl_group, line, col_start=0, col_end=-1, src_id=-1, async_=None, **kwargs): """Add a highlight to the buffer.""" async_ = check_async(async_, kwargs, src_id != 0) return self.request('nvim_buf_add_highlight', src_id, hl_group, ...
python
{ "resource": "" }
q32689
Buffer.clear_highlight
train
def clear_highlight(self, src_id, line_start=0, line_end=-1, async_=None, **kwargs): """Clear highlights from the buffer.""" async_ = check_async(async_, kwargs, True) self.request('nvim_buf_clear_highlight', src_id, line_start, line_end, async_=async...
python
{ "resource": "" }
q32690
Buffer.update_highlights
train
def update_highlights(self, src_id, hls, clear_start=0, clear_end=-1, clear=False, async_=True): """Add or update highlights in batch to avoid unnecessary redraws. A `src_id` must have been allocated prior to use of this function. Use for instance `nvim.new_highlight_s...
python
{ "resource": "" }
q32691
Host.start
train
def start(self, plugins): """Start listening for msgpack-rpc requests and notifications.""" self.nvim.run_loop(self._on_request, self._on_notification, lambda: self._load(plugins), err_cb=self._on_async_err)
python
{ "resource": "" }
q32692
Host._on_request
train
def _on_request(self, name, args): """Handle a msgpack-rpc request.""" if IS_PYTHON3: name = decode_if_bytes(name) handler = self._request_handlers.get(name, None) if not handler: msg = self._missing_handler_error(name, 'request') error(msg) ...
python
{ "resource": "" }
q32693
Host._on_notification
train
def _on_notification(self, name, args): """Handle a msgpack-rpc notification.""" if IS_PYTHON3: name = decode_if_bytes(name) handler = self._notification_handlers.get(name, None) if not handler: msg = self._missing_handler_error(name, 'notification') e...
python
{ "resource": "" }
q32694
decode_if_bytes
train
def decode_if_bytes(obj, mode=True): """Decode obj if it is bytes.""" if mode is True: mode = unicode_errors_default if isinstance(obj, bytes): return obj.decode("utf-8", errors=mode) return obj
python
{ "resource": "" }
q32695
Remote.request
train
def request(self, name, *args, **kwargs): """Wrapper for nvim.request.""" return self._session.request(name, self, *args, **kwargs)
python
{ "resource": "" }
q32696
MsgpackStream.send
train
def send(self, msg): """Queue `msg` for sending to Nvim.""" debug('sent %s', msg) self.loop.send(self._packer.pack(msg))
python
{ "resource": "" }
q32697
MsgpackStream.run
train
def run(self, message_cb): """Run the event loop to receive messages from Nvim. While the event loop is running, `message_cb` will be called whenever a message has been successfully parsed from the input stream. """ self._message_cb = message_cb self.loop.run(self._on_da...
python
{ "resource": "" }
q32698
Session.threadsafe_call
train
def threadsafe_call(self, fn, *args, **kwargs): """Wrapper around `AsyncSession.threadsafe_call`.""" def handler(): try: fn(*args, **kwargs) except Exception: warn("error caught while excecuting async callback\n%s\n", format_ex...
python
{ "resource": "" }
q32699
Session.request
train
def request(self, method, *args, **kwargs): """Send a msgpack-rpc request and block until as response is received. If the event loop is running, this method must have been called by a request or notification handler running on a greenlet. In that case, send the quest and yield to the pa...
python
{ "resource": "" }