Search is not available for this dataset
text
stringlengths
75
104k
def extract_zipdir(zip_file): """ Extract contents of zip file into subfolder in parent directory. Parameters ---------- zip_file : str Path to zip file Returns ------- str : folder where the zip was extracted """ if not os.path.exists(zip_file): rai...
def autologin(function, timeout=TIMEOUT): """Decorator that will try to login and redo an action before failing.""" @wraps(function) async def wrapper(self, *args, **kwargs): """Wrap a function with timeout.""" try: async with async_timeout.timeout(timeout): retur...
async def get_information(): """Example of printing the inbox.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2]) result = await modem.informa...
async def send_message(): """Example of sending a message.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2]) await modem.sms(phone=sys.argv[3...
async def get_information(): """Example of printing the current upstream.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) try: modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2]) ...
async def set_failover_mode(mode): """Example of printing the current upstream.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) try: modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2])...
def parse(file_or_string): """Parse a file-like object or string. Args: file_or_string (file, str): File-like object or string. Returns: ParseResults: instance of pyparsing parse results. """ from mysqlparse.grammar.sql_file import sql_file_syntax if hasattr(file_or_string, 'r...
def nbviewer_link(url): """Return the link to the Jupyter nbviewer for the given notebook url""" if six.PY2: from urlparse import urlparse as urlsplit else: from urllib.parse import urlsplit info = urlsplit(url) domain = info.netloc url_type = 'github' if domain == 'github.com' e...
def thumbnail_div(self): """The string for creating the thumbnail of this example""" return self.THUMBNAIL_TEMPLATE.format( snippet=self.get_description()[1], thumbnail=self.thumb_file, ref_name=self.reference)
def code_div(self): """The string for creating a code example for the gallery""" code_example = self.code_example if code_example is None: return None return self.CODE_TEMPLATE.format( snippet=self.get_description()[1], code=code_example, ref_name=self...
def code_example(self): """The code example out of the notebook metadata""" if self._code_example is not None: return self._code_example return getattr(self.nb.metadata, 'code_example', None)
def supplementary_files(self): """The supplementary files of this notebook""" if self._supplementary_files is not None: return self._supplementary_files return getattr(self.nb.metadata, 'supplementary_files', None)
def other_supplementary_files(self): """The supplementary files of this notebook""" if self._other_supplementary_files is not None: return self._other_supplementary_files return getattr(self.nb.metadata, 'other_supplementary_files', None)
def url(self): """The url on jupyter nbviewer for this notebook or None if unknown""" if self._url is not None: url = self._url else: url = getattr(self.nb.metadata, 'url', None) if url is not None: return nbviewer_link(url)
def get_out_file(self, ending='rst'): """get the output file with the specified `ending`""" return os.path.splitext(self.outfile)[0] + os.path.extsep + ending
def process_notebook(self, disable_warnings=True): """Process the notebook and create all the pictures and files This method runs the notebook using the :mod:`nbconvert` and :mod:`nbformat` modules. It creates the :attr:`outfile` notebook, a python and a rst file""" infile = sel...
def create_rst(self, nb, in_dir, odir): """Create the rst file from the notebook node""" raw_rst, resources = nbconvert.export_by_name('rst', nb) # remove ipython magics rst_content = '' i0 = 0 m = None # HACK: we insert the bokeh style sheets here as well, since ...
def create_py(self, nb, force=False): """Create the python script from the notebook node""" # Although we would love to simply use ``nbconvert.export_python(nb)`` # this causes troubles in other cells processed by the ipython # directive. Instead of getting something like ``Out [5]:``, w...
def data_download(self, files): """Create the rst string to download supplementary data""" if len(files) > 1: return self.DATA_DOWNLOAD % ( ('\n\n' + ' '*8) + ('\n' + ' '*8).join( '* :download:`%s`' % f for f in files)) return self.DATA_DOWNLOAD % ...
def create_thumb(self): """Create the thumbnail for html output""" thumbnail_figure = self.copy_thumbnail_figure() if thumbnail_figure is not None: if isinstance(thumbnail_figure, six.string_types): pic = thumbnail_figure else: pic = self.p...
def get_description(self): """Get summary and description of this notebook""" def split_header(s, get_header=True): s = s.lstrip().rstrip() parts = s.splitlines() if parts[0].startswith('#'): if get_header: header = re.sub('#+\s*', ...
def scale_image(self, in_fname, out_fname, max_width, max_height): """Scales an image with the same aspect ratio centered in an image with a given max_width and max_height if in_fname == out_fname the image can only be scaled down """ # local import to avoid testing depende...
def save_thumbnail(self, image_path): """Save the thumbnail image""" thumb_dir = os.path.join(os.path.dirname(image_path), 'thumb') create_dirs(thumb_dir) thumb_file = os.path.join(thumb_dir, '%s_thumb.png' % self.reference) if os.path.exists(im...
def copy_thumbnail_figure(self): """The integer of the thumbnail figure""" ret = None if self._thumbnail_figure is not None: if not isstring(self._thumbnail_figure): ret = self._thumbnail_figure else: ret = osp.join(osp.dirname(self.outfile...
def process_directories(self): """Create the rst files from the input directories in the :attr:`in_dir` attribute""" for i, (base_dir, target_dir, paths) in enumerate(zip( self.in_dir, self.out_dir, map(os.walk, self.in_dir))): self._in_dir_count = i self....
def recursive_processing(self, base_dir, target_dir, it): """Method to recursivly process the notebooks in the `base_dir` Parameters ---------- base_dir: str Path to the base example directory (see the `examples_dir` parameter for the :class:`Gallery` class) ...
def from_sphinx(cls, app): """Class method to create a :class:`Gallery` instance from the configuration of a sphinx application""" app.config.html_static_path.append(os.path.join( os.path.dirname(__file__), '_static')) config = app.config.example_gallery_config inser...
def get_url(self, nbfile): """Return the url corresponding to the given notebook file Parameters ---------- nbfile: str The path of the notebook relative to the corresponding :attr:``in_dir`` Returns ------- str or None The ur...
def handle(self, *args, **options): """ command execution """ assume_yes = options.get('assume_yes', False) default_language = options.get('default_language', None) # set manual transaction management transaction.commit_unless_managed() transaction.enter_transaction_mana...
def get_db_change_languages(self, field_name, db_table_fields): """ get only db changes fields """ for lang_code, lang_name in get_languages(): if get_real_fieldname(field_name, lang_code) not in db_table_fields: yield lang_code for db_table_field in db_table_fields: ...
def get_sync_sql(self, field_name, db_change_langs, model, db_table_fields): """ returns SQL needed for sync schema for a new translatable field """ qn = connection.ops.quote_name style = no_style() sql_output = [] db_table = model._meta.db_table was_translatable_before =...
def get_all_translatable_fields(model, model_trans_fields=None, column_in_current_table=False): """ returns all translatable fields in a model (including superclasses ones) """ if model_trans_fields is None: model_trans_fields = set() model_trans_fields.update(set(getattr(model._meta, 'translatable_...
def default_value(field): ''' When accessing to the name of the field itself, the value in the current language will be returned. Unless it's set, the value in the default language will be returned. ''' def default_value_func(self): attname = lambda x: get_real_fieldname(field, x) ...
def process(thumbnail_file, size, **kwargs): """ Post processors are functions that receive file objects, performs necessary operations and return the results as file objects. """ from . import conf size_dict = conf.SIZES[size] for processor in size_dict['POST_PROCESSORS']: processo...
def optimize(thumbnail_file, jpg_command=None, png_command=None, gif_command=None): """ A post processing function to optimize file size. Accepts commands to optimize JPG, PNG and GIF images as arguments. Example: THUMBNAILS = { # Other options... 'POST_PROCESSORS': [ ...
def import_attribute(name): """ Return an attribute from a dotted path name (e.g. "path.to.func"). Copied from nvie's rq https://github.com/nvie/rq/blob/master/rq/utils.py """ if hasattr(name, '__call__'): return name module_name, attribute = name.rsplit('.', 1) module = importlib.im...
def parse_processors(processor_definition): """ Returns a dictionary that contains the imported processors and kwargs. For example, passing in: processors = [ {'processor': 'thumbnails.processors.resize', 'width': 10, 'height': 10}, {'processor': 'thumbnails.processors.crop', 'width': 1...
def process(file, size): """ Process an image through its defined processors params :file: filename or file-like object params :size: string for size defined in settings return a ContentFile """ from . import conf # open image in piccaso raw_image = images.from_file(file) # run ...
def pre_save(self, model_instance, add): """ Process the source image through the defined processors. """ file = getattr(model_instance, self.attname) if file and not file._committed: image_file = file if self.resize_source_to: file.seek(0...
def _refresh_cache(self): """Populate self._thumbnails.""" self._thumbnails = {} metadatas = self.metadata_backend.get_thumbnails(self.source_image.name) for metadata in metadatas: self._thumbnails[metadata.size] = Thumbnail(metadata=metadata, storage=self.storage)
def all(self): """ Return all thumbnails in a dict format. """ if self._thumbnails is not None: return self._thumbnails self._refresh_cache() return self._thumbnails
def get(self, size, create=True): """ Returns a Thumbnail instance. First check whether thumbnail is already cached. If it doesn't: 1. Try to fetch the thumbnail 2. Create thumbnail if it's not present 3. Cache the thumbnail for future use """ if self._thu...
def create(self, size): """ Creates and return a thumbnail of a given size. """ thumbnail = images.create(self.source_image.name, size, self.metadata_backend, self.storage) return thumbnail
def delete(self, size): """ Deletes a thumbnail of a given size """ images.delete(self.source_image.name, size, self.metadata_backend, self.storage) del(self._thumbnails[size])
def create(source_name, size, metadata_backend=None, storage_backend=None): """ Creates a thumbnail file and its relevant metadata. Returns a Thumbnail instance. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadat...
def get(source_name, size, metadata_backend=None, storage_backend=None): """ Returns a Thumbnail instance, or None if thumbnail does not yet exist. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadata_backend = backend...
def delete(source_name, size, metadata_backend=None, storage_backend=None): """ Deletes a thumbnail file and its relevant metadata. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadata_backend = backends.metadata.get_b...
def received(self, src, body): """ Simulate an incoming message :type src: str :param src: Message source :type boby: str | unicode :param body: Message body :rtype: IncomingMessage """ # Create the message self._msgid += 1 ...
def subscribe(self, number, callback): """ Register a virtual subscriber which receives messages to the matching number. :type number: str :param number: Subscriber phone number :type callback: callable :param callback: A callback(OutgoingMessage) which handles t...
def states(self): """ Get the set of states. Mostly used for pretty printing :rtype: set :returns: Set of 'accepted', 'delivered', 'expired', 'error' """ ret = set() if self.accepted: ret.add('accepted') if self.delivered: ret.add(...
def add_provider(self, name, Provider, **config): """ Register a provider on the gateway The first provider defined becomes the default one: used in case the routing function has no better idea. :type name: str :param name: Provider name that will be used to uniquely identi...
def send(self, message): """ Send a message object :type message: data.OutgoingMessage :param message: The message to send :rtype: data.OutgoingMessage :returns: The sent message with populated fields :raises AssertionError: wrong provider name encoun...
def receiver_blueprint_for(self, name): """ Get a Flask blueprint for the named provider that handles incoming messages & status reports Note: this requires Flask microframework. :rtype: flask.blueprints.Blueprint :returns: Flask Blueprint, fully functional :rai...
def receiver_blueprints(self): """ Get Flask blueprints for every provider that supports it Note: this requires Flask microframework. :rtype: dict :returns: A dict { provider-name: Blueprint } """ blueprints = {} for name in self._providers: ...
def receiver_blueprints_register(self, app, prefix='/'): """ Register all provider receivers on the provided Flask application under '/{prefix}/provider-name' Note: this requires Flask microframework. :type app: flask.Flask :param app: Flask app to register the blueprints o...
def _receive_message(self, message): """ Incoming message callback Calls Gateway.onReceive event hook Providers are required to: * Cast phone numbers to digits-only * Support both ASCII and Unicode messages * Populate `message.msgid` and `message.met...
def _receive_status(self, status): """ Incoming status callback Calls Gateway.onStatus event hook Providers are required to: * Cast phone numbers to digits-only * Use proper MessageStatus subclasses * Populate `status.msgid` and `status.meta` fields ...
def im(): """ Incoming message handler: forwarded by ForwardServerProvider """ req = jsonex_loads(request.get_data()) message = g.provider._receive_message(req['message']) return {'message': message}
def status(): """ Incoming status handler: forwarded by ForwardServerProvider """ req = jsonex_loads(request.get_data()) status = g.provider._receive_status(req['status']) return {'status': status}
def jsonex_loads(s): """ Unserialize with JsonEx :rtype: dict """ return json.loads(s.decode('utf-8'), cls=JsonExDecoder, classes=classes, exceptions=exceptions)
def jsonex_api(f): """ View wrapper for JsonEx responses. Catches exceptions as well """ @wraps(f) def wrapper(*args, **kwargs): # Call, catch exceptions try: code, res = 200, f(*args, **kwargs) except HTTPException as e: code, res = e.code, {'error': e} ...
def _parse_authentication(url): """ Parse authentication data from the URL and put it in the `headers` dict. With caching behavior :param url: URL :type url: str :return: (URL without authentication info, headers dict) :rtype: str, dict """ u = url h = {} # New headers # Cache? ...
def jsonex_request(url, data, headers=None): """ Make a request with JsonEx :param url: URL :type url: str :param data: Data to POST :type data: dict :return: Response :rtype: dict :raises exc.ConnectionError: Connection error :raises exc.ServerError: Remote server error (unknown) ...
def send(self, message): """ Send a message by forwarding it to the server :param message: Message :type message: smsframework.data.OutgoingMessage :rtype: smsframework.data.OutgoingMessage :raise Exception: any exception reported by the other side :raise urllib2.URLError...
def _forward_object_to_client(self, client, obj): """ Forward an object to client :type client: str :type obj: smsframework.data.IncomingMessage|smsframework.data.MessageStatus :rtype: smsframework.data.IncomingMessage|smsframework.data.MessageStatus :raise Exception: any excepti...
def forward(self, obj): """ Forward an object to clients. :param obj: The object to be forwarded :type obj: smsframework.data.IncomingMessage|smsframework.data.MessageStatus :raises Exception: if any of the clients failed """ assert isinstance(obj, (IncomingMessage, Mess...
def stats(self): """ Returns a dictionnary of dictionnary that contains critical information about the transport and protocol behavior, such as: * amount of received frames * amount of badly delimited frames * amount of correctly delimited but still corrupted frames * etc """ d = dic...
def get_balance(self, address: str, erc20_address: str) -> int: """ Get balance of address for `erc20_address` :param address: owner address :param erc20_address: erc20 token address :return: balance """ return get_erc20_contract(self.w3, erc20_address).functions....
def get_info(self, erc20_address: str) -> Erc20_Info: """ Get erc20 information (`name`, `symbol` and `decimals`) :param erc20_address: :return: Erc20_Info """ # We use the `example erc20` as the `erc20 interface` doesn't have `name`, `symbol` nor `decimals` erc20...
def get_transfer_history(self, from_block: int, to_block: Optional[int] = None, from_address: Optional[str] = None, to_address: Optional[str] = None, token_address: Optional[str] = None) -> List[Dict[str, any]]: """ Get events for erc20 transfers...
def send_tokens(self, to: str, amount: int, erc20_address: str, private_key: str) -> bytes: """ Send tokens to address :param to: :param amount: :param erc20_address: :param private_key: :return: tx_hash """ erc20 = get_erc20_contract(self.w3, erc2...
def trace_filter(self, from_block: int = 1, to_block: Optional[int] = None, from_address: Optional[List[str]] = None, to_address: Optional[List[str]] = None, after: Optional[int] = None, count: Optional[int] = None) -> List[Dict[str, any]]: """ :param from_block...
def get_slow_provider(self, timeout: int): """ Get web3 provider for slow queries. Default `HTTPProvider` timeouts after 10 seconds :param provider: Configured Web3 provider :param timeout: Timeout to configure for internal requests (default is 10) :return: A new web3 provider wi...
def send_unsigned_transaction(self, tx: Dict[str, any], private_key: Optional[str] = None, public_key: Optional[str] = None, retry: bool = False, block_identifier: Optional[str] = None) -> bytes: """ Send a tx using an unlocked public k...
def send_eth_to(self, private_key: str, to: str, gas_price: int, value: int, gas: int=22000, retry: bool = False, block_identifier=None, max_eth_to_send: int = 0) -> bytes: """ Send ether using configured account :param to: to :param gas_price: gas_price :para...
def check_tx_with_confirmations(self, tx_hash: str, confirmations: int) -> bool: """ Check tx hash and make sure it has the confirmations required :param w3: Web3 instance :param tx_hash: Hash of the tx :param confirmations: Minimum number of confirmations required :retur...
def get_signing_address(hash: Union[bytes, str], v: int, r: int, s: int) -> str: """ :return: checksum encoded address starting by 0x, for example `0x568c93675A8dEb121700A6FAdDdfE7DFAb66Ae4A` :rtype: str """ encoded_64_address = ecrecover_to_pub(hash, v, r, s) address_byt...
def generate_address_2(from_: Union[str, bytes], salt: Union[str, bytes], init_code: [str, bytes]) -> str: """ Generates an address for a contract created using CREATE2. :param from_: The address which is creating this new address (need to be 20 bytes) :param salt: A salt (32 bytes) :param init_code...
def get_safe_contract(w3: Web3, address=None): """ Get Gnosis Safe Master contract. It should be used to access Safe methods on Proxy contracts. :param w3: Web3 instance :param address: address of the safe contract/proxy contract :return: Safe Contract """ return w3.eth.contract(address, ...
def get_old_safe_contract(w3: Web3, address=None): """ Get Old Gnosis Safe Master contract. It should be used to access Safe methods on Proxy contracts. :param w3: Web3 instance :param address: address of the safe contract/proxy contract :return: Safe Contract """ return w3.eth.contract(addr...
def get_paying_proxy_contract(w3: Web3, address=None): """ Get Paying Proxy Contract. This should be used just for contract creation/changing master_copy If you want to call Safe methods you should use `get_safe_contract` with the Proxy address, so you can access every method of the Safe :param w3: ...
def get_erc20_contract(w3: Web3, address=None): """ Get ERC20 interface :param w3: Web3 instance :param address: address of the proxy contract :return: ERC 20 contract """ return w3.eth.contract(address, abi=ERC20_INTERFACE['abi'], byteco...
def signature_split(signatures: bytes, pos: int) -> Tuple[int, int, int]: """ :param signatures: signatures in form of {bytes32 r}{bytes32 s}{uint8 v} :param pos: position of the signature :return: Tuple with v, r, s """ signature_pos = 65 * pos v = signatures[64 + signature_pos] r = int...
def signature_to_bytes(vrs: Tuple[int, int, int]) -> bytes: """ Convert signature to bytes :param vrs: tuple of v, r, s :return: signature in form of {bytes32 r}{bytes32 s}{uint8 v} """ byte_order = 'big' v, r, s = vrs return (r.to_bytes(32, byteorder=byte_order) + s.to_byt...
def signatures_to_bytes(signatures: List[Tuple[int, int, int]]) -> bytes: """ Convert signatures to bytes :param signatures: list of tuples(v, r, s) :return: 65 bytes per signature """ return b''.join([signature_to_bytes(vrs) for vrs in signatures])
def find_valid_random_signature(s: int) -> Tuple[int, int]: """ Find v and r valid values for a given s :param s: random value :return: v, r """ for _ in range(10000): r = int(os.urandom(31).hex(), 16) v = (r % 2) + 27 if r < secpk1n: ...
def _build_proxy_contract_creation_constructor(self, master_copy: str, initializer: bytes, funder: str, payment_toke...
def _build_proxy_contract_creation_tx(self, master_copy: str, initializer: bytes, funder: str, payment_token: str, ...
def _build_contract_creation_tx_with_valid_signature(self, tx_dict: Dict[str, None], s: int) -> Transaction: """ Use pyethereum `Transaction` to generate valid tx using a random signature :param tx_dict: Web3 tx dictionary :param s: Signature s value :return: PyEthereum creation ...
def _estimate_gas(self, master_copy: str, initializer: bytes, funder: str, payment_token: str) -> int: """ Gas estimation done using web3 and calling the node Payment cannot be estimated, as no ether is in th...
def _sign_web3_transaction(tx: Dict[str, any], v: int, r: int, s: int) -> (bytes, HexBytes): """ Signed transaction that compatible with `w3.eth.sendRawTransaction` Is not used because `pyEthereum` implementation of Transaction was found to be more robust regarding invalid signatures ...
def check_proxy_code(self, address) -> bool: """ Check if proxy is valid :param address: address of the proxy :return: True if proxy is valid, False otherwise """ deployed_proxy_code = self.w3.eth.getCode(address) proxy_code_fns = (get_paying_proxy_deployed_byteco...
def check_funds_for_tx_gas(self, safe_address: str, safe_tx_gas: int, data_gas: int, gas_price: int, gas_token: str) -> bool: """ Check safe has enough funds to pay for a tx :param safe_address: Address of the safe :param safe_tx_gas: Start gas :par...
def deploy_master_contract(self, deployer_account=None, deployer_private_key=None) -> str: """ Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param deployer_account: Unlocked ethereum account :param deployer_private_key: Private key ...
def deploy_paying_proxy_contract(self, initializer=b'', deployer_account=None, deployer_private_key=None) -> str: """ Deploy proxy contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param initializer: Initializer :param deployer_account: Unlocked ethe...
def deploy_proxy_contract(self, initializer=b'', deployer_account=None, deployer_private_key=None) -> str: """ Deploy proxy contract using the `Proxy Factory Contract`. Takes deployer_account (if unlocked in the node) or the deployer private key :param initializer: Initializer :p...
def deploy_proxy_contract_with_nonce(self, salt_nonce: int, initializer: bytes, gas: int, gas_price: int, deployer_private_key=None) -> Tuple[bytes, Dict[str, any], str]: """ Deploy proxy contract using `create2` withthe `Proxy Factory Contract`. Takes `d...
def deploy_proxy_factory_contract(self, deployer_account=None, deployer_private_key=None) -> str: """ Deploy proxy factory contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param deployer_account: Unlocked ethereum account :param deployer_private_key...
def estimate_tx_gas_with_safe(self, safe_address: str, to: str, value: int, data: bytes, operation: int, block_identifier='pending') -> int: """ Estimate tx gas using safe `requiredTxGas` method :return: int: Estimated gas :raises: CannotEstimateGas: If ...
def estimate_tx_gas_with_web3(self, safe_address: str, to: str, value: int, data: bytes) -> int: """ Estimate tx gas using web3 """ return self.ethereum_client.estimate_gas(safe_address, to, value, data, block_identifier='pending')