sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
def get_asset_path(self, filename):
"""
Get the full system path of a given asset if it exists. Otherwise it throws
an error.
Args:
filename (str) - File name of a file in /assets folder to fetch the path for.
Returns:
str - path to the target file.
Raises:
AssetNotFoundError - if asset does not exist in the asset folder.
Usage::
path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png")
# path = /your/workspace/location/WTFProjectName/assets/my_asset.png
"""
if os.path.exists(os.path.join(self._asset_path, filename)):
return os.path.join(self._asset_path, filename)
else:
raise AssetNotFoundError(
u("Cannot find asset: {0}").format(filename)) | Get the full system path of a given asset if it exists. Otherwise it throws
an error.
Args:
filename (str) - File name of a file in /assets folder to fetch the path for.
Returns:
str - path to the target file.
Raises:
AssetNotFoundError - if asset does not exist in the asset folder.
Usage::
path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png")
# path = /your/workspace/location/WTFProjectName/assets/my_asset.png | entailment |
def create_webdriver(self, testname=None):
'''
Creates an instance of Selenium webdriver based on config settings.
This should only be called by a shutdown hook. Do not call directly within
a test.
Kwargs:
testname: Optional test name to pass, this gets appended to the test name
sent to selenium grid.
Returns:
WebDriver - Selenium Webdriver instance.
'''
try:
driver_type = self._config_reader.get(
self.DRIVER_TYPE_CONFIG)
except:
driver_type = self.DRIVER_TYPE_LOCAL
_wtflog.warn("%s setting is missing from config. Using default setting, %s",
self.DRIVER_TYPE_CONFIG, driver_type)
if driver_type == self.DRIVER_TYPE_REMOTE:
# Create desired capabilities.
self.webdriver = self.__create_remote_webdriver_from_config(
testname=testname)
else:
# handle as local webdriver
self.webdriver = self.__create_driver_from_browser_config()
try:
self.webdriver.maximize_window()
except:
# wait a short period and try again.
time.sleep(self._timeout_mgr.BRIEF)
try:
self.webdriver.maximize_window()
except Exception as e:
if (isinstance(e, WebDriverException) and
"implemented" in e.msg.lower()):
pass # Maximizing window not supported by this webdriver.
else:
_wtflog.warn("Unable to maxmize browser window. " +
"It may be possible the browser did not instantiate correctly. % s",
e)
return self.webdriver | Creates an instance of Selenium webdriver based on config settings.
This should only be called by a shutdown hook. Do not call directly within
a test.
Kwargs:
testname: Optional test name to pass, this gets appended to the test name
sent to selenium grid.
Returns:
WebDriver - Selenium Webdriver instance. | entailment |
def __create_driver_from_browser_config(self):
'''
Reads the config value for browser type.
'''
try:
browser_type = self._config_reader.get(
WebDriverFactory.BROWSER_TYPE_CONFIG)
except KeyError:
_wtflog("%s missing is missing from config file. Using defaults",
WebDriverFactory.BROWSER_TYPE_CONFIG)
browser_type = WebDriverFactory.FIREFOX
# Special Chrome Sauce
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"])
options.add_argument("always-authorize-plugins")
browser_type_dict = {
self.CHROME: lambda: webdriver.Chrome(
self._config_reader.get(WebDriverFactory.CHROME_DRIVER_PATH),
chrome_options=options),
self.FIREFOX: lambda: webdriver.Firefox(),
self.INTERNETEXPLORER: lambda: webdriver.Ie(),
self.OPERA: lambda: webdriver.Opera(),
self.PHANTOMJS: lambda: self.__create_phantom_js_driver(),
self.SAFARI: lambda: self.__create_safari_driver()
}
try:
return browser_type_dict[browser_type]()
except KeyError:
raise TypeError(
u("Unsupported Browser Type {0}").format(browser_type)) | Reads the config value for browser type. | entailment |
def __create_safari_driver(self):
'''
Creates an instance of Safari webdriver.
'''
# Check for selenium jar env file needed for safari driver.
if not os.getenv(self.__SELENIUM_SERVER_JAR_ENV):
# If not set, check if we have a config setting for it.
try:
selenium_server_path = self._config_reader.get(
self.SELENIUM_SERVER_LOCATION)
self._env_vars[
self.__SELENIUM_SERVER_JAR_ENV] = selenium_server_path
except KeyError:
raise RuntimeError(u("Missing selenium server path config {0}.").format(
self.SELENIUM_SERVER_LOCATION))
return webdriver.Safari() | Creates an instance of Safari webdriver. | entailment |
def __create_phantom_js_driver(self):
'''
Creates an instance of PhantomJS driver.
'''
try:
return webdriver.PhantomJS(executable_path=self._config_reader.get(self.PHANTOMEJS_EXEC_PATH),
service_args=['--ignore-ssl-errors=true'])
except KeyError:
return webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true']) | Creates an instance of PhantomJS driver. | entailment |
def __create_remote_webdriver_from_config(self, testname=None):
'''
Reads the config value for browser type.
'''
desired_capabilities = self._generate_desired_capabilities(testname)
remote_url = self._config_reader.get(
WebDriverFactory.REMOTE_URL_CONFIG)
# Instantiate remote webdriver.
driver = webdriver.Remote(
desired_capabilities=desired_capabilities,
command_executor=remote_url
)
# Log IP Address of node if configured, so it can be used to
# troubleshoot issues if they occur.
log_driver_props = \
self._config_reader.get(
WebDriverFactory.LOG_REMOTEDRIVER_PROPS, default_value=False
) in [True, "true", "TRUE", "True"]
if "wd/hub" in remote_url and log_driver_props:
try:
grid_addr = remote_url[:remote_url.index("wd/hub")]
info_request_response = urllib2.urlopen(
grid_addr + "grid/api/testsession?session=" + driver.session_id, "", 5000)
node_info = info_request_response.read()
_wtflog.info(
u("RemoteWebdriver using node: ") + u(node_info).strip())
except:
# Unable to get IP Address of remote webdriver.
# This happens with many 3rd party grid providers as they don't want you accessing info on nodes on
# their internal network.
pass
return driver | Reads the config value for browser type. | entailment |
def clean_up_webdrivers(self):
'''
Clean up webdrivers created during execution.
'''
# Quit webdrivers.
_wtflog.info("WebdriverManager: Cleaning up webdrivers")
try:
if self.__use_shutdown_hook:
for key in self.__registered_drivers.keys():
for driver in self.__registered_drivers[key]:
try:
_wtflog.debug(
"Shutdown hook closing Webdriver for thread: %s", key)
driver.quit()
except:
pass
except:
pass | Clean up webdrivers created during execution. | entailment |
def close_driver(self):
"""
Close current running instance of Webdriver.
Usage::
driver = WTF_WEBDRIVER_MANAGER.new_driver()
driver.get("http://the-internet.herokuapp.com")
WTF_WEBDRIVER_MANAGER.close_driver()
"""
channel = self.__get_channel()
driver = self.__get_driver_for_channel(channel)
if self.__config.get(self.REUSE_BROWSER, True):
# If reuse browser is set, we'll avoid closing it and just clear out the cookies,
# and reset the location.
try:
driver.delete_all_cookies()
# check to see if webdriver is still responding
driver.get("about:blank")
except:
pass
if driver is not None:
try:
driver.quit()
except:
pass
self.__unregister_driver(channel)
if driver in self.__registered_drivers[channel]:
self.__registered_drivers[channel].remove(driver)
self.webdriver = None | Close current running instance of Webdriver.
Usage::
driver = WTF_WEBDRIVER_MANAGER.new_driver()
driver.get("http://the-internet.herokuapp.com")
WTF_WEBDRIVER_MANAGER.close_driver() | entailment |
def get_driver(self):
'''
Get an already running instance of Webdriver. If there is none, it will create one.
Returns:
Webdriver - Selenium Webdriver instance.
Usage::
driver = WTF_WEBDRIVER_MANAGER.new_driver()
driver.get("http://the-internet.herokuapp.com")
same_driver = WTF_WEBDRIVER_MANAGER.get_driver()
print(driver is same_driver) # True
'''
driver = self.__get_driver_for_channel(self.__get_channel())
if driver is None:
driver = self.new_driver()
return driver | Get an already running instance of Webdriver. If there is none, it will create one.
Returns:
Webdriver - Selenium Webdriver instance.
Usage::
driver = WTF_WEBDRIVER_MANAGER.new_driver()
driver.get("http://the-internet.herokuapp.com")
same_driver = WTF_WEBDRIVER_MANAGER.get_driver()
print(driver is same_driver) # True | entailment |
def new_driver(self, testname=None):
'''
Used at a start of a test to get a new instance of WebDriver. If the
'resuebrowser' setting is true, it will use a recycled WebDriver instance
with delete_all_cookies() called.
Kwargs:
testname (str) - Optional test name to pass to Selenium Grid. Helpful for
labeling tests on 3rd party WebDriver cloud providers.
Returns:
Webdriver - Selenium Webdriver instance.
Usage::
driver = WTF_WEBDRIVER_MANAGER.new_driver()
driver.get("http://the-internet.herokuapp.com")
'''
channel = self.__get_channel()
# Get reference for the current driver.
driver = self.__get_driver_for_channel(channel)
if self.__config.get(WebDriverManager.REUSE_BROWSER, True):
if driver is None:
driver = self._webdriver_factory.create_webdriver(
testname=testname)
# Register webdriver so it can be retrieved by the manager and
# cleaned up after exit.
self.__register_driver(channel, driver)
else:
try:
# Attempt to get the browser to a pristine state as possible when we are
# reusing this for another test.
driver.delete_all_cookies()
# check to see if webdriver is still responding
driver.get("about:blank")
except:
# In the case the browser is unhealthy, we should kill it
# and serve a new one.
try:
if driver.is_online():
driver.quit()
except:
pass
driver = self._webdriver_factory.create_webdriver(
testname=testname)
self.__register_driver(channel, driver)
else:
# Attempt to tear down any existing webdriver.
if driver is not None:
try:
driver.quit()
except:
pass
self.__unregister_driver(channel)
driver = self._webdriver_factory.create_webdriver(
testname=testname)
self.__register_driver(channel, driver)
return driver | Used at a start of a test to get a new instance of WebDriver. If the
'resuebrowser' setting is true, it will use a recycled WebDriver instance
with delete_all_cookies() called.
Kwargs:
testname (str) - Optional test name to pass to Selenium Grid. Helpful for
labeling tests on 3rd party WebDriver cloud providers.
Returns:
Webdriver - Selenium Webdriver instance.
Usage::
driver = WTF_WEBDRIVER_MANAGER.new_driver()
driver.get("http://the-internet.herokuapp.com") | entailment |
def __register_driver(self, channel, webdriver):
"Register webdriver to a channel."
# Add to list of webdrivers to cleanup.
if not self.__registered_drivers.has_key(channel):
self.__registered_drivers[channel] = [] # set to new empty array
self.__registered_drivers[channel].append(webdriver)
# Set singleton instance for the channel
self.__webdriver[channel] = webdriver | Register webdriver to a channel. | entailment |
def __unregister_driver(self, channel):
"Unregister webdriver"
driver = self.__get_driver_for_channel(channel)
if self.__registered_drivers.has_key(channel) \
and driver in self.__registered_drivers[channel]:
self.__registered_drivers[channel].remove(driver)
self.__webdriver[channel] = None | Unregister webdriver | entailment |
def __get_channel(self):
"Get the channel to register webdriver to."
if self.__config.get(WebDriverManager.ENABLE_THREADING_SUPPORT, False):
channel = current_thread().ident
else:
channel = 0
return channel | Get the channel to register webdriver to. | entailment |
def take_screenshot(webdriver, file_name):
"""
Captures a screenshot.
Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as.
"""
folder_location = os.path.join(ProjectUtils.get_project_root(),
WebScreenShotUtil.SCREEN_SHOT_LOCATION)
WebScreenShotUtil.__capture_screenshot(
webdriver, folder_location, file_name + ".png") | Captures a screenshot.
Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as. | entailment |
def take_reference_screenshot(webdriver, file_name):
"""
Captures a screenshot as a reference screenshot.
Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as.
"""
folder_location = os.path.join(ProjectUtils.get_project_root(),
WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION)
WebScreenShotUtil.__capture_screenshot(
webdriver, folder_location, file_name + ".png") | Captures a screenshot as a reference screenshot.
Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as. | entailment |
def __capture_screenshot(webdriver, folder_location, file_name):
"Capture a screenshot"
# Check folder location exists.
if not os.path.exists(folder_location):
os.makedirs(folder_location)
file_location = os.path.join(folder_location, file_name)
if isinstance(webdriver, remote.webdriver.WebDriver):
# If this is a remote webdriver. We need to transmit the image data
# back across system boundries as a base 64 encoded string so it can
# be decoded back on the local system and written to disk.
base64_data = webdriver.get_screenshot_as_base64()
screenshot_data = base64.decodestring(base64_data)
screenshot_file = open(file_location, "wb")
screenshot_file.write(screenshot_data)
screenshot_file.close()
else:
webdriver.save_screenshot(file_location) | Capture a screenshot | entailment |
def get_project_root(cls):
'''
Return path of the project directory. Use this method for getting paths relative to the project.
However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended
to use WTF_ASSET_MANAGER, which are already singleton instances that manger the /data, and /assets
folder for you.
Returns:
str - path of project root directory.
'''
if(cls.__root_folder__ != None):
return cls.__root_folder__
# Check for enviornment variable override.
try:
cls.__root_folder__ = os.environ[cls.WTF_HOME_CONFIG_ENV_VAR]
except KeyError:
# Means WTF_HOME override isn't specified.
pass
# Search starting from the current working directory and traverse up parent directories for the
# hidden file denoting the project root folder.
path = os.getcwd()
seperator_matches = re.finditer("/|\\\\", path)
paths_to_search = [path]
for match in seperator_matches:
p = path[:match.start()]
paths_to_search.insert(0, p)
for path in paths_to_search:
target_path = os.path.join(path, cls.__WTF_ROOT_FOLDER_FILE)
if os.path.isfile(target_path):
cls.__root_folder__ = path
return cls.__root_folder__
raise RuntimeError(u("Missing root project folder locator file '.wtf_root_folder'.")
+ u("Check to make sure this file is located in your project directory.")) | Return path of the project directory. Use this method for getting paths relative to the project.
However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended
to use WTF_ASSET_MANAGER, which are already singleton instances that manger the /data, and /assets
folder for you.
Returns:
str - path of project root directory. | entailment |
def do_until(lambda_expr, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, message=None):
'''
A retry wrapper that'll keep performing the action until it succeeds.
(main differnce between do_until and wait_until is do_until will keep trying
until a value is returned, while wait until will wait until the function
evaluates True.)
Args:
lambda_expr (lambda) : Expression to evaluate.
Kwargs:
timeout (number): Timeout period in seconds.
sleep (number) : Sleep time to wait between iterations
message (str) : Provide a message for TimeoutError raised.
Returns:
The value of the evaluated lambda expression.
Usage::
do_until(lambda: driver.find_element_by_id("save").click(),
timeout=30,
sleep=0.5)
Is equivalent to:
end_time = datetime.now() + timedelta(seconds=30)
while datetime.now() < end_time:
try:
return driver.find_element_by_id("save").click()
except:
pass
time.sleep(0.5)
raise OperationTimeoutError()
'''
__check_condition_parameter_is_function(lambda_expr)
end_time = datetime.now() + timedelta(seconds=timeout)
last_exception = None
while datetime.now() < end_time:
try:
return lambda_expr()
except Exception as e:
last_exception = e
time.sleep(sleep)
if message:
raise OperationTimeoutError(message, last_exception)
else:
raise OperationTimeoutError("Operation timed out.", last_exception) | A retry wrapper that'll keep performing the action until it succeeds.
(main differnce between do_until and wait_until is do_until will keep trying
until a value is returned, while wait until will wait until the function
evaluates True.)
Args:
lambda_expr (lambda) : Expression to evaluate.
Kwargs:
timeout (number): Timeout period in seconds.
sleep (number) : Sleep time to wait between iterations
message (str) : Provide a message for TimeoutError raised.
Returns:
The value of the evaluated lambda expression.
Usage::
do_until(lambda: driver.find_element_by_id("save").click(),
timeout=30,
sleep=0.5)
Is equivalent to:
end_time = datetime.now() + timedelta(seconds=30)
while datetime.now() < end_time:
try:
return driver.find_element_by_id("save").click()
except:
pass
time.sleep(0.5)
raise OperationTimeoutError() | entailment |
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5):
'''
Waits wrapper that'll wait for the condition to become true, but will
not error if the condition isn't met.
Args:
condition (lambda) - Lambda expression to wait for to evaluate to True.
Kwargs:
timeout (number) : Maximum number of seconds to wait.
sleep (number) : Sleep time to wait between iterations.
Example::
wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(),
timeout=30,
sleep=0.5)
is equivalent to::
end_time = datetime.now() + timedelta(seconds=30)
while datetime.now() < end_time:
try:
if driver.find_element_by_id("success").is_displayed():
break;
except:
pass
time.sleep(0.5)
'''
try:
return wait_until(condition, timeout, sleep)
except:
pass | Waits wrapper that'll wait for the condition to become true, but will
not error if the condition isn't met.
Args:
condition (lambda) - Lambda expression to wait for to evaluate to True.
Kwargs:
timeout (number) : Maximum number of seconds to wait.
sleep (number) : Sleep time to wait between iterations.
Example::
wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(),
timeout=30,
sleep=0.5)
is equivalent to::
end_time = datetime.now() + timedelta(seconds=30)
while datetime.now() < end_time:
try:
if driver.find_element_by_id("success").is_displayed():
break;
except:
pass
time.sleep(0.5) | entailment |
def wait_until(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, pass_exceptions=False, message=None):
'''
Waits wrapper that'll wait for the condition to become true.
(main differnce between do_until and wait_until is do_until will keep trying
until a value is returned, while wait until will wait until the function
evaluates True.)
Args:
condition (lambda) - Lambda expression to wait for to evaluate to True.
Kwargs:
timeout (number) : Maximum number of seconds to wait.
sleep (number) : Sleep time to wait between iterations.
pass_exceptions (bool) : If set true, any exceptions raised will be re-raised up the chain.
Normally exceptions are ignored.
message (str) : Optional message to pass into OperationTimeoutError if the wait times out.
Example::
wait_until(lambda: driver.find_element_by_id("success").is_displayed(),
timeout=30,
sleep=0.5)
is equivalent to::
end_time = datetime.now() + timedelta(seconds=30)
did_succeed = False
while datetime.now() < end_time:
try:
if driver.find_element_by_id("success").is_displayed():
did_succeed = True
break;
except:
pass
time.sleep(0.5)
if not did_succeed:
raise OperationTimeoutError()
'''
__check_condition_parameter_is_function(condition)
last_exception = None
end_time = datetime.now() + timedelta(seconds=timeout)
while datetime.now() < end_time:
try:
if condition():
return
except Exception as e:
if pass_exceptions:
raise e
else:
last_exception = e
time.sleep(sleep)
if message:
if last_exception:
raise OperationTimeoutError(message, e)
else:
raise OperationTimeoutError(message)
else:
if last_exception:
raise OperationTimeoutError("Operation timed out.", e)
else:
raise OperationTimeoutError("Operation timed out.") | Waits wrapper that'll wait for the condition to become true.
(main differnce between do_until and wait_until is do_until will keep trying
until a value is returned, while wait until will wait until the function
evaluates True.)
Args:
condition (lambda) - Lambda expression to wait for to evaluate to True.
Kwargs:
timeout (number) : Maximum number of seconds to wait.
sleep (number) : Sleep time to wait between iterations.
pass_exceptions (bool) : If set true, any exceptions raised will be re-raised up the chain.
Normally exceptions are ignored.
message (str) : Optional message to pass into OperationTimeoutError if the wait times out.
Example::
wait_until(lambda: driver.find_element_by_id("success").is_displayed(),
timeout=30,
sleep=0.5)
is equivalent to::
end_time = datetime.now() + timedelta(seconds=30)
did_succeed = False
while datetime.now() < end_time:
try:
if driver.find_element_by_id("success").is_displayed():
did_succeed = True
break;
except:
pass
time.sleep(0.5)
if not did_succeed:
raise OperationTimeoutError() | entailment |
def check_email_exists_by_subject(self, subject, match_recipient=None):
"""
Searches for Email by Subject. Returns True or False.
Args:
subject (str): Subject to search for.
Kwargs:
match_recipient (str) : Recipient to match exactly. (don't care if not specified)
Returns:
True - email found, False - email not found
"""
# Select inbox to fetch the latest mail on server.
self._mail.select("inbox")
try:
matches = self.__search_email_by_subject(subject, match_recipient)
if len(matches) <= 0:
return False
else:
return True
except Exception as e:
raise e | Searches for Email by Subject. Returns True or False.
Args:
subject (str): Subject to search for.
Kwargs:
match_recipient (str) : Recipient to match exactly. (don't care if not specified)
Returns:
True - email found, False - email not found | entailment |
def find_emails_by_subject(self, subject, limit=50, match_recipient=None):
"""
Searches for Email by Subject. Returns email's imap message IDs
as a list if matching subjects is found.
Args:
subject (str) - Subject to search for.
Kwargs:
limit (int) - Limit search to X number of matches, default 50
match_recipient (str) - Recipient to exactly (don't care if not specified)
Returns:
list - List of Integers representing imap message UIDs.
"""
# Select inbox to fetch the latest mail on server.
self._mail.select("inbox")
matching_uids = self.__search_email_by_subject(
subject, match_recipient)
return matching_uids | Searches for Email by Subject. Returns email's imap message IDs
as a list if matching subjects is found.
Args:
subject (str) - Subject to search for.
Kwargs:
limit (int) - Limit search to X number of matches, default 50
match_recipient (str) - Recipient to exactly (don't care if not specified)
Returns:
list - List of Integers representing imap message UIDs. | entailment |
def get_email_message(self, message_uid, message_type="text/plain"):
"""
Fetch contents of email.
Args:
message_uid (int): IMAP Message UID number.
Kwargs:
message_type: Can be 'text' or 'html'
"""
self._mail.select("inbox")
result = self._mail.uid('fetch', message_uid, "(RFC822)")
msg = email.message_from_string(result[1][0][1])
try:
# Try to handle as multipart message first.
for part in msg.walk():
if part.get_content_type() == message_type:
return part.get_payload(decode=True)
except:
# handle as plain text email
return msg.get_payload(decode=True) | Fetch contents of email.
Args:
message_uid (int): IMAP Message UID number.
Kwargs:
message_type: Can be 'text' or 'html' | entailment |
def raw_search(self, *args, **kwargs):
"""
Find the a set of emails matching each regular expression passed in against the (RFC822) content.
Args:
*args: list of regular expressions.
Kwargs:
limit (int) - Limit to how many of the most resent emails to search through.
date (datetime) - If specified, it will filter avoid checking messages older
than this date.
"""
limit = 50
try:
limit = kwargs['limit']
except KeyError:
pass
# Get first X messages.
self._mail.select("inbox")
# apply date filter.
try:
date = kwargs['date']
date_str = date.strftime("%d-%b-%Y")
_, email_ids = self._mail.search(None, '(SINCE "%s")' % date_str)
except KeyError:
_, email_ids = self._mail.search(None, 'ALL')
# Above call returns email IDs as an array containing 1 str
email_ids = email_ids[0].split()
matching_uids = []
for _ in range(1, min(limit, len(email_ids))):
email_id = email_ids.pop()
rfc_body = self._mail.fetch(email_id, "(RFC822)")[1][0][1]
match = True
for expr in args:
if re.search(expr, rfc_body) is None:
match = False
break
if match:
uid = re.search(
"UID\\D*(\\d+)\\D*", self._mail.fetch(email_id, 'UID')[1][0]).group(1)
matching_uids.append(uid)
return matching_uids | Find the a set of emails matching each regular expression passed in against the (RFC822) content.
Args:
*args: list of regular expressions.
Kwargs:
limit (int) - Limit to how many of the most resent emails to search through.
date (datetime) - If specified, it will filter avoid checking messages older
than this date. | entailment |
def __search_email_by_subject(self, subject, match_recipient):
"Get a list of message numbers"
if match_recipient is None:
_, data = self._mail.uid('search',
None,
'(HEADER SUBJECT "{subject}")'
.format(subject=subject))
uid_list = data[0].split()
return uid_list
else:
_, data = self._mail.uid('search',
None,
'(HEADER SUBJECT "{subject}" TO "{recipient}")'
.format(subject=subject, recipient=match_recipient))
filtered_list = []
uid_list = data[0].split()
for uid in uid_list:
# Those hard coded indexes [1][0][1] is a hard reference to the message email message headers
# that's burried in all those wrapper objects that's associated
# with fetching a message.
to_addr = re.search(
"[^-]To: (.*)", self._mail.uid('fetch', uid, "(RFC822)")[1][0][1]).group(1).strip()
if (to_addr == match_recipient or to_addr == "<{0}>".format(match_recipient)):
# Add matching entry to the list.
filtered_list.append(uid)
return filtered_list | Get a list of message numbers | entailment |
def get(self, key, default_value=__NoDefaultSpecified__):
'''
Gets the value from the yaml config based on the key.
No type casting is performed, any type casting should be
performed by the caller.
Args:
key (str) - Config setting key.
Kwargs:
default_value - Default value to return if config is not specified.
Returns:
Returns value stored in config file.
'''
# First attempt to get the var from OS enviornment.
os_env_string = ConfigReader.ENV_PREFIX + key
os_env_string = os_env_string.replace(".", "_")
if type(os.getenv(os_env_string)) != NoneType:
return os.getenv(os_env_string)
# Otherwise search through config files.
for data_map in self._dataMaps:
try:
if "." in key:
# this is a multi levl string
namespaces = key.split(".")
temp_var = data_map
for name in namespaces:
temp_var = temp_var[name]
return temp_var
else:
value = data_map[key]
return value
except (AttributeError, TypeError, KeyError):
pass
if default_value == self.__NoDefaultSpecified__:
raise KeyError(u("Key '{0}' does not exist").format(key))
else:
return default_value | Gets the value from the yaml config based on the key.
No type casting is performed, any type casting should be
performed by the caller.
Args:
key (str) - Config setting key.
Kwargs:
default_value - Default value to return if config is not specified.
Returns:
Returns value stored in config file. | entailment |
def generate_page_object(page_name, url):
"Generate page object from URL"
# Attempt to extract partial URL for verification.
url_with_path = u('^.*//[^/]+([^?]+)?|$')
try:
match = re.match(url_with_path, url)
partial_url = match.group(1)
print("Using partial URL for location verification. ", partial_url)
except:
# use full url since we couldn't extract a partial.
partial_url = url
print("Could not find usable partial url, using full url.", url)
# Attempt to map input objects.
print("Processing page source...")
response = urllib2.urlopen(url)
html = response.read()
input_tags_expr = u('<\s*input[^>]*>')
input_tag_iter = re.finditer(input_tags_expr, html, re.IGNORECASE)
objectmap = ""
print("Creating object map for <input> tags...")
for input_tag_match in input_tag_iter:
if not "hidden" in input_tag_match.group(0):
try:
print("processing", input_tag_match.group(0))
obj_map_entry = _process_input_tag(input_tag_match.group(0))
objectmap += u(" ") + obj_map_entry + "\n"
except Exception as e:
print(e)
# we failed to process it, nothing more we can do.
pass
return _page_object_template_.contents.format(date=datetime.now(),
url=url,
pagename=page_name,
partialurl=partial_url,
objectmap=objectmap) | Generate page object from URL | entailment |
def get_data_path(self, filename, env_prefix=None):
"""
Get data path.
Args:
filename (string) : Name of file inside of /data folder to retrieve.
Kwargs:
env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa
Returns:
String - path to file.
Usage::
open(WTF_DATA_MANAGER.get_data_path('testdata.csv')
Note: WTF_DATA_MANAGER is a provided global instance of DataManager
"""
if env_prefix == None:
target_file = filename
else:
target_file = os.path.join(env_prefix, filename)
if os.path.exists(os.path.join(self._data_path, target_file)):
return os.path.join(self._data_path, target_file)
else:
raise DataNotFoundError(
u("Cannot find data file: {0}").format(target_file)) | Get data path.
Args:
filename (string) : Name of file inside of /data folder to retrieve.
Kwargs:
env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa
Returns:
String - path to file.
Usage::
open(WTF_DATA_MANAGER.get_data_path('testdata.csv')
Note: WTF_DATA_MANAGER is a provided global instance of DataManager | entailment |
def next(self):
"""
Gets next entry as a dictionary.
Returns:
object - Object key/value pair representing a row.
{key1: value1, key2: value2, ...}
"""
try:
entry = {}
row = self._csv_reader.next()
for i in range(0, len(row)):
entry[self._headers[i]] = row[i]
return entry
except Exception as e:
# close our file when we're done reading.
self._file.close()
raise e | Gets next entry as a dictionary.
Returns:
object - Object key/value pair representing a row.
{key1: value1, key2: value2, ...} | entailment |
def find_element_by_selectors(webdriver, *selectors):
"""
Utility method makes it easier to find an element using multiple selectors. This is
useful for problematic elements what might works with one browser, but fail in another.
(Like different page elements being served up for different browsers)
Args:
selectors - var arg if N number of selectors to match against. Each selector should
be a Selenium 'By' object.
Usage::
my_element = WebElementSelector.find_element_by_selectors(webdriver,
(By.ID, "MyElementID"),
(By.CSS, "MyClassSelector") )
"""
# perform initial check to verify selectors are valid by statements.
for selector in selectors:
(by_method, value) = selector
if not WebElementSelector.__is_valid_by_type(by_method):
raise BadSelectorError(
u("Selectors should be of type selenium.webdriver.common.by.By"))
if type(value) != str:
raise BadSelectorError(
u("Selectors should be of type selenium.webdriver.common.by.By"))
selectors_used = []
for selector in selectors:
(by_method, value) = selector
selectors_used.append(
u("{by}:{value}").format(by=by_method, value=value))
try:
return webdriver.find_element(by=by_method, value=value)
except:
pass
raise ElementNotSelectableException(
u("Unable to find elements using:") + u(",").join(selectors_used)) | Utility method makes it easier to find an element using multiple selectors. This is
useful for problematic elements what might works with one browser, but fail in another.
(Like different page elements being served up for different browsers)
Args:
selectors - var arg if N number of selectors to match against. Each selector should
be a Selenium 'By' object.
Usage::
my_element = WebElementSelector.find_element_by_selectors(webdriver,
(By.ID, "MyElementID"),
(By.CSS, "MyClassSelector") ) | entailment |
def wait_until_element_not_visible(webdriver, locator_lambda_expression,
timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5):
"""
Wait for a WebElement to disappear.
Args:
webdriver (Webdriver) - Selenium Webdriver
locator (lambda) - Locator lambda expression.
Kwargs:
timeout (number) - timeout period
sleep (number) - sleep period between intervals.
"""
# Wait for loading progress indicator to go away.
try:
stoptime = datetime.now() + timedelta(seconds=timeout)
while datetime.now() < stoptime:
element = WebDriverWait(webdriver, WTF_TIMEOUT_MANAGER.BRIEF).until(
locator_lambda_expression)
if element.is_displayed():
time.sleep(sleep)
else:
break
except TimeoutException:
pass | Wait for a WebElement to disappear.
Args:
webdriver (Webdriver) - Selenium Webdriver
locator (lambda) - Locator lambda expression.
Kwargs:
timeout (number) - timeout period
sleep (number) - sleep period between intervals. | entailment |
def is_image_loaded(webdriver, webelement):
'''
Check if an image (in an image tag) is loaded.
Note: This call will not work against background images. Only Images in <img> tags.
Args:
webelement (WebElement) - WebDriver web element to validate.
'''
script = (u("return arguments[0].complete && type of arguments[0].naturalWidth != \"undefined\" ") +
u("&& arguments[0].naturalWidth > 0"))
try:
return webdriver.execute_script(script, webelement)
except:
return False | Check if an image (in an image tag) is loaded.
Note: This call will not work against background images. Only Images in <img> tags.
Args:
webelement (WebElement) - WebDriver web element to validate. | entailment |
def generate_timestamped_string(subject="test", number_of_random_chars=4):
"""
Generate time-stamped string. Format as follows...
`2013-01-31_14:12:23_SubjectString_a3Zg`
Kwargs:
subject (str): String to use as subject.
number_of_random_chars (int) : Number of random characters to append.
This method is helpful for creating unique names with timestamps in them so
when you have to troubleshoot an issue, the name is easier to find.::
self.project_name = generate_timestamped_string("project")
new_project_page.create_project(project_name)
"""
random_str = generate_random_string(number_of_random_chars)
timestamp = generate_timestamp()
return u"{timestamp}_{subject}_{random_str}".format(timestamp=timestamp,
subject=subject,
random_str=random_str) | Generate time-stamped string. Format as follows...
`2013-01-31_14:12:23_SubjectString_a3Zg`
Kwargs:
subject (str): String to use as subject.
number_of_random_chars (int) : Number of random characters to append.
This method is helpful for creating unique names with timestamps in them so
when you have to troubleshoot an issue, the name is easier to find.::
self.project_name = generate_timestamped_string("project")
new_project_page.create_project(project_name) | entailment |
def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters):
"""
Generate a series of random characters.
Kwargs:
number_of_random_chars (int) : Number of characters long
character_set (str): Specify a character set. Default is ASCII
"""
return u('').join(random.choice(character_set)
for _ in range(number_of_random_chars)) | Generate a series of random characters.
Kwargs:
number_of_random_chars (int) : Number of characters long
character_set (str): Specify a character set. Default is ASCII | entailment |
def convert_weka_to_py_date_pattern(p):
"""
Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime().
"""
# https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
# https://www.cs.waikato.ac.nz/ml/weka/arff.html
p = p.replace('yyyy', r'%Y')
p = p.replace('MM', r'%m')
p = p.replace('dd', r'%d')
p = p.replace('HH', r'%H')
p = p.replace('mm', r'%M')
p = p.replace('ss', r'%S')
return p | Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime(). | entailment |
def get_attribute_value(self, name, index):
"""
Returns the value associated with the given value index
of the attribute with the given name.
This is only applicable for nominal and string types.
"""
if index == MISSING:
return
elif self.attribute_types[name] in NUMERIC_TYPES:
at = self.attribute_types[name]
if at == TYPE_INTEGER:
return int(index)
return Decimal(str(index))
else:
assert self.attribute_types[name] == TYPE_NOMINAL
cls_index, cls_value = index.split(':')
#return self.attribute_data[name][index-1]
if cls_value != MISSING:
assert cls_value in self.attribute_data[name], \
'Predicted value "%s" but only values %s are allowed.' \
% (cls_value, ', '.join(self.attribute_data[name]))
return cls_value | Returns the value associated with the given value index
of the attribute with the given name.
This is only applicable for nominal and string types. | entailment |
def load(cls, filename, schema_only=False):
"""
Load an ARFF File from a file.
"""
o = open(filename)
s = o.read()
a = cls.parse(s, schema_only=schema_only)
if not schema_only:
a._filename = filename
o.close()
return a | Load an ARFF File from a file. | entailment |
def parse(cls, s, schema_only=False):
"""
Parse an ARFF File already loaded into a string.
"""
a = cls()
a.state = 'comment'
a.lineno = 1
for l in s.splitlines():
a.parseline(l)
a.lineno += 1
if schema_only and a.state == 'data':
# Don't parse data if we're only loading the schema.
break
return a | Parse an ARFF File already loaded into a string. | entailment |
def copy(self, schema_only=False):
"""
Creates a deepcopy of the instance.
If schema_only is True, the data will be excluded from the copy.
"""
o = type(self)()
o.relation = self.relation
o.attributes = list(self.attributes)
o.attribute_types = self.attribute_types.copy()
o.attribute_data = self.attribute_data.copy()
if not schema_only:
o.comment = list(self.comment)
o.data = copy.deepcopy(self.data)
return o | Creates a deepcopy of the instance.
If schema_only is True, the data will be excluded from the copy. | entailment |
def open_stream(self, class_attr_name=None, fn=None):
"""
Save an arff structure to a file, leaving the file object
open for writing of new data samples.
This prevents you from directly accessing the data via Python,
but when generating a huge file, this prevents all your data
from being stored in memory.
"""
if fn:
self.fout_fn = fn
else:
fd, self.fout_fn = tempfile.mkstemp()
os.close(fd)
self.fout = open(self.fout_fn, 'w')
if class_attr_name:
self.class_attr_name = class_attr_name
self.write(fout=self.fout, schema_only=True)
self.write(fout=self.fout, data_only=True)
self.fout.flush() | Save an arff structure to a file, leaving the file object
open for writing of new data samples.
This prevents you from directly accessing the data via Python,
but when generating a huge file, this prevents all your data
from being stored in memory. | entailment |
def close_stream(self):
"""
Terminates an open stream and returns the filename
of the file containing the streamed data.
"""
if self.fout:
fout = self.fout
fout_fn = self.fout_fn
self.fout.flush()
self.fout.close()
self.fout = None
self.fout_fn = None
return fout_fn | Terminates an open stream and returns the filename
of the file containing the streamed data. | entailment |
def save(self, filename=None):
"""
Save an arff structure to a file.
"""
filename = filename or self._filename
o = open(filename, 'w')
o.write(self.write())
o.close() | Save an arff structure to a file. | entailment |
def write_line(self, d, fmt=SPARSE):
"""
Converts a single data line to a string.
"""
def smart_quote(s):
if isinstance(s, basestring) and ' ' in s and s[0] != '"':
s = '"%s"' % s
return s
if fmt == DENSE:
#TODO:fix
assert not isinstance(d, dict), NotImplemented
line = []
for e, a in zip(d, self.attributes):
at = self.attribute_types[a]
if at in NUMERIC_TYPES:
line.append(str(e))
elif at == TYPE_STRING:
line.append(self.esc(e))
elif at == TYPE_NOMINAL:
line.append(e)
else:
raise Exception("Type " + at + " not supported for writing!")
s = ','.join(map(str, line))
return s
elif fmt == SPARSE:
line = []
# Convert flat row into dictionary.
if isinstance(d, (list, tuple)):
d = dict(zip(self.attributes, d))
for k in d:
at = self.attribute_types.get(k)
if isinstance(d[k], Value):
continue
elif d[k] == MISSING:
d[k] = Str(d[k])
elif at in (TYPE_NUMERIC, TYPE_REAL):
d[k] = Num(d[k])
elif at == TYPE_STRING:
d[k] = Str(d[k])
elif at == TYPE_INTEGER:
d[k] = Int(d[k])
elif at == TYPE_NOMINAL:
d[k] = Nom(d[k])
elif at == TYPE_DATE:
d[k] = Date(d[k])
else:
raise Exception('Unknown type: %s' % at)
for i, name in enumerate(self.attributes):
v = d.get(name)
if v is None:
# print 'Skipping attribute with None value:', name
continue
elif v == MISSING or (isinstance(v, Value) and v.value == MISSING):
v = MISSING
elif isinstance(v, String):
v = '"%s"' % v.value
elif isinstance(v, Date):
date_format = self.attribute_data.get(name, DEFAULT_DATE_FORMAT)
date_format = convert_weka_to_py_date_pattern(date_format)
if isinstance(v.value, basestring):
_value = dateutil.parser.parse(v.value)
else:
assert isinstance(v.value, (date, datetime))
_value = v.value
v.value = v = _value.strftime(date_format)
elif isinstance(v, Value):
v = v.value
if v != MISSING and self.attribute_types[name] == TYPE_NOMINAL and str(v) not in map(str, self.attribute_data[name]):
pass
else:
line.append('%i %s' % (i, smart_quote(v)))
if len(line) == 1 and MISSING in line[-1]:
# Skip lines with nothing other than a missing class.
return
elif not line:
# Don't write blank lines.
return
return '{' + (', '.join(line)) + '}'
else:
raise Exception('Uknown format: %s' % (fmt,)) | Converts a single data line to a string. | entailment |
def write(self,
fout=None,
fmt=SPARSE,
schema_only=False,
data_only=False):
"""
Write an arff structure to a string.
"""
assert not (schema_only and data_only), 'Make up your mind.'
assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s' % (fmt, ', '.join(FORMATS))
close = False
if fout is None:
close = True
fout = StringIO()
if not data_only:
print('% ' + re.sub("\n", "\n% ", '\n'.join(self.comment)), file=fout)
print("@relation " + self.relation, file=fout)
self.write_attributes(fout=fout)
if not schema_only:
print("@data", file=fout)
for d in self.data:
line_str = self.write_line(d, fmt=fmt)
if line_str:
print(line_str, file=fout)
if isinstance(fout, StringIO) and close:
return fout.getvalue() | Write an arff structure to a string. | entailment |
def define_attribute(self, name, atype, data=None):
"""
Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'.
For nominal attributes, pass the possible values as data.
For date attributes, pass the format as data.
"""
self.attributes.append(name)
assert atype in TYPES, "Unknown type '%s'. Must be one of: %s" % (atype, ', '.join(TYPES),)
self.attribute_types[name] = atype
self.attribute_data[name] = data | Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'.
For nominal attributes, pass the possible values as data.
For date attributes, pass the format as data. | entailment |
def dump(self):
"""Print an overview of the ARFF file."""
print("Relation " + self.relation)
print(" With attributes")
for n in self.attributes:
if self.attribute_types[n] != TYPE_NOMINAL:
print(" %s of type %s" % (n, self.attribute_types[n]))
else:
print(" " + n + " of type nominal with values " + ', '.join(self.attribute_data[n]))
for d in self.data:
print(d) | Print an overview of the ARFF file. | entailment |
def alphabetize_attributes(self):
"""
Orders attributes names alphabetically, except for the class attribute, which is kept last.
"""
self.attributes.sort(key=lambda name: (name == self.class_attr_name, name)) | Orders attributes names alphabetically, except for the class attribute, which is kept last. | entailment |
def rgb_to_hsl(r, g=None, b=None):
"""Convert the color from RGB coordinates to HSL.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, l) tuple in the range:
h[0...360],
s[0...1],
l[0...1]
>>> rgb_to_hsl(1, 0.5, 0)
(30.0, 1.0, 0.5)
"""
if type(r) in [list,tuple]:
r, g, b = r
minVal = min(r, g, b) # min RGB value
maxVal = max(r, g, b) # max RGB value
l = (maxVal + minVal) / 2.0
if minVal==maxVal:
return (0.0, 0.0, l) # achromatic (gray)
d = maxVal - minVal # delta RGB value
if l < 0.5: s = d / (maxVal + minVal)
else: s = d / (2.0 - maxVal - minVal)
dr, dg, db = [(maxVal-val) / d for val in (r, g, b)]
if r==maxVal:
h = db - dg
elif g==maxVal:
h = 2.0 + dr - db
else:
h = 4.0 + dg - dr
h = (h*60.0) % 360.0
return (h, s, l) | Convert the color from RGB coordinates to HSL.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, l) tuple in the range:
h[0...360],
s[0...1],
l[0...1]
>>> rgb_to_hsl(1, 0.5, 0)
(30.0, 1.0, 0.5) | entailment |
def hsl_to_rgb(h, s=None, l=None):
"""Convert the color from HSL coordinates to RGB.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> hsl_to_rgb(30.0, 1.0, 0.5)
(1.0, 0.5, 0.0)
"""
if type(h) in [list,tuple]:
h, s, l = h
if s==0: return (l, l, l) # achromatic (gray)
if l<0.5: n2 = l * (1.0 + s)
else: n2 = l+s - (l*s)
n1 = (2.0 * l) - n2
h /= 60.0
hueToRgb = _hue_to_rgb
r = hueToRgb(n1, n2, h + 2)
g = hueToRgb(n1, n2, h)
b = hueToRgb(n1, n2, h - 2)
return (r, g, b) | Convert the color from HSL coordinates to RGB.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> hsl_to_rgb(30.0, 1.0, 0.5)
(1.0, 0.5, 0.0) | entailment |
def rgb_to_hsv(r, g=None, b=None):
"""Convert the color from RGB coordinates to HSV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, v) tuple in the range:
h[0...360],
s[0...1],
v[0...1]
>>> rgb_to_hsv(1, 0.5, 0)
(30.0, 1.0, 1.0)
"""
if type(r) in [list,tuple]:
r, g, b = r
v = float(max(r, g, b))
d = v - min(r, g, b)
if d==0: return (0.0, 0.0, v)
s = d / v
dr, dg, db = [(v - val) / d for val in (r, g, b)]
if r==v:
h = db - dg # between yellow & magenta
elif g==v:
h = 2.0 + dr - db # between cyan & yellow
else: # b==v
h = 4.0 + dg - dr # between magenta & cyan
h = (h*60.0) % 360.0
return (h, s, v) | Convert the color from RGB coordinates to HSV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, v) tuple in the range:
h[0...360],
s[0...1],
v[0...1]
>>> rgb_to_hsv(1, 0.5, 0)
(30.0, 1.0, 1.0) | entailment |
def hsv_to_rgb(h, s=None, v=None):
"""Convert the color from RGB coordinates to HSV.
Parameters:
:h:
The Hus component value [0...1]
:s:
The Saturation component value [0...1]
:v:
The Value component [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> hsv_to_rgb(30.0, 1.0, 0.5)
(0.5, 0.25, 0.0)
"""
if type(h) in [list,tuple]:
h, s, v = h
if s==0: return (v, v, v) # achromatic (gray)
h /= 60.0
h = h % 6.0
i = int(h)
f = h - i
if not(i&1): f = 1-f # if i is even
m = v * (1.0 - s)
n = v * (1.0 - (s * f))
if i==0: return (v, n, m)
if i==1: return (n, v, m)
if i==2: return (m, v, n)
if i==3: return (m, n, v)
if i==4: return (n, m, v)
return (v, m, n) | Convert the color from RGB coordinates to HSV.
Parameters:
:h:
The Hus component value [0...1]
:s:
The Saturation component value [0...1]
:v:
The Value component [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> hsv_to_rgb(30.0, 1.0, 0.5)
(0.5, 0.25, 0.0) | entailment |
def rgb_to_yiq(r, g=None, b=None):
"""Convert the color from RGB to YIQ.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, i, q) tuple in the range:
y[0...1],
i[0...1],
q[0...1]
>>> '(%g, %g, %g)' % rgb_to_yiq(1, 0.5, 0)
'(0.592263, 0.458874, -0.0499818)'
"""
if type(r) in [list,tuple]:
r, g, b = r
y = (r * 0.29895808) + (g * 0.58660979) + (b *0.11443213)
i = (r * 0.59590296) - (g * 0.27405705) - (b *0.32184591)
q = (r * 0.21133576) - (g * 0.52263517) + (b *0.31129940)
return (y, i, q) | Convert the color from RGB to YIQ.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, i, q) tuple in the range:
y[0...1],
i[0...1],
q[0...1]
>>> '(%g, %g, %g)' % rgb_to_yiq(1, 0.5, 0)
'(0.592263, 0.458874, -0.0499818)' | entailment |
def yiq_to_rgb(y, i=None, q=None):
"""Convert the color from YIQ coordinates to RGB.
Parameters:
:y:
Tte Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> '({}, {}, {})'.format(*[round(v, 6) for v in yiq_to_rgb(0.592263, 0.458874, -0.0499818)])
'(1.0, 0.5, 1e-06)'
"""
if type(y) in [list,tuple]:
y, i, q = y
r = y + (i * 0.9562) + (q * 0.6210)
g = y - (i * 0.2717) - (q * 0.6485)
b = y - (i * 1.1053) + (q * 1.7020)
return (r, g, b) | Convert the color from YIQ coordinates to RGB.
Parameters:
:y:
Tte Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> '({}, {}, {})'.format(*[round(v, 6) for v in yiq_to_rgb(0.592263, 0.458874, -0.0499818)])
'(1.0, 0.5, 1e-06)' | entailment |
def rgb_to_yuv(r, g=None, b=None):
"""Convert the color from RGB coordinates to YUV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, u, v) tuple in the range:
y[0...1],
u[-0.436...0.436],
v[-0.615...0.615]
>>> '(%g, %g, %g)' % rgb_to_yuv(1, 0.5, 0)
'(0.5925, -0.29156, 0.357505)'
"""
if type(r) in [list,tuple]:
r, g, b = r
y = (r * 0.29900) + (g * 0.58700) + (b * 0.11400)
u = -(r * 0.14713) - (g * 0.28886) + (b * 0.43600)
v = (r * 0.61500) - (g * 0.51499) - (b * 0.10001)
return (y, u, v) | Convert the color from RGB coordinates to YUV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, u, v) tuple in the range:
y[0...1],
u[-0.436...0.436],
v[-0.615...0.615]
>>> '(%g, %g, %g)' % rgb_to_yuv(1, 0.5, 0)
'(0.5925, -0.29156, 0.357505)' | entailment |
def yuv_to_rgb(y, u=None, v=None):
"""Convert the color from YUV coordinates to RGB.
Parameters:
:y:
The Y component value [0...1]
:u:
The U component value [-0.436...0.436]
:v:
The V component value [-0.615...0.615]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % yuv_to_rgb(0.5925, -0.2916, 0.3575)
'(0.999989, 0.500015, -6.3276e-05)'
"""
if type(y) in [list,tuple]:
y, u, v = y
r = y + (v * 1.13983)
g = y - (u * 0.39465) - (v * 0.58060)
b = y + (u * 2.03211)
return (r, g, b) | Convert the color from YUV coordinates to RGB.
Parameters:
:y:
The Y component value [0...1]
:u:
The U component value [-0.436...0.436]
:v:
The V component value [-0.615...0.615]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % yuv_to_rgb(0.5925, -0.2916, 0.3575)
'(0.999989, 0.500015, -6.3276e-05)' | entailment |
def rgb_to_xyz(r, g=None, b=None):
"""Convert the color from sRGB to CIE XYZ.
The methods assumes that the RGB coordinates are given in the sRGB
colorspace (D65).
.. note::
Compensation for the sRGB gamma correction is applied before converting.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (x, y, z) tuple in the range:
x[0...1],
y[0...1],
z[0...1]
>>> '(%g, %g, %g)' % rgb_to_xyz(1, 0.5, 0)
'(0.488941, 0.365682, 0.0448137)'
"""
if type(r) in [list,tuple]:
r, g, b = r
r, g, b = [((v <= 0.03928) and [v / 12.92] or [((v+0.055) / 1.055) **2.4])[0] for v in (r, g, b)]
x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805)
y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722)
z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505)
return (x, y, z) | Convert the color from sRGB to CIE XYZ.
The methods assumes that the RGB coordinates are given in the sRGB
colorspace (D65).
.. note::
Compensation for the sRGB gamma correction is applied before converting.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (x, y, z) tuple in the range:
x[0...1],
y[0...1],
z[0...1]
>>> '(%g, %g, %g)' % rgb_to_xyz(1, 0.5, 0)
'(0.488941, 0.365682, 0.0448137)' | entailment |
def xyz_to_rgb(x, y=None, z=None):
"""Convert the color from CIE XYZ coordinates to sRGB.
.. note::
Compensation for sRGB gamma correction is applied before converting.
Parameters:
:x:
The X component value [0...1]
:y:
The Y component value [0...1]
:z:
The Z component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % xyz_to_rgb(0.488941, 0.365682, 0.0448137)
'(1, 0.5, 6.81883e-08)'
"""
if type(x) in [list,tuple]:
x, y, z = x
r = (x * 3.2406255) - (y * 1.5372080) - (z * 0.4986286)
g = -(x * 0.9689307) + (y * 1.8757561) + (z * 0.0415175)
b = (x * 0.0557101) - (y * 0.2040211) + (z * 1.0569959)
return tuple((((v <= _srgbGammaCorrInv) and [v * 12.92] or [(1.055 * (v ** (1/2.4))) - 0.055])[0] for v in (r, g, b))) | Convert the color from CIE XYZ coordinates to sRGB.
.. note::
Compensation for sRGB gamma correction is applied before converting.
Parameters:
:x:
The X component value [0...1]
:y:
The Y component value [0...1]
:z:
The Z component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % xyz_to_rgb(0.488941, 0.365682, 0.0448137)
'(1, 0.5, 6.81883e-08)' | entailment |
def xyz_to_lab(x, y=None, z=None, wref=_DEFAULT_WREF):
"""Convert the color from CIE XYZ to CIE L*a*b*.
Parameters:
:x:
The X component value [0...1]
:y:
The Y component value [0...1]
:z:
The Z component value [0...1]
:wref:
The whitepoint reference, default is 2° D65.
Returns:
The color as an (L, a, b) tuple in the range:
L[0...100],
a[-1...1],
b[-1...1]
>>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137)
'(66.9518, 0.430841, 0.739692)'
>>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137, WHITE_REFERENCE['std_D50'])
'(66.9518, 0.41166, 0.67282)'
"""
if type(x) in [list,tuple]:
x, y, z = x
# White point correction
x /= wref[0]
y /= wref[1]
z /= wref[2]
# Nonlinear distortion and linear transformation
x, y, z = [((v > 0.008856) and [v**_oneThird] or [(7.787 * v) + _sixteenHundredsixteenth])[0] for v in (x, y, z)]
# Vector scaling
l = (116 * y) - 16
a = 5.0 * (x - y)
b = 2.0 * (y - z)
return (l, a, b) | Convert the color from CIE XYZ to CIE L*a*b*.
Parameters:
:x:
The X component value [0...1]
:y:
The Y component value [0...1]
:z:
The Z component value [0...1]
:wref:
The whitepoint reference, default is 2° D65.
Returns:
The color as an (L, a, b) tuple in the range:
L[0...100],
a[-1...1],
b[-1...1]
>>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137)
'(66.9518, 0.430841, 0.739692)'
>>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137, WHITE_REFERENCE['std_D50'])
'(66.9518, 0.41166, 0.67282)' | entailment |
def lab_to_xyz(l, a=None, b=None, wref=_DEFAULT_WREF):
"""Convert the color from CIE L*a*b* to CIE 1931 XYZ.
Parameters:
:l:
The L component [0...100]
:a:
The a component [-1...1]
:b:
The a component [-1...1]
:wref:
The whitepoint reference, default is 2° D65.
Returns:
The color as an (x, y, z) tuple in the range:
x[0...q],
y[0...1],
z[0...1]
>>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.43084, 0.739692)
'(0.48894, 0.365682, 0.0448137)'
>>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.411663, 0.67282, WHITE_REFERENCE['std_D50'])
'(0.488942, 0.365682, 0.0448137)'
"""
if type(l) in [list,tuple]:
l, a, b = l
y = (l + 16) / 116
x = (a / 5.0) + y
z = y - (b / 2.0)
return tuple((((v > 0.206893) and [v**3] or [(v - _sixteenHundredsixteenth) / 7.787])[0] * w for v, w in zip((x, y, z), wref))) | Convert the color from CIE L*a*b* to CIE 1931 XYZ.
Parameters:
:l:
The L component [0...100]
:a:
The a component [-1...1]
:b:
The a component [-1...1]
:wref:
The whitepoint reference, default is 2° D65.
Returns:
The color as an (x, y, z) tuple in the range:
x[0...q],
y[0...1],
z[0...1]
>>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.43084, 0.739692)
'(0.48894, 0.365682, 0.0448137)'
>>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.411663, 0.67282, WHITE_REFERENCE['std_D50'])
'(0.488942, 0.365682, 0.0448137)' | entailment |
def cmyk_to_cmy(c, m=None, y=None, k=None):
"""Convert the color from CMYK coordinates to CMY.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:k:
The Black component value [0...1]
Returns:
The color as an (c, m, y) tuple in the range:
c[0...1],
m[0...1],
y[0...1]
>>> '(%g, %g, %g)' % cmyk_to_cmy(1, 0.32, 0, 0.5)
'(1, 0.66, 0.5)'
"""
if type(c) in [list,tuple]:
c, m, y, k = c
mk = 1-k
return ((c*mk + k), (m*mk + k), (y*mk + k)) | Convert the color from CMYK coordinates to CMY.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:k:
The Black component value [0...1]
Returns:
The color as an (c, m, y) tuple in the range:
c[0...1],
m[0...1],
y[0...1]
>>> '(%g, %g, %g)' % cmyk_to_cmy(1, 0.32, 0, 0.5)
'(1, 0.66, 0.5)' | entailment |
def cmy_to_cmyk(c, m=None, y=None):
"""Convert the color from CMY coordinates to CMYK.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
Returns:
The color as an (c, m, y, k) tuple in the range:
c[0...1],
m[0...1],
y[0...1],
k[0...1]
>>> '(%g, %g, %g, %g)' % cmy_to_cmyk(1, 0.66, 0.5)
'(1, 0.32, 0, 0.5)'
"""
if type(c) in [list,tuple]:
c, m, y = c
k = min(c, m, y)
if k==1.0: return (0.0, 0.0, 0.0, 1.0)
mk = 1.0-k
return ((c-k) / mk, (m-k) / mk, (y-k) / mk, k) | Convert the color from CMY coordinates to CMYK.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
Returns:
The color as an (c, m, y, k) tuple in the range:
c[0...1],
m[0...1],
y[0...1],
k[0...1]
>>> '(%g, %g, %g, %g)' % cmy_to_cmyk(1, 0.66, 0.5)
'(1, 0.32, 0, 0.5)' | entailment |
def rgb_to_cmy(r, g=None, b=None):
"""Convert the color from RGB coordinates to CMY.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (c, m, y) tuple in the range:
c[0...1],
m[0...1],
y[0...1]
>>> rgb_to_cmy(1, 0.5, 0)
(0, 0.5, 1)
"""
if type(r) in [list,tuple]:
r, g, b = r
return (1-r, 1-g, 1-b) | Convert the color from RGB coordinates to CMY.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (c, m, y) tuple in the range:
c[0...1],
m[0...1],
y[0...1]
>>> rgb_to_cmy(1, 0.5, 0)
(0, 0.5, 1) | entailment |
def cmy_to_rgb(c, m=None, y=None):
"""Convert the color from CMY coordinates to RGB.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> cmy_to_rgb(0, 0.5, 1)
(1, 0.5, 0)
"""
if type(c) in [list,tuple]:
c, m, y = c
return (1-c, 1-m, 1-y) | Convert the color from CMY coordinates to RGB.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> cmy_to_rgb(0, 0.5, 1)
(1, 0.5, 0) | entailment |
def rgb_to_ints(r, g=None, b=None):
"""Convert the color in the standard [0...1] range to ints in the [0..255] range.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...255],
g[0...2551],
b[0...2551]
>>> rgb_to_ints(1, 0.5, 0)
(255, 128, 0)
"""
if type(r) in [list,tuple]:
r, g, b = r
return tuple(int(round(v*255)) for v in (r, g, b)) | Convert the color in the standard [0...1] range to ints in the [0..255] range.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...255],
g[0...2551],
b[0...2551]
>>> rgb_to_ints(1, 0.5, 0)
(255, 128, 0) | entailment |
def ints_to_rgb(r, g=None, b=None):
"""Convert ints in the [0...255] range to the standard [0...1] range.
Parameters:
:r:
The Red component value [0...255]
:g:
The Green component value [0...255]
:b:
The Blue component value [0...255]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % ints_to_rgb((255, 128, 0))
'(1, 0.501961, 0)'
"""
if type(r) in [list,tuple]:
r, g, b = r
return tuple(float(v) / 255.0 for v in [r, g, b]) | Convert ints in the [0...255] range to the standard [0...1] range.
Parameters:
:r:
The Red component value [0...255]
:g:
The Green component value [0...255]
:b:
The Blue component value [0...255]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % ints_to_rgb((255, 128, 0))
'(1, 0.501961, 0)' | entailment |
def rgb_to_html(r, g=None, b=None):
"""Convert the color from (r, g, b) to #RRGGBB.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A CSS string representation of this color (#RRGGBB).
>>> rgb_to_html(1, 0.5, 0)
'#ff8000'
"""
if type(r) in [list,tuple]:
r, g, b = r
return '#%02x%02x%02x' % tuple((min(round(v*255), 255) for v in (r, g, b))) | Convert the color from (r, g, b) to #RRGGBB.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A CSS string representation of this color (#RRGGBB).
>>> rgb_to_html(1, 0.5, 0)
'#ff8000' | entailment |
def html_to_rgb(html):
"""Convert the HTML color to (r, g, b).
Parameters:
:html:
the HTML definition of the color (#RRGGBB or #RGB or a color name).
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
Throws:
:ValueError:
If html is neither a known color name or a hexadecimal RGB
representation.
>>> '(%g, %g, %g)' % html_to_rgb('#ff8000')
'(1, 0.501961, 0)'
>>> '(%g, %g, %g)' % html_to_rgb('ff8000')
'(1, 0.501961, 0)'
>>> '(%g, %g, %g)' % html_to_rgb('#f60')
'(1, 0.4, 0)'
>>> '(%g, %g, %g)' % html_to_rgb('f60')
'(1, 0.4, 0)'
>>> '(%g, %g, %g)' % html_to_rgb('lemonchiffon')
'(1, 0.980392, 0.803922)'
"""
html = html.strip().lower()
if html[0]=='#':
html = html[1:]
elif html in NAMED_COLOR:
html = NAMED_COLOR[html][1:]
if len(html)==6:
rgb = html[:2], html[2:4], html[4:]
elif len(html)==3:
rgb = ['%c%c' % (v,v) for v in html]
else:
raise ValueError("input #%s is not in #RRGGBB format" % html)
return tuple(((int(n, 16) / 255.0) for n in rgb)) | Convert the HTML color to (r, g, b).
Parameters:
:html:
the HTML definition of the color (#RRGGBB or #RGB or a color name).
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
Throws:
:ValueError:
If html is neither a known color name or a hexadecimal RGB
representation.
>>> '(%g, %g, %g)' % html_to_rgb('#ff8000')
'(1, 0.501961, 0)'
>>> '(%g, %g, %g)' % html_to_rgb('ff8000')
'(1, 0.501961, 0)'
>>> '(%g, %g, %g)' % html_to_rgb('#f60')
'(1, 0.4, 0)'
>>> '(%g, %g, %g)' % html_to_rgb('f60')
'(1, 0.4, 0)'
>>> '(%g, %g, %g)' % html_to_rgb('lemonchiffon')
'(1, 0.980392, 0.803922)' | entailment |
def rgb_to_pil(r, g=None, b=None):
"""Convert the color from RGB to a PIL-compatible integer.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A PIL compatible integer (0xBBGGRR).
>>> '0x%06x' % rgb_to_pil(1, 0.5, 0)
'0x0080ff'
"""
if type(r) in [list,tuple]:
r, g, b = r
r, g, b = [min(int(round(v*255)), 255) for v in (r, g, b)]
return (b << 16) + (g << 8) + r | Convert the color from RGB to a PIL-compatible integer.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A PIL compatible integer (0xBBGGRR).
>>> '0x%06x' % rgb_to_pil(1, 0.5, 0)
'0x0080ff' | entailment |
def pil_to_rgb(pil):
"""Convert the color from a PIL-compatible integer to RGB.
Parameters:
pil: a PIL compatible color representation (0xBBGGRR)
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r: [0...1]
g: [0...1]
b: [0...1]
>>> '(%g, %g, %g)' % pil_to_rgb(0x0080ff)
'(1, 0.501961, 0)'
"""
r = 0xff & pil
g = 0xff & (pil >> 8)
b = 0xff & (pil >> 16)
return tuple((v / 255.0 for v in (r, g, b))) | Convert the color from a PIL-compatible integer to RGB.
Parameters:
pil: a PIL compatible color representation (0xBBGGRR)
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r: [0...1]
g: [0...1]
b: [0...1]
>>> '(%g, %g, %g)' % pil_to_rgb(0x0080ff)
'(1, 0.501961, 0)' | entailment |
def _websafe_component(c, alt=False):
"""Convert a color component to its web safe equivalent.
Parameters:
:c:
The component value [0...1]
:alt:
If True, return the alternative value instead of the nearest one.
Returns:
The web safe equivalent of the component value.
"""
# This sucks, but floating point between 0 and 1 is quite fuzzy...
# So we just change the scale a while to make the equality tests
# work, otherwise it gets wrong at some decimal far to the right.
sc = c * 100.0
# If the color is already safe, return it straight away
d = sc % 20
if d==0: return c
# Get the lower and upper safe values
l = sc - d
u = l + 20
# Return the 'closest' value according to the alt flag
if alt:
if (sc-l) >= (u-sc): return l/100.0
else: return u/100.0
else:
if (sc-l) >= (u-sc): return u/100.0
else: return l/100.0 | Convert a color component to its web safe equivalent.
Parameters:
:c:
The component value [0...1]
:alt:
If True, return the alternative value instead of the nearest one.
Returns:
The web safe equivalent of the component value. | entailment |
def rgb_to_websafe(r, g=None, b=None, alt=False):
"""Convert the color from RGB to 'web safe' RGB
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alt:
If True, use the alternative color instead of the nearest one.
Can be used for dithering.
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % rgb_to_websafe(1, 0.55, 0.0)
'(1, 0.6, 0)'
"""
if type(r) in [list,tuple]:
r, g, b = r
websafeComponent = _websafe_component
return tuple((websafeComponent(v, alt) for v in (r, g, b))) | Convert the color from RGB to 'web safe' RGB
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alt:
If True, use the alternative color instead of the nearest one.
Can be used for dithering.
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % rgb_to_websafe(1, 0.55, 0.0)
'(1, 0.6, 0)' | entailment |
def rgb_to_greyscale(r, g=None, b=None):
"""Convert the color from RGB to its greyscale equivalent
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % rgb_to_greyscale(1, 0.8, 0)
'(0.6, 0.6, 0.6)'
"""
if type(r) in [list,tuple]:
r, g, b = r
v = (r + g + b) / 3.0
return (v, v, v) | Convert the color from RGB to its greyscale equivalent
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r[0...1],
g[0...1],
b[0...1]
>>> '(%g, %g, %g)' % rgb_to_greyscale(1, 0.8, 0)
'(0.6, 0.6, 0.6)' | entailment |
def rgb_to_ryb(hue):
"""Maps a hue on the RGB color wheel to Itten's RYB wheel.
Parameters:
:hue:
The hue on the RGB color wheel [0...360]
Returns:
An approximation of the corresponding hue on Itten's RYB wheel.
>>> rgb_to_ryb(15)
26.0
"""
d = hue % 15
i = int(hue / 15)
x0 = _RybWheel[i]
x1 = _RybWheel[i+1]
return x0 + (x1-x0) * d / 15 | Maps a hue on the RGB color wheel to Itten's RYB wheel.
Parameters:
:hue:
The hue on the RGB color wheel [0...360]
Returns:
An approximation of the corresponding hue on Itten's RYB wheel.
>>> rgb_to_ryb(15)
26.0 | entailment |
def ryb_to_rgb(hue):
"""Maps a hue on Itten's RYB color wheel to the standard RGB wheel.
Parameters:
:hue:
The hue on Itten's RYB color wheel [0...360]
Returns:
An approximation of the corresponding hue on the standard RGB wheel.
>>> ryb_to_rgb(15)
8.0
"""
d = hue % 15
i = int(hue / 15)
x0 = _RgbWheel[i]
x1 = _RgbWheel[i+1]
return x0 + (x1-x0) * d / 15 | Maps a hue on Itten's RYB color wheel to the standard RGB wheel.
Parameters:
:hue:
The hue on Itten's RYB color wheel [0...360]
Returns:
An approximation of the corresponding hue on the standard RGB wheel.
>>> ryb_to_rgb(15)
8.0 | entailment |
def from_rgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed RGB values.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_rgb(1.0, 0.5, 0.0)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_rgb(1.0, 0.5, 0.0, 0.5)
Color(1.0, 0.5, 0.0, 0.5)
"""
return Color((r, g, b), 'rgb', alpha, wref) | Create a new instance based on the specifed RGB values.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_rgb(1.0, 0.5, 0.0)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_rgb(1.0, 0.5, 0.0, 0.5)
Color(1.0, 0.5, 0.0, 0.5) | entailment |
def from_hsl(h, s, l, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed HSL values.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 1, 0.5)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_hsl(30, 1, 0.5, 0.5)
Color(1.0, 0.5, 0.0, 0.5)
"""
return Color((h, s, l), 'hsl', alpha, wref) | Create a new instance based on the specifed HSL values.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 1, 0.5)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_hsl(30, 1, 0.5, 0.5)
Color(1.0, 0.5, 0.0, 0.5) | entailment |
def from_hsv(h, s, v, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed HSV values.
Parameters:
:h:
The Hus component value [0...1]
:s:
The Saturation component value [0...1]
:v:
The Value component [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_hsv(30, 1, 1)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_hsv(30, 1, 1, 0.5)
Color(1.0, 0.5, 0.0, 0.5)
"""
h2, s, l = rgb_to_hsl(*hsv_to_rgb(h, s, v))
return Color((h, s, l), 'hsl', alpha, wref) | Create a new instance based on the specifed HSV values.
Parameters:
:h:
The Hus component value [0...1]
:s:
The Saturation component value [0...1]
:v:
The Value component [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_hsv(30, 1, 1)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_hsv(30, 1, 1, 0.5)
Color(1.0, 0.5, 0.0, 0.5) | entailment |
def from_yiq(y, i, q, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed YIQ values.
Parameters:
:y:
The Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_yiq(0.5922, 0.45885,-0.05)
Color(0.999902, 0.499955, -6.7e-05, 1.0)
>>> Color.from_yiq(0.5922, 0.45885,-0.05, 0.5)
Color(0.999902, 0.499955, -6.7e-05, 0.5)
"""
return Color(yiq_to_rgb(y, i, q), 'rgb', alpha, wref) | Create a new instance based on the specifed YIQ values.
Parameters:
:y:
The Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_yiq(0.5922, 0.45885,-0.05)
Color(0.999902, 0.499955, -6.7e-05, 1.0)
>>> Color.from_yiq(0.5922, 0.45885,-0.05, 0.5)
Color(0.999902, 0.499955, -6.7e-05, 0.5) | entailment |
def from_yuv(y, u, v, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed YUV values.
Parameters:
:y:
The Y component value [0...1]
:u:
The U component value [-0.436...0.436]
:v:
The V component value [-0.615...0.615]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_yuv(0.5925, -0.2916, 0.3575)
Color(0.999989, 0.500015, -6.3e-05, 1.0)
>>> Color.from_yuv(0.5925, -0.2916, 0.3575, 0.5)
Color(0.999989, 0.500015, -6.3e-05, 0.5)
"""
return Color(yuv_to_rgb(y, u, v), 'rgb', alpha, wref) | Create a new instance based on the specifed YUV values.
Parameters:
:y:
The Y component value [0...1]
:u:
The U component value [-0.436...0.436]
:v:
The V component value [-0.615...0.615]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_yuv(0.5925, -0.2916, 0.3575)
Color(0.999989, 0.500015, -6.3e-05, 1.0)
>>> Color.from_yuv(0.5925, -0.2916, 0.3575, 0.5)
Color(0.999989, 0.500015, -6.3e-05, 0.5) | entailment |
def from_xyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed CIE-XYZ values.
Parameters:
:x:
The Red component value [0...1]
:y:
The Green component value [0...1]
:z:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_xyz(0.488941, 0.365682, 0.0448137)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_xyz(0.488941, 0.365682, 0.0448137, 0.5)
Color(1.0, 0.5, 0.0, 0.5)
"""
return Color(xyz_to_rgb(x, y, z), 'rgb', alpha, wref) | Create a new instance based on the specifed CIE-XYZ values.
Parameters:
:x:
The Red component value [0...1]
:y:
The Green component value [0...1]
:z:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_xyz(0.488941, 0.365682, 0.0448137)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_xyz(0.488941, 0.365682, 0.0448137, 0.5)
Color(1.0, 0.5, 0.0, 0.5) | entailment |
def from_lab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed CIE-LAB values.
Parameters:
:l:
The L component [0...100]
:a:
The a component [-1...1]
:b:
The a component [-1...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_lab(66.951823, 0.43084105, 0.73969231)
Color(1.0, 0.5, -0.0, 1.0)
>>> Color.from_lab(66.951823, 0.41165967, 0.67282012, wref=WHITE_REFERENCE['std_D50'])
Color(1.0, 0.5, -0.0, 1.0)
>>> Color.from_lab(66.951823, 0.43084105, 0.73969231, 0.5)
Color(1.0, 0.5, -0.0, 0.5)
>>> Color.from_lab(66.951823, 0.41165967, 0.67282012, 0.5, WHITE_REFERENCE['std_D50'])
Color(1.0, 0.5, -0.0, 0.5)
"""
return Color(xyz_to_rgb(*lab_to_xyz(l, a, b, wref)), 'rgb', alpha, wref) | Create a new instance based on the specifed CIE-LAB values.
Parameters:
:l:
The L component [0...100]
:a:
The a component [-1...1]
:b:
The a component [-1...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_lab(66.951823, 0.43084105, 0.73969231)
Color(1.0, 0.5, -0.0, 1.0)
>>> Color.from_lab(66.951823, 0.41165967, 0.67282012, wref=WHITE_REFERENCE['std_D50'])
Color(1.0, 0.5, -0.0, 1.0)
>>> Color.from_lab(66.951823, 0.43084105, 0.73969231, 0.5)
Color(1.0, 0.5, -0.0, 0.5)
>>> Color.from_lab(66.951823, 0.41165967, 0.67282012, 0.5, WHITE_REFERENCE['std_D50'])
Color(1.0, 0.5, -0.0, 0.5) | entailment |
def from_cmy(c, m, y, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed CMY values.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_cmy(0, 0.5, 1)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_cmy(0, 0.5, 1, 0.5)
Color(1.0, 0.5, 0.0, 0.5)
"""
return Color(cmy_to_rgb(c, m, y), 'rgb', alpha, wref) | Create a new instance based on the specifed CMY values.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_cmy(0, 0.5, 1)
Color(1.0, 0.5, 0.0, 1.0)
>>> Color.from_cmy(0, 0.5, 1, 0.5)
Color(1.0, 0.5, 0.0, 0.5) | entailment |
def from_cmyk(c, m, y, k, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed CMYK values.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:k:
The Black component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_cmyk(1, 0.32, 0, 0.5)
Color(0.0, 0.34, 0.5, 1.0)
>>> Color.from_cmyk(1, 0.32, 0, 0.5, 0.5)
Color(0.0, 0.34, 0.5, 0.5)
"""
return Color(cmy_to_rgb(*cmyk_to_cmy(c, m, y, k)), 'rgb', alpha, wref) | Create a new instance based on the specifed CMYK values.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:k:
The Black component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_cmyk(1, 0.32, 0, 0.5)
Color(0.0, 0.34, 0.5, 1.0)
>>> Color.from_cmyk(1, 0.32, 0, 0.5, 0.5)
Color(0.0, 0.34, 0.5, 0.5) | entailment |
def from_html(html, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed HTML color definition.
Parameters:
:html:
The HTML definition of the color (#RRGGBB or #RGB or a color name).
:alpha:
The color transparency [0...1], default is opaque.
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_html('#ff8000')
Color(1.0, 0.501961, 0.0, 1.0)
>>> Color.from_html('ff8000')
Color(1.0, 0.501961, 0.0, 1.0)
>>> Color.from_html('#f60')
Color(1.0, 0.4, 0.0, 1.0)
>>> Color.from_html('f60')
Color(1.0, 0.4, 0.0, 1.0)
>>> Color.from_html('lemonchiffon')
Color(1.0, 0.980392, 0.803922, 1.0)
>>> Color.from_html('#ff8000', 0.5)
Color(1.0, 0.501961, 0.0, 0.5)
"""
return Color(html_to_rgb(html), 'rgb', alpha, wref) | Create a new instance based on the specifed HTML color definition.
Parameters:
:html:
The HTML definition of the color (#RRGGBB or #RGB or a color name).
:alpha:
The color transparency [0...1], default is opaque.
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_html('#ff8000')
Color(1.0, 0.501961, 0.0, 1.0)
>>> Color.from_html('ff8000')
Color(1.0, 0.501961, 0.0, 1.0)
>>> Color.from_html('#f60')
Color(1.0, 0.4, 0.0, 1.0)
>>> Color.from_html('f60')
Color(1.0, 0.4, 0.0, 1.0)
>>> Color.from_html('lemonchiffon')
Color(1.0, 0.980392, 0.803922, 1.0)
>>> Color.from_html('#ff8000', 0.5)
Color(1.0, 0.501961, 0.0, 0.5) | entailment |
def from_pil(pil, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed PIL color.
Parameters:
:pil:
A PIL compatible color representation (0xBBGGRR)
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_pil(0x0080ff)
Color(1.0, 0.501961, 0.0, 1.0)
>>> Color.from_pil(0x0080ff, 0.5)
Color(1.0, 0.501961, 0.0, 0.5)
"""
return Color(pil_to_rgb(pil), 'rgb', alpha, wref) | Create a new instance based on the specifed PIL color.
Parameters:
:pil:
A PIL compatible color representation (0xBBGGRR)
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.from_pil(0x0080ff)
Color(1.0, 0.501961, 0.0, 1.0)
>>> Color.from_pil(0x0080ff, 0.5)
Color(1.0, 0.501961, 0.0, 0.5) | entailment |
def with_white_ref(self, wref, labAsRef=False):
"""Create a new instance based on this one with a new white reference.
Parameters:
:wref:
The whitepoint reference.
:labAsRef:
If True, the L*a*b* values of the current instance are used as reference
for the new color; otherwise, the RGB values are used as reference.
Returns:
A grapefruit.Color instance.
>>> c = Color.from_rgb(1.0, 0.5, 0.0, 1.0, WHITE_REFERENCE['std_D65'])
>>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50'])
>>> c2.rgb
(1.0, 0.5, 0.0)
>>> '(%g, %g, %g)' % c2.white_ref
'(0.967206, 1, 0.81428)'
>>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50'], labAsRef=True)
>>> '(%g, %g, %g)' % c2.rgb
'(1.01463, 0.490341, -0.148133)'
>>> '(%g, %g, %g)' % c2.white_ref
'(0.967206, 1, 0.81428)'
>>> '(%g, %g, %g)' % c.lab
'(66.9518, 0.430841, 0.739692)'
>>> '(%g, %g, %g)' % c2.lab
'(66.9518, 0.430841, 0.739693)'
"""
if labAsRef:
l, a, b = self.lab
return Color.from_lab(l, a, b, self.__a, wref)
else:
return Color(self.__rgb, 'rgb', self.__a, wref) | Create a new instance based on this one with a new white reference.
Parameters:
:wref:
The whitepoint reference.
:labAsRef:
If True, the L*a*b* values of the current instance are used as reference
for the new color; otherwise, the RGB values are used as reference.
Returns:
A grapefruit.Color instance.
>>> c = Color.from_rgb(1.0, 0.5, 0.0, 1.0, WHITE_REFERENCE['std_D65'])
>>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50'])
>>> c2.rgb
(1.0, 0.5, 0.0)
>>> '(%g, %g, %g)' % c2.white_ref
'(0.967206, 1, 0.81428)'
>>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50'], labAsRef=True)
>>> '(%g, %g, %g)' % c2.rgb
'(1.01463, 0.490341, -0.148133)'
>>> '(%g, %g, %g)' % c2.white_ref
'(0.967206, 1, 0.81428)'
>>> '(%g, %g, %g)' % c.lab
'(66.9518, 0.430841, 0.739692)'
>>> '(%g, %g, %g)' % c2.lab
'(66.9518, 0.430841, 0.739693)' | entailment |
def desaturate(self, level):
"""Create a new instance based on this one but less saturated.
Parameters:
:level:
The amount by which the color should be desaturated to produce
the new one [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25)
Color(0.625, 0.5, 0.375, 1.0)
>>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25).hsl
(30.0, 0.25, 0.5)
"""
h, s, l = self.__hsl
return Color((h, max(s - level, 0), l), 'hsl', self.__a, self.__wref) | Create a new instance based on this one but less saturated.
Parameters:
:level:
The amount by which the color should be desaturated to produce
the new one [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25)
Color(0.625, 0.5, 0.375, 1.0)
>>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25).hsl
(30.0, 0.25, 0.5) | entailment |
def websafe_dither(self):
"""Return the two websafe colors nearest to this one.
Returns:
A tuple of two grapefruit.Color instances which are the two
web safe colors closest this one.
>>> c = Color.from_rgb(1.0, 0.45, 0.0)
>>> c1, c2 = c.websafe_dither()
>>> c1
Color(1.0, 0.4, 0.0, 1.0)
>>> c2
Color(1.0, 0.6, 0.0, 1.0)
"""
return (
Color(rgb_to_websafe(*self.__rgb), 'rgb', self.__a, self.__wref),
Color(rgb_to_websafe(alt=True, *self.__rgb), 'rgb', self.__a, self.__wref)) | Return the two websafe colors nearest to this one.
Returns:
A tuple of two grapefruit.Color instances which are the two
web safe colors closest this one.
>>> c = Color.from_rgb(1.0, 0.45, 0.0)
>>> c1, c2 = c.websafe_dither()
>>> c1
Color(1.0, 0.4, 0.0, 1.0)
>>> c2
Color(1.0, 0.6, 0.0, 1.0) | entailment |
def complementary_color(self, mode='ryb'):
"""Create a new instance which is the complementary color of this one.
Parameters:
:mode:
Select which color wheel to use for the generation (ryb/rgb).
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb')
Color(0.0, 0.5, 1.0, 1.0)
>>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb').hsl
(210.0, 1.0, 0.5)
"""
h, s, l = self.__hsl
if mode == 'ryb': h = rgb_to_ryb(h)
h = (h+180)%360
if mode == 'ryb': h = ryb_to_rgb(h)
return Color((h, s, l), 'hsl', self.__a, self.__wref) | Create a new instance which is the complementary color of this one.
Parameters:
:mode:
Select which color wheel to use for the generation (ryb/rgb).
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb')
Color(0.0, 0.5, 1.0, 1.0)
>>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb').hsl
(210.0, 1.0, 0.5) | entailment |
def make_analogous_scheme(self, angle=30, mode='ryb'):
"""Return two colors analogous to this one.
Args:
:angle:
The angle between the hues of the created colors and this one.
:mode:
Select which color wheel to use for the generation (ryb/rgb).
Returns:
A tuple of grapefruit.Colors analogous to this one.
>>> c1 = Color.from_hsl(30, 1, 0.5)
>>> c2, c3 = c1.make_analogous_scheme(angle=60, mode='rgb')
>>> c2.hsl
(330.0, 1.0, 0.5)
>>> c3.hsl
(90.0, 1.0, 0.5)
>>> c2, c3 = c1.make_analogous_scheme(angle=10, mode='rgb')
>>> c2.hsl
(20.0, 1.0, 0.5)
>>> c3.hsl
(40.0, 1.0, 0.5)
"""
h, s, l = self.__hsl
if mode == 'ryb': h = rgb_to_ryb(h)
h += 360
h1 = (h - angle) % 360
h2 = (h + angle) % 360
if mode == 'ryb':
h1 = ryb_to_rgb(h1)
h2 = ryb_to_rgb(h2)
return (Color((h1, s, l), 'hsl', self.__a, self.__wref),
Color((h2, s, l), 'hsl', self.__a, self.__wref)) | Return two colors analogous to this one.
Args:
:angle:
The angle between the hues of the created colors and this one.
:mode:
Select which color wheel to use for the generation (ryb/rgb).
Returns:
A tuple of grapefruit.Colors analogous to this one.
>>> c1 = Color.from_hsl(30, 1, 0.5)
>>> c2, c3 = c1.make_analogous_scheme(angle=60, mode='rgb')
>>> c2.hsl
(330.0, 1.0, 0.5)
>>> c3.hsl
(90.0, 1.0, 0.5)
>>> c2, c3 = c1.make_analogous_scheme(angle=10, mode='rgb')
>>> c2.hsl
(20.0, 1.0, 0.5)
>>> c3.hsl
(40.0, 1.0, 0.5) | entailment |
def alpha_blend(self, other):
"""Alpha-blend this color on the other one.
Args:
:other:
The grapefruit.Color to alpha-blend with this one.
Returns:
A grapefruit.Color instance which is the result of alpha-blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)
>>> c2 = Color.from_rgb(1, 1, 1, 0.8)
>>> c3 = c1.alpha_blend(c2)
>>> c3
Color(1.0, 0.875, 0.75, 0.84)
"""
# get final alpha channel
fa = self.__a + other.__a - (self.__a * other.__a)
# get percentage of source alpha compared to final alpha
if fa==0: sa = 0
else: sa = min(1.0, self.__a/other.__a)
# destination percentage is just the additive inverse
da = 1.0 - sa
sr, sg, sb = [v * sa for v in self.__rgb]
dr, dg, db = [v * da for v in other.__rgb]
return Color((sr+dr, sg+dg, sb+db), 'rgb', fa, self.__wref) | Alpha-blend this color on the other one.
Args:
:other:
The grapefruit.Color to alpha-blend with this one.
Returns:
A grapefruit.Color instance which is the result of alpha-blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)
>>> c2 = Color.from_rgb(1, 1, 1, 0.8)
>>> c3 = c1.alpha_blend(c2)
>>> c3
Color(1.0, 0.875, 0.75, 0.84) | entailment |
def blend(self, other, percent=0.5):
"""blend this color with the other one.
Args:
:other:
the grapefruit.Color to blend with this one.
Returns:
A grapefruit.Color instance which is the result of blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)
>>> c2 = Color.from_rgb(1, 1, 1, 0.6)
>>> c3 = c1.blend(c2)
>>> c3
Color(1.0, 0.75, 0.5, 0.4)
"""
dest = 1.0 - percent
rgb = tuple(((u * percent) + (v * dest) for u, v in zip(self.__rgb, other.__rgb)))
a = (self.__a * percent) + (other.__a * dest)
return Color(rgb, 'rgb', a, self.__wref) | blend this color with the other one.
Args:
:other:
the grapefruit.Color to blend with this one.
Returns:
A grapefruit.Color instance which is the result of blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)
>>> c2 = Color.from_rgb(1, 1, 1, 0.6)
>>> c3 = c1.blend(c2)
>>> c3
Color(1.0, 0.75, 0.5, 0.4) | entailment |
def get_parser():
"""Parse command-line arguments."""
parser = ArgumentParser(description='a command-line web scraping tool')
parser.add_argument('query', metavar='QUERY', type=str, nargs='*',
help='URLs/files to scrape')
parser.add_argument('-a', '--attributes', type=str, nargs='*',
help='extract text using tag attributes')
parser.add_argument('-all', '--crawl-all', help='crawl all pages',
action='store_true')
parser.add_argument('-c', '--crawl', type=str, nargs='*',
help='regexp rules for following new pages')
parser.add_argument('-C', '--clear-cache', help='clear requests cache',
action='store_true')
parser.add_argument('--csv', help='write files as csv',
action='store_true')
parser.add_argument('-cs', '--cache-size', type=int, nargs='?',
help='size of page cache (default: 1000)',
default=1000)
parser.add_argument('-f', '--filter', type=str, nargs='*',
help='regexp rules for filtering text')
parser.add_argument('--html', help='write files as HTML',
action='store_true')
parser.add_argument('-i', '--images', action='store_true',
help='save page images')
parser.add_argument('-m', '--multiple', help='save to multiple files',
action='store_true')
parser.add_argument('-max', '--max-crawls', type=int,
help='max number of pages to crawl')
parser.add_argument('-n', '--nonstrict', action='store_true',
help='allow crawler to visit any domain')
parser.add_argument('-ni', '--no-images', action='store_true',
help='do not save page images')
parser.add_argument('-no', '--no-overwrite', action='store_true',
help='do not overwrite files if they exist')
parser.add_argument('-o', '--out', type=str, nargs='*',
help='specify outfile names')
parser.add_argument('-ow', '--overwrite', action='store_true',
help='overwrite a file if it exists')
parser.add_argument('-p', '--pdf', help='write files as pdf',
action='store_true')
parser.add_argument('-pt', '--print', help='print text output',
action='store_true')
parser.add_argument('-q', '--quiet', help='suppress program output',
action='store_true')
parser.add_argument('-s', '--single', help='save to a single file',
action='store_true')
parser.add_argument('-t', '--text', help='write files as text',
action='store_true')
parser.add_argument('-v', '--version', help='display current version',
action='store_true')
parser.add_argument('-x', '--xpath', type=str, nargs='?',
help='filter HTML using XPath')
return parser | Parse command-line arguments. | entailment |
def write_files(args, infilenames, outfilename):
"""Write scraped or local file(s) in desired format.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output file (str)
Remove PART(#).html files after conversion unless otherwise specified.
"""
write_actions = {'print': utils.print_text,
'pdf': utils.write_pdf_files,
'csv': utils.write_csv_files,
'text': utils.write_text_files}
try:
for action in iterkeys(write_actions):
if args[action]:
write_actions[action](args, infilenames, outfilename)
finally:
if args['urls'] and not args['html']:
utils.remove_part_files() | Write scraped or local file(s) in desired format.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output file (str)
Remove PART(#).html files after conversion unless otherwise specified. | entailment |
def write_single_file(args, base_dir, crawler):
"""Write to a single output file and/or subdirectory."""
if args['urls'] and args['html']:
# Create a directory to save PART.html files in
domain = utils.get_domain(args['urls'][0])
if not args['quiet']:
print('Storing html files in {0}/'.format(domain))
utils.mkdir_and_cd(domain)
infilenames = []
for query in args['query']:
if query in args['files']:
infilenames.append(query)
elif query.strip('/') in args['urls']:
if args['crawl'] or args['crawl_all']:
# Crawl and save HTML files/image files to disk
infilenames += crawler.crawl_links(query)
else:
raw_resp = utils.get_raw_resp(query)
if raw_resp is None:
return False
prev_part_num = utils.get_num_part_files()
utils.write_part_file(args, query, raw_resp)
curr_part_num = prev_part_num + 1
infilenames += utils.get_part_filenames(curr_part_num, prev_part_num)
# Convert output or leave as PART.html files
if args['html']:
# HTML files have been written already, so return to base directory
os.chdir(base_dir)
else:
# Write files to text or pdf
if infilenames:
if args['out']:
outfilename = args['out'][0]
else:
outfilename = utils.get_single_outfilename(args)
if outfilename:
write_files(args, infilenames, outfilename)
else:
utils.remove_part_files()
return True | Write to a single output file and/or subdirectory. | entailment |
def write_multiple_files(args, base_dir, crawler):
"""Write to multiple output files and/or subdirectories."""
for i, query in enumerate(args['query']):
if query in args['files']:
# Write files
if args['out'] and i < len(args['out']):
outfilename = args['out'][i]
else:
outfilename = '.'.join(query.split('.')[:-1])
write_files(args, [query], outfilename)
elif query in args['urls']:
# Scrape/crawl urls
domain = utils.get_domain(query)
if args['html']:
# Create a directory to save PART.html files in
if not args['quiet']:
print('Storing html files in {0}/'.format(domain))
utils.mkdir_and_cd(domain)
if args['crawl'] or args['crawl_all']:
# Crawl and save HTML files/image files to disk
infilenames = crawler.crawl_links(query)
else:
raw_resp = utils.get_raw_resp(query)
if raw_resp is None:
return False
# Saves page as PART.html file
prev_part_num = utils.get_num_part_files()
utils.write_part_file(args, query, raw_resp)
curr_part_num = prev_part_num + 1
infilenames = utils.get_part_filenames(curr_part_num, prev_part_num)
# Convert output or leave as PART.html files
if args['html']:
# HTML files have been written already, so return to base dir
os.chdir(base_dir)
else:
# Write files to text or pdf
if infilenames:
if args['out'] and i < len(args['out']):
outfilename = args['out'][i]
else:
outfilename = utils.get_outfilename(query, domain)
write_files(args, infilenames, outfilename)
else:
sys.stderr.write('Failed to retrieve content from {0}.\n'
.format(query))
return True | Write to multiple output files and/or subdirectories. | entailment |
def split_input(args):
"""Split query input into local files and URLs."""
args['files'] = []
args['urls'] = []
for arg in args['query']:
if os.path.isfile(arg):
args['files'].append(arg)
else:
args['urls'].append(arg.strip('/')) | Split query input into local files and URLs. | entailment |
def detect_output_type(args):
"""Detect whether to save to a single or multiple files."""
if not args['single'] and not args['multiple']:
# Save to multiple files if multiple files/URLs entered
if len(args['query']) > 1 or len(args['out']) > 1:
args['multiple'] = True
else:
args['single'] = True | Detect whether to save to a single or multiple files. | entailment |
def scrape(args):
"""Scrape webpage content."""
try:
base_dir = os.getcwd()
if args['out'] is None:
args['out'] = []
# Detect whether to save to a single or multiple files
detect_output_type(args)
# Split query input into local files and URLs
split_input(args)
if args['urls']:
# Add URL extensions and schemes and update query and URLs
urls_with_exts = [utils.add_url_suffix(x) for x in args['urls']]
args['query'] = [utils.add_protocol(x) if x in args['urls'] else x
for x in urls_with_exts]
args['urls'] = [x for x in args['query'] if x not in args['files']]
# Print error if attempting to convert local files to HTML
if args['files'] and args['html']:
sys.stderr.write('Cannot convert local files to HTML.\n')
args['files'] = []
# Instantiate web crawler if necessary
crawler = None
if args['crawl'] or args['crawl_all']:
crawler = Crawler(args)
if args['single']:
return write_single_file(args, base_dir, crawler)
elif args['multiple']:
return write_multiple_files(args, base_dir, crawler)
except (KeyboardInterrupt, Exception):
if args['html']:
try:
os.chdir(base_dir)
except OSError:
pass
else:
utils.remove_part_files()
raise | Scrape webpage content. | entailment |
def prompt_filetype(args):
"""Prompt user for filetype if none specified."""
valid_types = ('print', 'text', 'csv', 'pdf', 'html')
if not any(args[x] for x in valid_types):
try:
filetype = input('Print or save output as ({0}): '
.format(', '.join(valid_types))).lower()
while filetype not in valid_types:
filetype = input('Invalid entry. Choose from ({0}): '
.format(', '.join(valid_types))).lower()
except (KeyboardInterrupt, EOFError):
return
args[filetype] = True | Prompt user for filetype if none specified. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.