sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
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... | Check request response for Slack API error
Args:
headers: Response headers
data: Response data
Raises:
:class:`slack.exceptions.SlackAPIError` | entailment |
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... | 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 | entailment |
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... | Find content-type and encoding of the response
Args:
headers: Response headers
Returns:
:py:class:`tuple` (content-type, encoding) | entailment |
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... | Prepare outgoing request
Create url, headers, add token to the body and if needed json encode it
Args:
url: :class:`slack.methods` item or string of url
data: Outgoing data
headers: Custom headers
global_headers: Global headers
token: Slack API token
as_json: Po... | entailment |
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... | Decode incoming response
Args:
status: Response status
headers: Response headers
body: Response body
Returns:
Response data | entailment |
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... | Find iteration mode and iteration key for a given :class:`slack.methods`
Args:
url: :class:`slack.methods` or string url
itermode: Custom iteration mode
iterkey: Custom iteration key
Returns:
:py:class:`tuple` (itermode, iterkey) | entailment |
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
... | Prepare outgoing iteration request
Args:
url: :class:`slack.methods` item or string of url
data: Outgoing data
limit: Maximum number of results to return per call.
iterkey: Key in response data to iterate over (required for url string).
itermode: Iteration mode (required for... | entailment |
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... | Decode incoming response from an iteration request
Args:
data: Response data
Returns:
Next itervalue | entailment |
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... | Check if the incoming event needs to be discarded
Args:
event: Incoming :class:`slack.events.Event`
bot_id: Id of connected bot
Returns:
boolean | entailment |
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... | 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 creating object from incoming HTTP request. Because the body of the request needs to be provided as text and not decoded a... | entailment |
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... | Runs a backup operation to At Least a local directory.
You must provide mongodb credentials along with a a directory for a dump
operation and a directory to contain your compressed backup.
backup_prefix: optionally provide a prefix to be prepended to your backups,
by default the pr... | entailment |
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... | Runs mongorestore with source data from the provided .tbz backup, using
the provided username and password.
The contents of the .tbz will be dumped into the provided backup directory,
and that folder will be deleted after a successful mongodb restore unless
cleanup is set to False.
Note: ... | entailment |
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. """
... | 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. | entailment |
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
... | 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
user must have restore permissions for the database. A mongolia superuser
will have more than a... | entailment |
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... | Returns a datetime object computed from a file name string, with
formatting based on DATETIME_FORMAT. | entailment |
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... | 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 default ("backup"),
provide it with the "custom_prefix" kwarg. | entailment |
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:
... | Use setuptools to search for a package's URI
@returns: URI string | entailment |
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... | 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 | entailment |
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 ... | Register a new handler for a specific slash command
Args:
command: Slash command
handler: Callback | entailment |
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... | Yields handlers matching the incoming :class:`slack.actions.Command`.
Args:
command: :class:`slack.actions.Command`
Yields:
handler | entailment |
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... | 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. | entailment |
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... | Select an Qt API to use.
This can only be set once and before any of the Qt modules are explicitly
imported. | entailment |
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... | 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 | entailment |
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
... | 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
@param version: project's PyPI version
@type version: string
... | entailment |
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... | 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 contains
a string and a pkg_resources Distribution ob... | entailment |
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
"""
... | 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 | entailment |
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... | Return case-sensitive package name given any-case package name
@param project_name: PyPI project name
@type project_name: string | entailment |
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()) | Non-atomic cache increment operation. Not optimal but
consistent across different cache backends. | entailment |
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... | Call all method on plugins in list, that define it, with provided
arguments. The first response that is not None is returned. | entailment |
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:
... | Load plugins, either builtin, others, or both. | entailment |
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... | Returns a Boto connection to the provided S3 bucket. | entailment |
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()
... | Lists the contents of the S3 bucket that end in .tbz and match
the passed prefix, if any. | entailment |
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... | 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 provided bucket with the .tbz extension, filtering by
prefix if it is provided. | entailment |
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... | Uploads the to Amazon S3 the contents of the provided file, keyed
with the name of the file. | entailment |
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... | Attempt to remedy:
https://www.riverbankcomputing.com/pipermail/pyqt/2016-February/037015.html | entailment |
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=
... | Setup the optparser
@returns: opt_parser.OptionParser | entailment |
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,
... | Check parse options that require pkg_spec
@returns: pkg_spec | entailment |
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
"""
... | 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 | entailment |
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... | 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` | entailment |
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:
... | Set log level according to command-line options
@returns: logger object | entailment |
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 ... | Perform actions based on CLI options
@returns: status code | entailment |
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... | 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 | entailment |
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... | 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 | entailment |
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
... | 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
@param active: show if package is activated or not
@type active: boolea... | entailment |
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... | Show dependencies for package(s)
@returns: 0 - sucess 1 - No dependency info supplied | entailment |
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... | Show detailed PyPI ChangeLog for the last `hours`
@returns: 0 = sucess or 1 if failed to retrieve from XML-RPC server | entailment |
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... | Show PyPI releases for the last number of `hours`
@returns: 0 = success or 1 if failed to retrieve from XML-RPC server | entailment |
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":
... | Query PyPI for pkg download URI for a packge
@returns: 0 | entailment |
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... | @param version: version number or 'dev' for svn
@type version: string
@param source: download source or egg
@type source: boolean
@returns: None | entailment |
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... | Download a package
@returns: 0 = success or 1 if failed download | entailment |
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... | 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 failed download | entailment |
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... | 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 download | entailment |
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... | 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 | entailment |
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
... | Show pkg metadata queried from PyPI
@returns: 0 | entailment |
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... | Query PyPI for a particular version or all versions of a package
@returns: 0 if version(s) found or 1 if none found | entailment |
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... | 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=ZPL AND name=Cheetah
@type spec: string
... | entailment |
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... | 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=GPL"]
@returns: 0 on success or 1 if... | entailment |
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... | Show entry map for a package
@param dist: package
@param type: srting
@returns: 0 for success or 1 if error | entailment |
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:
... | Show entry points for a module
@returns: 0 for success or 1 if error | entailment |
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
... | 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
@returns: tuple(project_name, version, all_versions) | entailment |
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... | 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 module AnyQt._backport as a substitute for PyQt... | entailment |
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... | 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: Import of PyQt4 is denied. | entailment |
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
... | Run command and return its return status code and its output | entailment |
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,... | Iterate over a slack API method supporting pagination
When using :class:`slack.methods` the request is made `as_json` if available
Args:
url: :class:`slack.methods` or url string
data: JSON encodable MutableMapping
headers:
limit: Maximum number of resul... | entailment |
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... | Connect and discard incoming RTM event if necessary.
:param url: Websocket url
:param bot_id: Bot ID
:return: Incoming events | entailment |
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... | Displays the login form and handles the login action. | entailment |
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... | 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 package manifest which can be checked.
'... | entailment |
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... | 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 xmlrpc. | entailment |
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"):
... | Returns URL of specified file type
'source', 'egg', or 'all' | entailment |
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)
... | Send xml-rpc request using proxy | entailment |
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... | Get a package name list from disk cache or PyPI | entailment |
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... | Returns PyPI's XML-RPC server instance | entailment |
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()
... | Fetch list of available versions for a package from The CheeseShop | entailment |
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")) | Return list of pickled package names from PYPI | entailment |
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 | Fetch and cache master list of package names from PYPI | entailment |
def search(self, spec, operator):
'''Query PYPI via XMLRPC interface using search spec'''
return self.xmlrpc.search(spec, operator.lower()) | Query PYPI via XMLRPC interface using search spec | entailment |
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... | Query PYPI via XMLRPC interface for a pkg's metadata | entailment |
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) | Query PYPI via XMLRPC interface for a pkg's available versions | entailment |
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... | Query PyPI for pkg download URI for a packge | entailment |
def clone(self) -> "Event":
"""
Clone the event
Returns:
:class:`slack.events.Event`
"""
return self.__class__(copy.deepcopy(self.event), copy.deepcopy(self.metadata)) | Clone the event
Returns:
:class:`slack.events.Event` | entailment |
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... | 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:
:class:`slack.events.Event` or :class:`slack.events.Message` | entailment |
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... | Create an event with data coming from the HTTP Event API.
If the event type is a message a :class:`slack.events.Message` is returned.
Args:
raw_body: Decoded body of the Event API request
verification_token: Slack verification token used to verify the request came from slack
... | entailment |
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... | 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): Overwrite the `threading` behaviour
Returns:
a new :class:`slack.even... | entailment |
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 | Serialize the message for sending to slack API
Returns:
serialized message | entailment |
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... | 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 used as a key/value pair to compare against what is in the incoming
:class:`slack.events.... | entailment |
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... | Yields handlers matching the routing of the incoming :class:`slack.events.Event`.
Args:
event: :class:`slack.events.Event`
Yields:
handler | entailment |
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... | Register a new handler for a specific :class:`slack.events.Message`.
The routing is based on regex pattern matching the message text and the incoming slack channel.
Args:
pattern: Regex pattern matching the message text.
handler: Callback
flags: Regex flags.
... | entailment |
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 ... | Yields handlers matching the routing of the incoming :class:`slack.events.Message`
Args:
message: :class:`slack.events.Message`
Yields:
handler | entailment |
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... | Query the slack API
When using :class:`slack.methods` the request is made `as_json` if available
Args:
url: :class:`slack.methods` or url string
data: JSON encodable MutableMapping
headers: Custom headers
as_json: Post JSON to the slack API
Retur... | entailment |
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... | Iterate over event from the RTM API
Args:
url: Websocket connection url
bot_id: Connecting bot ID
Returns:
:class:`slack.events.Event` or :class:`slack.events.Message` | entailment |
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... | Displays the login form for the given HttpRequest. | entailment |
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... | Get configuration from a file. | entailment |
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... | 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_options specified in the config file at the base
* DEFAULT_OPTIONS h... | entailment |
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]
... | Output the results to stdout.
TODO: add AMPQ support for efficiency | entailment |
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... | 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
downstream file operations. If you are downloading a VCF, then
"False" is great. If this is a B... | entailment |
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) | Accurate float rounding from http://stackoverflow.com/a/15398691. | entailment |
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 >= ... | 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. | entailment |
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... | 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. | entailment |
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... | Returns the first and last name of the user separated by a space. | entailment |
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:
... | 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 >. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.