_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q224600
SafeProduct.get_requests
train
def get_requests(self): """ Creates product structure and returns list of files for download :return: list of download requests :rtype: list(download.DownloadRequest) """ safe = self.get_safe_struct() self.download_list = [] self.structure_recursion(safe...
python
{ "resource": "" }
q224601
SafeProduct.get_safe_struct
train
def get_safe_struct(self): """ Describes a structure inside tile folder of ESA product .SAFE structure :return: nested dictionaries representing .SAFE structure :rtype: dict """ safe = {} main_folder = self.get_main_folder() safe[main_folder] = {} ...
python
{ "resource": "" }
q224602
SafeTile.get_tile_id
train
def get_tile_id(self): """Creates ESA tile ID :return: ESA tile ID :rtype: str """ tree = get_xml(self.get_url(AwsConstants.METADATA)) tile_id_tag = 'TILE_ID_2A' if self.data_source is DataSource.SENTINEL2_L2A and self.baseline <= '02.06' else\ 'TILE_ID' ...
python
{ "resource": "" }
q224603
AreaSplitter._parse_shape_list
train
def _parse_shape_list(shape_list, crs): """ Checks if the given list of shapes is in correct format and parses geometry objects :param shape_list: The parameter `shape_list` from class initialization :type shape_list: list(shapely.geometry.multipolygon.MultiPolygon or shapely.geometry.polygon.P...
python
{ "resource": "" }
q224604
AreaSplitter.get_bbox_list
train
def get_bbox_list(self, crs=None, buffer=None, reduce_bbox_sizes=None): """Returns a list of bounding boxes that are the result of the split :param crs: Coordinate reference system in which the bounding boxes should be returned. If None the CRS will be the default CRS of the splitte...
python
{ "resource": "" }
q224605
AreaSplitter.get_area_bbox
train
def get_area_bbox(self, crs=None): """Returns a bounding box of the entire area :param crs: Coordinate reference system in which the bounding box should be returned. If None the CRS will be the default CRS of the splitter. :type crs: CRS or None :return: A bounding b...
python
{ "resource": "" }
q224606
AreaSplitter._bbox_to_area_polygon
train
def _bbox_to_area_polygon(self, bbox): """Transforms bounding box into a polygon object in the area CRS. :param bbox: A bounding box :type bbox: BBox :return: A polygon :rtype: shapely.geometry.polygon.Polygon """ projected_bbox = bbox.transform(self.crs) ...
python
{ "resource": "" }
q224607
AreaSplitter._reduce_sizes
train
def _reduce_sizes(self, bbox_list): """Reduces sizes of bounding boxes """ return [BBox(self._intersection_area(bbox).bounds, self.crs).transform(bbox.crs) for bbox in bbox_list]
python
{ "resource": "" }
q224608
BBoxSplitter._parse_split_shape
train
def _parse_split_shape(split_shape): """Parses the parameter `split_shape` :param split_shape: The parameter `split_shape` from class initialization :type split_shape: int or (int, int) :return: A tuple of n :rtype: (int, int) :raises: ValueError """ if i...
python
{ "resource": "" }
q224609
OsmSplitter._recursive_split
train
def _recursive_split(self, bbox, zoom_level, column, row): """Method that recursively creates bounding boxes of OSM grid that intersect the area. :param bbox: Bounding box :type bbox: BBox :param zoom_level: OSM zoom level :type zoom_level: int :param column: Column in t...
python
{ "resource": "" }
q224610
CustomGridSplitter._parse_bbox_grid
train
def _parse_bbox_grid(bbox_grid): """ Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection` """ if isinstance(bbox_grid, BBoxCollection): return bbox_grid if isinstance(bbox_grid, list): return BBoxCollection(bbox_grid) ...
python
{ "resource": "" }
q224611
AwsService._parse_metafiles
train
def _parse_metafiles(self, metafile_input): """ Parses class input and verifies metadata file names. :param metafile_input: class input parameter `metafiles` :type metafile_input: str or list(str) or None :return: verified list of metadata files :rtype: list(str) ...
python
{ "resource": "" }
q224612
AwsService.get_base_url
train
def get_base_url(self, force_http=False): """ Creates base URL path :param force_http: `True` if HTTP base URL should be used and `False` otherwise :type force_http: str :return: base url string :rtype: str """ base_url = SHConfig().aws_metadata_url.rstrip('/') i...
python
{ "resource": "" }
q224613
AwsService.get_safe_type
train
def get_safe_type(self): """Determines the type of ESA product. In 2016 ESA changed structure and naming of data. Therefore the class must distinguish between old product type and compact (new) product type. :return: type of ESA product :rtype: constants.EsaSafeType :ra...
python
{ "resource": "" }
q224614
AwsService._read_baseline_from_info
train
def _read_baseline_from_info(self): """Tries to find and return baseline number from either tileInfo or productInfo file. :return: Baseline ID :rtype: str :raises: ValueError """ if hasattr(self, 'tile_info'): return self.tile_info['datastrip']['id'][-5:] ...
python
{ "resource": "" }
q224615
AwsService.url_to_tile
train
def url_to_tile(url): """ Extracts tile name, date and AWS index from tile url on AWS. :param url: class input parameter 'metafiles' :type url: str :return: Name of tile, date and AWS index which uniquely identifies tile on AWS :rtype: (str, str, int) """ ...
python
{ "resource": "" }
q224616
AwsService.structure_recursion
train
def structure_recursion(self, struct, folder): """ From nested dictionaries representing .SAFE structure it recursively extracts all the files that need to be downloaded and stores them into class attribute `download_list`. :param struct: nested dictionaries representing a part of .SAFE...
python
{ "resource": "" }
q224617
AwsService.add_file_extension
train
def add_file_extension(filename, data_format=None, remove_path=False): """Joins filename and corresponding file extension if it has one. :param filename: Name of the file without extension :type filename: str :param data_format: format of file, if None it will be set automatically ...
python
{ "resource": "" }
q224618
AwsService.is_early_compact_l2a
train
def is_early_compact_l2a(self): """Check if product is early version of compact L2A product :return: True if product is early version of compact L2A product and False otherwise :rtype: bool """ return self.data_source is DataSource.SENTINEL2_L2A and self.safe_type is EsaSafeType...
python
{ "resource": "" }
q224619
AwsProduct.get_requests
train
def get_requests(self): """ Creates product structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str)) """ self.download_list = [DownloadReques...
python
{ "resource": "" }
q224620
AwsProduct.get_data_source
train
def get_data_source(self): """The method determines data source from product ID. :return: Data source of the product :rtype: DataSource :raises: ValueError """ product_type = self.product_id.split('_')[1] if product_type.endswith('L1C') or product_type == 'OPER':...
python
{ "resource": "" }
q224621
AwsProduct.get_date
train
def get_date(self): """ Collects sensing date of the product. :return: Sensing date :rtype: str """ if self.safe_type == EsaSafeType.OLD_TYPE: name = self.product_id.split('_')[-2] date = [name[1:5], name[5:7], name[7:9]] else: name = ...
python
{ "resource": "" }
q224622
AwsProduct.get_product_url
train
def get_product_url(self, force_http=False): """ Creates base url of product location on AWS. :param force_http: True if HTTP base URL should be used and False otherwise :type force_http: str :return: url of product location :rtype: str """ base_url = sel...
python
{ "resource": "" }
q224623
AwsTile.parse_tile_name
train
def parse_tile_name(name): """ Parses and verifies tile name. :param name: class input parameter `tile_name` :type name: str :return: parsed tile name :rtype: str """ tile_name = name.lstrip('T0') if len(tile_name) == 4: tile_name = '0...
python
{ "resource": "" }
q224624
AwsTile.get_requests
train
def get_requests(self): """ Creates tile structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str)) """ self.download_list = [] for dat...
python
{ "resource": "" }
q224625
AwsTile.get_aws_index
train
def get_aws_index(self): """ Returns tile index on AWS. If `tile_index` was not set during class initialization it will be determined according to existing tiles on AWS. :return: Index of tile on AWS :rtype: int """ if self.aws_index is not None: retu...
python
{ "resource": "" }
q224626
AwsTile.tile_is_valid
train
def tile_is_valid(self): """ Checks if tile has tile info and valid timestamp :return: `True` if tile is valid and `False` otherwise :rtype: bool """ return self.tile_info is not None \ and (self.datetime == self.date or self.datetime == self.parse_datetime(self.tile...
python
{ "resource": "" }
q224627
AwsTile.get_tile_url
train
def get_tile_url(self, force_http=False): """ Creates base url of tile location on AWS. :param force_http: True if HTTP base URL should be used and False otherwise :type force_http: str :return: url of tile location :rtype: str """ base_url = self.base_ht...
python
{ "resource": "" }
q224628
split32
train
def split32(data): """ Split data into pieces of 32 bytes. """ all_pieces = [] for position in range(0, len(data), 32): piece = data[position:position + 32] all_pieces.append(piece) return all_pieces
python
{ "resource": "" }
q224629
_canonical_type
train
def _canonical_type(name): # pylint: disable=too-many-return-statements """ Replace aliases to the corresponding type to compute the ids. """ if name == 'int': return 'int256' if name == 'uint': return 'uint256' if name == 'fixed': return 'fixed128x128' if name == 'ufixe...
python
{ "resource": "" }
q224630
method_id
train
def method_id(name, encode_types): """ Return the unique method id. The signature is defined as the canonical expression of the basic prototype, i.e. the function name with the parenthesised list of parameter types. Parameter types are split by a single comma - no spaces are used. The method id is...
python
{ "resource": "" }
q224631
event_id
train
def event_id(name, encode_types): """ Return the event id. Defined as: `keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")")` Where `canonical_type_of` is a function that simply returns the canonical type of a given argument, e.g. for uint indexed foo, it would return ui...
python
{ "resource": "" }
q224632
ContractTranslator.encode_function_call
train
def encode_function_call(self, function_name, args): """ Return the encoded function call. Args: function_name (str): One of the existing functions described in the contract interface. args (List[object]): The function arguments that wll be encoded and ...
python
{ "resource": "" }
q224633
ContractTranslator.decode_function_result
train
def decode_function_result(self, function_name, data): """ Return the function call result decoded. Args: function_name (str): One of the existing functions described in the contract interface. data (bin): The encoded result from calling `function_name`. ...
python
{ "resource": "" }
q224634
ContractTranslator.encode_constructor_arguments
train
def encode_constructor_arguments(self, args): """ Return the encoded constructor call. """ if self.constructor_data is None: raise ValueError( "The contract interface didn't have a constructor") return encode_abi(self.constructor_data['encode_types'], args)
python
{ "resource": "" }
q224635
ContractTranslator.decode_event
train
def decode_event(self, log_topics, log_data): """ Return a dictionary representation the log. Note: This function won't work with anonymous events. Args: log_topics (List[bin]): The log's indexed arguments. log_data (bin): The encoded non-indexed arguments. ...
python
{ "resource": "" }
q224636
ContractTranslator.listen
train
def listen(self, log, noprint=True): """ Return a dictionary representation of the Log instance. Note: This function won't work with anonymous events. Args: log (processblock.Log): The Log instance that needs to be parsed. noprint (bool): Flag to tur...
python
{ "resource": "" }
q224637
unpack_to_nibbles
train
def unpack_to_nibbles(bindata): """unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator """ o = bin_to_nibbles(bindata) flags = o[0] if flags & 2: o.append(NIBBLE_TERMINATOR) if flags & 1 == 1: o...
python
{ "resource": "" }
q224638
starts_with
train
def starts_with(full, part): """ test whether the items in the part is the leading items of the full """ if len(full) < len(part): return False return full[:len(part)] == part
python
{ "resource": "" }
q224639
Trie._get_node_type
train
def _get_node_type(self, node): """ get node type and content :param node: node in form of list, or BLANK_NODE :return: node type """ if node == BLANK_NODE: return NODE_TYPE_BLANK if len(node) == 2: nibbles = unpack_to_nibbles(node[0]) ...
python
{ "resource": "" }
q224640
Trie._get
train
def _get(self, node, key): """ get value inside a node :param node: node in form of list, or BLANK_NODE :param key: nibble list without terminator :return: BLANK_NODE if does not exist, otherwise value or hash """ node_type = self._get_node_type(node) ...
python
{ "resource": "" }
q224641
Trie._normalize_branch_node
train
def _normalize_branch_node(self, node): # sys.stderr.write('nbn\n') """node should have only one item changed """ not_blank_items_count = sum(1 for x in range(17) if node[x]) assert not_blank_items_count >= 1 if not_blank_items_count > 1: self._encode_node(no...
python
{ "resource": "" }
q224642
DEBUG
train
def DEBUG(msg, *args, **kwargs): """temporary logger during development that is always on""" logger = getLogger("DEBUG") if len(logger.handlers) == 0: logger.addHandler(StreamHandler()) logger.propagate = False logger.setLevel(logging.DEBUG) logger.DEV(msg, *args, **kwargs)
python
{ "resource": "" }
q224643
vm_trace
train
def vm_trace(ext, msg, compustate, opcode, pushcache, tracer=log_vm_op): """ This diverges from normal logging, as we use the logging namespace only to decide which features get logged in 'eth.vm.op' i.e. tracing can not be activated by activating a sub like 'eth.vm.op.stack' """ op, in_arg...
python
{ "resource": "" }
q224644
Transaction.sign
train
def sign(self, key, network_id=None): """Sign this transaction with a private key. A potentially already existing signature would be overridden. """ if network_id is None: rawhash = utils.sha3(rlp.encode(unsigned_tx_from_tx(self), UnsignedTransaction)) else: ...
python
{ "resource": "" }
q224645
Transaction.creates
train
def creates(self): "returns the address of a contract created by this tx" if self.to in (b'', '\0' * 20): return mk_contract_address(self.sender, self.nonce)
python
{ "resource": "" }
q224646
check_pow
train
def check_pow(block_number, header_hash, mixhash, nonce, difficulty): """Check if the proof-of-work of the block is valid. :param nonce: if given the proof of work function will be evaluated with this nonce instead of the one already present in the header :returns: `True...
python
{ "resource": "" }
q224647
BlockHeader.to_dict
train
def to_dict(self): """Serialize the header to a readable dictionary.""" d = {} for field in ('prevhash', 'uncles_hash', 'extra_data', 'nonce', 'mixhash'): d[field] = '0x' + encode_hex(getattr(self, field)) for field in ('state_root', 'tx_list_root', 'rec...
python
{ "resource": "" }
q224648
decode_int
train
def decode_int(v): """decodes and integer from serialization""" if len(v) > 0 and (v[0] == b'\x00' or v[0] == 0): raise Exception("No leading zero bytes allowed for integers") return big_endian_to_int(v)
python
{ "resource": "" }
q224649
encode_int
train
def encode_int(v): """encodes an integer into serialization""" if not is_numeric(v) or v < 0 or v >= TT256: raise Exception("Integer invalid or out of range: %r" % v) return int_to_big_endian(v)
python
{ "resource": "" }
q224650
print_func_call
train
def print_func_call(ignore_first_arg=False, max_call_number=100): """ utility function to facilitate debug, it will print input args before function call, and print return value after function call usage: @print_func_call def some_func_to_be_debu(): pass :param ignore_firs...
python
{ "resource": "" }
q224651
get_compiler_path
train
def get_compiler_path(): """ Return the path to the solc compiler. This funtion will search for the solc binary in the $PATH and return the path of the first executable occurence. """ # If the user provides a specific solc binary let's use that given_binary = os.environ.get('SOLC_BINARY') i...
python
{ "resource": "" }
q224652
solc_arguments
train
def solc_arguments(libraries=None, combined='bin,abi', optimize=True, extra_args=None): """ Build the arguments to call the solc binary. """ args = [ '--combined-json', combined, ] def str_of(address): """cast address to string. py2/3 compatability. """ try: ...
python
{ "resource": "" }
q224653
solc_parse_output
train
def solc_parse_output(compiler_output): """ Parses the compiler output. """ # At the moment some solc output like --hashes or -- gas will not output # json at all so if used with those arguments the logic here will break. # Perhaps solidity will slowly switch to a json only output and this comment #...
python
{ "resource": "" }
q224654
compiler_version
train
def compiler_version(): """ Return the version of the installed solc. """ version_info = subprocess.check_output(['solc', '--version']) match = re.search(b'^Version: ([0-9a-z.-]+)/', version_info, re.MULTILINE) if match: return match.group(1)
python
{ "resource": "" }
q224655
solidity_names
train
def solidity_names(code): # pylint: disable=too-many-branches """ Return the library and contract names in order of appearence. """ names = [] in_string = None backslash = False comment = None # "parse" the code by hand to handle the corner cases: # - the contract or library can be inside...
python
{ "resource": "" }
q224656
compile_file
train
def compile_file(filepath, libraries=None, combined='bin,abi', optimize=True, extra_args=None): """ Return the compile contract code. Args: filepath (str): The path to the contract source code. libraries (dict): A dictionary mapping library name to it's address. combine...
python
{ "resource": "" }
q224657
solidity_get_contract_key
train
def solidity_get_contract_key(all_contracts, filepath, contract_name): """ A backwards compatible method of getting the key to the all_contracts dictionary for a particular contract""" if contract_name in all_contracts: return contract_name else: if filepath is None: filename...
python
{ "resource": "" }
q224658
Solc.compile
train
def compile(cls, code, path=None, libraries=None, contract_name='', extra_args=None): """ Return the binary of last contract in code. """ result = cls._code_or_path( code, path, contract_name, libraries, 'bin', extra...
python
{ "resource": "" }
q224659
Solc.combined
train
def combined(cls, code, path=None, extra_args=None): """ Compile combined-json with abi,bin,devdoc,userdoc. @param code: literal solidity code as a string. @param path: absolute path to solidity-file. Note: code & path are mutually exclusive! @param extra_args: Eith...
python
{ "resource": "" }
q224660
Solc.compile_rich
train
def compile_rich(cls, code, path=None, extra_args=None): """full format as returned by jsonrpc""" return { contract_name: { 'code': '0x' + contract.get('bin_hex'), 'info': { 'abiDefinition': contract.get('abi'), 'compil...
python
{ "resource": "" }
q224661
validate_uncles
train
def validate_uncles(state, block): """Validate the uncles of this block.""" # Make sure hash matches up if utils.sha3(rlp.encode(block.uncles)) != block.header.uncles_hash: raise VerificationFailed("Uncle hash mismatch") # Enforce maximum number of uncles if len(block.uncles) > state.config[...
python
{ "resource": "" }
q224662
finalize
train
def finalize(state, block): """Apply rewards and commit.""" if state.is_METROPOLIS(): br = state.config['BYZANTIUM_BLOCK_REWARD'] nr = state.config['BYZANTIUM_NEPHEW_REWARD'] else: br = state.config['BLOCK_REWARD'] nr = state.config['NEPHEW_REWARD'] delta = int(...
python
{ "resource": "" }
q224663
Deprecated.ensure_new_style_deprecation
train
def ensure_new_style_deprecation(cli_ctx, kwargs, object_type): """ Helper method to make the previous string-based deprecate_info kwarg work with the new style. """ deprecate_info = kwargs.get('deprecate_info', None) if isinstance(deprecate_info, Deprecated): deprecate_i...
python
{ "resource": "" }
q224664
Deprecated._version_less_than_or_equal_to
train
def _version_less_than_or_equal_to(self, v1, v2): """ Returns true if v1 <= v2. """ # pylint: disable=no-name-in-module, import-error from distutils.version import LooseVersion return LooseVersion(v1) <= LooseVersion(v2)
python
{ "resource": "" }
q224665
prompt_choice_list
train
def prompt_choice_list(msg, a_list, default=1, help_string=None): """Prompt user to select from a list of possible choices. :param msg:A message displayed to the user before the choice list :type msg: str :param a_list:The list of choices (list of strings or list of dicts with 'name' & 'desc') "typ...
python
{ "resource": "" }
q224666
CLICommandParser._add_argument
train
def _add_argument(obj, arg): """ Only pass valid argparse kwargs to argparse.ArgumentParser.add_argument """ argparse_options = {name: value for name, value in arg.options.items() if name in ARGPARSE_SUPPORTED_KWARGS} if arg.options_list: scrubbed_options_list = [] for it...
python
{ "resource": "" }
q224667
CLICommandParser.load_command_table
train
def load_command_table(self, command_loader): """ Process the command table and load it into the parser :param cmd_tbl: A dictionary containing the commands :type cmd_tbl: dict """ cmd_tbl = command_loader.command_table grp_tbl = command_loader.command_group_table ...
python
{ "resource": "" }
q224668
CLICommandParser._get_subparser
train
def _get_subparser(self, path, group_table=None): """For each part of the path, walk down the tree of subparsers, creating new ones if one doesn't already exist. """ group_table = group_table or {} for length in range(0, len(path)): parent_path = path[:length] ...
python
{ "resource": "" }
q224669
CLICommandParser.parse_args
train
def parse_args(self, args=None, namespace=None): """ Overrides argparse.ArgumentParser.parse_args Enables '@'-prefixed files to be expanded before arguments are processed by ArgumentParser.parse_args as usual """ self._expand_prefixed_files(args) return super(CLICommandP...
python
{ "resource": "" }
q224670
extract_full_summary_from_signature
train
def extract_full_summary_from_signature(operation): """ Extract the summary from the docstring of the command. """ lines = inspect.getdoc(operation) regex = r'\s*(:param)\s+(.+?)\s*:(.*)' summary = '' if lines: match = re.search(regex, lines) summary = lines[:match.regs[0][0]] if mat...
python
{ "resource": "" }
q224671
CLI.get_runtime_version
train
def get_runtime_version(self): # pylint: disable=no-self-use """ Get the runtime information. :return: Runtime information :rtype: str """ import platform version_info = '\n\n' version_info += 'Python ({}) {}'.format(platform.system(), sys.version) vers...
python
{ "resource": "" }
q224672
CLI.show_version
train
def show_version(self): """ Print version information to the out file. """ version_info = self.get_cli_version() version_info += self.get_runtime_version() print(version_info, file=self.out_file)
python
{ "resource": "" }
q224673
CLI.unregister_event
train
def unregister_event(self, event_name, handler): """ Unregister a callable that will be called when event is raised. :param event_name: The name of the event (see knack.events for in-built events) :type event_name: str :param handler: The callback that was used to register the event ...
python
{ "resource": "" }
q224674
CLI.raise_event
train
def raise_event(self, event_name, **kwargs): """ Raise an event. Calls each handler in turn with kwargs :param event_name: The name of the event to raise :type event_name: str :param kwargs: Kwargs to be passed to all event handlers """ handlers = list(self._event_handle...
python
{ "resource": "" }
q224675
CLI.exception_handler
train
def exception_handler(self, ex): # pylint: disable=no-self-use """ The default exception handler """ if isinstance(ex, CLIError): logger.error(ex) else: logger.exception(ex) return 1
python
{ "resource": "" }
q224676
CLI.invoke
train
def invoke(self, args, initial_invocation_data=None, out_file=None): """ Invoke a command. :param args: The arguments that represent the command :type args: list, tuple :param initial_invocation_data: Prime the in memory collection of key-value data for this invocation. :type in...
python
{ "resource": "" }
q224677
get_logger
train
def get_logger(module_name=None): """ Get the logger for a module. If no module name is given, the current CLI logger is returned. Example: get_logger(__name__) :param module_name: The module to get the logger for :type module_name: str :return: The logger :rtype: logger """ if...
python
{ "resource": "" }
q224678
CLILogging.configure
train
def configure(self, args): """ Configure the loggers with the appropriate log level etc. :param args: The arguments from the command line :type args: list """ verbose_level = self._determine_verbose_level(args) log_level_config = self.console_log_configs[verbose_level] ...
python
{ "resource": "" }
q224679
CLILogging._determine_verbose_level
train
def _determine_verbose_level(self, args): """ Get verbose level by reading the arguments. """ verbose_level = 0 for arg in args: if arg == CLILogging.VERBOSE_FLAG: verbose_level += 1 elif arg == CLILogging.DEBUG_FLAG: verbose_level += 2 ...
python
{ "resource": "" }
q224680
enum_choice_list
train
def enum_choice_list(data): """ Creates the argparse choices and type kwargs for a supplied enum type or list of strings """ # transform enum types, otherwise assume list of string choices if not data: return {} try: choices = [x.value for x in data] except AttributeError: c...
python
{ "resource": "" }
q224681
ArgumentRegistry.register_cli_argument
train
def register_cli_argument(self, scope, dest, argtype, **kwargs): """ Add an argument to the argument registry :param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand') :type scope: str :param dest: The parameter/destination that this argument is for ...
python
{ "resource": "" }
q224682
ArgumentRegistry.get_cli_argument
train
def get_cli_argument(self, command, name): """ Get the argument for the command after applying the scope hierarchy :param command: The command that we want the argument for :type command: str :param name: The name of the argument :type name: str :return: The CLI command ...
python
{ "resource": "" }
q224683
ArgumentsContext.argument
train
def argument(self, argument_dest, arg_type=None, **kwargs): """ Register an argument for the given command scope using a knack.arguments.CLIArgumentType :param argument_dest: The destination argument to add this argument type to :type argument_dest: str :param arg_type: Predefined CLIAr...
python
{ "resource": "" }
q224684
ArgumentsContext.positional
train
def positional(self, argument_dest, arg_type=None, **kwargs): """ Register a positional argument for the given command scope using a knack.arguments.CLIArgumentType :param argument_dest: The destination argument to add this argument type to :type argument_dest: str :param arg_type: Pred...
python
{ "resource": "" }
q224685
ArgumentsContext.extra
train
def extra(self, argument_dest, **kwargs): """Register extra parameters for the given command. Typically used to augment auto-command built commands to add more parameters than the specific SDK method introspected. :param argument_dest: The destination argument to add this argument type to ...
python
{ "resource": "" }
q224686
CLICommandsLoader.load_command_table
train
def load_command_table(self, args): # pylint: disable=unused-argument """ Load commands into the command table :param args: List of the arguments from the command line :type args: list :return: The ordered command table :rtype: collections.OrderedDict """ self.c...
python
{ "resource": "" }
q224687
CLICommandsLoader.load_arguments
train
def load_arguments(self, command): """ Load the arguments for the specified command :param command: The command to load arguments for :type command: str """ from knack.arguments import ArgumentsContext self.cli_ctx.raise_event(EVENT_CMDLOADER_LOAD_ARGUMENTS, cmd_tbl=sel...
python
{ "resource": "" }
q224688
CLICommandsLoader.create_command
train
def create_command(self, name, operation, **kwargs): """ Constructs the command object that can then be added to the command table """ if not isinstance(operation, six.string_types): raise ValueError("Operation must be a string. Got '{}'".format(operation)) name = ' '.join(name.spli...
python
{ "resource": "" }
q224689
CLICommandsLoader._get_op_handler
train
def _get_op_handler(operation): """ Import and load the operation handler """ try: mod_to_import, attr_path = operation.split('#') op = import_module(mod_to_import) for part in attr_path.split('.'): op = getattr(op, part) if isinstance(op, ...
python
{ "resource": "" }
q224690
CommandGroup.command
train
def command(self, name, handler_name, **kwargs): """ Register a command into the command table :param name: The name of the command :type name: str :param handler_name: The name of the handler that will be applied to the operations template :type handler_name: str :param...
python
{ "resource": "" }
q224691
CommandInvoker._rudimentary_get_command
train
def _rudimentary_get_command(self, args): """ Rudimentary parsing to get the command """ nouns = [] command_names = self.commands_loader.command_table.keys() for arg in args: if arg and arg[0] != '-': nouns.append(arg) else: break ...
python
{ "resource": "" }
q224692
CommandInvoker.execute
train
def execute(self, args): """ Executes the command invocation :param args: The command arguments for this invocation :type args: list :return: The command result :rtype: knack.util.CommandResultItem """ import colorama self.cli_ctx.raise_event(EVENT_INVOK...
python
{ "resource": "" }
q224693
CLICompletion.get_completion_args
train
def get_completion_args(self, is_completion=False, comp_line=None): # pylint: disable=no-self-use """ Get the args that will be used to tab completion if completion is active. """ is_completion = is_completion or os.environ.get(ARGCOMPLETE_ENV_NAME) comp_line = comp_line or os.environ.get('COMP...
python
{ "resource": "" }
q224694
OutputProducer.out
train
def out(self, obj, formatter=None, out_file=None): # pylint: disable=no-self-use """ Produces the output using the command result. The method does not return a result as the output is written straight to the output file. :param obj: The command result :type obj: knack.util.CommandR...
python
{ "resource": "" }
q224695
EndpointsMixin.update_status_with_media
train
def update_status_with_media(self, **params): # pragma: no cover """Updates the authenticating user's current status and attaches media for upload. In other words, it creates a Tweet with a picture attached. Docs: https://developer.twitter.com/en/docs/tweets/post-and-engage/api-referen...
python
{ "resource": "" }
q224696
EndpointsMixin.create_metadata
train
def create_metadata(self, **params): """ Adds metadata to a media element, such as image descriptions for visually impaired. Docs: https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create """ params = json.dumps(params) return se...
python
{ "resource": "" }
q224697
Twython._get_error_message
train
def _get_error_message(self, response): """Parse and return the first error message""" error_message = 'An error occurred processing your request.' try: content = response.json() # {"errors":[{"code":34,"message":"Sorry, # that page does not exist"}]} ...
python
{ "resource": "" }
q224698
Twython.request
train
def request(self, endpoint, method='GET', params=None, version='1.1', json_encoded=False): """Return dict of response received from Twitter's API :param endpoint: (required) Full url or Twitter API endpoint (e.g. search/tweets) :type endpoint: string :param meth...
python
{ "resource": "" }
q224699
Twython.get_lastfunction_header
train
def get_lastfunction_header(self, header, default_return_value=None): """Returns a specific header from the last API call This will return None if the header is not present :param header: (required) The name of the header you want to get the value of Most useful ...
python
{ "resource": "" }