_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q32400
from_dict
train
def from_dict(data, require=None): """Validates a dictionary containing Google service account data. Creates and returns a :class:`google.auth.crypt.Signer` instance from the private key specified in the data. Args: data (Mapping[str, str]): The service account data require (Sequence[s...
python
{ "resource": "" }
q32401
from_filename
train
def from_filename(filename, require=None): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. Returns: Tuple...
python
{ "resource": "" }
q32402
copy_docstring
train
def copy_docstring(source_class): """Decorator that copies a method's docstring from another class. Args: source_class (type): The class that has the documented method. Returns: Callable: A decorator that will copy the docstring of the same named method in the source class to t...
python
{ "resource": "" }
q32403
from_bytes
train
def from_bytes(value): """Converts bytes to a string value, if necessary. Args: value (Union[str, bytes]): The value to be converted. Returns: str: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. Raises: ValueError: ...
python
{ "resource": "" }
q32404
update_query
train
def update_query(url, params, remove=None): """Updates a URL's query parameters. Replaces any current values if they are already present in the URL. Args: url (str): The URL to update. params (Mapping[str, str]): A mapping of query parameter keys to values. remove (Sequ...
python
{ "resource": "" }
q32405
padded_urlsafe_b64decode
train
def padded_urlsafe_b64decode(value): """Decodes base64 strings lacking padding characters. Google infrastructure tends to omit the base64 padding characters. Args: value (Union[str, bytes]): The encoded value. Returns: bytes: The decoded value """ b64string = to_bytes(value) ...
python
{ "resource": "" }
q32406
configure_processes
train
def configure_processes(agent_metadata_map, logger): """ This will update the priority and CPU affinity of the processes owned by bots to try to achieve fairness and good performance. :param agent_metadata_map: A mapping of player index to agent metadata, including a list of owned process ids. """ ...
python
{ "resource": "" }
q32407
ConfigObject.get_header
train
def get_header(self, header_name): """ Returns a header with that name, creates it if it does not exist. """ if header_name in self.headers: return self.headers[header_name] return self.add_header_name(header_name)
python
{ "resource": "" }
q32408
log_warn
train
def log_warn(message, args): """Logs a warning message using the default logger.""" get_logger(DEFAULT_LOGGER, log_creation=False).log(logging.WARNING, message, *args)
python
{ "resource": "" }
q32409
CarCustomisationDialog.create_config_headers_dicts
train
def create_config_headers_dicts(self): """ Creates the config_headers_to_widgets and config_widgets_to_headers and config_headers_to_categories dicts """ self.config_headers_to_widgets = { # blue stuff 'Bot Loadout': { 'team_color_id': (self.blue_p...
python
{ "resource": "" }
q32410
get_rlbot_directory
train
def get_rlbot_directory() -> str: """Gets the path of the rlbot package directory""" return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
python
{ "resource": "" }
q32411
read_match_config_from_file
train
def read_match_config_from_file(match_config_path: Path) -> MatchConfig: """ Parse the rlbot.cfg file on disk into the python datastructure. """ config_obj = create_bot_config_layout() config_obj.parse_file(match_config_path, max_index=MAX_PLAYERS) return parse_match_config(config_obj, match_con...
python
{ "resource": "" }
q32412
validate_bot_config
train
def validate_bot_config(config_bundle) -> None: """ Checks the config bundle to see whether it has all required attributes. """ if not config_bundle.name: bot_config = os.path.join(config_bundle.config_directory, config_bundle.config_file_name or '') raise AttributeError(f"Bot config {bo...
python
{ "resource": "" }
q32413
HelperProcessManager.start_or_update_helper_process
train
def start_or_update_helper_process(self, agent_metadata: AgentMetadata): """ Examines the agent metadata to see if the agent needs a helper process. If the process is not running yet, create the process. Once the process is running, feed the agent metadata to it. If a process is created...
python
{ "resource": "" }
q32414
PlayerConfig.bot_config
train
def bot_config(player_config_path: Path, team: Team) -> 'PlayerConfig': """ A function to cover the common case of creating a config for a bot. """ bot_config = PlayerConfig() bot_config.bot = True bot_config.rlbot_controlled = True bot_config.team = team.value ...
python
{ "resource": "" }
q32415
setup_manager_context
train
def setup_manager_context(): """ Creates a initialized context manager which shuts down at the end of the `with` block. usage: >>> with setup_manager_context() as setup_manager: ... setup_manager.load_config(...) ... # ... Run match """ setup_manager = SetupManager() set...
python
{ "resource": "" }
q32416
SetupManager.load_match_config
train
def load_match_config(self, match_config: MatchConfig, bot_config_overrides={}): """ Loads the match config into internal data structures, which prepares us to later launch bot processes and start the match. This is an alternative to the load_config method; they accomplish the same thin...
python
{ "resource": "" }
q32417
SetupManager.load_config
train
def load_config(self, framework_config: ConfigObject = None, config_location=DEFAULT_RLBOT_CONFIG_LOCATION, bot_configs=None, looks_configs=None): """ Loads the configuration into internal data structures, which prepares us to later launch bot processes an...
python
{ "resource": "" }
q32418
load_external_module
train
def load_external_module(python_file): """ Returns the loaded module. All of its newly added dependencies are removed from sys.path after load. """ # There's a special case where python_file may be pointing at the base agent definition here in the framework. # This is sometimes done as a defaul...
python
{ "resource": "" }
q32419
BotManager.send_quick_chat_from_agent
train
def send_quick_chat_from_agent(self, team_only, quick_chat): """ Passes the agents quick chats to the game, and also to other python bots. This does perform limiting. You are limited to 5 quick chats in a 2 second period starting from the first chat. This means you can spread you...
python
{ "resource": "" }
q32420
BotManager.run
train
def run(self): """ Loads interface for RLBot, prepares environment and agent, and calls the update for the agent. """ self.logger.debug('initializing agent') self.game_interface.load_interface() self.prepare_for_run() # Create Ratelimiter rate_limit = ra...
python
{ "resource": "" }
q32421
RLBotQTGui.clean_overall_config_loadouts
train
def clean_overall_config_loadouts(self): """ Set all unusued loadout paths to None. This makes sure agents don't have a custom loadout when new agents are added in the gui. """ for i in range(MAX_PLAYERS): if i not in self.index_manager.numbers: self.o...
python
{ "resource": "" }
q32422
BaseAgent.convert_output_to_v4
train
def convert_output_to_v4(self, controller_input): """Converts a v3 output to a v4 controller state""" player_input = SimpleControllerState() player_input.throttle = controller_input[0] player_input.steer = controller_input[1] player_input.pitch = controller_input[2] playe...
python
{ "resource": "" }
q32423
_wait_until_good_ticks
train
def _wait_until_good_ticks(game_interface: GameInterface, required_new_ticks: int=3): """Blocks until we're getting new packets, indicating that the match is ready.""" rate_limit = rate_limiter.RateLimiter(120) last_tick_game_time = None # What the tick time of the last observed tick was packet = GameT...
python
{ "resource": "" }
q32424
training_status_renderer_context
train
def training_status_renderer_context(exercise_names: List[str], renderman: RenderingManager): """ Ensures that the screen is always cleared, even on fatal errors in code that uses this renderer. """ renderer = TrainingStatusRenderer(exercise_names, renderman) try: yield renderer fina...
python
{ "resource": "" }
q32425
GameInterface.inject_dll
train
def inject_dll(self): """ Calling this function will inject the DLL without GUI DLL will return status codes from 0 to 5 which correspond to injector_codes DLL injection is only valid if codes are 0->'INJECTION_SUCCESSFUL' or 3->'RLBOT_DLL_ALREADY_INJECTED' It will print the outp...
python
{ "resource": "" }
q32426
GameInterface.update_rigid_body_tick
train
def update_rigid_body_tick(self, rigid_body_tick: RigidBodyTick): """Get the most recent state of the physics engine.""" rlbot_status = self.game.UpdateRigidBodyTick(rigid_body_tick) self.game_status(None, rlbot_status) return rigid_body_tick
python
{ "resource": "" }
q32427
GameInterface.get_ball_prediction
train
def get_ball_prediction(self) -> BallPredictionPacket: """ Gets the latest ball prediction available in shared memory. Only works if BallPrediction.exe is running. """ byte_buffer = self.game.GetBallPrediction() if byte_buffer.size >= 4: # GetRootAsGameTickPacket gets angry if ...
python
{ "resource": "" }
q32428
CarState.convert_to_flat
train
def convert_to_flat(self, builder): """ In this conversion, we always want to return a valid flatbuffer pointer even if all the contents are blank because sometimes we need to put empty car states into the car list to make the indices line up. """ physics_offset = None if...
python
{ "resource": "" }
q32429
BoostState.convert_to_flat
train
def convert_to_flat(self, builder): """ In this conversion, we always want to return a valid flatbuffer pointer even if all the contents are blank because sometimes we need to put empty boost states into the boost list to make the indices line up. """ DesiredBoostState.D...
python
{ "resource": "" }
q32430
BloggingEngine.init_app
train
def init_app(self, app, storage=None, cache=None, file_upload=None): """ Initialize the engine. :param app: The app to use :type app: Object :param storage: The blog storage instance that implements the :type storage: Object :param cache: (Optional) A Flask-Cache...
python
{ "resource": "" }
q32431
SQLAStorage.get_post_by_id
train
def get_post_by_id(self, post_id): """ Fetch the blog post given by ``post_id`` :param post_id: The post identifier for the blog post :type post_id: str :return: If the ``post_id`` is valid, the post data is retrieved, else returns ``None``. """ r = None...
python
{ "resource": "" }
q32432
SQLAStorage.count_posts
train
def count_posts(self, tag=None, user_id=None, include_draft=False): """ Returns the total number of posts for the give filter :param tag: Filter by a specific tag :type tag: str :param user_id: Filter by a specific user :type user_id: str :param include_draft: Wh...
python
{ "resource": "" }
q32433
SQLAStorage.delete_post
train
def delete_post(self, post_id): """ Delete the post defined by ``post_id`` :param post_id: The identifier corresponding to a post :type post_id: int :return: Returns True if the post was successfully deleted and False otherwise. """ status = False ...
python
{ "resource": "" }
q32434
index
train
def index(count, page): """ Serves the page with a list of blog posts :param count: :param offset: :return: """ blogging_engine = _get_blogging_engine(current_app) storage = blogging_engine.storage config = blogging_engine.config count = count or config.get("BLOGGING_POSTS_PER_P...
python
{ "resource": "" }
q32435
convert_to_dict
train
def convert_to_dict(obj): """Converts a StripeObject back to a regular dict. Nested StripeObjects are also converted back to regular dicts. :param obj: The StripeObject to convert. :returns: The StripeObject as a dict. """ if isinstance(obj, list): return [convert_to_dict(i) for i in ...
python
{ "resource": "" }
q32436
Browser
train
def Browser(driver_name="firefox", *args, **kwargs): """ Returns a driver instance for the given name. When working with ``firefox``, it's possible to provide a profile name and a list of extensions. If you don't provide any driver_name, then ``firefox`` will be used. If there is no driver re...
python
{ "resource": "" }
q32437
Window.title
train
def title(self): """ The title of this window """ with switch_window(self._browser, self.name): return self._browser.title
python
{ "resource": "" }
q32438
Window.url
train
def url(self): """ The url of this window """ with switch_window(self._browser, self.name): return self._browser.url
python
{ "resource": "" }
q32439
Window.prev
train
def prev(self): """ Return the previous window """ prev_index = self.index - 1 prev_handle = self._browser.driver.window_handles[prev_index] return Window(self._browser, prev_handle)
python
{ "resource": "" }
q32440
Window.next
train
def next(self): """ Return the next window """ next_index = (self.index + 1) % len(self._browser.driver.window_handles) next_handle = self._browser.driver.window_handles[next_index] return Window(self._browser, next_handle)
python
{ "resource": "" }
q32441
Window.close
train
def close(self): """ Close this window. If this window is active, switch to previous window """ target = self.prev if (self.is_current and self.prev != self) else None with switch_window(self._browser, self.name): self._browser.driver.close() if target is not None: ...
python
{ "resource": "" }
q32442
WebDriverElement.mouse_over
train
def mouse_over(self): """ Performs a mouse over the element. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).move_to_element(self._element).perform()
python
{ "resource": "" }
q32443
WebDriverElement.mouse_out
train
def mouse_out(self): """ Performs a mouse out the element. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).move_by_offset(0, 0).click().perform()
python
{ "resource": "" }
q32444
WebDriverElement.double_click
train
def double_click(self): """ Performs a double click in the element. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).double_click(self._element).perform()
python
{ "resource": "" }
q32445
WebDriverElement.right_click
train
def right_click(self): """ Performs a right click in the element. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).context_click(self._element).perform()
python
{ "resource": "" }
q32446
WebDriverElement.drag_and_drop
train
def drag_and_drop(self, droppable): """ Performs drag a element to another elmenet. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()
python
{ "resource": "" }
q32447
force_unicode
train
def force_unicode(value): """ Forces a bytestring to become a Unicode string. """ if IS_PY3: # Python 3.X if isinstance(value, bytes): value = value.decode('utf-8', errors='replace') elif not isinstance(value, str): value = str(value) else: # P...
python
{ "resource": "" }
q32448
force_bytes
train
def force_bytes(value): """ Forces a Unicode string to become a bytestring. """ if IS_PY3: if isinstance(value, str): value = value.encode('utf-8', 'backslashreplace') else: if isinstance(value, unicode): # NOQA: F821 value = value.encode('utf-8') return...
python
{ "resource": "" }
q32449
safe_urlencode
train
def safe_urlencode(params, doseq=0): """ UTF-8-safe version of safe_urlencode The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values which can't fail down to ascii. """ if IS_PY3: return urlencode(params, doseq) if hasattr(params, "items"): params = params.ite...
python
{ "resource": "" }
q32450
Solr._extract_error
train
def _extract_error(self, resp): """ Extract the actual error message from a solr response. """ reason = resp.headers.get('reason', None) full_response = None if reason is None: try: # if response is in json format reason = resp...
python
{ "resource": "" }
q32451
Solr._scrape_response
train
def _scrape_response(self, headers, response): """ Scrape the html response. """ # identify the responding server server_type = None server_string = headers.get('server', '') if server_string and 'jetty' in server_string.lower(): server_type = 'jetty'...
python
{ "resource": "" }
q32452
Solr._from_python
train
def _from_python(self, value): """ Converts python values to a form suitable for insertion into the xml we send to solr. """ if hasattr(value, 'strftime'): if hasattr(value, 'hour'): offset = value.utcoffset() if offset: ...
python
{ "resource": "" }
q32453
Solr._to_python
train
def _to_python(self, value): """ Converts values from Solr to native Python values. """ if isinstance(value, (int, float, long, complex)): return value if isinstance(value, (list, tuple)): value = value[0] if value == 'true': return T...
python
{ "resource": "" }
q32454
Solr._is_null_value
train
def _is_null_value(self, value): """ Check if a given value is ``null``. Criteria for this is based on values that shouldn't be included in the Solr ``add`` request at all. """ if value is None: return True if IS_PY3: # Python 3.X ...
python
{ "resource": "" }
q32455
Solr.search
train
def search(self, q, search_handler=None, **kwargs): """ Performs a search and returns the results. Requires a ``q`` for a string version of the query to run. Optionally accepts ``**kwargs`` for additional options to be passed through the Solr URL. Returns ``self.result...
python
{ "resource": "" }
q32456
Solr.more_like_this
train
def more_like_this(self, q, mltfl, handler='mlt', **kwargs): """ Finds and returns results similar to the provided query. Returns ``self.results_cls`` class object (defaults to ``pysolr.Results``) Requires Solr 1.3+. Usage:: similar = solr.more_like_this('...
python
{ "resource": "" }
q32457
Solr.suggest_terms
train
def suggest_terms(self, fields, prefix, handler='terms', **kwargs): """ Accepts a list of field names and a prefix Returns a dictionary keyed on field name containing a list of ``(term, count)`` pairs Requires Solr 1.4+. """ params = { 'terms.fl': fi...
python
{ "resource": "" }
q32458
Solr.add
train
def add(self, docs, boost=None, fieldUpdates=None, commit=None, softCommit=False, commitWithin=None, waitFlush=None, waitSearcher=None, overwrite=None, handler='update'): """ Adds or updates documents. Requires ``docs``, which is a list of dictionaries. Each key is the field...
python
{ "resource": "" }
q32459
Solr.delete
train
def delete(self, id=None, q=None, commit=None, softCommit=False, waitFlush=None, waitSearcher=None, handler='update'): # NOQA: A002 """ Deletes documents. Requires *either* ``id`` or ``query``. ``id`` is if you know the specific document id to remove. Note that ``id`` can also be a lis...
python
{ "resource": "" }
q32460
Solr.commit
train
def commit(self, softCommit=False, waitFlush=None, waitSearcher=None, expungeDeletes=None, handler='update'): """ Forces Solr to write the index data to disk. Optionally accepts ``expungeDeletes``. Default is ``None``. Optionally accepts ``waitFlush``. Default is ``None``. Opt...
python
{ "resource": "" }
q32461
Solr.optimize
train
def optimize(self, commit=True, waitFlush=None, waitSearcher=None, maxSegments=None, handler='update'): """ Tells Solr to streamline the number of segments used, essentially a defragmentation operation. Optionally accepts ``maxSegments``. Default is ``None``. Optionally accepts...
python
{ "resource": "" }
q32462
Solr.ping
train
def ping(self, handler='admin/ping', **kwargs): """ Sends a ping request. Usage:: solr.ping() """ params = kwargs params_encoded = safe_urlencode(params, True) if len(params_encoded) < 1024: # Typical case. path = '%s/?%s' %...
python
{ "resource": "" }
q32463
InteractiveKeyBindings.format_response
train
def format_response(self, response): """ formats a response in a binary """ conversion = self.shell_ctx.config.BOOLEAN_STATES if response in conversion: if conversion[response]: return 'yes' return 'no' raise ValueError('Invalid response: input sho...
python
{ "resource": "" }
q32464
get_window_dim
train
def get_window_dim(): """ gets the dimensions depending on python version and os""" version = sys.version_info if version >= (3, 3): return _size_36() if platform.system() == 'Windows': return _size_windows() return _size_27()
python
{ "resource": "" }
q32465
_size_36
train
def _size_36(): """ returns the rows, columns of terminal """ from shutil import get_terminal_size dim = get_terminal_size() if isinstance(dim, list): return dim[0], dim[1] return dim.lines, dim.columns
python
{ "resource": "" }
q32466
update_frequency
train
def update_frequency(shell_ctx): """ updates the frequency from files """ frequency_path = os.path.join(shell_ctx.config.get_config_dir(), shell_ctx.config.get_frequency()) if os.path.exists(frequency_path): with open(frequency_path, 'r') as freq: try: frequency = json.lo...
python
{ "resource": "" }
q32467
frequency_measurement
train
def frequency_measurement(shell_ctx): """ measures how many times a user has used this program in the last calendar week """ freq = update_frequency(shell_ctx) count = 0 base = datetime.datetime.utcnow() date_list = [base - datetime.timedelta(days=x) for x in range(0, DAYS_AGO)] for day in date_...
python
{ "resource": "" }
q32468
get_public_ip_validator
train
def get_public_ip_validator(): """ Retrieves a validator for public IP address. Accepting all defaults will perform a check for an existing name or ID with no ARM-required -type parameter. """ from msrestazure.tools import is_valid_resource_id, resource_id def simple_validator(cmd, namespace): ...
python
{ "resource": "" }
q32469
load_help_files
train
def load_help_files(data): """ loads all the extra information from help files """ for command_name, help_yaml in helps.items(): help_entry = yaml.safe_load(help_yaml) try: help_type = help_entry['type'] except KeyError: continue # if there is extra help...
python
{ "resource": "" }
q32470
get_cache_dir
train
def get_cache_dir(shell_ctx): """ gets the location of the cache """ azure_folder = shell_ctx.config.get_config_dir() cache_path = os.path.join(azure_folder, 'cache') if not os.path.exists(azure_folder): os.makedirs(azure_folder) if not os.path.exists(cache_path): os.makedirs(cache_p...
python
{ "resource": "" }
q32471
FreshTable.dump_command_table
train
def dump_command_table(self, shell_ctx=None): """ dumps the command table """ from azure.cli.core.commands.arm import register_global_subscription_argument, register_ids_argument from knack import events import timeit start_time = timeit.default_timer() shell_ctx = shell...
python
{ "resource": "" }
q32472
_query_account_key
train
def _query_account_key(cli_ctx, account_name): """Query the storage account key. This is used when the customer doesn't offer account key but name.""" rg, scf = _query_account_rg(cli_ctx, account_name) t_storage_account_keys = get_sdk( cli_ctx, CUSTOM_MGMT_STORAGE, 'models.storage_account_keys#Stora...
python
{ "resource": "" }
q32473
_query_account_rg
train
def _query_account_rg(cli_ctx, account_name): """Query the storage account's resource group, which the mgmt sdk requires.""" scf = get_mgmt_service_client(cli_ctx, CUSTOM_MGMT_STORAGE) acc = next((x for x in scf.storage_accounts.list() if x.name == account_name), None) if acc: from msrestazure.t...
python
{ "resource": "" }
q32474
process_resource_group
train
def process_resource_group(cmd, namespace): """Processes the resource group parameter from the account name""" if namespace.account_name and not namespace.resource_group_name: namespace.resource_group_name = _query_account_rg(cmd.cli_ctx, namespace.account_name)[0]
python
{ "resource": "" }
q32475
validate_client_parameters
train
def validate_client_parameters(cmd, namespace): """ Retrieves storage connection parameters from environment variables and parses out connection string into account name and key """ n = namespace def get_config_value(section, key, default): return cmd.cli_ctx.config.get(section, key, default) ...
python
{ "resource": "" }
q32476
validate_encryption_services
train
def validate_encryption_services(cmd, namespace): """ Builds up the encryption services object for storage account operations based on the list of services passed in. """ if namespace.encryption_services: t_encryption_services, t_encryption_service = get_sdk(cmd.cli_ctx, CUSTOM_MGMT_STORAGE, ...
python
{ "resource": "" }
q32477
get_file_path_validator
train
def get_file_path_validator(default_file_param=None): """ Creates a namespace validator that splits out 'path' into 'directory_name' and 'file_name'. Allows another path-type parameter to be named which can supply a default filename. """ def validator(namespace): if not hasattr(namespace, 'path'): ...
python
{ "resource": "" }
q32478
ipv4_range_type
train
def ipv4_range_type(string): """ Validates an IPv4 address or address range. """ import re ip_format = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' if not re.match("^{}$".format(ip_format), string): if not re.match("^{ip_format}-{ip_format}$".format(ip_format=ip_format), string): raise Valu...
python
{ "resource": "" }
q32479
resource_type_type
train
def resource_type_type(loader): """ Returns a function which validates that resource types string contains only a combination of service, container, and object. Their shorthand representations are s, c, and o. """ def impl(string): t_resources = loader.get_models('common.models#ResourceTypes') ...
python
{ "resource": "" }
q32480
services_type
train
def services_type(loader): """ Returns a function which validates that services string contains only a combination of blob, queue, table, and file. Their shorthand representations are b, q, t, and f. """ def impl(string): t_services = loader.get_models('common.models#Services') if set(strin...
python
{ "resource": "" }
q32481
validate_k8s_version
train
def validate_k8s_version(namespace): """Validates a string as a possible Kubernetes version. An empty string is also valid, which tells the server to use its default version.""" if namespace.kubernetes_version: k8s_release_regex = re.compile(r'^[v|V]?(\d+\.\d+\.\d+.*)$') found = k8s_release_...
python
{ "resource": "" }
q32482
validate_linux_host_name
train
def validate_linux_host_name(namespace): """Validates a string as a legal host name component. This validation will also occur server-side in the ARM API, but that may take a minute or two before the user sees it. So it's more user-friendly to validate in the CLI pre-flight. """ # https://stack...
python
{ "resource": "" }
q32483
validate_max_pods
train
def validate_max_pods(namespace): """Validates that max_pods is set to a reasonable minimum number.""" # kube-proxy and kube-svc reside each nodes, # 2 kube-proxy pods, 1 azureproxy/heapster/dashboard/tunnelfront are in kube-system minimum_pods_required = ceil((namespace.node_count * 2 + 6 + 1) / namesp...
python
{ "resource": "" }
q32484
validate_nodes_count
train
def validate_nodes_count(namespace): """Validate that min_count and max_count is set to 1-100""" if namespace.min_count is not None: if namespace.min_count < 1 or namespace.min_count > 100: raise CLIError('--min-count must be in the range [1,100]') if namespace.max_count is not None: ...
python
{ "resource": "" }
q32485
validate_nodepool_name
train
def validate_nodepool_name(namespace): """Validates a nodepool name to be at most 12 characters, alphanumeric only.""" if namespace.nodepool_name != "": if len(namespace.nodepool_name) > 12: raise CLIError('--nodepool-name can contain atmost 12 characters') if not namespace.nodepool_...
python
{ "resource": "" }
q32486
CloudStorageAccount.create_block_blob_service
train
def create_block_blob_service(self): ''' Creates a BlockBlobService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.blob.blockblobservice.BlockBlobService` ''' try: from azure.s...
python
{ "resource": "" }
q32487
CloudStorageAccount.create_page_blob_service
train
def create_page_blob_service(self): ''' Creates a PageBlobService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.blob.pageblobservice.PageBlobService` ''' try: from azure.stora...
python
{ "resource": "" }
q32488
CloudStorageAccount.create_append_blob_service
train
def create_append_blob_service(self): ''' Creates a AppendBlobService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.blob.appendblobservice.AppendBlobService` ''' try: from azu...
python
{ "resource": "" }
q32489
CloudStorageAccount.create_queue_service
train
def create_queue_service(self): ''' Creates a QueueService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.queue.queueservice.QueueService` ''' try: from azure.storage.queue.que...
python
{ "resource": "" }
q32490
QueueService.exists
train
def exists(self, queue_name, timeout=None): ''' Returns a boolean indicating whether the queue exists. :param str queue_name: The name of queue to check for existence. :param int timeout: The server timeout, expressed in seconds. :return: A boolean indica...
python
{ "resource": "" }
q32491
space_toolbar
train
def space_toolbar(settings_items, empty_space): """ formats the toolbar """ counter = 0 for part in settings_items: counter += len(part) if len(settings_items) == 1: spacing = '' else: spacing = empty_space[ :int(math.floor((len(empty_space) - counter) / (len(set...
python
{ "resource": "" }
q32492
AzInteractiveShell.cli
train
def cli(self): """ Makes the interface or refreshes it """ if self._cli is None: self._cli = self.create_interface() return self._cli
python
{ "resource": "" }
q32493
AzInteractiveShell.on_input_timeout
train
def on_input_timeout(self, cli): """ brings up the metadata for the command if there is a valid command already typed """ document = cli.current_buffer.document text = document.text text = text.replace('az ', '') if self.default_command: text = self.d...
python
{ "resource": "" }
q32494
AzInteractiveShell._space_examples
train
def _space_examples(self, list_examples, rows, section_value): """ makes the example text """ examples_with_index = [] for i, _ in list(enumerate(list_examples)): if len(list_examples[i]) > 1: examples_with_index.append("[" + str(i + 1) + "] " + list_examples[i][0] +...
python
{ "resource": "" }
q32495
AzInteractiveShell.generate_help_text
train
def generate_help_text(self): """ generates the help text based on commands typed """ param_descrip = example = "" self.description_docs = u'' rows, _ = get_window_dim() rows = int(rows) param_args = self.completer.leftover_args last_word = self.completer.unfini...
python
{ "resource": "" }
q32496
AzInteractiveShell.create_application
train
def create_application(self, full_layout=True): """ makes the application object and the buffers """ layout_manager = LayoutManager(self) if full_layout: layout = layout_manager.create_layout(ExampleLexer, ToolbarLexer) else: layout = layout_manager.create_tutoria...
python
{ "resource": "" }
q32497
AzInteractiveShell.set_prompt
train
def set_prompt(self, prompt_command="", position=0): """ writes the prompt line """ self.description_docs = u'{}'.format(prompt_command) self.cli.current_buffer.reset( initial_document=Document( self.description_docs, cursor_position=position)) ...
python
{ "resource": "" }
q32498
AzInteractiveShell.set_scope
train
def set_scope(self, value): """ narrows the scopes the commands """ if self.default_command: self.default_command += ' ' + value else: self.default_command += value return value
python
{ "resource": "" }
q32499
AzInteractiveShell.handle_example
train
def handle_example(self, text, continue_flag): """ parses for the tutorial """ cmd = text.partition(SELECT_SYMBOL['example'])[0].rstrip() num = text.partition(SELECT_SYMBOL['example'])[2].strip() example = "" try: num = int(num) - 1 except ValueError: ...
python
{ "resource": "" }