Search is not available for this dataset
text stringlengths 75 104k |
|---|
def raise_for_api_error(headers: MutableMapping, data: MutableMapping) -> None:
"""
Check request response for Slack API error
Args:
headers: Response headers
data: Response data
Raises:
:class:`slack.exceptions.SlackAPIError`
"""
if not data["ok"]:
raise excep... |
def decode_body(headers: MutableMapping, body: bytes) -> dict:
"""
Decode the response body
For 'application/json' content-type load the body as a dictionary
Args:
headers: Response headers
body: Response body
Returns:
decoded body
"""
type_, encoding = parse_cont... |
def parse_content_type(headers: MutableMapping) -> Tuple[Optional[str], str]:
"""
Find content-type and encoding of the response
Args:
headers: Response headers
Returns:
:py:class:`tuple` (content-type, encoding)
"""
content_type = headers.get("content-type")
if not content... |
def prepare_request(
url: Union[str, methods],
data: Optional[MutableMapping],
headers: Optional[MutableMapping],
global_headers: MutableMapping,
token: str,
as_json: Optional[bool] = None,
) -> Tuple[str, Union[str, MutableMapping], MutableMapping]:
"""
Prepare outgoing request
Cre... |
def decode_response(status: int, headers: MutableMapping, body: bytes) -> dict:
"""
Decode incoming response
Args:
status: Response status
headers: Response headers
body: Response body
Returns:
Response data
"""
data = decode_body(headers, body)
raise_for_st... |
def find_iteration(
url: Union[methods, str],
itermode: Optional[str] = None,
iterkey: Optional[str] = None,
) -> Tuple[str, str]:
"""
Find iteration mode and iteration key for a given :class:`slack.methods`
Args:
url: :class:`slack.methods` or string url
itermode: Custom iterat... |
def prepare_iter_request(
url: Union[methods, str],
data: MutableMapping,
*,
iterkey: Optional[str] = None,
itermode: Optional[str] = None,
limit: int = 200,
itervalue: Optional[Union[str, int]] = None,
) -> Tuple[MutableMapping, str, str]:
"""
Prepare outgoing iteration request
... |
def decode_iter_request(data: dict) -> Optional[Union[str, int]]:
"""
Decode incoming response from an iteration request
Args:
data: Response data
Returns:
Next itervalue
"""
if "response_metadata" in data:
return data["response_metadata"].get("next_cursor")
elif "p... |
def discard_event(event: events.Event, bot_id: str = None) -> bool:
"""
Check if the incoming event needs to be discarded
Args:
event: Incoming :class:`slack.events.Event`
bot_id: Id of connected bot
Returns:
boolean
"""
if event["type"] in SKIP_EVENTS:
return T... |
def validate_request_signature(
body: str, headers: MutableMapping, signing_secret: str
) -> None:
"""
Validate incoming request signature using the application signing secret.
Contrary to the ``team_id`` and ``verification_token`` verification this method is not called by ``slack-sansio`` when creatin... |
def backup(mongo_username, mongo_password, local_backup_directory_path, database=None,
attached_directory_path=None, custom_prefix="backup",
mongo_backup_directory_path="/tmp/mongo_dump",
s3_bucket=None, s3_access_key_id=None, s3_secret_key=None,
purge_local=None, purge_a... |
def restore(mongo_user, mongo_password, backup_tbz_path,
backup_directory_output_path="/tmp/mongo_dump",
drop_database=False, cleanup=True, silent=False,
skip_system_and_user_files=False):
"""
Runs mongorestore with source data from the provided .tbz backup, using
t... |
def mongodump(mongo_user, mongo_password, mongo_dump_directory_path, database=None, silent=False):
""" Runs mongodump using the provided credentials on the running mongod
process.
WARNING: This function will delete the contents of the provided
directory before it runs. """
... |
def mongorestore(mongo_user, mongo_password, backup_directory_path, drop_database=False, silent=False):
""" Warning: Setting drop_database to True will drop the ENTIRE
CURRENTLY RUNNING DATABASE before restoring.
Mongorestore requires a running mongod process, in addition the provided
... |
def get_backup_file_time_tag(file_name, custom_prefix="backup"):
""" Returns a datetime object computed from a file name string, with
formatting based on DATETIME_FORMAT."""
name_string = file_name[len(custom_prefix):]
time_tag = name_string.split(".", 1)[0]
return datetime.strptime(time_ta... |
def purge_old_files(date_time, directory_path, custom_prefix="backup"):
""" Takes a datetime object and a directory path, runs through files in the
directory and deletes those tagged with a date from before the provided
datetime.
If your backups have a custom_prefix that is not the defau... |
def get_download_uri(package_name, version, source, index_url=None):
"""
Use setuptools to search for a package's URI
@returns: URI string
"""
tmpdir = None
force_scan = True
develop_ok = False
if not index_url:
index_url = 'http://cheeseshop.python.org/pypi'
if version:
... |
def get_pkglist():
"""
Return list of all installed packages
Note: It returns one project name per pkg no matter how many versions
of a particular package is installed
@returns: list of project name strings for every installed pkg
"""
dists = Distributions()
projects = []
for (di... |
def register(self, command: str, handler: Any):
"""
Register a new handler for a specific slash command
Args:
command: Slash command
handler: Callback
"""
if not command.startswith("/"):
command = f"/{command}"
LOG.info("Registering ... |
def dispatch(self, command: Command) -> Iterator[Any]:
"""
Yields handlers matching the incoming :class:`slack.actions.Command`.
Args:
command: :class:`slack.actions.Command`
Yields:
handler
"""
LOG.debug("Dispatching command %s", command["comman... |
def setpreferredapi(api):
"""
Set the preferred Qt API.
Will raise a RuntimeError if a Qt API was already selected.
Note that QT_API environment variable (if set) will take precedence.
"""
global __PREFERRED_API
if __SELECTED_API is not None:
raise RuntimeError("A Qt api {} was alr... |
def selectapi(api):
"""
Select an Qt API to use.
This can only be set once and before any of the Qt modules are explicitly
imported.
"""
global __SELECTED_API, USED_API
if api.lower() not in {"pyqt4", "pyqt5", "pyside", "pyside2"}:
raise ValueError(api)
if __SELECTED_API is not... |
def get_highest_version(versions):
"""
Returns highest available version for a package in a list of versions
Uses pkg_resources to parse the versions
@param versions: List of PyPI package versions
@type versions: List of strings
@returns: string of a PyPI package version
"""
sorted_v... |
def get_distributions(self, show, pkg_name="", version=""):
"""
Yield installed packages
@param show: Type of package(s) to show; active, non-active or all
@type show: string: "active", "non-active", "all"
@param pkg_name: PyPI project name
@type pkg_name: string
... |
def get_alpha(self, show, pkg_name="", version=""):
"""
Return list of alphabetized packages
@param pkg_name: PyPI project name
@type pkg_name: string
@param version: project's PyPI version
@type version: string
@returns: Alphabetized list of tuples. Each tuple... |
def get_packages(self, show):
"""
Return list of Distributions filtered by active status or all
@param show: Type of package(s) to show; active, non-active or all
@type show: string: "active", "non-active", "all"
@returns: list of pkg_resources Distribution objects
"""
... |
def case_sensitive_name(self, package_name):
"""
Return case-sensitive package name given any-case package name
@param project_name: PyPI project name
@type project_name: string
"""
if len(self.environment[package_name]):
return self.environment[package_name... |
def cache_incr(self, key):
"""
Non-atomic cache increment operation. Not optimal but
consistent across different cache backends.
"""
cache.set(key, cache.get(key, 0) + 1, self.expire_after()) |
def call_plugins(plugins, method, *arg, **kw):
"""Call all method on plugins in list, that define it, with provided
arguments. The first response that is not None is returned.
"""
for plug in plugins:
func = getattr(plug, method, None)
if func is None:
continue
#LOG.d... |
def load_plugins(builtin=True, others=True):
"""Load plugins, either builtin, others, or both.
"""
for entry_point in pkg_resources.iter_entry_points('yolk.plugins'):
#LOG.debug("load plugin %s" % entry_point)
try:
plugin = entry_point.load()
except KeyboardInterrupt:
... |
def s3_connect(bucket_name, s3_access_key_id, s3_secret_key):
""" Returns a Boto connection to the provided S3 bucket. """
conn = connect_s3(s3_access_key_id, s3_secret_key)
try:
return conn.get_bucket(bucket_name)
except S3ResponseError as e:
if e.status == 403:
raise Except... |
def s3_list(s3_bucket, s3_access_key_id, s3_secret_key, prefix=None):
""" Lists the contents of the S3 bucket that end in .tbz and match
the passed prefix, if any. """
bucket = s3_connect(s3_bucket, s3_access_key_id, s3_secret_key)
return sorted([key.name for key in bucket.list()
... |
def s3_download(output_file_path, s3_bucket, s3_access_key_id, s3_secret_key,
s3_file_key=None, prefix=None):
""" Downloads the file matching the provided key, in the provided bucket,
from Amazon S3.
If s3_file_key is none, it downloads the last file
from the provide... |
def s3_upload(source_file_path, bucket_name, s3_access_key_id, s3_secret_key):
""" Uploads the to Amazon S3 the contents of the provided file, keyed
with the name of the file. """
key = s3_key(bucket_name, s3_access_key_id, s3_secret_key)
file_name = source_file_path.split("/")[-1]
key.key = fil... |
def fix_pyqt5_QGraphicsItem_itemChange():
"""
Attempt to remedy:
https://www.riverbankcomputing.com/pipermail/pyqt/2016-February/037015.html
"""
from PyQt5.QtWidgets import QGraphicsObject, QGraphicsItem
class Obj(QGraphicsObject):
def itemChange(self, change, value):
return... |
def setup_opt_parser():
"""
Setup the optparser
@returns: opt_parser.OptionParser
"""
#pylint: disable-msg=C0301
#line too long
usage = "usage: %prog [options]"
opt_parser = optparse.OptionParser(usage=usage)
opt_parser.add_option("--version", action='store_true', dest=
... |
def validate_pypi_opts(opt_parser):
"""
Check parse options that require pkg_spec
@returns: pkg_spec
"""
(options, remaining_args) = opt_parser.parse_args()
options_pkg_specs = [ options.versions_available,
options.query_metadata_pypi,
options.show_download_links,
... |
def write(self, inline):
"""
Write a line to stdout if it isn't in a blacklist
Try to get the name of the calling module to see if we want
to filter it. If there is no calling module, use current
frame in case there's a traceback before there is any calling module
"""
... |
def get_plugin(self, method):
"""
Return plugin object if CLI option is activated and method exists
@param method: name of plugin's method we're calling
@type method: string
@returns: list of plugins with `method`
"""
all_plugins = []
for entry_point in... |
def set_log_level(self):
"""
Set log level according to command-line options
@returns: logger object
"""
if self.options.debug:
self.logger.setLevel(logging.DEBUG)
elif self.options.quiet:
self.logger.setLevel(logging.ERROR)
else:
... |
def run(self):
"""
Perform actions based on CLI options
@returns: status code
"""
opt_parser = setup_opt_parser()
(self.options, remaining_args) = opt_parser.parse_args()
logger = self.set_log_level()
pkg_spec = validate_pypi_opts(opt_parser)
if ... |
def show_updates(self):
"""
Check installed packages for available updates on PyPI
@param project_name: optional package name to check; checks every
installed pacakge if none specified
@type project_name: string
@returns: None
"""
di... |
def show_distributions(self, show):
"""
Show list of installed activated OR non-activated packages
@param show: type of pkgs to show (all, active or nonactive)
@type show: string
@returns: None or 2 if error
"""
show_metadata = self.options.metadata
#Se... |
def print_metadata(self, metadata, develop, active, installed_by):
"""
Print out formatted metadata
@param metadata: package's metadata
@type metadata: pkg_resources Distribution obj
@param develop: path to pkg if its deployed in development mode
@type develop: string
... |
def show_deps(self):
"""
Show dependencies for package(s)
@returns: 0 - sucess 1 - No dependency info supplied
"""
pkgs = pkg_resources.Environment()
for pkg in pkgs[self.project_name]:
if not self.version:
print(pkg.project_name, pkg.versi... |
def show_pypi_changelog(self):
"""
Show detailed PyPI ChangeLog for the last `hours`
@returns: 0 = sucess or 1 if failed to retrieve from XML-RPC server
"""
hours = self.options.show_pypi_changelog
if not hours.isdigit():
self.logger.error("Error: You must s... |
def show_pypi_releases(self):
"""
Show PyPI releases for the last number of `hours`
@returns: 0 = success or 1 if failed to retrieve from XML-RPC server
"""
try:
hours = int(self.options.show_pypi_releases)
except ValueError:
self.logger.error("E... |
def show_download_links(self):
"""
Query PyPI for pkg download URI for a packge
@returns: 0
"""
#In case they specify version as 'dev' instead of using -T svn,
#don't show three svn URI's
if self.options.file_type == "all" and self.version == "dev":
... |
def print_download_uri(self, version, source):
"""
@param version: version number or 'dev' for svn
@type version: string
@param source: download source or egg
@type source: boolean
@returns: None
"""
if version == "dev":
pkg_type = "subvers... |
def fetch(self):
"""
Download a package
@returns: 0 = success or 1 if failed download
"""
#Default type to download
source = True
directory = "."
if self.options.file_type == "svn":
version = "dev"
svn_uri = get_download_uri(self... |
def fetch_uri(self, directory, uri):
"""
Use ``urllib.urlretrieve`` to download package to file in sandbox dir.
@param directory: directory to download to
@type directory: string
@param uri: uri to download
@type uri: string
@returns: 0 = success or 1 for faile... |
def fetch_svn(self, svn_uri, directory):
"""
Fetch subversion repository
@param svn_uri: subversion repository uri to check out
@type svn_uri: string
@param directory: directory to download to
@type directory: string
@returns: 0 = success or 1 for failed downlo... |
def browse_website(self, browser=None):
"""
Launch web browser at project's homepage
@param browser: name of web browser to use
@type browser: string
@returns: 0 if homepage found, 1 if no homepage found
"""
if len(self.all_versions):
metadata = self... |
def query_metadata_pypi(self):
"""
Show pkg metadata queried from PyPI
@returns: 0
"""
if self.version and self.version in self.all_versions:
metadata = self.pypi.release_data(self.project_name, self.version)
else:
#Give highest version
... |
def versions_available(self):
"""
Query PyPI for a particular version or all versions of a package
@returns: 0 if version(s) found or 1 if none found
"""
if self.version:
spec = "%s==%s" % (self.project_name, self.version)
else:
spec = self.proje... |
def parse_search_spec(self, spec):
"""
Parse search args and return spec dict for PyPI
* Owwww, my eyes!. Re-write this.
@param spec: Cheese Shop package search spec
e.g.
name=Cheetah
license=ZPL
license... |
def pypi_search(self):
"""
Search PyPI by metadata keyword
e.g. yolk -S name=yolk AND license=GPL
@param spec: Cheese Shop search spec
@type spec: list of strings
spec examples:
["name=yolk"]
["license=GPL"]
["name=yolk", "AND", "license=GP... |
def show_entry_map(self):
"""
Show entry map for a package
@param dist: package
@param type: srting
@returns: 0 for success or 1 if error
"""
pprinter = pprint.PrettyPrinter()
try:
entry_map = pkg_resources.get_entry_map(self.options.show_ent... |
def show_entry_points(self):
"""
Show entry points for a module
@returns: 0 for success or 1 if error
"""
found = False
for entry_point in \
pkg_resources.iter_entry_points(self.options.show_entry_points):
found = True
try:
... |
def parse_pkg_ver(self, want_installed):
"""
Return tuple with project_name and version from CLI args
If the user gave the wrong case for the project name, this corrects it
@param want_installed: whether package we want is installed or not
@type want_installed: boolean
... |
def install_backport_hook(api):
"""
Install a backport import hook for Qt4 api
Parameters
----------
api : str
The Qt4 api whose structure should be intercepted
('pyqt4' or 'pyside').
Example
-------
>>> install_backport_hook("pyqt4")
>>> import PyQt4
Loaded mod... |
def install_deny_hook(api):
"""
Install a deny import hook for Qt api.
Parameters
----------
api : str
The Qt api whose import should be prevented
Example
-------
>>> install_deny_import("pyqt4")
>>> import PyQt4
Traceback (most recent call last):...
ImportError: Im... |
def run_command(cmd, env=None, max_timeout=None):
"""
Run command and return its return status code and its output
"""
arglist = cmd.split()
output = os.tmpfile()
try:
pipe = Popen(arglist, stdout=output, stderr=STDOUT, env=env)
except Exception as errmsg:
return 1, errmsg
... |
async def iter(
self,
url: Union[str, methods],
data: Optional[MutableMapping] = None,
headers: Optional[MutableMapping] = None,
*,
limit: int = 200,
iterkey: Optional[str] = None,
itermode: Optional[str] = None,
minimum_time: Optional[int] = None,... |
async def _incoming_from_rtm(
self, url: str, bot_id: str
) -> AsyncIterator[events.Event]:
"""
Connect and discard incoming RTM event if necessary.
:param url: Websocket url
:param bot_id: Bot ID
:return: Incoming events
"""
async for data in self._r... |
def login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm,
current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.POST.get(r... |
def package_manager_owns(self, dist):
"""
Returns True if package manager 'owns' file
Returns False if package manager does not 'own' file
There is currently no way to determine if distutils or
setuptools installed a package. A future feature of setuptools
will make a pa... |
def check_proxy_setting():
"""
If the environmental variable 'HTTP_PROXY' is set, it will most likely be
in one of these forms:
proxyhost:8080
http://proxyhost:8080
urlllib2 requires the proxy URL to start with 'http://'
This routine does that, and returns the transport for xml... |
def filter_url(pkg_type, url):
"""
Returns URL of specified file type
'source', 'egg', or 'all'
"""
bad_stuff = ["?modtime", "#md5="]
for junk in bad_stuff:
if junk in url:
url = url.split(junk)[0]
break
#pkg_spec==dev (svn)
if url.endswith("-dev"):
... |
def request(self, host, handler, request_body, verbose):
'''Send xml-rpc request using proxy'''
#We get a traceback if we don't have this attribute:
self.verbose = verbose
url = 'http://' + host + handler
request = urllib2.Request(url)
request.add_data(request_body)
... |
def get_cache(self):
"""
Get a package name list from disk cache or PyPI
"""
#This is used by external programs that import `CheeseShop` and don't
#want a cache file written to ~/.pypi and query PyPI every time.
if self.no_cache:
self.pkg_list = self.list_pack... |
def get_xmlrpc_server(self):
"""
Returns PyPI's XML-RPC server instance
"""
check_proxy_setting()
if os.environ.has_key('XMLRPC_DEBUG'):
debug = 1
else:
debug = 0
try:
return xmlrpclib.Server(XML_RPC_SERVER, transport=ProxyTrans... |
def query_versions_pypi(self, package_name):
"""Fetch list of available versions for a package from The CheeseShop"""
if not package_name in self.pkg_list:
self.logger.debug("Package %s not in cache, querying PyPI..." \
% package_name)
self.fetch_pkg_list()
... |
def query_cached_package_list(self):
"""Return list of pickled package names from PYPI"""
if self.debug:
self.logger.debug("DEBUG: reading pickled cache file")
return cPickle.load(open(self.pkg_cache_file, "r")) |
def fetch_pkg_list(self):
"""Fetch and cache master list of package names from PYPI"""
self.logger.debug("DEBUG: Fetching package name list from PyPI")
package_list = self.list_packages()
cPickle.dump(package_list, open(self.pkg_cache_file, "w"))
self.pkg_list = package_list |
def search(self, spec, operator):
'''Query PYPI via XMLRPC interface using search spec'''
return self.xmlrpc.search(spec, operator.lower()) |
def release_data(self, package_name, version):
"""Query PYPI via XMLRPC interface for a pkg's metadata"""
try:
return self.xmlrpc.release_data(package_name, version)
except xmlrpclib.Fault:
#XXX Raises xmlrpclib.Fault if you give non-existant version
#Could th... |
def package_releases(self, package_name):
"""Query PYPI via XMLRPC interface for a pkg's available versions"""
if self.debug:
self.logger.debug("DEBUG: querying PyPI for versions of " \
+ package_name)
return self.xmlrpc.package_releases(package_name) |
def get_download_urls(self, package_name, version="", pkg_type="all"):
"""Query PyPI for pkg download URI for a packge"""
if version:
versions = [version]
else:
#If they don't specify version, show em all.
(package_name, versions) = self.query_versions_pypi... |
def clone(self) -> "Event":
"""
Clone the event
Returns:
:class:`slack.events.Event`
"""
return self.__class__(copy.deepcopy(self.event), copy.deepcopy(self.metadata)) |
def from_rtm(cls, raw_event: MutableMapping) -> "Event":
"""
Create an event with data coming from the RTM API.
If the event type is a message a :class:`slack.events.Message` is returned.
Args:
raw_event: JSON decoded data from the RTM API
Returns:
:cla... |
def from_http(
cls,
raw_body: MutableMapping,
verification_token: Optional[str] = None,
team_id: Optional[str] = None,
) -> "Event":
"""
Create an event with data coming from the HTTP Event API.
If the event type is a message a :class:`slack.events.Message` i... |
def response(self, in_thread: Optional[bool] = None) -> "Message":
"""
Create a response message.
Depending on the incoming message the response can be in a thread. By default the response follow where the
incoming message was posted.
Args:
in_thread (boolean): Over... |
def serialize(self) -> dict:
"""
Serialize the message for sending to slack API
Returns:
serialized message
"""
data = {**self}
if "attachments" in self:
data["attachments"] = json.dumps(self["attachments"])
return data |
def register(self, event_type: str, handler: Any, **detail: Any) -> None:
"""
Register a new handler for a specific :class:`slack.events.Event` `type` (See `slack event types documentation
<https://api.slack.com/events>`_ for a list of event types).
The arbitrary keyword argument is use... |
def dispatch(self, event: Event) -> Iterator[Any]:
"""
Yields handlers matching the routing of the incoming :class:`slack.events.Event`.
Args:
event: :class:`slack.events.Event`
Yields:
handler
"""
LOG.debug('Dispatching event "%s"', event.get("t... |
def register(
self,
pattern: str,
handler: Any,
flags: int = 0,
channel: str = "*",
subtype: Optional[str] = None,
) -> None:
"""
Register a new handler for a specific :class:`slack.events.Message`.
The routing is based on regex pattern matchi... |
def dispatch(self, message: Message) -> Iterator[Any]:
"""
Yields handlers matching the routing of the incoming :class:`slack.events.Message`
Args:
message: :class:`slack.events.Message`
Yields:
handler
"""
if "text" in message:
text ... |
def query( # type: ignore
self,
url: Union[str, methods],
data: Optional[MutableMapping] = None,
headers: Optional[MutableMapping] = None,
as_json: Optional[bool] = None,
) -> dict:
"""
Query the slack API
When using :class:`slack.methods` the reques... |
def rtm( # type: ignore
self, url: Optional[str] = None, bot_id: Optional[str] = None
) -> Iterator[events.Event]:
"""
Iterate over event from the RTM API
Args:
url: Websocket connection url
bot_id: Connecting bot ID
Returns:
:class:`sla... |
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
context = {
'title': _('Log in'),
'app_path': request.get_full_path(),
}
if (REDIRECT_FIELD_NAME not in request.GET and
REDIREC... |
def get_config(config_file):
"""Get configuration from a file."""
def load(fp):
try:
return yaml.safe_load(fp)
except yaml.YAMLError as e:
sys.stderr.write(text_type(e))
sys.exit(1) # TODO document exit codes
if config_file == '-':
return load(sy... |
def get_options(config_options, local_options, cli_options):
"""
Figure out what options to use based on the four places it can come from.
Order of precedence:
* cli_options specified by the user at the command line
* local_options specified in the config file for the metric
* config_op... |
def output_results(results, metric, options):
"""
Output the results to stdout.
TODO: add AMPQ support for efficiency
"""
formatter = options['Formatter']
context = metric.copy() # XXX might need to sanitize this
try:
context['dimension'] = list(metric['Dimensions'].values())[0]
... |
def download_to_path(self, gsuri, localpath, binary_mode=False, tmpdir=None):
"""
This method is analogous to "gsutil cp gsuri localpath", but in a
programatically accesible way. The only difference is that we
have to make a guess about the encoding of the file to not upset
downs... |
def round_float(f, digits, rounding=ROUND_HALF_UP):
"""
Accurate float rounding from http://stackoverflow.com/a/15398691.
"""
return Decimal(str(f)).quantize(Decimal(10) ** (-1 * digits),
rounding=rounding) |
def float_str(f, min_digits=2, max_digits=6):
"""
Returns a string representing a float, where the number of
significant digits is min_digits unless it takes more digits
to hit a non-zero digit (and the number is 0 < x < 1).
We stop looking for a non-zero digit after max_digits.
"""
if f >= ... |
def default_format(self):
"""
Returns full name (first and last) if name is available.
If not, returns username if available.
If not available too, returns the user id as a string.
"""
user = self.user
if user.first_name is not None:
return self.full_n... |
def full_name(self):
"""
Returns the first and last name of the user separated by a space.
"""
formatted_user = []
if self.user.first_name is not None:
formatted_user.append(self.user.first_name)
if self.user.last_name is not None:
formatted_user.a... |
def full_format(self):
"""
Returns the full name (first and last parts), and the username between brackets if the user has it.
If there is no info about the user, returns the user id between < and >.
"""
formatted_user = self.full_name
if self.user.username is not None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.