text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_metadata(dist):
""" Return dictionary of metadata for given dist @param dist: distribution @type dist: pkg_resources Distribution object @returns: dict o... |
if not dist.has_metadata('PKG-INFO'):
return
msg = email.message_from_string(dist.get_metadata('PKG-INFO'))
metadata = {}
for header in [l for l in msg._headers]:
metadata[header[0]] = header[1]
return metadata |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_options(self, parser):
"""Add command-line options for this plugin. The base plugin class adds --with-$name by default, used to enable the plugin. """ |
parser.add_option("--with-%s" % self.name,
action="store_true",
dest=self.enable_opt,
help="Enable plugin %s: %s" %
(self.__class__.__name__, self.help())
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self, options, conf):
"""Configure the plugin and system, based on selected options. The base plugin class sets the plugin to enabled if the enable... |
self.conf = conf
if hasattr(options, self.enable_opt):
self.enabled = getattr(options, self.enable_opt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raise_for_status( status: int, headers: MutableMapping, data: MutableMapping ) -> None: """ Check request response status Args: status: Response status header... |
if status != 200:
if status == 429:
if isinstance(data, str):
error = data
else:
error = data.get("error", "ratelimited")
try:
retry_after = int(headers.get("Retry-After", 1))
except ValueError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raise_for_api_error(headers: MutableMapping, data: MutableMapping) -> None: """ Check request response for Slack API error Args: headers: Response headers dat... |
if not data["ok"]:
raise exceptions.SlackAPIError(data.get("error", "unknow_error"), headers, data)
if "warning" in data:
LOG.warning("Slack API WARNING: %s", data["warning"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_body(headers: MutableMapping, body: bytes) -> dict: """ Decode the response body For 'application/json' content-type load the body as a dictionary Args... |
type_, encoding = parse_content_type(headers)
decoded_body = body.decode(encoding)
# There is one api that just returns `ok` instead of json. In order to have a consistent API we decided to modify the returned payload into a dict.
if type_ == "application/json":
payload = json.loads(decoded_b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_content_type(headers: MutableMapping) -> Tuple[Optional[str], str]: """ Find content-type and encoding of the response Args: headers: Response headers R... |
content_type = headers.get("content-type")
if not content_type:
return None, "utf-8"
else:
type_, parameters = cgi.parse_header(content_type)
encoding = parameters.get("charset", "utf-8")
return type_, encoding |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_request( url: Union[str, methods], data: Optional[MutableMapping], headers: Optional[MutableMapping], global_headers: MutableMapping, token: str, as_j... |
if isinstance(url, methods):
as_json = as_json or url.value[3]
real_url = url.value[0]
else:
real_url = url
as_json = False
if not headers:
headers = {**global_headers}
else:
headers = {**global_headers, **headers}
payload: Optional[Union[str, Muta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_response(status: int, headers: MutableMapping, body: bytes) -> dict: """ Decode incoming response Args: status: Response status headers: Response heade... |
data = decode_body(headers, body)
raise_for_status(status, headers, data)
raise_for_api_error(headers, data)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_iter_request( url: Union[methods, str], data: MutableMapping, *, iterkey: Optional[str] = None, itermode: Optional[str] = None, limit: int = 200, iter... |
itermode, iterkey = find_iteration(url, itermode, iterkey)
if itermode == "cursor":
data["limit"] = limit
if itervalue:
data["cursor"] = itervalue
elif itermode == "page":
data["count"] = limit
if itervalue:
data["page"] = itervalue
elif itermode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_iter_request(data: dict) -> Optional[Union[str, int]]: """ Decode incoming response from an iteration request Args: data: Response data Returns: Next i... |
if "response_metadata" in data:
return data["response_metadata"].get("next_cursor")
elif "paging" in data:
current_page = int(data["paging"].get("page", 1))
max_page = int(data["paging"].get("pages", 1))
if current_page < max_page:
return current_page + 1
elif "... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.even... |
if event["type"] in SKIP_EVENTS:
return True
elif bot_id and isinstance(event, events.Message):
if event.get("bot_id") == bot_id:
LOG.debug("Ignoring event: %s", event)
return True
elif "message" in event and event["message"].get("bot_id") == bot_id:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_request_signature( body: str, headers: MutableMapping, signing_secret: str ) -> None: """ Validate incoming request signature using the application s... |
request_timestamp = int(headers["X-Slack-Request-Timestamp"])
if (int(time.time()) - request_timestamp) > (60 * 5):
raise exceptions.InvalidTimestamp(timestamp=request_timestamp)
slack_signature = headers["X-Slack-Signature"]
calculated_signature = (
"v0="
+ hmac.new(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 DATET... |
name_string = file_name[len(custom_prefix):]
time_tag = name_string.split(".", 1)[0]
return datetime.strptime(time_tag, DATETIME_FORMAT) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
pkg_spec = "%s==%s" % (package_name, version)
else:
pkg_spec = package_name
req = pkg_resources.Requirement.parse(pkg_spec)
pkg_index... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ins... |
dists = Distributions()
projects = []
for (dist, _active) in dists.get_distributions("all"):
if dist.project_name not in projects:
projects.append(dist.project_name)
return projects |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 %s to %s", command, handler)
self._routes[command].append(handler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
global __PREFERRED_API
if __SELECTED_API is not None:
raise RuntimeError("A Qt api {} was already selected"
.format(__SELECTED_API))
if api.lower() not in {"pyqt4", "pyqt5", "pyside", "pyside2"}:
raise ValueError(api)
__PREFERRED_API = api.lower() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 None and __SELECTED_API.lower() != api.lower():
raise RuntimeError("A Qt API {} was already selected"
.format(__SELECTED_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 vers... |
sorted_versions = []
for ver in versions:
sorted_versions.append((pkg_resources.parse_version(ver), ver))
sorted_versions = sorted(sorted_versions)
sorted_versions.reverse()
return sorted_versions[0][1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
#pylint: disable-msg=W0612
#'name' is a placeholder for the sorted list
for name, dist in self.get_alpha(show, pkg_name, version):
ver = dist.version
for package in self.environment[dist.project_name]:
if ver == package.version:
if sho... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_alpha(self, show, pkg_name="", version=""):
""" Return list of alphabetized packages @param pkg_name: PyPI project name @type pkg_name: string @param ver... |
alpha_list = []
for dist in self.get_packages(show):
if pkg_name and dist.project_name != pkg_name:
#Only checking for a single package name
pass
elif version and dist.version != version:
#Only checking for a single version of a pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 al... |
if show == 'nonactive' or show == "all":
all_packages = []
for package in self.environment:
#There may be multiple versions of same packages
for i in range(len(self.environment[package])):
if self.environment[package][i]:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def case_sensitive_name(self, package_name):
""" Return case-sensitive package name given any-case package name @param project_name: PyPI project name @type proj... |
if len(self.environment[package_name]):
return self.environment[package_name][0].project_name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 Non... |
for plug in plugins:
func = getattr(plug, method, None)
if func is None:
continue
#LOG.debug("call plugin %s: %s", plug.name, method)
result = func(*arg, **kw)
if result is not None:
return result
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
raise
except Exception as err_msg:
# never want a plugin load to exit yolk
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 Exception("Bad Amazon S3 credentials.")
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 an... |
bucket = s3_connect(s3_bucket, s3_access_key_id, s3_secret_key)
return sorted([key.name for key in bucket.list()
if key.name.endswith(".tbz")
and (prefix is None or key.name.startswith(prefix))]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, i... |
bucket = s3_connect(s3_bucket, s3_access_key_id, s3_secret_key)
if not s3_file_key:
keys = s3_list(s3_bucket, s3_access_key_id, s3_secret_key, prefix)
if not keys:
raise Exception("Target S3 bucket is empty")
s3_file_key = keys[-1]
key = Key(bucket, s3_file_key)
with... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 nam... |
key = s3_key(bucket_name, s3_access_key_id, s3_secret_key)
file_name = source_file_path.split("/")[-1]
key.key = file_name
if key.exists():
raise Exception("s3 key %s already exists for current period."
% (file_name))
key.set_contents_from_filename(source_file_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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,
options.browse_website,
options.fetch,
options.show_deps,
]
for pkg_spec i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
frame = inspect.currentframe().f_back
if frame:
mod = frame.f_globals.get('__name__')
else:
mod = sys._getframe(0).f_globals.get('__name__')
if not mod in self.modulenames:
self.stdout.write(inline) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 me... |
all_plugins = []
for entry_point in pkg_resources.iter_entry_points('yolk.plugins'):
plugin_obj = entry_point.load()
plugin = plugin_obj()
plugin.configure(self.options, None)
if plugin.enabled:
if not hasattr(plugin, method):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
self.logger.setLevel(logging.INFO)
self.logger.addHandler(logging.StreamHandler())
return self.logger |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 not pkg_spec:
pkg_spec = remaining_args
self.pkg_spec = pkg_spec
if not self.options.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_updates(self):
""" Check installed packages for available updates on PyPI @param project_name: optional package name to check; checks every installed pa... |
dists = Distributions()
if self.project_name:
#Check for a single package
pkg_list = [self.project_name]
else:
#Check for every installed package
pkg_list = get_pkglist()
found = None
for pkg in pkg_list:
for (dist, act... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) @... |
show_metadata = self.options.metadata
#Search for any plugins with active CLI options with add_column() method
plugins = self.get_plugin("add_column")
#Some locations show false positive for 'development' packages:
ignores = ["/UNIONFS", "/KNOPPIX.IMG"]
#Check if we'r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 supply an integer.")
return 1
try:
changelog = self.pypi.changelog(int(hours))
except XMLRPCFault as err_msg:
self.logger.error(err_msg)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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("ERROR: You must supply an integer.")
return 1
try:
latest_releases = self.pypi.updated_releases(hours)
except XMLRPCFault as err_msg:
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.project_name, \
"dev", True)
if svn_uri:
directory = self.project_name + "... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_uri(self, directory, uri):
""" Use ``urllib.urlretrieve`` to download package to file in sandbox dir. @param directory: directory to download to @type ... |
filename = os.path.basename(urlparse(uri)[2])
if os.path.exists(filename):
self.logger.error("ERROR: File exists: " + filename)
return 1
try:
downloaded_filename, headers = urlretrieve(uri, filename)
self.logger.info("Downloaded ./" + filename)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_svn(self, svn_uri, directory):
""" Fetch subversion repository @param svn_uri: subversion repository uri to check out @type svn_uri: string @param dire... |
if not command_successful("svn --version"):
self.logger.error("ERROR: Do you have subversion installed?")
return 1
if os.path.exists(directory):
self.logger.error("ERROR: Checkout directory exists - %s" \
% directory)
return 1
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 len(self.all_versions):
metadata = self.pypi.release_data(self.project_name, \
self.all_versions[0])
self.logger.debug("DEBUG: browser: %s" % browser)
if metadata.has_key("home_page"):
self.logger.info("Launching browser: %s" \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
metadata = self.pypi.release_data(self.project_name, \
self.all_versions[0])
if metadata... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.project_name
if self.all_versions and self.version in self.all_versions:
print_pkg_versions(self.project_name, [self.version])
elif not self.version and self.all_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_entry_map)
if entry_map:
pprinter.pprint(entry_map)
except pkg_resources.DistributionNotFound:
self.logger.error("Distribution not found: %s" \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
plugin = entry_point.load()
print(plugin.__module__)
print(" %s" % entry_point)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
all_versions = []
arg_str = ("").join(self.pkg_spec)
if "==" not in arg_str:
#No version specified
project_name = arg_str
version = None
else:
(project_name, version) = arg_str.split("==")
project_name = project_name.strip()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
if api == USED_API:
raise ValueError
sys.meta_path.insert(0, ImportHookBackport(api)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ------- ImportErr... |
if api == USED_API:
raise ValueError
sys.meta_path.insert(0, ImportHookDeny(api)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
# Wait only max_timeout seconds.
if max_timeout:
start = time.time()
while pipe.poll() is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def iter( self, url: Union[str, methods], data: Optional[MutableMapping] = None, headers: Optional[MutableMapping] = None, *, limit: int = 200, iterkey: Opt... |
itervalue = None
if not data:
data = {}
last_request_time = None
while True:
current_time = time.time()
if (
minimum_time
and last_request_time
and last_request_time + minimum_time > current_time
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _incoming_from_rtm( self, url: str, bot_id: str ) -> AsyncIterator[events.Event]: """ Connect and discard incoming RTM event if necessary. :param url: W... |
async for data in self._rtm(url):
event = events.Event.from_rtm(json.loads(data))
if sansio.need_reconnect(event):
break
elif sansio.discard_event(event, bot_id):
continue
else:
yield event |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
#Installed by distutils/setuptools or external package manager?
#If location is in site-packages dir, check for .egg-info file
if dist.location.lower() == get_python_lib().lower():
filename = os.path.join(dist.location, dist.egg_name() + ".egg-info")
else:
filena... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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"):
url = url.split("#egg=")[0]
if pkg_type == "all":
return url
elif pkg_type == "source":
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_packages()
return
if not os.path.exists(self.yolk_dir):
os.mkdir(self.y... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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=ProxyTransport(), verbose=debug)
except IOError:
self.logger("ERROR: Can't connect to XML... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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()
#I have to set version=[] for edge cases like "Magic file extensions"
#but I'm not sure why this happens. It's ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def search(self, spec, operator):
'''Query PYPI via XMLRPC interface using search spec'''
return self.xmlrpc.search(spec, operator.lower()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 this be server bug?
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clone(self) -> "Event": """ Clone the event Returns: :class:`slack.events.Event` """ |
return self.__class__(copy.deepcopy(self.event), copy.deepcopy(self.metadata)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.eve... |
if raw_event["type"].startswith("message"):
return Message(raw_event)
else:
return Event(raw_event) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_http( cls, raw_body: MutableMapping, verification_token: Optional[str] = None, team_id: Optional[str] = None, ) -> "Event": """ Create an event with data... |
if verification_token and raw_body["token"] != verification_token:
raise exceptions.FailedVerification(raw_body["token"], raw_body["team_id"])
if team_id and raw_body["team_id"] != team_id:
raise exceptions.FailedVerification(raw_body["token"], raw_body["team_id"])
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def response(self, in_thread: Optional[bool] = None) -> "Message": """ Create a response message. Depending on the incoming message the response can be in a threa... |
data = {"channel": self["channel"]}
if in_thread:
if "message" in self:
data["thread_ts"] = (
self["message"].get("thread_ts") or self["message"]["ts"]
)
else:
data["thread_ts"] = self.get("thread_ts") or self[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query( # type: ignore self, url: Union[str, methods], data: Optional[MutableMapping] = None, headers: Optional[MutableMapping] = None, as_json: Optional[bool]... |
url, body, headers = sansio.prepare_request(
url=url,
data=data,
headers=headers,
global_headers=self._headers,
token=self._token,
)
return self._make_query(url, body, headers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: u... |
while True:
bot_id = bot_id or self._find_bot_id()
url = url or self._find_rtm_url()
for event in self._incoming_from_rtm(url, bot_id):
yield event
url = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(sys.stdin)
if not os.path.exists(config_file):
sys.stderr.w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: *... |
options = DEFAULT_OPTIONS.copy()
if config_options is not None:
options.update(config_options)
if local_options is not None:
options.update(local_options)
if cli_options is not None:
options.update(cli_options)
return options |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]
except AttributeError:
context['dimension'] = ''
for result in results:
stat_keys = metric['Statistics']
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_to_path(self, gsuri, localpath, binary_mode=False, tmpdir=None):
""" This method is analogous to "gsutil cp gsuri localpath", but in a programatical... |
bucket_name, gs_rel_path = self.parse_uri(gsuri)
# And now request the handles for bucket and the file
bucket = self._client.get_bucket(bucket_name)
# Just assignment, no downloading (yet)
ablob = bucket.get_blob(gs_rel_path)
if not ablob:
raise GoogleStorage... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.append(self.user.last_name)
return " ".join(formatted_user) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use_defaults(func):
""" Decorator for functions that should automatically fall back to the Cohort-default filter_fn and normalized_per_mb if not specified. "... |
@wraps(func)
def wrapper(row, cohort, filter_fn=None, normalized_per_mb=None, **kwargs):
filter_fn = first_not_none_param([filter_fn, cohort.filter_fn], no_filter)
normalized_per_mb = first_not_none_param([normalized_per_mb, cohort.normalized_per_mb], False)
return func(row=row,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_variants_function_builder(function_name, filterable_variant_function=None):
""" Creates a function that counts variants that are filtered by the provid... |
@count_function
def count(row, cohort, filter_fn, normalized_per_mb, **kwargs):
def count_filter_fn(filterable_variant, **kwargs):
assert filter_fn is not None, "filter_fn should never be None, but it is."
return ((filterable_variant_function(filterable_variant) if filterable_va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_effects_function_builder(function_name, only_nonsynonymous, filterable_effect_function=None):
""" Create a function that counts effects that are filter... |
@count_function
def count(row, cohort, filter_fn, normalized_per_mb, **kwargs):
def count_filter_fn(filterable_effect, **kwargs):
assert filter_fn is not None, "filter_fn should never be None, but it is."
return ((filterable_effect_function(filterable_effect) if filterable_effec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bootstrap_auc(df, col, pred_col, n_bootstrap=1000):
""" Calculate the boostrapped AUC for a given col trying to predict a pred_col. Parameters df : pandas.Da... |
scores = np.zeros(n_bootstrap)
old_len = len(df)
df.dropna(subset=[col], inplace=True)
new_len = len(df)
if new_len < old_len:
logger.info("Dropping NaN values in %s to go from %d to %d rows" % (col, old_len, new_len))
preds = df[pred_col].astype(int)
for i in range(n_bootstrap):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_worker(self, name: str):
"""Creates a new Worker and start a new Thread with it. Returns the Worker.""" |
if not self.running:
return self.immediate_worker
worker = self._new_worker(name)
self._start_worker(worker)
return worker |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_worker_pool(self, name: str, min_workers: int = 0, max_workers: int = 1, max_seconds_idle: int = DEFAULT_WORKER_POOL_MAX_SECONDS_IDLE):
""" Creates a new... |
if not self.running:
return self.immediate_worker
worker = self._new_worker_pool(name, min_workers, max_workers, max_seconds_idle)
self._start_worker_pool(worker)
return worker |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_dataframe(self, on=None, join_with=None, join_how=None, return_cols=False, rename_cols=False, keep_paren_contents=True, **kwargs):
""" Return this Cohort ... |
df = self._as_dataframe_unmodified(join_with=join_with, join_how=join_how)
if on is None:
return DataFrameHolder.return_obj(None, df, return_cols)
if type(on) == str:
return DataFrameHolder.return_obj(on, df, return_cols)
def apply_func(on, col, df):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_dataframe(self, df_loader_name):
""" Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes we may want to just directly load... |
logger.debug("loading dataframe: {}".format(df_loader_name))
# Get the DataFrameLoader object corresponding to this name.
df_loaders = [df_loader for df_loader in self.df_loaders if df_loader.name == df_loader_name]
if len(df_loaders) == 0:
raise ValueError("No DataFrameLoa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_function_name(self, fn, default="None"):
""" Return name of function, using default value if function not defined """ |
if fn is None:
fn_name = default
else:
fn_name = fn.__name__
return fn_name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_variants(self, patients=None, filter_fn=None, **kwargs):
"""Load a dictionary of patient_id to varcode.VariantCollection Parameters patients : str, opti... |
filter_fn = first_not_none_param([filter_fn, self.filter_fn], no_filter)
filter_fn_name = self._get_function_name(filter_fn)
logger.debug("loading variants with filter_fn: {}".format(filter_fn_name))
patient_variants = {}
for patient in self.iter_patients(patients):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _hash_filter_fn(self, filter_fn, **kwargs):
""" Construct string representing state of filter_fn Used to cache filtered variants or effects uniquely dependin... |
filter_fn_name = self._get_function_name(filter_fn, default="filter-none")
logger.debug("Computing hash for filter_fn: {} with kwargs {}".format(filter_fn_name, str(dict(**kwargs))))
# hash function source code
fn_source = str(dill.source.getsource(filter_fn))
pickled_fn_source ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_single_patient_variants(self, patient, filter_fn, use_cache=True, **kwargs):
""" Load filtered, merged variants for a single patient, optionally using ... |
if filter_fn is None:
use_filtered_cache = False
else:
filter_fn_name = self._get_function_name(filter_fn)
logger.debug("loading variants for patient {} with filter_fn {}".format(patient.id, filter_fn_name))
use_filtered_cache = use_cache
## conf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_single_patient_merged_variants(self, patient, use_cache=True):
""" Load merged variants for a single patient, optionally using cache Note that merged v... |
logger.debug("loading merged variants for patient {}".format(patient.id))
no_variants = False
try:
# get merged-variants from cache
if use_cache:
## load unfiltered variants into list of collections
variant_cache_file_name = "%s-variants.p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_polyphen_annotations(self, as_dataframe=False, filter_fn=None):
"""Load a dataframe containing polyphen2 annotations for all variants Parameters databas... |
filter_fn = first_not_none_param([filter_fn, self.filter_fn], no_filter)
patient_annotations = {}
for patient in self:
annotations = self._load_single_patient_polyphen(
patient,
filter_fn=filter_fn)
if annotations is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_effects(self, patients=None, only_nonsynonymous=False, all_effects=False, filter_fn=None, **kwargs):
"""Load a dictionary of patient_id to varcode.Effec... |
filter_fn = first_not_none_param([filter_fn, self.filter_fn], no_filter)
filter_fn_name = self._get_function_name(filter_fn)
logger.debug("loading effects with filter_fn {}".format(filter_fn_name))
patient_effects = {}
for patient in self.iter_patients(patients):
eff... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_kallisto(self):
""" Load Kallisto transcript quantification data for a cohort Parameters Returns ------- kallisto_data : Pandas dataframe Pandas datafra... |
kallisto_data = pd.concat(
[self._load_single_patient_kallisto(patient) for patient in self],
copy=False
)
if self.kallisto_ensembl_version is None:
raise ValueError("Required a kallisto_ensembl_version but none was specified")
ensembl_release = cac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_single_patient_kallisto(self, patient):
""" Load Kallisto gene quantification given a patient Parameters patient : Patient Returns ------- data: Pandas... |
data = pd.read_csv(patient.tumor_sample.kallisto_path, sep="\t")
data["patient_id"] = patient.id
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_cufflinks(self, filter_ok=True):
""" Load a Cufflinks gene expression data for a cohort Parameters filter_ok : bool, optional If true, filter Cufflinks ... |
return \
pd.concat(
[self._load_single_patient_cufflinks(patient, filter_ok) for patient in self],
copy=False
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_single_patient_cufflinks(self, patient, filter_ok):
""" Load Cufflinks gene quantification given a patient Parameters patient : Patient filter_ok : boo... |
data = pd.read_csv(patient.tumor_sample.cufflinks_path, sep="\t")
data["patient_id"] = patient.id
if filter_ok:
# Filter to OK FPKM counts
data = data[data["FPKM_status"] == "OK"]
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_filtered_isovar_epitopes(self, epitopes, ic50_cutoff):
""" Mostly replicates topiary.build_epitope_collection_from_binding_predictions Note: topiary need... |
mutant_binding_predictions = []
for binding_prediction in epitopes:
peptide = binding_prediction.peptide
peptide_offset = binding_prediction.offset
isovar_row = dict(binding_prediction.source_sequence_key)
is_mutant = contains_mutant_residues(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_roc_curve(self, on, bootstrap_samples=100, ax=None, **kwargs):
"""Plot an ROC curve for benefit and a given variable Parameters on : str or function or ... |
plot_col, df = self.as_dataframe(on, return_cols=True, **kwargs)
df = filter_not_null(df, "benefit")
df = filter_not_null(df, plot_col)
df.benefit = df.benefit.astype(bool)
return roc_curve_plot(df, plot_col, "benefit", bootstrap_samples, ax=ax) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_boolean(self, on, boolean_col, plot_col=None, boolean_label=None, boolean_value_map={}, order=None, ax=None, alternative="two-sided", **kwargs):
"""Plot... |
cols, df = self.as_dataframe(on, return_cols=True, **kwargs)
plot_col = self.plot_col_from_cols(cols=cols, plot_col=plot_col)
df = filter_not_null(df, boolean_col)
df = filter_not_null(df, plot_col)
if boolean_label:
df[boolean_label] = df[boolean_col]
b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_correlation(self, on, x_col=None, plot_type="jointplot", stat_func=pearsonr, show_stat_func=True, plot_kwargs={}, **kwargs):
"""Plot the correlation bet... |
if plot_type not in ["boxplot", "barplot", "jointplot", "regplot"]:
raise ValueError("Invalid plot_type %s" % plot_type)
plot_cols, df = self.as_dataframe(on, return_cols=True, **kwargs)
if len(plot_cols) != 2:
raise ValueError("Must be comparing two columns, but there a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.