INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
The method checks if the area bounding box is completely inside the OSM grid. That means that its latitudes must be contained in the interval (-85.0511, 85.0511) :raises: ValueError
def _check_area_bbox(self): """The method checks if the area bounding box is completely inside the OSM grid. That means that its latitudes must be contained in the interval (-85.0511, 85.0511) :raises: ValueError """ for coord in self.area_bbox: if abs(coord) > self....
Creates a bounding box of the entire world in EPSG: 3857 :return: Bounding box of entire world :rtype: BBox
def get_world_bbox(self): """Creates a bounding box of the entire world in EPSG: 3857 :return: Bounding box of entire world :rtype: BBox """ return BBox((-self.POP_WEB_MAX, -self.POP_WEB_MAX, self.POP_WEB_MAX, self.POP_WEB_MAX), crs=CRS.POP_WEB)
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 the OSM grid :type column: int :param row: Row in the O...
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...
This method makes the split
def _make_split(self): """ This method makes the split """ self.tile_dict = {} wfs = WebFeatureService(self.area_bbox, self.time_interval, data_source=self.data_source, instance_id=self.instance_id) date_list = wfs.get_dates() geometry_lis...
Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection`
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) ...
Parses class input and verifies band names. :param band_input: input parameter `bands` :type band_input: str or list(str) or None :return: verified list of bands :rtype: list(str)
def _parse_bands(self, band_input): """ Parses class input and verifies band names. :param band_input: input parameter `bands` :type band_input: str or list(str) or None :return: verified list of bands :rtype: list(str) """ all_bands = AwsConstants.S2_L1C...
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)
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) ...
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
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...
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 :raises: ValueError
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...
Determines the baseline number (i.e. version) of ESA .SAFE product :return: baseline number :rtype: str :raises: ValueError
def get_baseline(self): """ Determines the baseline number (i.e. version) of ESA .SAFE product :return: baseline number :rtype: str :raises: ValueError """ if self.safe_type is EsaSafeType.COMPACT_TYPE: baseline = self.product_id.split('_')[3].lstrip('N') ...
Tries to find and return baseline number from either tileInfo or productInfo file. :return: Baseline ID :rtype: str :raises: ValueError
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:] ...
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)
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) """ ...
Method for sorting the list of download requests. Band images have priority before metadata files. If bands images or metadata files are specified with a list they will be sorted in the same order as in the list. Otherwise they will be sorted alphabetically (band B8A will be between B08 and B09).
def sort_download_list(self): """ Method for sorting the list of download requests. Band images have priority before metadata files. If bands images or metadata files are specified with a list they will be sorted in the same order as in the list. Otherwise they will be sorted alphabetica...
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 structure :type struct: dict :param folder: name o...
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...
Converts url back to name of product/tile and name of the file :param url: URL location of the data :type url: str :return: Names of product or tile and name of a file :rtype: str, str
def _url_to_props(self, url): """ Converts url back to name of product/tile and name of the file :param url: URL location of the data :type url: str :return: Names of product or tile and name of a file :rtype: str, str """ props = (url[len(self.base_url):] if url...
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 :type data_format: constants.MimeType or None :param remove_path: True ...
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 ...
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
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...
Parses class input and verifies band names. :param tile_input: class input parameter `tile_list` :type tile_input: str or list(str) :return: parsed list of tiles :rtype: list(str) or None
def parse_tile_list(tile_input): """ Parses class input and verifies band names. :param tile_input: class input parameter `tile_list` :type tile_input: str or list(str) :return: parsed list of tiles :rtype: list(str) or None """ if tile_input is None: ...
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))
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...
The method determines data source from product ID. :return: Data source of the product :rtype: DataSource :raises: ValueError
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':...
Collects sensing date of the product. :return: Sensing date :rtype: str
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 = ...
Creates url of file location on AWS. :param filename: name of file :type filename: str :param data_format: format of file, if None it will be set automatically :type data_format: constants.MimeType or None :return: url of file location :rtype: str
def get_url(self, filename, data_format=None): """ Creates url of file location on AWS. :param filename: name of file :type filename: str :param data_format: format of file, if None it will be set automatically :type data_format: constants.MimeType or None :retur...
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
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...
Creates file path for the file. :param filename: name of the file :type filename: str :return: filename with path on disk :rtype: str
def get_filepath(self, filename): """ Creates file path for the file. :param filename: name of the file :type filename: str :return: filename with path on disk :rtype: str """ return os.path.join(self.parent_folder, self.product_id, self.add_file_extensio...
Parses and verifies tile name. :param name: class input parameter `tile_name` :type name: str :return: parsed tile name :rtype: str
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...
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))
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...
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
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...
Checks if tile has tile info and valid timestamp :return: `True` if tile is valid and `False` otherwise :rtype: bool
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...
Creates url of file location on AWS. :param filename: name of file :type filename: str :return: url of file location :rtype: str
def get_url(self, filename): """ Creates url of file location on AWS. :param filename: name of file :type filename: str :return: url of file location :rtype: str """ tile_url = self.tile_url force_http = filename in [AwsConstants.TILE_INFO, AwsCon...
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
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...
:param qi_type: type of quality indicator :type qi_type: str :param band: band name :type band: str :return: location of gml file on AWS :rtype: str
def get_gml_url(self, qi_type, band='B00'): """ :param qi_type: type of quality indicator :type qi_type: str :param band: band name :type band: str :return: location of gml file on AWS :rtype: str """ band = band.split('/')[-1] return self....
Returns url location of full resolution L1C preview :return:
def get_preview_url(self, data_type='L1C'): """Returns url location of full resolution L1C preview :return: """ if self.data_source is DataSource.SENTINEL2_L1C or self.safe_type is EsaSafeType.OLD_TYPE: return self.get_url(AwsConstants.PREVIEW_JP2) return self.get_qi_...
Creates file path for the file. :param filename: name of the file :type filename: str :return: filename with path on disk :rtype: str
def get_filepath(self, filename): """ Creates file path for the file. :param filename: name of the file :type filename: str :return: filename with path on disk :rtype: str """ return os.path.join(self.parent_folder, '{},{},{}'.format(self.tile_name, self....
:param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type: str :return: tile name, sensing date and AWS index :rtype: (str, str, int)
def tile_id_to_tile(tile_id): """ :param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type: str :return: tile name, sensing date and AWS index :rtype: (str, str, int) ...
Split data into pieces of 32 bytes.
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
Replace aliases to the corresponding type to compute the ids.
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...
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 defined as the first four bytes (left, hig...
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...
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 uint256). Note the lack of spaces.
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...
Decode an unsigned/signed integer.
def decint(n, signed=False): # pylint: disable=invalid-name,too-many-branches """ Decode an unsigned/signed integer. """ if isinstance(n, str): n = utils.to_string(n) if n is True: return 1 if n is False: return 0 if n is None: return 0 if is_numeric(n): ...
Encode `arg` as `typ`. `arg` will be encoded in a best effort manner, were necessary the function will try to correctly define the underlying binary representation (ie. decoding a hex-encoded address/hash). Args: typ (Tuple[(str, int, list)]): A 3-tuple defining the `arg` type. Th...
def encode_single(typ, arg): # pylint: disable=too-many-return-statements,too-many-branches,too-many-statements,too-many-locals """ Encode `arg` as `typ`. `arg` will be encoded in a best effort manner, were necessary the function will try to correctly define the underlying binary representation (ie. d...
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 used in the contract execution in the vm. Return: ...
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 ...
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`. Return: List[object]: The values returned by the call ...
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`. ...
Return the encoded constructor call.
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)
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.
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. ...
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 turn off priting of the decoded log instance.
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...
unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator
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...
test whether the items in the part is the leading items of the full
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
clear all tree data
def clear(self): """ clear all tree data """ self._delete_child_storage(self.root_node) self._delete_node_storage(self.root_node) self.root_node = BLANK_NODE
get node type and content :param node: node in form of list, or BLANK_NODE :return: node type
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]) ...
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
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) ...
delete storage :param node: node in form of list, or BLANK_NODE
def _delete_node_storage(self, node, is_root=False): """delete storage :param node: node in form of list, or BLANK_NODE """ if node == BLANK_NODE: return # assert isinstance(node, list) encoded = rlp_encode(node) if len(encoded) < 32 and not is_root: ...
update item inside a node :param node: node in form of list, or BLANK_NODE :param key: nibble list without terminator .. note:: key may be [] :return: new node if this node is changed to a new node, it's parent will take the responsibility to *store* the new node st...
def _delete(self, node, key): """ update item inside a node :param node: node in form of list, or BLANK_NODE :param key: nibble list without terminator .. note:: key may be [] :return: new node if this node is changed to a new node, it's parent will take the ...
node should have only one item changed
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...
:param key: a string with length of [0, 32]
def delete(self, key): """ :param key: a string with length of [0, 32] """ if not is_string(key): raise Exception("Key must be string") if len(key) > 32: raise Exception("Max key length is 32") old_root = copy.deepcopy(self.root_node) sel...
Get counts of (key, value) stored in this and the descendant nodes :param node: node in form of list, or BLANK_NODE
def _get_size(self, node): """Get counts of (key, value) stored in this and the descendant nodes :param node: node in form of list, or BLANK_NODE """ if node == BLANK_NODE: return 0 node_type = self._get_node_type(node) if is_key_value_type(node_type): ...
convert (key, value) stored in this and the descendant nodes to dict items. :param node: node in form of list, or BLANK_NODE .. note:: Here key is in full form, rather than key of the individual node
def _to_dict(self, node): """convert (key, value) stored in this and the descendant nodes to dict items. :param node: node in form of list, or BLANK_NODE .. note:: Here key is in full form, rather than key of the individual node """ if node == BLANK_NODE: ...
:param key: a string :value: a string
def update(self, key, value): """ :param key: a string :value: a string """ if not is_string(key): raise Exception("Key must be string") # if len(key) > 32: # raise Exception("Max key length is 32") if not is_string(value): ra...
clear all tree data
def clear(self): """ clear all tree data """ self._delete_child_storage(self.root_node) self._delete_node_storage(self.root_node) self.root_node = BLANK_NODE self._root_hash = BLANK_ROOT
update item inside a node :param node: node in form of list, or BLANK_NODE :param key: nibble list without terminator .. note:: key may be [] :param value: value string :return: new node if this node is changed to a new node, it's parent will take the respon...
def _update(self, node, key, value): """ update item inside a node :param node: node in form of list, or BLANK_NODE :param key: nibble list without terminator .. note:: key may be [] :param value: value string :return: new node if this node is changed to a n...
delete storage :param node: node in form of list, or BLANK_NODE
def _delete_node_storage(self, node): """delete storage :param node: node in form of list, or BLANK_NODE """ if node == BLANK_NODE: return # assert isinstance(node, list) encoded = self._encode_node(node, put_in_db=False) if len(encoded) < 32: ...
:param key: a string with length of [0, 32]
def delete(self, key): """ :param key: a string with length of [0, 32] """ if not is_string(key): raise Exception("Key must be string") if len(key) > 32: raise Exception("Max key length is 32") self.root_node = self._delete_and_delete_storage( ...
:param key: a string :value: a string
def update(self, key, value): """ :param key: a string :value: a string """ if not is_string(key): raise Exception("Key must be string") # if len(key) > 32: # raise Exception("Max key length is 32") if not is_string(value): ra...
get a configuration (snapshot) that can be used to call configure snapshot = get_configuration() configure(**snapshot)
def get_configuration(): """ get a configuration (snapshot) that can be used to call configure snapshot = get_configuration() configure(**snapshot) """ root = getLogger() name_levels = [('', logging.getLevelName(root.level))] name_levels.extend( (name, logging.getLevelName(logger...
Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger.
def getLogger(name=None): """ Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. """ if name: logger = SLogger.manager.getLogger(name) return logger else: return rootLogger
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'
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...
temporary logger during development that is always on
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)
Sign this transaction with a private key. A potentially already existing signature would be overridden.
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: ...
returns the address of a contract created by this tx
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)
convert fixture into *behave* examples :param fixture: a dictionary in the following form:: { "test1name": { "test1property1": ..., "test1property2": ..., ... }, "test2name": { "test2...
def fixture_to_tables(fixture): """ convert fixture into *behave* examples :param fixture: a dictionary in the following form:: { "test1name": { "test1property1": ..., "test1property2": ..., ... }, "test2nam...
:param py: python format or not
def format_item(item, py=True): """ :param py: python format or not """ # for non python format, just output itself. # so the result is `something` instead of `"something"` if not py: return unicode(item) if isinstance(item, (str, unicode)): # long int is prefixed by a # ...
format table to *behave* example :param table: `(caption, rows)`, each item in `rows` is `(col1, col2,...)` :return
def format_to_example(table, tabspace=2, indent=2): """ format table to *behave* example :param table: `(caption, rows)`, each item in `rows` is `(col1, col2,...)` :return """ from io import StringIO output = StringIO() caption, rows = table # output caption line output.write(u'{0}...
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` or `False`
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...
Check if ``jsondata`` has the structure of a keystore file version 3. Note that this test is not complete, e.g. it doesn't check key derivation or cipher parameters. :param jsondata: dictionary containing the data from the json file :returns: `True` if the data appears to be valid, otherwise `False`
def check_keystore_json(jsondata): """Check if ``jsondata`` has the structure of a keystore file version 3. Note that this test is not complete, e.g. it doesn't check key derivation or cipher parameters. :param jsondata: dictionary containing the data from the json file :returns: `True` if the data ap...
Serialize the header to a readable dictionary.
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...
decodes and integer from serialization
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)
encodes an integer into serialization
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)
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_first_arg: whether print the first arg or not. useful when ignore the `sel...
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...
RLP encode (a nested sequence of) bytes
def _encode_optimized(item): """RLP encode (a nested sequence of) bytes""" if isinstance(item, bytes): if len(item) == 1 and ord(item) < 128: return item prefix = length_prefix(len(item), 128) else: item = b''.join([_encode_optimized(x) for x in item]) prefix = le...
Construct the prefix to lists or strings denoting their length. :param length: the length of the item in bytes :param offset: ``0x80`` when encoding raw bytes, ``0xc0`` when encoding a list
def length_prefix(length, offset): """Construct the prefix to lists or strings denoting their length. :param length: the length of the item in bytes :param offset: ``0x80`` when encoding raw bytes, ``0xc0`` when encoding a list """ if length < 56: return chr(offset + leng...
Read a length prefix from an RLP string. :param rlp: the rlp string to read from :param start: the position at which to start reading :returns: a tuple ``(type, length, end)``, where ``type`` is either ``str`` or ``list`` depending on the type of the following payload, ``length`...
def consume_length_prefix(rlp, start): """Read a length prefix from an RLP string. :param rlp: the rlp string to read from :param start: the position at which to start reading :returns: a tuple ``(type, length, end)``, where ``type`` is either ``str`` or ``list`` depending on the type of ...
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.
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...
Build the arguments to call the solc binary.
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: ...
Parses the compiler output.
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 #...
Return the version of the installed solc.
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)
Return the library and contract names in order of appearence.
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...
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. combined (str): The argument for solc's --combined-json. optimize (bool): Enable/disables compiler optimization. Re...
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...
A backwards compatible method of getting the contract data out of a solc --combined-json output
def solidity_get_contract_data(all_contracts, filepath, contract_name): """ A backwards compatible method of getting the contract data out of a solc --combined-json output""" try: contract_data = all_contracts[contract_name] except BaseException: if filepath is None: filename...
A backwards compatible method of getting the key to the all_contracts dictionary for a particular contract
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...
Return the binary of last contract in code.
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...
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: Either a space separated string or a list of extra ...
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...
full format as returned by jsonrpc
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...
Validate the uncles of this block.
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[...
Apply rewards and commit.
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(...
Helper method to make the previous string-based deprecate_info kwarg work with the new style.
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...
Returns true if v1 <= v2.
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)
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') "type a_list: list :param default:The default option that should be chose...
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...
Only pass valid argparse kwargs to argparse.ArgumentParser.add_argument
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...
Load arguments prefixed with '@' from file as string :param args: Arguments passed from command line :type args: list
def _expand_prefixed_files(args): """ Load arguments prefixed with '@' from file as string :param args: Arguments passed from command line :type args: list """ for arg, _ in enumerate(args): if args[arg].startswith('@'): try: logge...
Process the command table and load it into the parser :param cmd_tbl: A dictionary containing the commands :type cmd_tbl: dict
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 ...
For each part of the path, walk down the tree of subparsers, creating new ones if one doesn't already exist.
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] ...