How to use the boltons.strutils function in boltons

To help you get started, we’ve selected a few boltons examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mahmoud / boltons / tests / test_strutils.py View on Github external
def test_shortcut_function(self):
        """Test replacing multiple values."""
        self.assertEqual(
            strutils.multi_replace(
                'The cat is purple',
                {r'cat': 'kedi', r'purple': 'mor', }
            ),
            'The kedi is mor'
        )
github mahmoud / boltons / tests / test_strutils.py View on Github external
def test_roundzip():
    aaa = b'a' * 10000
    assert strutils.gunzip_bytes(strutils.gzip_bytes(aaa)) == aaa

    assert strutils.gunzip_bytes(strutils.gzip_bytes(b'')) == b''
github securestate / king-phisher / king_phisher / client / widget / extras.py View on Github external
def do_render(self, *args, **kwargs):
		original = self.get_property('text')
		if original.isdigit():
			self.set_property('text', boltons.strutils.bytes2human(int(original), 1))
		Gtk.CellRendererText.do_render(self, *args, **kwargs)
github GeoscienceAustralia / digitalearthau / datacubenci / sync.py View on Github external
def query_name(query: Mapping[str, Any]) -> str:
    """
    Get a string name for the given query args.

    >>> query_name({'product': 'ls8_level1_scene'})
    'product_ls8_level1_scene'
    >>> query_name({'metadata_type': 'telemetry'})
    'metadata_type_telemetry'
    >>> query_name({'a': '1', 'b': 2, 'c': '"3"'})
    'a_1-b_2-c_3'
    """
    return "-".join(
        '{}_{}'.format(k, strutils.slugify(str(v)))
        for k, v in sorted(query.items())
    )
github GeoscienceAustralia / digitalearthau / digitalearthau / sync / differences.py View on Github external
def to_dict(self):
        return dict(
            name=strutils.camel2under(self.__class__.__name__),
            dataset_id=str(self.dataset.id) if self.dataset else None,
            uri=self.uri
        )
github securestate / king-phisher / king_phisher / templates.py View on Github external
def __init__(self, loader=None, global_vars=None):
		"""
		:param loader: The loader to supply to the environment.
		:type loader: :py:class:`jinja2.BaseLoader`
		:param dict global_vars: Additional global variables for the environment.
		"""
		self.logger = logging.getLogger('KingPhisher.TemplateEnvironment')
		autoescape = jinja2.select_autoescape(['html', 'htm', 'xml'], default_for_string=False)
		extensions = ['jinja2.ext.autoescape', 'jinja2.ext.do']
		super(TemplateEnvironmentBase, self).__init__(autoescape=autoescape, extensions=extensions, loader=loader, trim_blocks=True)

		# misc. string filters
		self.filters['cardinalize'] = boltons.strutils.cardinalize
		self.filters['ordinalize'] = boltons.strutils.ordinalize
		self.filters['pluralize'] = boltons.strutils.pluralize
		self.filters['singularize'] = boltons.strutils.singularize
		self.filters['possessive'] = lambda word: word + ('\'' if word.endswith('s') else '\'s')
		self.filters['encode'] = self._filter_encode
		self.filters['decode'] = self._filter_decode
		self.filters['hash'] = self._filter_hash
		# counter part to https://jinja.readthedocs.io/en/stable/templates.html#tojson
		self.filters['fromjson'] = self._filter_json

		# time filters
		self.filters['strftime'] = self._filter_strftime
		self.filters['timedelta'] = self._filter_timedelta
		self.filters['tomorrow'] = lambda dt: dt + datetime.timedelta(days=1)
		self.filters['next_week'] = lambda dt: dt + datetime.timedelta(weeks=1)
		self.filters['next_month'] = lambda dt: dt + datetime.timedelta(days=30)
		self.filters['next_year'] = lambda dt: dt + datetime.timedelta(days=365)
		self.filters['yesterday'] = lambda dt: dt + datetime.timedelta(days=-1)
github mosesschwartz / scrypture / scrypture / demo_scripts / Text / camelcase_to_underscores.py View on Github external
def camelcase_to_underscores(s):
    '''Converts a camelcased string to underscores'''
    return strutils.camel2under(s)
github GeoscienceAustralia / digitalearthau / datacubenci / sync.py View on Github external
for collection_name in collections:
        collection = NCI_COLLECTIONS[collection_name]

        log = _LOG.bind(collection=collection_name)
        collection_cache = cache.joinpath(query_name(collection.query))
        fileutils.mkdir_p(str(collection_cache))

        with AgdcDatasetPathIndex(index, collection.query) as path_index:
            for mismatch in find_index_disk_mismatches(log,
                                                       path_index,
                                                       collection.base_path,
                                                       collection.offset_pattern,
                                                       cache_path=collection_cache):
                click.echo('\t'.join(map(str, (
                    collection_name,
                    strutils.camel2under(mismatch.__class__.__name__),
                    mismatch.dataset.id,
                    mismatch.uri
                ))))
                if not dry_run:
                    log.info('mismatch.fix', mismatch=mismatch)
                    mismatch.fix(path_index)
github securestate / king-phisher-plugins / client / sftp_client.py View on Github external
parent_treerowref = task.parent.treerowref
					if parent_treerowref is None:
						continue
					parent_treepath = parent_treerowref.get_path()
					if parent_treepath is None:
						continue
					parent_treeiter = self._tv_model.get_iter(parent_treepath)
				direction = Gtk.STOCK_GO_FORWARD if task.transfer_direction == 'upload' else Gtk.STOCK_GO_BACK
				image = self.treeview_transfer.render_icon(direction, Gtk.IconSize.BUTTON, None) if parent_treeiter is None else Gtk.Image()
				treeiter = self._tv_model.append(parent_treeiter, [
					image,
					task.local_path,
					task.remote_path,
					task.state,
					0,
					None if (task.size is None or isinstance(task, TransferDirectoryTask)) else boltons.strutils.bytes2human(task.size),
					task
				])
				task.treerowref = Gtk.TreeRowReference.new(self._tv_model, self._tv_model.get_path(treeiter))
			elif task.treerowref.valid():
				row = self._tv_model[task.treerowref.get_path()]  # pylint: disable=unsubscriptable-object
				row[3] = task.state
				row[4] = task.progress
		self.queue.mutex.release()
		return False